@agimon-ai/po-cloudflare 0.0.2-alpha.2 → 0.0.2-alpha.21

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 (283) hide show
  1. package/README.md +4 -3
  2. package/dist/abort-signals-2GUraIGq.js +34 -0
  3. package/dist/agent-DZ-OKOHn.js +6850 -0
  4. package/dist/anthropic-messages-5ODquUB-.js +14317 -0
  5. package/dist/{apiContracts-CHOiCbS_.js → apiContracts-b33nSAAI.js} +18 -81
  6. package/dist/{approval-BMXqnTYd.js → approval-r3NnI1VC.js} +19 -3
  7. package/dist/{approvalPrompt-Bg1JrEEY.js → approvalPrompt-DWoXxu3S.js} +2 -2
  8. package/dist/artifactFiles-DLCReI0-.js +1 -0
  9. package/dist/assets/assets/{CodeEditorView-BnyZHaYM.js → CodeEditorView-XeNS0L9M.js} +2 -2
  10. package/dist/assets/assets/{abnfDiagram-WEYOIA3C-muME0eCj.js → abnfDiagram-WEYOIA3C-B6ZW0nkR.js} +2 -2
  11. package/dist/assets/assets/{architecture-WOLXFQ4H-DMnhK1WH.js → architecture-WOLXFQ4H-bVR64sHO.js} +1 -1
  12. package/dist/assets/assets/{architectureDiagram-ZHVYKT53-DKn7XGP7.js → architectureDiagram-ZHVYKT53-D7tZz3io.js} +2 -2
  13. package/dist/assets/assets/{blockDiagram-RJAE7QA3-DtDctXZg.js → blockDiagram-RJAE7QA3-DdwScfiX.js} +2 -2
  14. package/dist/assets/assets/{c4Diagram-XDPPPE54-23pGLJeP.js → c4Diagram-XDPPPE54-DgSxZJCV.js} +2 -2
  15. package/dist/assets/assets/channel-TPcVvp_3.js +2 -0
  16. package/dist/assets/assets/{chunk-2E7WHVMD-BZ2nGNPa.js → chunk-2E7WHVMD-D5TXC2SM.js} +2 -2
  17. package/dist/assets/assets/{chunk-4EMNKR2T-Dui1SYFi.js → chunk-4EMNKR2T-BWhOSvo1.js} +2 -2
  18. package/dist/assets/assets/{chunk-55XCU76K-CUB92Evl.js → chunk-55XCU76K-HkkBzLtZ.js} +2 -2
  19. package/dist/assets/assets/{chunk-7S6XSTFO-CVayPHfE.js → chunk-7S6XSTFO-CBnjycLU.js} +2 -2
  20. package/dist/assets/assets/{chunk-AQDTSKZB---wakYqY.js → chunk-AQDTSKZB-75lIIq8T.js} +2 -2
  21. package/dist/assets/assets/{chunk-DSNLSHJZ-DfbdohUR.js → chunk-DSNLSHJZ-D8PpnXMk.js} +2 -2
  22. package/dist/assets/assets/{chunk-HAGFOTED-Dr4KRh-b.js → chunk-HAGFOTED-CXRS2NIN.js} +2 -2
  23. package/dist/assets/assets/{chunk-HNE4Q36P-D06cR91Z.js → chunk-HNE4Q36P-BocUqS94.js} +2 -2
  24. package/dist/assets/assets/{chunk-NQOKRVIF-Ca4gLeDb.js → chunk-NQOKRVIF-CHf_ogYT.js} +2 -2
  25. package/dist/assets/assets/{chunk-UHW7PFBP-DmL638jN.js → chunk-UHW7PFBP-DrW1PaIv.js} +2 -2
  26. package/dist/assets/assets/{chunk-VQ5W62QI-pkxSW5Zj.js → chunk-VQ5W62QI-CLoA7bFm.js} +2 -2
  27. package/dist/assets/assets/{chunk-WQQL4CDK-Dcc8hV4U.js → chunk-WQQL4CDK-BmBsrj9I.js} +2 -2
  28. package/dist/assets/assets/chunk-XXDRQBXY-iFE4Tl8c.js +2 -0
  29. package/dist/assets/assets/{chunk-YZO67HFG-B_HKcFrw.js → chunk-YZO67HFG-DShE_cgv.js} +2 -2
  30. package/dist/assets/assets/{chunk-ZAUX2LTX-DAzZUysS.js → chunk-ZAUX2LTX-B3oLvSXy.js} +2 -2
  31. package/dist/assets/assets/{chunk-ZCHMQSOR-DAVgjymL.js → chunk-ZCHMQSOR-B14vKK7C.js} +2 -2
  32. package/dist/assets/assets/{classDiagram-v2-4MYWR3UA-Fsw8TGPu.js → classDiagram-v2-4MYWR3UA-Da8elIW2.js} +2 -2
  33. package/dist/assets/assets/{cose-bilkent-JH36ORCC-CgUbISYV.js → cose-bilkent-JH36ORCC-Du4tGtiJ.js} +2 -2
  34. package/dist/assets/assets/{cynefin-EF2NZ3EQ-D1LxAU2x.js → cynefin-EF2NZ3EQ-Cyj6i_WI.js} +1 -1
  35. package/dist/assets/assets/{cynefinDiagram-WF24UDRP-D54I1jil.js → cynefinDiagram-WF24UDRP-DFWXwO7A.js} +2 -2
  36. package/dist/assets/assets/{dagre-NK4GIZVX-DC7zL16U.js → dagre-NK4GIZVX-C1wB_cf-.js} +2 -2
  37. package/dist/assets/assets/{diagram-CBK3MWTC-DB0ptUdz.js → diagram-CBK3MWTC-MYCOBYl6.js} +2 -2
  38. package/dist/assets/assets/{diagram-I5XIIV2D-CozSftPJ.js → diagram-I5XIIV2D-BFYbKUFf.js} +2 -2
  39. package/dist/assets/assets/{diagram-ODIL2UCW-g3WOEWDS.js → diagram-ODIL2UCW-6siqTpv_.js} +2 -2
  40. package/dist/assets/assets/{diagram-PFBEJUXE-CFxGeOYi.js → diagram-PFBEJUXE-CaBr9CoB.js} +2 -2
  41. package/dist/assets/assets/{diagram-RJA3I4VV-BQBsLche.js → diagram-RJA3I4VV-DAvmuDpc.js} +2 -2
  42. package/dist/assets/assets/{diagram-TYUNFSNR-DrjpW2yq.js → diagram-TYUNFSNR-CJnhgCpo.js} +2 -2
  43. package/dist/assets/assets/{dist-DjL8d1jZ.js → dist-BQ4W1R18.js} +2 -2
  44. package/dist/assets/assets/{dist-DvgCCshF.js → dist-BnzFckPF.js} +2 -2
  45. package/dist/assets/assets/{dist-gfbb4ygy.js → dist-CFtBpcYL.js} +2 -2
  46. package/dist/assets/assets/{dist-BabjcJ3j.js → dist-CIQX1z4W.js} +2 -2
  47. package/dist/assets/assets/{dist-XIZum9n5.js → dist-ChHYoe9_.js} +2 -2
  48. package/dist/assets/assets/{dist-1-mhYUBH.js → dist-DKxZO8d9.js} +2 -2
  49. package/dist/assets/assets/{dist-h6SOnP8-.js → dist-DL6z28wl.js} +2 -2
  50. package/dist/assets/assets/{dist-B3JXhDWV.js → dist-DNyn1p9Z.js} +2 -2
  51. package/dist/assets/assets/{dist-Izr2SB3q.js → dist-qYlLXIa8.js} +2 -2
  52. package/dist/assets/assets/{ebnfDiagram-V4P3TTPT-BZS_aAve.js → ebnfDiagram-V4P3TTPT-AUcqDTM3.js} +2 -2
  53. package/dist/assets/assets/{elk-QONTBCTQ-B2ksVmMA.js → elk-QONTBCTQ-aA10PEHJ.js} +2 -2
  54. package/dist/assets/assets/{erDiagram-KYQIGQAA-7P6zF-Z-.js → erDiagram-KYQIGQAA-hhYiqA-x.js} +2 -2
  55. package/dist/assets/assets/{eventmodeling-K75KTNOO-RoGQoRq-.js → eventmodeling-K75KTNOO-BQZqbRo5.js} +1 -1
  56. package/dist/assets/assets/flowDiagram-IUGLLWBU-BuyysPYC.js +1 -0
  57. package/dist/assets/assets/{ganttDiagram-R7GPNTJY-CTOlRy7M.js → ganttDiagram-R7GPNTJY-CLON1GpW.js} +2 -2
  58. package/dist/assets/assets/{gitGraph-VSP46ZUC-CPqytIt0.js → gitGraph-VSP46ZUC-DbmvNwR2.js} +1 -1
  59. package/dist/assets/assets/{gitGraphDiagram-PDYL7XHY-BffLxuxg.js → gitGraphDiagram-PDYL7XHY-DJVO0WlL.js} +2 -2
  60. package/dist/assets/assets/index-BiTVAj5E.js +155 -0
  61. package/dist/assets/assets/index-CBNQEGK3.css +1 -0
  62. package/dist/assets/assets/{info-OHQRW6UA-BI8RK0Ow.js → info-OHQRW6UA-CAt3Nt3g.js} +1 -1
  63. package/dist/assets/assets/{infoDiagram-MVDRKAX5-DUIst1FB.js → infoDiagram-MVDRKAX5-DTuqH-Zb.js} +2 -2
  64. package/dist/assets/assets/{ishikawaDiagram-HPEHV2GE-CA17Eho5.js → ishikawaDiagram-HPEHV2GE-BnWvdonT.js} +2 -2
  65. package/dist/assets/assets/{journeyDiagram-BOSHW7O7-CNri5Ap9.js → journeyDiagram-BOSHW7O7-Btxtcgvl.js} +2 -2
  66. package/dist/assets/assets/{kanban-definition-FNSA4HC5-DnXna7jO.js → kanban-definition-FNSA4HC5-q7ek9o_H.js} +2 -2
  67. package/dist/assets/assets/{line-BsXJZn93.js → line-B7yLilmC.js} +2 -2
  68. package/dist/assets/assets/{linear-BHYaD5T0.js → linear-y8aSKEli.js} +2 -2
  69. package/dist/assets/assets/{mermaid-parser.core-B64Eo-8a.js → mermaid-parser.core-B4rH50nD.js} +4 -4
  70. package/dist/assets/assets/{mermaid.core-Zw9qmTzg.js → mermaid.core-DnRVHTjE.js} +5 -5
  71. package/dist/assets/assets/{mindmap-definition-6OY57UG3-E5qz4KNc.js → mindmap-definition-6OY57UG3-DT9Afs2v.js} +2 -2
  72. package/dist/assets/assets/{packet-JDAUHWVQ-DgfizTr3.js → packet-JDAUHWVQ-CnqNbu4p.js} +1 -1
  73. package/dist/assets/assets/{pegDiagram-ECIUJNBX-D0WK_agM.js → pegDiagram-ECIUJNBX-cvxdBBFq.js} +2 -2
  74. package/dist/assets/assets/{pie-XZMESJXO-PJR1sXD4.js → pie-XZMESJXO-etXMNsaL.js} +1 -1
  75. package/dist/assets/assets/{pieDiagram-GNMPY74T-CPuU-NTs.js → pieDiagram-GNMPY74T-CBN-R3_j.js} +2 -2
  76. package/dist/assets/assets/{quadrantDiagram-D57K4MC3-5C9yjM1b.js → quadrantDiagram-D57K4MC3-C5jjVPIH.js} +2 -2
  77. package/dist/assets/assets/{radar-ABXABTNO-BspdXgl0.js → radar-ABXABTNO-CAMd_mrV.js} +1 -1
  78. package/dist/assets/assets/{railroad-I3PHUGI6-Ct0a6hLD.js → railroad-I3PHUGI6-DIs3auoe.js} +1 -1
  79. package/dist/assets/assets/{railroad-abnf-LNEFI6M7-fduYB4SA.js → railroad-abnf-LNEFI6M7-CJXr1qWy.js} +1 -1
  80. package/dist/assets/assets/{railroad-ebnf-DWYD2UWJ-CTQa8Sww.js → railroad-ebnf-DWYD2UWJ-DfwtykqI.js} +1 -1
  81. package/dist/assets/assets/{railroad-peg-JR7BVNR7-DatoH3GJ.js → railroad-peg-JR7BVNR7-B8beAhTs.js} +1 -1
  82. package/dist/assets/assets/{railroadDiagram-Y72NRBL7-C8sWN8l2.js → railroadDiagram-Y72NRBL7-BDcQE-EL.js} +2 -2
  83. package/dist/assets/assets/{requirementDiagram-EQYSW5RA-CqRz4RcT.js → requirementDiagram-EQYSW5RA-KJ4-QjZM.js} +2 -2
  84. package/dist/assets/assets/{sankeyDiagram-SY24JHO5-bdiuKKlX.js → sankeyDiagram-SY24JHO5-VjIB-Ybr.js} +2 -2
  85. package/dist/assets/assets/{sequenceDiagram-BLEHNHQU-Zy-8I0Hy.js → sequenceDiagram-BLEHNHQU-MfMuWq1M.js} +2 -2
  86. package/dist/assets/assets/{src-gihY33R9.js → src-BAxIj8GJ.js} +2 -2
  87. package/dist/assets/assets/{stateDiagram-v2-A6IESKWZ-DXQERPvz.js → stateDiagram-v2-A6IESKWZ-mHwLRRCY.js} +2 -2
  88. package/dist/assets/assets/{swimlanes-B3ENRKFQ-1gjZQElg.js → swimlanes-B3ENRKFQ-PArlYoqV.js} +2 -2
  89. package/dist/assets/assets/swimlanesDiagram-AYQRV4AK-The09-5S.js +9 -0
  90. package/dist/assets/assets/{timeline-definition-JXYKGLGB-CTeYEw-9.js → timeline-definition-JXYKGLGB-B2nKiNFU.js} +2 -2
  91. package/dist/assets/assets/{treeView-D4JQ5SDB-DD-EsLLT.js → treeView-D4JQ5SDB-gU23_RuI.js} +1 -1
  92. package/dist/assets/assets/{treemap-SAJKECNS-BLdFeS5J.js → treemap-SAJKECNS-CiqoMvZa.js} +1 -1
  93. package/dist/assets/assets/{usecaseDiagram-WPOLBNNX-C1GikSSP.js → usecaseDiagram-WPOLBNNX-DpeoWpMK.js} +2 -2
  94. package/dist/assets/assets/{vennDiagram-Q3Y3IDCW-B1FoA3g8.js → vennDiagram-Q3Y3IDCW-C31iGKvM.js} +2 -2
  95. package/dist/assets/assets/{wardley-7MLQ67FV-BrHb5Bjf.js → wardley-7MLQ67FV-CIzHhzNw.js} +1 -1
  96. package/dist/assets/assets/{wardleyDiagram-IVAIDKWA-CmPLD1X4.js → wardleyDiagram-IVAIDKWA-DIIkoezc.js} +2 -2
  97. package/dist/assets/assets/{webpack-BYWDFj_R.js → webpack-RFseiMZW.js} +2 -2
  98. package/dist/assets/assets/{xychartDiagram-4URNHDU4-DR5pfEjl.js → xychartDiagram-4URNHDU4-QiHL91kC.js} +2 -2
  99. package/dist/assets/bundle-asset-policy.json +1 -1
  100. package/dist/assets/index.html +2 -2
  101. package/dist/assets/plugins/assets/base-CKKRZ7-h.css +2 -0
  102. package/dist/assets/plugins/assets/browserCaptureWorklet-Droj0fW0-Droj0fW0.js +13 -0
  103. package/dist/assets/plugins/assets/ibm-plex-sans-cyrillic-ext-wght-normal-d45eAU9y.woff2 +0 -0
  104. package/dist/assets/plugins/assets/ibm-plex-sans-cyrillic-wght-normal-BAAhND-U.woff2 +0 -0
  105. package/dist/assets/plugins/assets/ibm-plex-sans-greek-wght-normal-CmyJS8uq.woff2 +0 -0
  106. package/dist/assets/plugins/assets/ibm-plex-sans-latin-ext-wght-normal-CIII54If.woff2 +0 -0
  107. package/dist/assets/plugins/assets/ibm-plex-sans-latin-wght-normal-IvpUvPa2.woff2 +0 -0
  108. package/dist/assets/plugins/assets/ibm-plex-sans-vietnamese-wght-normal-Dg1JeJN0.woff2 +0 -0
  109. package/dist/assets/plugins/assets/jetbrains-mono-cyrillic-ext-wght-normal-EocZY2iu.woff2 +0 -0
  110. package/dist/assets/plugins/assets/jetbrains-mono-cyrillic-wght-normal-D73BlboJ.woff2 +0 -0
  111. package/dist/assets/plugins/assets/jetbrains-mono-greek-wght-normal-Bw9x6K1M.woff2 +0 -0
  112. package/dist/assets/plugins/assets/jetbrains-mono-latin-ext-wght-normal-DBQx-q_a.woff2 +0 -0
  113. package/dist/assets/plugins/assets/jetbrains-mono-latin-wght-normal-B9CIFXIH.woff2 +0 -0
  114. package/dist/assets/plugins/assets/jetbrains-mono-vietnamese-wght-normal-Bt-aOZkq.woff2 +0 -0
  115. package/dist/assets/plugins/assets/sileroVadWorker-D894njUe-DjN_BMWf.mjs +110 -0
  116. package/dist/assets/plugins/assets/silero_vad_v6.2.1-SjbCxFXk-SjbCxFXk.onnx +0 -0
  117. package/dist/assets/plugins/chunks/po-web-runtime-BJDT6Lbw.js +1 -0
  118. package/dist/assets/plugins/compositions.json +1 -0
  119. package/dist/assets/plugins/slots/approval.293d9a00-BXIhaPlQ.js +2 -0
  120. package/dist/assets/plugins/slots/artifacts.24567664-ZzR0gbvy.js +1 -0
  121. package/dist/assets/plugins/slots/author.0998a880-DAbA-7rb.js +93 -0
  122. package/dist/assets/plugins/slots/autocompact.dd97d013-IVq4Z6qm.js +1 -0
  123. package/dist/assets/plugins/slots/builtin-tools.36d7400b-CpCLjRRN.js +7 -0
  124. package/dist/assets/plugins/slots/codemode.8eaee717-VWt9PqsU.js +10 -0
  125. package/dist/assets/plugins/slots/domain.5e95fc37-5PIUBqDe.js +1 -0
  126. package/dist/assets/plugins/slots/edit.385c9aa9-DNAjPNG5.js +7 -0
  127. package/dist/assets/plugins/slots/files.daf34ed8-CQaTz0i1.js +2 -0
  128. package/dist/assets/plugins/slots/goal.77ec9930-B8EkarBq.js +1 -0
  129. package/dist/assets/plugins/slots/grep.02052cdc-CIRhO2gY.js +1 -0
  130. package/dist/assets/plugins/slots/help.ecd4c0f9-naMF9NN1.js +3 -0
  131. package/dist/assets/plugins/slots/log.a86eb6d0-D5__rAZJ.js +4 -0
  132. package/dist/assets/plugins/slots/mcp.974af249-DPNHn9XH.js +109 -0
  133. package/dist/assets/plugins/slots/plan.bafb8f68-C5GEpybF.js +3 -0
  134. package/dist/assets/plugins/slots/profile.48851a1d-yX6tzV3x.js +1 -0
  135. package/dist/assets/plugins/slots/prompts.723d7748-B7zpPeoF.js +3 -0
  136. package/dist/assets/plugins/slots/read.46bf6536-Cw5Z5z5T.js +1 -0
  137. package/dist/assets/plugins/slots/runner.53e9bd76-CiQR_FPX.js +8 -0
  138. package/dist/assets/plugins/slots/skill.086701a4-CL6h_F-x.js +4 -0
  139. package/dist/assets/plugins/slots/vault.ac9935c8-DKERQYg4.js +1 -0
  140. package/dist/assets/plugins/slots/voice.e85ca7f9-DEgb-U9m.js +1 -0
  141. package/dist/assets/pwa/pwa.js +12 -12
  142. package/dist/assets/pwa/sw.js +4 -4
  143. package/dist/{atomicJson-BJfPFSYF.js → atomicJson-C_7F2zD1.js} +2 -3
  144. package/dist/azure-openai-config-COZUaRzM.js +55 -0
  145. package/dist/azure-openai-responses-Cs4k2HOd.js +183 -0
  146. package/dist/{backgroundWork-CeFrbRnj.js → backgroundWork-B1mPDYlf.js} +1 -1
  147. package/dist/browser-BWf8OMfl.js +3 -0
  148. package/dist/childSession-Cf2-kH4O.js +22 -0
  149. package/dist/classifier-shared-IhSH9hhh.js +106 -0
  150. package/dist/cloudflare-workers-ai-system-one-BNnc8MuH.js +52 -0
  151. package/dist/{codemode-DbPu0yJN.js → codemode-DQFmrosw.js} +5 -2
  152. package/dist/contracts-DD3f1Lpn.js +19 -0
  153. package/dist/diagnostics-1lYFeSJe.js +131 -0
  154. package/dist/{server-D3PQk1Gt.js → dist-B-vqs6tA.js} +1 -546
  155. package/dist/dist-Dvx5mlIR.js +50 -0
  156. package/dist/env-api-keys-Bow6MJe2.js +32 -0
  157. package/dist/error-body-CJk7jMUh.js +102 -0
  158. package/dist/esm-BKJy3O9-.js +1553 -0
  159. package/dist/exports-B0WMEXCP.js +34 -0
  160. package/dist/{remoteMcp-CMqZldeA.js → exports-D09VsUk-.js} +1153 -175
  161. package/dist/{exports-BNZz2DNU.js → exports-nV43ShA7.js} +25 -9
  162. package/dist/{extensionFile-CXOa5G4C.js → extensionFile-DNM4xsje.js} +26 -2
  163. package/dist/github-copilot-headers-D1RedfLn.js +22 -0
  164. package/dist/google-generative-ai-DXTILNT0.js +328 -0
  165. package/dist/google-shared-e4JDCTVP.js +19588 -0
  166. package/dist/google-vertex-a1lzvJfq.js +374 -0
  167. package/dist/{domains-BNjGTOPj.js → harnessState-Dwrk3lfv.js} +175 -16
  168. package/dist/{harnessStore-BT706Ly6.js → harnessStore-Z7yDLO45.js} +4 -5
  169. package/dist/hash-Dt6RIbkn.js +16 -0
  170. package/dist/headers-CwtEVQvr.js +17 -0
  171. package/dist/help-w6vVEZGL.js +101 -0
  172. package/dist/hubChannel-Cm-sxOvU.js +21 -0
  173. package/dist/hubRevisions-58pU2dW5.js +363 -0
  174. package/dist/identity-BgfHobJH.js +165 -0
  175. package/dist/index.edge-COJJ_Dv2.js +937 -0
  176. package/dist/index.edge-ChYa2LU4.js +14 -0
  177. package/dist/index.edge-ClLTmPFz.js +191 -0
  178. package/dist/index.edge-DyYmurS7.js +62 -0
  179. package/dist/index.edge-K0w5auwG.js +56 -0
  180. package/dist/index.edge-Xa5LLtxz.js +67 -0
  181. package/dist/iso-BPQViXM8.js +10 -0
  182. package/dist/{layeredConfig-DPQAnlXD.js → layeredConfig-CUkYUs1f.js} +193 -15
  183. package/dist/{majorModes-DbCfLZH3.js → majorModes-BB0PXgFn.js} +4 -14
  184. package/dist/majorModes-C7vtBs4D.js +1 -0
  185. package/dist/{mcpProjection-BsP0IEnb.js → mcpProjection-BtKzB6oK.js} +2 -2
  186. package/dist/migrations-5gbLIQIc.js +32 -0
  187. package/dist/mistral-conversations-CLwhVDjA.js +689 -0
  188. package/dist/modeDefinition-C3Zbrw48.js +44 -0
  189. package/dist/models-Chzm15vC.js +1511 -0
  190. package/dist/narration-CpRurWLO.js +127 -0
  191. package/dist/node-BT4GsJQp.js +2479 -0
  192. package/dist/node-DytJOfYf.js +23 -0
  193. package/dist/notification-kckG3leF.js +102 -0
  194. package/dist/openai-codex-responses-DRMONxDE.js +1210 -0
  195. package/dist/openai-completions-CcNhAv8l.js +984 -0
  196. package/dist/openai-decisions-BsFjaAGw.js +142 -0
  197. package/dist/openai-kPrtlgjl.js +17357 -0
  198. package/dist/openai-prompt-cache-Bc6qNWt0.js +8 -0
  199. package/dist/openai-responses-C5Gp2UOV.js +281 -0
  200. package/dist/openai-responses-shared-BbSi-wBR.js +661 -0
  201. package/dist/openrouter-cost-CvC52g3b.js +30 -0
  202. package/dist/openrouter-images-BoHl8g8p.js +124 -0
  203. package/dist/{hubChannel-BHQyzcOo.js → packageApi-t1oCjNDU.js} +4 -41
  204. package/dist/photon_rs_bg.wasm +0 -0
  205. package/dist/pi-messages-BXfrZLC7.js +312 -0
  206. package/dist/piConfig-DQzlbPY4.js +126 -0
  207. package/dist/piSettings-Cf1QofNe.js +1 -0
  208. package/dist/platform-BIEiM4TG.js +113 -0
  209. package/dist/pluginContributions-Be9EnCAW.js +16 -0
  210. package/dist/pluginProtocol-BqXXyI4z.js +80 -0
  211. package/dist/{protocol-Xpm_mCNN.js → protocol-DDL8geoS.js} +2 -2
  212. package/dist/provider-env-CxhHUFiF.js +38 -0
  213. package/dist/provider-retry-BUoezuw8.js +79 -0
  214. package/dist/sanitize-unicode-C3Ec8oL6.js +26 -0
  215. package/dist/sealedChannel-BeWNTWys.js +27 -0
  216. package/dist/server-AbXyhXlY.js +217 -0
  217. package/dist/server-B6dqQoh2.js +1518 -0
  218. package/dist/server-BIHo9TFu.js +505 -0
  219. package/dist/{server-BZh1ZXz_.js → server-BJ7DNzCp.js} +8 -19
  220. package/dist/server-BO-j_GbD.js +15106 -0
  221. package/dist/{server-D4W7EdJY.js → server-BQzAiMns.js} +16 -16
  222. package/dist/server-BR7SZtj7.js +3125 -0
  223. package/dist/{server-BE6VqEiA.js → server-BT2ORK83.js} +20 -12
  224. package/dist/server-BbSHYRnY.js +295 -0
  225. package/dist/server-BqoKlEGk.js +1806 -0
  226. package/dist/{server-tvgQ99rv.js → server-Busl0pQI.js} +370 -120
  227. package/dist/server-CIHM4jqu.js +1116 -0
  228. package/dist/server-CgWSSdvd.js +576 -0
  229. package/dist/{server-Dpgh8PDh.js → server-Co_UWKrR.js} +14 -5
  230. package/dist/{server-BAAL9-NA.js → server-CuEPb7u-.js} +3 -10
  231. package/dist/{server-Dt4y1rZD.js → server-D40q2Jpx.js} +47 -27
  232. package/dist/server-DCyf2Asb.js +679 -0
  233. package/dist/server-DH7PfLln.js +148 -0
  234. package/dist/server-DJ8bc89M.js +934 -0
  235. package/dist/server-DYdp0W9v.js +489 -0
  236. package/dist/server-DsdPEYGu.js +639 -0
  237. package/dist/server-DymH4Ucq.js +189 -0
  238. package/dist/server-IqECnUrb.js +834 -0
  239. package/dist/{server-36iuA3MI.js → server-KBgW77zh.js} +3 -3
  240. package/dist/server-RW_9R3R3.js +1522 -0
  241. package/dist/server-aUit8j6r.js +1028 -0
  242. package/dist/{server-DJAanjoI.js → server-gifRriZK.js} +491 -103
  243. package/dist/server-nkUlqnAL.js +2658 -0
  244. package/dist/server-oxyEbv1a.js +1256 -0
  245. package/dist/{server-D8ndq0wL.js → server-ub3s16Mc.js} +11 -9
  246. package/dist/{build-2gFaVEfG.js → serverPlugin-CELT6P0Q.js} +3946 -3
  247. package/dist/{sessionConfig-rBQgzXlT.js → sessionConfig-RQGvfm6E.js} +550 -760
  248. package/dist/simple-options-CFzI5Pd_.js +156 -0
  249. package/dist/streaming-json-BWTHTwz-.js +858 -0
  250. package/dist/system-one-shared-CiIrx29d.js +132 -0
  251. package/dist/{notification-D76PSL7r.js → telemetry-Csv1ZxAn.js} +1 -92
  252. package/dist/transform-messages-D77af7Bx.js +356 -0
  253. package/dist/truncate-M3KbFyVj.js +89 -0
  254. package/dist/{server-A-_GFpPr.js → type-ASYnCGVW.js} +10 -1031
  255. package/dist/typesafe-system-one-DGxeggJh.js +37 -0
  256. package/dist/uuid-B0QJx6Kr.js +31 -0
  257. package/dist/{validation-D77NZBrx.js → validation-BJxVSAwx.js} +8 -3
  258. package/dist/{value-Djvc2foV.js → value-_W31So3B.js} +1 -1
  259. package/dist/vaultSettings-Di3n5YIg.js +328 -0
  260. package/dist/voiceTools-RMn4HvWo.js +246 -0
  261. package/dist/web-DCP7ELJj.js +3 -0
  262. package/dist/worker.js +95288 -49863
  263. package/dist/workflow-B7qx0Vv9.js +79 -0
  264. package/package.json +37 -22
  265. package/wrangler.jsonc +4 -2
  266. package/dist/assets/assets/channel-CMrEzemr.js +0 -2
  267. package/dist/assets/assets/chunk-XXDRQBXY-CFf0S6bN.js +0 -2
  268. package/dist/assets/assets/flowDiagram-IUGLLWBU-BhGbWVf0.js +0 -1
  269. package/dist/assets/assets/index-Bx_K4Joy.js +0 -155
  270. package/dist/assets/assets/index-DZM68mTk.css +0 -1
  271. package/dist/assets/assets/swimlanesDiagram-AYQRV4AK-q91tR8ri.js +0 -9
  272. package/dist/contextProjection-DVP2Vc5j.js +0 -188
  273. package/dist/harnessState-gmzJcPGt.js +0 -88
  274. package/dist/harnessStore-BiH9vSuD.js +0 -1
  275. package/dist/index.edge-BgSx_gRO.js +0 -45
  276. package/dist/majorModes-BvWNqoHt.js +0 -1
  277. package/dist/piSettings-B6fsgIBA.js +0 -1
  278. package/dist/platform-B4AAgwJ0.js +0 -16
  279. package/dist/platformFiles-C_bXo4Ig.js +0 -39
  280. package/dist/server-BZaPPoQp.js +0 -592
  281. package/dist/server-D75MWDhB.js +0 -118
  282. package/dist/server-r358hzQg.js +0 -280
  283. package/dist/serverPlugin-BOI6c6s5.js +0 -3393
@@ -1,3393 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import path from "node:path";
3
- //#region ../../core/po-core/src/schemas/serverScope.ts
4
- /**
5
- * The server inversion-of-control tree: global, then one scope per workspace, then one per session.
6
- *
7
- * Each level has its own cordis root. A contract names an abstract service and the one level whose
8
- * plugin binds the concrete value; every descendant level sees that value as a native cordis service,
9
- * so `inject` and `ctx.get` work unchanged. A level never sees a contract bound below it.
10
- */
11
- const PO_SERVER_SCOPE_SERVICE = "po/server-scope";
12
- /** Outermost first, so a lower index is an ancestor level. */
13
- const PO_SERVER_SCOPE_LEVELS = [
14
- "global",
15
- "workspace",
16
- "session"
17
- ];
18
- function defineServiceContract(name, options) {
19
- return {
20
- name,
21
- scope: options.scope
22
- };
23
- }
24
- function readPoServerScope(context) {
25
- return context.get(PO_SERVER_SCOPE_SERVICE);
26
- }
27
- function requirePoServerScope(context) {
28
- const service = readPoServerScope(context);
29
- if (!service) throw new Error("The Po server scope is unavailable. Install packages through a Po server scope.");
30
- return service;
31
- }
32
- //#endregion
33
- //#region ../../../node_modules/.pnpm/@earendil-works+pi-telemetry@1.5.0/node_modules/@earendil-works/pi-telemetry/dist/noop.js
34
- async function startNoopSpan(_options, callback) {
35
- return callback(noopTelemetrySpan);
36
- }
37
- const noopCounter = Object.freeze({ add: () => {} });
38
- const noopUpDownCounter = Object.freeze({ add: () => {} });
39
- const noopHistogram = Object.freeze({ record: () => {} });
40
- /** Shared instruments that never inspect or retain metadata, measurements, or contexts. */
41
- const NOOP_TELEMETRY_METRICS = Object.freeze({
42
- counter: () => noopCounter,
43
- upDownCounter: () => noopUpDownCounter,
44
- histogram: () => noopHistogram
45
- });
46
- const noopTelemetrySpan = {
47
- metrics: NOOP_TELEMETRY_METRICS,
48
- propagation: Object.freeze({
49
- inject: () => void 0,
50
- extract: () => NOOP_TELEMETRY_CONTEXT
51
- }),
52
- startSpan: startNoopSpan,
53
- addLink: () => {},
54
- addEvent: () => {},
55
- setAttributes: () => {},
56
- setStatus: () => {}
57
- };
58
- Object.freeze(noopTelemetrySpan);
59
- /** Shared telemetry context used when an application does not provide one. */
60
- const NOOP_TELEMETRY_CONTEXT = noopTelemetrySpan;
61
- //#endregion
62
- //#region ../../../node_modules/.pnpm/@earendil-works+pi-telemetry@1.5.0/node_modules/@earendil-works/pi-telemetry/dist/index.js
63
- /** Typed identity helper for serializable telemetry schema data. */
64
- function defineTelemetrySchema(schema) {
65
- return schema;
66
- }
67
- function bindTypedSpanStarter(telemetryContext) {
68
- const startSpan = (name, attributes, callback) => telemetryContext.startSpan({
69
- name,
70
- attributes
71
- }, (span) => callback(span, bindTypedSpanStarter(span)));
72
- return startSpan;
73
- }
74
- /**
75
- * Bind an explicit parent context to the combined span vocabulary of one or more schemas.
76
- * Schema values are used only for type inference; no runtime schema validation is performed.
77
- */
78
- function createTypedSpanStarter(telemetryContext, _schemas) {
79
- return bindTypedSpanStarter(telemetryContext);
80
- }
81
- //#endregion
82
- //#region ../../../node_modules/.pnpm/@earendil-works+chord@1.5.0_esbuild@0.28.2/node_modules/@earendil-works/chord/dist/context/index.js
83
- const ABORT_SIGNAL_CONTEXT_KEY = Object.freeze({ token: Symbol("chord.abortSignal") });
84
- const TELEMETRY_CONTEXT_KEY = Object.freeze({ token: Symbol("chord.telemetry") });
85
- var BaseContext = class {
86
- get abortSignal() {
87
- return this.value(ABORT_SIGNAL_CONTEXT_KEY);
88
- }
89
- get telemetry() {
90
- return this.value(TELEMETRY_CONTEXT_KEY) ?? NOOP_TELEMETRY_CONTEXT;
91
- }
92
- };
93
- var EmptyContext = class extends BaseContext {
94
- #name;
95
- constructor(name) {
96
- super();
97
- this.#name = name;
98
- }
99
- value(_key) {}
100
- toString() {
101
- return this.#name;
102
- }
103
- };
104
- var ContextValue = class extends BaseContext {
105
- #parent;
106
- #key;
107
- #value;
108
- constructor(parent, key, value) {
109
- super();
110
- this.#parent = parent;
111
- this.#key = key;
112
- this.#value = value;
113
- }
114
- value(key) {
115
- if (key.token === this.#key.token) return this.#value;
116
- return this.#parent.value(key);
117
- }
118
- toString() {
119
- return `${this.#parent}.WithValue(${this.#key.token.description ?? "anonymous"})`;
120
- }
121
- };
122
- const BACKGROUND_CONTEXT = new EmptyContext("[Context BACKGROUND_CONTEXT]");
123
- new EmptyContext("[Context TODO_CONTEXT]");
124
- /** Derive a context containing one additional or replaced value. */
125
- function withContextValue(key, value, parent) {
126
- return new ContextValue(parent, key, value);
127
- }
128
- /** Derive an explicit telemetry parent without changing cancellation or application values. */
129
- function withTelemetry(telemetry, context) {
130
- return withContextValue(TELEMETRY_CONTEXT_KEY, telemetry, context);
131
- }
132
- /**
133
- * Derive a context cancelled by either the parent signal or the supplied signal.
134
- * The parent context remains unchanged.
135
- */
136
- function withAbortSignal(signal, context) {
137
- const parentSignal = context.abortSignal;
138
- const combined = parentSignal === void 0 ? signal : AbortSignal.any([parentSignal, signal]);
139
- return withContextValue(ABORT_SIGNAL_CONTEXT_KEY, combined, context);
140
- }
141
- /** Derive a context retaining all values except caller cancellation. Intended for mandatory cleanup only. */
142
- function withoutAbortSignal(context) {
143
- return withContextValue(ABORT_SIGNAL_CONTEXT_KEY, void 0, context);
144
- }
145
- /**
146
- * Observe a promise until it settles or the invocation is cancelled.
147
- * Cancellation rejects only this waiter; it does not cancel the underlying promise.
148
- */
149
- function awaitWithContext(promise, context) {
150
- const signal = context.abortSignal;
151
- if (signal === void 0) return promise;
152
- if (signal.aborted) return Promise.reject(abortError(signal));
153
- return new Promise((resolve, reject) => {
154
- const onAbort = () => reject(abortError(signal));
155
- signal.addEventListener("abort", onAbort, { once: true });
156
- promise.then((value) => {
157
- signal.removeEventListener("abort", onAbort);
158
- resolve(value);
159
- }, (error) => {
160
- signal.removeEventListener("abort", onAbort);
161
- reject(error);
162
- });
163
- });
164
- }
165
- function abortError(signal) {
166
- const reason = signal.reason;
167
- return reason instanceof Error ? reason : new DOMException("The operation was aborted", "AbortError");
168
- }
169
- //#endregion
170
- //#region ../../core/po-core/src/schemas/serverPlugin.ts
171
- /** The host service each scope level publishes for the packages installed into it. */
172
- const PO_SERVER_HOST_SERVICE = "po/server-host";
173
- function readPoServerHost(context) {
174
- return context.get(PO_SERVER_HOST_SERVICE);
175
- }
176
- function requirePoServerHost(context) {
177
- const service = readPoServerHost(context);
178
- if (!service) throw new Error("The Po server host is unavailable. Start a Po server first.");
179
- return service;
180
- }
181
- /** Read pure root metadata without initializing or mounting the root. */
182
- function composeServerProviderOverrides(...roots) {
183
- return (context) => roots.flatMap((root) => {
184
- if (typeof root !== "function" && typeof root !== "object" || root === null) return [];
185
- const callback = root.providerOverrides;
186
- return typeof callback === "function" ? callback(context) : [];
187
- });
188
- }
189
- /** Capture schema inference before heterogeneous methods enter a contribution array. */
190
- function defineServerMethod(definition, handler) {
191
- return { register: (host) => host.registerMethod(definition, handler) };
192
- }
193
- defineServiceContract("po/global-services", { scope: "global" });
194
- /** Longest a package factory (server plugin apply, MCP session, Pi factory) may take. */
195
- const LIVE_FACTORY_TIMEOUT_MS = 1e4;
196
- /**
197
- * Bounds one host-awaited step of package code.
198
- *
199
- * The abandoned promise keeps running, because a module cannot be cancelled; its late
200
- * rejection is observed here so it never surfaces as an unhandled rejection.
201
- */
202
- function withTimeout(work, ms, label) {
203
- let timer;
204
- const timeout = new Promise((_, reject) => {
205
- timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`${label} timed out after ${String(ms)} ms`)), ms);
206
- timer.unref?.();
207
- });
208
- work.catch(() => void 0);
209
- return Promise.race([work, timeout]).finally(() => clearTimeout(timer));
210
- }
211
- /** Imports a live package URL under a timeout, skipping and recording poisoned URLs. */
212
- async function guardedImport(url, importer, guard) {
213
- if (guard.poisoned?.has(url)) throw new Error("skipped: this package content failed to load earlier and retries only after it changes");
214
- try {
215
- return await withTimeout(Promise.resolve().then(() => importer(url)), guard.importTimeoutMs ?? 15e3, "import");
216
- } catch (error) {
217
- guard.poisoned?.add(url);
218
- throw error;
219
- }
220
- }
221
- //#endregion
222
- //#region ../../../node_modules/.pnpm/@deepseek-ai+cosmokit@1.8.6/node_modules/@deepseek-ai/cosmokit/lib/index.js
223
- /** Return true when a value is `null` or `undefined`. */
224
- function isNullable(value) {
225
- return value === null || value === void 0;
226
- }
227
- /** Define a non-enumerable writable property and return the object. */
228
- function defineProperty(object, key, value) {
229
- return Object.defineProperty(object, key, {
230
- writable: true,
231
- value,
232
- enumerable: false
233
- });
234
- }
235
- /** Test values using `instanceof` with a `toStringTag` fallback. */
236
- function is(type, value) {
237
- if (arguments.length === 1) return (value) => is(type, value);
238
- return type in globalThis && value instanceof globalThis[type] || Object.prototype.toString.call(value).slice(8, -1) === type;
239
- }
240
- function isArrayBufferLike(value) {
241
- return is("ArrayBuffer", value) || is("SharedArrayBuffer", value);
242
- }
243
- function isArrayBufferSource(value) {
244
- return isArrayBufferLike(value) || ArrayBuffer.isView(value);
245
- }
246
- /** Binary source detection and base64/hex conversion helpers. */
247
- var Binary;
248
- (function(Binary) {
249
- Binary.is = isArrayBufferLike;
250
- Binary.isSource = isArrayBufferSource;
251
- function fromSource(source) {
252
- if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
253
- else return source;
254
- }
255
- Binary.fromSource = fromSource;
256
- function toBase64(source) {
257
- source = fromSource(source);
258
- if (typeof Buffer !== "undefined") return Buffer.from(source).toString("base64");
259
- let binary = "";
260
- const bytes = new Uint8Array(source);
261
- for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);
262
- return btoa(binary);
263
- }
264
- Binary.toBase64 = toBase64;
265
- function fromBase64(source) {
266
- if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "base64"));
267
- return Uint8Array.from(atob(source), (c) => c.charCodeAt(0));
268
- }
269
- Binary.fromBase64 = fromBase64;
270
- function toHex(source) {
271
- source = fromSource(source);
272
- if (typeof Buffer !== "undefined") return Buffer.from(source).toString("hex");
273
- return Array.from(new Uint8Array(source), (byte) => byte.toString(16).padStart(2, "0")).join("");
274
- }
275
- Binary.toHex = toHex;
276
- function fromHex(source) {
277
- if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "hex"));
278
- const hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1);
279
- const buffer = [];
280
- for (let i = 0; i < hex.length; i += 2) buffer.push(parseInt(`${hex[i]}${hex[i + 1]}`, 16));
281
- return Uint8Array.from(buffer).buffer;
282
- }
283
- Binary.fromHex = fromHex;
284
- })(Binary || (Binary = {}));
285
- Binary.fromBase64;
286
- Binary.toBase64;
287
- Binary.fromHex;
288
- Binary.toHex;
289
- function tokenize(source, delimiters, delimiter) {
290
- const output = [];
291
- let state = 0;
292
- for (let i = 0; i < source.length; i++) {
293
- const code = source.charCodeAt(i);
294
- if (code >= 65 && code <= 90) {
295
- if (state === 1) {
296
- const next = source.charCodeAt(i + 1);
297
- if (next >= 97 && next <= 122) output.push(delimiter);
298
- output.push(code + 32);
299
- } else {
300
- if (state !== 0) output.push(delimiter);
301
- output.push(code + 32);
302
- }
303
- state = 1;
304
- } else if (code >= 97 && code <= 122) {
305
- output.push(code);
306
- state = 2;
307
- } else if (delimiters.includes(code)) {
308
- if (state !== 0) output.push(delimiter);
309
- state = 0;
310
- } else output.push(code);
311
- }
312
- return String.fromCharCode(...output);
313
- }
314
- /** Convert text to dash-delimited parameter case. */
315
- function paramCase(source) {
316
- return tokenize(source, [45, 95], 45);
317
- }
318
- /** Runtime alias for `paramCase`. */
319
- const hyphenate = paramCase;
320
- /** Time constants plus parsing and formatting helpers. */
321
- var Time;
322
- (function(Time) {
323
- Time.millisecond = 1;
324
- Time.second = 1e3;
325
- Time.minute = Time.second * 60;
326
- Time.hour = Time.minute * 60;
327
- Time.day = Time.hour * 24;
328
- Time.week = Time.day * 7;
329
- let timezoneOffset = (/* @__PURE__ */ new Date()).getTimezoneOffset();
330
- function setTimezoneOffset(offset) {
331
- timezoneOffset = offset;
332
- }
333
- Time.setTimezoneOffset = setTimezoneOffset;
334
- function getTimezoneOffset() {
335
- return timezoneOffset;
336
- }
337
- Time.getTimezoneOffset = getTimezoneOffset;
338
- function getDateNumber(date = /* @__PURE__ */ new Date(), offset) {
339
- if (typeof date === "number") date = new Date(date);
340
- if (offset === void 0) offset = timezoneOffset;
341
- return Math.floor((date.valueOf() / Time.minute - offset) / 1440);
342
- }
343
- Time.getDateNumber = getDateNumber;
344
- function fromDateNumber(value, offset) {
345
- const date = new Date(value * Time.day);
346
- if (offset === void 0) offset = timezoneOffset;
347
- return new Date(+date + offset * Time.minute);
348
- }
349
- Time.fromDateNumber = fromDateNumber;
350
- const numeric = /\d+(?:\.\d+)?/.source;
351
- const timeRegExp = new RegExp(`^${[
352
- "w(?:eek(?:s)?)?",
353
- "d(?:ay(?:s)?)?",
354
- "h(?:our(?:s)?)?",
355
- "m(?:in(?:ute)?(?:s)?)?",
356
- "s(?:ec(?:ond)?(?:s)?)?"
357
- ].map((unit) => `(${numeric}${unit})?`).join("")}$`);
358
- function parseTime(source) {
359
- const capture = timeRegExp.exec(source);
360
- if (!capture) return 0;
361
- return (parseFloat(capture[1]) * Time.week || 0) + (parseFloat(capture[2]) * Time.day || 0) + (parseFloat(capture[3]) * Time.hour || 0) + (parseFloat(capture[4]) * Time.minute || 0) + (parseFloat(capture[5]) * Time.second || 0);
362
- }
363
- Time.parseTime = parseTime;
364
- function parseDate(date) {
365
- const parsed = parseTime(date);
366
- if (parsed) date = Date.now() + parsed;
367
- else if (/^\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).toLocaleDateString()}-${date}`;
368
- else if (/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).getFullYear()}-${date}`;
369
- return date ? new Date(date) : /* @__PURE__ */ new Date();
370
- }
371
- Time.parseDate = parseDate;
372
- function format(ms) {
373
- const abs = Math.abs(ms);
374
- if (abs >= Time.day - Time.hour / 2) return Math.round(ms / Time.day) + "d";
375
- else if (abs >= Time.hour - Time.minute / 2) return Math.round(ms / Time.hour) + "h";
376
- else if (abs >= Time.minute - Time.second / 2) return Math.round(ms / Time.minute) + "m";
377
- else if (abs >= Time.second) return Math.round(ms / Time.second) + "s";
378
- return ms + "ms";
379
- }
380
- Time.format = format;
381
- function toDigits(source, length = 2) {
382
- return source.toString().padStart(length, "0");
383
- }
384
- Time.toDigits = toDigits;
385
- function template(template, time = /* @__PURE__ */ new Date()) {
386
- return template.replace("yyyy", time.getFullYear().toString()).replace("yy", time.getFullYear().toString().slice(2)).replace("MM", toDigits(time.getMonth() + 1)).replace("dd", toDigits(time.getDate())).replace("hh", toDigits(time.getHours())).replace("mm", toDigits(time.getMinutes())).replace("ss", toDigits(time.getSeconds())).replace("SSS", toDigits(time.getMilliseconds(), 3));
387
- }
388
- Time.template = template;
389
- })(Time || (Time = {}));
390
- //#endregion
391
- //#region ../../../node_modules/.pnpm/@deepseek-ai+cordis@4.0.5/node_modules/@deepseek-ai/cordis/lib/index.js
392
- /** Ordered collection of disposable values with O(1) deletion by value. */
393
- var DisposableList = class {
394
- sn = 0;
395
- map = /* @__PURE__ */ new Map();
396
- weak = /* @__PURE__ */ new WeakMap();
397
- get length() {
398
- return this.map.size;
399
- }
400
- push(value) {
401
- const sn = ++this.sn;
402
- this.map.set(sn, value);
403
- this.weak.set(value, sn);
404
- return () => this.map.delete(sn);
405
- }
406
- delete(value) {
407
- const sn = this.weak.get(value);
408
- if (!sn) return false;
409
- return this.map.delete(sn);
410
- }
411
- clear() {
412
- const values = [...this.map.values()];
413
- this.map.clear();
414
- return values.reverse();
415
- }
416
- [Symbol.iterator]() {
417
- return this.map.values();
418
- }
419
- [Symbol.for("nodejs.util.inspect.custom")]() {
420
- return [...this];
421
- }
422
- };
423
- /** Shared symbols used to avoid public property-name collisions. */
424
- const symbols = {
425
- shadow: Symbol.for("cordis.shadow"),
426
- receiver: Symbol.for("cordis.receiver"),
427
- original: Symbol.for("cordis.original"),
428
- metadata: Symbol.for("cordis.metadata"),
429
- initHooks: Symbol.for("cordis.initHooks"),
430
- checkProto: Symbol.for("cordis.checkProto"),
431
- effect: Symbol.for("cordis.effect"),
432
- filter: Symbol.for("cordis.filter"),
433
- isolate: Symbol.for("cordis.isolate"),
434
- intercept: Symbol.for("cordis.intercept"),
435
- init: Symbol.for("cordis.init"),
436
- check: Symbol.for("cordis.check"),
437
- config: Symbol.for("cordis.config"),
438
- invoke: Symbol.for("cordis.invoke"),
439
- extend: Symbol.for("cordis.extend"),
440
- tracker: Symbol.for("cordis.tracker"),
441
- resolveConfig: Symbol.for("cordis.resolveConfig")
442
- };
443
- const GeneratorFunction = function* () {}.constructor;
444
- const AsyncGeneratorFunction = async function* () {}.constructor;
445
- /** Return true when a plugin callback should be constructed with `new`. */
446
- function isConstructor(func) {
447
- if (!func.prototype) return false;
448
- if (func instanceof GeneratorFunction) return false;
449
- if (AsyncGeneratorFunction !== Function && func instanceof AsyncGeneratorFunction) return false;
450
- return true;
451
- }
452
- /** Merge two prototype chains while preserving descriptors from `proto1`. */
453
- function joinPrototype(proto1, proto2) {
454
- if (proto1 === Object.prototype) return proto2;
455
- const result = Object.create(joinPrototype(Object.getPrototypeOf(proto1), proto2));
456
- for (const key of Reflect.ownKeys(proto1)) Object.defineProperty(result, key, Object.getOwnPropertyDescriptor(proto1, key));
457
- return result;
458
- }
459
- /** Return true for non-null objects and functions. */
460
- function isObject(value) {
461
- return value && (typeof value === "object" || typeof value === "function");
462
- }
463
- /** Find a property descriptor by walking an object's prototype chain. */
464
- function getPropertyDescriptor(target, prop) {
465
- let proto = target;
466
- while (proto) {
467
- const desc = Reflect.getOwnPropertyDescriptor(proto, prop);
468
- if (desc) return desc;
469
- proto = Object.getPrototypeOf(proto);
470
- }
471
- }
472
- /** Wrap services/functions so method calls see the caller's active context. */
473
- function getTraceable(ctx, value) {
474
- if (!isObject(value)) return value;
475
- if (Object.hasOwn(value, symbols.shadow)) return Object.getPrototypeOf(value);
476
- const tracker = value[symbols.tracker];
477
- if (!tracker) return value;
478
- return createTraceable(ctx, value, tracker);
479
- }
480
- /** Return a proxy that overlays readonly or writable properties onto a target. */
481
- function withProps(target, props) {
482
- if (!props) return target;
483
- return new Proxy(target, {
484
- get: (target, prop, receiver) => {
485
- if (prop in props && prop !== "constructor") return Reflect.get(props, prop, receiver);
486
- return Reflect.get(target, prop, receiver);
487
- },
488
- set: (target, prop, value, receiver) => {
489
- if (prop in props && prop !== "constructor") return Reflect.set(props, prop, value, receiver);
490
- return Reflect.set(target, prop, value, receiver);
491
- }
492
- });
493
- }
494
- function withProp(target, prop, value) {
495
- return withProps(target, Object.defineProperty(Object.create(null), prop, {
496
- value,
497
- writable: false
498
- }));
499
- }
500
- function createShadow(ctx, target, property, receiver) {
501
- if (!property) return receiver;
502
- const origin = Reflect.getOwnPropertyDescriptor(target, property)?.value;
503
- if (!origin) return receiver;
504
- return withProp(receiver, property, ctx.extend({ [symbols.shadow]: origin }));
505
- }
506
- function createShadowMethod(ctx, value, outer, shadow) {
507
- return new Proxy(value, { apply: (target, thisArg, args) => {
508
- if (thisArg === outer) thisArg = shadow;
509
- return getTraceable(ctx, Reflect.apply(target, thisArg, args));
510
- } });
511
- }
512
- function createTraceable(ctx, value, tracker) {
513
- if (ctx[symbols.shadow] && !tracker.noShadow) ctx = Object.getPrototypeOf(ctx);
514
- const proxy = new Proxy(value, {
515
- get: (target, prop, receiver) => {
516
- if (prop === symbols.original) return target;
517
- if (prop === tracker.property) return ctx;
518
- if (typeof prop === "symbol") return Reflect.get(target, prop, receiver);
519
- if (tracker.associate && ctx.reflect.props[`${tracker.associate}.${prop}`]) return Reflect.get(ctx, `${tracker.associate}.${prop}`, withProp(ctx, symbols.receiver, receiver));
520
- let shadow, innerValue;
521
- const desc = getPropertyDescriptor(target, prop);
522
- if (desc && "value" in desc) innerValue = desc.value;
523
- else {
524
- shadow = createShadow(ctx, target, tracker.property, receiver);
525
- innerValue = Reflect.get(target, prop, shadow);
526
- }
527
- const innerTracker = innerValue?.[symbols.tracker];
528
- if (innerTracker) return createTraceable(ctx, innerValue, innerTracker);
529
- else if (!tracker.noShadow && typeof innerValue === "function") {
530
- shadow ??= createShadow(ctx, target, tracker.property, receiver);
531
- return createShadowMethod(ctx, innerValue, receiver, shadow);
532
- } else return innerValue;
533
- },
534
- set: (target, prop, value, receiver) => {
535
- if (prop === symbols.original) return false;
536
- if (prop === tracker.property) return false;
537
- if (typeof prop === "symbol") return Reflect.set(target, prop, value, receiver);
538
- if (tracker.associate && ctx.reflect.props[`${tracker.associate}.${prop}`]) return Reflect.set(ctx, `${tracker.associate}.${prop}`, value, withProp(ctx, symbols.receiver, receiver));
539
- const shadow = createShadow(ctx, target, tracker.property, receiver);
540
- return Reflect.set(target, prop, value, shadow);
541
- },
542
- apply: (target, thisArg, args) => {
543
- return applyTraceable(proxy, target, thisArg, args);
544
- }
545
- });
546
- return proxy;
547
- }
548
- function applyTraceable(proxy, value, thisArg, args) {
549
- if (!value[symbols.invoke]) return Reflect.apply(value, thisArg, args);
550
- return value[symbols.invoke].apply(proxy, args);
551
- }
552
- /** Create a callable service object that dispatches through `symbols.invoke`. */
553
- function createCallable(name, proto, tracker) {
554
- const self = function(...args) {
555
- return applyTraceable(createTraceable(self["ctx"], self, tracker), self, this, args);
556
- };
557
- defineProperty(self, "name", name);
558
- return Object.setPrototypeOf(self, proto);
559
- }
560
- function handleError(info, reason, getOuterStack) {
561
- const innerLines = info.error.stack.split("\n");
562
- if (typeof reason?.stack !== "string") {
563
- const outerError = new Error(reason);
564
- const lines = outerError.stack.split("\n");
565
- lines.splice(1, Infinity, ...getOuterStack());
566
- outerError.stack = lines.join("\n");
567
- throw outerError;
568
- }
569
- const lines = reason.stack.split("\n");
570
- let index = lines.indexOf(innerLines[2]);
571
- if (index === -1) throw reason;
572
- index -= info.offset;
573
- while (index > 0) {
574
- if (!lines[index - 1].endsWith(" (<anonymous>)")) break;
575
- index -= 1;
576
- }
577
- lines.splice(index, Infinity, ...getOuterStack());
578
- reason.stack = lines.join("\n");
579
- throw reason;
580
- }
581
- /** Run a callback and splice outer call-site frames into thrown async errors. */
582
- function composeError(callback, getOuterStack = buildOuterStack()) {
583
- const info = {
584
- offset: 1,
585
- error: /* @__PURE__ */ new Error()
586
- };
587
- try {
588
- const result = callback(info);
589
- if (isObject(result) && "then" in result) return result.then(void 0, (reason) => handleError(info, reason, getOuterStack));
590
- else return result;
591
- } catch (reason) {
592
- handleError(info, reason, getOuterStack);
593
- }
594
- }
595
- /** Capture a lazy stack-frame supplier for later error composition. */
596
- function buildOuterStack(offset = 0) {
597
- const outerError = /* @__PURE__ */ new Error();
598
- return () => outerError.stack.split("\n").slice(3 + offset);
599
- }
600
- /**
601
- * Return whether an event result should stop a bail-style dispatch.
602
- *
603
- * @param value — a listener's return value.
604
- * @returns `true` unless `value` is `null`, `false`, or `undefined`.
605
- */
606
- function isBailed(value) {
607
- return value !== null && value !== false && value !== void 0;
608
- }
609
- /**
610
- * Event bus installed as `ctx.events` and mixed into every context.
611
- *
612
- * The service supports concurrent, synchronous, serial, bail, and waterfall
613
- * dispatch and automatically disposes listeners with their owning fiber.
614
- */
615
- var EventsService = class {
616
- ctx;
617
- _hooks = {};
618
- constructor(ctx) {
619
- this.ctx = ctx;
620
- defineProperty(this, symbols.tracker, {
621
- property: "ctx",
622
- noShadow: true
623
- });
624
- this.on("internal/listener", function(name, listener, options) {
625
- if (name === "internal/update" && !options.global) return (this.fiber._hooks["internal/update"] ??= new DisposableList())[options.prepend ? "unshift" : "push"](listener);
626
- });
627
- this.on("internal/update", function(config, noSave, next) {
628
- const cbs = [...this._hooks["internal/update"] || []];
629
- const _next = () => {
630
- return (cbs.shift() ?? next).call(this, config, noSave, _next);
631
- };
632
- return _next();
633
- }, {
634
- global: true,
635
- prepend: true
636
- });
637
- }
638
- /**
639
- * Resolve listeners for one dispatch and apply context filtering.
640
- *
641
- * @param type — the dispatch mode, reported on `internal/dispatch`.
642
- * @param args — the raw dispatch arguments; consumed up to the event name.
643
- * @returns the matching listener callbacks, bound to the dispatch `this`.
644
- */
645
- dispatch(type, args) {
646
- const thisArg = typeof args[0] === "object" || typeof args[0] === "function" ? args.shift() : null;
647
- const name = args.shift();
648
- if (!name.startsWith("internal/")) this.emit("internal/dispatch", type, name, args, thisArg);
649
- const filter = thisArg?.[Context.filter];
650
- return (this._hooks[name] || []).filter((hook) => hook.global || !filter || filter.call(thisArg, hook.ctx)).map((hook) => hook.callback.bind(thisArg));
651
- }
652
- /**
653
- * Run listeners concurrently and wait for all of them.
654
- *
655
- * @param args — optional `this`, the event name, then listener arguments.
656
- * @returns a promise resolving once every listener has settled.
657
- */
658
- async parallel(...args) {
659
- const errors = (await Promise.allSettled(this.dispatch("emit", args).map(async (cb) => cb(...args)))).filter((result) => result.status === "rejected");
660
- if (errors.length) throw new AggregateError(errors.map((error) => error.reason));
661
- }
662
- /**
663
- * Run listeners synchronously without waiting for returned promises.
664
- *
665
- * @param args — optional `this`, the event name, then listener arguments.
666
- */
667
- emit(...args) {
668
- this.dispatch("emit", args).map((cb) => cb(...args));
669
- }
670
- /**
671
- * Run listeners in order, awaiting each, until one returns a bail value.
672
- *
673
- * @param args — optional `this`, the event name, then listener arguments.
674
- * @returns the first bail value (see {@link isBailed}), if any.
675
- */
676
- async serial(...args) {
677
- for (const cb of this.dispatch("serial", args)) {
678
- const result = await cb(...args);
679
- if (isBailed(result)) return result;
680
- }
681
- }
682
- /**
683
- * Run listeners synchronously until one returns a bail value.
684
- *
685
- * @param args — optional `this`, the event name, then listener arguments.
686
- * @returns the first bail value (see {@link isBailed}), if any.
687
- */
688
- bail(...args) {
689
- for (const cb of this.dispatch("bail", args)) {
690
- const result = cb(...args);
691
- if (isBailed(result)) return result;
692
- }
693
- }
694
- /**
695
- * Compose listeners around the final `next` callback.
696
- *
697
- * The last dispatch argument is treated as the innermost `next`. Listeners
698
- * run outermost-first; a listener that does not call `next()` vetoes the
699
- * rest of the chain, including the built-in behavior.
700
- *
701
- * @param args — optional `this`, the event name, listener arguments, then `next`.
702
- * @returns the outermost listener's return value.
703
- */
704
- waterfall(...args) {
705
- const cbs = this.dispatch("waterfall", args);
706
- const inner = args.pop();
707
- const next = () => {
708
- return (cbs.shift() ?? inner)(...args);
709
- };
710
- args.push(next);
711
- return next();
712
- }
713
- /**
714
- * Store a listener record as an effect on the current fiber.
715
- *
716
- * @param label — effect label shown in fiber diagnostics.
717
- * @param hooks — the listener list for one event.
718
- * @param callback — the listener to store.
719
- * @param options — placement and filtering options.
720
- * @returns a disposer that unregisters the listener.
721
- */
722
- register(label, hooks, callback, options) {
723
- const method = options.prepend ? "unshift" : "push";
724
- return this.ctx.fiber.effect(() => {
725
- hooks[method]({
726
- ctx: this.ctx,
727
- callback,
728
- ...options
729
- });
730
- return () => this.unregister(hooks, callback);
731
- }, label);
732
- }
733
- /**
734
- * Remove a stored listener record.
735
- *
736
- * @param hooks — the listener list for one event.
737
- * @param callback — the listener to remove.
738
- * @returns `true` if the listener was found and removed.
739
- */
740
- unregister(hooks, callback) {
741
- const index = hooks.findIndex((hook) => hook.callback === callback);
742
- if (index >= 0) {
743
- hooks.splice(index, 1);
744
- return true;
745
- }
746
- }
747
- /**
748
- * Register an event listener owned by the current fiber.
749
- *
750
- * The listener is removed automatically when the fiber unloads. Throws
751
- * `CordisError('INACTIVE_EFFECT')` if the fiber is already disposed.
752
- *
753
- * @param name — the event name to listen for.
754
- * @param listener — called with the dispatch arguments.
755
- * @param options — listener options; a boolean is shorthand for `prepend`.
756
- * @returns a disposer removing the listener; `true` if it was still registered.
757
- */
758
- on(name, listener, options) {
759
- if (typeof options !== "object") options = { prepend: options };
760
- this.ctx.fiber.assertActive();
761
- listener = this.ctx.reflect.bind(listener);
762
- const result = this.bail(this.ctx, "internal/listener", name, listener, options);
763
- if (result) return result;
764
- const hooks = this._hooks[name] ||= [];
765
- const label = `ctx.on(${typeof name === "string" ? JSON.stringify(name) : name.toString()})`;
766
- return this.register(label, hooks, listener, options);
767
- }
768
- /**
769
- * Register an event listener that disposes itself after the first call.
770
- *
771
- * @param name — the event name to listen for.
772
- * @param listener — called at most once with the dispatch arguments.
773
- * @param options — listener options; a boolean is shorthand for `prepend`.
774
- * @returns a disposer removing the listener; `true` if it was still registered.
775
- */
776
- once(name, listener, options) {
777
- const dispose = this.on(name, function(...args) {
778
- dispose();
779
- return listener.apply(this, args);
780
- }, options);
781
- return dispose;
782
- }
783
- };
784
- /** Built-in placeholder formatters used by `Logger.format()`. */
785
- const defaultFormatters = {
786
- s: (value) => String(value),
787
- d: (value) => Math.trunc(Number(value)),
788
- i: (value) => Math.trunc(Number(value)),
789
- f: (value) => Number(value),
790
- o: (value) => JSON.stringify(value),
791
- O: (value) => JSON.stringify(value),
792
- c: () => "",
793
- C: (value, exporter, message) => {
794
- return Logger.color(exporter, Logger.code(message.name, exporter.colors), value);
795
- }
796
- };
797
- function isAggregateError(error) {
798
- return error instanceof Error && Array.isArray(error["errors"]);
799
- }
800
- /** Logger facade for one named subsystem. */
801
- var Logger = class {
802
- service;
803
- static color(exporter, code, value, decoration = "") {
804
- if (!exporter.colors) return "" + value;
805
- return `\u001b[3${code < 8 ? code : "8;5;" + code}${exporter.colors >= 2 ? decoration : ""}m${value}\u001b[0m`;
806
- }
807
- static code(name, level) {
808
- let hash = 0;
809
- for (let i = 0; i < name.length; i++) {
810
- hash = (hash << 3) - hash + name.charCodeAt(i) + 13;
811
- hash |= 0;
812
- }
813
- const colors = !level ? [] : level >= 2 ? c256 : c16;
814
- return colors[Math.abs(hash) % colors.length];
815
- }
816
- static format(exporter, message) {
817
- const args = message.args.slice();
818
- if (args[0] instanceof Error) {
819
- args[0] = args[0].stack || args[0].message;
820
- args.unshift("%s");
821
- } else if (typeof args[0] !== "string") args.unshift("%o");
822
- let format = args.shift();
823
- format = format.replace(/%([a-zA-Z%])/g, (match, char) => {
824
- if (match === "%%") return "%";
825
- const formatter = exporter.formatters?.[char] ?? defaultFormatters[char];
826
- if (typeof formatter === "function") return formatter(args.shift(), exporter, message);
827
- return match;
828
- });
829
- const oFormatter = exporter.formatters?.o ?? defaultFormatters.o;
830
- for (let arg of args) {
831
- if (typeof arg === "object" && arg) arg = oFormatter(arg, exporter, message);
832
- format += " " + arg;
833
- }
834
- const { maxLength = 10240 } = exporter;
835
- return format.split(/\r?\n/g).map((line) => {
836
- return line.slice(0, maxLength) + (line.length > maxLength ? "..." : "");
837
- }).join("\n");
838
- }
839
- constructor(options, service) {
840
- this.service = service;
841
- Object.assign(this, options);
842
- this.error = this._method("error", 0);
843
- this.info = this._method("info", 1);
844
- this.warn = this._method("warn", 2);
845
- this.debug = this._method("debug", 3);
846
- }
847
- _method(type, level) {
848
- return (...args) => {
849
- if (args.length === 1 && args[0] instanceof Error) {
850
- if (args[0].cause) this[type](args[0].cause);
851
- else if (isAggregateError(args[0])) {
852
- args[0].errors.forEach((error) => this[type](error));
853
- return;
854
- }
855
- }
856
- const sn = ++this.service._snMessage;
857
- const ts = Date.now();
858
- for (const exporter of this.service.exporters.values()) {
859
- if ((exporter.levels?.[this.name] ?? exporter.levels?.default ?? this.level ?? 1) < level) continue;
860
- const message = {
861
- sn,
862
- ts,
863
- type,
864
- level,
865
- name: this.name,
866
- ...this.meta,
867
- args
868
- };
869
- exporter.export(message);
870
- }
871
- };
872
- }
873
- };
874
- /** ANSI 16-color palette indexes used for logger name coloring. */
875
- const c16 = [
876
- 6,
877
- 2,
878
- 3,
879
- 4,
880
- 5,
881
- 1
882
- ];
883
- /** ANSI 256-color palette indexes used for logger name coloring. */
884
- const c256 = [
885
- 20,
886
- 21,
887
- 26,
888
- 27,
889
- 32,
890
- 33,
891
- 38,
892
- 39,
893
- 40,
894
- 41,
895
- 42,
896
- 43,
897
- 44,
898
- 45,
899
- 56,
900
- 57,
901
- 62,
902
- 63,
903
- 68,
904
- 69,
905
- 74,
906
- 75,
907
- 76,
908
- 77,
909
- 78,
910
- 79,
911
- 80,
912
- 81,
913
- 92,
914
- 93,
915
- 98,
916
- 99,
917
- 112,
918
- 113,
919
- 129,
920
- 134,
921
- 135,
922
- 148,
923
- 149,
924
- 160,
925
- 161,
926
- 162,
927
- 163,
928
- 164,
929
- 165,
930
- 166,
931
- 167,
932
- 168,
933
- 169,
934
- 170,
935
- 171,
936
- 172,
937
- 173,
938
- 178,
939
- 179,
940
- 184,
941
- 185,
942
- 196,
943
- 197,
944
- 198,
945
- 199,
946
- 200,
947
- 201,
948
- 202,
949
- 203,
950
- 204,
951
- 205,
952
- 206,
953
- 207,
954
- 208,
955
- 209,
956
- 214,
957
- 215,
958
- 220,
959
- 221
960
- ];
961
- /**
962
- * Built-in logging service.
963
- *
964
- * Call `ctx.logger()` to create a named logger, or call `ctx.logger.info()`
965
- * directly to log with the current fiber-derived name.
966
- */
967
- var LoggerService = class LoggerService {
968
- bufferSize = 1e3;
969
- buffer = [];
970
- ctx;
971
- _snMessage = 0;
972
- _snExporter = 0;
973
- exporters = /* @__PURE__ */ new Map();
974
- constructor(ctx) {
975
- const tracker = {
976
- property: "ctx",
977
- noShadow: true
978
- };
979
- const self = createCallable("logger", joinPrototype(Object.getPrototypeOf(this), Function.prototype), tracker);
980
- Object.assign(self, this);
981
- self.ctx = ctx;
982
- defineProperty(self, symbols.tracker, tracker);
983
- self.exporter({
984
- colors: 3,
985
- export: (message) => {
986
- self.buffer.push(message);
987
- if (self.buffer.length > self.bufferSize) self.buffer = self.buffer.slice(-self.bufferSize);
988
- }
989
- });
990
- return self;
991
- }
992
- /**
993
- * Register an exporter and dispose it with the current fiber.
994
- *
995
- * @param exporter — the sink that receives structured log messages.
996
- * @returns a disposer that removes the exporter.
997
- */
998
- exporter(exporter) {
999
- return this.ctx.effect(() => {
1000
- const id = ++this._snExporter;
1001
- this.exporters.set(id, exporter);
1002
- return () => this.exporters.delete(id);
1003
- }, "ctx.logger.exporter()");
1004
- }
1005
- _resolveConfig() {
1006
- let intercept = this.ctx[symbols.intercept];
1007
- const configs = [];
1008
- while ("logger" in intercept) {
1009
- if (Object.hasOwn(intercept, "logger")) configs.unshift(intercept["logger"]);
1010
- intercept = Object.getPrototypeOf(intercept);
1011
- }
1012
- return Object.assign({}, ...configs);
1013
- }
1014
- [symbols.invoke](name) {
1015
- const config = this._resolveConfig();
1016
- const fiber = (this.ctx[symbols.shadow] ?? this.ctx).fiber;
1017
- name ??= config.name;
1018
- name ??= hyphenate(fiber.name);
1019
- return new Logger({
1020
- name,
1021
- level: config.level,
1022
- meta: { fiber: new WeakRef(fiber) }
1023
- }, this);
1024
- }
1025
- static {
1026
- for (const type of [
1027
- "error",
1028
- "info",
1029
- "warn",
1030
- "debug"
1031
- ]) LoggerService.prototype[type] = function(...args) {
1032
- return this()[type](...args);
1033
- };
1034
- }
1035
- };
1036
- function enhanceError(error) {
1037
- const lines = error.stack.split("\n");
1038
- lines.splice(0, 2, `Error: ${error.message}`);
1039
- error.stack = lines.join("\n");
1040
- return error;
1041
- }
1042
- const RESERVED_WORDS = ["prototype", "then"];
1043
- function isSpecialProperty(prop) {
1044
- return typeof prop === "symbol" || RESERVED_WORDS.includes(prop) || parseInt(prop).toString() === prop || prop.startsWith("_");
1045
- }
1046
- /**
1047
- * Reflection and service-resolution layer installed as `ctx.reflect`.
1048
- *
1049
- * This service powers the context proxy, service registration, accessors, and
1050
- * the mixins that expose core service methods directly on `ctx`.
1051
- */
1052
- var ReflectService = class {
1053
- ctx;
1054
- /** Proxy traps implementing service resolution for every context object. */
1055
- static handler = {
1056
- get: (target, prop, ctx) => {
1057
- if (isSpecialProperty(prop)) return Reflect.get(target, prop, ctx);
1058
- if (Reflect.has(target, prop)) return getTraceable(ctx, Reflect.get(target, prop, ctx));
1059
- const error = /* @__PURE__ */ new Error(`cannot get property "${prop}" without inject`);
1060
- try {
1061
- const def = target.reflect.props[prop];
1062
- if (def?.type === "accessor") return def.get.call(ctx, ctx[symbols.receiver], error);
1063
- if (!ctx.fiber.runtime) return ctx.reflect.get(prop, false);
1064
- return ctx.events.waterfall("internal/get", ctx, prop, error, () => {
1065
- const key = target[symbols.isolate][prop];
1066
- let fiber = (ctx[symbols.shadow] ?? ctx).fiber;
1067
- while (true) {
1068
- const impl = fiber.store?.[prop];
1069
- if (impl) return getTraceable(ctx, impl.value);
1070
- if (prop in fiber.inject) {
1071
- error.message = `cannot get required service "${prop}" in inactive context`;
1072
- throw error;
1073
- }
1074
- if (!fiber.runtime) throw error;
1075
- if (fiber.parent[symbols.isolate][prop] !== key) throw error;
1076
- fiber = fiber.parent.fiber;
1077
- }
1078
- });
1079
- } catch (e) {
1080
- throw e === error ? enhanceError(e) : e;
1081
- }
1082
- },
1083
- set: (target, prop, value, ctx) => {
1084
- if (isSpecialProperty(prop)) return Reflect.set(target, prop, value, ctx);
1085
- const error = /* @__PURE__ */ new Error(`cannot set property "${prop}" without provide`);
1086
- const def = target.reflect.props[prop];
1087
- if (!def) {
1088
- if (!ctx.fiber.runtime) return Reflect.set(target, prop, value, ctx);
1089
- throw enhanceError(error);
1090
- }
1091
- try {
1092
- if (def.type === "accessor") {
1093
- if (!def.set) return false;
1094
- return def.set.call(ctx, value, ctx[symbols.receiver], error);
1095
- }
1096
- return ctx.events.waterfall("internal/set", ctx, prop, value, error, () => {
1097
- return ctx.reflect.set(prop, value, error);
1098
- });
1099
- } catch (e) {
1100
- throw e === error ? enhanceError(e) : e;
1101
- }
1102
- },
1103
- has: (target, prop) => {
1104
- if (isSpecialProperty(prop)) return Reflect.has(target, prop);
1105
- if (Reflect.has(target, prop)) return true;
1106
- return !!target.reflect.props[prop];
1107
- }
1108
- };
1109
- /** Service implementations, keyed by isolation label. */
1110
- store = Object.create(null);
1111
- /** Declared context properties (services and accessors), by name. */
1112
- props = Object.create(null);
1113
- constructor(ctx) {
1114
- this.ctx = ctx;
1115
- defineProperty(this, symbols.tracker, {
1116
- property: "ctx",
1117
- noShadow: true
1118
- });
1119
- this.mixin("reflect", [
1120
- "get",
1121
- "set",
1122
- "provide",
1123
- "accessor",
1124
- "mixin"
1125
- ]);
1126
- this.mixin("fiber", ["runtime", "effect"]);
1127
- this.mixin("registry", ["inject", "plugin"]);
1128
- this.mixin("events", [
1129
- "on",
1130
- "once",
1131
- "parallel",
1132
- "emit",
1133
- "serial",
1134
- "bail",
1135
- "waterfall"
1136
- ]);
1137
- }
1138
- /**
1139
- * Read a service from the store without the inject requirement.
1140
- *
1141
- * @param name — the service name.
1142
- * @param strict — when `true`, only return implementations whose providing
1143
- * fiber is currently active.
1144
- * @returns the service value, or `undefined` when not (yet) provided.
1145
- */
1146
- get(name, strict = true) {
1147
- return getTraceable(this.ctx, this._getImpl(name, strict)?.value);
1148
- }
1149
- _getImpl(name, strict = true) {
1150
- const key = this.ctx[symbols.isolate][name];
1151
- const impl = key && this.store[key];
1152
- if (!impl) return;
1153
- if (strict && impl.fiber.state !== 2) return;
1154
- return impl;
1155
- }
1156
- /**
1157
- * Overwrite a provided service's value.
1158
- *
1159
- * @param name — the service name.
1160
- * @param value — the new service value.
1161
- * @param error — carrier for the caller stack in diagnostics.
1162
- * @returns `true` on success.
1163
- * @throws when `name` was never provided, or was provided by another fiber.
1164
- */
1165
- set(name, value, error) {
1166
- const key = this.ctx[symbols.isolate][name];
1167
- const impl = this.store[key];
1168
- if (!impl) throw new Error(`cannot set property "${name}" without provide`);
1169
- if (impl.fiber !== this.ctx.fiber) throw new Error(`cannot set property "${name}" in multiple fibers`);
1170
- impl.value = value;
1171
- return true;
1172
- }
1173
- /**
1174
- * Register a service implementation owned by the current fiber.
1175
- *
1176
- * See the `ctx.provide()` overload above for the full contract.
1177
- *
1178
- * @param name — the service name.
1179
- * @param value — the service value.
1180
- * @param check — optional availability predicate for dependents.
1181
- * @returns a disposer that unregisters the service.
1182
- */
1183
- provide(name, value, check) {
1184
- return this.ctx.fiber.effect(() => {
1185
- if (!this.props[name]) this.props[name] ??= { type: "service" };
1186
- else if (this.props[name].type !== "service") throw new Error(`property "${name}" is already declared as ${this.props[name].type}`);
1187
- this.props[name] = { type: "service" };
1188
- this.ctx.root[symbols.isolate][name] ??= Symbol(name);
1189
- const key = this.ctx[symbols.isolate][name];
1190
- const impl = {
1191
- name,
1192
- value,
1193
- fiber: this.ctx.fiber,
1194
- check
1195
- };
1196
- if (this.store[key]) throw new Error(`service "${name}" has been registered at <${this.store[key].fiber.name}>`);
1197
- this.store[key] = impl;
1198
- this.ctx.fiber.store[name] = impl;
1199
- if (this.ctx.fiber.state === 2) this.notify([name]);
1200
- return async () => {
1201
- delete this.store[key];
1202
- const fibers = this.notify([name]);
1203
- await Promise.allSettled(fibers.map((fiber) => fiber.await()));
1204
- delete this.ctx.fiber.store[name];
1205
- };
1206
- }, `ctx.provide(${JSON.stringify(name)})`);
1207
- }
1208
- /**
1209
- * Re-evaluate every fiber that requires one of the given services.
1210
- *
1211
- * @param names — the service names that changed.
1212
- * @param filter — restricts notification to matching isolation scopes.
1213
- * @returns the fibers whose dependency state was refreshed.
1214
- */
1215
- notify(names, filter = (ctx, name) => ctx[symbols.isolate][name] === this.ctx[symbols.isolate][name]) {
1216
- const fibers = [];
1217
- for (const runtime of this.ctx.registry.values()) for (const fiber of runtime.fibers) {
1218
- let hasUpdate = false;
1219
- for (const name of names) {
1220
- if (!(name in fiber.inject)) continue;
1221
- if (!filter(fiber.ctx, name)) continue;
1222
- hasUpdate = true;
1223
- fiber._checkImpl(name);
1224
- }
1225
- if (!hasUpdate) continue;
1226
- fiber._refresh();
1227
- fibers.push(fiber);
1228
- }
1229
- for (const name of names) {
1230
- const self = Object.create(this.ctx);
1231
- self[symbols.filter] = (target) => filter(target, name);
1232
- this.ctx.events.emit(self, "internal/service", name, this._getImpl(name, false)?.value);
1233
- }
1234
- return fibers;
1235
- }
1236
- /**
1237
- * Define a computed context property backed by get/set hooks.
1238
- *
1239
- * @param name — the context property name.
1240
- * @param options — the `get` hook and optional `set` hook.
1241
- * @returns a disposer that removes the accessor.
1242
- */
1243
- accessor(name, options) {
1244
- return this.ctx.fiber.effect(() => {
1245
- if (name in this.props) throw new Error(`property "${name}" is already declared as ${this.props[name].type}`);
1246
- this.props[name] = {
1247
- type: "accessor",
1248
- ...options
1249
- };
1250
- return () => delete this.props[name];
1251
- }, `ctx.accessor(${JSON.stringify(name)})`);
1252
- }
1253
- /**
1254
- * Expose selected members of a service directly on `ctx`.
1255
- *
1256
- * See the `ctx.mixin()` overload above for the full contract.
1257
- *
1258
- * @param source — a context property name or a source object.
1259
- * @param mixins — keys to forward, or a source-key → ctx-key map.
1260
- * @returns a disposer that removes all created accessors.
1261
- */
1262
- mixin(source, mixins) {
1263
- const self = this;
1264
- return this.ctx.fiber.effect(function* () {
1265
- const entries = Array.isArray(mixins) ? mixins.map((key) => [key, key]) : Object.entries(mixins);
1266
- const getTarget = (ctx, error) => {
1267
- return ctx[source];
1268
- };
1269
- for (const [key, value] of entries) yield self.accessor(value, {
1270
- get(receiver, error) {
1271
- const service = getTarget(this, error);
1272
- if (isNullable(service)) return service;
1273
- const mixin = receiver ? withProps(receiver, service) : service;
1274
- const value = Reflect.get(service, key, mixin);
1275
- if (typeof value !== "function") return value;
1276
- return value.bind(mixin ?? service);
1277
- },
1278
- set(value, receiver, error) {
1279
- const service = getTarget(this, error);
1280
- const mixin = receiver ? withProps(receiver, service) : service;
1281
- return Reflect.set(service, key, value, mixin);
1282
- }
1283
- });
1284
- }, `ctx.mixin(${JSON.stringify(source)})`);
1285
- }
1286
- /**
1287
- * Attach this context's tracing wrapper to a value.
1288
- *
1289
- * @param value — the value to wrap.
1290
- * @returns the traceable wrapper (or the value itself when not applicable).
1291
- */
1292
- trace(value) {
1293
- return getTraceable(this.ctx, value);
1294
- }
1295
- /**
1296
- * Wrap a callback so calls trace `this` and arguments to this context.
1297
- *
1298
- * @param callback — the function to wrap.
1299
- * @returns a proxy delegating to `callback` with traced values.
1300
- */
1301
- bind(callback) {
1302
- return new Proxy(callback, {
1303
- apply: (target, thisArg, args) => {
1304
- return Reflect.apply(target, this.trace(thisArg), args.map((arg) => this.trace(arg)));
1305
- },
1306
- construct: (target, args, newTarget) => {
1307
- return Reflect.construct(target, args.map((arg) => this.trace(arg)), newTarget);
1308
- }
1309
- });
1310
- }
1311
- };
1312
- const kValidationError = Symbol.for("ValidationError");
1313
- /** Error raised when plugin configuration fails standard-schema validation. */
1314
- var ValidationError = class extends TypeError {
1315
- name = "ValidationError";
1316
- /**
1317
- * Build the aggregated message from schema issues.
1318
- *
1319
- * @param issues — the standard-schema issues, one message line each.
1320
- */
1321
- constructor(issues) {
1322
- super(`invalid config:\n` + issues.map((issue) => {
1323
- if (issue.path) return ` - ${issue.message} (at ${issue.path.join(".")})`;
1324
- else return ` - ${issue.message}`;
1325
- }).join("\n"));
1326
- }
1327
- };
1328
- Object.defineProperty(ValidationError.prototype, kValidationError, { value: true });
1329
- /**
1330
- * Validate and normalize config for a plugin runtime before it starts.
1331
- *
1332
- * @param runtime — the plugin runtime whose `Config` schema to apply.
1333
- * @param config — the raw user config.
1334
- * @returns the validated config, or `config` unchanged if the runtime has no schema.
1335
- * @throws {ValidationError} when validation reports issues.
1336
- */
1337
- function resolveConfig(runtime, config) {
1338
- if (!runtime.Config) return config;
1339
- const result = runtime.Config["~standard"].validate(config);
1340
- if ("then" in result) throw new TypeError("Async config validation is not supported");
1341
- if (result.issues) throw new ValidationError(result.issues);
1342
- else return result.value;
1343
- }
1344
- const effectInertia = /* @__PURE__ */ new WeakMap();
1345
- function runDisposable(dispose) {
1346
- const result = dispose();
1347
- return effectInertia.get(dispose)?.() ?? result;
1348
- }
1349
- /** Notify plugin teardown without allowing one observer to break ownership cleanup. */
1350
- function emitPluginDisposed(context, fiber) {
1351
- const args = ["internal/plugin", fiber];
1352
- let callbacks;
1353
- try {
1354
- callbacks = context.events.dispatch("emit", args);
1355
- } catch (error) {
1356
- context.logger.error(error);
1357
- return;
1358
- }
1359
- for (const callback of callbacks) try {
1360
- const returned = callback(...args);
1361
- Promise.resolve(returned).catch((error) => context.logger.error(error));
1362
- } catch (error) {
1363
- context.logger.error(error);
1364
- }
1365
- }
1366
- /** Framework error with a stable machine-readable code. */
1367
- var CordisError = class CordisError extends Error {
1368
- code;
1369
- /**
1370
- * @param code — the stable error code; also the default message.
1371
- * @param message — optional human-readable override.
1372
- */
1373
- constructor(code, message) {
1374
- super(message ?? CordisError.Code[code]);
1375
- this.code = code;
1376
- }
1377
- };
1378
- /** Cordis error code definitions. */
1379
- (function(CordisError) {
1380
- CordisError.Code = { INACTIVE_EFFECT: "cannot create effect on inactive context" };
1381
- })(CordisError || (CordisError = {}));
1382
- const INACTIVE = "__INACTIVE__";
1383
- /**
1384
- * Runtime instance of one plugin application.
1385
- *
1386
- * A fiber tracks dependency state, validated config, lifecycle effects, and
1387
- * cleanup for the plugin context returned by `ctx.plugin()`.
1388
- */
1389
- var Fiber = class {
1390
- parent;
1391
- inject;
1392
- runtime;
1393
- /** Unique id within the registry; 0 for the root fiber, `null` once disposed. */
1394
- uid;
1395
- /** The context this fiber's plugin runs in (extends the parent context). */
1396
- ctx;
1397
- /** The validated plugin config (updated by `update()`). */
1398
- config;
1399
- /** The raw plugin config, re-resolved before each activation. */
1400
- _config;
1401
- /** Current lifecycle state; transitions emit `internal/status`. */
1402
- state = 0;
1403
- /** Dispose this fiber: unload the plugin, then settle once cleanup finished. */
1404
- dispose;
1405
- /** Snapshot of required service implementations while loaded; `undefined` otherwise. */
1406
- store;
1407
- /** The in-flight load/unload transition, if one is currently running. */
1408
- inertia;
1409
- _hooks = Object.create(null);
1410
- _disposables = new DisposableList();
1411
- context;
1412
- _error;
1413
- _runner;
1414
- _store = Object.create(null);
1415
- /**
1416
- * Create a fiber. Plugin authors normally obtain fibers from `ctx.plugin()`
1417
- * rather than constructing them directly.
1418
- *
1419
- * @param parent — the context the plugin was loaded from.
1420
- * @param config — raw config, validated against the runtime's schema.
1421
- * @param inject — resolved dependency map (service name → intercept config).
1422
- * @param runtime — the shared plugin runtime, or `null` for the root fiber.
1423
- * @param getOuterStack — captures the caller stack for effect diagnostics.
1424
- */
1425
- constructor(parent, config, inject, runtime, getOuterStack) {
1426
- this.parent = parent;
1427
- this.inject = inject;
1428
- this.runtime = runtime;
1429
- this._config = config;
1430
- const collect = (dispose) => {
1431
- this._disposables.push(dispose);
1432
- };
1433
- if (runtime) {
1434
- this.uid = parent.registry.counter;
1435
- this.ctx = this.context = parent.extend({ fiber: this });
1436
- const injectEntries = Object.entries(this.inject);
1437
- if (injectEntries.length) {
1438
- this.ctx[Context.intercept] = Object.create(parent[Context.intercept]);
1439
- for (const [name, config] of injectEntries) {
1440
- if (isNullable(config)) continue;
1441
- this.ctx[Context.intercept][name] = config;
1442
- }
1443
- }
1444
- this._runner = {
1445
- epoch: INACTIVE,
1446
- getOuterStack,
1447
- execute: function() {
1448
- if (isConstructor(runtime.callback)) {
1449
- const instance = new runtime.callback(this.ctx, this.config);
1450
- for (const hook of instance?.[symbols.initHooks] ?? []) hook();
1451
- return instance?.[symbols.init]?.();
1452
- } else return runtime.callback(this.ctx, this.config);
1453
- },
1454
- collect
1455
- };
1456
- this.dispose = parent.fiber.effect(() => {
1457
- const remove = runtime.fibers.push(this);
1458
- return async () => {
1459
- this.uid = null;
1460
- emitPluginDisposed(this.context, this);
1461
- if (this.ctx.registry.has(runtime.callback)) {
1462
- remove();
1463
- if (!runtime.fibers.length) this.ctx.registry.delete(runtime.callback);
1464
- }
1465
- this._setEpoch(INACTIVE);
1466
- if (!this.inertia) this._updateState(() => {
1467
- this.inertia = this._unload();
1468
- return 5;
1469
- });
1470
- while (this.inertia) await this.inertia;
1471
- };
1472
- }, "ctx.plugin()");
1473
- try {
1474
- this.context.emit("internal/plugin", this);
1475
- } catch (error) {
1476
- Promise.resolve(this.dispose()).catch((reason) => this.ctx.logger.error(reason));
1477
- throw error;
1478
- }
1479
- if (this.uid !== null && parent.fiber.state !== 5) {
1480
- for (const name of Object.keys(this.inject)) this._checkImpl(name);
1481
- this._refresh();
1482
- }
1483
- } else {
1484
- this.uid = 0;
1485
- this.ctx = this.context = parent;
1486
- this.state = 2;
1487
- this.store = Object.create(null);
1488
- this._runner = {
1489
- epoch: "",
1490
- getOuterStack,
1491
- execute: () => {},
1492
- collect
1493
- };
1494
- this.dispose = () => this.restart();
1495
- }
1496
- }
1497
- /** The plugin's display name, inherited from the nearest named ancestor, else `'root'`. */
1498
- get name() {
1499
- let fiber = this;
1500
- do {
1501
- if (fiber.runtime?.name) return fiber.runtime.name;
1502
- fiber = fiber.parent.fiber;
1503
- } while (fiber !== fiber.parent.fiber);
1504
- return "root";
1505
- }
1506
- /**
1507
- * Throw if the fiber has already been disposed.
1508
- *
1509
- * @returns nothing when the fiber is still active.
1510
- * @throws {CordisError} `INACTIVE_EFFECT` when the fiber's uid has been cleared.
1511
- */
1512
- assertActive() {
1513
- if (this.uid !== null) return;
1514
- throw new CordisError("INACTIVE_EFFECT");
1515
- }
1516
- _execute(runner) {
1517
- const oldEpoch = runner.epoch;
1518
- return composeError((info) => {
1519
- const safeCollect = (dispose) => {
1520
- if (typeof dispose === "function") runner.collect(dispose);
1521
- else if (!isNullable(dispose)) throw new TypeError("Invalid effect");
1522
- };
1523
- const effect = runner.execute.call(this);
1524
- if (typeof effect === "function") return runner.collect(effect);
1525
- else if (isNullable(effect)) {} else if (!isObject(effect)) throw new TypeError("Invalid effect");
1526
- else if ("then" in effect) return effect.then(safeCollect);
1527
- else if (Symbol.iterator in effect) {
1528
- info.error = /* @__PURE__ */ new Error();
1529
- const iter = effect[Symbol.iterator]();
1530
- while (true) {
1531
- const result = iter.next();
1532
- safeCollect(result.value);
1533
- if (result.done) return;
1534
- }
1535
- } else if (Symbol.asyncIterator in effect) {
1536
- const iter = effect[Symbol.asyncIterator]();
1537
- return (async () => {
1538
- await Promise.resolve();
1539
- info.error = /* @__PURE__ */ new Error();
1540
- while (true) {
1541
- if (runner.epoch !== oldEpoch) return;
1542
- const result = await iter.next();
1543
- safeCollect(result.value);
1544
- if (result.done) return;
1545
- }
1546
- })();
1547
- } else throw new TypeError("Invalid effect");
1548
- }, runner.getOuterStack);
1549
- }
1550
- effect(execute, label = "anonymous") {
1551
- this.assertActive();
1552
- if (this.state === 5) throw new CordisError("INACTIVE_EFFECT");
1553
- const disposables = [];
1554
- let disposing = false;
1555
- let disposalTask;
1556
- const dispose = () => {
1557
- if (disposing) return disposalTask;
1558
- disposing = true;
1559
- let task;
1560
- for (const disposable of disposables.splice(0).reverse()) if (task) task = task.then(() => runDisposable(disposable));
1561
- else {
1562
- const result = runDisposable(disposable);
1563
- if (isObject(result) && "then" in result) task = result;
1564
- }
1565
- return disposalTask = task;
1566
- };
1567
- const meta = {
1568
- label,
1569
- children: []
1570
- };
1571
- const runner = {
1572
- execute,
1573
- epoch: true,
1574
- collect: (dispose) => {
1575
- disposables.push(dispose);
1576
- this._disposables.delete(dispose);
1577
- if (dispose[symbols.effect]) meta.children.push(dispose[symbols.effect]);
1578
- },
1579
- getOuterStack: buildOuterStack()
1580
- };
1581
- let task;
1582
- let executing = true;
1583
- let resolveSetup;
1584
- let rejectSetup;
1585
- let setupBarrier;
1586
- let setupFailed = false;
1587
- let inFlight;
1588
- let removeWrapper = () => false;
1589
- const waitForSetup = () => {
1590
- setupBarrier ??= new Promise((resolve, reject) => {
1591
- resolveSetup = resolve;
1592
- rejectSetup = reject;
1593
- });
1594
- return setupBarrier;
1595
- };
1596
- const disposeAfter = (setup) => {
1597
- return Promise.resolve(setup).then(() => dispose(), async (reason) => {
1598
- await dispose();
1599
- throw reason;
1600
- });
1601
- };
1602
- const finalizeDisposal = (callback) => {
1603
- let result;
1604
- try {
1605
- result = callback();
1606
- } catch (error) {
1607
- removeWrapper();
1608
- throw error;
1609
- }
1610
- if (isObject(result) && "then" in result) {
1611
- const pending = Promise.resolve(result).finally(() => {
1612
- removeWrapper();
1613
- if (inFlight === pending) inFlight = void 0;
1614
- });
1615
- return inFlight = pending;
1616
- }
1617
- removeWrapper();
1618
- return result;
1619
- };
1620
- const wrapper = defineProperty(() => {
1621
- if (!runner.epoch) return setupFailed ? inFlight : void 0;
1622
- runner.epoch = false;
1623
- return finalizeDisposal(() => {
1624
- if (executing) return disposeAfter(waitForSetup());
1625
- return task ? disposeAfter(task) : dispose();
1626
- });
1627
- }, symbols.effect, meta);
1628
- effectInertia.set(wrapper, () => inFlight);
1629
- removeWrapper = this._disposables.push(wrapper);
1630
- try {
1631
- task = this._execute(runner);
1632
- } catch (reason) {
1633
- executing = false;
1634
- setupFailed = true;
1635
- runner.epoch = false;
1636
- let cleanup;
1637
- try {
1638
- cleanup = finalizeDisposal(dispose);
1639
- } finally {
1640
- rejectSetup?.(reason);
1641
- }
1642
- if (isObject(cleanup) && "then" in cleanup) cleanup.catch((error) => this.ctx.logger.error(error));
1643
- throw reason;
1644
- }
1645
- executing = false;
1646
- if (setupBarrier) Promise.resolve(task).then(resolveSetup, rejectSetup);
1647
- task?.catch(() => {
1648
- if (!runner.epoch) return dispose();
1649
- return finalizeDisposal(dispose);
1650
- }).catch((error) => this.ctx.logger.error(error));
1651
- const disposeAsync = () => {
1652
- if (!runner.epoch) return;
1653
- runner.epoch = false;
1654
- return finalizeDisposal(dispose);
1655
- };
1656
- wrapper.then = async (onFulfilled, onRejected) => {
1657
- return Promise.resolve(task).then(() => disposeAsync).then(onFulfilled, onRejected);
1658
- };
1659
- return wrapper;
1660
- }
1661
- /**
1662
- * Return metadata for currently registered effects.
1663
- *
1664
- * @returns one {@link EffectMeta} tree per labeled live effect.
1665
- */
1666
- getEffects() {
1667
- return [...this._disposables].map((dispose) => dispose[symbols.effect]).filter(Boolean);
1668
- }
1669
- _getState() {
1670
- if (this.uid === null) return 4;
1671
- if (this._error) return 3;
1672
- if (this._runner.epoch !== INACTIVE) return 2;
1673
- return 0;
1674
- }
1675
- _updateState(callback) {
1676
- const oldState = this.state;
1677
- this.state = callback() ?? this._getState();
1678
- if (oldState === this.state) return;
1679
- this.context.emit("internal/status", this, oldState);
1680
- if (oldState !== 2 && this.state !== 2) return;
1681
- for (const key of Reflect.ownKeys(this.ctx.reflect.store)) {
1682
- const impl = this.ctx.reflect.store[key];
1683
- if (impl.fiber !== this) continue;
1684
- this.ctx.reflect.notify([impl.name]);
1685
- }
1686
- }
1687
- _checkImpl(name) {
1688
- const impl = this.ctx.reflect._getImpl(name, true);
1689
- if (!impl) return delete this._store[name];
1690
- try {
1691
- if (impl.check && !impl.check.call(getTraceable(this.ctx, impl.value))) return delete this._store[name];
1692
- } catch (error) {
1693
- impl.fiber.ctx.logger.error(error);
1694
- return delete this._store[name];
1695
- }
1696
- this._store[name] = impl;
1697
- }
1698
- _refresh() {
1699
- let epoch = false;
1700
- epoch = "";
1701
- for (const name of Object.keys(this.inject)) {
1702
- const impl = this._store[name];
1703
- if (!impl) {
1704
- epoch = INACTIVE;
1705
- break;
1706
- }
1707
- epoch += ":" + impl.fiber.uid;
1708
- }
1709
- this._setEpoch(epoch);
1710
- }
1711
- _setEpoch(epoch) {
1712
- const oldEpoch = this._runner.epoch;
1713
- if (epoch === oldEpoch) return;
1714
- this._runner.epoch = epoch;
1715
- if (this.inertia) return;
1716
- this._updateState(() => {
1717
- if (epoch !== INACTIVE && oldEpoch === INACTIVE) {
1718
- this.inertia = this._reload();
1719
- return 1;
1720
- } else {
1721
- this.inertia = this._unload();
1722
- return 5;
1723
- }
1724
- });
1725
- }
1726
- _resolveConfig(config) {
1727
- config = this.context.waterfall(this, "internal/config", config, () => config);
1728
- return this.runtime ? resolveConfig(this.runtime, config) : config;
1729
- }
1730
- async _reload() {
1731
- this.store = { ...this._store };
1732
- const oldEpoch = this._runner.epoch;
1733
- try {
1734
- await Promise.resolve();
1735
- if (this._runner.epoch === oldEpoch) {
1736
- this.config = this._resolveConfig(this._config);
1737
- await this._execute(this._runner);
1738
- this._error = void 0;
1739
- }
1740
- } catch (reason) {
1741
- this.ctx.logger.error(reason);
1742
- this._error = reason;
1743
- this._runner.epoch = INACTIVE;
1744
- }
1745
- this._updateState(() => {
1746
- if (this._runner.epoch === oldEpoch) this.inertia = void 0;
1747
- else {
1748
- this.inertia = this._unload();
1749
- return 5;
1750
- }
1751
- });
1752
- }
1753
- async _unload() {
1754
- await Promise.all(this._disposables.clear().map(async (dispose) => {
1755
- try {
1756
- await composeError(async (info) => {
1757
- await Promise.resolve();
1758
- info.error = /* @__PURE__ */ new Error();
1759
- await runDisposable(dispose);
1760
- }, this._runner.getOuterStack);
1761
- } catch (reason) {
1762
- this.ctx.logger.error(reason);
1763
- }
1764
- }));
1765
- this.store = void 0;
1766
- this._updateState(() => {
1767
- if (this._runner.epoch === INACTIVE) this.inertia = void 0;
1768
- else {
1769
- this.inertia = this._reload();
1770
- return 1;
1771
- }
1772
- });
1773
- }
1774
- /**
1775
- * Wait for current lifecycle work and rethrow startup errors.
1776
- *
1777
- * @returns this fiber, once it has settled into a stable state.
1778
- * @throws the config-validation or plugin-startup error, if any.
1779
- */
1780
- async await() {
1781
- while (this.inertia) await this.inertia;
1782
- if (this._error) throw this._error;
1783
- return this;
1784
- }
1785
- /**
1786
- * Dispose and immediately reload this plugin with its current config.
1787
- *
1788
- * @returns a promise resolving once the reload settled.
1789
- * @throws {CordisError} `INACTIVE_EFFECT` when the fiber is already disposed.
1790
- */
1791
- async restart() {
1792
- this.assertActive();
1793
- this._setEpoch(INACTIVE);
1794
- this._refresh();
1795
- await this.await();
1796
- }
1797
- /**
1798
- * Validate and apply new config, then restart the plugin.
1799
- *
1800
- * Runs the `internal/update` waterfall first, so update hooks (and HMR)
1801
- * can veto or replace the restart.
1802
- *
1803
- * @param config — the new raw config; validated before anything restarts.
1804
- * @param noSave — hint for persistence hooks not to write the change back.
1805
- * @returns nothing; the restart runs behind the `internal/update` waterfall.
1806
- * @throws {ValidationError} when the new config fails validation.
1807
- */
1808
- update(config, noSave = false) {
1809
- this.assertActive();
1810
- this._config = config;
1811
- if (this.state !== 2) {
1812
- this._error = void 0;
1813
- this._setEpoch(INACTIVE);
1814
- this._refresh();
1815
- return;
1816
- }
1817
- config = this._resolveConfig(config);
1818
- this.context.waterfall(this, "internal/update", config, noSave, () => {
1819
- this.config = config;
1820
- this._error = void 0;
1821
- return this.restart();
1822
- });
1823
- }
1824
- };
1825
- function isApplicable(object) {
1826
- return object && typeof object === "object" && typeof object.apply === "function";
1827
- }
1828
- /**
1829
- * Decorator for declaring service dependencies on classes or class methods.
1830
- *
1831
- * On classes it contributes to the plugin's static `inject` map. On methods it
1832
- * delays the method call until the declared services are available.
1833
- */
1834
- /**
1835
- * @param name — the required service name.
1836
- * @param config — optional intercept config applied for that service.
1837
- * @returns the class or method decorator.
1838
- */
1839
- function Inject(name, config) {
1840
- return function(value, decorator) {
1841
- if (decorator.kind === "class") {
1842
- if (!Object.hasOwn(value, "inject")) {
1843
- defineProperty(value, "inject", Object.create(Object.getPrototypeOf(value).inject ?? null));
1844
- defineProperty(value.inject, symbols.checkProto, true);
1845
- }
1846
- value.inject[name] = config;
1847
- } else if (decorator.kind === "method") {
1848
- const inject = (value[symbols.metadata] ??= {}).inject ??= Object.create(null);
1849
- inject[name] = config;
1850
- decorator.addInitializer(function() {
1851
- const property = this[symbols.tracker]?.property;
1852
- (this[symbols.initHooks] ??= []).push(() => {
1853
- this.ctx.inject(inject, (ctx) => {
1854
- return value.call(property ? withProps(this, { [property]: ctx }) : this);
1855
- });
1856
- });
1857
- });
1858
- } else throw new Error("@Inject() can only be used on class or class methods");
1859
- };
1860
- }
1861
- /** Utilities for normalizing plugin dependency declarations. */
1862
- (function(Inject) {
1863
- /**
1864
- * Convert array/object/class-inherited inject metadata into a plain map.
1865
- *
1866
- * @param inject — the declaration to normalize; `null`/`undefined` add nothing.
1867
- * @param result — the map to fill (service name → intercept config or `null`).
1868
- * @returns `result`.
1869
- */
1870
- function resolve(inject, result = Object.create(null)) {
1871
- if (!inject) return result;
1872
- if (Array.isArray(inject)) for (const name of inject) result[name] = null;
1873
- else if (Reflect.has(inject, symbols.checkProto)) {
1874
- Object.assign(result, resolve(Object.getPrototypeOf(inject)));
1875
- for (const name of Object.keys(inject)) result[name] = inject[name] ?? null;
1876
- } else for (const name of Object.keys(inject)) result[name] = inject[name] ?? null;
1877
- return result;
1878
- }
1879
- Inject.resolve = resolve;
1880
- })(Inject || (Inject = {}));
1881
- /**
1882
- * Plugin registry installed as `ctx.registry` and mixed into every context.
1883
- *
1884
- * It normalizes plugin shapes, tracks plugin runtimes, starts fibers, and
1885
- * exposes map-like inspection over active plugin callbacks.
1886
- */
1887
- var RegistryService = class {
1888
- ctx;
1889
- _counter = 0;
1890
- _internal = /* @__PURE__ */ new Map();
1891
- constructor(ctx) {
1892
- this.ctx = ctx;
1893
- defineProperty(this, symbols.tracker, {
1894
- property: "ctx",
1895
- noShadow: true
1896
- });
1897
- }
1898
- /** Allocate the next fiber uid (increments on every read). */
1899
- get counter() {
1900
- return ++this._counter;
1901
- }
1902
- /** Number of registered plugin runtimes. */
1903
- get size() {
1904
- return this._internal.size;
1905
- }
1906
- /**
1907
- * Resolve a supported plugin shape to its executable callback.
1908
- *
1909
- * @param plugin — a function, class, or `{ apply }` object plugin.
1910
- * @returns the callback identifying the plugin, or `undefined` if invalid.
1911
- */
1912
- resolve(plugin) {
1913
- try {
1914
- if (typeof plugin === "function") return plugin;
1915
- if (isApplicable(plugin)) return plugin.apply;
1916
- } catch {}
1917
- }
1918
- /**
1919
- * Look up the runtime record for a plugin.
1920
- *
1921
- * @param plugin — any supported plugin shape.
1922
- * @returns the runtime, or `undefined` when the plugin is not registered.
1923
- */
1924
- get(plugin) {
1925
- const key = this.resolve(plugin);
1926
- return key && this._internal.get(key);
1927
- }
1928
- /**
1929
- * Check whether a plugin has a registered runtime.
1930
- *
1931
- * @param plugin — any supported plugin shape.
1932
- * @returns `true` when at least one fiber of the plugin exists.
1933
- */
1934
- has(plugin) {
1935
- const key = this.resolve(plugin);
1936
- return !!key && this._internal.has(key);
1937
- }
1938
- /**
1939
- * Dispose every running fiber for a plugin and remove its runtime record.
1940
- *
1941
- * @param plugin — any supported plugin shape.
1942
- * @returns the removed runtime, or `undefined` when none was registered.
1943
- */
1944
- delete(plugin) {
1945
- const key = this.resolve(plugin);
1946
- const runtime = key && this._internal.get(key);
1947
- if (!runtime) return;
1948
- this._internal.delete(key);
1949
- for (const fiber of runtime.fibers) fiber.dispose();
1950
- return runtime;
1951
- }
1952
- /** Iterate the registered plugin callbacks. */
1953
- keys() {
1954
- return this._internal.keys();
1955
- }
1956
- /** Iterate the registered plugin runtimes. */
1957
- values() {
1958
- return this._internal.values();
1959
- }
1960
- /** Iterate `[callback, runtime]` pairs. */
1961
- entries() {
1962
- return this._internal.entries();
1963
- }
1964
- /**
1965
- * Visit every registered runtime.
1966
- *
1967
- * @param callback — receives each runtime and its identifying callback.
1968
- */
1969
- forEach(callback) {
1970
- return this._internal.forEach(callback);
1971
- }
1972
- /**
1973
- * Start a callback once the requested dependencies are available.
1974
- *
1975
- * @param inject — required services, as an array or a name → config map.
1976
- * @param callback — plugin body called with `(ctx, config)`.
1977
- * @returns the fiber; awaiting it settles once loading finished.
1978
- */
1979
- inject(inject, callback) {
1980
- return this.plugin({
1981
- inject,
1982
- apply: callback,
1983
- name: callback.name
1984
- });
1985
- }
1986
- /**
1987
- * Start a plugin in the current context and return its fiber.
1988
- *
1989
- * Creates (or reuses) the plugin's runtime record, then starts a new fiber
1990
- * under the current context. Throws if `plugin` is not a supported shape or
1991
- * if the current fiber is already disposed.
1992
- *
1993
- * @param plugin — a function, class, or `{ apply }` object plugin.
1994
- * @param config — the plugin config, validated against its `Config` schema.
1995
- * @param getOuterStack — captures the caller stack for effect diagnostics.
1996
- * @returns the fiber; awaiting it settles once loading finished.
1997
- */
1998
- plugin(plugin, config, getOuterStack = buildOuterStack()) {
1999
- const callback = this.resolve(plugin);
2000
- if (!callback) throw new Error("invalid plugin, expect function or object with an \"apply\" method, received " + typeof plugin);
2001
- this.ctx.fiber.assertActive();
2002
- let runtime = this._internal.get(callback);
2003
- if (!runtime) {
2004
- let name = plugin.name;
2005
- if (name === "apply") name = void 0;
2006
- runtime = {
2007
- name,
2008
- callback,
2009
- fibers: new DisposableList(),
2010
- Config: plugin.Config
2011
- };
2012
- this._internal.set(callback, runtime);
2013
- }
2014
- const fiber = new Fiber(this.ctx, config, Inject.resolve(plugin.inject), runtime, getOuterStack);
2015
- const wrapped = Object.create(fiber);
2016
- wrapped.then = (onFulfilled, onRejected) => {
2017
- return fiber.await().then(onFulfilled, onRejected);
2018
- };
2019
- return wrapped;
2020
- }
2021
- };
2022
- /**
2023
- * Root and child dependency containers for Cordis plugins.
2024
- *
2025
- * A context is a proxy: normal property reads go through the service resolver,
2026
- * while `extend()`, `isolate()`, and `intercept()` create scoped child
2027
- * contexts without mutating their parent.
2028
- */
2029
- var Context = class Context {
2030
- /** Symbol key under which a disposer exposes its {@link EffectMeta} diagnostics tree. */
2031
- static effect = symbols.effect;
2032
- /** Symbol key for a context's listener filter, consulted on every event dispatch. */
2033
- static filter = symbols.filter;
2034
- /** Symbol key of the isolation map (see the `Context[symbols.isolate]` property). */
2035
- static isolate = symbols.isolate;
2036
- /** Symbol key of the intercept map (see the `Context[symbols.intercept]` property). */
2037
- static intercept = symbols.intercept;
2038
- /**
2039
- * Returns true for Cordis context proxies and context prototypes.
2040
- *
2041
- * Works across realms and across multiple copies of cordis, because the
2042
- * brand is keyed by a global symbol rather than by `instanceof`.
2043
- *
2044
- * @param value — the value to test.
2045
- * @returns `true` if `value` is a Cordis context, narrowing its type.
2046
- */
2047
- static is(value) {
2048
- return !!value?.[Context.is];
2049
- }
2050
- static {
2051
- Context.is[Symbol.toPrimitive] = () => Symbol.for("cordis.is");
2052
- Context.prototype[Context.is] = true;
2053
- }
2054
- /** Create the root context and install the built-in services. */
2055
- constructor() {
2056
- this[symbols.isolate] = Object.create(null);
2057
- this[symbols.intercept] = Object.create(null);
2058
- const self = new Proxy(this, ReflectService.handler);
2059
- this.root = self;
2060
- this.baseUrl = void 0;
2061
- this.fiber = new Fiber(self, {}, Object.create(null), null, () => []);
2062
- this.reflect = new ReflectService(self);
2063
- this.registry = new RegistryService(self);
2064
- this.events = new EventsService(self);
2065
- this.logger = new LoggerService(self);
2066
- this.fiber._disposables.clear();
2067
- return self;
2068
- }
2069
- [Symbol.for("nodejs.util.inspect.custom")]() {
2070
- return `Context <${this.fiber.name}>`;
2071
- }
2072
- /**
2073
- * Create a child context with extra metadata on top of the current scope.
2074
- *
2075
- * The child prototypally inherits every property of this context; own
2076
- * properties of `meta` shadow the inherited ones. The parent is not mutated.
2077
- *
2078
- * @param meta — own properties (including symbol keys) to define on the child.
2079
- * @returns a child context inheriting from this one.
2080
- */
2081
- extend(meta = {}) {
2082
- const shadow = Reflect.getOwnPropertyDescriptor(this, symbols.shadow)?.value;
2083
- const self = Object.create(getTraceable(this, this));
2084
- for (const prop of Reflect.ownKeys(meta)) Object.defineProperty(self, prop, Reflect.getOwnPropertyDescriptor(meta, prop));
2085
- if (!shadow) return self;
2086
- return Object.assign(Object.create(self), { [symbols.shadow]: shadow });
2087
- }
2088
- /**
2089
- * Create a child context with an independent service scope for `name`.
2090
- *
2091
- * Below the returned context, reads and writes of the service `name`
2092
- * resolve against the new label instead of the parent's, so a different
2093
- * implementation can be provided without affecting the parent scope.
2094
- * Passing the same `label` to two `isolate()` calls joins their scopes.
2095
- *
2096
- * @param name — the service name to isolate.
2097
- * @param label — scope label to join; defaults to a fresh unique symbol.
2098
- * @returns a child context whose `name` service resolves in the new scope.
2099
- */
2100
- isolate(name, label) {
2101
- const shadow = Object.create(this[symbols.isolate]);
2102
- shadow[name] = label ?? Symbol(name);
2103
- return this.extend({ [symbols.isolate]: shadow });
2104
- }
2105
- intercept(name, config) {
2106
- const intercept = Object.create(this[symbols.intercept]);
2107
- intercept[name] = config;
2108
- return this.extend({ [symbols.intercept]: intercept });
2109
- }
2110
- };
2111
- /**
2112
- * Base class for services that expose a named API on `ctx`.
2113
- *
2114
- * Subclasses call `super(ctx, name)` from their constructor. The service is
2115
- * registered immediately and is automatically removed with the owning fiber.
2116
- */
2117
- var Service = class Service {
2118
- ctx;
2119
- /** Symbol key of an instance method run after construction (class plugins). */
2120
- static init = symbols.init;
2121
- /** Symbol key of the availability predicate passed to `ctx.provide()`. */
2122
- static check = symbols.check;
2123
- /** Symbol key of the phantom intercept-config type parameter. */
2124
- static config = symbols.config;
2125
- /** Symbol key of the call body making a service callable (e.g. `ctx.logger()`). */
2126
- static invoke = symbols.invoke;
2127
- /** Symbol key of the helper deriving an extended service instance. */
2128
- static extend = symbols.extend;
2129
- /** Symbol key of the tracker metadata used for context tracing. */
2130
- static tracker = symbols.tracker;
2131
- /** Symbol key of the intercept-config resolution helper below. */
2132
- static resolveConfig = symbols.resolveConfig;
2133
- /** The service name this instance is registered under. */
2134
- name;
2135
- /**
2136
- * Register this instance as `name` in the current context.
2137
- *
2138
- * Calls `ctx.reflect.provide(name, this, this[Service.check])`, so the
2139
- * service is unregistered automatically when the owning fiber unloads.
2140
- * Services with a `[Service.invoke]` body return a callable instance.
2141
- *
2142
- * @param ctx — the context to register in (stored as `this.ctx`).
2143
- * @param name — the service name; defaults to the static `provide` field.
2144
- */
2145
- constructor(ctx, name) {
2146
- this.ctx = ctx;
2147
- name ??= this.constructor["provide"];
2148
- let self = this;
2149
- const tracker = {
2150
- associate: name,
2151
- property: "ctx"
2152
- };
2153
- if (self[symbols.invoke]) self = createCallable(name, joinPrototype(Object.getPrototypeOf(this), Function.prototype), tracker);
2154
- self.ctx = ctx;
2155
- self.name = name;
2156
- defineProperty(self, symbols.tracker, tracker);
2157
- self.ctx.reflect.provide(name, self, this[symbols.check]);
2158
- return self;
2159
- }
2160
- [symbols.filter](ctx) {
2161
- return ctx[symbols.isolate][this.name] === this.ctx[symbols.isolate][this.name];
2162
- }
2163
- [symbols.extend](props) {
2164
- let self;
2165
- if (this[Service.invoke]) self = createCallable(this.name, this, this[symbols.tracker]);
2166
- else self = Object.create(this);
2167
- return Object.assign(self, props);
2168
- }
2169
- /**
2170
- * Merge intercept config from ancestors with optional base and head values.
2171
- *
2172
- * Entries added closer to the root apply first; `base` is prepended and
2173
- * `head` appended. Uses `Config.merge` when the service declares one,
2174
- * otherwise a shallow `Object.assign`.
2175
- *
2176
- * @param base — lowest-precedence config merged before all intercepts.
2177
- * @param head — highest-precedence config merged after all intercepts.
2178
- * @returns the merged config.
2179
- */
2180
- [symbols.resolveConfig](base, head) {
2181
- let intercept = this.ctx[Context.intercept];
2182
- const configs = [];
2183
- while (this.name in intercept) {
2184
- if (Object.hasOwn(intercept, this.name)) configs.unshift(intercept[this.name]);
2185
- intercept = Object.getPrototypeOf(intercept);
2186
- }
2187
- if (base) configs.unshift(base);
2188
- if (head) configs.push(head);
2189
- if (this["Config"]?.merge) return this["Config"].merge(...configs);
2190
- else return Object.assign({}, ...configs);
2191
- }
2192
- static [Symbol.hasInstance](instance) {
2193
- if (!instance) return false;
2194
- let constructor = instance.constructor;
2195
- while (constructor) {
2196
- constructor = constructor.prototype?.constructor;
2197
- if (constructor === this) return true;
2198
- constructor &&= Object.getPrototypeOf(constructor);
2199
- }
2200
- return false;
2201
- }
2202
- };
2203
- //#endregion
2204
- //#region ../../core/po-core/src/schemas/headless.ts
2205
- /** Session-only contributions. This is not a Pi ExtensionAPI or a TUI adapter. */
2206
- const PO_HEADLESS_HOST_SERVICE = "po/headless-host";
2207
- const PO_HEADLESS_OWNER = Symbol.for("po/headless-owner");
2208
- const PROMPT_ADMISSION_ERROR = "PoHeadlessPromptAdmissionError";
2209
- /** Admission is a host boundary, not an advisory package-hook failure. */
2210
- var PoHeadlessPromptAdmissionError = class extends Error {
2211
- constructor(cause) {
2212
- super(cause instanceof Error ? cause.message : String(cause), { cause });
2213
- this.name = PROMPT_ADMISSION_ERROR;
2214
- }
2215
- };
2216
- const SESSION_SETUP_ERROR = "PoSessionSetupError";
2217
- /**
2218
- * A session cannot start until the user fixes their setup, such as configuring a model.
2219
- *
2220
- * Its message is written for the user and says what to do, so a server returns it as is
2221
- * rather than hiding it behind a generic internal error.
2222
- */
2223
- var PoSessionSetupError = class extends Error {
2224
- constructor(message) {
2225
- super(message);
2226
- this.name = SESSION_SETUP_ERROR;
2227
- }
2228
- };
2229
- /** Error identity must survive independently bundled server and extension graphs. */
2230
- function isPoHeadlessPromptAdmissionError(error) {
2231
- return error instanceof Error && error.name === PROMPT_ADMISSION_ERROR;
2232
- }
2233
- const TOOL_BUSY_ERROR = "PoHeadlessToolBusyError";
2234
- /** The tool and its hooks have not started. */
2235
- var PoHeadlessToolBusyError = class extends Error {
2236
- constructor() {
2237
- super("An operation is already running");
2238
- this.name = TOOL_BUSY_ERROR;
2239
- }
2240
- };
2241
- function readPoHeadlessOwner(context) {
2242
- return context[PO_HEADLESS_OWNER];
2243
- }
2244
- let crcTable;
2245
- function crc32(bytes, start, end) {
2246
- if (crcTable === void 0) {
2247
- crcTable = /* @__PURE__ */ new Uint32Array(256);
2248
- for (let n = 0; n < 256; n++) {
2249
- let c = n;
2250
- for (let k = 0; k < 8; k++) c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
2251
- crcTable[n] = c >>> 0;
2252
- }
2253
- }
2254
- let crc = 4294967295;
2255
- for (let i = start; i < end; i++) crc = crcTable[(crc ^ bytes[i]) & 255] ^ crc >>> 8;
2256
- return (crc ^ 4294967295) >>> 0;
2257
- }
2258
- const PNG_SIGNATURE = [
2259
- 137,
2260
- 80,
2261
- 78,
2262
- 71,
2263
- 13,
2264
- 10,
2265
- 26,
2266
- 10
2267
- ];
2268
- function startsWith(bytes, prefix, offset = 0) {
2269
- return prefix.every((byte, index) => bytes[offset + index] === byte);
2270
- }
2271
- /** Why the model API would reject this image, or undefined when it looks decodable. Only png, jpeg, gif and webp are checked. */
2272
- function invalidImageReason(data, mimeType) {
2273
- let bytes;
2274
- try {
2275
- bytes = Uint8Array.from(atob(data), (char) => char.charCodeAt(0));
2276
- } catch {
2277
- return "the data is not valid base64";
2278
- }
2279
- if (mimeType === "image/png") {
2280
- if (!startsWith(bytes, PNG_SIGNATURE)) return "the data is not a PNG";
2281
- const view = new DataView(bytes.buffer);
2282
- let offset = 8;
2283
- while (offset + 12 <= bytes.length) {
2284
- const length = view.getUint32(offset);
2285
- const end = offset + 8 + length;
2286
- if (end + 4 > bytes.length) break;
2287
- if (crc32(bytes, offset + 4, end) !== view.getUint32(end)) return "a PNG chunk failed its checksum";
2288
- if (startsWith(bytes, [
2289
- 73,
2290
- 69,
2291
- 78,
2292
- 68
2293
- ], offset + 4)) return void 0;
2294
- offset = end + 4;
2295
- }
2296
- return "the PNG is truncated";
2297
- }
2298
- if (mimeType === "image/jpeg") return startsWith(bytes, [255, 216]) ? void 0 : "the data is not a JPEG";
2299
- if (mimeType === "image/gif") return startsWith(bytes, [
2300
- 71,
2301
- 73,
2302
- 70,
2303
- 56
2304
- ]) ? void 0 : "the data is not a GIF";
2305
- if (mimeType === "image/webp") return startsWith(bytes, [
2306
- 82,
2307
- 73,
2308
- 70,
2309
- 70
2310
- ]) && startsWith(bytes, [
2311
- 87,
2312
- 69,
2313
- 66,
2314
- 80
2315
- ], 8) ? void 0 : "the data is not a WebP";
2316
- }
2317
- /** Keeps valid images and swaps an undecodable one for a text note, since one bad image fails the whole turn and every later one. */
2318
- function dropInvalidImages(content) {
2319
- return content.map((part) => {
2320
- if (part.type !== "image") return part;
2321
- const reason = invalidImageReason(part.data, part.mimeType);
2322
- return reason === void 0 ? part : {
2323
- type: "text",
2324
- text: `[image omitted: ${reason}]`
2325
- };
2326
- });
2327
- }
2328
- /** Visibility controls model discovery only, never admission for external execution. */
2329
- function isPoHeadlessToolModelVisible(tool) {
2330
- const visibility = tool._meta?.ui?.visibility;
2331
- return visibility === void 0 || visibility.includes("model");
2332
- }
2333
- /** Session skill discovery tools, adapted to the size of the active catalog. */
2334
- const PO_LOAD_SKILL_TOOL = "load_skill";
2335
- const PO_SEARCH_SKILLS_TOOL = "search_skills";
2336
- function readPoHeadlessHost(context) {
2337
- return context.get(PO_HEADLESS_HOST_SERVICE);
2338
- }
2339
- //#endregion
2340
- //#region ../../core/po-core/src/schemas/platform.ts
2341
- const PO_FS_SERVICE = "po/fs";
2342
- const PO_SHELL_SERVICE = "po/shell";
2343
- const PO_SQLITE_SERVICE = "po/sqlite";
2344
- const PO_SESSION_STORAGE_SERVICE = "po/session-storage";
2345
- const PO_ISOLATE_SERVICE = "po/isolate";
2346
- const PO_NPM_SERVICE = "po/npm";
2347
- const PO_ELECTRON_SERVICE = "po/electron";
2348
- const PO_BROWSER_SERVICE = "po/browser";
2349
- function readPoFs(context) {
2350
- return context.get(PO_FS_SERVICE);
2351
- }
2352
- function requirePoFs(context) {
2353
- const service = readPoFs(context);
2354
- if (!service) throw new Error(`The '${PO_FS_SERVICE}' service is unavailable. Start a Po server first.`);
2355
- return service;
2356
- }
2357
- function requirePoSqlite(context) {
2358
- const service = context.get(PO_SQLITE_SERVICE);
2359
- if (!service) throw new Error(`The '${PO_SQLITE_SERVICE}' service is unavailable. Start a Po server first.`);
2360
- return service;
2361
- }
2362
- function readPoNpm(context) {
2363
- return context.get(PO_NPM_SERVICE);
2364
- }
2365
- function readPoBrowser(context) {
2366
- return context.get(PO_BROWSER_SERVICE);
2367
- }
2368
- function readPoIsolate(context) {
2369
- return context.get(PO_ISOLATE_SERVICE);
2370
- }
2371
- //#endregion
2372
- //#region ../../../node_modules/.pnpm/@earendil-works+chord@1.5.0_esbuild@0.28.2/node_modules/@earendil-works/chord/dist/json.js
2373
- const DATA_DESCRIPTOR = {
2374
- value: void 0,
2375
- writable: true,
2376
- enumerable: true,
2377
- configurable: true
2378
- };
2379
- /** Copy a value into an alias-free strict-JSON tree owned by the caller. */
2380
- function copyJson(value, options) {
2381
- return copy(value, void 0, options?.omitUndefinedProperties === true);
2382
- }
2383
- function copy(value, ancestors, omitUndefinedProperties) {
2384
- if (value === null || typeof value === "string" || typeof value === "boolean") return value;
2385
- if (typeof value === "number") {
2386
- if (Number.isFinite(value)) return value;
2387
- throw new TypeError("Value contains a non-finite number and is not strict JSON");
2388
- }
2389
- if (typeof value !== "object") throw new TypeError(`Value contains a non-JSON ${typeof value}; expected strict JSON`);
2390
- const active = ancestors ?? /* @__PURE__ */ new Set();
2391
- if (active.has(value)) throw new TypeError("Value contains cycles and is not strict JSON");
2392
- active.add(value);
2393
- try {
2394
- if (Array.isArray(value)) {
2395
- if (Object.getPrototypeOf(value) !== Array.prototype || Reflect.ownKeys(value).length !== value.length + 1) throw new TypeError("Value must contain strict JSON dense plain arrays");
2396
- const result = new Array(value.length);
2397
- for (let index = 0; index < value.length; index++) {
2398
- const descriptor = Object.getOwnPropertyDescriptor(value, index);
2399
- if (descriptor === void 0 || !descriptor.enumerable || !("value" in descriptor)) throw new TypeError("Value must contain strict JSON enumerable indexed data properties");
2400
- defineData(result, String(index), copy(descriptor.value, active, omitUndefinedProperties));
2401
- }
2402
- return result;
2403
- }
2404
- const prototype = Object.getPrototypeOf(value);
2405
- if (prototype !== Object.prototype && prototype !== null) throw new TypeError("Value must contain strict JSON plain objects or arrays");
2406
- const result = Object.create(prototype);
2407
- for (const key of Reflect.ownKeys(value)) {
2408
- if (typeof key === "symbol") throw new TypeError("Value contains a symbol key and is not strict JSON");
2409
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
2410
- if (!descriptor.enumerable || !("value" in descriptor)) throw new TypeError("Value must contain strict JSON enumerable data properties");
2411
- if (descriptor.value === void 0 && omitUndefinedProperties) continue;
2412
- defineData(result, key, copy(descriptor.value, active, omitUndefinedProperties));
2413
- }
2414
- return result;
2415
- } finally {
2416
- active.delete(value);
2417
- }
2418
- }
2419
- function defineData(target, key, value) {
2420
- DATA_DESCRIPTOR.value = value;
2421
- Object.defineProperty(target, key, DATA_DESCRIPTOR);
2422
- DATA_DESCRIPTOR.value = void 0;
2423
- }
2424
- //#endregion
2425
- //#region ../../../node_modules/.pnpm/@earendil-works+pi-durable@1.5.0_patch_hash=0f5e595daa4c370af407284d99d6dba48a9e21f56aa_0f219e156e08feb96504f67b2b506549/node_modules/@earendil-works/pi-durable/dist/ids.js
2426
- /** Apply an erased ID brand at a trusted numeric allocation or decoding boundary. */
2427
- function idFromNumber(value) {
2428
- return value;
2429
- }
2430
- /** Apply the erased commit-sequence brand at a trusted storage boundary. */
2431
- function seqFromNumber(value) {
2432
- return value;
2433
- }
2434
- //#endregion
2435
- //#region ../../../node_modules/.pnpm/@earendil-works+pi-durable@1.5.0_patch_hash=0f5e595daa4c370af407284d99d6dba48a9e21f56aa_0f219e156e08feb96504f67b2b506549/node_modules/@earendil-works/pi-durable/dist/documents.js
2436
- function defineDoc(definition) {
2437
- validateDefinition(definition);
2438
- return { definition };
2439
- }
2440
- function defineDocFamily(definition) {
2441
- validateDefinition(definition);
2442
- return { definition };
2443
- }
2444
- function validateDefinition(definition) {
2445
- if (!Number.isSafeInteger(definition.version) || definition.version < 1) throw new TypeError(`Document ${definition.kind} version must be a positive integer`);
2446
- }
2447
- /** Resolve an overloaded argument list and return the index after the owner and family key. */
2448
- function resolveAddress(definition, args) {
2449
- let index = 0;
2450
- let scope;
2451
- switch (definition.scope) {
2452
- case "session":
2453
- scope = { kind: "session" };
2454
- break;
2455
- case "conversation":
2456
- scope = {
2457
- kind: "conversation",
2458
- conversationId: ownerId(args[index++], definition)
2459
- };
2460
- break;
2461
- case "task": scope = {
2462
- kind: "task",
2463
- taskId: ownerId(args[index++], definition)
2464
- };
2465
- }
2466
- const key = definition.family === true ? args[index++] : void 0;
2467
- const address = key === void 0 ? {
2468
- kind: definition.kind,
2469
- scope
2470
- } : {
2471
- kind: definition.kind,
2472
- scope,
2473
- key
2474
- };
2475
- return {
2476
- address,
2477
- id: addressId(address),
2478
- nextArgument: index
2479
- };
2480
- }
2481
- function ownerId(value, definition) {
2482
- if (typeof value !== "number" || !Number.isSafeInteger(value)) throw new TypeError(`Document ${definition.kind} requires a ${definition.scope} ID`);
2483
- return idFromNumber(value);
2484
- }
2485
- /** Stable string identity of one logical address. */
2486
- function addressId(address) {
2487
- const owner = address.scope.kind === "session" ? null : address.scope.kind === "conversation" ? address.scope.conversationId : address.scope.taskId;
2488
- return JSON.stringify([
2489
- address.kind,
2490
- address.scope.kind,
2491
- owner,
2492
- address.key ?? null
2493
- ]);
2494
- }
2495
- /** Build the storage create record for a new incarnation at an address. */
2496
- function documentCreate(definition, address, id) {
2497
- const key = address.key === void 0 ? {} : { key: address.key };
2498
- switch (address.scope.kind) {
2499
- case "session": return {
2500
- id,
2501
- kind: address.kind,
2502
- ...key,
2503
- scope: address.scope
2504
- };
2505
- case "task": return {
2506
- id,
2507
- kind: address.kind,
2508
- ...key,
2509
- scope: address.scope
2510
- };
2511
- case "conversation": return {
2512
- id,
2513
- kind: address.kind,
2514
- ...key,
2515
- scope: address.scope,
2516
- history: definition.history,
2517
- fork: definition.fork
2518
- };
2519
- }
2520
- }
2521
- /** Reject typed access whose token disagrees with the persisted scope, history, or fork semantics. */
2522
- function checkRecordScope(definition, record) {
2523
- if (record.scope.kind !== definition.scope || record.scope.kind === "conversation" && (record.history !== definition.history || record.fork !== definition.fork)) throw new TypeError(`Document ${record.id} (${record.kind}) does not match the supplied definition semantics`);
2524
- }
2525
- /** Reject typed access to a stored version the supplied definition cannot use. */
2526
- function checkRecordVersion(definition, record, version) {
2527
- if (version > definition.version) throw new Error(`Document ${record.id} (${record.kind}) has newer version ${version} than ${definition.version}`);
2528
- if (version < definition.version && definition.migrate === void 0) throw new Error(`Document ${record.id} (${record.kind}) requires migration from version ${version}`);
2529
- }
2530
- /** Validate and materialize a detached stored value for typed access. */
2531
- function materializeDocument(definition, stored) {
2532
- return materializeDocumentValue(definition, stored.record, stored.version, stored.value);
2533
- }
2534
- /** Validate and materialize one detached value before its first persisted incarnation. */
2535
- function materializeDocumentValue(definition, record, version, value) {
2536
- checkRecordScope(definition, record);
2537
- checkRecordVersion(definition, record, version);
2538
- if (version === definition.version) return value;
2539
- return copyJson(definition.migrate(value, version));
2540
- }
2541
- //#endregion
2542
- //#region ../../core/po-core/src/services/durableSession/docs.ts
2543
- /** Public string identity belongs to Po, not the durable numeric ID namespace. */
2544
- const SessionIdentityDoc = defineDoc({
2545
- kind: "po.session.identity",
2546
- checkpointWhen: () => false,
2547
- version: 1,
2548
- scope: "session",
2549
- initial: () => ({
2550
- id: "",
2551
- createdAt: 0,
2552
- parentSessionId: ""
2553
- })
2554
- });
2555
- const SessionMetadataDoc = defineDoc({
2556
- kind: "po.session.metadata",
2557
- checkpointWhen: () => false,
2558
- version: 1,
2559
- scope: "session",
2560
- initial: () => ({
2561
- name: "",
2562
- workspaceRoot: "",
2563
- execution: "",
2564
- laneName: "main",
2565
- groups: []
2566
- })
2567
- });
2568
- const FastModeDoc = defineDoc({
2569
- kind: "po.fast-mode",
2570
- checkpointWhen: () => false,
2571
- version: 1,
2572
- scope: "session",
2573
- initial: () => ({ enabled: false })
2574
- });
2575
- const AgentLockDoc = defineDoc({
2576
- kind: "po.agent-lock",
2577
- checkpointWhen: () => false,
2578
- version: 1,
2579
- scope: "session",
2580
- initial: () => ({ locked: false })
2581
- });
2582
- const LabelsDoc = defineDoc({
2583
- kind: "po.labels",
2584
- checkpointWhen: () => false,
2585
- version: 1,
2586
- scope: "session",
2587
- initial: () => ({ labels: {} })
2588
- });
2589
- /**
2590
- * Profile identity entries of one conversation, written in the identity entry's commit, so a transcript page finds
2591
- * the avatar in effect without scanning backwards. Rewindable with `asOf` forks: a fork keeps only the identities
2592
- * written before its fork point. Sessions written before this document have no entries and show the default avatar.
2593
- */
2594
- const IdentityHistoryDoc = defineDoc({
2595
- kind: "po.identity-history",
2596
- checkpointWhen: () => false,
2597
- version: 1,
2598
- scope: "conversation",
2599
- history: "rewindable",
2600
- fork: "asOf",
2601
- initial: () => ({ items: [] })
2602
- });
2603
- //#endregion
2604
- //#region ../../../node_modules/.pnpm/@earendil-works+pi-durable@1.5.0_patch_hash=0f5e595daa4c370af407284d99d6dba48a9e21f56aa_0f219e156e08feb96504f67b2b506549/node_modules/@earendil-works/pi-durable/dist/env/index.js
2605
- function ok(value) {
2606
- return {
2607
- ok: true,
2608
- value
2609
- };
2610
- }
2611
- function err(error) {
2612
- return {
2613
- ok: false,
2614
- error
2615
- };
2616
- }
2617
- function getOrThrow(result) {
2618
- if (!result.ok) throw result.error;
2619
- return result.value;
2620
- }
2621
- var FileError = class extends Error {
2622
- code;
2623
- path;
2624
- constructor(code, message, path, cause) {
2625
- super(message, cause === void 0 ? void 0 : { cause });
2626
- this.name = "FileError";
2627
- this.code = code;
2628
- this.path = path;
2629
- }
2630
- };
2631
- var ExecutionError = class extends Error {
2632
- code;
2633
- /** Spill file of a command that timed out or was aborted after its output crossed the spill thresholds. */
2634
- spillPath;
2635
- constructor(code, message, cause) {
2636
- super(message, cause === void 0 ? void 0 : { cause });
2637
- this.name = "ExecutionError";
2638
- this.code = code;
2639
- }
2640
- };
2641
- //#endregion
2642
- //#region ../../core/po-core/src/services/nodeHost/index.edge.ts
2643
- /** The edge host: one Durable Object, its virtual filesystem laid out as in po-cloudflare's DoFileSystem. */
2644
- const nodeHost = {
2645
- homeDirectory: () => "/home/po",
2646
- temporaryDirectory: () => "/tmp",
2647
- /** A Durable Object is one logical process. */
2648
- processId: () => 1,
2649
- setMode: async (_filePath, _mode) => void 0,
2650
- /** No modes on the edge, so callers skip their permission checks, as `setMode` does. */
2651
- fileMode: async (_filePath) => void 0
2652
- };
2653
- //#endregion
2654
- //#region ../../core/po-core/src/services/serialRunner/index.ts
2655
- /** Runs operations one at a time in call order; a rejection reaches its caller and never stalls the queue. */
2656
- function createSerialRunner() {
2657
- let tail = Promise.resolve();
2658
- const tails = /* @__PURE__ */ new Map();
2659
- const run = (operation) => {
2660
- const result = tail.then(operation);
2661
- tail = result.catch(() => void 0);
2662
- return result;
2663
- };
2664
- const forKey = (key) => (operation) => {
2665
- const result = (tails.get(key) ?? Promise.resolve()).then(operation);
2666
- const settled = result.catch(() => void 0);
2667
- tails.set(key, settled);
2668
- settled.then(() => {
2669
- if (tails.get(key) === settled) tails.delete(key);
2670
- });
2671
- return result;
2672
- };
2673
- return Object.assign(run, { forKey });
2674
- }
2675
- createSerialRunner();
2676
- //#endregion
2677
- //#region ../../core/po-core/src/services/piSettings/core.ts
2678
- /**
2679
- * Pi's user settings, as `po sync` maintains them.
2680
- *
2681
- * The Po package is registered globally so a plain `pi` process can find the
2682
- * lightweight package bootstrap before project resources are trusted. Sync owns
2683
- * the extension registration, ambient-discovery filter, theme resource, selected default theme, and quiet-startup keys
2684
- * while preserving every unrelated user setting.
2685
- */
2686
- const PI_CODING_AGENT_DIR_ENV = "PI_CODING_AGENT_DIR";
2687
- /** Moves Po's whole home, agent directory included, away from `~/.po`. */
2688
- const PO_HOME_ENV = "PO_HOME";
2689
- /** The agent folder inside a Po or Pi home. */
2690
- const AGENT_DIRECTORY = "agent";
2691
- const HOME_ALIAS = "~";
2692
- const HOME_ALIAS_PREFIX = "~/";
2693
- /**
2694
- * Expands `~` and resolves a relative path against home, never the cwd, so every
2695
- * Po process lands on the same directory wherever it was started.
2696
- */
2697
- function resolveConfiguredDirectory(configured, homeDirectory) {
2698
- if (configured === HOME_ALIAS) return homeDirectory;
2699
- if (configured.startsWith(HOME_ALIAS_PREFIX)) return path.join(homeDirectory, configured.slice(2));
2700
- return path.resolve(homeDirectory, configured);
2701
- }
2702
- /**
2703
- * Po's home: config, workspaces, runtime registry and its Pi agent directory.
2704
- * Defaults to `~/.po`; `PO_HOME` moves all of it.
2705
- */
2706
- function poHomeDirectory(homeDirectory = nodeHost.homeDirectory(), environment = process.env) {
2707
- const configured = environment[PO_HOME_ENV]?.trim();
2708
- return configured ? resolveConfiguredDirectory(configured, homeDirectory) : path.join(homeDirectory, ".po");
2709
- }
2710
- /**
2711
- * The Pi agent directory Po runs with. Honors Pi's documented override; every Po
2712
- * entry point sets that override, so the default only applies to library callers.
2713
- */
2714
- function piAgentDirectory(environment = process.env, homeDirectory = nodeHost.homeDirectory()) {
2715
- const configured = environment[PI_CODING_AGENT_DIR_ENV]?.trim();
2716
- if (!configured) return path.join(poHomeDirectory(homeDirectory, environment), AGENT_DIRECTORY);
2717
- return resolveConfiguredDirectory(configured, homeDirectory);
2718
- }
2719
- createSerialRunner();
2720
- //#endregion
2721
- //#region ../../core/po-core/src/services/sessionFiles/sessionDirectory.edge.ts
2722
- /** The Durable Object filesystem is already isolated to its owning session. */
2723
- async function prepareSessionDirectory(platform, directory) {
2724
- const fs = platform.env(platform.homeDirectory);
2725
- try {
2726
- getOrThrow(await fs.createDir(directory, { recursive: true }, BACKGROUND_CONTEXT));
2727
- return directory;
2728
- } finally {
2729
- await fs.cleanup(BACKGROUND_CONTEXT);
2730
- }
2731
- }
2732
- //#endregion
2733
- //#region ../../core/po-core/src/services/sessionFiles/index.ts
2734
- const PO_SESSION_TEMP_DIR = "PO_SESSION_TEMP_DIR";
2735
- const PO_SESSION_FILES_SERVICE = "po/session-files";
2736
- /** A host-owned path, never a client-selected root or an inherited parent session path. */
2737
- function sessionTempDirectory(options) {
2738
- if (!/^[a-zA-Z0-9_-]+$/u.test(options.sessionId)) throw new Error("Invalid temporary-file session identity.");
2739
- if (!path.isAbsolute(options.temporaryDirectory)) throw new Error("The host temporary directory must be absolute.");
2740
- const namespace = createHash("sha256").update(options.homeDirectory).update("\0").update(poHomeDirectory(options.homeDirectory, options.environment)).digest("hex").slice(0, 24);
2741
- return path.join(options.temporaryDirectory, `po-${namespace}`, "sessions", options.sessionId);
2742
- }
2743
- /** Both the execution host and package APIs call this with their admitted session identity. */
2744
- async function prepareSessionEnvironment(input) {
2745
- const environment = { ...input.environment };
2746
- delete environment[PO_SESSION_TEMP_DIR];
2747
- if (input.platform.temporaryDirectory === void 0) return Object.freeze(environment);
2748
- const directory = sessionTempDirectory({
2749
- sessionId: input.sessionId,
2750
- homeDirectory: input.platform.homeDirectory,
2751
- environment,
2752
- temporaryDirectory: input.platform.temporaryDirectory
2753
- });
2754
- const preparedDirectory = await prepareSessionDirectory(input.platform, directory);
2755
- return Object.freeze({
2756
- ...environment,
2757
- [PO_SESSION_TEMP_DIR]: preparedDirectory
2758
- });
2759
- }
2760
- //#endregion
2761
- //#region ../../core/po-core/src/server/serverScope.ts
2762
- /** What one plugin build shares in one tree: its keyed values, and what each scope running it holds. */
2763
- var PluginShare = class {
2764
- values = /* @__PURE__ */ new Map();
2765
- running = /* @__PURE__ */ new Map();
2766
- get idle() {
2767
- return this.values.size === 0 && this.running.size === 0;
2768
- }
2769
- };
2770
- const resourceName = (key) => JSON.stringify(typeof key === "string" ? [key] : key);
2771
- const depth = (level) => PO_SERVER_SCOPE_LEVELS.indexOf(level);
2772
- const describe = (error) => error instanceof Error ? error.message : String(error);
2773
- let scopesOpened = 0;
2774
- let buildsSeen = 0;
2775
- const builds = /* @__PURE__ */ new WeakMap();
2776
- /** A stable log label for one plugin build; a reload imports a new module, and so a new build. */
2777
- function buildOf(owner) {
2778
- let build = builds.get(owner);
2779
- if (build === void 0) builds.set(owner, build = ++buildsSeen);
2780
- return `build#${build}`;
2781
- }
2782
- const nameOf = (owner) => {
2783
- const name = owner.name;
2784
- return typeof name === "string" ? name : void 0;
2785
- };
2786
- /** Publishes one binding as a native service of the root it is plugged into. */
2787
- function bindingProvider(context, binding) {
2788
- context.provide(binding.name, binding.value);
2789
- }
2790
- /**
2791
- * The scope service each root publishes.
2792
- *
2793
- * Cordis traceable services rebind `ctx` to the caller, so a binding made through
2794
- * `provide` unwinds with the plugin that made it.
2795
- */
2796
- var ScopeService = class extends Service {
2797
- scope;
2798
- level;
2799
- constructor(ctx, scope) {
2800
- super(ctx, PO_SERVER_SCOPE_SERVICE);
2801
- this.scope = scope;
2802
- this.level = scope.level;
2803
- }
2804
- async provide(contract, value) {
2805
- return await this.ctx.effect(() => this.scope.bind(contract, value), `po scope provide ${contract.name}`);
2806
- }
2807
- resolve(contract) {
2808
- return this.scope.resolve(contract);
2809
- }
2810
- emit(name, ...args) {
2811
- this.scope.emit(name, ...args);
2812
- }
2813
- broadcast(name, ...args) {
2814
- this.scope.broadcast(name, ...args);
2815
- }
2816
- plugin(owner) {
2817
- return this.scope.share(owner);
2818
- }
2819
- };
2820
- /**
2821
- * Binds registrations to the Cordis fiber that calls the host service.
2822
- *
2823
- * The host itself is shared by every package at its level, but Cordis traceable
2824
- * services rebind `ctx` to the caller. That lets a package's registration unwind
2825
- * even when `apply` throws before it can return its disposer.
2826
- */
2827
- var ScopedPoServerHost = class extends Service {
2828
- host;
2829
- scope;
2830
- context;
2831
- constructor(ctx, host) {
2832
- super(ctx, PO_SERVER_HOST_SERVICE);
2833
- this.host = host;
2834
- this.scope = host.scope;
2835
- this.context = host.context;
2836
- }
2837
- registerApi(api) {
2838
- const headless = this.scope === "session" ? readPoHeadlessHost(this.ctx) : void 0;
2839
- if (headless) {
2840
- const activity = headless.registerActivity({
2841
- name: `api:${api.basePath}`,
2842
- start: () => {
2843
- const registration = this.host.registerApi(api);
2844
- if (registration.mounted !== true) {
2845
- registration.dispose();
2846
- throw new Error(`package API '${api.basePath}' did not mount.`);
2847
- }
2848
- return () => {
2849
- registration.dispose();
2850
- };
2851
- }
2852
- });
2853
- return {
2854
- mounted: true,
2855
- dispose: () => activity.dispose()
2856
- };
2857
- }
2858
- const registration = this.host.registerApi(api);
2859
- if (registration.mounted !== true) {
2860
- registration.dispose();
2861
- throw new Error(`package API '${api.basePath}' did not mount.`);
2862
- }
2863
- this.ctx.effect(() => () => registration.dispose(), "server package API registration");
2864
- return registration;
2865
- }
2866
- registerChannel(channel) {
2867
- const registration = this.host.registerChannel(channel);
2868
- if (registration.mounted !== true) {
2869
- registration.dispose();
2870
- throw new Error(`hub channel '${channel.frameType}' did not mount.`);
2871
- }
2872
- this.ctx.effect(() => () => registration.dispose(), "server package channel registration");
2873
- return registration;
2874
- }
2875
- registerMethod = (definition, handler) => {
2876
- const registration = this.host.registerMethod(definition, handler);
2877
- if (registration.mounted !== true) {
2878
- registration.dispose();
2879
- throw new Error(`plugin method '${definition.service}.${definition.method}' did not mount.`);
2880
- }
2881
- this.ctx.effect(() => () => registration.dispose(), "server package method registration");
2882
- return registration;
2883
- };
2884
- mounted() {
2885
- return this.host.mounted();
2886
- }
2887
- mountedChannels() {
2888
- return this.host.mountedChannels();
2889
- }
2890
- };
2891
- /** Publishes the host service from inside a root-level plugin, so it unwinds with the scope. */
2892
- function serverHostProvider(context, host) {
2893
- new ScopedPoServerHost(context, host);
2894
- }
2895
- /** Publishes the platform services from inside a root-level plugin, so they unwind with the scope. */
2896
- function platformProvider(context, input) {
2897
- const env = input.platform.env(input.cwd);
2898
- context.provide(PO_FS_SERVICE, env);
2899
- context.provide(PO_SHELL_SERVICE, env);
2900
- context.provide(PO_SQLITE_SERVICE, input.platform.sqlite);
2901
- context.provide(PO_SESSION_STORAGE_SERVICE, input.platform.sessions);
2902
- if (input.platform.isolate !== void 0) context.provide(PO_ISOLATE_SERVICE, input.platform.isolate);
2903
- if (input.platform.npm !== void 0) context.provide(PO_NPM_SERVICE, input.platform.npm);
2904
- if (input.platform.electron !== void 0) context.provide(PO_ELECTRON_SERVICE, input.platform.electron);
2905
- if (input.platform.browser !== void 0) context.provide(PO_BROWSER_SERVICE, input.platform.browser);
2906
- if (input.temporaryDirectory !== void 0) context.provide(PO_SESSION_FILES_SERVICE, { temporaryDirectory: input.temporaryDirectory });
2907
- context.effect(() => () => env.cleanup(BACKGROUND_CONTEXT), "platform execution env");
2908
- }
2909
- /**
2910
- * One level of the server IoC tree: its own cordis root, a parent link, the contracts bound here,
2911
- * and the packages installed here.
2912
- *
2913
- * Separate roots rather than one shared root, because cordis re-checks every fiber of a root on each
2914
- * service change; a hundred sessions in one root would make every change scan all of them. A binding
2915
- * is instead mirrored into each descendant root as a native service, so a plugin injects an outer
2916
- * level's service exactly as it injects its own.
2917
- */
2918
- var PoServerScope = class PoServerScope {
2919
- level;
2920
- parent;
2921
- root = new Context();
2922
- children = /* @__PURE__ */ new Set();
2923
- bound = /* @__PURE__ */ new Map();
2924
- mirrors = /* @__PURE__ */ new Map();
2925
- /** A binding waiting here for the farther one it shadows to leave, so a repeat mirror waits too. */
2926
- replacing = /* @__PURE__ */ new Map();
2927
- installed = /* @__PURE__ */ new Map();
2928
- installs = Promise.resolve();
2929
- /** Set once a package's apply never settled, to the bound it overran; its fiber may never finish disposing. */
2930
- abandonedTimeoutMs;
2931
- notice = () => void 0;
2932
- disposing;
2933
- /** The served mount table, read when a request routes through this level. */
2934
- router;
2935
- /** Kept by the outermost scope only: what each plugin build shares across the whole tree. */
2936
- shares = /* @__PURE__ */ new Map();
2937
- /** Names this scope in logs, as its level and the order it opened in. */
2938
- label;
2939
- /** The last graph logged for a failing binding, by name, so a retry that fails the same way stays quiet. */
2940
- reported = /* @__PURE__ */ new Map();
2941
- constructor(level, parent) {
2942
- this.level = level;
2943
- this.parent = parent;
2944
- this.label = `${level}#${++scopesOpened}`;
2945
- }
2946
- /** Opens a scope below `parent`, with every binding visible from its ancestors already published. */
2947
- static async open(level, parent) {
2948
- if (parent?.disposing !== void 0) throw new Error(`The ${parent.level} scope is disposed.`);
2949
- if (parent !== void 0 && depth(level) <= depth(parent.level)) throw new Error(`A ${level} scope cannot open below a ${parent.level} scope.`);
2950
- const scope = new PoServerScope(level, parent);
2951
- parent?.children.add(scope);
2952
- try {
2953
- await scope.root.plugin(ScopeService, scope);
2954
- await Promise.all((parent?.visible() ?? []).map((binding) => scope.mirror(binding)));
2955
- } catch (error) {
2956
- await scope.dispose();
2957
- throw error;
2958
- }
2959
- return scope;
2960
- }
2961
- get disposed() {
2962
- return this.disposing !== void 0;
2963
- }
2964
- /**
2965
- * Publishes what every package at this level reads: the owner's mount table as `po/server-host`,
2966
- * and the platform services. They stay for the life of the scope; the owner still disposes the
2967
- * mount table it handed in.
2968
- */
2969
- async serve(input) {
2970
- if (this.disposed) throw new Error(`The ${this.level} scope is disposed.`);
2971
- if (input.host.scope !== this.level) throw new Error(`A ${input.host.scope} host cannot serve a ${this.level} scope.`);
2972
- await this.root.plugin(serverHostProvider, input.host);
2973
- this.router = input.host;
2974
- const hostContext = input.host.context;
2975
- const cwd = hostContext?.cwd ?? hostContext?.workspaceRoot ?? input.platform.homeDirectory;
2976
- await this.root.plugin(platformProvider, {
2977
- platform: input.platform,
2978
- cwd,
2979
- temporaryDirectory: this.level === "session" ? hostContext?.environment?.[PO_SESSION_TEMP_DIR] : void 0
2980
- });
2981
- }
2982
- /**
2983
- * Installs packages at this level, each as its own fiber in this root, one at a time.
2984
- *
2985
- * Installation only adds. A package installed from the same build (the same plugin object) is
2986
- * skipped. One whose build changed is disposed and the new build applied; when that fails, the
2987
- * previous build is applied again. A package missing from `packages` stays installed, because
2988
- * which packages a session runs is its own composition's choice. Installs into one scope run one
2989
- * at a time. Resolves with every package installed here, in install order.
2990
- */
2991
- install(packages, options = {}) {
2992
- const run = this.installs.then(() => this.installAll(packages, options));
2993
- this.installs = run.then(() => void 0, () => void 0);
2994
- return run;
2995
- }
2996
- /**
2997
- * Disposes the named packages installed here, in reverse install order, each bounded by the
2998
- * cleanup time limit. Runs in order with installs. Resolves with every package still installed.
2999
- */
3000
- uninstall(names) {
3001
- const run = this.installs.then(async () => {
3002
- if (this.disposed) throw new Error(`The ${this.level} scope is disposed.`);
3003
- for (const [name, { fiber }] of [...this.installed].reverse()) {
3004
- if (!names.includes(name)) continue;
3005
- this.installed.delete(name);
3006
- await this.disposeFiber(name, fiber, LIVE_FACTORY_TIMEOUT_MS);
3007
- }
3008
- return [...this.installed.keys()];
3009
- });
3010
- this.installs = run.then(() => void 0, () => void 0);
3011
- return run;
3012
- }
3013
- /**
3014
- * Binds a contract owned by this level here and in every descendant, including ones opened later.
3015
- * Settles once every descendant root publishes it, or a nearer binding of the same name shadows it
3016
- * there. Hosts call this directly; plugins go through the scope service so the binding follows
3017
- * their fiber.
3018
- */
3019
- async bind(contract, value) {
3020
- if (this.disposed) throw new Error(`The ${this.level} scope is disposed.`);
3021
- if (contract.scope !== this.level) throw new Error(`Contract '${contract.name}' belongs to the ${contract.scope} scope and cannot be provided from the ${this.level} scope.`);
3022
- if (this.bound.has(contract.name)) throw new Error(`Contract '${contract.name}' is already provided in this ${this.level} scope.`);
3023
- const binding = {
3024
- name: contract.name,
3025
- value,
3026
- owner: this
3027
- };
3028
- this.bound.set(contract.name, binding);
3029
- const withdraw = async () => {
3030
- if (this.bound.get(contract.name) !== binding) return;
3031
- this.bound.delete(contract.name);
3032
- await Promise.all([...this.subtree()].map(async (scope) => {
3033
- await scope.unmirror(binding);
3034
- const outer = scope.nearest(contract.name);
3035
- if (outer === void 0) return;
3036
- await scope.mirror(outer).catch((error) => {
3037
- this.notice(`binding '${contract.name}' from ${outer.owner.label} did not return to ${scope.label} (${describe(error)})`);
3038
- });
3039
- }));
3040
- };
3041
- try {
3042
- await Promise.all([...this.subtree()].map((scope) => scope.mirror(binding)));
3043
- } catch (error) {
3044
- this.reportGraph(contract.name, error);
3045
- await withdraw();
3046
- throw error;
3047
- }
3048
- return withdraw;
3049
- }
3050
- resolve(contract) {
3051
- if (depth(contract.scope) > depth(this.level)) throw new Error(`A ${this.level} scope cannot see the ${contract.scope} contract '${contract.name}'.`);
3052
- for (const scope of this.ancestry()) if (scope.level === contract.scope) return scope.bound.get(contract.name)?.value;
3053
- }
3054
- /**
3055
- * The handler for an API, from this level or the nearest one above it that serves it. An API
3056
- * declared at a level reaches every level below it, and a level that runs a package from an outer
3057
- * level leaves that level's root-bound APIs to it; a level that declares the API itself wins.
3058
- */
3059
- apiHandler(basePath) {
3060
- for (const scope of this.ancestry()) {
3061
- const handler = scope.router?.handlerFor?.(basePath);
3062
- if (handler !== void 0) return handler;
3063
- }
3064
- }
3065
- /** Resolve only the nearest mounted API's parsed contract, never a caller supplied operation. */
3066
- apiOperation(basePath, method, path) {
3067
- for (const scope of this.ancestry()) {
3068
- if (!scope.router?.handlerFor?.(basePath)) continue;
3069
- for (const { declaration } of scope.installed.values()) {
3070
- const route = declaration?.apiContract?.http.find((route) => route.scope === scope.level && route.basePath === basePath && route.method === method && route.path.split("/").length === path.split("/").length && route.path.split("/").every((part, index) => part.startsWith(":") ? !!path.split("/")[index] : part === path.split("/")[index]));
3071
- if (route) return route.id;
3072
- }
3073
- return;
3074
- }
3075
- }
3076
- emit(name, ...args) {
3077
- deliver([...this.ancestry()], name, args);
3078
- }
3079
- broadcast(name, ...args) {
3080
- deliver([...this.subtree()], name, args);
3081
- }
3082
- /**
3083
- * Disposes descendants first, then the packages installed here in reverse install order, then
3084
- * this root; a binding made here unwinds with its provider.
3085
- */
3086
- dispose() {
3087
- this.disposing ??= (async () => {
3088
- await Promise.all([...this.children].map((child) => child.dispose()));
3089
- this.parent?.children.delete(this);
3090
- this.mirrors.clear();
3091
- this.router = void 0;
3092
- const packages = [...this.installed.values()].reverse();
3093
- this.installed.clear();
3094
- for (const { plugin, declaration, fiber } of packages) await this.disposeFiber(declaration?.packageName ?? plugin.name, fiber, LIVE_FACTORY_TIMEOUT_MS);
3095
- const disposal = this.root.fiber.dispose();
3096
- if (this.abandonedTimeoutMs === void 0) return await disposal;
3097
- await withTimeout(disposal, this.abandonedTimeoutMs, `${this.level} scope dispose`).catch((error) => this.notice(describe(error)));
3098
- })().finally(async () => {
3099
- if (this.parent === void 0) await this.disposeShares();
3100
- });
3101
- return this.disposing;
3102
- }
3103
- /**
3104
- * What the plugin build `owner` shares in this tree, seen from this scope. The outermost scope keeps
3105
- * one store per build, so every level of one hub sees the same values and no two hubs ever do.
3106
- */
3107
- share(owner) {
3108
- const top = this.outermost();
3109
- const name = nameOf(owner);
3110
- const build = buildOf(owner);
3111
- for (const scope of this.parent?.ancestry() ?? []) for (const [other, store] of top.shares) if (other !== owner && name !== void 0 && nameOf(other) === name && store.running.has(scope)) this.notice(`${this.label} mounts ${build} of '${name}' while ${scope.label} runs ${buildOf(other)}, so it builds that build's roots itself.`);
3112
- const storeOf = () => {
3113
- let store = top.shares.get(owner);
3114
- if (store === void 0) {
3115
- store = new PluginShare();
3116
- top.shares.set(owner, store);
3117
- }
3118
- return store;
3119
- };
3120
- const settle = (store) => {
3121
- if (store.idle && top.shares.get(owner) === store) top.shares.delete(owner);
3122
- };
3123
- return {
3124
- acquire: async (key, create, dispose) => {
3125
- if (this.disposed) throw new Error(`The ${this.level} scope is disposed.`);
3126
- const store = storeOf();
3127
- const name = resourceName(key);
3128
- let shared = store.values.get(name);
3129
- if (shared === void 0) {
3130
- const created = {
3131
- value: Promise.resolve().then(create),
3132
- holders: 0,
3133
- disposeValue: dispose === void 0 ? void 0 : (value) => dispose(value)
3134
- };
3135
- store.values.set(name, created);
3136
- created.value.catch(() => {
3137
- if (store.values.get(name) === created) store.values.delete(name);
3138
- settle(store);
3139
- });
3140
- shared = created;
3141
- }
3142
- const held = shared;
3143
- held.holders += 1;
3144
- let value;
3145
- try {
3146
- value = await held.value;
3147
- } catch (error) {
3148
- held.holders -= 1;
3149
- throw error;
3150
- }
3151
- let released = false;
3152
- return {
3153
- value,
3154
- release: async () => {
3155
- if (released) return;
3156
- released = true;
3157
- held.holders -= 1;
3158
- if (held.holders > 0 || store.values.get(name) !== held) return;
3159
- store.values.delete(name);
3160
- settle(store);
3161
- await held.disposeValue?.(value);
3162
- }
3163
- };
3164
- },
3165
- run: (roots) => {
3166
- if (this.disposed) throw new Error(`The ${this.level} scope is disposed.`);
3167
- const store = storeOf();
3168
- store.running.set(this, roots);
3169
- return () => {
3170
- if (store.running.get(this) === roots) store.running.delete(this);
3171
- settle(store);
3172
- };
3173
- },
3174
- outer: (from) => {
3175
- const store = top.shares.get(owner);
3176
- if (store === void 0) return [];
3177
- const held = [];
3178
- for (const scope of this.parent?.ancestry() ?? []) if (depth(scope.level) >= depth(from) && store.running.has(scope)) held.push(store.running.get(scope));
3179
- return held;
3180
- }
3181
- };
3182
- }
3183
- async installAll(packages, options) {
3184
- if (this.disposed) throw new Error(`The ${this.level} scope is disposed.`);
3185
- const notice = options.onNotice ?? (() => {});
3186
- this.notice = notice;
3187
- if (packages.some((candidate) => "retained" in candidate && candidate.retained === true) && !readPoHeadlessHost(this.root)) throw new Error("Retained server candidates require a gated headless host");
3188
- for (const candidate of packages) {
3189
- const plugin = "declaration" in candidate ? candidate.plugin : candidate;
3190
- const declaration = "declaration" in candidate ? candidate.declaration : void 0;
3191
- const name = declaration?.packageName ?? plugin.name;
3192
- const previous = this.installed.get(name);
3193
- if (previous?.plugin === plugin) continue;
3194
- if (previous !== void 0) {
3195
- this.installed.delete(name);
3196
- await this.disposeFiber(name, previous.fiber, options.factoryTimeoutMs ?? 1e4);
3197
- }
3198
- try {
3199
- const fiber = await this.apply(name, plugin, declaration, options);
3200
- this.installed.set(name, {
3201
- plugin,
3202
- ...declaration === void 0 ? {} : { declaration },
3203
- fiber
3204
- });
3205
- } catch (error) {
3206
- const message = `server package '${name}' did not install (${describe(error)})`;
3207
- if (previous !== void 0) {
3208
- const restored = await this.restore(name, previous, options, message);
3209
- options.onPackageFailed?.({
3210
- packageName: name,
3211
- reason: describe(error),
3212
- previous: restored ? "restored" : "lost"
3213
- });
3214
- continue;
3215
- }
3216
- options.onPackageFailed?.({
3217
- packageName: name,
3218
- reason: describe(error),
3219
- previous: "none"
3220
- });
3221
- if (declaration?.required === true && !("initiallyEligible" in candidate && candidate.initiallyEligible === false)) throw new Error(message, { cause: error });
3222
- notice(message);
3223
- }
3224
- }
3225
- for (const candidate of packages) {
3226
- const plugin = "declaration" in candidate ? candidate.plugin : candidate;
3227
- const name = ("declaration" in candidate ? candidate.declaration.packageName : void 0) ?? plugin.name;
3228
- if (this.installed.get(name)?.plugin !== plugin) continue;
3229
- for (const contract of plugin.injects?.[this.level] ?? []) if (depth(contract.scope) > depth(this.level) || this.resolve(contract) === void 0) notice(`server package '${name}' waits for contract '${contract.name}', which no ${contract.scope} package provides.`);
3230
- }
3231
- return [...this.installed.keys()];
3232
- }
3233
- /** Applies a replaced package's previous build again after its new build failed; true when it runs. */
3234
- async restore(name, previous, options, message) {
3235
- try {
3236
- const fiber = await this.apply(name, previous.plugin, previous.declaration, options);
3237
- this.installed.set(name, {
3238
- ...previous,
3239
- fiber
3240
- });
3241
- this.notice(`${message}; its previous build is restored.`);
3242
- return true;
3243
- } catch (rollbackError) {
3244
- this.notice(`${message}; its previous build could not be restored (${describe(rollbackError)}).`);
3245
- return false;
3246
- }
3247
- }
3248
- /** Applies one package as its own fiber, bounded by the factory timeout, and reports how it settled. */
3249
- async apply(name, plugin, declaration, options) {
3250
- const startedAt = Date.now();
3251
- const timeoutMs = options.factoryTimeoutMs ?? 1e4;
3252
- const settled = (outcome) => options.onPackageSettled?.({
3253
- packageName: name,
3254
- durationMs: Date.now() - startedAt,
3255
- outcome
3256
- });
3257
- let fiber;
3258
- let applySettled = false;
3259
- try {
3260
- fiber = (declaration ? this.root.extend({ [PO_HEADLESS_OWNER]: declaration }) : this.root).plugin(plugin);
3261
- const applied = fiber.await();
3262
- const markSettled = () => {
3263
- applySettled = true;
3264
- };
3265
- applied.then(markSettled, markSettled);
3266
- await withTimeout(applied, timeoutMs, `server package '${name}' apply`);
3267
- settled("installed");
3268
- return fiber;
3269
- } catch (error) {
3270
- settled(fiber && !applySettled ? "timed_out" : "failed");
3271
- if (fiber && !applySettled) {
3272
- this.abandonedTimeoutMs = Math.max(this.abandonedTimeoutMs ?? 0, timeoutMs);
3273
- fiber.dispose().catch((disposeError) => this.notice(`abandoned server package '${name}' did not dispose (${describe(disposeError)})`));
3274
- } else if (fiber) await this.disposeFiber(name, fiber, timeoutMs);
3275
- throw error;
3276
- }
3277
- }
3278
- /**
3279
- * Disposes one package's fiber within `timeoutMs`. A package whose cleanup throws or never settles
3280
- * is reported and left behind, so it cannot block the packages after it or the scope's teardown.
3281
- */
3282
- async disposeFiber(name, fiber, timeoutMs) {
3283
- try {
3284
- await withTimeout(fiber.dispose(), timeoutMs, `server package '${name}' dispose`);
3285
- } catch (error) {
3286
- this.abandonedTimeoutMs = Math.max(this.abandonedTimeoutMs ?? 0, timeoutMs);
3287
- this.notice(`server package '${name}' did not dispose (${describe(error)})`);
3288
- }
3289
- }
3290
- visible() {
3291
- return [...this.parent?.visible() ?? [], ...this.bound.values()];
3292
- }
3293
- /**
3294
- * Logs, once per distinct tree, which scopes bind `name`, whose binding each root mirrors, and
3295
- * which Cordis fiber actually holds the service in that root.
3296
- */
3297
- reportGraph(name, error) {
3298
- const top = this.outermost();
3299
- const graph = [...top.subtree()].map((scope) => {
3300
- const context = scope.router?.context;
3301
- const cwd = context?.cwd ?? context?.workspaceRoot;
3302
- const holds = [...scope.mirrors.keys()].filter((binding) => binding.name === name).map(({ owner }) => owner.label);
3303
- const impl = scope.root.reflect._getImpl(name, false);
3304
- const mirrored = impl && [...scope.mirrors].find(([, fiber]) => fiber === impl.fiber)?.[0];
3305
- const cordis = impl === void 0 ? "none" : `<${impl.fiber.name}#${impl.fiber.uid}> state=${impl.fiber.state}${mirrored ? ` from ${mirrored.owner.label}` : ""}`;
3306
- return `${" ".repeat(depth(scope.level))}${scope.label}${cwd ? ` ${cwd}` : ""} binds=${scope.bound.has(name) ? "yes" : "no"} mirrors=[${holds.join(", ")}] cordis=${cordis}`;
3307
- }).join("\n");
3308
- if (top.reported.get(name) === graph) return;
3309
- top.reported.set(name, graph);
3310
- this.notice(`binding '${name}' from ${this.label} failed (${describe(error)}); scope tree:\n${graph}`);
3311
- }
3312
- /** This scope, then each parent out to the root. */
3313
- outermost() {
3314
- return this.parent === void 0 ? this : this.parent.outermost();
3315
- }
3316
- /** Disposes every value the tree still holds, newest first; a failure is reported and the rest still go. */
3317
- async disposeShares() {
3318
- const values = [...this.shares.values()].flatMap((store) => [...store.values.values()]).reverse();
3319
- this.shares.clear();
3320
- for (const shared of values) try {
3321
- await shared.disposeValue?.(await shared.value);
3322
- } catch (error) {
3323
- this.notice(`a shared server value did not dispose (${describe(error)})`);
3324
- }
3325
- }
3326
- *ancestry() {
3327
- yield this;
3328
- if (this.parent !== void 0) yield* this.parent.ancestry();
3329
- }
3330
- *subtree() {
3331
- if (this.disposed) return;
3332
- yield this;
3333
- for (const child of this.children) yield* child.subtree();
3334
- }
3335
- /** The binding of `name` this root publishes: the one bound nearest to it. */
3336
- nearest(name) {
3337
- for (const scope of this.ancestry()) {
3338
- const binding = scope.bound.get(name);
3339
- if (binding !== void 0) return binding;
3340
- }
3341
- }
3342
- /**
3343
- * Publishes a binding into this root and settles once it is live. Idempotent per binding, since a
3344
- * child opening mid-bind is reached by both `open` and `bind`. A nearer level binding the same
3345
- * name wins, as a level declaring an API itself does; Cordis holds one service per name in a root,
3346
- * so the farther binding leaves first.
3347
- */
3348
- async mirror(binding) {
3349
- if (this.disposed || this.nearest(binding.name) !== binding) return;
3350
- const replacing = this.replacing.get(binding);
3351
- if (replacing !== void 0) {
3352
- await replacing;
3353
- return await this.mirror(binding);
3354
- }
3355
- let fiber = this.mirrors.get(binding);
3356
- if (fiber === void 0) {
3357
- const shadowed = [...this.mirrors.keys()].filter((other) => other.name === binding.name);
3358
- if (shadowed.length > 0) {
3359
- const cleared = Promise.all(shadowed.map((other) => this.unmirror(other))).finally(() => this.replacing.delete(binding));
3360
- this.replacing.set(binding, cleared.then(() => void 0, () => void 0));
3361
- await cleared;
3362
- return await this.mirror(binding);
3363
- }
3364
- fiber = this.root.plugin(bindingProvider, binding);
3365
- this.mirrors.set(binding, fiber);
3366
- }
3367
- try {
3368
- await fiber.await();
3369
- } catch (error) {
3370
- throw new Error(`${describe(error)} when ${binding.owner.label} published it into ${this.label}`, { cause: error });
3371
- }
3372
- }
3373
- async unmirror(binding) {
3374
- const fiber = this.mirrors.get(binding);
3375
- this.mirrors.delete(binding);
3376
- if (!this.disposed) await fiber?.dispose();
3377
- }
3378
- };
3379
- /** Every scope receives the event even when an earlier one's listener throws. */
3380
- function deliver(scopes, name, args) {
3381
- const errors = [];
3382
- for (const scope of scopes) {
3383
- if (scope.disposed) continue;
3384
- try {
3385
- scope.root.events.emit(name, ...args);
3386
- } catch (error) {
3387
- errors.push(error);
3388
- }
3389
- }
3390
- if (errors.length > 0) throw new AggregateError(errors, `${errors.length} scope listener(s) of '${name}' failed.`);
3391
- }
3392
- //#endregion
3393
- export { readPoHeadlessOwner as $, seqFromNumber as A, requirePoFs as B, defineDoc as C, materializeDocumentValue as D, materializeDocument as E, PO_SQLITE_SERVICE as F, PoHeadlessPromptAdmissionError as G, PO_HEADLESS_HOST_SERVICE as H, readPoBrowser as I, dropInvalidImages as J, PoHeadlessToolBusyError as K, readPoFs as L, PO_BROWSER_SERVICE as M, PO_FS_SERVICE as N, resolveAddress as O, PO_SHELL_SERVICE as P, readPoHeadlessHost as Q, readPoIsolate as R, checkRecordVersion as S, documentCreate as T, PO_LOAD_SKILL_TOOL as U, requirePoSqlite as V, PO_SEARCH_SKILLS_TOOL as W, isPoHeadlessPromptAdmissionError as X, invalidImageReason as Y, isPoHeadlessToolModelVisible as Z, LabelsDoc as _, defineServiceContract as _t, piAgentDirectory as a, requirePoServerHost as at, addressId as b, nodeHost as c, withAbortSignal as ct, err as d, createTypedSpanStarter as dt, Service as et, getOrThrow as f, defineTelemetrySchema as ft, IdentityHistoryDoc as g, PO_SERVER_SCOPE_SERVICE as gt, FastModeDoc as h, PO_SERVER_SCOPE_LEVELS as ht, prepareSessionEnvironment as i, defineServerMethod as it, copyJson as j, idFromNumber as k, ExecutionError as l, withTelemetry as lt, AgentLockDoc as m, NOOP_TELEMETRY_METRICS as mt, PO_SESSION_FILES_SERVICE as n, PO_SERVER_HOST_SERVICE as nt, poHomeDirectory as o, BACKGROUND_CONTEXT as ot, ok as p, NOOP_TELEMETRY_CONTEXT as pt, PoSessionSetupError as q, PO_SESSION_TEMP_DIR as r, composeServerProviderOverrides as rt, createSerialRunner as s, awaitWithContext as st, PoServerScope as t, guardedImport as tt, FileError as u, withoutAbortSignal as ut, SessionIdentityDoc as v, requirePoServerScope as vt, defineDocFamily as w, checkRecordScope as x, SessionMetadataDoc as y, readPoNpm as z };