@agimon-ai/po-cloudflare 0.0.2-alpha.7 → 0.0.2-alpha.70

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 (355) hide show
  1. package/README.md +64 -241
  2. package/container/Dockerfile +27 -0
  3. package/dist/{BrowserWebSocketTransport-C2SC2VeJ.js → BrowserWebSocketTransport-B4heNdrp.js} +1 -1
  4. package/dist/{NodeWebSocketTransport-CKilJesa.js → NodeWebSocketTransport-BCiOXUEz.js} +2 -2
  5. package/dist/{abort-signals-Bkmp_euQ.js → abort-signals-C8CttjsR.js} +1 -1
  6. package/dist/agent-CEqvgRl6.js +3878 -0
  7. package/dist/{anthropic-messages-CkYm8M3V.js → anthropic-messages-DCLLLNuM.js} +292 -64
  8. package/dist/apiContracts-DaOpUHnu.js +1719 -0
  9. package/dist/{approval-CQ3ZuoTy.js → approval-DXPV7Vm5.js} +15 -2
  10. package/dist/{approvalPrompt-CylV3C84.js → approvalPrompt-CBaxjb_g.js} +1 -2
  11. package/dist/approvalSession-C9bg7tPo.js +132 -0
  12. package/dist/artifactFiles-5KwXIxYf.js +1 -0
  13. package/dist/artifactsApi-bg2wMYWg.js +200 -0
  14. package/dist/assets/assets/{CodeEditorView-D4q94XH-.js → CodeEditorView-i4Ppo-Ez.js} +2 -2
  15. package/dist/assets/assets/{abnfDiagram-WEYOIA3C-C85p4OYZ.js → abnfDiagram-WEYOIA3C-DyhZRVQg.js} +2 -2
  16. package/dist/assets/assets/{architecture-WOLXFQ4H-Bt_NOdwE.js → architecture-WOLXFQ4H-BBs2Sd0N.js} +1 -1
  17. package/dist/assets/assets/{architectureDiagram-ZHVYKT53-DzH1GKMm.js → architectureDiagram-ZHVYKT53-DsCX6klV.js} +2 -2
  18. package/dist/assets/assets/{blockDiagram-RJAE7QA3-BmWU34j3.js → blockDiagram-RJAE7QA3-BI3vEkHp.js} +2 -2
  19. package/dist/assets/assets/{c4Diagram-XDPPPE54-BpGOdOuo.js → c4Diagram-XDPPPE54-BPQ3l3Wo.js} +2 -2
  20. package/dist/assets/assets/channel-1ehKCuz-.js +2 -0
  21. package/dist/assets/assets/{chunk-2E7WHVMD-AycP1cXU.js → chunk-2E7WHVMD-w1BaZW2E.js} +2 -2
  22. package/dist/assets/assets/{chunk-4EMNKR2T-DX-DrZzc.js → chunk-4EMNKR2T-CUW8s7jF.js} +2 -2
  23. package/dist/assets/assets/{chunk-55XCU76K-BdwnLWzI.js → chunk-55XCU76K-By6CWPPC.js} +2 -2
  24. package/dist/assets/assets/{chunk-7S6XSTFO-D-RBAwAn.js → chunk-7S6XSTFO-BBrnzWpC.js} +2 -2
  25. package/dist/assets/assets/{chunk-AQDTSKZB-CCxNNhKs.js → chunk-AQDTSKZB-DPdxwHEp.js} +2 -2
  26. package/dist/assets/assets/{chunk-DSNLSHJZ-D2hGwWm1.js → chunk-DSNLSHJZ-DYgD5g3I.js} +2 -2
  27. package/dist/assets/assets/{chunk-HAGFOTED-BPi-cqGh.js → chunk-HAGFOTED-DQK-CQol.js} +2 -2
  28. package/dist/assets/assets/{chunk-HNE4Q36P-D-r1ChHT.js → chunk-HNE4Q36P-B7wgFR7D.js} +2 -2
  29. package/dist/assets/assets/{chunk-NQOKRVIF-RgmZCAdn.js → chunk-NQOKRVIF-CCLgsSmY.js} +2 -2
  30. package/dist/assets/assets/{chunk-UHW7PFBP-B-Hul-rZ.js → chunk-UHW7PFBP-ynXsycud.js} +2 -2
  31. package/dist/assets/assets/{chunk-VQ5W62QI-D1zlXCt8.js → chunk-VQ5W62QI-g-S-R-1r.js} +2 -2
  32. package/dist/assets/assets/{chunk-WQQL4CDK-CtjIbVJn.js → chunk-WQQL4CDK-BacAjFnN.js} +2 -2
  33. package/dist/assets/assets/chunk-XXDRQBXY-CpS2hTCb.js +2 -0
  34. package/dist/assets/assets/{chunk-YZO67HFG-BQOgXG99.js → chunk-YZO67HFG-BpftQis1.js} +2 -2
  35. package/dist/assets/assets/{chunk-ZAUX2LTX-CsDDxmqv.js → chunk-ZAUX2LTX-DJdy-AMG.js} +2 -2
  36. package/dist/assets/assets/{chunk-ZCHMQSOR-deyEYMjx.js → chunk-ZCHMQSOR-87ga4cjt.js} +2 -2
  37. package/dist/assets/assets/{classDiagram-v2-4MYWR3UA-DVJHeFlq.js → classDiagram-v2-4MYWR3UA-CpsLBpS_.js} +2 -2
  38. package/dist/assets/assets/{cose-bilkent-JH36ORCC-ipcN28Fw.js → cose-bilkent-JH36ORCC-DJaIzCvD.js} +2 -2
  39. package/dist/assets/assets/{cynefin-EF2NZ3EQ-s9ZkPF55.js → cynefin-EF2NZ3EQ-CI6zLM35.js} +1 -1
  40. package/dist/assets/assets/{cynefinDiagram-WF24UDRP-Ksr2qjsS.js → cynefinDiagram-WF24UDRP-DfzAHZ0M.js} +2 -2
  41. package/dist/assets/assets/{dagre-NK4GIZVX-2_Wl-XEW.js → dagre-NK4GIZVX-B8tLPoML.js} +2 -2
  42. package/dist/assets/assets/{diagram-CBK3MWTC-C7PeyT7l.js → diagram-CBK3MWTC-Dr80S-jH.js} +2 -2
  43. package/dist/assets/assets/{diagram-I5XIIV2D-DPYzeKdj.js → diagram-I5XIIV2D-B8UFhfTz.js} +2 -2
  44. package/dist/assets/assets/{diagram-ODIL2UCW-DHw1cAmn.js → diagram-ODIL2UCW-CcuwPetk.js} +2 -2
  45. package/dist/assets/assets/{diagram-PFBEJUXE-C2wA8i-1.js → diagram-PFBEJUXE-RcrmwqS-.js} +2 -2
  46. package/dist/assets/assets/{diagram-RJA3I4VV-tM3moCIs.js → diagram-RJA3I4VV-L0etfW8v.js} +2 -2
  47. package/dist/assets/assets/{diagram-TYUNFSNR-CInyJxF7.js → diagram-TYUNFSNR-qAWwJAuP.js} +2 -2
  48. package/dist/assets/assets/{dist-DSLprmec.js → dist-8Be2UxDt.js} +2 -2
  49. package/dist/assets/assets/{dist-DUS0U_ge.js → dist-BEo-JIto.js} +2 -2
  50. package/dist/assets/assets/{dist-BASEd5LC.js → dist-BH9U8iUV.js} +2 -2
  51. package/dist/assets/assets/{dist-07dRlnp1.js → dist-CgWFM0mc.js} +2 -2
  52. package/dist/assets/assets/{dist-ChXoRSS6.js → dist-CpVa1sRY.js} +2 -2
  53. package/dist/assets/assets/{dist-hpZIQBl4.js → dist-CzUZg8tE.js} +2 -2
  54. package/dist/assets/assets/{dist-BDqjNLTC.js → dist-DGxK4Eqg.js} +2 -2
  55. package/dist/assets/assets/{dist-CeOy6PjJ.js → dist-GAOFeWFO.js} +2 -2
  56. package/dist/assets/assets/{dist-BuYBvf4F.js → dist-engyz38V.js} +2 -2
  57. package/dist/assets/assets/{ebnfDiagram-V4P3TTPT-4nZgqaSt.js → ebnfDiagram-V4P3TTPT-BprXAPMU.js} +2 -2
  58. package/dist/assets/assets/{elk-QONTBCTQ-nFh54c1Q.js → elk-QONTBCTQ-D523_9vu.js} +2 -2
  59. package/dist/assets/assets/{erDiagram-KYQIGQAA-CIQ0_IgZ.js → erDiagram-KYQIGQAA-QpR6wQYW.js} +2 -2
  60. package/dist/assets/assets/{eventmodeling-K75KTNOO-Cw4BlbYP.js → eventmodeling-K75KTNOO-BaGn1fXz.js} +1 -1
  61. package/dist/assets/assets/flowDiagram-IUGLLWBU-BLGi2Tcw.js +1 -0
  62. package/dist/assets/assets/{ganttDiagram-R7GPNTJY-C97qoUpX.js → ganttDiagram-R7GPNTJY-CdOyCuYE.js} +2 -2
  63. package/dist/assets/assets/{gitGraph-VSP46ZUC-B8HWVkEX.js → gitGraph-VSP46ZUC-EsAHczV6.js} +1 -1
  64. package/dist/assets/assets/{gitGraphDiagram-PDYL7XHY-B4Js56_8.js → gitGraphDiagram-PDYL7XHY-BIujo2Py.js} +2 -2
  65. package/dist/assets/assets/index-BpJxd2yX.js +256 -0
  66. package/dist/assets/assets/index-CNDyKUDF.css +1 -0
  67. package/dist/assets/assets/{info-OHQRW6UA-A4qythhA.js → info-OHQRW6UA-LjorJFXn.js} +1 -1
  68. package/dist/assets/assets/{infoDiagram-MVDRKAX5-BSNwG9yI.js → infoDiagram-MVDRKAX5-DH9gnzLg.js} +2 -2
  69. package/dist/assets/assets/{ishikawaDiagram-HPEHV2GE-D4gU-3RA.js → ishikawaDiagram-HPEHV2GE-hX3Vi2D5.js} +2 -2
  70. package/dist/assets/assets/{journeyDiagram-BOSHW7O7-CxxDrw7o.js → journeyDiagram-BOSHW7O7-D_DP_Ais.js} +2 -2
  71. package/dist/assets/assets/{kanban-definition-FNSA4HC5-DUxQv3v0.js → kanban-definition-FNSA4HC5-xjXWPA_c.js} +2 -2
  72. package/dist/assets/assets/{line-BKODXUmk.js → line-DmYSe7_a.js} +2 -2
  73. package/dist/assets/assets/{linear-Cm5uyUun.js → linear-bTjWiO8g.js} +2 -2
  74. package/dist/assets/assets/{mermaid-parser.core-CYst2kCg.js → mermaid-parser.core-Canr1bD7.js} +4 -4
  75. package/dist/assets/assets/{mermaid.core-B4Qq8SMa.js → mermaid.core-CzdNzF6I.js} +5 -5
  76. package/dist/assets/assets/{mindmap-definition-6OY57UG3-CZFvUTIM.js → mindmap-definition-6OY57UG3-DADwSr-4.js} +2 -2
  77. package/dist/assets/assets/{packet-JDAUHWVQ-DZMlaiuy.js → packet-JDAUHWVQ-Bbicx2nv.js} +1 -1
  78. package/dist/assets/assets/{pegDiagram-ECIUJNBX-BjM668dT.js → pegDiagram-ECIUJNBX-CsayWcP2.js} +2 -2
  79. package/dist/assets/assets/{pie-XZMESJXO-CmpJ6vb8.js → pie-XZMESJXO-Blegt3hx.js} +1 -1
  80. package/dist/assets/assets/{pieDiagram-GNMPY74T-BCA9DCDe.js → pieDiagram-GNMPY74T-CVDQwYsb.js} +2 -2
  81. package/dist/assets/assets/{quadrantDiagram-D57K4MC3-CUnpC-Rl.js → quadrantDiagram-D57K4MC3-B_3o8LPt.js} +2 -2
  82. package/dist/assets/assets/{radar-ABXABTNO-C9x42-KP.js → radar-ABXABTNO-RkOj7KMI.js} +1 -1
  83. package/dist/assets/assets/{railroad-I3PHUGI6-CLvHKrsC.js → railroad-I3PHUGI6-BJRK-sej.js} +1 -1
  84. package/dist/assets/assets/{railroad-abnf-LNEFI6M7-B0LGF3gx.js → railroad-abnf-LNEFI6M7-zDVbNx_e.js} +1 -1
  85. package/dist/assets/assets/{railroad-ebnf-DWYD2UWJ-SKnYapAj.js → railroad-ebnf-DWYD2UWJ-DR--F1w_.js} +1 -1
  86. package/dist/assets/assets/{railroad-peg-JR7BVNR7-wsUpPloN.js → railroad-peg-JR7BVNR7-DUU7CG0O.js} +1 -1
  87. package/dist/assets/assets/{railroadDiagram-Y72NRBL7-BYJtosKO.js → railroadDiagram-Y72NRBL7-BTI5d3Dh.js} +2 -2
  88. package/dist/assets/assets/{requirementDiagram-EQYSW5RA-YYdoWMnl.js → requirementDiagram-EQYSW5RA-ryj3WI8d.js} +2 -2
  89. package/dist/assets/assets/{sankeyDiagram-SY24JHO5-DtZyCTdM.js → sankeyDiagram-SY24JHO5-CpxzEis6.js} +2 -2
  90. package/dist/assets/assets/{sequenceDiagram-BLEHNHQU-BPE8f413.js → sequenceDiagram-BLEHNHQU-Ck0eH0AG.js} +2 -2
  91. package/dist/assets/assets/{src-BNTOLq2G.js → src-CVheRzH-.js} +2 -2
  92. package/dist/assets/assets/{stateDiagram-v2-A6IESKWZ-9f8Ow4Fl.js → stateDiagram-v2-A6IESKWZ-BUP0MEeM.js} +2 -2
  93. package/dist/assets/assets/{swimlanes-B3ENRKFQ-DdAEbxGp.js → swimlanes-B3ENRKFQ-Bv0gbKOG.js} +2 -2
  94. package/dist/assets/assets/swimlanesDiagram-AYQRV4AK-BMOkq2v_.js +9 -0
  95. package/dist/assets/assets/{timeline-definition-JXYKGLGB-DJNGd2mU.js → timeline-definition-JXYKGLGB-Bvln6k4A.js} +2 -2
  96. package/dist/assets/assets/{treeView-D4JQ5SDB-BHONoCCw.js → treeView-D4JQ5SDB-DTTZJ9g6.js} +1 -1
  97. package/dist/assets/assets/{treemap-SAJKECNS-pOaYkxq7.js → treemap-SAJKECNS-DvSBR2VN.js} +1 -1
  98. package/dist/assets/assets/{usecaseDiagram-WPOLBNNX-C3eDYL9v.js → usecaseDiagram-WPOLBNNX-DDmtJ3Uv.js} +2 -2
  99. package/dist/assets/assets/{vennDiagram-Q3Y3IDCW-CJi1xfsR.js → vennDiagram-Q3Y3IDCW-CgTKk1M4.js} +2 -2
  100. package/dist/assets/assets/{wardley-7MLQ67FV-CEy4w7Ir.js → wardley-7MLQ67FV-Dc3Gbgal.js} +1 -1
  101. package/dist/assets/assets/{wardleyDiagram-IVAIDKWA-DfdLMMpN.js → wardleyDiagram-IVAIDKWA-Bt6AAQZb.js} +2 -2
  102. package/dist/assets/assets/{webpack-v8XGbQTa.js → webpack-Vcj694ip.js} +2 -2
  103. package/dist/assets/assets/{xychartDiagram-4URNHDU4-Aw-Ix4uC.js → xychartDiagram-4URNHDU4-4WaL7qQg.js} +2 -2
  104. package/dist/assets/bundle-asset-policy.json +1 -1
  105. package/dist/assets/index.html +8 -2
  106. package/dist/assets/mascot/cta-provider.png +0 -0
  107. package/dist/assets/mascot/cta-sign-in.png +0 -0
  108. package/dist/assets/plugins/assets/base-GzIOAd-t.css +2 -0
  109. package/dist/assets/plugins/assets/browserCaptureWorklet-Droj0fW0-Droj0fW0.js +13 -0
  110. package/dist/assets/plugins/assets/day-bottom-left-5um-x02r-5um-x02r.webp +0 -0
  111. package/dist/assets/plugins/assets/day-grain-CvEuNhlI-CvEuNhlI.webp +0 -0
  112. package/dist/assets/plugins/assets/day-right-C9W-XtjV-C9W-XtjV.webp +0 -0
  113. package/dist/assets/plugins/assets/day-top-left-B544Eq9J-B544Eq9J.webp +0 -0
  114. package/dist/assets/plugins/assets/night-bottom-left-N03ST5Uz-N03ST5Uz.webp +0 -0
  115. package/dist/assets/plugins/assets/night-grain-BY9q-tNN-BY9q-tNN.webp +0 -0
  116. package/dist/assets/plugins/assets/night-right-C6Denrqj-C6Denrqj.webp +0 -0
  117. package/dist/assets/plugins/assets/night-top-left-KOou6UxY-KOou6UxY.webp +0 -0
  118. package/dist/assets/plugins/assets/sileroVadWorker-D894njUe-DjN_BMWf.mjs +110 -0
  119. package/dist/assets/plugins/assets/silero_vad_v6.2.1-SjbCxFXk-SjbCxFXk.onnx +0 -0
  120. package/dist/assets/plugins/chunks/po-web-runtime-Yjk5kSCS.js +1 -0
  121. package/dist/assets/plugins/chunks/schemas-DVQ8BvvP.js +55 -0
  122. package/dist/assets/plugins/compositions.json +1 -1
  123. package/dist/assets/plugins/slots/approval.3e4ea6e4-CFdw9ob_.js +2 -0
  124. package/dist/assets/plugins/slots/artifacts.84980c32-ocCs81ac.js +1 -0
  125. package/dist/assets/plugins/slots/author.8eca1a3d-Dht6Emzx.js +93 -0
  126. package/dist/assets/plugins/slots/autocompact.ec8f713f-Dn7Bt8Bf.js +1 -0
  127. package/dist/assets/plugins/slots/backdrop-bamboo.1a4d85e9-B7xkLXXQ.js +1 -0
  128. package/dist/assets/plugins/slots/browse.61a8907a-B8xsrCRp.js +1 -0
  129. package/dist/assets/plugins/slots/builtin-tools.16ef5e25-HORNeYBw.js +7 -0
  130. package/dist/assets/plugins/slots/calendar.d337fc49-ZApjFb8a.js +2 -0
  131. package/dist/assets/plugins/slots/codemode.5f359b9c-B60BP7uB.js +11 -0
  132. package/dist/assets/plugins/slots/domain.832848c8-Cwu_vvzo.js +1 -0
  133. package/dist/assets/plugins/slots/edit.7c802139-DyVlM6he.js +7 -0
  134. package/dist/assets/plugins/slots/files.364f16c9-BZpLJy01.js +2 -0
  135. package/dist/assets/plugins/slots/goal.a97b169d-Bi5YKBZC.js +1 -0
  136. package/dist/assets/plugins/slots/grep.d8bf9f57-hqVwtdze.js +1 -0
  137. package/dist/assets/plugins/slots/help.5c78c071-Drhx02TI.js +3 -0
  138. package/dist/assets/plugins/slots/log.07fd59a4-CoJHv8w_.js +4 -0
  139. package/dist/assets/plugins/slots/mcp.ea8b6aa2-C8Fnd-JT.js +55 -0
  140. package/dist/assets/plugins/slots/plan.7b30f8d8-CZYr2pT-.js +3 -0
  141. package/dist/assets/plugins/slots/profile.63bc3ae6-DKIhEgIG.js +1 -0
  142. package/dist/assets/plugins/slots/prompts.9d9b47cc-B1gwBWg8.js +38 -0
  143. package/dist/assets/plugins/slots/read.926c024f-ClmLDj9R.js +1 -0
  144. package/dist/assets/plugins/slots/runner.5393fa6c-ttJbdJZ2.js +9 -0
  145. package/dist/assets/plugins/slots/scaffold.686222eb-3wV6oBNu.js +1 -0
  146. package/dist/assets/plugins/slots/session-mcp.8eb68fc9-B-Xa5onX.js +2 -0
  147. package/dist/assets/plugins/slots/sessions.8e378a3b-BfIRgip7.js +1 -0
  148. package/dist/assets/plugins/slots/skill.56c1cc07-BqmMUx5M.js +4 -0
  149. package/dist/assets/plugins/slots/space.056e8bbc-DIA3v5sn.js +1 -0
  150. package/dist/assets/plugins/slots/subagents.31fc045b-BZXTwTSN.js +7 -0
  151. package/dist/assets/plugins/slots/template-advanced.9e8350fe-jSxtKth9.js +1 -0
  152. package/dist/assets/plugins/slots/template-desktop.69a46f62-IV-rW8Gz.js +7 -0
  153. package/dist/assets/plugins/slots/template-elegant.381f6acb-Dr2lz9D3.js +1 -0
  154. package/dist/assets/plugins/slots/vault.587549ba-CLv0qsTB.js +1 -0
  155. package/dist/assets/plugins/slots/voice.9c687181-d6cHs1CH.js +1 -0
  156. package/dist/assets/plugins/slots/web-search.f6292793-uk9YiOK-.js +1 -0
  157. package/dist/assets/plugins/slots/workflows.8a13baad-B4cnDzRF.js +16 -0
  158. package/dist/assets/pwa/pwa.js +12 -12
  159. package/dist/assets/pwa/sw.js +58 -4
  160. package/dist/{atomicJson-wczZBXQP.js → atomicJson-XYtxz032.js} +2 -3
  161. package/dist/{azure-openai-config-DHMgdIa-.js → azure-openai-config-S-quxzTC.js} +2 -2
  162. package/dist/{azure-openai-responses-CTgRdQ4m.js → azure-openai-responses-DdpV5zh7.js} +13 -13
  163. package/dist/backgroundWork-Bv0ib_lY.js +49 -0
  164. package/dist/browser-Cw6DqE4e.js +34 -0
  165. package/dist/{layeredConfig-xmTHGrw8.js → browser-DwY5dXHX.js} +21 -983
  166. package/dist/{browser-EJ5_ffnN.js → browser-IsHIcvFg.js} +1 -1
  167. package/dist/calendarSetup-CI3AACVo.js +3892 -0
  168. package/dist/childProcess-Cv8rJuUf.js +32 -0
  169. package/dist/childSession-BrDCrNtL.js +25 -0
  170. package/dist/{classifier-shared-jXm-plIK.js → classifier-shared-DFprgrML.js} +5 -5
  171. package/dist/{cloudflare-workers-ai-system-one-B0wH6HU5.js → cloudflare-workers-ai-system-one-B0MD19yZ.js} +3 -3
  172. package/dist/{codemode-CFVDmyGm.js → codemode-LpcMFMYM.js} +1 -1
  173. package/dist/coerce-DM9YrILC.js +13 -0
  174. package/dist/config-DeWkdjj7.js +1372 -0
  175. package/dist/contextContributions-C1bsEJef.js +13 -0
  176. package/dist/contracts-CW8o6Xyi.js +19 -0
  177. package/dist/contracts-WRa9e98H.js +40 -0
  178. package/dist/cordisHost-_-jtkneB.js +25 -0
  179. package/dist/delegation-B2rBgv8A.js +100 -0
  180. package/dist/{diagnostics-DPTP-yrt.js → diagnostics-BY5LXbHJ.js} +2 -2
  181. package/dist/{dist-BVBi6VMV.js → dist-B2ArMqge.js} +1 -1
  182. package/dist/{server-Cg07O2W6.js → dist-C6IqjC-m.js} +1 -546
  183. package/dist/{dist-PDDFdqDX.js → dist-CDz5dYMj.js} +1 -1
  184. package/dist/{dist-Dvx5mlIR.js → dist-kgi2Ix1y.js} +16 -3
  185. package/dist/{emscripten-module.cloudflare-D4Bc9Ykz.js → emscripten-module.cloudflare-B4fhfquU.js} +1 -1
  186. package/dist/{env-api-keys-CAnjjnsR.js → env-api-keys-BgCPpU9t.js} +1 -1
  187. package/dist/{error-body-DQZRsyL5.js → error-body-CeumezyR.js} +26 -4
  188. package/dist/esm-BKJy3O9-.js +1553 -0
  189. package/dist/{remoteMcp-DqE2xFWS.js → exports-BEEgtkya.js} +1588 -714
  190. package/dist/{exports-LjvSY7Y6.js → exports-CBp_9dVk.js} +47 -28
  191. package/dist/exports-CRjRvvX0.js +34 -0
  192. package/dist/exports-Cg0wxflf.js +1 -0
  193. package/dist/exports-Ct56PRB9.js +46 -0
  194. package/dist/extensionFile-B940JOEn.js +121 -0
  195. package/dist/{factory-Cs8iaUtc.js → factory-BU0cZY0I.js} +1 -1
  196. package/dist/{github-copilot-headers-DpQQAh-s.js → github-copilot-headers-Cq9pnpl2.js} +1 -1
  197. package/dist/{google-generative-ai-BTTOo5RQ.js → google-generative-ai-DmbUlCGv.js} +9 -9
  198. package/dist/{google-shared-S7bqOccz.js → google-shared-Diz2uk39.js} +6 -6
  199. package/dist/{google-vertex-BcMU_DMb.js → google-vertex-CGCpI9Po.js} +10 -10
  200. package/dist/{domains-B6Ae4swm.js → harnessState-Df--jB5z.js} +162 -42
  201. package/dist/{harnessStore-Ccbia9_u.js → harnessStore-DInwiLYb.js} +4 -5
  202. package/dist/{hash-B3RRpLS2.js → hash-IQBoLxOB.js} +1 -1
  203. package/dist/{headers-BEuxFxDI.js → headers-Dkgiqogr.js} +1 -1
  204. package/dist/help-C9UGKetC.js +100 -0
  205. package/dist/home-kwZFHqOx.js +60 -0
  206. package/dist/http-BekstF5S.js +64 -0
  207. package/dist/hubChannel-Dldv3EEb.js +32 -0
  208. package/dist/hubRevisions-BPoC6quI.js +364 -0
  209. package/dist/{identity-BIeAyilV.js → identity-BzB1N-Sn.js} +3 -3
  210. package/dist/index.edge-CSGx6QOL.js +56 -0
  211. package/dist/index.edge-CfP4Hcva.js +198 -0
  212. package/dist/index.edge-ClLTmPFz.js +191 -0
  213. package/dist/index.edge-CzoLWbyl.js +238 -0
  214. package/dist/index.edge-D1biKw71.js +946 -0
  215. package/dist/index.edge-D2RirEwK.js +14 -0
  216. package/dist/iso-BGFmgtky.js +27 -0
  217. package/dist/{kysely-adapter-D51abb3q.js → kysely-adapter-D8KUrWxm.js} +1 -1
  218. package/dist/liquid.browser-1BcykmIN.js +4596 -0
  219. package/dist/manualTranscription-DN56fzgj.js +96 -0
  220. package/dist/{mcpProjection-BXiECnW0.js → mcpProjection-D2U50Pel.js} +1 -2
  221. package/dist/meta-CVgfTHQP.js +1030 -0
  222. package/dist/migrations-DJBPDwSR.js +32 -0
  223. package/dist/{mistral-conversations-DN8VSERk.js → mistral-conversations-Bv_m1MRF.js} +12 -12
  224. package/dist/modeDefinition-Di95_IiU.js +44 -0
  225. package/dist/{models-D6d73jcW.js → models-D50yN8Ag.js} +41 -46
  226. package/dist/{node-UuMT2C3q.js → node-B4kSjHeD.js} +2 -2
  227. package/dist/{node-DytJOfYf.js → node-CBLSc-YH.js} +1 -1
  228. package/dist/notification-DjxbNoMR.js +143 -0
  229. package/dist/{openai-bt3ZRBZv.js → openai-D6Q-l6hT.js} +187 -187
  230. package/dist/{openai-codex-responses-cL36x0ml.js → openai-codex-responses-BnoiTqYV.js} +21 -25
  231. package/dist/{openai-completions-BWsTNYyT.js → openai-completions-C68qs5rI.js} +26 -19
  232. package/dist/{openai-decisions-Dfn_KgQd.js → openai-decisions-BSxU_aoV.js} +3 -3
  233. package/dist/{openai-responses-aa0LoyCJ.js → openai-responses-D6hXen-k.js} +17 -15
  234. package/dist/{openai-responses-shared-H-jH5SlM.js → openai-responses-shared-BD8K7FAC.js} +7 -7
  235. package/dist/{openrouter-cost-D99Qqcs6.js → openrouter-cost-BPam8wyW.js} +1 -1
  236. package/dist/{openrouter-images-BpwVpALC.js → openrouter-images-DylXiHy7.js} +7 -7
  237. package/dist/{hubChannel-Dn5NMpvu.js → packageApi-DYkaxP59.js} +33 -42
  238. package/dist/photon_rs_bg.wasm +0 -0
  239. package/dist/{pi-messages-BHAIkYBj.js → pi-messages-DaIlYYlO.js} +6 -6
  240. package/dist/piConfig-5tRPD0ov.js +126 -0
  241. package/dist/piSettings-ekBG5OeF.js +1 -0
  242. package/dist/platform-CQahdzpG.js +138 -0
  243. package/dist/pluginCatalog-BAALyedS.js +30 -0
  244. package/dist/pluginContributions-Be9EnCAW.js +16 -0
  245. package/dist/pluginProtocol-7_gVUeM9.js +1 -0
  246. package/dist/pluginProtocol-DVIfJnav.js +135 -0
  247. package/dist/portableConfig-0tnk9anb.js +49 -0
  248. package/dist/presetConfig-n-oiNd3h.js +541 -0
  249. package/dist/profileSources-D1rymC97.js +537 -0
  250. package/dist/{protocol-DUeE0Q8z.js → protocol-Cri0GpZR.js} +1 -2
  251. package/dist/{provider-env-DgfpjgTa.js → provider-env-DJb40UF7.js} +2 -2
  252. package/dist/{provider-retry-ChD-K2Gv.js → provider-retry-jpvs7ixx.js} +1 -1
  253. package/dist/{puppeteer-cloudflare-B-GHrPGO.js → puppeteer-cloudflare-D4l8smMS.js} +3 -3
  254. package/dist/{server-BWJmxCrm.js → readiness-Ydw5zrKy.js} +4 -169
  255. package/dist/{rolldown-runtime-B-lAHAz2.js → rolldown-runtime-DbVrKiKs.js} +1 -1
  256. package/dist/{sanitize-unicode-Dl4ROF7y.js → sanitize-unicode-B1ZFaEtf.js} +1 -1
  257. package/dist/scaffoldRegistry-CeFe3Pf0.js +1240 -0
  258. package/dist/{schemas-Vj8-rCR4.js → schemas-D2dRon18.js} +1901 -53
  259. package/dist/server-B3hOw2hW.js +3326 -0
  260. package/dist/server-B9tL6m4q.js +571 -0
  261. package/dist/server-BHjAYOdl.js +1527 -0
  262. package/dist/server-BPV1OpOD.js +15108 -0
  263. package/dist/server-BRWPQZ3b.js +1116 -0
  264. package/dist/server-BW1v1CXw.js +1825 -0
  265. package/dist/server-BWZTwInM.js +1744 -0
  266. package/dist/server-BXCRqk1Y.js +742 -0
  267. package/dist/server-BZE1vhGE.js +492 -0
  268. package/dist/server-BbHDXrj8.js +156 -0
  269. package/dist/server-BcPD_6a2.js +1533 -0
  270. package/dist/server-BmUYK0Ig.js +27187 -0
  271. package/dist/server-BtBc4Sdj.js +584 -0
  272. package/dist/server-C-HBjWRo.js +2800 -0
  273. package/dist/server-C3H2x8Rn.js +9603 -0
  274. package/dist/server-C5LjIK29.js +580 -0
  275. package/dist/server-C8NPfG1H.js +148 -0
  276. package/dist/server-CKkaxOc0.js +978 -0
  277. package/dist/server-CQPI6jIa.js +295 -0
  278. package/dist/{server-BhYE7Vqk.js → server-CQmb0lYL.js} +114 -176
  279. package/dist/server-CZiAy2v5.js +641 -0
  280. package/dist/server-ClQQGtsI.js +679 -0
  281. package/dist/{server-BpPEzRes.js → server-D39LRN9f.js} +654 -745
  282. package/dist/server-D4VFb4Uf.js +24 -0
  283. package/dist/server-D50y-w6B.js +1379 -0
  284. package/dist/{server-CWg0m_wq.js → server-D70beQ8N.js} +269 -1062
  285. package/dist/server-D8lpe7s-.js +1300 -0
  286. package/dist/server-DIArHmjQ.js +877 -0
  287. package/dist/{server-zkcrP99W.js → server-Df1defzp.js} +89 -87
  288. package/dist/server-DgZd_TuT.js +189 -0
  289. package/dist/server-DlRePYOB.js +343 -0
  290. package/dist/{server-yABhJa2K.js → server-G7w-rLJ4.js} +57 -37
  291. package/dist/server-HOmc-Wq6.js +1884 -0
  292. package/dist/server-W6fE1shC.js +112 -0
  293. package/dist/server-i_olh10z.js +24 -0
  294. package/dist/server-lgV6liTt.js +140 -0
  295. package/dist/server-rYmfX6Hw.js +466 -0
  296. package/dist/{server-SA0dsIJ2.js → server-w1aKMZOs.js} +3 -10
  297. package/dist/serverPlugin-4nI5J6Zt.js +39622 -0
  298. package/dist/session-resources-BvR3cwiH.js +10 -0
  299. package/dist/{sessionConfig-DgnPcGBu.js → sessionConfig-UMlgu98q.js} +926 -844
  300. package/dist/{simple-options-DWrW31_K.js → simple-options-Cp5p46f9.js} +13 -6
  301. package/dist/space-C3Wnli1l.js +92 -0
  302. package/dist/sse-XlzXs1es.js +151 -0
  303. package/dist/{streaming-json-t4rzNHEp.js → streaming-json-CZyrX_Ux.js} +6 -6
  304. package/dist/{system-one-shared-DLVLdzYL.js → system-one-shared-Du6bka0h.js} +3 -3
  305. package/dist/{notification-valMY1zH.js → telemetry-CrTcxeA5.js} +2 -93
  306. package/dist/{transform-messages-CjTSwW9q.js → transform-messages-CBj9g2mx.js} +3 -16
  307. package/dist/truncate-M3KbFyVj.js +89 -0
  308. package/dist/{server-BXjfQYeU.js → type-DppaYz6F.js} +955 -1187
  309. package/dist/type-yokaDI_F.js +7 -0
  310. package/dist/{typesafe-system-one-DBVcjcUQ.js → typesafe-system-one-C7YFgvrX.js} +3 -3
  311. package/dist/{uuid-mkNGilLv.js → uuid-BVI0BZsx.js} +1 -1
  312. package/dist/{validation-BLnxgJU_.js → validation-QWuk6kwJ.js} +79 -74
  313. package/dist/vaultSettings-Bq8wkbDv.js +292 -0
  314. package/dist/voiceTools-BdJyfzwB.js +246 -0
  315. package/dist/web-B2sdV-F2.js +4 -0
  316. package/dist/worker.js +126658 -102442
  317. package/dist/workflow-DTCt4n6k.js +171 -0
  318. package/dist/workflowLibrary-DGa6qbh_.js +59 -0
  319. package/package.json +55 -25
  320. package/wrangler.jsonc +16 -3
  321. package/dist/apiContracts-sG5b90Qa.js +0 -4451
  322. package/dist/assets/assets/channel-BOT7In0s.js +0 -2
  323. package/dist/assets/assets/chunk-XXDRQBXY-Dp9-QbR6.js +0 -2
  324. package/dist/assets/assets/flowDiagram-IUGLLWBU-B9D9uWwn.js +0 -1
  325. package/dist/assets/assets/index-BlPEYpuN.css +0 -1
  326. package/dist/assets/assets/index-DS9w_Q1B.js +0 -155
  327. package/dist/assets/assets/swimlanesDiagram-AYQRV4AK-CyUKtW7v.js +0 -9
  328. package/dist/assets/plugins/assets/base-DyDpY0zD.css +0 -2
  329. package/dist/assets/plugins/chunks/po-web-runtime-4JiBsb_c.js +0 -1
  330. package/dist/assets/plugins/slots/approval.09e72f36-DwFz-UMh.js +0 -2
  331. package/dist/assets/plugins/slots/artifacts.50b639bb-CUtFC806.js +0 -1
  332. package/dist/assets/plugins/slots/builtin-tools.75108f21-B69GLfY_.js +0 -7
  333. package/dist/assets/plugins/slots/codemode.c58fb583-C0Gmb7_s.js +0 -9
  334. package/dist/assets/plugins/slots/domain.753f9f92-BTBYRLkE.js +0 -1
  335. package/dist/assets/plugins/slots/mcp.82cc1ff5-Ecacjn0a.js +0 -109
  336. package/dist/assets/plugins/slots/profile.ab16dcec-DIVXNHmh.js +0 -1
  337. package/dist/assets/plugins/slots/skill.62a0a1b3-BNr7DmPH.js +0 -4
  338. package/dist/backgroundWork-CSpsJ-Rg.js +0 -25
  339. package/dist/contextProjection-DDIQRgN4.js +0 -188
  340. package/dist/extensionFile-CacKVegY.js +0 -409
  341. package/dist/harnessState-gmzJcPGt.js +0 -88
  342. package/dist/harnessStore-Ch6hdYYe.js +0 -1
  343. package/dist/index.edge-BgSx_gRO.js +0 -45
  344. package/dist/majorModes-CCnwAjfF.js +0 -333
  345. package/dist/majorModes-DNQbxkpt.js +0 -1
  346. package/dist/piSettings-B6fsgIBA.js +0 -1
  347. package/dist/platform-Bs2_X_dK.js +0 -16
  348. package/dist/platformFiles-CCGujP9o.js +0 -39
  349. package/dist/server-5hLs7M43.js +0 -656
  350. package/dist/server-B3iqBHOP.js +0 -118
  351. package/dist/server-Dv0EKLwc.js +0 -108
  352. package/dist/server-Y5A21sJf.js +0 -591
  353. package/dist/server-a1K226XK.js +0 -279
  354. package/dist/serverPlugin-DUc4gGep.js +0 -7279
  355. package/dist/value-Bd477RDX.js +0 -2247
@@ -0,0 +1,3878 @@
1
+ import { $ as copyJson, A as materializeDocumentValue, C as addressId, E as defineDoc, G as Watch, M as idFromNumber, O as documentCreate, Q as track, T as checkRecordVersion, X as PendingOps, _t as BACKGROUND_CONTEXT, j as resolveAddress, k as materializeDocument, vt as awaitWithContext, w as checkRecordScope, xt as withoutAbortSignal } from "./serverPlugin-4nI5J6Zt.js";
2
+ //#region ../../../node_modules/.pnpm/@earendil-works+pi-durable@1.5.2_patch_hash=0f5e595daa4c370af407284d99d6dba48a9e21f56aa_abe77735ae11ff0752ddae934766aeb6/node_modules/@earendil-works/pi-durable/dist/errors.js
3
+ /**
4
+ * The message of a thrown value, without throwing itself: `String()` throws for values such as `Object.create(null)`,
5
+ * and code that formats an error must not fail for the value it formats.
6
+ */
7
+ function errorMessage(error) {
8
+ if (error instanceof Error) return error.message;
9
+ try {
10
+ return String(error);
11
+ } catch {
12
+ return Object.prototype.toString.call(error);
13
+ }
14
+ }
15
+ /**
16
+ * A transaction read a table after its first table write, or admitted a submission (`submit(tx, draft)`) after it. Read
17
+ * every required row, and admit, before writing.
18
+ */
19
+ var ReadAfterWrite = class extends Error {
20
+ /** `operation` names the call, such as `Tx.task()`. */
21
+ constructor(operation) {
22
+ super(`${operation} cannot read tables after the first table write`);
23
+ this.name = "ReadAfterWrite";
24
+ }
25
+ };
26
+ /**
27
+ * A Storage read rejected an invalid request, such as an unknown conversation or a cursor from another scan, with no
28
+ * durable effect. Unlike any other error a Storage throws, it fails only that read, not the Session; from `commit()` it is
29
+ * fatal like any other.
30
+ */
31
+ var StorageRequestError = class extends Error {
32
+ constructor(message) {
33
+ super(message);
34
+ this.name = "StorageRequestError";
35
+ }
36
+ };
37
+ /**
38
+ * The Session failed, so nothing runs or commits any more. It fails when a Storage method throws, a commit cannot be
39
+ * adopted, or the Harness's own bookkeeping throws (a scheduler commit, an internal commit listener, a registry whose
40
+ * `snapshot()` throws). `cause` is that first error. Reopen the Session; reopening recovers from what was committed.
41
+ */
42
+ var SessionFailed = class extends Error {
43
+ constructor(cause) {
44
+ super("Session failed after a storage error; close and reopen it", { cause });
45
+ this.name = "SessionFailed";
46
+ }
47
+ };
48
+ /**
49
+ * The Harness was opened read-only (`HarnessOptions.readOnly`): a commit with writes, or a call that would run tasks, was
50
+ * refused. Nothing was written, and the Harness stays usable for reads.
51
+ */
52
+ var ReadOnlySession = class extends Error {
53
+ constructor(what) {
54
+ super(`Read-only Harness: ${what} refused`);
55
+ this.name = "ReadOnlySession";
56
+ }
57
+ };
58
+ /** A submission reached a busy conversation and was not admitted. */
59
+ var ConversationBusy = class extends Error {
60
+ conversationId;
61
+ constructor(conversationId) {
62
+ super(`Conversation ${conversationId} is busy`);
63
+ this.name = "ConversationBusy";
64
+ this.conversationId = conversationId;
65
+ }
66
+ };
67
+ /** An input with `whenIdle: "reject"` reached an idle conversation and was not admitted. */
68
+ var ConversationIdle = class extends Error {
69
+ conversationId;
70
+ constructor(conversationId) {
71
+ super(`Conversation ${conversationId} is idle`);
72
+ this.name = "ConversationIdle";
73
+ this.conversationId = conversationId;
74
+ }
75
+ };
76
+ //#endregion
77
+ //#region ../../../node_modules/.pnpm/@earendil-works+pi-durable@1.5.2_patch_hash=0f5e595daa4c370af407284d99d6dba48a9e21f56aa_abe77735ae11ff0752ddae934766aeb6/node_modules/@earendil-works/pi-durable/dist/timers.js
78
+ /** Longest delay `setTimeout` supports; a longer one is waited for in several steps. */
79
+ const MAX_TIMER_DELAY = 2147483647;
80
+ /**
81
+ * Cloudflare Workers: a pending timer keeps a Durable Object from hibernating or being evicted, even an unreferenced
82
+ * one (`nodejs_compat` gives timers an `unref()` that changes nothing).
83
+ */
84
+ const inWorkers = typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers";
85
+ /**
86
+ * The default `HarnessOptions.setTimer`: `setTimeout`, waiting out delays beyond its limit in steps. A background timer
87
+ * is unreferenced, so it never keeps the process alive. It is declined in Cloudflare Workers and wherever timers cannot
88
+ * be unreferenced.
89
+ */
90
+ const nativeTimer = (callback, delayMs, options) => {
91
+ if (options.background && inWorkers) return void 0;
92
+ const arm = (remaining) => {
93
+ const next = setTimeout(() => {
94
+ if (remaining > MAX_TIMER_DELAY) handle = arm(remaining - MAX_TIMER_DELAY);
95
+ else callback();
96
+ }, Math.min(remaining, MAX_TIMER_DELAY));
97
+ if (options.background) next.unref?.();
98
+ return next;
99
+ };
100
+ let handle = arm(Math.max(0, delayMs));
101
+ if (options.background && typeof handle.unref !== "function") {
102
+ clearTimeout(handle);
103
+ return;
104
+ }
105
+ return () => clearTimeout(handle);
106
+ };
107
+ /**
108
+ * Wrap a host `setTimer`. A foreground timer must fire, or work stalls: one the host throws on or declines is armed
109
+ * with `setTimeout`, and the first such failure is reported. A background one the host throws on is reported and
110
+ * declined.
111
+ */
112
+ function hostTimers(setTimer, report) {
113
+ const arm = setTimer ?? nativeTimer;
114
+ let reported = false;
115
+ const fallBack = (error) => {
116
+ if (reported) return;
117
+ reported = true;
118
+ report(error);
119
+ };
120
+ return {
121
+ foreground: (callback, delayMs) => {
122
+ try {
123
+ const disarm = arm(callback, delayMs, { background: false });
124
+ if (disarm !== void 0) return disarm;
125
+ fallBack(/* @__PURE__ */ new Error("HarnessOptions.setTimer declined a timer that paces work; using setTimeout"));
126
+ } catch (error) {
127
+ fallBack(error);
128
+ }
129
+ return nativeTimer(callback, delayMs, { background: false });
130
+ },
131
+ background: (callback, delayMs) => {
132
+ try {
133
+ return arm(callback, delayMs, { background: true });
134
+ } catch (error) {
135
+ report(error);
136
+ return;
137
+ }
138
+ }
139
+ };
140
+ }
141
+ //#endregion
142
+ //#region ../../../node_modules/.pnpm/@earendil-works+pi-durable@1.5.2_patch_hash=0f5e595daa4c370af407284d99d6dba48a9e21f56aa_abe77735ae11ff0752ddae934766aeb6/node_modules/@earendil-works/pi-durable/dist/session/cached-storage.js
143
+ /**
144
+ * Storage that serves hot record reads from memory: conversations, tasks, and written submissions, each table bounded
145
+ * by a count, the least recently used record leaving first, except live tasks, which are kept until they end, and the
146
+ * ended tasks a task waits on, kept until it moved on from its wait: a task's record is read again at each of its state
147
+ * changes, a waiter reads the outcomes of what it waited on once it resumes (`runtime.outcomes()`), and both are
148
+ * bounded by live work, which the scheduler keeps in memory too. Without that, a burst of more tasks than the count
149
+ * would make each of those reads a Storage read on the line. Every commit goes through it, and one process owns a
150
+ * Storage, so it applies each batch as it is published and never goes stale: `commit()`'s batches when the Session publishes
151
+ * them (`published()`), not at their durability receipts. A read
152
+ * result is kept only when no commit published since the read started wrote its record, as the read may not observe
153
+ * that commit; versions are kept only for records with a read in flight. Cached values are frozen and shared. Entries,
154
+ * scans, and documents pass through: the Session keeps documents and the newest entry per conversation itself, and
155
+ * context ranges hold the entries a run reads.
156
+ *
157
+ * Not for a read-only Session: another process writes its Storage.
158
+ */
159
+ var CachedStorage = class {
160
+ #storage;
161
+ #conversations = new Lru(4096);
162
+ /** Live (non-terminal) task records, until their task ends. */
163
+ #liveTasks = /* @__PURE__ */ new Map();
164
+ /**
165
+ * Tasks some task waits on, or waited on until its wait ended and it has not moved on since: how many such waits name
166
+ * each, and its ended record once it ended.
167
+ */
168
+ #awaited = /* @__PURE__ */ new Map();
169
+ /** Per task that waits, or left its wait and has not changed since: what it waited on, and whether it left. */
170
+ #waits = /* @__PURE__ */ new Map();
171
+ #tasks = new Lru(256);
172
+ #submissions = new Lru(256);
173
+ /** Per record with a read in flight: the reads, and how many published commits wrote it since the first began. */
174
+ #reads = /* @__PURE__ */ new Map();
175
+ constructor(storage) {
176
+ this.#storage = storage;
177
+ }
178
+ /** The backend's own scope for a publication (`Storage.publishing`), when it has one. */
179
+ get publishing() {
180
+ return scopeOf(this.#storage);
181
+ }
182
+ /** Pass the batches through; the Session applies each one with `published()` when it publishes it. */
183
+ commit(batches, receive, context) {
184
+ return this.#storage.commit(batches, receive, context);
185
+ }
186
+ /**
187
+ * Apply a batch `commit()` stored, when the Session publishes it. Its records are frozen in place and kept as
188
+ * they are, no copies: the Session's components that follow the publication, such as the scheduler's live tasks,
189
+ * hold the same objects, so a live task's record is in memory once.
190
+ */
191
+ published(writes) {
192
+ for (const write of writes) switch (write.type) {
193
+ case "conversation":
194
+ this.#wrote(write.value.id);
195
+ this.#conversations.set(write.value.id, freeze$1(write.value));
196
+ break;
197
+ case "task":
198
+ this.#wrote(write.value.id);
199
+ this.#followWait(write.value);
200
+ this.#keepTask(freeze$1(write.value));
201
+ break;
202
+ case "submission":
203
+ this.#wrote(write.value.id);
204
+ this.#submissions.set(write.value.id, freeze$1(write.value));
205
+ }
206
+ }
207
+ mintId() {
208
+ return this.#storage.mintId();
209
+ }
210
+ conversation(id, context) {
211
+ const cached = this.#conversations.get(id);
212
+ if (cached !== void 0) return Promise.resolve(cached);
213
+ return this.#keep(id, () => this.#storage.conversation(id, context), (record) => this.#conversations.set(id, record));
214
+ }
215
+ scanConversations(query, limit, cursor, context) {
216
+ return this.#storage.scanConversations(query, limit, cursor, context);
217
+ }
218
+ entry(first, second, third) {
219
+ if (third === void 0) return this.#storage.entry(first, second);
220
+ return this.#storage.entry(first, second, third);
221
+ }
222
+ findLatestHeadMarker(conversationId, atOrBeforeEntryId, context) {
223
+ return this.#storage.findLatestHeadMarker(conversationId, atOrBeforeEntryId, context);
224
+ }
225
+ scanEntries(query, limit, cursor, context) {
226
+ return this.#storage.scanEntries(query, limit, cursor, context);
227
+ }
228
+ task(id, context) {
229
+ const cached = this.#liveTasks.get(id) ?? this.#awaited.get(id)?.record ?? this.#tasks.get(id);
230
+ if (cached !== void 0) return Promise.resolve(cached);
231
+ return this.#keep(id, () => this.#storage.task(id, context), (record) => this.#keepTask(record));
232
+ }
233
+ scanTasks(query, limit, cursor, context) {
234
+ return this.#storage.scanTasks(query, limit, cursor, context);
235
+ }
236
+ /** Cached as written only: this process writes every submission it settles, and a read one is usually settled. */
237
+ submission(id, context) {
238
+ const cached = this.#submissions.get(id);
239
+ return cached === void 0 ? this.#storage.submission(id, context) : Promise.resolve(cached);
240
+ }
241
+ scanSubmissions(query, limit, cursor, context) {
242
+ return this.#storage.scanSubmissions(query, limit, cursor, context);
243
+ }
244
+ submissionByRequest(conversationId, requestId, context) {
245
+ return this.#storage.submissionByRequest(conversationId, requestId, context);
246
+ }
247
+ findDocument(address, at, context) {
248
+ return this.#storage.findDocument(address, at, context);
249
+ }
250
+ document(id, at, context) {
251
+ return this.#storage.document(id, at, context);
252
+ }
253
+ scanDocuments(query, limit, cursor, context) {
254
+ return this.#storage.scanDocuments(query, limit, cursor, context);
255
+ }
256
+ close(context) {
257
+ return this.#storage.close(context);
258
+ }
259
+ /** Records kept per table, for tests that bound memory. */
260
+ get sizes() {
261
+ return {
262
+ conversations: this.#conversations.size,
263
+ tasks: this.#tasks.size,
264
+ liveTasks: this.#liveTasks.size,
265
+ awaited: this.#awaited.size,
266
+ waits: this.#waits.size,
267
+ submissions: this.#submissions.size
268
+ };
269
+ }
270
+ /** Keep a frozen task record: a live one until its task ends, an ended one in the bounded table. */
271
+ #keepTask(record) {
272
+ if (record.state.status === "terminal") {
273
+ this.#liveTasks.delete(record.id);
274
+ const awaited = this.#awaited.get(record.id);
275
+ if (awaited !== void 0) awaited.record = record;
276
+ else this.#tasks.set(record.id, record);
277
+ return;
278
+ }
279
+ this.#tasks.delete(record.id);
280
+ this.#liveTasks.set(record.id, record);
281
+ }
282
+ /**
283
+ * Follow a task's waits from its written record: a wait holds the ended records of its `on` until the task, after
284
+ * leaving the wait, changes again (or ends), as the phase that resumes reads their outcomes before its next commit.
285
+ */
286
+ #followWait(record) {
287
+ const wait = this.#waits.get(record.id);
288
+ if (record.state.status === "waiting") {
289
+ if (wait !== void 0) this.#release(wait.on);
290
+ const on = record.state.on;
291
+ this.#waits.set(record.id, {
292
+ on,
293
+ left: false
294
+ });
295
+ for (const id of on) {
296
+ let awaited = this.#awaited.get(id);
297
+ if (awaited === void 0) {
298
+ const ended = this.#tasks.get(id);
299
+ this.#tasks.delete(id);
300
+ awaited = ended === void 0 ? { count: 0 } : {
301
+ count: 0,
302
+ record: ended
303
+ };
304
+ this.#awaited.set(id, awaited);
305
+ }
306
+ awaited.count++;
307
+ }
308
+ return;
309
+ }
310
+ if (wait === void 0) return;
311
+ if (!wait.left && record.state.status !== "terminal") {
312
+ wait.left = true;
313
+ return;
314
+ }
315
+ this.#waits.delete(record.id);
316
+ this.#release(wait.on);
317
+ }
318
+ /** A wait on `on` is over: what no other wait names goes back to the bounded table. */
319
+ #release(on) {
320
+ for (const id of on) {
321
+ const awaited = this.#awaited.get(id);
322
+ if (--awaited.count > 0) continue;
323
+ this.#awaited.delete(id);
324
+ if (awaited.record !== void 0) this.#tasks.set(id, awaited.record);
325
+ }
326
+ }
327
+ /** A published commit wrote record `id`: a read of it in flight may have missed that. */
328
+ #wrote(id) {
329
+ const reads = this.#reads.get(id);
330
+ if (reads !== void 0) reads.version++;
331
+ }
332
+ /** Resolve with a read's result, frozen; keep a found record unless a commit published since wrote it. */
333
+ async #keep(id, read, keep) {
334
+ let reads = this.#reads.get(id);
335
+ if (reads === void 0) {
336
+ reads = {
337
+ count: 0,
338
+ version: 0
339
+ };
340
+ this.#reads.set(id, reads);
341
+ }
342
+ reads.count++;
343
+ const version = reads.version;
344
+ let value;
345
+ try {
346
+ value = await read();
347
+ } finally {
348
+ if (--reads.count === 0) this.#reads.delete(id);
349
+ }
350
+ if (value === void 0) return void 0;
351
+ freeze$1(value);
352
+ if (reads.version === version) keep(value);
353
+ return value;
354
+ }
355
+ /** Records with a read in flight, for tests that bound memory. */
356
+ get readsInFlight() {
357
+ return this.#reads.size;
358
+ }
359
+ };
360
+ /** `storage`'s publication scope (`Storage.publishing`), for a wrapper to expose as its own; none when it has none. */
361
+ function scopeOf(storage) {
362
+ if (storage.publishing === void 0) return void 0;
363
+ return (publish, context) => storage.publishing(publish, context);
364
+ }
365
+ /** A Map bounded to `capacity` entries that drops the least recently used one. */
366
+ var Lru = class {
367
+ #map = /* @__PURE__ */ new Map();
368
+ #capacity;
369
+ constructor(capacity) {
370
+ this.#capacity = capacity;
371
+ }
372
+ get(key) {
373
+ const value = this.#map.get(key);
374
+ if (value === void 0) return void 0;
375
+ this.#map.delete(key);
376
+ this.#map.set(key, value);
377
+ return value;
378
+ }
379
+ get size() {
380
+ return this.#map.size;
381
+ }
382
+ delete(key) {
383
+ this.#map.delete(key);
384
+ }
385
+ set(key, value) {
386
+ this.#map.delete(key);
387
+ this.#map.set(key, value);
388
+ if (this.#map.size > this.#capacity) this.#map.delete(this.#map.keys().next().value);
389
+ }
390
+ };
391
+ function freeze$1(value) {
392
+ if (value === null || typeof value !== "object" || Object.isFrozen(value)) return value;
393
+ for (const child of Object.values(value)) freeze$1(child);
394
+ return Object.freeze(value);
395
+ }
396
+ //#endregion
397
+ //#region ../../../node_modules/.pnpm/@earendil-works+pi-durable@1.5.2_patch_hash=0f5e595daa4c370af407284d99d6dba48a9e21f56aa_abe77735ae11ff0752ddae934766aeb6/node_modules/@earendil-works/pi-durable/dist/session/conversation-tails.js
398
+ /** Conversations whose newest entry ID is kept: IDs only, so many. */
399
+ const LATEST_CAPACITY = 4096;
400
+ /** Conversations whose newest head marker is kept: whole entries (a compaction summary is one), so fewer. */
401
+ const MARKER_CAPACITY = 256;
402
+ /**
403
+ * The newest entry ID and newest head marker per conversation, for the Session that owns its Storage: every entry is
404
+ * written by one of its commits, so `apply` keeps both current, and a value read from Storage stays valid until the
405
+ * next entry of that conversation. Read only on the Session line after touching the conversation's appends, so no
406
+ * commit that appends to it is unpublished and a value read from Storage can be kept. The newest entry visible from a conversation is its own newest, or for a fork without entries
407
+ * of its own the parent's entry at the fork point: IDs grow, so a conversation's own new entry is always the newest.
408
+ * Each map is bounded by a count, the least recently used conversation leaving first. Kept markers are frozen: entry
409
+ * records are immutable (`Tx.appendEntry()`).
410
+ */
411
+ var ConversationTails = class {
412
+ /** Newest entry ID per conversation, `null` for none. */
413
+ #latest = /* @__PURE__ */ new Map();
414
+ /** Newest head marker per conversation, `null` for none. */
415
+ #markers = /* @__PURE__ */ new Map();
416
+ /** The newest entry ID visible from `conversationId`, read with `read` when not known. */
417
+ async latest(conversationId, read) {
418
+ const known = use(this.#latest, conversationId);
419
+ if (known !== void 0) return known ?? void 0;
420
+ const latest = await read();
421
+ put(this.#latest, conversationId, latest ?? null, LATEST_CAPACITY);
422
+ return latest;
423
+ }
424
+ /**
425
+ * The newest visible head marker at or before `atOrBefore` (any when `undefined`), read with `read` when not known.
426
+ * The newest marker answers every cutoff at or after it, and no marker answers every cutoff.
427
+ */
428
+ async marker(conversationId, atOrBefore, read) {
429
+ const marker = use(this.#markers, conversationId);
430
+ if (marker === null) return void 0;
431
+ if (marker !== void 0 && (atOrBefore === void 0 || atOrBefore >= marker.id)) return marker;
432
+ const latest = this.#latest.get(conversationId);
433
+ const found = await read();
434
+ if (atOrBefore === void 0 || latest !== void 0 && (latest ?? 0) <= atOrBefore) put(this.#markers, conversationId, found === void 0 ? null : freeze(found), MARKER_CAPACITY);
435
+ return found;
436
+ }
437
+ /** The newest entry ID of `conversationId` if known, without reading: `null` for none, `undefined` when unknown. */
438
+ peek(conversationId) {
439
+ return this.#latest.get(conversationId);
440
+ }
441
+ /** At a commit's publication: apply a durable batch. */
442
+ apply(writes) {
443
+ for (const write of writes) if (write.type === "conversation") {
444
+ if (write.value.parent !== void 0) continue;
445
+ put(this.#latest, write.value.id, null, LATEST_CAPACITY);
446
+ put(this.#markers, write.value.id, null, MARKER_CAPACITY);
447
+ } else if (write.type === "entry") {
448
+ const entry = write.value;
449
+ put(this.#latest, entry.conversationId, entry.id, LATEST_CAPACITY);
450
+ if (entry.head !== void 0) put(this.#markers, entry.conversationId, freeze(entry), MARKER_CAPACITY);
451
+ }
452
+ }
453
+ /** How many conversations have their newest entry kept, for tests that bound memory. */
454
+ get size() {
455
+ return this.#latest.size;
456
+ }
457
+ /** How many conversations have their newest head marker kept, for tests that bound memory. */
458
+ get markers() {
459
+ return this.#markers.size;
460
+ }
461
+ };
462
+ /** `map`'s value for `key`, made the most recently used. */
463
+ function use(map, key) {
464
+ const value = map.get(key);
465
+ if (value === void 0) return void 0;
466
+ map.delete(key);
467
+ map.set(key, value);
468
+ return value;
469
+ }
470
+ /** Set `key` as the most recently used, dropping the least recently used beyond `capacity`. */
471
+ function put(map, key, value, capacity) {
472
+ map.delete(key);
473
+ map.set(key, value);
474
+ if (map.size > capacity) map.delete(map.keys().next().value);
475
+ }
476
+ function freeze(value) {
477
+ if (value === null || typeof value !== "object" || Object.isFrozen(value)) return value;
478
+ for (const child of Object.values(value)) freeze(child);
479
+ return Object.freeze(value);
480
+ }
481
+ //#endregion
482
+ //#region ../../../node_modules/.pnpm/@earendil-works+pi-durable@1.5.2_patch_hash=0f5e595daa4c370af407284d99d6dba48a9e21f56aa_abe77735ae11ff0752ddae934766aeb6/node_modules/@earendil-works/pi-durable/dist/session/keys.js
483
+ /** A task record. */
484
+ function taskKey(id) {
485
+ return `task:${id}`;
486
+ }
487
+ /** A conversation record. */
488
+ function conversationKey(id) {
489
+ return `conv:${id}`;
490
+ }
491
+ /** An entry record. */
492
+ function entryKey(id) {
493
+ return `entry:${id}`;
494
+ }
495
+ /** The newest entries of a conversation: appended blind, read by scans, the newest entry, and head markers. */
496
+ function appendKey(id) {
497
+ return `entry-append:${id}`;
498
+ }
499
+ /** A submission record. */
500
+ function submissionKey(id) {
501
+ return `sub:${id}`;
502
+ }
503
+ /** The submission a conversation's request ID names. */
504
+ function requestKey(conversationId, requestId) {
505
+ return `req:${conversationId}:${requestId}`;
506
+ }
507
+ /** A document address (`addressId()`): its current incarnation, value, and held changes. */
508
+ function documentKey(addressId) {
509
+ return `doc:${addressId}`;
510
+ }
511
+ /** A document incarnation, for reads by its ID. */
512
+ function incarnationKey(id) {
513
+ return `docid:${id}`;
514
+ }
515
+ /** The incarnations alive in a scope: created and retired blind, read by scans and the task-document index. */
516
+ function scopeKey(scope) {
517
+ switch (scope.kind) {
518
+ case "session": return "docscope:session";
519
+ case "conversation": return `docscope:c${scope.conversationId}`;
520
+ case "task": return `docscope:t${scope.taskId}`;
521
+ }
522
+ }
523
+ /**
524
+ * A node of the scheduler's ownership tree (a task ID, or `c<conversation ID>`): the live work listed below it. Written
525
+ * by task creation and a task becoming terminal for every node from the task's parent up to and including the nearest
526
+ * live task or the root conversation; read by every walk that expands the node.
527
+ */
528
+ function ownedKey(node) {
529
+ return `owned:${node}`;
530
+ }
531
+ /** The ownerless conversations with live work below them, which global idle walks from. */
532
+ const ROOTS_KEY = "roots";
533
+ /** The live tasks with cancellation intent: abort marks, and held outcomes other than `completed`. */
534
+ const INTENT_KEY = "intent";
535
+ /** The keys of the table records in `writes`; document writes are keyed by the transaction, which knows addresses. */
536
+ function tableKeys(writes, keys) {
537
+ for (const write of writes) switch (write.type) {
538
+ case "conversation":
539
+ keys.push(conversationKey(write.value.id));
540
+ break;
541
+ case "entry":
542
+ keys.push(entryKey(write.value.id), appendKey(write.value.conversationId));
543
+ break;
544
+ case "task":
545
+ keys.push(taskKey(write.value.id));
546
+ break;
547
+ case "submission":
548
+ keys.push(submissionKey(write.value.id));
549
+ if (write.value.requestId !== void 0) keys.push(requestKey(write.value.conversationId, write.value.requestId));
550
+ }
551
+ }
552
+ /**
553
+ * The Storage a job on the line reads through: every read first touches its key (`touch`), which waits while the key
554
+ * has an unpublished writer, so the read sees what the line admitted before it. Scans that cannot be keyed touch
555
+ * `ALL_KEYS`. Commits and `close()` pass through; the line never commits through it.
556
+ */
557
+ var GatedStorage = class {
558
+ #storage;
559
+ #touch;
560
+ constructor(storage, touch) {
561
+ this.#storage = storage;
562
+ this.#touch = touch;
563
+ }
564
+ commit(batches, receive, context) {
565
+ return this.#storage.commit(batches, receive, context);
566
+ }
567
+ mintId() {
568
+ return this.#storage.mintId();
569
+ }
570
+ conversation(id, context) {
571
+ return this.#after(conversationKey(id), () => this.#storage.conversation(id, context));
572
+ }
573
+ scanConversations(query, limit, cursor, context) {
574
+ return this.#after("*", () => this.#storage.scanConversations(query, limit, cursor, context));
575
+ }
576
+ entry(first, second, third) {
577
+ if (third === void 0) {
578
+ const id = first;
579
+ return this.#after(entryKey(id), () => this.#storage.entry(id, second));
580
+ }
581
+ const conversationId = first;
582
+ const id = second;
583
+ return this.#after(conversationKey(conversationId), () => this.#after(entryKey(id), () => this.#storage.entry(conversationId, id, third)));
584
+ }
585
+ findLatestHeadMarker(conversationId, atOrBeforeEntryId, context) {
586
+ return this.#afterEntries(conversationId, () => this.#storage.findLatestHeadMarker(conversationId, atOrBeforeEntryId, context));
587
+ }
588
+ scanEntries(query, limit, cursor, context) {
589
+ return this.#afterEntries(query.conversationId, () => this.#storage.scanEntries(query, limit, cursor, context));
590
+ }
591
+ task(id, context) {
592
+ return this.#after(taskKey(id), () => this.#storage.task(id, context));
593
+ }
594
+ scanTasks(query, limit, cursor, context) {
595
+ return this.#after("*", () => this.#storage.scanTasks(query, limit, cursor, context));
596
+ }
597
+ submission(id, context) {
598
+ return this.#after(submissionKey(id), () => this.#storage.submission(id, context));
599
+ }
600
+ scanSubmissions(query, limit, cursor, context) {
601
+ return this.#after("*", () => this.#storage.scanSubmissions(query, limit, cursor, context));
602
+ }
603
+ submissionByRequest(conversationId, requestId, context) {
604
+ return this.#after(requestKey(conversationId, requestId), () => this.#storage.submissionByRequest(conversationId, requestId, context));
605
+ }
606
+ findDocument(address, at, context) {
607
+ return this.#after(documentKey(addressId(address)), () => this.#storage.findDocument(address, at, context));
608
+ }
609
+ document(id, at, context) {
610
+ return this.#after(incarnationKey(id), () => this.#storage.document(id, at, context));
611
+ }
612
+ scanDocuments(query, limit, cursor, context) {
613
+ return this.#after(scopeKey(query.scope), () => this.#storage.scanDocuments(query, limit, cursor, context));
614
+ }
615
+ close(context) {
616
+ return this.#storage.close(context);
617
+ }
618
+ /**
619
+ * Run a read of a conversation's entries once neither its appends nor its creation has an unpublished writer: Storage
620
+ * refuses the read of a conversation it does not have yet.
621
+ */
622
+ #afterEntries(conversationId, read) {
623
+ return this.#after(conversationKey(conversationId), () => this.#after(appendKey(conversationId), read));
624
+ }
625
+ /** Run `read` once `key` has no unpublished writer. */
626
+ #after(key, read) {
627
+ const gate = this.#touch(key);
628
+ return gate === void 0 ? read() : gate.then(read);
629
+ }
630
+ };
631
+ //#endregion
632
+ //#region ../../../node_modules/.pnpm/@earendil-works+pi-durable@1.5.2_patch_hash=0f5e595daa4c370af407284d99d6dba48a9e21f56aa_abe77735ae11ff0752ddae934766aeb6/node_modules/@earendil-works/pi-durable/dist/session/forks.js
633
+ const SCAN_PAGE_SIZE = 256;
634
+ /** Select every persisted conversation document copied by one fork. */
635
+ async function prepareForkDocumentCopies(storage, parentConversationId, at, childConversationId, context) {
636
+ const entry = await storage.entry(parentConversationId, at, context);
637
+ if (entry === void 0) throw new Error(`Entry ${at} is not visible from conversation ${parentConversationId}`);
638
+ const copies = [];
639
+ const copiedAddresses = /* @__PURE__ */ new Set();
640
+ await collectCopies(storage, {
641
+ kind: "conversation",
642
+ conversationId: entry.entry.conversationId
643
+ }, entry.commitSeq, "asOf", childConversationId, copies, copiedAddresses, context);
644
+ await collectCopies(storage, {
645
+ kind: "conversation",
646
+ conversationId: parentConversationId
647
+ }, "current", "current", childConversationId, copies, copiedAddresses, context);
648
+ return copies;
649
+ }
650
+ async function collectCopies(storage, scope, at, policy, childConversationId, copies, copiedAddresses, context) {
651
+ let cursor;
652
+ do {
653
+ const page = await storage.scanDocuments({
654
+ scope,
655
+ at
656
+ }, SCAN_PAGE_SIZE, cursor, context);
657
+ for (const source of page.items) {
658
+ if (source.scope.kind !== "conversation" || source.fork !== policy) continue;
659
+ const identity = {
660
+ id: await storage.mintId(),
661
+ kind: source.kind,
662
+ ...source.key === void 0 ? {} : { key: source.key },
663
+ scope: {
664
+ kind: "conversation",
665
+ conversationId: childConversationId
666
+ }
667
+ };
668
+ const record = source.history === "latest" ? {
669
+ ...identity,
670
+ history: "latest",
671
+ fork: source.fork
672
+ } : {
673
+ ...identity,
674
+ history: "rewindable",
675
+ fork: source.fork
676
+ };
677
+ const copyAddress = addressId(record);
678
+ if (copiedAddresses.has(copyAddress)) {
679
+ const member = record.key === void 0 ? record.kind : `${record.kind}/${record.key}`;
680
+ throw new Error(`Fork selects multiple source documents for ${member}`);
681
+ }
682
+ copiedAddresses.add(copyAddress);
683
+ copies.push({
684
+ record,
685
+ source: {
686
+ id: source.id,
687
+ at
688
+ }
689
+ });
690
+ }
691
+ cursor = page.next;
692
+ } while (cursor !== void 0);
693
+ }
694
+ //#endregion
695
+ //#region ../../../node_modules/.pnpm/@earendil-works+pi-durable@1.5.2_patch_hash=0f5e595daa4c370af407284d99d6dba48a9e21f56aa_abe77735ae11ff0752ddae934766aeb6/node_modules/@earendil-works/pi-durable/dist/session/transaction.js
696
+ /**
697
+ * Complete record after applying one change. Placement turns a queued input `placed` and a queued write `done`; a
698
+ * continue is never queued, so never placed. Only a placed input or continue can be answered. A settled record stays.
699
+ */
700
+ function applySubmissionChange(current, change) {
701
+ if (current.status === "done" || current.status === "unanswered") return current;
702
+ if (change.status === "placed") {
703
+ if (current.status !== "queued") throw new Error(`Submission ${current.id} is not queued`);
704
+ const status = current.type === "input" ? "placed" : "done";
705
+ return {
706
+ ...current,
707
+ status,
708
+ entry: change.entry
709
+ };
710
+ }
711
+ if (change.status === "done" && current.status !== "placed") throw new Error(`Submission ${current.id} is not a placed input or continue`);
712
+ return {
713
+ ...current,
714
+ ...change
715
+ };
716
+ }
717
+ const INTERNAL_SCAN_PAGE_SIZE = 256;
718
+ const EMPTY_OPERATIONS = [];
719
+ const TABLE_JSON_COPY_OPTIONS = { omitUndefinedProperties: true };
720
+ /**
721
+ * Transaction for one Session commit callback.
722
+ *
723
+ * Every asynchronous operation is tracked so callback settlement can reject and drain unfinished work. Session calls
724
+ * one settlement method, then either discards prepared changes or adopts them once after Storage succeeds.
725
+ */
726
+ var Transaction = class {
727
+ #host;
728
+ #context;
729
+ #scope;
730
+ #pendingOperations = /* @__PURE__ */ new Set();
731
+ #sealed = false;
732
+ #hasTableWrite = false;
733
+ /** Atomic batch; conversation and entry writes stage eagerly, while task and document writes assemble later. */
734
+ #writes = [];
735
+ #createdConversationIds = /* @__PURE__ */ new Set();
736
+ #forkSourceConversationIds = /* @__PURE__ */ new Set();
737
+ #forkSourceDocumentIds = /* @__PURE__ */ new Set();
738
+ /** One entry per task touched by a public read, candidate write, or document-owner lookup. */
739
+ #tasksById = /* @__PURE__ */ new Map();
740
+ /** Submissions created by this transaction, by ID. */
741
+ #submissions = /* @__PURE__ */ new Map();
742
+ /** Submission settlements and placements in staging order; resolved against the latest candidate record during assembly. */
743
+ #submissionChanges = [];
744
+ /** Write and publication plans of every staged incarnation, built during assembly. */
745
+ #plans = [];
746
+ /** Every document acquisition or retirement marker in staging order. */
747
+ #documents = [];
748
+ /** Latest transaction-local incarnation or retirement marker at each logical address. */
749
+ #latestDocumentByAddress = /* @__PURE__ */ new Map();
750
+ constructor(host, context, scope = {}) {
751
+ this.#host = host;
752
+ this.#context = context;
753
+ this.#scope = scope;
754
+ }
755
+ /** Internal: the context of the commit this transaction belongs to. */
756
+ get context() {
757
+ return this.#context;
758
+ }
759
+ /** Internal: whether a table write was staged, after which table reads throw `ReadAfterWrite`. */
760
+ get hasTableWrite() {
761
+ return this.#hasTableWrite;
762
+ }
763
+ /**
764
+ * Internal: whether `tx` is a transaction of a commit of the Session behind `host`. A brand check, so a proxy or
765
+ * another wrapper of a transaction is not one.
766
+ */
767
+ static ownedBy(tx, host) {
768
+ return #host in tx && tx.#host === host;
769
+ }
770
+ conversation(id) {
771
+ return this.#read("conversation", () => this.#host.storage.conversation(id, this.#context));
772
+ }
773
+ entry(first, second) {
774
+ const kind = typeof first === "number" ? void 0 : first.kind;
775
+ const id = typeof first === "number" ? first : second;
776
+ return this.#read("entry", async () => {
777
+ const entry = (await this.#host.storage.entry(id, this.#context))?.entry;
778
+ return kind === void 0 || entry?.kind === kind ? entry : void 0;
779
+ });
780
+ }
781
+ task(id) {
782
+ return this.#read("task", () => this.#committedTask(id));
783
+ }
784
+ scanConversations(query, limit, cursor) {
785
+ return this.#read("scanConversations", () => this.#host.storage.scanConversations(query, limit, cursor, this.#context));
786
+ }
787
+ scanEntries(query, limit, cursor) {
788
+ return this.#read("scanEntries", () => this.#host.storage.scanEntries(query, limit, cursor, this.#context));
789
+ }
790
+ latestHeadMarker(conversationId) {
791
+ return this.#read("latestHeadMarker", () => this.#host.latestHeadMarker(conversationId, this.#context));
792
+ }
793
+ latestEntryId(conversationId) {
794
+ return this.#read("latestEntryId", () => this.#host.latestEntryId(conversationId, this.#context));
795
+ }
796
+ scanTasks(query, limit, cursor) {
797
+ return this.#read("scanTasks", () => this.#host.storage.scanTasks(query, limit, cursor, this.#context));
798
+ }
799
+ /** Committed submission record. */
800
+ submission(id) {
801
+ return this.#read("submission", () => this.#host.storage.submission(id, this.#context));
802
+ }
803
+ /** Committed submission with a conversation-scoped request ID. */
804
+ submissionByRequest(conversationId, requestId) {
805
+ return this.#read("submissionByRequest", () => this.#host.storage.submissionByRequest(conversationId, requestId, this.#context));
806
+ }
807
+ createConversation(options) {
808
+ return this.#write(() => this.#stageConversation(void 0, options.ownership));
809
+ }
810
+ /** Internal final-form bootstrap path for the reserved root identity. */
811
+ createRootConversation() {
812
+ return this.#write(() => this.#stageConversation(void 0, { kind: "ownerless" }, 1));
813
+ }
814
+ forkConversation(parentConversationId, at, options) {
815
+ return this.#write(() => this.#stageConversation({
816
+ conversationId: parentConversationId,
817
+ at
818
+ }, options.ownership));
819
+ }
820
+ async #stageConversation(parent, ownership, reservedId) {
821
+ const ownerTaskId = ownership.kind === "task" ? ownership.taskId : void 0;
822
+ const id = reservedId ?? await this.#host.storage.mintId();
823
+ this.#assertOpen();
824
+ let owner;
825
+ if (ownerTaskId !== void 0) {
826
+ const task = await this.#currentTask(ownerTaskId);
827
+ this.#assertOpen();
828
+ if (task === void 0) throw new Error(`Conversation owner task ${ownerTaskId} does not exist`);
829
+ owner = {
830
+ conversationId: task.conversationId,
831
+ taskId: ownerTaskId
832
+ };
833
+ }
834
+ const record = {
835
+ id,
836
+ ...parent === void 0 ? {} : { parent },
837
+ ...owner === void 0 ? {} : { owner }
838
+ };
839
+ const copies = parent === void 0 ? [] : await prepareForkDocumentCopies(this.#host.storage, parent.conversationId, parent.at, id, this.#context);
840
+ this.#assertOpen();
841
+ for (const copy of copies) {
842
+ this.#forkSourceDocumentIds.add(copy.source.id);
843
+ const entry = {
844
+ addressId: addressId(copy.record),
845
+ address: copy.record,
846
+ target: {
847
+ kind: "fork-copy",
848
+ ...copy
849
+ },
850
+ retireOnCommit: false
851
+ };
852
+ this.#documents.push(entry);
853
+ this.#latestDocumentByAddress.set(entry.addressId, entry);
854
+ }
855
+ if (parent !== void 0) this.#forkSourceConversationIds.add(parent.conversationId);
856
+ this.#createdConversationIds.add(id);
857
+ this.#writes.push({
858
+ type: "conversation",
859
+ value: record
860
+ });
861
+ await this.#host.conversationCreated(this, record);
862
+ this.#assertOpen();
863
+ return record;
864
+ }
865
+ appendEntry(first, second, third) {
866
+ if (typeof first === "number") return this.#appendEntry(first, second);
867
+ return this.#appendEntry(second, {
868
+ ...third,
869
+ kind: first.kind
870
+ });
871
+ }
872
+ #appendEntry(conversationId, value) {
873
+ return this.#write(async () => {
874
+ await this.#requireConversation(conversationId);
875
+ this.#assertOpen();
876
+ const id = await this.#host.storage.mintId();
877
+ this.#assertOpen();
878
+ const { head, ...rest } = value;
879
+ const record = copyJson({
880
+ ...rest,
881
+ id,
882
+ conversationId,
883
+ head: head === "self" ? id : head,
884
+ byTaskId: this.#scope.taskId
885
+ }, TABLE_JSON_COPY_OPTIONS);
886
+ this.#writes.push({
887
+ type: "entry",
888
+ value: record
889
+ });
890
+ return record;
891
+ });
892
+ }
893
+ createTask(task, input, options) {
894
+ return this.#write(async () => {
895
+ if (options.submissionIds !== void 0) {
896
+ let trace;
897
+ let links;
898
+ for (let index = 0; index < options.submissionIds.length; index++) {
899
+ const id = options.submissionIds[index];
900
+ const submission = this.#submissions.get(id) ?? await this.#host.storage.submission(id, this.#context);
901
+ if (index === 0) trace = submission?.trace ?? "root";
902
+ else if (submission?.trace !== void 0) {
903
+ links ??= [];
904
+ links.push(submission.trace);
905
+ }
906
+ }
907
+ options = {
908
+ ...options,
909
+ trace,
910
+ links
911
+ };
912
+ }
913
+ const ownership = options.ownership;
914
+ let owner;
915
+ if (ownership.kind === "task") {
916
+ owner = await this.#currentTask(ownership.taskId);
917
+ this.#assertOpen();
918
+ if (owner === void 0) throw new Error(`Task owner ${ownership.taskId} does not exist`);
919
+ if (options.background === true) throw new TypeError("A child task cannot be background");
920
+ if (options.conversationId !== void 0 && options.conversationId !== owner.conversationId) throw new Error(`A child task lives in its owner's conversation ${owner.conversationId}`);
921
+ }
922
+ const conversationId = owner?.conversationId ?? options.conversationId ?? this.#scope.conversationId;
923
+ if (conversationId === void 0) throw new TypeError("Tx.createTask() requires options.conversationId");
924
+ await this.#requireConversation(conversationId);
925
+ this.#assertOpen();
926
+ const definition = task.definition;
927
+ const checkpoint = definition.initial(input);
928
+ const id = await this.#host.storage.mintId();
929
+ this.#assertOpen();
930
+ const record = copyJson({
931
+ id,
932
+ conversationId,
933
+ kind: definition.name,
934
+ version: definition.version,
935
+ input,
936
+ trace: options.trace === "root" ? void 0 : options.trace ?? this.#context.telemetry.propagation?.inject(this.#context.telemetry),
937
+ links: options.links,
938
+ ...owner === void 0 ? {} : { owner: owner.id },
939
+ background: options.background ?? false,
940
+ abortRequested: false,
941
+ ...options.abandonOnRestart === true ? { abandonOnRestart: true } : {},
942
+ state: {
943
+ status: "pending",
944
+ checkpoint
945
+ }
946
+ }, TABLE_JSON_COPY_OPTIONS);
947
+ this.#tasksById.set(id, { write: {
948
+ kind: "create",
949
+ record
950
+ } });
951
+ return id;
952
+ });
953
+ }
954
+ /** Create a raw submission record with a fresh ID; no admission rules apply. */
955
+ createSubmission(create) {
956
+ return this.#write(async () => {
957
+ await this.#requireConversation(create.conversationId);
958
+ this.#assertOpen();
959
+ const id = await this.#host.storage.mintId();
960
+ this.#assertOpen();
961
+ const record = copyJson({
962
+ ...create,
963
+ id
964
+ }, TABLE_JSON_COPY_OPTIONS);
965
+ this.#submissions.set(id, record);
966
+ return record;
967
+ });
968
+ }
969
+ /**
970
+ * Settle a submission. Resolved during assembly against the transaction's latest candidate record, falling back to
971
+ * committed state, so it is not a caller table read and works after the first table write.
972
+ */
973
+ settleSubmission(id, settlement) {
974
+ this.#assertOpen();
975
+ this.#hasTableWrite = true;
976
+ this.#submissionChanges.push({
977
+ id,
978
+ change: copyJson(settlement)
979
+ });
980
+ }
981
+ /** Place a queued submission at `entry`; resolved during assembly like `settleSubmission()`. */
982
+ placeSubmission(id, entry) {
983
+ this.#assertOpen();
984
+ this.#hasTableWrite = true;
985
+ this.#submissionChanges.push({
986
+ id,
987
+ change: {
988
+ status: "placed",
989
+ entry
990
+ }
991
+ });
992
+ }
993
+ /** Internal: replace one task record completely. Tasks change their own state through their runtime. */
994
+ setTask(value) {
995
+ this.#assertOpen();
996
+ this.#hasTableWrite = true;
997
+ const task = this.#taskEntry(value.id);
998
+ const candidate = task.write?.record;
999
+ if (candidate?.state.status === "terminal") throw new Error(`Task ${value.id} already has a terminal candidate`);
1000
+ if (candidate !== void 0 && candidate.conversationId !== value.conversationId) throw new Error(`Task ${value.id} cannot change conversations`);
1001
+ task.write = {
1002
+ kind: task.write?.kind === "create" ? "create" : "replace",
1003
+ record: copyJson(this.#stampTimes(value, candidate), TABLE_JSON_COPY_OPTIONS)
1004
+ };
1005
+ }
1006
+ /** Internal: candidate records of the tasks this transaction created or replaced so far. */
1007
+ stagedTasks() {
1008
+ const records = [];
1009
+ for (const task of this.#tasksById.values()) if (task.write !== void 0) records.push(task.write.record);
1010
+ return records;
1011
+ }
1012
+ /** Internal: IDs of the tasks this transaction creates. */
1013
+ createdTaskIds() {
1014
+ const ids = [];
1015
+ for (const [id, task] of this.#tasksById) if (task.write?.kind === "create") ids.push(id);
1016
+ return ids;
1017
+ }
1018
+ /** Internal: conversations this transaction created or forked so far. */
1019
+ stagedConversations() {
1020
+ const records = [];
1021
+ for (const write of this.#writes) if (write.type === "conversation") records.push(write.value);
1022
+ return records;
1023
+ }
1024
+ doc(token, ...args) {
1025
+ try {
1026
+ this.#assertOpen();
1027
+ const definition = token.definition;
1028
+ const resolved = resolveAddress(definition, args);
1029
+ this.#assertTaskDocumentsOpen(resolved);
1030
+ const latest = this.#latestDocumentByAddress.get(resolved.id);
1031
+ if (latest !== void 0 && !latest.retireOnCommit) {
1032
+ if (latest.draftPromise !== void 0) return latest.draftPromise;
1033
+ if (latest.target?.kind === "fork-copy") {
1034
+ latest.draftPromise = this.#track(this.#acquireForkCopy(latest, definition, latest.target));
1035
+ return latest.draftPromise;
1036
+ }
1037
+ }
1038
+ const seed = definition.family === true ? copyJson(args[resolved.nextArgument]) : void 0;
1039
+ const docEntry = {
1040
+ addressId: resolved.id,
1041
+ address: resolved.address,
1042
+ definition,
1043
+ retireOnCommit: false
1044
+ };
1045
+ this.#documents.push(docEntry);
1046
+ this.#latestDocumentByAddress.set(docEntry.addressId, docEntry);
1047
+ docEntry.draftPromise = this.#track(this.#acquire(docEntry, seed, latest?.retireOnCommit === true));
1048
+ return docEntry.draftPromise;
1049
+ } catch (error) {
1050
+ return Promise.reject(error);
1051
+ }
1052
+ }
1053
+ retireDoc(token, ...args) {
1054
+ try {
1055
+ this.#assertOpen();
1056
+ const definition = token.definition;
1057
+ const resolved = resolveAddress(definition, args);
1058
+ const latest = this.#latestDocumentByAddress.get(resolved.id);
1059
+ if (latest?.retireOnCommit) return Promise.resolve();
1060
+ if (latest?.target?.kind === "fork-copy") {
1061
+ checkRecordScope(definition, latest.target.record);
1062
+ latest.retireOnCommit = true;
1063
+ return Promise.resolve();
1064
+ }
1065
+ if (latest?.draftPromise !== void 0) {
1066
+ latest.retireOnCommit = true;
1067
+ return this.#track(latest.draftPromise.then(() => void 0));
1068
+ }
1069
+ const entry = {
1070
+ addressId: resolved.id,
1071
+ address: resolved.address,
1072
+ definition,
1073
+ retireOnCommit: true
1074
+ };
1075
+ this.#documents.push(entry);
1076
+ this.#latestDocumentByAddress.set(entry.addressId, entry);
1077
+ return this.#track(this.#findRetirement(entry));
1078
+ } catch (error) {
1079
+ return Promise.reject(error);
1080
+ }
1081
+ }
1082
+ async #acquire(entry, seed, skipLoad) {
1083
+ const definition = entry.definition;
1084
+ const loaded = skipLoad ? void 0 : await this.#host.load(definition, entry.addressId, entry.address, this.#context);
1085
+ this.#assertOpen();
1086
+ if (loaded !== void 0) {
1087
+ checkRecordScope(definition, loaded.record);
1088
+ checkRecordVersion(definition, loaded.record, loaded.storedVersion);
1089
+ entry.target = {
1090
+ kind: "loaded",
1091
+ document: loaded
1092
+ };
1093
+ entry.change = loaded.tracker.beginChange();
1094
+ return entry.change.state;
1095
+ }
1096
+ const scope = entry.address.scope;
1097
+ if (scope.kind === "conversation") await this.#requireConversation(scope.conversationId);
1098
+ if (scope.kind === "task") {
1099
+ const task = await this.#currentTask(scope.taskId);
1100
+ if (task === void 0) throw new Error(`Task ${scope.taskId} does not exist`);
1101
+ if (task.state.status === "terminal") throw new Error(`Task ${scope.taskId} is terminal`);
1102
+ }
1103
+ this.#assertOpen();
1104
+ const value = copyJson(definition.family === true ? definition.initial(seed) : definition.initial());
1105
+ const id = await this.#host.storage.mintId();
1106
+ this.#assertOpen();
1107
+ const tracker = track(value);
1108
+ entry.target = {
1109
+ kind: "created",
1110
+ record: documentCreate(definition, entry.address, id),
1111
+ version: definition.version,
1112
+ tracker
1113
+ };
1114
+ entry.change = tracker.beginChange();
1115
+ return entry.change.state;
1116
+ }
1117
+ async #acquireForkCopy(entry, definition, target) {
1118
+ const stored = await this.#host.storage.document(target.source.id, target.source.at, this.#context);
1119
+ this.#assertOpen();
1120
+ if (stored === void 0) throw new Error(`Fork source document ${target.source.id} cannot be read`);
1121
+ if (stored.record.scope.kind !== "conversation" || stored.record.kind !== target.record.kind || stored.record.key !== target.record.key || stored.record.history !== target.record.history || stored.record.fork !== target.record.fork) throw new Error(`Fork source document ${target.source.id} does not match the copied record`);
1122
+ const value = materializeDocumentValue(definition, target.record, stored.version, stored.value);
1123
+ const tracker = track(value);
1124
+ entry.definition = definition;
1125
+ entry.target = {
1126
+ kind: "created",
1127
+ record: target.record,
1128
+ version: definition.version,
1129
+ tracker
1130
+ };
1131
+ entry.change = tracker.beginChange();
1132
+ return entry.change.state;
1133
+ }
1134
+ async #findRetirement(entry) {
1135
+ const gate = this.#host.touch(documentKey(entry.addressId));
1136
+ if (gate !== void 0) await gate;
1137
+ const record = this.#host.cached(entry.addressId)?.record ?? await this.#host.storage.findDocument(entry.address, "current", this.#context);
1138
+ this.#assertOpen();
1139
+ if (record === void 0) return;
1140
+ checkRecordScope(entry.definition, record);
1141
+ entry.target = {
1142
+ kind: "retire-only",
1143
+ record
1144
+ };
1145
+ }
1146
+ /** Seal after callback failure: abort every change and observe every pending operation. */
1147
+ async settleFailure() {
1148
+ this.#sealed = true;
1149
+ this.#abortChanges();
1150
+ await Promise.allSettled(this.#pendingOperations);
1151
+ this.#context = BACKGROUND_CONTEXT;
1152
+ }
1153
+ /**
1154
+ * Seal after callback success, prepare every open change, and assemble the atomic batch.
1155
+ * Any failure aborts every change before Storage admission.
1156
+ */
1157
+ async settleSuccess() {
1158
+ this.#sealed = true;
1159
+ if (this.#pendingOperations.size > 0) {
1160
+ this.#abortChanges();
1161
+ await Promise.allSettled(this.#pendingOperations);
1162
+ this.#context = BACKGROUND_CONTEXT;
1163
+ throw new Error("Session commit callback settled before its pending Tx operations");
1164
+ }
1165
+ try {
1166
+ for (const document of this.#documents) if (document.change !== void 0) document.prepared = document.change.prepare();
1167
+ return await this.#assemble();
1168
+ } catch (error) {
1169
+ this.#abortChanges();
1170
+ throw error;
1171
+ } finally {
1172
+ this.#context = BACKGROUND_CONTEXT;
1173
+ }
1174
+ }
1175
+ /** Abort every prepared change after Storage failure or when no write is required. */
1176
+ discard() {
1177
+ this.#abortChanges();
1178
+ }
1179
+ /**
1180
+ * Internal: what a deferred commit holds in memory instead of storing (`CommitPersistence`), each changed incarnation
1181
+ * with its operations and whether they selected a base; `undefined` when the commit must be stored. It may be held
1182
+ * only when every write changes an existing `latest`, `initial`-fork conversation document at its stored version.
1183
+ */
1184
+ holdable() {
1185
+ if (this.#writes.some((write) => write.type !== "document.change")) return void 0;
1186
+ const held = [];
1187
+ for (const plan of this.#plans) {
1188
+ const { content, change } = plan;
1189
+ if (content === void 0 && !plan.retire) continue;
1190
+ if (plan.retire || change?.loaded === void 0 || content?.type !== "document.change") return void 0;
1191
+ const { loaded, prepared, version } = change;
1192
+ const record = loaded.record;
1193
+ if (record.scope.kind !== "conversation" || record.history !== "latest" || record.fork !== "initial") return;
1194
+ if (loaded.storedVersion !== version) return void 0;
1195
+ held.push({
1196
+ loaded,
1197
+ ops: prepared.ops,
1198
+ base: content.content.kind === "base"
1199
+ });
1200
+ }
1201
+ return held;
1202
+ }
1203
+ /**
1204
+ * Internal: adopt a held commit (`holdable()`) in memory only. Trackers advance by pointer swap; stored versions and
1205
+ * delta counts stay, as nothing was stored. Returns its publication for the Session's own observers.
1206
+ */
1207
+ adoptHeld() {
1208
+ const publications = [];
1209
+ for (const plan of this.#plans) {
1210
+ const { tracker, prepared, version, loaded } = plan.change;
1211
+ if (prepared.ops.length === 0) {
1212
+ prepared.abort();
1213
+ continue;
1214
+ }
1215
+ tracker.adopt(prepared);
1216
+ const record = loaded.record;
1217
+ const conversationId = plan.conversationId;
1218
+ publications.push({
1219
+ type: "document",
1220
+ kind: "change",
1221
+ record,
1222
+ conversationId,
1223
+ version,
1224
+ value: prepared.value,
1225
+ ops: prepared.ops
1226
+ });
1227
+ }
1228
+ return publications;
1229
+ }
1230
+ /**
1231
+ * Internal: store the held changes of every incarnation this commit reads or writes in front of its own, so a stored
1232
+ * document never misses an operation its later ones build on. Called right before Storage admission, after every
1233
+ * fallible step, because it empties the holds: a failure earlier keeps them. Returns the holds it took.
1234
+ */
1235
+ takeHeld(held) {
1236
+ const taken = [];
1237
+ for (const plan of this.#plans) {
1238
+ if (!("createdAt" in plan.record)) continue;
1239
+ const hold = held(plan.record.id);
1240
+ if (hold === void 0) continue;
1241
+ taken.push(hold);
1242
+ const own = plan.content?.type === "document.change" ? plan.content : void 0;
1243
+ const change = plan.change;
1244
+ const value = change?.prepared.value ?? hold.loaded.tracker.value;
1245
+ const stored = storeHeld(hold, change?.prepared.ops ?? EMPTY_OPERATIONS, value, hold.loaded.valueVersion);
1246
+ const content = own?.content.kind === "base" ? own.content : stored.content;
1247
+ const write = {
1248
+ type: "document.change",
1249
+ id: plan.record.id,
1250
+ content
1251
+ };
1252
+ if (own !== void 0) this.#writes[this.#writes.indexOf(own)] = write;
1253
+ else this.#insertBeforeRetirement(write);
1254
+ if (!plan.retire) plan.held = {
1255
+ ops: stored.ops,
1256
+ observed: own !== void 0
1257
+ };
1258
+ plan.content = write;
1259
+ if (plan.record.scope.kind === "conversation") plan.conversationId = plan.record.scope.conversationId;
1260
+ }
1261
+ return taken;
1262
+ }
1263
+ /**
1264
+ * Internal: the keys this commit writes, once settled (and after `takeHeld()`), for the Session's unpublished write
1265
+ * set: its table records, and the address and incarnation of every document it creates, changes, or retires, with
1266
+ * the scope of every incarnation it creates or retires.
1267
+ */
1268
+ writeKeys() {
1269
+ const keys = [];
1270
+ tableKeys(this.#writes, keys);
1271
+ for (const plan of this.#plans) {
1272
+ if (plan.content === void 0 && !plan.retire) continue;
1273
+ keys.push(documentKey(plan.addressId), incarnationKey(plan.record.id));
1274
+ if (plan.retire || !("createdAt" in plan.record)) keys.push(scopeKey(plan.record.scope));
1275
+ }
1276
+ return keys;
1277
+ }
1278
+ /** Stage a content write for an incarnation, before its retirement when it retires. */
1279
+ #insertBeforeRetirement(write) {
1280
+ const at = this.#writes.findIndex((candidate) => candidate.type === "document.retire" && candidate.id === write.id);
1281
+ if (at < 0) this.#writes.push(write);
1282
+ else this.#writes.splice(at, 0, write);
1283
+ }
1284
+ /** Adopt every prepared change by pointer swap after Storage success and describe the publication. */
1285
+ adopt(seq) {
1286
+ const publications = [];
1287
+ let stored;
1288
+ for (const plan of this.#plans) {
1289
+ const committed = "createdAt" in plan.record;
1290
+ let record = committed ? plan.record : {
1291
+ ...plan.record,
1292
+ createdAt: seq
1293
+ };
1294
+ if (plan.retire) record = {
1295
+ ...record,
1296
+ retiredAt: seq
1297
+ };
1298
+ const change = plan.change;
1299
+ if (change !== void 0) {
1300
+ const { tracker, prepared, loaded, version } = change;
1301
+ if (loaded === void 0 ? !plan.retire : prepared.ops.length > 0) tracker.adopt(prepared);
1302
+ else prepared.abort();
1303
+ if (loaded !== void 0) {
1304
+ if (loaded.storedVersion < version) loaded.storedVersion = version;
1305
+ if (plan.content?.type === "document.change") {
1306
+ if (plan.content.content.kind === "base") loaded.deltasSinceBase = 0;
1307
+ else loaded.deltasSinceBase++;
1308
+ }
1309
+ } else if (!plan.retire) this.#host.install({
1310
+ addressId: plan.addressId,
1311
+ record,
1312
+ storedVersion: version,
1313
+ valueVersion: version,
1314
+ deltasSinceBase: 0,
1315
+ tracker
1316
+ });
1317
+ }
1318
+ if (plan.retire && committed) this.#host.evict(plan.addressId, record.id);
1319
+ const publication = describe(plan, record);
1320
+ if (publication === void 0) continue;
1321
+ const held = plan.held;
1322
+ if (held === void 0) {
1323
+ publications.push(publication);
1324
+ stored?.push(publication);
1325
+ continue;
1326
+ }
1327
+ stored ??= [...publications];
1328
+ if (held.observed) publications.push(publication);
1329
+ stored.push(publication.type === "document" && publication.kind === "change" ? {
1330
+ ...publication,
1331
+ ops: held.ops
1332
+ } : publication);
1333
+ }
1334
+ return {
1335
+ observed: publications,
1336
+ stored: stored ?? publications
1337
+ };
1338
+ }
1339
+ async #assemble() {
1340
+ const storage = this.#host.storage;
1341
+ const plans = this.#plans;
1342
+ for (const document of this.#documents) {
1343
+ const plan = planDocument(document);
1344
+ if (plan !== void 0) plans.push(plan);
1345
+ }
1346
+ this.#rejectForkSourceWrites(plans);
1347
+ await this.#validateOwners();
1348
+ for (const [id, task] of this.#tasksById) {
1349
+ if (task.write?.kind !== "replace") continue;
1350
+ const committed = await this.#committedTask(id);
1351
+ if (committed === void 0) throw new Error(`Task ${id} does not exist`);
1352
+ if (committed.state.status === "terminal") throw new Error(`Task ${id} is already terminal`);
1353
+ if (committed.conversationId !== task.write.record.conversationId) throw new Error(`Task ${id} cannot change conversations`);
1354
+ }
1355
+ const terminalTaskIds = /* @__PURE__ */ new Set();
1356
+ for (const task of this.#tasksById.values()) if (task.write?.record.state.status === "terminal") terminalTaskIds.add(task.write.record.id);
1357
+ if (terminalTaskIds.size > 0) {
1358
+ const retiring = /* @__PURE__ */ new Set();
1359
+ for (const plan of plans) {
1360
+ const scope = plan.record.scope;
1361
+ if (scope.kind !== "task" || !terminalTaskIds.has(scope.taskId)) continue;
1362
+ plan.retire = true;
1363
+ retiring.add(plan.record.id);
1364
+ }
1365
+ const retire = (record) => {
1366
+ if (retiring.has(record.id)) return;
1367
+ plans.push({
1368
+ addressId: addressId(record),
1369
+ record,
1370
+ retire: true
1371
+ });
1372
+ retiring.add(record.id);
1373
+ };
1374
+ for (const taskId of terminalTaskIds) {
1375
+ if (this.#tasksById.get(taskId)?.write?.kind === "create") continue;
1376
+ const gate = this.#host.touch(scopeKey({
1377
+ kind: "task",
1378
+ taskId
1379
+ }));
1380
+ if (gate !== void 0) await gate;
1381
+ const known = this.#host.taskDocuments(taskId);
1382
+ if (known !== void 0) {
1383
+ for (const record of known) retire(record);
1384
+ continue;
1385
+ }
1386
+ let cursor;
1387
+ do {
1388
+ const page = await storage.scanDocuments({
1389
+ scope: {
1390
+ kind: "task",
1391
+ taskId
1392
+ },
1393
+ at: "current"
1394
+ }, INTERNAL_SCAN_PAGE_SIZE, cursor, this.#context);
1395
+ for (const record of page.items) retire(record);
1396
+ cursor = page.next;
1397
+ } while (cursor !== void 0);
1398
+ }
1399
+ }
1400
+ for (const plan of plans) {
1401
+ if (!publishes(plan)) continue;
1402
+ const scope = plan.record.scope;
1403
+ if (scope.kind === "conversation") plan.conversationId = scope.conversationId;
1404
+ if (scope.kind !== "task") continue;
1405
+ const task = this.#taskEntry(scope.taskId);
1406
+ if (task.publicationConversationId === void 0) {
1407
+ const current = await this.#currentTask(scope.taskId);
1408
+ if (current !== void 0) task.publicationConversationId = current.conversationId;
1409
+ }
1410
+ plan.conversationId = task.publicationConversationId;
1411
+ }
1412
+ for (const { id, change } of this.#submissionChanges) {
1413
+ const current = this.#submissions.get(id) ?? await storage.submission(id, this.#context);
1414
+ if (current === void 0) throw new Error(`Submission ${id} does not exist`);
1415
+ const next = applySubmissionChange(current, change);
1416
+ if (next !== current) this.#submissions.set(id, next);
1417
+ }
1418
+ const writes = this.#writes;
1419
+ for (const value of this.#submissions.values()) writes.push({
1420
+ type: "submission",
1421
+ value
1422
+ });
1423
+ for (const task of this.#tasksById.values()) if (task.write !== void 0) writes.push({
1424
+ type: "task",
1425
+ value: task.write.record
1426
+ });
1427
+ for (const plan of plans) {
1428
+ const change = plan.change;
1429
+ if (plan.content?.type === "document.change" && plan.content.content.kind === "delta" && change?.loaded) {
1430
+ const { prepared, version } = change;
1431
+ const info = { deltasSinceBase: change.loaded.deltasSinceBase };
1432
+ if (change.definition.checkpointWhen(prepared.value, prepared.ops, info)) plan.content = {
1433
+ ...plan.content,
1434
+ content: {
1435
+ version,
1436
+ kind: "base",
1437
+ value: prepared.value
1438
+ }
1439
+ };
1440
+ }
1441
+ if (plan.content !== void 0) writes.push(plan.content);
1442
+ if (plan.retire) writes.push({
1443
+ type: "document.retire",
1444
+ id: plan.record.id
1445
+ });
1446
+ }
1447
+ return writes;
1448
+ }
1449
+ /**
1450
+ * New owned work needs a live owner, judged on the owner's final candidate: not `completing`, terminal, or
1451
+ * abort-marked. A task therefore cannot create owned work in the commit that finishes it (spec §5.5).
1452
+ */
1453
+ async #validateOwners() {
1454
+ const owners = [];
1455
+ for (const write of this.#writes) {
1456
+ if (write.type !== "conversation" || write.value.owner === void 0) continue;
1457
+ owners.push({
1458
+ what: "Conversation owner task",
1459
+ taskId: write.value.owner.taskId
1460
+ });
1461
+ }
1462
+ for (const task of this.#tasksById.values()) {
1463
+ const record = task.write?.kind === "create" ? task.write.record : void 0;
1464
+ if (record?.owner !== void 0) owners.push({
1465
+ what: "Task owner",
1466
+ taskId: record.owner
1467
+ });
1468
+ }
1469
+ for (const { what, taskId } of owners) {
1470
+ const task = await this.#currentTask(taskId);
1471
+ if (task === void 0) throw new Error(`${what} ${taskId} does not exist`);
1472
+ if (task.state.status === "terminal" || task.state.status === "completing") throw new Error(`${what} ${taskId} is ${task.state.status}`);
1473
+ if (task.abortRequested) throw new Error(`${what} ${taskId} is abort-marked`);
1474
+ }
1475
+ }
1476
+ #rejectForkSourceWrites(plans) {
1477
+ for (const plan of plans) {
1478
+ if (plan.content === void 0 && !plan.retire) continue;
1479
+ const record = plan.record;
1480
+ if (this.#forkSourceDocumentIds.has(record.id)) throw new Error(`Cannot change fork source document ${record.id} in the fork transaction`);
1481
+ const scope = plan.record.scope;
1482
+ if (scope.kind === "conversation" && this.#forkSourceConversationIds.has(scope.conversationId) && record.scope.kind === "conversation" && record.fork === "current") throw new Error(`Cannot fork conversation ${scope.conversationId} while changing its current-policy documents`);
1483
+ }
1484
+ }
1485
+ #abortChanges() {
1486
+ for (const document of this.#documents) document.change?.abort();
1487
+ }
1488
+ #assertOpen() {
1489
+ if (this.#sealed) throw new Error("Transaction has settled");
1490
+ }
1491
+ #assertTaskDocumentsOpen(resolved) {
1492
+ const scope = resolved.address.scope;
1493
+ if (scope.kind === "task" && this.#tasksById.get(scope.taskId)?.write?.record.state.status === "terminal") throw new Error(`Task ${scope.taskId} is terminal`);
1494
+ }
1495
+ /** Register an operation so callback settlement can reject and drain it. */
1496
+ #track(operation) {
1497
+ this.#pendingOperations.add(operation);
1498
+ const settle = () => {
1499
+ this.#pendingOperations.delete(operation);
1500
+ };
1501
+ operation.then(settle, settle);
1502
+ return operation;
1503
+ }
1504
+ #read(method, read) {
1505
+ try {
1506
+ this.#assertOpen();
1507
+ if (this.#hasTableWrite) throw new ReadAfterWrite(`Tx.${method}()`);
1508
+ return this.#track(read());
1509
+ } catch (error) {
1510
+ return Promise.reject(error);
1511
+ }
1512
+ }
1513
+ #write(write) {
1514
+ try {
1515
+ this.#assertOpen();
1516
+ this.#hasTableWrite = true;
1517
+ return this.#track(write());
1518
+ } catch (error) {
1519
+ return Promise.reject(error);
1520
+ }
1521
+ }
1522
+ async #requireConversation(id) {
1523
+ if (this.#createdConversationIds.has(id)) return;
1524
+ if (await this.#host.storage.conversation(id, this.#context) === void 0) throw new Error(`Conversation ${id} does not exist`);
1525
+ }
1526
+ /**
1527
+ * Lifecycle times: `startedAt` on the first change to `running`, `endedAt` on the change to `terminal`. Once set,
1528
+ * they carry over from the replaced record; records written before they existed lack them.
1529
+ */
1530
+ #stampTimes(value, candidate) {
1531
+ const status = value.state.status;
1532
+ const now = (stamps) => stamps ? this.#host.now() : void 0;
1533
+ const startedAt = candidate?.startedAt ?? value.startedAt ?? now(status === "running");
1534
+ const endedAt = candidate?.endedAt ?? value.endedAt ?? now(status === "terminal");
1535
+ if (startedAt === value.startedAt && endedAt === value.endedAt) return value;
1536
+ return {
1537
+ ...value,
1538
+ ...startedAt === void 0 ? {} : { startedAt },
1539
+ ...endedAt === void 0 ? {} : { endedAt }
1540
+ };
1541
+ }
1542
+ #taskEntry(id) {
1543
+ let task = this.#tasksById.get(id);
1544
+ if (task === void 0) {
1545
+ task = {};
1546
+ this.#tasksById.set(id, task);
1547
+ }
1548
+ return task;
1549
+ }
1550
+ /** Latest candidate task record, falling back to committed state; not a caller table read. */
1551
+ async #currentTask(id) {
1552
+ return this.#tasksById.get(id)?.write?.record ?? await this.#committedTask(id);
1553
+ }
1554
+ #committedTask(id) {
1555
+ const task = this.#taskEntry(id);
1556
+ task.committedRead ??= this.#host.storage.task(id, this.#context);
1557
+ return task.committedRead;
1558
+ }
1559
+ };
1560
+ /** Plan of one staged document: its record, content write, and prepared change. Retirement is decided later. */
1561
+ function planDocument(document) {
1562
+ const target = document.target;
1563
+ if (target === void 0) return void 0;
1564
+ const plan = {
1565
+ addressId: document.addressId,
1566
+ retire: document.retireOnCommit
1567
+ };
1568
+ switch (target.kind) {
1569
+ case "created": {
1570
+ const prepared = document.prepared;
1571
+ const { record, version, tracker } = target;
1572
+ const content = {
1573
+ version,
1574
+ kind: "base",
1575
+ value: prepared.value
1576
+ };
1577
+ return {
1578
+ ...plan,
1579
+ record,
1580
+ content: {
1581
+ type: "document.create",
1582
+ record,
1583
+ content
1584
+ },
1585
+ change: {
1586
+ tracker,
1587
+ prepared,
1588
+ version
1589
+ }
1590
+ };
1591
+ }
1592
+ case "fork-copy": return {
1593
+ ...plan,
1594
+ record: target.record,
1595
+ content: {
1596
+ type: "document.copy",
1597
+ record: target.record,
1598
+ source: target.source
1599
+ }
1600
+ };
1601
+ case "retire-only": return {
1602
+ ...plan,
1603
+ record: target.record
1604
+ };
1605
+ case "loaded": {
1606
+ const loaded = target.document;
1607
+ const definition = document.definition;
1608
+ const prepared = document.prepared;
1609
+ const version = definition.version;
1610
+ const id = loaded.record.id;
1611
+ const content = loaded.storedVersion < version ? {
1612
+ type: "document.change",
1613
+ id,
1614
+ content: {
1615
+ version,
1616
+ kind: "base",
1617
+ value: prepared.value
1618
+ }
1619
+ } : prepared.ops.length > 0 ? {
1620
+ type: "document.change",
1621
+ id,
1622
+ content: {
1623
+ version,
1624
+ kind: "delta",
1625
+ ops: prepared.ops
1626
+ }
1627
+ } : void 0;
1628
+ const change = {
1629
+ tracker: loaded.tracker,
1630
+ prepared,
1631
+ version,
1632
+ loaded,
1633
+ definition
1634
+ };
1635
+ return {
1636
+ ...plan,
1637
+ record: loaded.record,
1638
+ change,
1639
+ ...content === void 0 ? {} : { content }
1640
+ };
1641
+ }
1642
+ }
1643
+ }
1644
+ /** The publication of one adopted plan, if it publishes (`publishes()`), with `record` as committed. */
1645
+ function describe(plan, record) {
1646
+ const conversationId = plan.conversationId;
1647
+ if (plan.retire) return {
1648
+ type: "document",
1649
+ kind: "retire",
1650
+ record,
1651
+ conversationId
1652
+ };
1653
+ if (plan.content?.type === "document.copy") return {
1654
+ type: "document.copy",
1655
+ record,
1656
+ conversationId,
1657
+ source: plan.content.source
1658
+ };
1659
+ const change = plan.change;
1660
+ if (change === void 0 || !publishes(plan)) return void 0;
1661
+ const ops = change.loaded === void 0 ? EMPTY_OPERATIONS : change.prepared.ops;
1662
+ return {
1663
+ type: "document",
1664
+ kind: "change",
1665
+ record,
1666
+ conversationId,
1667
+ version: change.version,
1668
+ value: change.prepared.value,
1669
+ ops
1670
+ };
1671
+ }
1672
+ /**
1673
+ * Take a hold's changes after `ops`, a commit's own on top of them, as one stored content for an incarnation now at
1674
+ * `value`, and the operations a reader of the stored state applies to reach it: the folded ones, or a root replacement
1675
+ * after the queue overflowed, which stores a base, as does a hold whose commits selected one.
1676
+ */
1677
+ function storeHeld(hold, ops, value, version) {
1678
+ hold.pending.push(ops);
1679
+ const taken = hold.pending.take();
1680
+ if (taken.kind === "replace") return {
1681
+ content: {
1682
+ version,
1683
+ kind: "base",
1684
+ value
1685
+ },
1686
+ ops: [["r", value]]
1687
+ };
1688
+ if (hold.base) return {
1689
+ content: {
1690
+ version,
1691
+ kind: "base",
1692
+ value
1693
+ },
1694
+ ops: taken.ops
1695
+ };
1696
+ return {
1697
+ content: {
1698
+ version,
1699
+ kind: "delta",
1700
+ ops: taken.ops
1701
+ },
1702
+ ops: taken.ops
1703
+ };
1704
+ }
1705
+ /**
1706
+ * Whether adoption publishes the plan: every creation, copy, and retirement, and a loaded incarnation that writes
1707
+ * content, which includes a migration-only base so observers of the older shape receive the new value.
1708
+ */
1709
+ function publishes(plan) {
1710
+ return plan.retire || plan.change?.loaded === void 0 || plan.content !== void 0;
1711
+ }
1712
+ //#endregion
1713
+ //#region ../../../node_modules/.pnpm/@earendil-works+pi-durable@1.5.2_patch_hash=0f5e595daa4c370af407284d99d6dba48a9e21f56aa_abe77735ae11ff0752ddae934766aeb6/node_modules/@earendil-works/pi-durable/dist/session/writer.js
1714
+ const SESSION_FAILED = { kind: "failed" };
1715
+ /**
1716
+ * The writer of one Session. The line admits each commit as a part once its callback and settlement succeeded; the
1717
+ * writer sends every part admitted while no call is in flight as one `commit()` call, off the line, and publishes
1718
+ * the parts of a call one by one, in line order, with a macrotask between two, so the continuations of the waits one
1719
+ * resolves start before the next is published. Held commits are parts without writes, published when the parts before
1720
+ * them are.
1721
+ *
1722
+ * Each part registers the keys it writes; until it is published, it is the newest unpublished writer of each, and a
1723
+ * job that touches one waits for its gate. A key leaves when its newest writer is published, so the map holds one entry
1724
+ * per key with an unpublished writer.
1725
+ */
1726
+ var Writer = class {
1727
+ #host;
1728
+ /** Admitted parts not yet sent, in line order. */
1729
+ #queue = [];
1730
+ #flight = false;
1731
+ /** Per key, the newest unpublished part that writes it. */
1732
+ #unpublished = /* @__PURE__ */ new Map();
1733
+ /** The newest admitted part that is not yet published, whose gate opens after every earlier one's. */
1734
+ #newest;
1735
+ constructor(host) {
1736
+ this.#host = host;
1737
+ }
1738
+ /** Admit a part: register its keys, queue it, and send it at once unless a call is in flight. */
1739
+ admit(spec) {
1740
+ const outcome = Promise.withResolvers();
1741
+ outcome.promise.catch(() => {});
1742
+ const part = {
1743
+ ...spec,
1744
+ outcome: outcome.promise,
1745
+ settle: {
1746
+ resolve: () => {
1747
+ part.done = true;
1748
+ outcome.resolve();
1749
+ },
1750
+ reject: (error) => {
1751
+ part.done = true;
1752
+ outcome.reject(error);
1753
+ }
1754
+ },
1755
+ done: false,
1756
+ gate: Promise.withResolvers()
1757
+ };
1758
+ for (const key of spec.keys) this.#unpublished.set(key, part);
1759
+ this.#newest = part;
1760
+ this.#queue.push(part);
1761
+ this.#pump();
1762
+ return part;
1763
+ }
1764
+ /** The gate of the newest unpublished writer of `key`, or `undefined` when it has none. */
1765
+ gate(key) {
1766
+ return this.#unpublished.get(key)?.gate.promise;
1767
+ }
1768
+ /** Opens once every part admitted so far is published or never will be. */
1769
+ drained() {
1770
+ return this.#newest?.gate.promise;
1771
+ }
1772
+ /** Keys with an unpublished writer, for tests that bound memory. */
1773
+ get unpublished() {
1774
+ return this.#unpublished.size;
1775
+ }
1776
+ #pump() {
1777
+ if (this.#flight || this.#queue.length === 0) return;
1778
+ this.#flight = true;
1779
+ const parts = this.#queue;
1780
+ this.#queue = [];
1781
+ this.#flush(parts);
1782
+ }
1783
+ /**
1784
+ * Send and publish `parts`, then what was admitted meanwhile. Never rejects: a throw the writer did not expect fails
1785
+ * the Session and settles the parts (`#abandon()`), so no outcome or gate is stranded.
1786
+ */
1787
+ async #flush(parts) {
1788
+ try {
1789
+ await this.#send(parts);
1790
+ } catch (error) {
1791
+ this.#abandon(parts, error);
1792
+ }
1793
+ this.#flight = false;
1794
+ this.#pump();
1795
+ }
1796
+ /** Store `parts` in one call, then publish them in order; settles every one of them. */
1797
+ async #send(parts) {
1798
+ const stored = parts.filter((part) => part.writes !== void 0);
1799
+ const seqs = [];
1800
+ let result;
1801
+ let rejected;
1802
+ const failed = this.#host.failure();
1803
+ if (failed !== void 0) {
1804
+ for (const part of parts) this.#unpublish(part, new SessionFailed(failed.error));
1805
+ return;
1806
+ }
1807
+ if (stored.length > 0) try {
1808
+ result = await this.#host.commit(stored.map((part) => part.writes), (index, seq) => {
1809
+ seqs[index] = seq;
1810
+ }, withoutAbortSignal(stored[0].context));
1811
+ } catch (error) {
1812
+ rejected = { error };
1813
+ }
1814
+ const failedMeanwhile = this.#host.failure();
1815
+ if (failedMeanwhile !== void 0) {
1816
+ for (const part of parts) this.#unpublish(part, new SessionFailed(failedMeanwhile.error));
1817
+ return;
1818
+ }
1819
+ await this.#publish(parts, seqs, result, rejected);
1820
+ }
1821
+ /**
1822
+ * Publish the received parts and held ones in order, a macrotask apart, and settle every part (group commit §3.4). A
1823
+ * refusal, a rejection, or a part whose adoption or own observer throws fails the Session once the parts before it
1824
+ * are published and the host observers got the last one; the parts after it are not published, and reject with
1825
+ * `SessionFailed`. What the failure decides (the outcomes, and the gates of the parts it concerns) is settled only
1826
+ * once the Session failed, so no job waiting at such a gate, and no later outcome, goes on as if it had not.
1827
+ */
1828
+ async #publish(parts, seqs, result, rejected) {
1829
+ let stop;
1830
+ /**
1831
+ * Settled once the Session failed: each part, whether it was published, and its outcome: an error of its own (any
1832
+ * value, `undefined` included), or `SessionFailed`.
1833
+ */
1834
+ const failing = [];
1835
+ let storedIndex = 0;
1836
+ let published = 0;
1837
+ for (const part of parts) {
1838
+ const index = part.writes === void 0 ? void 0 : storedIndex++;
1839
+ if (stop !== void 0) {
1840
+ const outcome = rejected !== void 0 && index !== void 0 && stop.external !== true ? {
1841
+ kind: "own",
1842
+ error: rejected.error
1843
+ } : SESSION_FAILED;
1844
+ failing.push({
1845
+ part,
1846
+ outcome,
1847
+ published: false
1848
+ });
1849
+ continue;
1850
+ }
1851
+ const seq = index === void 0 ? void 0 : seqs[index];
1852
+ if (index !== void 0 && seq === void 0) {
1853
+ const error = rejected !== void 0 ? rejected.error : index === result?.stored && "refused" in result ? result.refused : /* @__PURE__ */ new Error("Storage committed without adopting the batch");
1854
+ failing.push({
1855
+ part,
1856
+ outcome: {
1857
+ kind: "own",
1858
+ error
1859
+ },
1860
+ published: false
1861
+ });
1862
+ stop = {
1863
+ error,
1864
+ at: part.index
1865
+ };
1866
+ continue;
1867
+ }
1868
+ if (published++ > 0) await hop();
1869
+ let failure;
1870
+ let external;
1871
+ const publication = this.#host.publishing(() => {
1872
+ external = this.#host.failure();
1873
+ if (external !== void 0) return;
1874
+ this.#unregister(part);
1875
+ try {
1876
+ if (part.writes !== void 0) this.#host.stored(part.writes);
1877
+ failure = part.publish(seq);
1878
+ } catch (error) {
1879
+ failure = {
1880
+ kind: "adoption",
1881
+ error
1882
+ };
1883
+ }
1884
+ }, part.context);
1885
+ if (publication !== void 0) await publication;
1886
+ if (external !== void 0) {
1887
+ stop = {
1888
+ error: external.error,
1889
+ at: part.index,
1890
+ external: true
1891
+ };
1892
+ failing.push({
1893
+ part,
1894
+ outcome: SESSION_FAILED,
1895
+ published: false
1896
+ });
1897
+ continue;
1898
+ }
1899
+ if (failure?.kind === "adoption") {
1900
+ failing.push({
1901
+ part,
1902
+ outcome: {
1903
+ kind: "own",
1904
+ error: failure.error
1905
+ },
1906
+ published: true
1907
+ });
1908
+ stop = {
1909
+ error: failure.error,
1910
+ at: part.index
1911
+ };
1912
+ continue;
1913
+ }
1914
+ if (rejected !== void 0) {
1915
+ if (failure !== void 0) this.#host.report(failure.error, part.context);
1916
+ failing.push({
1917
+ part,
1918
+ outcome: {
1919
+ kind: "own",
1920
+ error: rejected.error
1921
+ },
1922
+ published: true
1923
+ });
1924
+ continue;
1925
+ }
1926
+ if (failure !== void 0) stop = {
1927
+ error: failure.error,
1928
+ at: part.index
1929
+ };
1930
+ const failedMeanwhile = this.#host.failure();
1931
+ if (failedMeanwhile !== void 0 && failure === void 0) part.settle.reject(new SessionFailed(failedMeanwhile.error));
1932
+ else part.settle.resolve();
1933
+ this.#open(part);
1934
+ }
1935
+ if (rejected !== void 0 || stop !== void 0) {
1936
+ await Promise.resolve();
1937
+ const own = failing.flatMap(({ part, outcome }) => outcome.kind === "own" ? [part.index] : []);
1938
+ if (rejected !== void 0) this.#host.fail(rejected.error, own[0], own);
1939
+ else this.#host.fail(stop.error, stop.at, own);
1940
+ }
1941
+ for (const { part, outcome, published: stored } of failing) {
1942
+ const error = outcome.kind === "own" ? outcome.error : this.#failed(stop.error);
1943
+ if (stored) {
1944
+ part.settle.reject(error);
1945
+ this.#open(part);
1946
+ } else this.#unpublish(part, error);
1947
+ }
1948
+ const failure = this.#host.failure();
1949
+ if (failure !== void 0) {
1950
+ const queued = this.#queue;
1951
+ this.#queue = [];
1952
+ for (const part of queued) this.#unpublish(part, new SessionFailed(failure.error));
1953
+ }
1954
+ }
1955
+ /**
1956
+ * A throw the writer itself did not expect while sending or publishing `parts` (a bug): fail the Session at the first
1957
+ * of them and settle every one not settled yet, so no outcome, gate, or close waits on it forever.
1958
+ */
1959
+ #abandon(parts, error) {
1960
+ this.#host.fail(error, parts[0].index, []);
1961
+ for (const part of parts) {
1962
+ if (!part.done) this.#unpublish(part, this.#failed(error));
1963
+ this.#unregister(part);
1964
+ this.#open(part);
1965
+ }
1966
+ }
1967
+ /** `SessionFailed` with the Session's failure, or with `error` until the Session records it. */
1968
+ #failed(error) {
1969
+ const failure = this.#host.failure();
1970
+ return new SessionFailed(failure !== void 0 ? failure.error : error);
1971
+ }
1972
+ /** Settle a part that will never be published: discard it, reject it with `error`, and open its gate. */
1973
+ #unpublish(part, error) {
1974
+ part.discard();
1975
+ part.settle.reject(error);
1976
+ this.#unregister(part);
1977
+ this.#open(part);
1978
+ }
1979
+ /** Drop the keys a part is still the newest writer of: it is published, or never will be. */
1980
+ #unregister(part) {
1981
+ for (const key of part.keys) if (this.#unpublished.get(key) === part) this.#unpublished.delete(key);
1982
+ }
1983
+ /** Open a part's gate: the jobs waiting for it go on. The newest part's opens `drained()` too. */
1984
+ #open(part) {
1985
+ part.gate.resolve();
1986
+ if (this.#newest === part) this.#newest = void 0;
1987
+ }
1988
+ };
1989
+ /**
1990
+ * Yield to the event loop once: `setImmediate` where there is one, otherwise a `MessageChannel` message (Workers,
1991
+ * browsers). Microtasks queued before it, such as wait continuations, run first.
1992
+ */
1993
+ function hop() {
1994
+ if (typeof setImmediate === "function") return new Promise((resolve) => setImmediate(resolve));
1995
+ const channel = new MessageChannel();
1996
+ return new Promise((resolve) => {
1997
+ channel.port1.onmessage = () => {
1998
+ channel.port1.close();
1999
+ resolve();
2000
+ };
2001
+ channel.port2.postMessage(void 0);
2002
+ });
2003
+ }
2004
+ //#endregion
2005
+ //#region ../../../node_modules/.pnpm/@earendil-works+pi-durable@1.5.2_patch_hash=0f5e595daa4c370af407284d99d6dba48a9e21f56aa_abe77735ae11ff0752ddae934766aeb6/node_modules/@earendil-works/pi-durable/dist/session/session.js
2006
+ const NO_HOLDS = [];
2007
+ const NO_OPERATIONS = [];
2008
+ const NO_KEYS = [];
2009
+ /**
2010
+ * Jobs admitted to the line whose outcome is not delivered yet, beyond which the line waits. A count, not bytes: what
2011
+ * waits is bounded by what one commit can hold (tool output by its output limits), times the count.
2012
+ */
2013
+ const MAX_OUTSTANDING = 256;
2014
+ const ignore = () => {};
2015
+ /**
2016
+ * Queues a commit's host dispatch as one microtask through `then`: in the same queue as `queueMicrotask()`, which Node
2017
+ * wraps in an async resource that costs about twice the memory and three times the time per stored commit.
2018
+ */
2019
+ const SETTLED = Promise.resolve();
2020
+ /** The default source of a report: a listener, which never fails what ran it. */
2021
+ const LISTENER = { kind: "listener_error" };
2022
+ /** A telemetry adapter that threw on a commit's event, which must not fail the durable commit. */
2023
+ const TELEMETRY = {
2024
+ kind: "host_error",
2025
+ callback: "telemetry"
2026
+ };
2027
+ /**
2028
+ * Open a Session kernel over one storage backend. `now` is the wall clock for task times; default `Date.now`.
2029
+ * `setTimer` arms the timers that evict idle documents; default `setTimeout` (see `HarnessOptions.setTimer`). The first
2030
+ * error a Storage method throws fails the Session (`SessionFailed`); see `SessionImpl`.
2031
+ */
2032
+ function createSession(storage, options) {
2033
+ const retention = options?.documentRetentionMs;
2034
+ const within = options?.persistWithinMs;
2035
+ return new SessionImpl(storage, options?.now, retention === void 0 ? void 0 : () => retention, options?.setTimer, false, () => within);
2036
+ }
2037
+ /** Default document retention: ten minutes, as for kept contexts. */
2038
+ let defaultRetention = 6e5;
2039
+ /**
2040
+ * A retention as given, when it is a number of milliseconds, `0` or more (`Infinity` keeps documents); otherwise the
2041
+ * default.
2042
+ */
2043
+ function documentRetention(ms) {
2044
+ return typeof ms === "number" && ms >= 0 ? ms : defaultRetention;
2045
+ }
2046
+ /** Default `withinMs` of a deferred commit, `settings.progress.persistWithinMs`. */
2047
+ const DEFAULT_PERSIST_WITHIN_MS = 1e3;
2048
+ /**
2049
+ * A deferred commit's default window as given, when it is a number of milliseconds, `0` or more (`Infinity` waits for a
2050
+ * reading or writing commit or close); otherwise the default.
2051
+ */
2052
+ function persistWithin(ms) {
2053
+ return typeof ms === "number" && ms >= 0 ? ms : DEFAULT_PERSIST_WITHIN_MS;
2054
+ }
2055
+ /**
2056
+ * Session kernel: one mutation line, the loaded document tracker cache, and committed publication.
2057
+ *
2058
+ * The cache is bounded by use: a document with no watch attached leaves it once it was not read or
2059
+ * written for the retention period, and the next access loads it from Storage. Eviction runs as a job on the mutation
2060
+ * line, so no transaction ever holds a tracker that leaves.
2061
+ *
2062
+ * Only committed state is observable. A deferred commit (`CommitPersistence`) is committed in memory first: it is
2063
+ * adopted and shown to the Session's own observers, and its changes wait, folded per document and pinned in the cache,
2064
+ * for the first commit that reads or writes the document, the document's deadline, a drop of its tracker, or close,
2065
+ * which store them.
2066
+ *
2067
+ * Group commit: the line runs one job at a time, a commit's callback and settlement; a commit with writes then joins
2068
+ * the writer's pending batch (logical admission, `Writer`) and the line goes on. The writer stores every commit admitted
2069
+ * while no call is in flight in one `commit()` call, off the line, and publishes them one by one, in line order, a
2070
+ * macrotask apart: the read caches, adoption, telemetry events, the Session's own observers, and one microtask later
2071
+ * `observeCommits()` observers, before every wait the commit resolves and every abort it queues. Host listeners and
2072
+ * watch listeners have no order. A deferred commit is published when the commits before it are. A job's every read
2073
+ * touches its key (`touch()`); while an unpublished commit writes that key, the job waits for its publication, so no
2074
+ * job observes state that is not stored. Outcomes are delivered in line order (`#enqueue()`).
2075
+ *
2076
+ * Storage failures are final. Every Storage call goes through one guard: the first error a Storage method throws, other
2077
+ * than for a cancelled caller, fails the Session, as does a commit it cannot adopt. That call gets the error; every later
2078
+ * call and every Storage call still underway gets `SessionFailed`; close listeners run at once with the error, and the
2079
+ * Session then closes itself, Storage included, and `closed` settles. Nothing retries: transient errors are the
2080
+ * Storage's to retry. Reopening recovers from what was committed.
2081
+ */
2082
+ var SessionImpl = class {
2083
+ #storage;
2084
+ /** Newest entry and head marker per conversation; none for a read-only Session, whose Storage another process writes. */
2085
+ #tails;
2086
+ /**
2087
+ * The current documents of each live task this Session created, so the commit that ends a task retires them without
2088
+ * a scan. An entry starts with its task's creation and goes when the task is terminal: bounded by live tasks.
2089
+ */
2090
+ #taskDocuments = /* @__PURE__ */ new Map();
2091
+ #documents = /* @__PURE__ */ new Map();
2092
+ /** Cached documents with no observer attached, by address, oldest use first, with the time of that use. */
2093
+ #idleDocuments = /* @__PURE__ */ new Map();
2094
+ /** Observers attached per document incarnation (record ID); a cached incarnation with any is never evicted. */
2095
+ #attachedDocuments = /* @__PURE__ */ new Map();
2096
+ #clock;
2097
+ #documentRetentionMs;
2098
+ #persistWithinMs;
2099
+ /** Documents with held changes, by incarnation (record ID); each is pinned in the cache until they are stored. */
2100
+ #holds = /* @__PURE__ */ new Map();
2101
+ #holdTimer;
2102
+ /** Refuse every commit with writes (`HarnessOptions.readOnly`). */
2103
+ #readOnly;
2104
+ #timers;
2105
+ /** The pending eviction: a timer for the oldest idle document, or a line job when the retention is 0. */
2106
+ #documentSweep;
2107
+ #sweepJobs = 0;
2108
+ /** Set once the host declined a background timer: then none is kept, and the end of each commit evicts what expired. */
2109
+ #documentTimersUnavailable = false;
2110
+ /** Host commit observers (`observeCommits()`), each behind `guardObserver()`. */
2111
+ #commitListeners = /* @__PURE__ */ new Set();
2112
+ /** The Session's own listeners, such as its scheduler's: they keep memory in step with storage, so a throw fails it. */
2113
+ #internalListeners = /* @__PURE__ */ new Set();
2114
+ #closeListeners = /* @__PURE__ */ new Set();
2115
+ #host;
2116
+ /** The record cache under the guard, which the writer applies each batch to at its publication. */
2117
+ #cached;
2118
+ #writer;
2119
+ /** The Storage jobs on the line read through: each read waits while its key has an unpublished writer. */
2120
+ #gated;
2121
+ /** The end of the last line job: the line runs one job at a time. */
2122
+ #tail = Promise.resolve();
2123
+ /** Line index of the next job; outcomes are delivered in this order. */
2124
+ #nextIndex = 0;
2125
+ /** The job on the line, while one runs: its index, and whether it waited at a gate. */
2126
+ #current;
2127
+ /** Settles once every job so far has its outcome delivered. */
2128
+ #fence = Promise.resolve();
2129
+ #lastDelivered = -1;
2130
+ /** Jobs that started on the line and have no outcome delivered yet (`MAX_OUTSTANDING`). */
2131
+ #outstanding = 0;
2132
+ #room;
2133
+ /** The line index whose outcome the failure is: every later job's outcome is `SessionFailed`, except `#ownOutcomes`. */
2134
+ #failAt;
2135
+ /** Later jobs whose outcome is their own error all the same: the other parts of a storage call that rejected. */
2136
+ #ownOutcomes = /* @__PURE__ */ new Set();
2137
+ #closing;
2138
+ #failure;
2139
+ /** Set when close reaches the backend: calls that fail from then on fail because it closes. */
2140
+ #failed = Promise.withResolvers();
2141
+ #closed = Promise.withResolvers();
2142
+ get closed() {
2143
+ return this.#closed.promise;
2144
+ }
2145
+ /** Internal: the error that failed the Session, if one did. */
2146
+ get failure() {
2147
+ return this.#failure;
2148
+ }
2149
+ /** Internal: rejects with `SessionFailed` the moment the Session fails, before work underway has ended; never resolves. */
2150
+ get failed() {
2151
+ return this.#failed.promise;
2152
+ }
2153
+ constructor(storage, now = Date.now, documentRetentionMs = () => void 0, setTimer, readOnly = false, persistWithinMs = () => void 0) {
2154
+ this.#failed.promise.catch(() => {});
2155
+ this.#readOnly = readOnly;
2156
+ this.#cached = readOnly ? void 0 : new CachedStorage(storage);
2157
+ this.#storage = new GuardedStorage(this.#cached ?? storage, this);
2158
+ this.#gated = new GatedStorage(this.#storage, (key) => this.touch(key));
2159
+ this.#writer = new Writer({
2160
+ commit: (batches, receive, context) => this.#storage.commit(batches, receive, context),
2161
+ stored: (writes) => {
2162
+ this.#cached?.published(writes);
2163
+ this.#tails?.apply(writes);
2164
+ },
2165
+ publishing: (publish, context) => this.#publishing(publish, context),
2166
+ failure: () => this.#failure,
2167
+ fail: (error, at, own) => this.fail(error, void 0, at, own),
2168
+ report: (error, context) => this.report(error, LISTENER, context)
2169
+ });
2170
+ this.#tails = readOnly ? void 0 : new ConversationTails();
2171
+ this.#timers = hostTimers(setTimer, (error) => this.report(error, {
2172
+ kind: "host_error",
2173
+ callback: "setTimer"
2174
+ }));
2175
+ this.#clock = () => {
2176
+ try {
2177
+ return now();
2178
+ } catch {
2179
+ return Date.now();
2180
+ }
2181
+ };
2182
+ this.#documentRetentionMs = () => {
2183
+ try {
2184
+ return documentRetention(documentRetentionMs());
2185
+ } catch {
2186
+ return documentRetention(void 0);
2187
+ }
2188
+ };
2189
+ this.#persistWithinMs = () => {
2190
+ try {
2191
+ return persistWithin(persistWithinMs());
2192
+ } catch {
2193
+ return persistWithin(void 0);
2194
+ }
2195
+ };
2196
+ this.#host = {
2197
+ storage: this.#gated,
2198
+ touch: (key) => this.touch(key),
2199
+ now,
2200
+ cached: (id) => {
2201
+ const cached = this.#documents.get(id);
2202
+ if (cached !== void 0) this.#touchDocument(id);
2203
+ return cached;
2204
+ },
2205
+ load: (definition, addressId, address, context) => this.#loadDocument(definition, addressId, address, context),
2206
+ install: (document) => {
2207
+ this.#documents.set(document.addressId, document);
2208
+ this.#touchDocument(document.addressId);
2209
+ },
2210
+ evict: (id, recordId) => {
2211
+ if (this.#documents.get(id)?.record.id === recordId) this.#dropDocument(id);
2212
+ },
2213
+ conversationCreated: (tx, record) => this.conversationCreated(tx, record),
2214
+ taskDocuments: (taskId) => this.#taskDocuments.get(taskId)?.values(),
2215
+ latestEntryId: (conversationId, context) => this.latestEntryId(conversationId, context),
2216
+ latestHeadMarker: (conversationId, context) => this.latestHeadMarker(conversationId, void 0, context)
2217
+ };
2218
+ }
2219
+ /** The Storage behind the failure guard; every component reads and writes through it. */
2220
+ get storage() {
2221
+ return this.#storage;
2222
+ }
2223
+ /**
2224
+ * Internal, on the Session line: the newest entry ID visible from `conversationId`. Known from the Session's own
2225
+ * commits when it owns its Storage, so it costs no Storage read after the first.
2226
+ */
2227
+ latestEntryId(conversationId, context) {
2228
+ const gate = this.#touchEntries(conversationId);
2229
+ const latest = () => {
2230
+ const read = async () => (await this.#storage.scanEntries({ conversationId }, 1, void 0, context)).items[0]?.id;
2231
+ return this.#tails === void 0 ? read() : this.#tails.latest(conversationId, read);
2232
+ };
2233
+ return gate === void 0 ? latest() : gate.then(latest);
2234
+ }
2235
+ /**
2236
+ * Internal: the newest entry ID of `conversationId` as known from the Session's commits right now, without reading;
2237
+ * `undefined` when not known (and always for a read-only Session).
2238
+ */
2239
+ knownLatestEntryId(conversationId) {
2240
+ return this.#tails?.peek(conversationId);
2241
+ }
2242
+ /**
2243
+ * Internal, on the Session line: the newest visible head marker of `conversationId` at or before `atOrBefore`, any
2244
+ * when `undefined`; known from the Session's own commits as `latestEntryId()` is.
2245
+ */
2246
+ latestHeadMarker(conversationId, atOrBefore, context) {
2247
+ const gate = this.#touchEntries(conversationId);
2248
+ const marker = () => {
2249
+ const read = () => this.#storage.findLatestHeadMarker(conversationId, atOrBefore, context);
2250
+ return this.#tails === void 0 ? read() : this.#tails.marker(conversationId, atOrBefore, read);
2251
+ };
2252
+ return gate === void 0 ? marker() : gate.then(marker);
2253
+ }
2254
+ /**
2255
+ * On the line: wait for what an unpublished commit wrote of a conversation's entries, its appends and its creation,
2256
+ * as reading them from Storage fails for a conversation not stored yet.
2257
+ */
2258
+ #touchEntries(conversationId) {
2259
+ const created = this.touch(conversationKey(conversationId));
2260
+ const appended = this.touch(appendKey(conversationId));
2261
+ if (created === void 0) return appended;
2262
+ return appended === void 0 ? created : Promise.all([created, appended]).then(ignore);
2263
+ }
2264
+ /**
2265
+ * Internal, on the line: wait, while `key` has an unpublished writer (for `ALL_KEYS`, while anything is unpublished),
2266
+ * until it is published, then check that the Session is healthy; `undefined` when there is nothing to wait for. A
2267
+ * job's every read touches its key first, so it never observes state an earlier job admitted and the writer has not
2268
+ * published.
2269
+ */
2270
+ touch(key) {
2271
+ const gate = key === "*" ? this.#writer.drained() : this.#writer.gate(key);
2272
+ if (gate === void 0) return void 0;
2273
+ if (this.#current !== void 0) this.#current.hit = true;
2274
+ return gate.then(() => this.#assertHealthy());
2275
+ }
2276
+ commit(change, context, options) {
2277
+ return this.commitWith(change, context, void 0, options);
2278
+ }
2279
+ /**
2280
+ * Internal: fail the Session with `error`, the first wins, and report it once. Admission ends, and close listeners run
2281
+ * now; they read the error from `failure`. The Storage guard calls this; the Harness also calls it for a throw in its
2282
+ * scheduler's own commits. `at` is the line index of the job whose outcome the failure is, by default the job on the
2283
+ * line: later jobs' outcomes become `SessionFailed`.
2284
+ */
2285
+ fail(error, context, at, own) {
2286
+ if (this.#failure !== void 0) return;
2287
+ this.#failure = { error };
2288
+ this.#failAt = at ?? this.#current?.index ?? this.#lastDelivered;
2289
+ if (own !== void 0) for (const index of own) this.#ownOutcomes.add(index);
2290
+ this.#failed.reject(new SessionFailed(error));
2291
+ this.close(BACKGROUND_CONTEXT).catch(() => {});
2292
+ this.report(error, { kind: "storage_failed" }, context);
2293
+ }
2294
+ /**
2295
+ * Internal commit exposing the concrete transaction and its internal operations, such as the reserved-ID root
2296
+ * bootstrap and task replacement. `scope` sets the default `tx.createTask()` conversation and the task attributed to
2297
+ * appended entries.
2298
+ */
2299
+ commitWith(change, context, scope, options) {
2300
+ let withinMs;
2301
+ try {
2302
+ this.assertUsable();
2303
+ withinMs = this.#deferral(options?.persistence);
2304
+ } catch (error) {
2305
+ return Promise.reject(error);
2306
+ }
2307
+ return this.#enqueue((index) => this.#runCommit(change, context, scope, withinMs, index));
2308
+ }
2309
+ /**
2310
+ * Internal: `commitWith()` for a commit of the scheduler's own whose outcome goes only to scheduler code. When it
2311
+ * writes nothing and waited at no gate, it is equivalent to having run before every unpublished commit, so its
2312
+ * outcome is delivered at once, ahead of theirs. One that writes is never exempt: its outcome waits for its own
2313
+ * publication and every earlier outcome, so no invocation starts on a reservation that is not durable.
2314
+ */
2315
+ commitInternal(change, context) {
2316
+ try {
2317
+ this.assertUsable();
2318
+ } catch (error) {
2319
+ return Promise.reject(error);
2320
+ }
2321
+ return this.#enqueue((index) => this.#runCommit(change, context, void 0, void 0, index), true);
2322
+ }
2323
+ /**
2324
+ * Internal, on the line: call `end` once the outcome of the job on the line settles, its commit published or never to
2325
+ * be; at once off the line.
2326
+ */
2327
+ onJobEnd(end) {
2328
+ const job = this.#current;
2329
+ if (job === void 0) {
2330
+ end();
2331
+ return;
2332
+ }
2333
+ if (job.ends === void 0) job.ends = [end];
2334
+ else job.ends.push(end);
2335
+ }
2336
+ /** Internal: the Storage jobs on the line read through (`touch()`); off the line, use the plain one. */
2337
+ get lineStorage() {
2338
+ return this.#gated;
2339
+ }
2340
+ /** How long a commit may stay in memory before it is stored; `undefined` when it is immediate. */
2341
+ #deferral(persistence) {
2342
+ if (persistence?.kind !== "deferred") return void 0;
2343
+ const ms = persistence.withinMs;
2344
+ if (ms === void 0) return this.#persistWithinMs();
2345
+ if (typeof ms !== "number" || !(ms >= 0)) throw new TypeError("CommitPersistence.withinMs must be a number of milliseconds, 0 or more");
2346
+ return ms;
2347
+ }
2348
+ /** Internal: whether `tx` is the transaction of one of this Session's commits. */
2349
+ ownsTransaction(tx) {
2350
+ return Transaction.ownedBy(tx, this.#host);
2351
+ }
2352
+ /**
2353
+ * Internal: run a read-only job on the mutation line so multi-read derivations observe one committed state. It reads
2354
+ * through `storage`, whose reads wait for the publication of what the line admitted before; its outcome comes after
2355
+ * theirs.
2356
+ */
2357
+ readOnLine(job) {
2358
+ try {
2359
+ this.assertUsable();
2360
+ } catch (error) {
2361
+ return Promise.reject(error);
2362
+ }
2363
+ return this.#enqueue(async () => {
2364
+ this.#assertHealthy();
2365
+ return { value: await job(this.#gated) };
2366
+ });
2367
+ }
2368
+ /**
2369
+ * Internal: a conversation document's current incarnation and value, for a job already running on the line (see
2370
+ * `readOnLine()`). Absent documents are `undefined`.
2371
+ */
2372
+ async conversationDocumentOnLine(token, conversationId, context) {
2373
+ const definition = token.definition;
2374
+ const resolved = resolveAddress(definition, [conversationId, context]);
2375
+ const loaded = await this.#loadDocument(definition, resolved.id, resolved.address, context);
2376
+ if (loaded === void 0) return void 0;
2377
+ checkRecordScope(definition, loaded.record);
2378
+ checkRecordVersion(definition, loaded.record, loaded.storedVersion);
2379
+ return {
2380
+ record: loaded.record,
2381
+ version: loaded.valueVersion,
2382
+ value: loaded.tracker.value
2383
+ };
2384
+ }
2385
+ async snapshot(token, ...args) {
2386
+ this.assertUsable();
2387
+ const definition = token.definition;
2388
+ const resolved = resolveAddress(definition, args);
2389
+ const context = args[resolved.nextArgument];
2390
+ const cached = this.#documents.get(resolved.id);
2391
+ if (cached?.valueVersion === definition.version) this.#touchDocument(resolved.id);
2392
+ const loaded = cached?.valueVersion === definition.version ? cached : await this.#enqueue(async () => {
2393
+ this.#assertHealthy();
2394
+ return { value: await this.#loadDocument(definition, resolved.id, resolved.address, context) };
2395
+ });
2396
+ if (loaded === void 0) return void 0;
2397
+ checkRecordScope(definition, loaded.record);
2398
+ checkRecordVersion(definition, loaded.record, loaded.storedVersion);
2399
+ return loaded.tracker.value;
2400
+ }
2401
+ watchDoc(token, ...args) {
2402
+ try {
2403
+ this.assertUsable();
2404
+ const definition = token.definition;
2405
+ const resolved = resolveAddress(definition, args);
2406
+ const context = args[resolved.nextArgument];
2407
+ const signal = context.abortSignal;
2408
+ return this.#attachDocument(definition, resolved, context, (loaded) => {
2409
+ const watch = this.#observeDocument(definition, loaded, createWatch, endWatch);
2410
+ if (signal !== void 0) watch.observeAbort(signal);
2411
+ return watch;
2412
+ }, abortWatch);
2413
+ } catch (error) {
2414
+ return Promise.reject(error);
2415
+ }
2416
+ }
2417
+ observeDoc(token, ...args) {
2418
+ try {
2419
+ this.assertUsable();
2420
+ const definition = token.definition;
2421
+ const resolved = resolveAddress(definition, args);
2422
+ const observer = args[resolved.nextArgument];
2423
+ const context = args[resolved.nextArgument + 1];
2424
+ return this.#attachDocument(definition, resolved, context, (loaded) => {
2425
+ const guarded = this.#observeDocument(definition, loaded, (_value, detach, report) => guardObserver(observer, detach, report), endGuarded);
2426
+ return observation(loaded.tracker.value, guarded);
2427
+ }, detachObservation);
2428
+ } catch (error) {
2429
+ return Promise.reject(error);
2430
+ }
2431
+ }
2432
+ async snapshotAsOf(token, ...args) {
2433
+ this.assertUsable();
2434
+ const definition = token.definition;
2435
+ const resolved = resolveAddress(definition, args);
2436
+ if (resolved.address.scope.kind !== "conversation") throw new TypeError("Session.snapshotAsOf() requires a conversation document");
2437
+ const conversationId = resolved.address.scope.conversationId;
2438
+ const atValue = args[resolved.nextArgument];
2439
+ if (typeof atValue !== "number" || !Number.isSafeInteger(atValue)) throw new TypeError("Session.snapshotAsOf() requires an entry ID");
2440
+ const at = idFromNumber(atValue);
2441
+ const context = args[resolved.nextArgument + 1];
2442
+ return this.#enqueue(async () => {
2443
+ this.#assertHealthy();
2444
+ const storedEntry = await this.#gated.entry(conversationId, at, context);
2445
+ if (storedEntry === void 0) throw new Error(`Entry ${at} is not visible from conversation ${conversationId}`);
2446
+ const address = {
2447
+ ...resolved.address,
2448
+ scope: {
2449
+ kind: "conversation",
2450
+ conversationId: storedEntry.entry.conversationId
2451
+ }
2452
+ };
2453
+ const record = await this.#gated.findDocument(address, storedEntry.commitSeq, context);
2454
+ if (record === void 0) return { value: void 0 };
2455
+ const stored = await this.#gated.document(record.id, storedEntry.commitSeq, context);
2456
+ if (stored === void 0) throw new Error(`Historical document ${record.id} (${record.kind}) cannot be read`);
2457
+ return { value: materializeDocument(definition, stored) };
2458
+ });
2459
+ }
2460
+ close(context) {
2461
+ if (this.#closing === void 0) {
2462
+ const cleanup = withoutAbortSignal(context);
2463
+ this.#closing = Promise.resolve().then(() => this.beforeClose()).then(() => this.#maintain(async () => {
2464
+ await this.#drained();
2465
+ let unstored;
2466
+ if (this.#failure === void 0 && this.#holds.size > 0) await this.#storeHolds(() => [...this.#holds.values()], cleanup).catch((error) => {
2467
+ unstored = { error };
2468
+ });
2469
+ const observers = [...this.#commitListeners];
2470
+ this.#commitListeners.clear();
2471
+ const end = closeEnds(this.#failure).observer;
2472
+ for (const observer of observers) observer.end(end);
2473
+ this.#internalListeners.clear();
2474
+ this.#documents.clear();
2475
+ this.#idleDocuments.clear();
2476
+ this.#attachedDocuments.clear();
2477
+ this.#holds.clear();
2478
+ this.#taskDocuments.clear();
2479
+ try {
2480
+ await this.#storage.close(cleanup);
2481
+ } catch (error) {
2482
+ if (this.#failure === void 0) {
2483
+ this.#failure = { error };
2484
+ this.report(error, { kind: "storage_failed" });
2485
+ }
2486
+ throw error;
2487
+ }
2488
+ if (unstored !== void 0) throw unstored.error;
2489
+ })).finally(() => {
2490
+ const failure = this.#failure;
2491
+ this.#closed.resolve(failure === void 0 ? { kind: "closed" } : {
2492
+ kind: "failed",
2493
+ error: failure.error
2494
+ });
2495
+ });
2496
+ this.#notifyClose();
2497
+ }
2498
+ return awaitWithContext(this.#closing, context);
2499
+ }
2500
+ /** Run the close listeners once, each on its own: one that fails is reported, and the rest still run. */
2501
+ #notifyClose() {
2502
+ this.#documentSweep?.disarm?.();
2503
+ this.#documentSweep = void 0;
2504
+ this.#holdTimer?.disarm();
2505
+ this.#holdTimer = void 0;
2506
+ const listeners = [...this.#closeListeners];
2507
+ this.#closeListeners.clear();
2508
+ for (const listener of listeners) contained(listener, (error) => this.report(error));
2509
+ }
2510
+ /**
2511
+ * Internal: the Session's failure, and errors of listeners, which never fail what ran them; `info` defaults to a
2512
+ * listener. A plain Session drops them.
2513
+ */
2514
+ report(_error, _info = LISTENER, _context) {}
2515
+ /**
2516
+ * Runs inside every transaction that creates or forks a conversation, after the conversation record is staged. A
2517
+ * plain Session stages nothing; a Harness stages its built-in documents.
2518
+ */
2519
+ conversationCreated(_tx, _record) {
2520
+ return Promise.resolve();
2521
+ }
2522
+ /**
2523
+ * Internal, for `beforeClose()`: on the line, after every commit admitted before the seal has settled, write what
2524
+ * `writes()` returns then straight to Storage. Nothing is published, since the Session is closing; a failed Session
2525
+ * writes nothing.
2526
+ */
2527
+ writeAtClose(writes) {
2528
+ return this.#maintain(async (index) => {
2529
+ await this.#drained();
2530
+ if (this.#failure !== void 0) return;
2531
+ const batch = writes();
2532
+ if (batch.length === 0) return;
2533
+ const context = BACKGROUND_CONTEXT;
2534
+ await this.#writer.admit({
2535
+ index,
2536
+ writes: batch,
2537
+ keys: [],
2538
+ context,
2539
+ publish: () => void 0,
2540
+ discard: ignore
2541
+ }).outcome;
2542
+ });
2543
+ }
2544
+ /**
2545
+ * Keys a commit writes besides its records' (`Transaction.writeKeys()`), at its admission, on the line: a Harness
2546
+ * adds the ownership memberships its task changes write. A plain Session adds none.
2547
+ */
2548
+ membershipKeys(_tx) {
2549
+ return NO_KEYS;
2550
+ }
2551
+ /** Runs after close seals admission and before the line closes Storage; must not reject. */
2552
+ beforeClose() {
2553
+ return Promise.resolve();
2554
+ }
2555
+ /**
2556
+ * Attach a synchronous observer of every stored commit, with exactly what it stored (`CommitPublication`). Its
2557
+ * `advance` runs one microtask after the commit's publication, which follows its storage call, in line order, before
2558
+ * every wait the commit resolves and every abort it queues (in no order with watch listeners); it must not block or
2559
+ * call Session operations. A throw is reported, detaches it, and ends it `listener_error`; `end` gets the Session's
2560
+ * close after its last publication.
2561
+ */
2562
+ observeCommits(observer) {
2563
+ this.assertUsable();
2564
+ const guarded = guardObserver(observer, () => this.#commitListeners.delete(guarded), (error, context) => this.report(error, LISTENER, context));
2565
+ this.#commitListeners.add(guarded);
2566
+ return { detach: () => guarded.detach() };
2567
+ }
2568
+ /**
2569
+ * Internal: follow every commit as memory adopts it (`ObservedCommit`), for the Session's own components, whose state
2570
+ * follows memory. A throw leaves that state behind, so it fails the Session instead of being reported. They run at
2571
+ * the commit's publication, synchronously, so they call no Storage method, run no task code, and contain every host
2572
+ * callback; the waits they resolve and the aborts they queue run after host observers.
2573
+ */
2574
+ followCommits(listener) {
2575
+ this.assertUsable();
2576
+ this.#internalListeners.add(listener);
2577
+ return () => this.#internalListeners.delete(listener);
2578
+ }
2579
+ /**
2580
+ * Register a listener called synchronously when close begins, also when a failure closes the Session (`failure` is
2581
+ * then set). It must not block or call Session operations; a throw is reported.
2582
+ */
2583
+ subscribeClose(listener) {
2584
+ this.assertUsable();
2585
+ this.#closeListeners.add(listener);
2586
+ return () => this.#closeListeners.delete(listener);
2587
+ }
2588
+ /** Drop every loaded tracker on the mutation line, held changes stored first; later access cold-loads from Storage. */
2589
+ unloadDocuments() {
2590
+ return this.#maintain(async () => {
2591
+ if (this.#failure === void 0) await this.#storeHolds(() => [...this.#holds.values()], BACKGROUND_CONTEXT);
2592
+ this.#documents.clear();
2593
+ this.#idleDocuments.clear();
2594
+ });
2595
+ }
2596
+ /**
2597
+ * Internal, for tests: how many documents the cache holds, how many are idle, how many incarnations are pinned, how
2598
+ * many sweep jobs were queued on the line so far, how many documents have held changes, how many live tasks have
2599
+ * their documents indexed, and how many conversations have their newest entry kept.
2600
+ */
2601
+ get documentCacheSizes() {
2602
+ return {
2603
+ cached: this.#documents.size,
2604
+ idle: this.#idleDocuments.size,
2605
+ attached: this.#attachedDocuments.size,
2606
+ sweeps: this.#sweepJobs,
2607
+ held: this.#holds.size,
2608
+ taskDocuments: this.#taskDocuments.size,
2609
+ tails: this.#tails?.size ?? 0
2610
+ };
2611
+ }
2612
+ /**
2613
+ * Internal, for tests that bound memory: jobs whose outcome is not delivered yet, keys with an unpublished writer,
2614
+ * and record reads in flight in the cache. All three are 0 once the line is idle.
2615
+ */
2616
+ get lineSizes() {
2617
+ return {
2618
+ outstanding: this.#outstanding,
2619
+ unpublished: this.#writer.unpublished,
2620
+ reads: this.#cached?.readsInFlight ?? 0
2621
+ };
2622
+ }
2623
+ /** Note a use of a cached document: an unattached one becomes the newest idle one, and an eviction is scheduled. */
2624
+ #touchDocument(addressId) {
2625
+ const cached = this.#documents.get(addressId);
2626
+ if (cached === void 0 || this.#attachedDocuments.has(cached.record.id)) return;
2627
+ const now = this.#clock();
2628
+ const since = this.#idleDocuments.get(addressId);
2629
+ if (since !== void 0 && now - since < Math.min(1e3, this.#documentRetentionMs() / 10)) return;
2630
+ this.#idleDocuments.delete(addressId);
2631
+ this.#idleDocuments.set(addressId, now);
2632
+ if (this.#documentSweep === void 0 || this.#documentSweep.at > now + this.#documentRetentionMs()) this.#scheduleDocumentSweep();
2633
+ }
2634
+ #dropDocument(addressId) {
2635
+ this.#documents.delete(addressId);
2636
+ this.#idleDocuments.delete(addressId);
2637
+ }
2638
+ /**
2639
+ * Schedule the eviction of the oldest idle document: on the line at once when the retention is 0, otherwise when it
2640
+ * expires, by a background timer (`HarnessOptions.setTimer`), which never keeps the process alive. Where the host
2641
+ * declines it, as the default does in Cloudflare Workers, none is kept: the end of each commit evicts what expired.
2642
+ */
2643
+ #scheduleDocumentSweep() {
2644
+ if (this.#closing !== void 0) return;
2645
+ let oldest;
2646
+ for (const [addressId, since] of this.#idleDocuments) {
2647
+ if (this.#writer.gate(documentKey(addressId)) !== void 0) continue;
2648
+ oldest = since;
2649
+ break;
2650
+ }
2651
+ if (oldest === void 0) return;
2652
+ const at = oldest + this.#documentRetentionMs();
2653
+ if (this.#documentSweep !== void 0 && this.#documentSweep.at <= at) return;
2654
+ this.#documentSweep?.disarm?.();
2655
+ const sweep = {
2656
+ at,
2657
+ disarm: void 0
2658
+ };
2659
+ const run = () => {
2660
+ this.#sweepJobs++;
2661
+ this.#maintain(async () => {
2662
+ if (this.#documentSweep === sweep) this.#documentSweep = void 0;
2663
+ if (this.#closing === void 0) this.#sweepDocuments();
2664
+ }).catch(() => {});
2665
+ };
2666
+ const delay = at - this.#clock();
2667
+ this.#documentSweep = sweep;
2668
+ if (delay <= 0) {
2669
+ queueMicrotask(run);
2670
+ return;
2671
+ }
2672
+ if (this.#documentTimersUnavailable) {
2673
+ this.#documentSweep = void 0;
2674
+ return;
2675
+ }
2676
+ const disarm = this.#timers.background(run, delay);
2677
+ if (disarm === void 0) {
2678
+ this.#documentTimersUnavailable = true;
2679
+ this.#documentSweep = void 0;
2680
+ return;
2681
+ }
2682
+ sweep.disarm = disarm;
2683
+ }
2684
+ /** On the line: evict the idle documents whose retention passed, oldest first, then schedule the next eviction. */
2685
+ #sweepDocuments() {
2686
+ const expired = this.#clock() - this.#documentRetentionMs();
2687
+ for (const [addressId, since] of this.#idleDocuments) {
2688
+ if (since > expired) break;
2689
+ if (this.#writer.gate(documentKey(addressId)) !== void 0) continue;
2690
+ this.#dropDocument(addressId);
2691
+ }
2692
+ this.#scheduleDocumentSweep();
2693
+ }
2694
+ /** Pin a cached incarnation for one observer; the returned release unpins it once, idle again after the last. */
2695
+ #pinDocument(addressId, recordId) {
2696
+ this.#attachedDocuments.set(recordId, (this.#attachedDocuments.get(recordId) ?? 0) + 1);
2697
+ this.#idleDocuments.delete(addressId);
2698
+ let pinned = true;
2699
+ return () => {
2700
+ if (!pinned) return;
2701
+ pinned = false;
2702
+ const count = (this.#attachedDocuments.get(recordId) ?? 1) - 1;
2703
+ if (count > 0) {
2704
+ this.#attachedDocuments.set(recordId, count);
2705
+ return;
2706
+ }
2707
+ this.#attachedDocuments.delete(recordId);
2708
+ if (this.#documents.get(addressId)?.record.id === recordId) this.#touchDocument(addressId);
2709
+ };
2710
+ }
2711
+ async #runCommit(change, context, scope, withinMs, index) {
2712
+ this.#assertHealthy();
2713
+ context.abortSignal?.throwIfAborted();
2714
+ const tx = new Transaction(this.#host, context, scope);
2715
+ let result;
2716
+ try {
2717
+ result = await change(tx);
2718
+ this.#assertHealthy();
2719
+ } catch (error) {
2720
+ await tx.settleFailure();
2721
+ this.#sweepDocuments();
2722
+ throw error;
2723
+ }
2724
+ let writes;
2725
+ try {
2726
+ writes = await tx.settleSuccess();
2727
+ } catch (error) {
2728
+ this.#sweepDocuments();
2729
+ throw error;
2730
+ }
2731
+ if (writes.length === 0) {
2732
+ tx.discard();
2733
+ this.#sweepDocuments();
2734
+ return { value: result };
2735
+ }
2736
+ if (this.#readOnly) {
2737
+ tx.discard();
2738
+ this.#sweepDocuments();
2739
+ throw new ReadOnlySession("a commit with writes");
2740
+ }
2741
+ const discard = () => tx.discard();
2742
+ if (withinMs !== void 0) {
2743
+ const held = tx.holdable();
2744
+ if (held !== void 0) {
2745
+ const part = this.#writer.admit({
2746
+ index,
2747
+ writes: void 0,
2748
+ keys: tx.writeKeys(),
2749
+ context,
2750
+ publish: () => this.#hold(tx, held, withinMs, context),
2751
+ discard
2752
+ });
2753
+ this.#sweepDocuments();
2754
+ return {
2755
+ value: result,
2756
+ after: part.outcome
2757
+ };
2758
+ }
2759
+ }
2760
+ let membership = this.membershipKeys(tx);
2761
+ if (!Array.isArray(membership)) try {
2762
+ membership = await membership;
2763
+ } catch (error) {
2764
+ tx.discard();
2765
+ this.#sweepDocuments();
2766
+ throw error;
2767
+ }
2768
+ const taken = this.#holds.size === 0 ? NO_HOLDS : tx.takeHeld((id) => this.#holds.get(id));
2769
+ const keys = tx.writeKeys();
2770
+ for (const key of membership) keys.push(key);
2771
+ const part = this.#writer.admit({
2772
+ index,
2773
+ writes,
2774
+ keys,
2775
+ context,
2776
+ publish: (seq) => this.#adopt(tx, writes, taken, seq, context),
2777
+ discard
2778
+ });
2779
+ this.#sweepDocuments();
2780
+ return {
2781
+ value: result,
2782
+ after: part.outcome
2783
+ };
2784
+ }
2785
+ /**
2786
+ * Publish a stored commit (`Writer`), after the read caches took its writes: adopt it in memory and run its
2787
+ * publication. A throw of the adoption leaves memory behind durable state; the writer fails the Session with it.
2788
+ */
2789
+ #adopt(tx, writes, taken, seq, context) {
2790
+ let documents;
2791
+ try {
2792
+ documents = tx.adopt(seq);
2793
+ } catch (error) {
2794
+ return {
2795
+ kind: "adoption",
2796
+ error
2797
+ };
2798
+ }
2799
+ this.#indexTaskDocuments(tx, writes, documents, seq);
2800
+ const failure = this.#publish(seq, writes, documents, context);
2801
+ if (taken.length > 0) this.#release(taken);
2802
+ for (const document of documents.stored) this.#touchDocument(addressId(document.record));
2803
+ return failure === void 0 ? void 0 : {
2804
+ kind: "listener",
2805
+ error: failure.error
2806
+ };
2807
+ }
2808
+ /**
2809
+ * At publication: keep `#taskDocuments` in step with a stored commit: the tasks it creates start with no documents,
2810
+ * task documents it creates join their task, ones it retires leave, and tasks it ends leave the index.
2811
+ */
2812
+ #indexTaskDocuments(tx, writes, documents, seq) {
2813
+ for (const id of tx.createdTaskIds()) this.#taskDocuments.set(id, /* @__PURE__ */ new Map());
2814
+ if (this.#taskDocuments.size === 0) return;
2815
+ for (const change of documents.stored) {
2816
+ if (change.type !== "document" || change.record.scope.kind !== "task") continue;
2817
+ const known = this.#taskDocuments.get(change.record.scope.taskId);
2818
+ if (known === void 0) continue;
2819
+ if (change.kind === "retire") known.delete(change.record.id);
2820
+ else if (change.record.createdAt === seq) known.set(change.record.id, change.record);
2821
+ }
2822
+ for (const write of writes) if (write.type === "task" && write.value.state.status === "terminal") this.#taskDocuments.delete(write.value.id);
2823
+ }
2824
+ /**
2825
+ * Hold a deferred commit (`Transaction.holdable()`): adopt it in memory, queue its changes per document, pinned, by
2826
+ * the earliest deadline of the document's held commits, and show it to the Session's own observers.
2827
+ */
2828
+ #hold(tx, held, withinMs, context) {
2829
+ let documents;
2830
+ try {
2831
+ documents = tx.adoptHeld();
2832
+ } catch (error) {
2833
+ return {
2834
+ kind: "adoption",
2835
+ error
2836
+ };
2837
+ }
2838
+ const deadline = this.#clock() + withinMs;
2839
+ for (const { loaded, ops, base } of held) {
2840
+ const id = loaded.record.id;
2841
+ let hold = this.#holds.get(id);
2842
+ if (hold === void 0) {
2843
+ const unpin = this.#pinDocument(loaded.addressId, id);
2844
+ hold = {
2845
+ loaded,
2846
+ pending: new PendingOps(),
2847
+ base: false,
2848
+ deadline,
2849
+ unpin
2850
+ };
2851
+ this.#holds.set(id, hold);
2852
+ }
2853
+ hold.pending.push(ops);
2854
+ if (base) hold.base = true;
2855
+ if (deadline < hold.deadline) hold.deadline = deadline;
2856
+ }
2857
+ this.#armHoldTimer();
2858
+ const publication = {
2859
+ kind: "memory",
2860
+ changes: documents
2861
+ };
2862
+ let failure;
2863
+ for (const listener of [...this.#internalListeners]) try {
2864
+ listener(publication, context);
2865
+ } catch (error) {
2866
+ failure ??= {
2867
+ kind: "listener",
2868
+ error
2869
+ };
2870
+ }
2871
+ return failure;
2872
+ }
2873
+ /**
2874
+ * Store the held changes `select` returns in one storage transaction, through the writer, from a job on the line. A
2875
+ * barrier: they are selected once every commit admitted before is published. Memory already has them, so only
2876
+ * `observeCommits()` observers see it, published as the writer publishes it. A failure fails the Session, as every
2877
+ * Storage failure does.
2878
+ */
2879
+ async #storeHolds(select, context) {
2880
+ await this.#drained();
2881
+ const holds = select();
2882
+ if (holds.length === 0) return;
2883
+ const writes = [];
2884
+ const changes = [];
2885
+ const keys = [];
2886
+ for (const hold of holds) {
2887
+ const { record, tracker, valueVersion: version } = hold.loaded;
2888
+ const value = tracker.value;
2889
+ const stored = storeHeld(hold, NO_OPERATIONS, value, version);
2890
+ writes.push({
2891
+ type: "document.change",
2892
+ id: record.id,
2893
+ content: stored.content
2894
+ });
2895
+ keys.push(documentKey(hold.loaded.addressId), incarnationKey(record.id));
2896
+ const conversationId = record.scope.kind === "conversation" ? record.scope.conversationId : void 0;
2897
+ changes.push({
2898
+ type: "document",
2899
+ kind: "change",
2900
+ record,
2901
+ conversationId,
2902
+ version,
2903
+ value,
2904
+ ops: stored.ops
2905
+ });
2906
+ }
2907
+ const publish = (seq) => {
2908
+ for (const [index, hold] of holds.entries()) if (writes[index].content.kind === "base") hold.loaded.deltasSinceBase = 0;
2909
+ else hold.loaded.deltasSinceBase++;
2910
+ if (this.#commitListeners.size > 0) this.#notifyHosts({
2911
+ seq,
2912
+ changes
2913
+ }, context);
2914
+ this.#release(holds);
2915
+ };
2916
+ const index = this.#current.index;
2917
+ await this.#writer.admit({
2918
+ index,
2919
+ writes,
2920
+ keys,
2921
+ context,
2922
+ publish,
2923
+ discard: ignore
2924
+ }).outcome;
2925
+ }
2926
+ /** After their store: forget `holds`, unpin their documents, and move the timer to the next deadline. */
2927
+ #release(holds) {
2928
+ for (const hold of holds) {
2929
+ this.#holds.delete(hold.loaded.record.id);
2930
+ hold.unpin();
2931
+ }
2932
+ this.#armHoldTimer();
2933
+ }
2934
+ /**
2935
+ * Keep a foreground timer (Workers refuse background ones) for the earliest deadline of the held documents. When it
2936
+ * fires, every held document is stored, in one storage transaction: a deadline is the latest time, and the others
2937
+ * cost little more in the same transaction. Once fired, it stays until its job ran.
2938
+ */
2939
+ #armHoldTimer() {
2940
+ if (this.#closing !== void 0) return;
2941
+ let at = Infinity;
2942
+ for (const hold of this.#holds.values()) if (hold.deadline < at) at = hold.deadline;
2943
+ const armed = this.#holdTimer;
2944
+ if (armed !== void 0 && (armed.fired || armed.at === at)) return;
2945
+ armed?.disarm();
2946
+ this.#holdTimer = void 0;
2947
+ if (at === Infinity) return;
2948
+ const timer = {
2949
+ at,
2950
+ disarm: () => {},
2951
+ fired: false
2952
+ };
2953
+ const run = () => {
2954
+ timer.fired = true;
2955
+ this.#maintain(async () => {
2956
+ if (this.#holdTimer === timer) this.#holdTimer = void 0;
2957
+ if (this.#closing !== void 0 || this.#failure !== void 0) return;
2958
+ await this.#storeHolds(() => [...this.#holds.values()], BACKGROUND_CONTEXT);
2959
+ }).catch(() => {});
2960
+ };
2961
+ this.#holdTimer = timer;
2962
+ timer.disarm = this.#timers.foreground(run, Math.max(0, at - this.#clock()));
2963
+ }
2964
+ /**
2965
+ * At publication: publish a stored commit. Its telemetry events first, then the dispatch to `observeCommits()`
2966
+ * observers, queued before the waits and aborts the observers wake, then the Session's own observers. Never throws:
2967
+ * returns the first error of an own observer, which fails the Session once its storage call settled.
2968
+ */
2969
+ #publish(seq, writes, documents, context) {
2970
+ const changes = this.#commitListeners.size > 0 || this.#internalListeners.size > 0 ? [] : void 0;
2971
+ for (const write of writes) switch (write.type) {
2972
+ case "entry":
2973
+ this.#event("pi.durable.entry", {
2974
+ "entry.id": write.value.id,
2975
+ "entry.kind": write.value.kind
2976
+ }, context);
2977
+ changes?.push(write);
2978
+ break;
2979
+ case "submission":
2980
+ if (write.value.status === "done" || write.value.status === "unanswered") this.#event("pi.durable.submission", {
2981
+ "submission.id": write.value.id,
2982
+ status: write.value.status,
2983
+ "answer.entry_id": write.value.answer
2984
+ }, context);
2985
+ changes?.push(write);
2986
+ break;
2987
+ case "conversation":
2988
+ case "task": changes?.push(write);
2989
+ }
2990
+ if (changes === void 0) return void 0;
2991
+ const tables = changes.length;
2992
+ for (const document of documents.observed) changes.push(document);
2993
+ const observed = {
2994
+ kind: "stored",
2995
+ seq,
2996
+ changes
2997
+ };
2998
+ if (this.#commitListeners.size > 0) {
2999
+ const stored = documents.stored === documents.observed ? observed : {
3000
+ seq,
3001
+ changes: [...changes.slice(0, tables), ...documents.stored]
3002
+ };
3003
+ this.#notifyHosts(stored, context);
3004
+ }
3005
+ let failure;
3006
+ for (const listener of [...this.#internalListeners]) try {
3007
+ listener(observed, context);
3008
+ } catch (error) {
3009
+ failure ??= { error };
3010
+ }
3011
+ return failure;
3012
+ }
3013
+ /** At publication: record a commit's telemetry event. A throwing adapter is reported, as publication must not throw. */
3014
+ #event(name, attributes, context) {
3015
+ try {
3016
+ context.telemetry.addEvent(name, attributes);
3017
+ } catch (error) {
3018
+ this.report(error, TELEMETRY, context);
3019
+ }
3020
+ }
3021
+ /**
3022
+ * At publication: call the `observeCommits()` observers with `publication` one microtask from now, and, queued
3023
+ * before the Session's own observers run, before the waits they resolve and the aborts they queue. The observers are
3024
+ * those attached when it runs; their guards report a throw.
3025
+ */
3026
+ #notifyHosts(publication, context) {
3027
+ SETTLED.then(() => {
3028
+ for (const observer of [...this.#commitListeners]) observer.advance(publication, context);
3029
+ });
3030
+ }
3031
+ /**
3032
+ * On the line, as one job: load the document at `resolved` and `attach` to it, so the attachment sees every commit
3033
+ * after the value it starts from; `undefined` when absent. Cancelling `context` meanwhile rejects, after `cancel`
3034
+ * undid an attachment made.
3035
+ */
3036
+ async #attachDocument(definition, resolved, context, attach, cancel) {
3037
+ const signal = context.abortSignal;
3038
+ let cancelled = signal?.aborted ?? false;
3039
+ const markCancelled = () => {
3040
+ cancelled = true;
3041
+ };
3042
+ signal?.addEventListener("abort", markCancelled, { once: true });
3043
+ try {
3044
+ const attached = await this.#enqueue(async () => {
3045
+ this.#assertHealthy();
3046
+ if (cancelled) throw cancellationError(signal);
3047
+ const loaded = await this.#loadDocument(definition, resolved.id, resolved.address, context);
3048
+ if (cancelled) throw cancellationError(signal);
3049
+ return { value: loaded === void 0 ? void 0 : attach(loaded) };
3050
+ });
3051
+ if (attached === void 0) return void 0;
3052
+ if (cancelled) {
3053
+ cancel(attached);
3054
+ throw cancellationError(signal);
3055
+ }
3056
+ return attached;
3057
+ } finally {
3058
+ signal?.removeEventListener("abort", markCancelled);
3059
+ }
3060
+ }
3061
+ /**
3062
+ * Follow the address of the incarnation `loaded`, after checking the definition, with the observer `create` makes
3063
+ * from its value, the idempotent detach, and the report of a listener error; returns that observer. It gets each
3064
+ * committed change there, a retirement as a `retired` change with the last value it was given and no ops (a change
3065
+ * in the retiring commit is not published), and a later incarnation as a root replacement. When the commit makes the
3066
+ * owner task of a task document terminal, no later commit can change the address: after its changes the commit
3067
+ * subscription and the pin go, and `ownerEnded` tells the observer, which stays subscribed to the Session's close
3068
+ * until it ends (its detach drops that). `end` gets the Session's close. The current incarnation is pinned in the
3069
+ * cache. The detach runs before `end`; once it ran, nothing more of the commit underway reaches the observer or pins
3070
+ * anything for it. `create` and `ownerEnded` are module functions where they can be, so a watch keeps no closure of
3071
+ * its caller.
3072
+ */
3073
+ #observeDocument(definition, loaded, create, ownerEnded) {
3074
+ checkRecordScope(definition, loaded.record);
3075
+ checkRecordVersion(definition, loaded.record, loaded.storedVersion);
3076
+ const addressId = loaded.addressId;
3077
+ const address = loaded.record;
3078
+ let incarnation = loaded.record.id;
3079
+ let value = loaded.tracker.value;
3080
+ let version = loaded.valueVersion;
3081
+ let unpin = this.#pinDocument(addressId, incarnation);
3082
+ let unsubscribeCommit = () => {};
3083
+ let unsubscribeClose = () => {};
3084
+ let attached = true;
3085
+ const detach = () => {
3086
+ if (!attached) return;
3087
+ attached = false;
3088
+ unsubscribeCommit();
3089
+ unsubscribeClose();
3090
+ unpin();
3091
+ };
3092
+ const observer = create(loaded.tracker.value, detach, (error) => this.report(error));
3093
+ unsubscribeCommit = this.followCommits((publication, context) => {
3094
+ if (!attached) return;
3095
+ let ownerEnds = false;
3096
+ for (const change of publication.changes) {
3097
+ if (change.type === "task") {
3098
+ const scope = address.scope;
3099
+ if (scope.kind === "task" && change.value.id === scope.taskId && change.value.state.status === "terminal") ownerEnds = true;
3100
+ continue;
3101
+ }
3102
+ if (change.type !== "document") continue;
3103
+ if (change.record.id !== incarnation && !atAddress(change.record, address)) continue;
3104
+ if (change.kind === "retire") {
3105
+ if (change.record.id !== incarnation) continue;
3106
+ const last = value;
3107
+ incarnation = void 0;
3108
+ value = void 0;
3109
+ unpin();
3110
+ observer.advance({
3111
+ kind: "value",
3112
+ value: last,
3113
+ ops: NO_OPERATIONS,
3114
+ retired: true
3115
+ }, context);
3116
+ } else if (change.record.id !== incarnation || change.version !== version) {
3117
+ if (change.record.id !== incarnation) {
3118
+ incarnation = change.record.id;
3119
+ unpin();
3120
+ unpin = this.#pinDocument(addressId, incarnation);
3121
+ }
3122
+ version = change.version;
3123
+ value = change.value;
3124
+ observer.advance({
3125
+ kind: "value",
3126
+ value,
3127
+ ops: [["r", value]],
3128
+ retired: false
3129
+ }, context);
3130
+ } else {
3131
+ if (change.ops.length === 0) continue;
3132
+ value = change.value;
3133
+ observer.advance({
3134
+ kind: "value",
3135
+ value,
3136
+ ops: change.ops,
3137
+ retired: false
3138
+ }, context);
3139
+ }
3140
+ if (!attached) return;
3141
+ }
3142
+ if (!ownerEnds) return;
3143
+ unsubscribeCommit();
3144
+ unpin();
3145
+ ownerEnded(observer);
3146
+ });
3147
+ unsubscribeClose = this.subscribeClose(() => {
3148
+ detach();
3149
+ observer.end(closeEndOf(observer, closeEnds(this.#failure)));
3150
+ });
3151
+ return observer;
3152
+ }
3153
+ async #loadDocument(definition, addressId, address, context) {
3154
+ const gate = this.touch(documentKey(addressId));
3155
+ if (gate !== void 0) await gate;
3156
+ const cached = this.#documents.get(addressId);
3157
+ if (cached?.valueVersion === definition.version) {
3158
+ this.#touchDocument(addressId);
3159
+ return cached;
3160
+ }
3161
+ if (cached !== void 0) {
3162
+ const id = cached.record.id;
3163
+ await this.#storeHolds(() => {
3164
+ const hold = this.#holds.get(id);
3165
+ return hold === void 0 ? NO_HOLDS : [hold];
3166
+ }, context);
3167
+ this.#dropDocument(addressId);
3168
+ }
3169
+ const record = await this.#storage.findDocument(address, "current", context);
3170
+ if (record === void 0) return void 0;
3171
+ const stored = await this.#storage.document(record.id, "current", context);
3172
+ if (stored === void 0) throw new Error(`Current document ${record.id} (${record.kind}) cannot be read`);
3173
+ const value = materializeDocument(definition, stored);
3174
+ const loaded = {
3175
+ addressId,
3176
+ record: stored.record,
3177
+ storedVersion: stored.version,
3178
+ valueVersion: definition.version,
3179
+ deltasSinceBase: stored.deltasSinceBase,
3180
+ tracker: track(value)
3181
+ };
3182
+ this.#documents.set(addressId, loaded);
3183
+ this.#touchDocument(addressId);
3184
+ return loaded;
3185
+ }
3186
+ /**
3187
+ * Run `job` on the line, after the jobs before it, and deliver its outcome in line order: once the jobs before it
3188
+ * have theirs, and once its commit, if it admitted one, is published. With `exempt`, a job that admitted no commit and
3189
+ * waited at no gate is delivered as soon as it has its outcome: it is equivalent to having run before every
3190
+ * unpublished commit. A job
3191
+ * whose outcome comes after the one a failure is gets `SessionFailed` instead. At most `MAX_OUTSTANDING` jobs wait
3192
+ * for their delivery; beyond it the line waits.
3193
+ */
3194
+ #enqueue(work, exempt = false) {
3195
+ const job = {
3196
+ index: this.#nextIndex++,
3197
+ hit: false
3198
+ };
3199
+ const ran = this.#tail.then(async () => {
3200
+ while (this.#outstanding >= MAX_OUTSTANDING) {
3201
+ this.#room ??= Promise.withResolvers();
3202
+ await this.#room.promise;
3203
+ }
3204
+ this.#outstanding++;
3205
+ return this.#onLine(job, work);
3206
+ });
3207
+ this.#tail = ran.then(ignore, ignore);
3208
+ const outcome = ran.then((result) => {
3209
+ if (result.after === void 0) {
3210
+ this.#ended(job);
3211
+ return result.value;
3212
+ }
3213
+ return result.after.then(() => {
3214
+ this.#ended(job);
3215
+ return result.value;
3216
+ }, (error) => {
3217
+ this.#ended(job);
3218
+ throw error;
3219
+ });
3220
+ }, (error) => {
3221
+ this.#ended(job);
3222
+ throw error;
3223
+ });
3224
+ outcome.catch(ignore);
3225
+ const fence = this.#fence;
3226
+ this.#fence = fence.then(() => outcome).then(ignore, ignore);
3227
+ const index = job.index;
3228
+ const deliver = (fenced) => (fenced ? fence.then(() => outcome) : outcome).then((value) => {
3229
+ this.#delivered(index, fenced);
3230
+ if (this.#poisoned(index)) throw new SessionFailed(this.#failure.error);
3231
+ return value;
3232
+ }, (error) => {
3233
+ this.#delivered(index, fenced);
3234
+ throw this.#poisoned(index) ? new SessionFailed(this.#failure.error) : error;
3235
+ });
3236
+ return exempt ? ran.then((result) => deliver(job.hit || result.after !== void 0), () => deliver(job.hit)) : deliver(true);
3237
+ }
3238
+ /** Whether job `index` comes after the failure's boundary without an outcome of its own: it gets `SessionFailed`. */
3239
+ #poisoned(index) {
3240
+ return this.#failAt !== void 0 && index > this.#failAt && !this.#ownOutcomes.has(index);
3241
+ }
3242
+ /** The job's outcome settled: run what waited for it (`onJobEnd()`). */
3243
+ #ended(job) {
3244
+ const ends = job.ends;
3245
+ if (ends === void 0) return;
3246
+ job.ends = void 0;
3247
+ for (const end of ends) end();
3248
+ }
3249
+ /** Run a job of the Session's own upkeep on the line: no outcome to deliver, so no fence and no `SessionFailed`. */
3250
+ #maintain(work) {
3251
+ const job = {
3252
+ index: this.#nextIndex++,
3253
+ hit: false
3254
+ };
3255
+ const ran = this.#tail.then(() => this.#onLine(job, work));
3256
+ this.#tail = ran.then(ignore, ignore);
3257
+ return ran;
3258
+ }
3259
+ /** Hold the line for job `index` until its line part, through admission, is done. Gates are its touches' own. */
3260
+ async #onLine(job, work) {
3261
+ this.#current = job;
3262
+ try {
3263
+ return await work(job.index);
3264
+ } finally {
3265
+ this.#current = void 0;
3266
+ }
3267
+ }
3268
+ /** A `*` barrier: once every part admitted so far is published, or never will be. */
3269
+ async #drained() {
3270
+ const drained = this.#writer.drained();
3271
+ if (drained !== void 0) await drained;
3272
+ }
3273
+ /**
3274
+ * Run one commit's publication inside the Storage's own scope (`Storage.publishing`), such as a store host's batch;
3275
+ * directly without one. `undefined` when it ran at once, else settles once it ran. A Storage that throws instead of
3276
+ * running it is reported, and the publication runs directly: the commit is stored, so it must be published.
3277
+ */
3278
+ #publishing(publish, context) {
3279
+ const publishing = this.#storage.publishing;
3280
+ if (publishing === void 0) {
3281
+ publish();
3282
+ return;
3283
+ }
3284
+ const done = Promise.withResolvers();
3285
+ let ran = false;
3286
+ const once = () => {
3287
+ if (ran) return;
3288
+ ran = true;
3289
+ try {
3290
+ publish();
3291
+ } finally {
3292
+ done.resolve();
3293
+ }
3294
+ };
3295
+ try {
3296
+ publishing(once, context);
3297
+ } catch (error) {
3298
+ this.report(error, LISTENER, context);
3299
+ once();
3300
+ }
3301
+ return done.promise;
3302
+ }
3303
+ /** Job `index` has its outcome: let the line go on past `MAX_OUTSTANDING`. */
3304
+ #delivered(index, fenced) {
3305
+ if (fenced) this.#lastDelivered = index;
3306
+ this.#outstanding--;
3307
+ const room = this.#room;
3308
+ if (room !== void 0 && this.#outstanding < MAX_OUTSTANDING) {
3309
+ this.#room = void 0;
3310
+ room.resolve();
3311
+ }
3312
+ }
3313
+ /** Internal: throw `SessionFailed` when failed, else an error when closing. */
3314
+ assertUsable() {
3315
+ this.#assertHealthy();
3316
+ if (this.#closing !== void 0) throw new Error("Session is closed");
3317
+ }
3318
+ #assertHealthy() {
3319
+ if (this.#failure !== void 0) throw new SessionFailed(this.#failure.error);
3320
+ }
3321
+ };
3322
+ /**
3323
+ * Run a host callback that must not fail its caller: a throw, or a promise it returns that rejects, goes to `onError`,
3324
+ * which is not awaited.
3325
+ */
3326
+ function contained(callback, onError) {
3327
+ try {
3328
+ const result = callback();
3329
+ if (typeof result?.then === "function") Promise.resolve(result).catch(onError);
3330
+ } catch (error) {
3331
+ onError(error);
3332
+ }
3333
+ }
3334
+ /**
3335
+ * `observer`, a host's, behind the rule for observers that run at a commit's publication: one that throws, or whose
3336
+ * `advance` returns a promise that rejects, is reported through `report`, detached, and ended `listener_error`, so the
3337
+ * throw never reaches `adopt`; nothing reaches it after its detach or end, and from then on the guard references
3338
+ * neither it nor its source. `detach` is the source's; the returned `detach()` is the observation's.
3339
+ */
3340
+ function guardObserver(observer, detach, report) {
3341
+ let attached = {
3342
+ observer,
3343
+ detach,
3344
+ report
3345
+ };
3346
+ /** Detach from the source once, and hand back what it was attached with. */
3347
+ const release = () => {
3348
+ const released = attached;
3349
+ attached = void 0;
3350
+ released?.detach();
3351
+ return released;
3352
+ };
3353
+ /** Report a throw of `current`'s `advance`, then detach and end it, unless that happened meanwhile. */
3354
+ const fault = (current, error, context) => {
3355
+ current.report(error, context);
3356
+ if (release() !== void 0) {
3357
+ const end = {
3358
+ kind: "listener_error",
3359
+ error: toError(error)
3360
+ };
3361
+ contained(() => current.observer.end(end), current.report);
3362
+ }
3363
+ };
3364
+ return {
3365
+ advance: (call, context) => {
3366
+ const current = attached;
3367
+ if (current === void 0) return;
3368
+ try {
3369
+ const result = current.observer.advance(call, context);
3370
+ if (typeof result?.then === "function") Promise.resolve(result).catch((error) => fault(current, error, context));
3371
+ } catch (error) {
3372
+ fault(current, error, context);
3373
+ }
3374
+ },
3375
+ end: (end) => {
3376
+ const ending = release();
3377
+ if (ending !== void 0) contained(() => ending.observer.end(end), ending.report);
3378
+ },
3379
+ detach: () => {
3380
+ release();
3381
+ }
3382
+ };
3383
+ }
3384
+ /** A listener's throw as the `Error` a `listener_error` end carries, as Chord's watch makes it. */
3385
+ function toError(error) {
3386
+ if (error instanceof Error) return error;
3387
+ try {
3388
+ return new Error(String(error));
3389
+ } catch {
3390
+ return new Error(Object.prototype.toString.call(error));
3391
+ }
3392
+ }
3393
+ /** The end of an observer whose source closed. */
3394
+ const ENDED = { kind: "ended" };
3395
+ /**
3396
+ * How a Session's close ends what follows it (decision "Slice 8 S1"), made once per close: an app's watch `ended`; a
3397
+ * synchronous observer (an adapter following the Session, which may open it again) `failed` with "session closed", so
3398
+ * it follows the next Session; `ended` stays for an observed owner that ended (a task document's task). A failed
3399
+ * Session ends both `failed` with its error.
3400
+ */
3401
+ function closeEnds(failure) {
3402
+ if (failure !== void 0) {
3403
+ const failed = {
3404
+ kind: "failed",
3405
+ error: failure.error
3406
+ };
3407
+ return {
3408
+ watch: failed,
3409
+ observer: failed
3410
+ };
3411
+ }
3412
+ return {
3413
+ watch: ENDED,
3414
+ observer: {
3415
+ kind: "failed",
3416
+ error: /* @__PURE__ */ new Error("session closed")
3417
+ }
3418
+ };
3419
+ }
3420
+ /** The end `ends` give `follower`: a watch's, or an observer's. */
3421
+ function closeEndOf(follower, ends) {
3422
+ return follower instanceof Watch ? ends.watch : ends.observer;
3423
+ }
3424
+ /**
3425
+ * The `Observation` of a guarded observer attached at `value`. Built outside the attaching closure, so a detached
3426
+ * observation keeps nothing but `value` and the spent guard alive.
3427
+ */
3428
+ function observation(value, guarded) {
3429
+ return {
3430
+ value,
3431
+ detach: () => guarded.detach()
3432
+ };
3433
+ }
3434
+ /** A document watch over its source's detach and report. */
3435
+ function createWatch(value, detach, report) {
3436
+ return new Watch(value, detach, report);
3437
+ }
3438
+ /** Undo a watch attached while its acquisition was aborted. */
3439
+ function abortWatch(watch) {
3440
+ watch.abort();
3441
+ }
3442
+ /** Undo an observation attached while its attachment was cancelled. */
3443
+ function detachObservation(attached) {
3444
+ attached.detach();
3445
+ }
3446
+ /** A task document's watch delivers the retirement that ends its task, then ends. */
3447
+ function endWatch(watch) {
3448
+ watch.endAfterDelivery();
3449
+ }
3450
+ /** A task document's observer ends right after the retirement that ends its task. */
3451
+ function endGuarded(guarded) {
3452
+ guarded.end(ENDED);
3453
+ }
3454
+ /** Whether `record` is an incarnation at `address`. */
3455
+ function atAddress(record, address) {
3456
+ if (record.kind !== address.kind || record.key !== address.key) return false;
3457
+ switch (record.scope.kind) {
3458
+ case "session": return address.scope.kind === "session";
3459
+ case "conversation": return address.scope.kind === "conversation" && address.scope.conversationId === record.scope.conversationId;
3460
+ case "task": return address.scope.kind === "task" && address.scope.taskId === record.scope.taskId;
3461
+ }
3462
+ }
3463
+ function cancellationError(signal) {
3464
+ return signal.reason instanceof Error ? signal.reason : new DOMException("The operation was aborted", "AbortError");
3465
+ }
3466
+ /**
3467
+ * The Session's Storage behind its failure guard; every component of the Session reads and writes through it. Before a
3468
+ * call, a failed Session gets `SessionFailed` without reaching the backend. A call that throws fails the Session and
3469
+ * rethrows the backend's error, unless it is a `StorageRequestError` or a read whose caller's context was aborted:
3470
+ * neither says the Storage is broken.
3471
+ * `close()` always reaches the backend, so a failed Session still closes it.
3472
+ */
3473
+ var GuardedStorage = class {
3474
+ #storage;
3475
+ #latch;
3476
+ /** Backend calls underway, also those off the Session line, which close waits for before it closes the backend. */
3477
+ #underway = /* @__PURE__ */ new Set();
3478
+ #closing = false;
3479
+ constructor(storage, latch) {
3480
+ this.#storage = storage;
3481
+ this.#latch = latch;
3482
+ }
3483
+ /** The backend's own scope for a publication (`Storage.publishing`), when it has one; not a call to guard. */
3484
+ get publishing() {
3485
+ return scopeOf(this.#storage);
3486
+ }
3487
+ /**
3488
+ * Guarded like every call, but its outcome is the Session writer's to judge: it publishes the batches received first,
3489
+ * then fails the Session for a refusal or a rejection, and for a Session that failed meanwhile.
3490
+ */
3491
+ async commit(batches, receive, context) {
3492
+ this.#assertHealthy();
3493
+ if (this.#closing) throw new Error("Session is closed");
3494
+ const call = (async () => this.#storage.commit(batches, receive, context))();
3495
+ this.#underway.add(call);
3496
+ try {
3497
+ return await call;
3498
+ } finally {
3499
+ this.#underway.delete(call);
3500
+ }
3501
+ }
3502
+ mintId() {
3503
+ return this.#call(void 0, () => this.#storage.mintId());
3504
+ }
3505
+ conversation(id, context) {
3506
+ return this.#call(context, () => this.#storage.conversation(id, context));
3507
+ }
3508
+ scanConversations(query, limit, cursor, context) {
3509
+ return this.#call(context, () => this.#storage.scanConversations(query, limit, cursor, context));
3510
+ }
3511
+ entry(first, second, third) {
3512
+ if (third === void 0) {
3513
+ const context = second;
3514
+ return this.#call(context, () => this.#storage.entry(first, context));
3515
+ }
3516
+ return this.#call(third, () => this.#storage.entry(first, second, third));
3517
+ }
3518
+ findLatestHeadMarker(conversationId, atOrBeforeEntryId, context) {
3519
+ return this.#call(context, () => this.#storage.findLatestHeadMarker(conversationId, atOrBeforeEntryId, context));
3520
+ }
3521
+ scanEntries(query, limit, cursor, context) {
3522
+ return this.#call(context, () => this.#storage.scanEntries(query, limit, cursor, context));
3523
+ }
3524
+ task(id, context) {
3525
+ return this.#call(context, () => this.#storage.task(id, context));
3526
+ }
3527
+ scanTasks(query, limit, cursor, context) {
3528
+ return this.#call(context, () => this.#storage.scanTasks(query, limit, cursor, context));
3529
+ }
3530
+ submission(id, context) {
3531
+ return this.#call(context, () => this.#storage.submission(id, context));
3532
+ }
3533
+ scanSubmissions(query, limit, cursor, context) {
3534
+ return this.#call(context, () => this.#storage.scanSubmissions(query, limit, cursor, context));
3535
+ }
3536
+ submissionByRequest(conversationId, requestId, context) {
3537
+ return this.#call(context, () => this.#storage.submissionByRequest(conversationId, requestId, context));
3538
+ }
3539
+ findDocument(address, at, context) {
3540
+ return this.#call(context, () => this.#storage.findDocument(address, at, context));
3541
+ }
3542
+ document(id, at, context) {
3543
+ return this.#call(context, () => this.#storage.document(id, at, context));
3544
+ }
3545
+ scanDocuments(query, limit, cursor, context) {
3546
+ return this.#call(context, () => this.#storage.scanDocuments(query, limit, cursor, context));
3547
+ }
3548
+ /**
3549
+ * Close the backend once every call underway has settled, so none outlives it or fails after `closed` settles. New
3550
+ * calls are refused from here on: a paged read must not start its next page while the backend closes.
3551
+ */
3552
+ async close(context) {
3553
+ this.#closing = true;
3554
+ await Promise.allSettled([...this.#underway]);
3555
+ return this.#storage.close(context);
3556
+ }
3557
+ /**
3558
+ * Run one backend call under the guard. `read` is a read's context; `commit()` and `mintId()` pass none, so nothing
3559
+ * exempts their errors: once a batch is admitted, whether it committed is unknown. A call still underway when another
3560
+ * fails the Session ends with `SessionFailed` too, whatever it returns: nothing it read or wrote is used.
3561
+ */
3562
+ async #call(read, run) {
3563
+ this.#assertHealthy();
3564
+ if (this.#closing) throw new Error("Session is closed");
3565
+ let result;
3566
+ const call = (async () => run())();
3567
+ this.#underway.add(call);
3568
+ try {
3569
+ result = await call;
3570
+ } catch (error) {
3571
+ this.#assertHealthy();
3572
+ if (!(read !== void 0 && (error instanceof StorageRequestError || read.abortSignal?.aborted === true))) this.#latch.fail(error);
3573
+ throw error;
3574
+ } finally {
3575
+ this.#underway.delete(call);
3576
+ }
3577
+ this.#assertHealthy();
3578
+ return result;
3579
+ }
3580
+ #assertHealthy() {
3581
+ const failure = this.#latch.failure;
3582
+ if (failure !== void 0) throw new SessionFailed(failure.error);
3583
+ }
3584
+ };
3585
+ //#endregion
3586
+ //#region ../../../node_modules/.pnpm/@earendil-works+pi-durable@1.5.2_patch_hash=0f5e595daa4c370af407284d99d6dba48a9e21f56aa_abe77735ae11ff0752ddae934766aeb6/node_modules/@earendil-works/pi-durable/dist/harness/agent.js
3587
+ const DEFAULT_RETRY_POLICY = {
3588
+ enabled: true,
3589
+ maxRetries: 3,
3590
+ baseDelayMs: 2e3,
3591
+ maxAgentDelayMs: 6e4
3592
+ };
3593
+ const DEFAULT_COMPACTION_POLICY = {
3594
+ enabled: true,
3595
+ reserveTokens: 16384,
3596
+ keepRecentTokens: 2e4,
3597
+ backgroundTokens: 32768
3598
+ };
3599
+ const DEFAULT_PROGRESS_POLICY = {
3600
+ partialIntervalMs: 100,
3601
+ outputIntervalMs: 100,
3602
+ persistWithinMs: 1e3
3603
+ };
3604
+ /** The reserved section key of the agent's `instructions`. */
3605
+ const INSTRUCTIONS_KEY = "instructions";
3606
+ /** Built-in agent document; rewindable so forks start from the agent at their fork entry. */
3607
+ const AgentDoc = defineDoc({
3608
+ kind: "pi.agent",
3609
+ version: 1,
3610
+ scope: "conversation",
3611
+ history: "rewindable",
3612
+ fork: "asOf",
3613
+ initial: () => ({}),
3614
+ checkpointWhen: () => true
3615
+ });
3616
+ /** Default `settings.contextRetentionMs`: ten minutes. */
3617
+ const DEFAULT_CONTEXT_RETENTION_MS = 6e5;
3618
+ /** A restart limit as given when it is a number of restarts, `1` or more, rounded down (`Infinity`: no task ends for restarts); else the default. */
3619
+ function restartLimit(limit) {
3620
+ return typeof limit === "number" && limit >= 1 ? Math.floor(limit) : 5;
3621
+ }
3622
+ /** Resolve the host settings: every field over its built-in default, object fields merged. */
3623
+ function resolveSettings(settings) {
3624
+ const extensions = settings?.extensions;
3625
+ return {
3626
+ ...extensions === void 0 ? {} : { extensions },
3627
+ stream: { ...settings?.stream },
3628
+ retry: {
3629
+ ...DEFAULT_RETRY_POLICY,
3630
+ ...settings?.retry
3631
+ },
3632
+ compaction: {
3633
+ ...DEFAULT_COMPACTION_POLICY,
3634
+ ...settings?.compaction
3635
+ },
3636
+ progress: {
3637
+ partialIntervalMs: settings?.progress?.partialIntervalMs ?? DEFAULT_PROGRESS_POLICY.partialIntervalMs,
3638
+ outputIntervalMs: settings?.progress?.outputIntervalMs ?? DEFAULT_PROGRESS_POLICY.outputIntervalMs,
3639
+ persistWithinMs: persistWithin(settings?.progress?.persistWithinMs)
3640
+ },
3641
+ toolExecution: settings?.toolExecution ?? "parallel",
3642
+ steeringMode: settings?.steeringMode ?? "one-at-a-time",
3643
+ followUpMode: settings?.followUpMode ?? "one-at-a-time",
3644
+ contextRetentionMs: settings?.contextRetentionMs ?? DEFAULT_CONTEXT_RETENTION_MS,
3645
+ documentRetentionMs: documentRetention(settings?.documentRetentionMs),
3646
+ afterFailedRun: settings?.afterFailedRun ?? "keep",
3647
+ restartLimit: restartLimit(settings?.restartLimit)
3648
+ };
3649
+ }
3650
+ /** Apply one change to `pi.agent`: a given field replaces the stored one, `null` clears it, `undefined` changes nothing. */
3651
+ async function configure(tx, conversationId, change) {
3652
+ applyChange(await tx.doc(AgentDoc, conversationId), change);
3653
+ }
3654
+ /**
3655
+ * `addTools` of a tool round, applied to `tools` and `modelTools`, so the next request offers the tools: an array gets
3656
+ * each name it lacks appended, and `{ remove }` loses the names. An unset `tools` already enables every tool, so nothing
3657
+ * is written for it. An unset or object `modelTools` also gets each name appended to its `add`, which loads deferred
3658
+ * tools and has no effect for others. By name, without the registry: a tool that is not registered now, such as one of
3659
+ * an MCP server that is reconnecting, is offered once it is again.
3660
+ */
3661
+ async function addTools(tx, conversationId, added) {
3662
+ const state = await tx.doc(AgentDoc, conversationId);
3663
+ const tools = state.tools;
3664
+ if (Array.isArray(tools)) {
3665
+ for (const name of added) if (!tools.includes(name)) tools.push(name);
3666
+ } else if (tools?.remove.some((name) => added.includes(name))) state.tools = { remove: tools.remove.filter((name) => !added.includes(name)) };
3667
+ const modelTools = state.modelTools;
3668
+ if (Array.isArray(modelTools)) {
3669
+ for (const name of added) if (!modelTools.includes(name)) modelTools.push(name);
3670
+ return;
3671
+ }
3672
+ const remove = (modelTools?.remove ?? []).filter((name) => !added.includes(name));
3673
+ const add = [...modelTools?.add ?? []];
3674
+ for (const name of added) if (!add.includes(name)) add.push(name);
3675
+ state.modelTools = {
3676
+ ...remove.length === 0 ? {} : { remove },
3677
+ add
3678
+ };
3679
+ }
3680
+ function applyChange(state, change) {
3681
+ const set = (key, value) => {
3682
+ if (value === void 0) return;
3683
+ if (value === null) delete state[key];
3684
+ else state[key] = value;
3685
+ };
3686
+ set("model", change.model === void 0 || change.model === null ? change.model : { ...change.model });
3687
+ set("thinkingLevel", change.thinkingLevel);
3688
+ const extensions = change.extensions;
3689
+ set("extensions", extensions === void 0 || extensions === null ? extensions : isList(extensions) ? names(extensions) : {
3690
+ ...extensions.add === void 0 ? {} : { add: names(extensions.add) },
3691
+ ...extensions.remove === void 0 ? {} : { remove: names(extensions.remove) }
3692
+ });
3693
+ const tools = change.tools;
3694
+ set("tools", tools === void 0 || tools === null ? tools : isList(tools) ? names(tools) : { remove: names(tools.remove) });
3695
+ const modelTools = change.modelTools;
3696
+ set("modelTools", modelTools === void 0 || modelTools === null ? modelTools : isList(modelTools) ? names(modelTools) : {
3697
+ ...modelTools.remove === void 0 ? {} : { remove: names(modelTools.remove) },
3698
+ ...modelTools.add === void 0 ? {} : { add: names(modelTools.add) }
3699
+ });
3700
+ set("instructions", change.instructions);
3701
+ set("cwd", change.cwd);
3702
+ const maxTurns = change.maxTurns;
3703
+ if (maxTurns !== void 0 && maxTurns !== null && !(Number.isSafeInteger(maxTurns) && maxTurns >= 1)) throw new RangeError(`maxTurns must be an integer 1 or more, got ${String(maxTurns)}`);
3704
+ set("maxTurns", maxTurns);
3705
+ const compaction = change.compaction;
3706
+ set("compaction", compaction === void 0 || compaction === null ? compaction : compactionSettings(compaction));
3707
+ }
3708
+ /** A stored copy of a conversation's compaction settings, without undefined fields. */
3709
+ function compactionSettings(settings) {
3710
+ const { modelOverrides, ...policy } = settings;
3711
+ if (modelOverrides === void 0) return compactionFields(policy);
3712
+ const overrides = Object.entries(modelOverrides).map(([key, override]) => [key, compactionFields(override)]);
3713
+ return {
3714
+ ...compactionFields(policy),
3715
+ modelOverrides: Object.fromEntries(overrides)
3716
+ };
3717
+ }
3718
+ const TOKEN_FIELDS = [
3719
+ "reserveTokens",
3720
+ "keepRecentTokens",
3721
+ "backgroundTokens"
3722
+ ];
3723
+ /** The set fields of `policy`; throws a `RangeError` for a token count that is not an integer `0` or more. */
3724
+ function compactionFields(policy) {
3725
+ const fields = policy.enabled === void 0 ? {} : { enabled: policy.enabled };
3726
+ for (const key of TOKEN_FIELDS) {
3727
+ const value = policy[key];
3728
+ if (value === void 0) continue;
3729
+ if (!(Number.isSafeInteger(value) && value >= 0)) throw new RangeError(`compaction.${key} must be an integer 0 or more, got ${String(value)}`);
3730
+ fields[key] = value;
3731
+ }
3732
+ return fields;
3733
+ }
3734
+ function isList(value) {
3735
+ return Array.isArray(value);
3736
+ }
3737
+ function names(items) {
3738
+ return items.map((item) => item.name);
3739
+ }
3740
+ /**
3741
+ * Built-in part of every Harness commit that creates or forks a conversation, for `pi.agent`: a fork keeps its `asOf`
3742
+ * copy; a new task-owned conversation copies the stored agent of its owner task's conversation; a new ownerless one
3743
+ * starts empty.
3744
+ */
3745
+ async function createAgent(tx, conversation) {
3746
+ if (conversation.parent !== void 0) return;
3747
+ const agent = await tx.doc(AgentDoc, conversation.id);
3748
+ if (conversation.owner === void 0) return;
3749
+ const owner = await tx.doc(AgentDoc, conversation.owner.conversationId);
3750
+ Object.assign(agent, copyJson(owner));
3751
+ }
3752
+ /** Handlers of the selected extensions' hooks for a task name, in extension order. */
3753
+ function agentHooks(agent, taskName) {
3754
+ const handlers = [];
3755
+ for (const extension of agent.extensions) for (const hook of extension.hooks ?? []) if (hook.task === taskName) handlers.push({
3756
+ extension: extension.name,
3757
+ handlers: hook.handlers
3758
+ });
3759
+ return handlers;
3760
+ }
3761
+ /** The extension whose code a section of `agent` runs: the last selected one that provides or wraps it. */
3762
+ function sectionExtension(agent, key) {
3763
+ let found;
3764
+ for (const extension of agent.extensions) {
3765
+ const provides = extension.sections?.some((section) => section.key === key) === true;
3766
+ const wraps = extension.wraps?.some((wrap) => "section" in wrap && wrap.section === key) === true;
3767
+ if (provides || wraps) found = extension.name;
3768
+ }
3769
+ return found;
3770
+ }
3771
+ /** The extension whose code a tool of `agent` runs: the last selected one that provides or wraps it. */
3772
+ function toolExtension(agent, name) {
3773
+ let found;
3774
+ for (const extension of agent.extensions) {
3775
+ const provides = extension.tools?.some((tool) => tool.name === name) === true;
3776
+ const wraps = extension.wraps?.some((wrap) => "tool" in wrap && wrap.tool === name) === true;
3777
+ if (provides || wraps) found = extension.name;
3778
+ }
3779
+ return found;
3780
+ }
3781
+ /**
3782
+ * Resolve an agent from its stored state (absent: every field unset), a registry snapshot, and resolved settings. A
3783
+ * wrapper that throws or renames drops its target and is reported; a wrapper without a target does nothing.
3784
+ */
3785
+ function resolveAgent(state, snapshot, settings, report) {
3786
+ const extensions = selectExtensions(state?.extensions, snapshot, settings);
3787
+ const composed = /* @__PURE__ */ new Map();
3788
+ for (const extension of extensions) for (const tool of extension.tools ?? []) composed.set(tool.name, tool);
3789
+ const sections = /* @__PURE__ */ new Map();
3790
+ for (const extension of extensions) for (const section of extension.sections ?? []) sections.set(section.key, section);
3791
+ for (const extension of extensions) for (const wrap of extension.wraps ?? []) {
3792
+ const wrapReport = (error) => report(error, extension.name);
3793
+ if ("tool" in wrap) applyWrap(composed, wrap.tool, (tool) => wrap.wrap(tool), (tool) => tool.name, wrapReport);
3794
+ else applyWrap(sections, wrap.section, (section) => wrap.wrap(section), (section) => section.key, wrapReport);
3795
+ }
3796
+ const enabled = filterTools([...composed.values()], state?.tools);
3797
+ const callableBy = (caller) => (tool) => tool.callers === void 0 || tool.callers.includes(caller);
3798
+ const modelCallable = enabled.filter(callableBy("model"));
3799
+ const tools = offeredTools(modelCallable, state?.modelTools);
3800
+ const offered = new Set(tools);
3801
+ const deferred = modelCallable.filter((tool) => tool.deferred === true && !offered.has(tool));
3802
+ const callable = enabled.filter(callableBy("tools"));
3803
+ const instructions = state?.instructions;
3804
+ const agentSections = [...sections.values()];
3805
+ if (instructions !== void 0) agentSections.push({
3806
+ key: INSTRUCTIONS_KEY,
3807
+ render: () => instructions
3808
+ });
3809
+ return {
3810
+ ...state?.model === void 0 ? {} : { model: state.model },
3811
+ thinkingLevel: state?.thinkingLevel ?? "off",
3812
+ extensions,
3813
+ tools,
3814
+ callable,
3815
+ deferred,
3816
+ sections: agentSections,
3817
+ ...instructions === void 0 ? {} : { instructions },
3818
+ ...state?.cwd === void 0 ? {} : { cwd: state.cwd },
3819
+ ...state?.maxTurns === void 0 ? {} : { maxTurns: state.maxTurns },
3820
+ ...state?.compaction === void 0 ? {} : { compaction: state.compaction }
3821
+ };
3822
+ }
3823
+ /** The tools offered to the model, as `AgentState.modelTools` describes. */
3824
+ function offeredTools(tools, filter) {
3825
+ if (Array.isArray(filter)) return filterTools(tools, filter);
3826
+ const removed = new Set(filter?.remove ?? []);
3827
+ const kept = tools.filter((tool) => tool.deferred !== true && !removed.has(tool.name));
3828
+ const byName = new Map(tools.map((tool) => [tool.name, tool]));
3829
+ const loaded = [...new Set(filter?.add ?? [])].flatMap((name) => {
3830
+ const tool = byName.get(name);
3831
+ return tool?.deferred === true && !removed.has(name) ? [tool] : [];
3832
+ });
3833
+ return [...kept, ...loaded];
3834
+ }
3835
+ /** `tools` through a stored filter: an array selects exactly its names, in its order; `{ remove }` drops names. */
3836
+ function filterTools(tools, filter) {
3837
+ if (filter === void 0) return tools;
3838
+ if (Array.isArray(filter)) {
3839
+ const byName = new Map(tools.map((tool) => [tool.name, tool]));
3840
+ return [...new Set(filter)].flatMap((name) => {
3841
+ const tool = byName.get(name);
3842
+ return tool === void 0 ? [] : [tool];
3843
+ });
3844
+ }
3845
+ const removed = new Set(filter.remove);
3846
+ return tools.filter((tool) => !removed.has(tool.name));
3847
+ }
3848
+ /** Selected installed extensions: the stored array, or the default selection edited by `{ add, remove }`. */
3849
+ function selectExtensions(stored, snapshot, settings) {
3850
+ let selected;
3851
+ if (Array.isArray(stored)) selected = stored;
3852
+ else {
3853
+ const base = settings.extensions?.map((extension) => extension.name) ?? snapshot.installed().map((e) => e.name);
3854
+ const edit = stored;
3855
+ const removed = new Set(edit?.remove ?? []);
3856
+ selected = [...base, ...edit?.add ?? []].filter((name) => !removed.has(name));
3857
+ }
3858
+ const extensions = [];
3859
+ for (const name of new Set(selected)) {
3860
+ const extension = snapshot.extension(name);
3861
+ if (extension !== void 0) extensions.push(extension);
3862
+ }
3863
+ return extensions;
3864
+ }
3865
+ function applyWrap(items, target, wrap, nameOf, report) {
3866
+ const item = items.get(target);
3867
+ if (item === void 0) return;
3868
+ try {
3869
+ const wrapped = wrap(item);
3870
+ if (nameOf(wrapped) !== target) throw new Error(`Wrapper renamed ${target} to ${nameOf(wrapped)}`);
3871
+ items.set(target, wrapped);
3872
+ } catch (error) {
3873
+ items.delete(target);
3874
+ report(error);
3875
+ }
3876
+ }
3877
+ //#endregion
3878
+ export { StorageRequestError as A, taskKey as C, ReadAfterWrite as D, ConversationIdle as E, ReadOnlySession as O, ownedKey as S, ConversationBusy as T, guardObserver as _, agentHooks as a, ROOTS_KEY as b, resolveAgent as c, toolExtension as d, SessionImpl as f, createSession as g, contained as h, addTools as i, errorMessage as j, SessionFailed as k, resolveSettings as l, closeEnds as m, DEFAULT_COMPACTION_POLICY as n, configure as o, closeEndOf as p, INSTRUCTIONS_KEY as r, createAgent as s, AgentDoc as t, sectionExtension as u, observation as v, hostTimers as w, conversationKey as x, INTENT_KEY as y };