@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,4 +1,675 @@
1
1
  import { n as __exportAll } from "./rolldown-runtime-B-lAHAz2.js";
2
+ import { r as NOOP_TELEMETRY_CONTEXT } from "./dist-Dvx5mlIR.js";
3
+ import { createHash } from "node:crypto";
4
+ import path from "node:path";
5
+ //#region ../../core/po-core/src/schemas/serverScope.ts
6
+ /**
7
+ * The server inversion-of-control tree: global, then one scope per workspace, then one per session.
8
+ *
9
+ * Each level has its own cordis root. A contract names an abstract service and the one level whose
10
+ * plugin binds the concrete value; every descendant level sees that value as a native cordis service,
11
+ * so `inject` and `ctx.get` work unchanged. A level never sees a contract bound below it.
12
+ */
13
+ const PO_SERVER_SCOPE_SERVICE = "po/server-scope";
14
+ /** Outermost first, so a lower index is an ancestor level. */
15
+ const PO_SERVER_SCOPE_LEVELS = [
16
+ "global",
17
+ "workspace",
18
+ "session"
19
+ ];
20
+ function defineServiceContract(name, options) {
21
+ return {
22
+ name,
23
+ scope: options.scope,
24
+ ...options.description === void 0 ? {} : { description: options.description }
25
+ };
26
+ }
27
+ /** Retain only detached public provenance, never structural contract extras or type carriers. */
28
+ function projectServiceBindingMetadata(metadata) {
29
+ return {
30
+ owner: {
31
+ kind: metadata.owner.kind,
32
+ packageName: metadata.owner.packageName,
33
+ origin: metadata.owner.origin
34
+ },
35
+ contracts: metadata.contracts.map(({ name, scope, description }) => ({
36
+ name,
37
+ scope,
38
+ ...description === void 0 ? {} : { description }
39
+ }))
40
+ };
41
+ }
42
+ function readPoServerScope(context) {
43
+ return context.get(PO_SERVER_SCOPE_SERVICE);
44
+ }
45
+ function requirePoServerScope(context) {
46
+ const service = readPoServerScope(context);
47
+ if (!service) throw new Error("The Po server scope is unavailable. Install packages through a Po server scope.");
48
+ return service;
49
+ }
50
+ //#endregion
51
+ //#region ../../core/po-core/src/schemas/platform.ts
52
+ const PO_FS_SERVICE = "po/fs";
53
+ const PO_SHELL_SERVICE = "po/shell";
54
+ const PO_SQLITE_SERVICE = "po/sqlite";
55
+ const PO_SESSION_STORAGE_SERVICE = "po/session-storage";
56
+ const PO_ISOLATE_SERVICE = "po/isolate";
57
+ const PO_NPM_SERVICE = "po/npm";
58
+ const PO_ELECTRON_SERVICE = "po/electron";
59
+ const PO_BROWSER_SERVICE = "po/browser";
60
+ const PO_PROVIDER_AUTH_SERVICE = "po/provider-auth";
61
+ function readPoFs(context) {
62
+ return context.get(PO_FS_SERVICE);
63
+ }
64
+ function requirePoFs(context) {
65
+ const service = readPoFs(context);
66
+ if (!service) throw new Error(`The '${PO_FS_SERVICE}' service is unavailable. Start a Po server first.`);
67
+ return service;
68
+ }
69
+ function requirePoSqlite(context) {
70
+ const service = context.get(PO_SQLITE_SERVICE);
71
+ if (!service) throw new Error(`The '${PO_SQLITE_SERVICE}' service is unavailable. Start a Po server first.`);
72
+ return service;
73
+ }
74
+ function readPoNpm(context) {
75
+ return context.get(PO_NPM_SERVICE);
76
+ }
77
+ function readPoBrowser(context) {
78
+ return context.get(PO_BROWSER_SERVICE);
79
+ }
80
+ function readPoIsolate(context) {
81
+ return context.get(PO_ISOLATE_SERVICE);
82
+ }
83
+ //#endregion
84
+ //#region ../../../node_modules/.pnpm/@earendil-works+chord@1.5.0_esbuild@0.28.2/node_modules/@earendil-works/chord/dist/context/index.js
85
+ const ABORT_SIGNAL_CONTEXT_KEY = Object.freeze({ token: Symbol("chord.abortSignal") });
86
+ const TELEMETRY_CONTEXT_KEY = Object.freeze({ token: Symbol("chord.telemetry") });
87
+ var BaseContext = class {
88
+ get abortSignal() {
89
+ return this.value(ABORT_SIGNAL_CONTEXT_KEY);
90
+ }
91
+ get telemetry() {
92
+ return this.value(TELEMETRY_CONTEXT_KEY) ?? NOOP_TELEMETRY_CONTEXT;
93
+ }
94
+ };
95
+ var EmptyContext = class extends BaseContext {
96
+ #name;
97
+ constructor(name) {
98
+ super();
99
+ this.#name = name;
100
+ }
101
+ value(_key) {}
102
+ toString() {
103
+ return this.#name;
104
+ }
105
+ };
106
+ var ContextValue = class extends BaseContext {
107
+ #parent;
108
+ #key;
109
+ #value;
110
+ constructor(parent, key, value) {
111
+ super();
112
+ this.#parent = parent;
113
+ this.#key = key;
114
+ this.#value = value;
115
+ }
116
+ value(key) {
117
+ if (key.token === this.#key.token) return this.#value;
118
+ return this.#parent.value(key);
119
+ }
120
+ toString() {
121
+ return `${this.#parent}.WithValue(${this.#key.token.description ?? "anonymous"})`;
122
+ }
123
+ };
124
+ const BACKGROUND_CONTEXT = new EmptyContext("[Context BACKGROUND_CONTEXT]");
125
+ new EmptyContext("[Context TODO_CONTEXT]");
126
+ /** Derive a context containing one additional or replaced value. */
127
+ function withContextValue(key, value, parent) {
128
+ return new ContextValue(parent, key, value);
129
+ }
130
+ /** Derive an explicit telemetry parent without changing cancellation or application values. */
131
+ function withTelemetry(telemetry, context) {
132
+ return withContextValue(TELEMETRY_CONTEXT_KEY, telemetry, context);
133
+ }
134
+ /**
135
+ * Derive a context cancelled by either the parent signal or the supplied signal.
136
+ * The parent context remains unchanged.
137
+ */
138
+ function withAbortSignal(signal, context) {
139
+ const parentSignal = context.abortSignal;
140
+ const combined = parentSignal === void 0 ? signal : AbortSignal.any([parentSignal, signal]);
141
+ return withContextValue(ABORT_SIGNAL_CONTEXT_KEY, combined, context);
142
+ }
143
+ /** Derive a context retaining all values except caller cancellation. Intended for mandatory cleanup only. */
144
+ function withoutAbortSignal(context) {
145
+ return withContextValue(ABORT_SIGNAL_CONTEXT_KEY, void 0, context);
146
+ }
147
+ /**
148
+ * Observe a promise until it settles or the invocation is cancelled.
149
+ * Cancellation rejects only this waiter; it does not cancel the underlying promise.
150
+ */
151
+ function awaitWithContext(promise, context) {
152
+ const signal = context.abortSignal;
153
+ if (signal === void 0) return promise;
154
+ if (signal.aborted) return Promise.reject(abortError(signal));
155
+ return new Promise((resolve, reject) => {
156
+ const onAbort = () => reject(abortError(signal));
157
+ signal.addEventListener("abort", onAbort, { once: true });
158
+ promise.then((value) => {
159
+ signal.removeEventListener("abort", onAbort);
160
+ resolve(value);
161
+ }, (error) => {
162
+ signal.removeEventListener("abort", onAbort);
163
+ reject(error);
164
+ });
165
+ });
166
+ }
167
+ function abortError(signal) {
168
+ const reason = signal.reason;
169
+ return reason instanceof Error ? reason : new DOMException("The operation was aborted", "AbortError");
170
+ }
171
+ //#endregion
172
+ //#region ../../../node_modules/.pnpm/@earendil-works+chord@1.5.0_esbuild@0.28.2/node_modules/@earendil-works/chord/dist/json.js
173
+ const DATA_DESCRIPTOR = {
174
+ value: void 0,
175
+ writable: true,
176
+ enumerable: true,
177
+ configurable: true
178
+ };
179
+ /** Copy a value into an alias-free strict-JSON tree owned by the caller. */
180
+ function copyJson(value, options) {
181
+ return copy(value, void 0, options?.omitUndefinedProperties === true);
182
+ }
183
+ function copy(value, ancestors, omitUndefinedProperties) {
184
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
185
+ if (typeof value === "number") {
186
+ if (Number.isFinite(value)) return value;
187
+ throw new TypeError("Value contains a non-finite number and is not strict JSON");
188
+ }
189
+ if (typeof value !== "object") throw new TypeError(`Value contains a non-JSON ${typeof value}; expected strict JSON`);
190
+ const active = ancestors ?? /* @__PURE__ */ new Set();
191
+ if (active.has(value)) throw new TypeError("Value contains cycles and is not strict JSON");
192
+ active.add(value);
193
+ try {
194
+ if (Array.isArray(value)) {
195
+ if (Object.getPrototypeOf(value) !== Array.prototype || Reflect.ownKeys(value).length !== value.length + 1) throw new TypeError("Value must contain strict JSON dense plain arrays");
196
+ const result = new Array(value.length);
197
+ for (let index = 0; index < value.length; index++) {
198
+ const descriptor = Object.getOwnPropertyDescriptor(value, index);
199
+ if (descriptor === void 0 || !descriptor.enumerable || !("value" in descriptor)) throw new TypeError("Value must contain strict JSON enumerable indexed data properties");
200
+ defineData(result, String(index), copy(descriptor.value, active, omitUndefinedProperties));
201
+ }
202
+ return result;
203
+ }
204
+ const prototype = Object.getPrototypeOf(value);
205
+ if (prototype !== Object.prototype && prototype !== null) throw new TypeError("Value must contain strict JSON plain objects or arrays");
206
+ const result = Object.create(prototype);
207
+ for (const key of Reflect.ownKeys(value)) {
208
+ if (typeof key === "symbol") throw new TypeError("Value contains a symbol key and is not strict JSON");
209
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
210
+ if (!descriptor.enumerable || !("value" in descriptor)) throw new TypeError("Value must contain strict JSON enumerable data properties");
211
+ if (descriptor.value === void 0 && omitUndefinedProperties) continue;
212
+ defineData(result, key, copy(descriptor.value, active, omitUndefinedProperties));
213
+ }
214
+ return result;
215
+ } finally {
216
+ active.delete(value);
217
+ }
218
+ }
219
+ function defineData(target, key, value) {
220
+ DATA_DESCRIPTOR.value = value;
221
+ Object.defineProperty(target, key, DATA_DESCRIPTOR);
222
+ DATA_DESCRIPTOR.value = void 0;
223
+ }
224
+ //#endregion
225
+ //#region ../../../node_modules/.pnpm/@earendil-works+pi-durable@1.5.0_patch_hash=0f5e595daa4c370af407284d99d6dba48a9e21f56aa_fbb51180c4b193ec70152883060baa79/node_modules/@earendil-works/pi-durable/dist/ids.js
226
+ /** Apply an erased ID brand at a trusted numeric allocation or decoding boundary. */
227
+ function idFromNumber(value) {
228
+ return value;
229
+ }
230
+ /** Apply the erased commit-sequence brand at a trusted storage boundary. */
231
+ function seqFromNumber(value) {
232
+ return value;
233
+ }
234
+ //#endregion
235
+ //#region ../../../node_modules/.pnpm/@earendil-works+pi-durable@1.5.0_patch_hash=0f5e595daa4c370af407284d99d6dba48a9e21f56aa_fbb51180c4b193ec70152883060baa79/node_modules/@earendil-works/pi-durable/dist/documents.js
236
+ function defineDoc(definition) {
237
+ validateDefinition(definition);
238
+ return { definition };
239
+ }
240
+ function defineDocFamily(definition) {
241
+ validateDefinition(definition);
242
+ return { definition };
243
+ }
244
+ function validateDefinition(definition) {
245
+ if (!Number.isSafeInteger(definition.version) || definition.version < 1) throw new TypeError(`Document ${definition.kind} version must be a positive integer`);
246
+ }
247
+ /** Resolve an overloaded argument list and return the index after the owner and family key. */
248
+ function resolveAddress(definition, args) {
249
+ let index = 0;
250
+ let scope;
251
+ switch (definition.scope) {
252
+ case "session":
253
+ scope = { kind: "session" };
254
+ break;
255
+ case "conversation":
256
+ scope = {
257
+ kind: "conversation",
258
+ conversationId: ownerId(args[index++], definition)
259
+ };
260
+ break;
261
+ case "task": scope = {
262
+ kind: "task",
263
+ taskId: ownerId(args[index++], definition)
264
+ };
265
+ }
266
+ const key = definition.family === true ? args[index++] : void 0;
267
+ const address = key === void 0 ? {
268
+ kind: definition.kind,
269
+ scope
270
+ } : {
271
+ kind: definition.kind,
272
+ scope,
273
+ key
274
+ };
275
+ return {
276
+ address,
277
+ id: addressId(address),
278
+ nextArgument: index
279
+ };
280
+ }
281
+ function ownerId(value, definition) {
282
+ if (typeof value !== "number" || !Number.isSafeInteger(value)) throw new TypeError(`Document ${definition.kind} requires a ${definition.scope} ID`);
283
+ return idFromNumber(value);
284
+ }
285
+ /** Stable string identity of one logical address. */
286
+ function addressId(address) {
287
+ const owner = address.scope.kind === "session" ? null : address.scope.kind === "conversation" ? address.scope.conversationId : address.scope.taskId;
288
+ return JSON.stringify([
289
+ address.kind,
290
+ address.scope.kind,
291
+ owner,
292
+ address.key ?? null
293
+ ]);
294
+ }
295
+ /** Build the storage create record for a new incarnation at an address. */
296
+ function documentCreate(definition, address, id) {
297
+ const key = address.key === void 0 ? {} : { key: address.key };
298
+ switch (address.scope.kind) {
299
+ case "session": return {
300
+ id,
301
+ kind: address.kind,
302
+ ...key,
303
+ scope: address.scope
304
+ };
305
+ case "task": return {
306
+ id,
307
+ kind: address.kind,
308
+ ...key,
309
+ scope: address.scope
310
+ };
311
+ case "conversation": return {
312
+ id,
313
+ kind: address.kind,
314
+ ...key,
315
+ scope: address.scope,
316
+ history: definition.history,
317
+ fork: definition.fork
318
+ };
319
+ }
320
+ }
321
+ /** Reject typed access whose token disagrees with the persisted scope, history, or fork semantics. */
322
+ function checkRecordScope(definition, record) {
323
+ 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`);
324
+ }
325
+ /** Reject typed access to a stored version the supplied definition cannot use. */
326
+ function checkRecordVersion(definition, record, version) {
327
+ if (version > definition.version) throw new Error(`Document ${record.id} (${record.kind}) has newer version ${version} than ${definition.version}`);
328
+ if (version < definition.version && definition.migrate === void 0) throw new Error(`Document ${record.id} (${record.kind}) requires migration from version ${version}`);
329
+ }
330
+ /** Validate and materialize a detached stored value for typed access. */
331
+ function materializeDocument(definition, stored) {
332
+ return materializeDocumentValue(definition, stored.record, stored.version, stored.value);
333
+ }
334
+ /** Validate and materialize one detached value before its first persisted incarnation. */
335
+ function materializeDocumentValue(definition, record, version, value) {
336
+ checkRecordScope(definition, record);
337
+ checkRecordVersion(definition, record, version);
338
+ if (version === definition.version) return value;
339
+ return copyJson(definition.migrate(value, version));
340
+ }
341
+ //#endregion
342
+ //#region ../../core/po-core/src/services/durableSession/docs.ts
343
+ /** Public string identity belongs to Po, not the durable numeric ID namespace. */
344
+ const SessionIdentityDoc = defineDoc({
345
+ kind: "po.session.identity",
346
+ checkpointWhen: () => false,
347
+ version: 1,
348
+ scope: "session",
349
+ initial: () => ({
350
+ id: "",
351
+ createdAt: 0,
352
+ parentSessionId: ""
353
+ })
354
+ });
355
+ const SessionMetadataDoc = defineDoc({
356
+ kind: "po.session.metadata",
357
+ checkpointWhen: () => false,
358
+ version: 1,
359
+ scope: "session",
360
+ initial: () => ({
361
+ name: "",
362
+ workspaceRoot: "",
363
+ execution: "",
364
+ laneName: "main",
365
+ groups: []
366
+ })
367
+ });
368
+ const FastModeDoc = defineDoc({
369
+ kind: "po.fast-mode",
370
+ checkpointWhen: () => false,
371
+ version: 1,
372
+ scope: "session",
373
+ initial: () => ({ enabled: false })
374
+ });
375
+ const AgentLockDoc = defineDoc({
376
+ kind: "po.agent-lock",
377
+ checkpointWhen: () => false,
378
+ version: 1,
379
+ scope: "session",
380
+ initial: () => ({ locked: false })
381
+ });
382
+ const LabelsDoc = defineDoc({
383
+ kind: "po.labels",
384
+ checkpointWhen: () => false,
385
+ version: 1,
386
+ scope: "session",
387
+ initial: () => ({ labels: {} })
388
+ });
389
+ /**
390
+ * Profile identity entries of one conversation, written in the identity entry's commit, so a transcript page finds
391
+ * the avatar in effect without scanning backwards. Rewindable with `asOf` forks: a fork keeps only the identities
392
+ * written before its fork point. Sessions written before this document have no entries and show the default avatar.
393
+ */
394
+ const IdentityHistoryDoc = defineDoc({
395
+ kind: "po.identity-history",
396
+ checkpointWhen: () => false,
397
+ version: 1,
398
+ scope: "conversation",
399
+ history: "rewindable",
400
+ fork: "asOf",
401
+ initial: () => ({ items: [] })
402
+ });
403
+ //#endregion
404
+ //#region ../../../node_modules/.pnpm/@earendil-works+pi-durable@1.5.0_patch_hash=0f5e595daa4c370af407284d99d6dba48a9e21f56aa_fbb51180c4b193ec70152883060baa79/node_modules/@earendil-works/pi-durable/dist/env/index.js
405
+ function ok(value) {
406
+ return {
407
+ ok: true,
408
+ value
409
+ };
410
+ }
411
+ function err(error) {
412
+ return {
413
+ ok: false,
414
+ error
415
+ };
416
+ }
417
+ function getOrThrow(result) {
418
+ if (!result.ok) throw result.error;
419
+ return result.value;
420
+ }
421
+ var FileError = class extends Error {
422
+ code;
423
+ path;
424
+ constructor(code, message, path, cause) {
425
+ super(message, cause === void 0 ? void 0 : { cause });
426
+ this.name = "FileError";
427
+ this.code = code;
428
+ this.path = path;
429
+ }
430
+ };
431
+ var ExecutionError = class extends Error {
432
+ code;
433
+ /** Spill file of a command that timed out or was aborted after its output crossed the spill thresholds. */
434
+ spillPath;
435
+ constructor(code, message, cause) {
436
+ super(message, cause === void 0 ? void 0 : { cause });
437
+ this.name = "ExecutionError";
438
+ this.code = code;
439
+ }
440
+ };
441
+ //#endregion
442
+ //#region ../../core/po-core/src/services/nodeHost/index.edge.ts
443
+ const EMPTY_ENVIRONMENT = Object.freeze({});
444
+ /** The edge host: one Durable Object, its virtual filesystem laid out as in po-cloudflare's DoFileSystem. */
445
+ const nodeHost = {
446
+ homeDirectory: () => "/home/po",
447
+ temporaryDirectory: () => "/tmp",
448
+ /** A Durable Object is one logical process. */
449
+ processId: () => 1,
450
+ /**
451
+ * Empty: the Worker's `process.env` holds its deployment vars and secrets, never a session's.
452
+ * Sessions receive their admitted environment explicitly.
453
+ */
454
+ environment: () => EMPTY_ENVIRONMENT,
455
+ setMode: async (_filePath, _mode) => void 0,
456
+ /** No modes on the edge, so callers skip their permission checks, as `setMode` does. */
457
+ fileMode: async (_filePath) => void 0
458
+ };
459
+ //#endregion
460
+ //#region ../../core/po-core/src/services/serialRunner/index.ts
461
+ /** Runs operations one at a time in call order; a rejection reaches its caller and never stalls the queue. */
462
+ function createSerialRunner() {
463
+ let tail = Promise.resolve();
464
+ const tails = /* @__PURE__ */ new Map();
465
+ const run = (operation) => {
466
+ const result = tail.then(operation);
467
+ tail = result.catch(() => void 0);
468
+ return result;
469
+ };
470
+ const forKey = (key) => (operation) => {
471
+ const result = (tails.get(key) ?? Promise.resolve()).then(operation);
472
+ const settled = result.catch(() => void 0);
473
+ tails.set(key, settled);
474
+ settled.then(() => {
475
+ if (tails.get(key) === settled) tails.delete(key);
476
+ });
477
+ return result;
478
+ };
479
+ return Object.assign(run, { forKey });
480
+ }
481
+ /** Cooperating API writers share this queue, keyed by the canonical target path. Not an OS file lock. */
482
+ const fileMutationRunner = createSerialRunner();
483
+ //#endregion
484
+ //#region ../../core/po-core/src/services/piSettings/core.ts
485
+ /**
486
+ * Pi's user settings, as `po sync` maintains them.
487
+ *
488
+ * The Po package is registered globally so a plain `pi` process can find the
489
+ * lightweight package bootstrap before project resources are trusted. Sync owns
490
+ * the extension registration, ambient-discovery filter, theme resource, selected default theme, and quiet-startup keys
491
+ * while preserving every unrelated user setting.
492
+ */
493
+ const PI_CODING_AGENT_DIR_ENV = "PI_CODING_AGENT_DIR";
494
+ /** Moves Po's whole home, agent directory included, away from `~/.po`. */
495
+ const PO_HOME_ENV = "PO_HOME";
496
+ /** The agent folder inside a Po or Pi home. */
497
+ const AGENT_DIRECTORY = "agent";
498
+ const HOME_ALIAS = "~";
499
+ const HOME_ALIAS_PREFIX = "~/";
500
+ /**
501
+ * Expands `~` and resolves a relative path against home, never the cwd, so every
502
+ * Po process lands on the same directory wherever it was started.
503
+ */
504
+ function resolveConfiguredDirectory(configured, homeDirectory) {
505
+ if (configured === HOME_ALIAS) return homeDirectory;
506
+ if (configured.startsWith(HOME_ALIAS_PREFIX)) return path.join(homeDirectory, configured.slice(2));
507
+ return path.resolve(homeDirectory, configured);
508
+ }
509
+ /**
510
+ * Po's home: config, workspaces, runtime registry and its Pi agent directory.
511
+ * Defaults to `~/.po`; `PO_HOME` moves all of it.
512
+ */
513
+ function poHomeDirectory(homeDirectory = nodeHost.homeDirectory(), environment = nodeHost.environment()) {
514
+ const configured = environment[PO_HOME_ENV]?.trim();
515
+ return configured ? resolveConfiguredDirectory(configured, homeDirectory) : path.join(homeDirectory, ".po");
516
+ }
517
+ /**
518
+ * The Pi agent directory Po runs with. Honors Pi's documented override; every Po
519
+ * entry point sets that override, so the default only applies to library callers.
520
+ */
521
+ function piAgentDirectory(environment = nodeHost.environment(), homeDirectory = nodeHost.homeDirectory()) {
522
+ const configured = environment[PI_CODING_AGENT_DIR_ENV]?.trim();
523
+ if (!configured) return path.join(poHomeDirectory(homeDirectory, environment), AGENT_DIRECTORY);
524
+ return resolveConfiguredDirectory(configured, homeDirectory);
525
+ }
526
+ createSerialRunner();
527
+ //#endregion
528
+ //#region ../../core/po-core/src/services/sessionFiles/sessionDirectory.edge.ts
529
+ /** The Durable Object filesystem is already isolated to its owning session. */
530
+ async function prepareSessionDirectory(platform, directory) {
531
+ const fs = platform.env(platform.homeDirectory);
532
+ try {
533
+ getOrThrow(await fs.createDir(directory, { recursive: true }, BACKGROUND_CONTEXT));
534
+ return directory;
535
+ } finally {
536
+ await fs.cleanup(BACKGROUND_CONTEXT);
537
+ }
538
+ }
539
+ //#endregion
540
+ //#region ../../core/po-core/src/services/sessionFiles/index.ts
541
+ const PO_SESSION_TEMP_DIR = "PO_SESSION_TEMP_DIR";
542
+ const PO_SESSION_FILES_SERVICE = "po/session-files";
543
+ /** A host-owned path, never a client-selected root or an inherited parent session path. */
544
+ function sessionTempDirectory(options) {
545
+ if (!/^[a-zA-Z0-9_-]+$/u.test(options.sessionId)) throw new Error("Invalid temporary-file session identity.");
546
+ if (!path.isAbsolute(options.temporaryDirectory)) throw new Error("The host temporary directory must be absolute.");
547
+ const namespace = createHash("sha256").update(options.homeDirectory).update("\0").update(poHomeDirectory(options.homeDirectory, options.environment)).digest("hex").slice(0, 24);
548
+ return path.join(options.temporaryDirectory, `po-${namespace}`, "sessions", options.sessionId);
549
+ }
550
+ /** Both the execution host and package APIs call this with their admitted session identity. */
551
+ async function prepareSessionEnvironment(input) {
552
+ const environment = { ...input.environment };
553
+ delete environment[PO_SESSION_TEMP_DIR];
554
+ if (input.platform.temporaryDirectory === void 0) return Object.freeze(environment);
555
+ const directory = sessionTempDirectory({
556
+ sessionId: input.sessionId,
557
+ homeDirectory: input.platform.homeDirectory,
558
+ environment,
559
+ temporaryDirectory: input.platform.temporaryDirectory
560
+ });
561
+ const preparedDirectory = await prepareSessionDirectory(input.platform, directory);
562
+ return Object.freeze({
563
+ ...environment,
564
+ [PO_SESSION_TEMP_DIR]: preparedDirectory
565
+ });
566
+ }
567
+ //#endregion
568
+ //#region ../../core/po-core/src/web/hostSlots.ts
569
+ /** Host-owned declarations are visible throughout the client scope tree. */
570
+ const HOST_SLOT_METADATA = {
571
+ home: {
572
+ slot: "home",
573
+ scope: "global",
574
+ description: "Typed Home content and launch contributions.",
575
+ kind: "data"
576
+ },
577
+ homeApps: {
578
+ slot: "home-apps",
579
+ scope: "global",
580
+ description: "Plugin cards on Home. Set data.column to side for the narrow column.",
581
+ parent: "home",
582
+ kind: "component"
583
+ },
584
+ dashboardTiles: {
585
+ slot: "dashboard-tiles",
586
+ scope: "global",
587
+ description: "Host-framed body-only tiles on Home and workspace dashboards.",
588
+ kind: "component"
589
+ },
590
+ homeAttention: {
591
+ slot: "home-attention",
592
+ scope: "global",
593
+ description: "Plugin-framed Home cards for things waiting on the person.",
594
+ parent: "home",
595
+ kind: "component"
596
+ },
597
+ overlay: {
598
+ slot: "overlay",
599
+ scope: "global",
600
+ description: "Overlays above the cockpit, such as a microphone dialog.",
601
+ kind: "component"
602
+ },
603
+ rail: {
604
+ slot: "rail",
605
+ scope: "global",
606
+ description: "Navigation items in the cockpit rail.",
607
+ kind: "component"
608
+ },
609
+ context: {
610
+ slot: "context",
611
+ scope: "global",
612
+ description: "Context panels beside the session conversation.",
613
+ kind: "component"
614
+ },
615
+ selectionBar: {
616
+ slot: "selection-bar",
617
+ scope: "global",
618
+ description: "Actions for the current text selection.",
619
+ kind: "component"
620
+ },
621
+ activity: {
622
+ slot: "activity",
623
+ scope: "global",
624
+ description: "Session activity panels, with explicit child slots for activity groups.",
625
+ kind: "component"
626
+ },
627
+ activityPromo: {
628
+ slot: "activity-promo",
629
+ scope: "global",
630
+ description: "Compact actions inside the activity promo card, such as Explore.",
631
+ parent: "activity",
632
+ kind: "component"
633
+ },
634
+ composerActions: {
635
+ slot: "composer-actions",
636
+ scope: "global",
637
+ description: "Action controls beside the session composer.",
638
+ kind: "component"
639
+ },
640
+ composerMenu: {
641
+ slot: "composer-menu",
642
+ scope: "global",
643
+ description: "Items in the session composer menu.",
644
+ kind: "component"
645
+ },
646
+ dialogPrompt: {
647
+ slot: "dialog-prompt",
648
+ scope: "global",
649
+ description: "Typed data fills that claim a dialog independently of a tool card.",
650
+ kind: "data"
651
+ },
652
+ sessionMenu: {
653
+ slot: "session-menu",
654
+ scope: "global",
655
+ description: "Items in the session menu.",
656
+ kind: "component"
657
+ },
658
+ newSession: {
659
+ slot: "new-session",
660
+ scope: "global",
661
+ description: "A workspace fill replacing the host new-session dialog.",
662
+ kind: "component"
663
+ },
664
+ page: {
665
+ slot: "page",
666
+ scope: "global",
667
+ description: "A full page at /page/<fill id> in the main area beside the sidebar.",
668
+ kind: "component"
669
+ }
670
+ };
671
+ Object.fromEntries(Object.entries(HOST_SLOT_METADATA).map(([key, declaration]) => [key, declaration.slot]));
672
+ //#endregion
2
673
  //#region ../../../node_modules/.pnpm/typebox@1.4.2/node_modules/typebox/build/system/memory/metrics.mjs
3
674
  /** TypeBox instantiation metrics */
4
675
  const Metrics = {
@@ -1013,7 +1684,7 @@ function IsNumber(value) {
1013
1684
  //#endregion
1014
1685
  //#region ../../../node_modules/.pnpm/typebox@1.4.2/node_modules/typebox/build/type/types/symbol.mjs
1015
1686
  /** Creates a Symbol type. */
1016
- function Symbol(options) {
1687
+ function Symbol$1(options) {
1017
1688
  return Create({ "~kind": "Symbol" }, { type: "symbol" }, options);
1018
1689
  }
1019
1690
  /** Returns true if the given value is TSymbol. */
@@ -2805,7 +3476,7 @@ function FromAny() {
2805
3476
  return Union([
2806
3477
  Number$1(),
2807
3478
  String$1(),
2808
- Symbol()
3479
+ Symbol$1()
2809
3480
  ]);
2810
3481
  }
2811
3482
  //#endregion
@@ -3352,4 +4023,3276 @@ function Priority(types) {
3352
4023
  return Sort(types);
3353
4024
  }
3354
4025
  //#endregion
3355
- export { IsSchema as $, Integer as A, IsObject$1 as At, IsEnum as B, Symbols as Bt, Null as C, IsLessEqualThan as Ct, IsLiteralNumber as D, IsMultipleOf as Dt, IsLiteralBoolean as E, IsMinLength as Et, IsCodec as F, IsUnsafePropertyKey as Ft, _Object_ as G, IsCyclic as H, Hash as I, IsValueLike as It, IsRef as J, IsOptional as K, Unreachable as L, Keys$1 as Lt, Boolean$1 as M, IsString$2 as Mt, IsBoolean as N, IsSymbol$1 as Nt, IsLiteralString as O, IsNull$1 as Ot, IsBigInt as P, IsUndefined$1 as Pt, _Array_ as Q, Intersect as R, Some as Rt, IsNull as S, IsInteger$1 as St, IsLiteralBigInt as T, IsMaxLength as Tt, Unknown as U, Unsafe as V, guard_exports as Vt, IsObject as W, ArrayOptions as X, Ref as Y, IsArray as Z, Union as _, IsDeepEqual as _t, Partial as a, IsTypeArray as at, IsNumber as b, IsGreaterEqualThan as bt, IsVoid as c, EntriesRegExp as ct, Record as d, HasPropertyKey as dt, Assign as et, RecordPattern as f, IsArray$1 as ft, IsUnion as g, IsConstructor$1 as gt, Tuple as h, IsClassInstance as ht, With as i, IsSet as it, IsInteger as j, IsObjectNotArray as jt, Literal as k, IsNumber$2 as kt, IsUndefined as l, Every as lt, IsTuple as m, IsBoolean$2 as mt, Evaluate as n, IsMap as nt, Omit as o, Counted as ot, RecordValue as p, IsBigInt$1 as pt, Optional as q, Instantiate as r, IsRegExp as rt, IsTemplateLiteral as s, Entries as st, Priority as t, Get as tt, IsRecord as u, EveryAll as ut, IsString as v, IsEqual as vt, IsLiteral as w, IsLessThan as wt, Number$1 as x, IsGreaterThan as xt, String$1 as y, IsFunction$1 as yt, IsIntersect as z, SomeAll as zt };
4026
+ //#region ../../core/po-core/src/schemas/config.ts
4027
+ /**
4028
+ * Configuration surfaces, contributed by every extension that owns settings.
4029
+ *
4030
+ * Po settings live in one YAML file but are owned by many extensions, and for
4031
+ * a long time the only way to change any of them was to edit that file by hand.
4032
+ * The one exception, an editor-command prompt, asked for a value with no way to
4033
+ * see what a valid one looked like.
4034
+ *
4035
+ * So configuration is published rather than centralised: an extension describes
4036
+ * its own fields, one renderer draws them all, and the extension still performs
4037
+ * every write. Nothing here knows what a voice model or an editor command is.
4038
+ *
4039
+ * Deliberately the same shape as the mode and footer contracts next door, since
4040
+ * the problem is the same one: several extensions sharing one surface. The UI
4041
+ * hub invokes an owner's registered action directly, because unlike a status
4042
+ * strip this surface is written to as well as read.
4043
+ */
4044
+ /** Canonical Cordis key for the session-owned Po configuration service. */
4045
+ const PO_CONFIG_SERVICE = "po/config";
4046
+ /** Matches the leader contract's source rule: package names, addressable and spoof-checkable. */
4047
+ const ConfigSourceSchema = String$1({
4048
+ minLength: 1,
4049
+ maxLength: 128,
4050
+ pattern: "^[A-Za-z0-9@][A-Za-z0-9@/._:-]*$"
4051
+ });
4052
+ const ConfigIdSchema = String$1({
4053
+ minLength: 1,
4054
+ maxLength: 128,
4055
+ pattern: "^[a-z0-9][a-z0-9._:-]*$"
4056
+ });
4057
+ /**
4058
+ * How ready a value is to be used, as opposed to whether it is merely set.
4059
+ * `blocked` covers a choice that needs something else first, such as a model
4060
+ * whose engine is not installed.
4061
+ */
4062
+ const ConfigStatusSchema = Union([
4063
+ Literal("ready"),
4064
+ Literal("available"),
4065
+ Literal("blocked")
4066
+ ]);
4067
+ const ConfigFieldKindSchema = Union([
4068
+ Literal("text"),
4069
+ Literal("enum"),
4070
+ Literal("choice"),
4071
+ Literal("info")
4072
+ ]);
4073
+ /**
4074
+ * A key the renderer offers on the focused field, sent back verbatim as an
4075
+ * action. Owners use this for confirmations, so the pending question survives a
4076
+ * panel that is closed and reopened.
4077
+ */
4078
+ const ConfigActionSchema = _Object_({
4079
+ key: String$1({
4080
+ minLength: 1,
4081
+ maxLength: 1
4082
+ }),
4083
+ label: String$1({
4084
+ minLength: 1,
4085
+ maxLength: 24
4086
+ }),
4087
+ action: ConfigIdSchema
4088
+ }, { additionalProperties: false });
4089
+ const ConfigChoiceSchema = _Object_({
4090
+ id: String$1({
4091
+ minLength: 1,
4092
+ maxLength: 256
4093
+ }),
4094
+ label: String$1({
4095
+ minLength: 1,
4096
+ maxLength: 96
4097
+ }),
4098
+ /** Right-aligned by the renderer. Sizes, ids, anything narrow. */
4099
+ detail: Optional(String$1({
4100
+ minLength: 1,
4101
+ maxLength: 96
4102
+ })),
4103
+ /** Groups entries under a heading the cursor skips over. */
4104
+ group: Optional(String$1({
4105
+ minLength: 1,
4106
+ maxLength: 48
4107
+ })),
4108
+ status: Optional(ConfigStatusSchema),
4109
+ statusText: Optional(String$1({
4110
+ minLength: 1,
4111
+ maxLength: 96
4112
+ })),
4113
+ /**
4114
+ * What enter does on this entry. Carrying it per-entry is what lets one list
4115
+ * hold both an installed model that only needs selecting and an absent one
4116
+ * that needs fetching, without the renderer knowing the difference.
4117
+ */
4118
+ action: Optional(ConfigIdSchema)
4119
+ }, { additionalProperties: false });
4120
+ /**
4121
+ * One line of a multi-step operation.
4122
+ *
4123
+ * Published as a list rather than a single "current step" string so the panel can
4124
+ * show what already ran alongside what is left. During an install that is the
4125
+ * difference between "something is happening" and knowing a package manager
4126
+ * already finished and a download is now underway.
4127
+ */
4128
+ const ConfigStepSchema = _Object_({
4129
+ label: String$1({
4130
+ minLength: 1,
4131
+ maxLength: 96
4132
+ }),
4133
+ state: Union([
4134
+ Literal("pending"),
4135
+ Literal("satisfied"),
4136
+ Literal("running"),
4137
+ Literal("done"),
4138
+ Literal("failed")
4139
+ ]),
4140
+ detail: Optional(String$1({
4141
+ minLength: 1,
4142
+ maxLength: 160
4143
+ }))
4144
+ }, { additionalProperties: false });
4145
+ const ConfigProgressSchema = _Object_({
4146
+ label: String$1({
4147
+ minLength: 1,
4148
+ maxLength: 96
4149
+ }),
4150
+ /** 0 to 1. Omitted when the work has no measurable total. */
4151
+ ratio: Optional(Number$1({
4152
+ minimum: 0,
4153
+ maximum: 1
4154
+ }))
4155
+ }, { additionalProperties: false });
4156
+ const ConfigFieldSchema = _Object_({
4157
+ id: ConfigIdSchema,
4158
+ label: String$1({
4159
+ minLength: 1,
4160
+ maxLength: 48
4161
+ }),
4162
+ kind: ConfigFieldKindSchema,
4163
+ /** Absent means unset; the renderer shows `placeholder` instead. */
4164
+ value: Optional(String$1({
4165
+ minLength: 1,
4166
+ maxLength: 4096
4167
+ })),
4168
+ placeholder: Optional(String$1({
4169
+ minLength: 1,
4170
+ maxLength: 96
4171
+ })),
4172
+ /** One line of help for the focused field. */
4173
+ detail: Optional(String$1({
4174
+ minLength: 1,
4175
+ maxLength: 240
4176
+ })),
4177
+ /** The config key this writes, shown under the focused field so the file stays legible. */
4178
+ keyPath: Optional(String$1({
4179
+ minLength: 1,
4180
+ maxLength: 128
4181
+ })),
4182
+ status: Optional(ConfigStatusSchema),
4183
+ /** Doubles as the error line: a rejected edit comes back as the old value plus this. */
4184
+ statusText: Optional(String$1({
4185
+ minLength: 1,
4186
+ maxLength: 240
4187
+ })),
4188
+ choices: Optional(_Array_(ConfigChoiceSchema, { maxItems: 128 })),
4189
+ actions: Optional(_Array_(ConfigActionSchema, { maxItems: 4 })),
4190
+ /** Work is running; the renderer dims the field and offers abort. */
4191
+ busy: Optional(Boolean$1()),
4192
+ progress: Optional(ConfigProgressSchema),
4193
+ steps: Optional(_Array_(ConfigStepSchema, { maxItems: 24 })),
4194
+ /**
4195
+ * The tail of a running command's terminal output.
4196
+ *
4197
+ * A tail rather than the whole scrollback: the field is a few rows of a
4198
+ * shared pane, and what matters is the question a package manager just
4199
+ * asked, not what it printed a minute ago.
4200
+ */
4201
+ output: Optional(_Array_(String$1({ maxLength: 512 }), { maxItems: 64 })),
4202
+ /**
4203
+ * The command is waiting on the user. The renderer offers a line to type
4204
+ * into, which comes back as an owner-defined action carrying the text.
4205
+ */
4206
+ awaitingInput: Optional(Boolean$1())
4207
+ }, { additionalProperties: false });
4208
+ const ConfigSectionSchema = _Object_({
4209
+ id: ConfigIdSchema,
4210
+ title: String$1({
4211
+ minLength: 1,
4212
+ maxLength: 32
4213
+ }),
4214
+ detail: Optional(String$1({
4215
+ minLength: 1,
4216
+ maxLength: 96
4217
+ })),
4218
+ order: Integer({
4219
+ minimum: 0,
4220
+ maximum: 1e3
4221
+ }),
4222
+ /** Section-wide state: readiness, or why a write failed. */
4223
+ notice: Optional(String$1({
4224
+ minLength: 1,
4225
+ maxLength: 240
4226
+ })),
4227
+ noticeLevel: Optional(Union([Literal("info"), Literal("error")])),
4228
+ fields: _Array_(ConfigFieldSchema, { maxItems: 64 })
4229
+ }, { additionalProperties: false });
4230
+ _Object_({
4231
+ ..._Object_({
4232
+ source: ConfigSourceSchema,
4233
+ generation: String$1({ minLength: 1 })
4234
+ }, { additionalProperties: false }).properties,
4235
+ sections: _Array_(ConfigSectionSchema, { maxItems: 32 })
4236
+ }, { additionalProperties: false });
4237
+ //#endregion
4238
+ //#region ../../../node_modules/.pnpm/@deepseek-ai+cosmokit@1.8.6/node_modules/@deepseek-ai/cosmokit/lib/index.js
4239
+ /** Return true when a value is `null` or `undefined`. */
4240
+ function isNullable(value) {
4241
+ return value === null || value === void 0;
4242
+ }
4243
+ /** Define a non-enumerable writable property and return the object. */
4244
+ function defineProperty(object, key, value) {
4245
+ return Object.defineProperty(object, key, {
4246
+ writable: true,
4247
+ value,
4248
+ enumerable: false
4249
+ });
4250
+ }
4251
+ /** Test values using `instanceof` with a `toStringTag` fallback. */
4252
+ function is(type, value) {
4253
+ if (arguments.length === 1) return (value) => is(type, value);
4254
+ return type in globalThis && value instanceof globalThis[type] || Object.prototype.toString.call(value).slice(8, -1) === type;
4255
+ }
4256
+ function isArrayBufferLike(value) {
4257
+ return is("ArrayBuffer", value) || is("SharedArrayBuffer", value);
4258
+ }
4259
+ function isArrayBufferSource(value) {
4260
+ return isArrayBufferLike(value) || ArrayBuffer.isView(value);
4261
+ }
4262
+ /** Binary source detection and base64/hex conversion helpers. */
4263
+ var Binary;
4264
+ (function(Binary) {
4265
+ Binary.is = isArrayBufferLike;
4266
+ Binary.isSource = isArrayBufferSource;
4267
+ function fromSource(source) {
4268
+ if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
4269
+ else return source;
4270
+ }
4271
+ Binary.fromSource = fromSource;
4272
+ function toBase64(source) {
4273
+ source = fromSource(source);
4274
+ if (typeof Buffer !== "undefined") return Buffer.from(source).toString("base64");
4275
+ let binary = "";
4276
+ const bytes = new Uint8Array(source);
4277
+ for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);
4278
+ return btoa(binary);
4279
+ }
4280
+ Binary.toBase64 = toBase64;
4281
+ function fromBase64(source) {
4282
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "base64"));
4283
+ return Uint8Array.from(atob(source), (c) => c.charCodeAt(0));
4284
+ }
4285
+ Binary.fromBase64 = fromBase64;
4286
+ function toHex(source) {
4287
+ source = fromSource(source);
4288
+ if (typeof Buffer !== "undefined") return Buffer.from(source).toString("hex");
4289
+ return Array.from(new Uint8Array(source), (byte) => byte.toString(16).padStart(2, "0")).join("");
4290
+ }
4291
+ Binary.toHex = toHex;
4292
+ function fromHex(source) {
4293
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "hex"));
4294
+ const hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1);
4295
+ const buffer = [];
4296
+ for (let i = 0; i < hex.length; i += 2) buffer.push(parseInt(`${hex[i]}${hex[i + 1]}`, 16));
4297
+ return Uint8Array.from(buffer).buffer;
4298
+ }
4299
+ Binary.fromHex = fromHex;
4300
+ })(Binary || (Binary = {}));
4301
+ Binary.fromBase64;
4302
+ Binary.toBase64;
4303
+ Binary.fromHex;
4304
+ Binary.toHex;
4305
+ function tokenize(source, delimiters, delimiter) {
4306
+ const output = [];
4307
+ let state = 0;
4308
+ for (let i = 0; i < source.length; i++) {
4309
+ const code = source.charCodeAt(i);
4310
+ if (code >= 65 && code <= 90) {
4311
+ if (state === 1) {
4312
+ const next = source.charCodeAt(i + 1);
4313
+ if (next >= 97 && next <= 122) output.push(delimiter);
4314
+ output.push(code + 32);
4315
+ } else {
4316
+ if (state !== 0) output.push(delimiter);
4317
+ output.push(code + 32);
4318
+ }
4319
+ state = 1;
4320
+ } else if (code >= 97 && code <= 122) {
4321
+ output.push(code);
4322
+ state = 2;
4323
+ } else if (delimiters.includes(code)) {
4324
+ if (state !== 0) output.push(delimiter);
4325
+ state = 0;
4326
+ } else output.push(code);
4327
+ }
4328
+ return String.fromCharCode(...output);
4329
+ }
4330
+ /** Convert text to dash-delimited parameter case. */
4331
+ function paramCase(source) {
4332
+ return tokenize(source, [45, 95], 45);
4333
+ }
4334
+ /** Runtime alias for `paramCase`. */
4335
+ const hyphenate = paramCase;
4336
+ /** Time constants plus parsing and formatting helpers. */
4337
+ var Time;
4338
+ (function(Time) {
4339
+ Time.millisecond = 1;
4340
+ Time.second = 1e3;
4341
+ Time.minute = Time.second * 60;
4342
+ Time.hour = Time.minute * 60;
4343
+ Time.day = Time.hour * 24;
4344
+ Time.week = Time.day * 7;
4345
+ let timezoneOffset = (/* @__PURE__ */ new Date()).getTimezoneOffset();
4346
+ function setTimezoneOffset(offset) {
4347
+ timezoneOffset = offset;
4348
+ }
4349
+ Time.setTimezoneOffset = setTimezoneOffset;
4350
+ function getTimezoneOffset() {
4351
+ return timezoneOffset;
4352
+ }
4353
+ Time.getTimezoneOffset = getTimezoneOffset;
4354
+ function getDateNumber(date = /* @__PURE__ */ new Date(), offset) {
4355
+ if (typeof date === "number") date = new Date(date);
4356
+ if (offset === void 0) offset = timezoneOffset;
4357
+ return Math.floor((date.valueOf() / Time.minute - offset) / 1440);
4358
+ }
4359
+ Time.getDateNumber = getDateNumber;
4360
+ function fromDateNumber(value, offset) {
4361
+ const date = new Date(value * Time.day);
4362
+ if (offset === void 0) offset = timezoneOffset;
4363
+ return new Date(+date + offset * Time.minute);
4364
+ }
4365
+ Time.fromDateNumber = fromDateNumber;
4366
+ const numeric = /\d+(?:\.\d+)?/.source;
4367
+ const timeRegExp = new RegExp(`^${[
4368
+ "w(?:eek(?:s)?)?",
4369
+ "d(?:ay(?:s)?)?",
4370
+ "h(?:our(?:s)?)?",
4371
+ "m(?:in(?:ute)?(?:s)?)?",
4372
+ "s(?:ec(?:ond)?(?:s)?)?"
4373
+ ].map((unit) => `(${numeric}${unit})?`).join("")}$`);
4374
+ function parseTime(source) {
4375
+ const capture = timeRegExp.exec(source);
4376
+ if (!capture) return 0;
4377
+ 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);
4378
+ }
4379
+ Time.parseTime = parseTime;
4380
+ function parseDate(date) {
4381
+ const parsed = parseTime(date);
4382
+ if (parsed) date = Date.now() + parsed;
4383
+ else if (/^\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).toLocaleDateString()}-${date}`;
4384
+ else if (/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).getFullYear()}-${date}`;
4385
+ return date ? new Date(date) : /* @__PURE__ */ new Date();
4386
+ }
4387
+ Time.parseDate = parseDate;
4388
+ function format(ms) {
4389
+ const abs = Math.abs(ms);
4390
+ if (abs >= Time.day - Time.hour / 2) return Math.round(ms / Time.day) + "d";
4391
+ else if (abs >= Time.hour - Time.minute / 2) return Math.round(ms / Time.hour) + "h";
4392
+ else if (abs >= Time.minute - Time.second / 2) return Math.round(ms / Time.minute) + "m";
4393
+ else if (abs >= Time.second) return Math.round(ms / Time.second) + "s";
4394
+ return ms + "ms";
4395
+ }
4396
+ Time.format = format;
4397
+ function toDigits(source, length = 2) {
4398
+ return source.toString().padStart(length, "0");
4399
+ }
4400
+ Time.toDigits = toDigits;
4401
+ function template(template, time = /* @__PURE__ */ new Date()) {
4402
+ 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));
4403
+ }
4404
+ Time.template = template;
4405
+ })(Time || (Time = {}));
4406
+ //#endregion
4407
+ //#region ../../../node_modules/.pnpm/@deepseek-ai+cordis@4.0.5/node_modules/@deepseek-ai/cordis/lib/index.js
4408
+ /** Ordered collection of disposable values with O(1) deletion by value. */
4409
+ var DisposableList = class {
4410
+ sn = 0;
4411
+ map = /* @__PURE__ */ new Map();
4412
+ weak = /* @__PURE__ */ new WeakMap();
4413
+ get length() {
4414
+ return this.map.size;
4415
+ }
4416
+ push(value) {
4417
+ const sn = ++this.sn;
4418
+ this.map.set(sn, value);
4419
+ this.weak.set(value, sn);
4420
+ return () => this.map.delete(sn);
4421
+ }
4422
+ delete(value) {
4423
+ const sn = this.weak.get(value);
4424
+ if (!sn) return false;
4425
+ return this.map.delete(sn);
4426
+ }
4427
+ clear() {
4428
+ const values = [...this.map.values()];
4429
+ this.map.clear();
4430
+ return values.reverse();
4431
+ }
4432
+ [Symbol.iterator]() {
4433
+ return this.map.values();
4434
+ }
4435
+ [Symbol.for("nodejs.util.inspect.custom")]() {
4436
+ return [...this];
4437
+ }
4438
+ };
4439
+ /** Shared symbols used to avoid public property-name collisions. */
4440
+ const symbols = {
4441
+ shadow: Symbol.for("cordis.shadow"),
4442
+ receiver: Symbol.for("cordis.receiver"),
4443
+ original: Symbol.for("cordis.original"),
4444
+ metadata: Symbol.for("cordis.metadata"),
4445
+ initHooks: Symbol.for("cordis.initHooks"),
4446
+ checkProto: Symbol.for("cordis.checkProto"),
4447
+ effect: Symbol.for("cordis.effect"),
4448
+ filter: Symbol.for("cordis.filter"),
4449
+ isolate: Symbol.for("cordis.isolate"),
4450
+ intercept: Symbol.for("cordis.intercept"),
4451
+ init: Symbol.for("cordis.init"),
4452
+ check: Symbol.for("cordis.check"),
4453
+ config: Symbol.for("cordis.config"),
4454
+ invoke: Symbol.for("cordis.invoke"),
4455
+ extend: Symbol.for("cordis.extend"),
4456
+ tracker: Symbol.for("cordis.tracker"),
4457
+ resolveConfig: Symbol.for("cordis.resolveConfig")
4458
+ };
4459
+ const GeneratorFunction = function* () {}.constructor;
4460
+ const AsyncGeneratorFunction = async function* () {}.constructor;
4461
+ /** Return true when a plugin callback should be constructed with `new`. */
4462
+ function isConstructor(func) {
4463
+ if (!func.prototype) return false;
4464
+ if (func instanceof GeneratorFunction) return false;
4465
+ if (AsyncGeneratorFunction !== Function && func instanceof AsyncGeneratorFunction) return false;
4466
+ return true;
4467
+ }
4468
+ /** Merge two prototype chains while preserving descriptors from `proto1`. */
4469
+ function joinPrototype(proto1, proto2) {
4470
+ if (proto1 === Object.prototype) return proto2;
4471
+ const result = Object.create(joinPrototype(Object.getPrototypeOf(proto1), proto2));
4472
+ for (const key of Reflect.ownKeys(proto1)) Object.defineProperty(result, key, Object.getOwnPropertyDescriptor(proto1, key));
4473
+ return result;
4474
+ }
4475
+ /** Return true for non-null objects and functions. */
4476
+ function isObject(value) {
4477
+ return value && (typeof value === "object" || typeof value === "function");
4478
+ }
4479
+ /** Find a property descriptor by walking an object's prototype chain. */
4480
+ function getPropertyDescriptor(target, prop) {
4481
+ let proto = target;
4482
+ while (proto) {
4483
+ const desc = Reflect.getOwnPropertyDescriptor(proto, prop);
4484
+ if (desc) return desc;
4485
+ proto = Object.getPrototypeOf(proto);
4486
+ }
4487
+ }
4488
+ /** Wrap services/functions so method calls see the caller's active context. */
4489
+ function getTraceable(ctx, value) {
4490
+ if (!isObject(value)) return value;
4491
+ if (Object.hasOwn(value, symbols.shadow)) return Object.getPrototypeOf(value);
4492
+ const tracker = value[symbols.tracker];
4493
+ if (!tracker) return value;
4494
+ return createTraceable(ctx, value, tracker);
4495
+ }
4496
+ /** Return a proxy that overlays readonly or writable properties onto a target. */
4497
+ function withProps(target, props) {
4498
+ if (!props) return target;
4499
+ return new Proxy(target, {
4500
+ get: (target, prop, receiver) => {
4501
+ if (prop in props && prop !== "constructor") return Reflect.get(props, prop, receiver);
4502
+ return Reflect.get(target, prop, receiver);
4503
+ },
4504
+ set: (target, prop, value, receiver) => {
4505
+ if (prop in props && prop !== "constructor") return Reflect.set(props, prop, value, receiver);
4506
+ return Reflect.set(target, prop, value, receiver);
4507
+ }
4508
+ });
4509
+ }
4510
+ function withProp(target, prop, value) {
4511
+ return withProps(target, Object.defineProperty(Object.create(null), prop, {
4512
+ value,
4513
+ writable: false
4514
+ }));
4515
+ }
4516
+ function createShadow(ctx, target, property, receiver) {
4517
+ if (!property) return receiver;
4518
+ const origin = Reflect.getOwnPropertyDescriptor(target, property)?.value;
4519
+ if (!origin) return receiver;
4520
+ return withProp(receiver, property, ctx.extend({ [symbols.shadow]: origin }));
4521
+ }
4522
+ function createShadowMethod(ctx, value, outer, shadow) {
4523
+ return new Proxy(value, { apply: (target, thisArg, args) => {
4524
+ if (thisArg === outer) thisArg = shadow;
4525
+ return getTraceable(ctx, Reflect.apply(target, thisArg, args));
4526
+ } });
4527
+ }
4528
+ function createTraceable(ctx, value, tracker) {
4529
+ if (ctx[symbols.shadow] && !tracker.noShadow) ctx = Object.getPrototypeOf(ctx);
4530
+ const proxy = new Proxy(value, {
4531
+ get: (target, prop, receiver) => {
4532
+ if (prop === symbols.original) return target;
4533
+ if (prop === tracker.property) return ctx;
4534
+ if (typeof prop === "symbol") return Reflect.get(target, prop, receiver);
4535
+ if (tracker.associate && ctx.reflect.props[`${tracker.associate}.${prop}`]) return Reflect.get(ctx, `${tracker.associate}.${prop}`, withProp(ctx, symbols.receiver, receiver));
4536
+ let shadow, innerValue;
4537
+ const desc = getPropertyDescriptor(target, prop);
4538
+ if (desc && "value" in desc) innerValue = desc.value;
4539
+ else {
4540
+ shadow = createShadow(ctx, target, tracker.property, receiver);
4541
+ innerValue = Reflect.get(target, prop, shadow);
4542
+ }
4543
+ const innerTracker = innerValue?.[symbols.tracker];
4544
+ if (innerTracker) return createTraceable(ctx, innerValue, innerTracker);
4545
+ else if (!tracker.noShadow && typeof innerValue === "function") {
4546
+ shadow ??= createShadow(ctx, target, tracker.property, receiver);
4547
+ return createShadowMethod(ctx, innerValue, receiver, shadow);
4548
+ } else return innerValue;
4549
+ },
4550
+ set: (target, prop, value, receiver) => {
4551
+ if (prop === symbols.original) return false;
4552
+ if (prop === tracker.property) return false;
4553
+ if (typeof prop === "symbol") return Reflect.set(target, prop, value, receiver);
4554
+ if (tracker.associate && ctx.reflect.props[`${tracker.associate}.${prop}`]) return Reflect.set(ctx, `${tracker.associate}.${prop}`, value, withProp(ctx, symbols.receiver, receiver));
4555
+ const shadow = createShadow(ctx, target, tracker.property, receiver);
4556
+ return Reflect.set(target, prop, value, shadow);
4557
+ },
4558
+ apply: (target, thisArg, args) => {
4559
+ return applyTraceable(proxy, target, thisArg, args);
4560
+ }
4561
+ });
4562
+ return proxy;
4563
+ }
4564
+ function applyTraceable(proxy, value, thisArg, args) {
4565
+ if (!value[symbols.invoke]) return Reflect.apply(value, thisArg, args);
4566
+ return value[symbols.invoke].apply(proxy, args);
4567
+ }
4568
+ /** Create a callable service object that dispatches through `symbols.invoke`. */
4569
+ function createCallable(name, proto, tracker) {
4570
+ const self = function(...args) {
4571
+ return applyTraceable(createTraceable(self["ctx"], self, tracker), self, this, args);
4572
+ };
4573
+ defineProperty(self, "name", name);
4574
+ return Object.setPrototypeOf(self, proto);
4575
+ }
4576
+ function handleError(info, reason, getOuterStack) {
4577
+ const innerLines = info.error.stack.split("\n");
4578
+ if (typeof reason?.stack !== "string") {
4579
+ const outerError = new Error(reason);
4580
+ const lines = outerError.stack.split("\n");
4581
+ lines.splice(1, Infinity, ...getOuterStack());
4582
+ outerError.stack = lines.join("\n");
4583
+ throw outerError;
4584
+ }
4585
+ const lines = reason.stack.split("\n");
4586
+ let index = lines.indexOf(innerLines[2]);
4587
+ if (index === -1) throw reason;
4588
+ index -= info.offset;
4589
+ while (index > 0) {
4590
+ if (!lines[index - 1].endsWith(" (<anonymous>)")) break;
4591
+ index -= 1;
4592
+ }
4593
+ lines.splice(index, Infinity, ...getOuterStack());
4594
+ reason.stack = lines.join("\n");
4595
+ throw reason;
4596
+ }
4597
+ /** Run a callback and splice outer call-site frames into thrown async errors. */
4598
+ function composeError(callback, getOuterStack = buildOuterStack()) {
4599
+ const info = {
4600
+ offset: 1,
4601
+ error: /* @__PURE__ */ new Error()
4602
+ };
4603
+ try {
4604
+ const result = callback(info);
4605
+ if (isObject(result) && "then" in result) return result.then(void 0, (reason) => handleError(info, reason, getOuterStack));
4606
+ else return result;
4607
+ } catch (reason) {
4608
+ handleError(info, reason, getOuterStack);
4609
+ }
4610
+ }
4611
+ /** Capture a lazy stack-frame supplier for later error composition. */
4612
+ function buildOuterStack(offset = 0) {
4613
+ const outerError = /* @__PURE__ */ new Error();
4614
+ return () => outerError.stack.split("\n").slice(3 + offset);
4615
+ }
4616
+ /**
4617
+ * Return whether an event result should stop a bail-style dispatch.
4618
+ *
4619
+ * @param value — a listener's return value.
4620
+ * @returns `true` unless `value` is `null`, `false`, or `undefined`.
4621
+ */
4622
+ function isBailed(value) {
4623
+ return value !== null && value !== false && value !== void 0;
4624
+ }
4625
+ /**
4626
+ * Event bus installed as `ctx.events` and mixed into every context.
4627
+ *
4628
+ * The service supports concurrent, synchronous, serial, bail, and waterfall
4629
+ * dispatch and automatically disposes listeners with their owning fiber.
4630
+ */
4631
+ var EventsService = class {
4632
+ ctx;
4633
+ _hooks = {};
4634
+ constructor(ctx) {
4635
+ this.ctx = ctx;
4636
+ defineProperty(this, symbols.tracker, {
4637
+ property: "ctx",
4638
+ noShadow: true
4639
+ });
4640
+ this.on("internal/listener", function(name, listener, options) {
4641
+ if (name === "internal/update" && !options.global) return (this.fiber._hooks["internal/update"] ??= new DisposableList())[options.prepend ? "unshift" : "push"](listener);
4642
+ });
4643
+ this.on("internal/update", function(config, noSave, next) {
4644
+ const cbs = [...this._hooks["internal/update"] || []];
4645
+ const _next = () => {
4646
+ return (cbs.shift() ?? next).call(this, config, noSave, _next);
4647
+ };
4648
+ return _next();
4649
+ }, {
4650
+ global: true,
4651
+ prepend: true
4652
+ });
4653
+ }
4654
+ /**
4655
+ * Resolve listeners for one dispatch and apply context filtering.
4656
+ *
4657
+ * @param type — the dispatch mode, reported on `internal/dispatch`.
4658
+ * @param args — the raw dispatch arguments; consumed up to the event name.
4659
+ * @returns the matching listener callbacks, bound to the dispatch `this`.
4660
+ */
4661
+ dispatch(type, args) {
4662
+ const thisArg = typeof args[0] === "object" || typeof args[0] === "function" ? args.shift() : null;
4663
+ const name = args.shift();
4664
+ if (!name.startsWith("internal/")) this.emit("internal/dispatch", type, name, args, thisArg);
4665
+ const filter = thisArg?.[Context.filter];
4666
+ return (this._hooks[name] || []).filter((hook) => hook.global || !filter || filter.call(thisArg, hook.ctx)).map((hook) => hook.callback.bind(thisArg));
4667
+ }
4668
+ /**
4669
+ * Run listeners concurrently and wait for all of them.
4670
+ *
4671
+ * @param args — optional `this`, the event name, then listener arguments.
4672
+ * @returns a promise resolving once every listener has settled.
4673
+ */
4674
+ async parallel(...args) {
4675
+ const errors = (await Promise.allSettled(this.dispatch("emit", args).map(async (cb) => cb(...args)))).filter((result) => result.status === "rejected");
4676
+ if (errors.length) throw new AggregateError(errors.map((error) => error.reason));
4677
+ }
4678
+ /**
4679
+ * Run listeners synchronously without waiting for returned promises.
4680
+ *
4681
+ * @param args — optional `this`, the event name, then listener arguments.
4682
+ */
4683
+ emit(...args) {
4684
+ this.dispatch("emit", args).map((cb) => cb(...args));
4685
+ }
4686
+ /**
4687
+ * Run listeners in order, awaiting each, until one returns a bail value.
4688
+ *
4689
+ * @param args — optional `this`, the event name, then listener arguments.
4690
+ * @returns the first bail value (see {@link isBailed}), if any.
4691
+ */
4692
+ async serial(...args) {
4693
+ for (const cb of this.dispatch("serial", args)) {
4694
+ const result = await cb(...args);
4695
+ if (isBailed(result)) return result;
4696
+ }
4697
+ }
4698
+ /**
4699
+ * Run listeners synchronously until one returns a bail value.
4700
+ *
4701
+ * @param args — optional `this`, the event name, then listener arguments.
4702
+ * @returns the first bail value (see {@link isBailed}), if any.
4703
+ */
4704
+ bail(...args) {
4705
+ for (const cb of this.dispatch("bail", args)) {
4706
+ const result = cb(...args);
4707
+ if (isBailed(result)) return result;
4708
+ }
4709
+ }
4710
+ /**
4711
+ * Compose listeners around the final `next` callback.
4712
+ *
4713
+ * The last dispatch argument is treated as the innermost `next`. Listeners
4714
+ * run outermost-first; a listener that does not call `next()` vetoes the
4715
+ * rest of the chain, including the built-in behavior.
4716
+ *
4717
+ * @param args — optional `this`, the event name, listener arguments, then `next`.
4718
+ * @returns the outermost listener's return value.
4719
+ */
4720
+ waterfall(...args) {
4721
+ const cbs = this.dispatch("waterfall", args);
4722
+ const inner = args.pop();
4723
+ const next = () => {
4724
+ return (cbs.shift() ?? inner)(...args);
4725
+ };
4726
+ args.push(next);
4727
+ return next();
4728
+ }
4729
+ /**
4730
+ * Store a listener record as an effect on the current fiber.
4731
+ *
4732
+ * @param label — effect label shown in fiber diagnostics.
4733
+ * @param hooks — the listener list for one event.
4734
+ * @param callback — the listener to store.
4735
+ * @param options — placement and filtering options.
4736
+ * @returns a disposer that unregisters the listener.
4737
+ */
4738
+ register(label, hooks, callback, options) {
4739
+ const method = options.prepend ? "unshift" : "push";
4740
+ return this.ctx.fiber.effect(() => {
4741
+ hooks[method]({
4742
+ ctx: this.ctx,
4743
+ callback,
4744
+ ...options
4745
+ });
4746
+ return () => this.unregister(hooks, callback);
4747
+ }, label);
4748
+ }
4749
+ /**
4750
+ * Remove a stored listener record.
4751
+ *
4752
+ * @param hooks — the listener list for one event.
4753
+ * @param callback — the listener to remove.
4754
+ * @returns `true` if the listener was found and removed.
4755
+ */
4756
+ unregister(hooks, callback) {
4757
+ const index = hooks.findIndex((hook) => hook.callback === callback);
4758
+ if (index >= 0) {
4759
+ hooks.splice(index, 1);
4760
+ return true;
4761
+ }
4762
+ }
4763
+ /**
4764
+ * Register an event listener owned by the current fiber.
4765
+ *
4766
+ * The listener is removed automatically when the fiber unloads. Throws
4767
+ * `CordisError('INACTIVE_EFFECT')` if the fiber is already disposed.
4768
+ *
4769
+ * @param name — the event name to listen for.
4770
+ * @param listener — called with the dispatch arguments.
4771
+ * @param options — listener options; a boolean is shorthand for `prepend`.
4772
+ * @returns a disposer removing the listener; `true` if it was still registered.
4773
+ */
4774
+ on(name, listener, options) {
4775
+ if (typeof options !== "object") options = { prepend: options };
4776
+ this.ctx.fiber.assertActive();
4777
+ listener = this.ctx.reflect.bind(listener);
4778
+ const result = this.bail(this.ctx, "internal/listener", name, listener, options);
4779
+ if (result) return result;
4780
+ const hooks = this._hooks[name] ||= [];
4781
+ const label = `ctx.on(${typeof name === "string" ? JSON.stringify(name) : name.toString()})`;
4782
+ return this.register(label, hooks, listener, options);
4783
+ }
4784
+ /**
4785
+ * Register an event listener that disposes itself after the first call.
4786
+ *
4787
+ * @param name — the event name to listen for.
4788
+ * @param listener — called at most once with the dispatch arguments.
4789
+ * @param options — listener options; a boolean is shorthand for `prepend`.
4790
+ * @returns a disposer removing the listener; `true` if it was still registered.
4791
+ */
4792
+ once(name, listener, options) {
4793
+ const dispose = this.on(name, function(...args) {
4794
+ dispose();
4795
+ return listener.apply(this, args);
4796
+ }, options);
4797
+ return dispose;
4798
+ }
4799
+ };
4800
+ /** Built-in placeholder formatters used by `Logger.format()`. */
4801
+ const defaultFormatters = {
4802
+ s: (value) => String(value),
4803
+ d: (value) => Math.trunc(Number(value)),
4804
+ i: (value) => Math.trunc(Number(value)),
4805
+ f: (value) => Number(value),
4806
+ o: (value) => JSON.stringify(value),
4807
+ O: (value) => JSON.stringify(value),
4808
+ c: () => "",
4809
+ C: (value, exporter, message) => {
4810
+ return Logger.color(exporter, Logger.code(message.name, exporter.colors), value);
4811
+ }
4812
+ };
4813
+ function isAggregateError(error) {
4814
+ return error instanceof Error && Array.isArray(error["errors"]);
4815
+ }
4816
+ /** Logger facade for one named subsystem. */
4817
+ var Logger = class {
4818
+ service;
4819
+ static color(exporter, code, value, decoration = "") {
4820
+ if (!exporter.colors) return "" + value;
4821
+ return `\u001b[3${code < 8 ? code : "8;5;" + code}${exporter.colors >= 2 ? decoration : ""}m${value}\u001b[0m`;
4822
+ }
4823
+ static code(name, level) {
4824
+ let hash = 0;
4825
+ for (let i = 0; i < name.length; i++) {
4826
+ hash = (hash << 3) - hash + name.charCodeAt(i) + 13;
4827
+ hash |= 0;
4828
+ }
4829
+ const colors = !level ? [] : level >= 2 ? c256 : c16;
4830
+ return colors[Math.abs(hash) % colors.length];
4831
+ }
4832
+ static format(exporter, message) {
4833
+ const args = message.args.slice();
4834
+ if (args[0] instanceof Error) {
4835
+ args[0] = args[0].stack || args[0].message;
4836
+ args.unshift("%s");
4837
+ } else if (typeof args[0] !== "string") args.unshift("%o");
4838
+ let format = args.shift();
4839
+ format = format.replace(/%([a-zA-Z%])/g, (match, char) => {
4840
+ if (match === "%%") return "%";
4841
+ const formatter = exporter.formatters?.[char] ?? defaultFormatters[char];
4842
+ if (typeof formatter === "function") return formatter(args.shift(), exporter, message);
4843
+ return match;
4844
+ });
4845
+ const oFormatter = exporter.formatters?.o ?? defaultFormatters.o;
4846
+ for (let arg of args) {
4847
+ if (typeof arg === "object" && arg) arg = oFormatter(arg, exporter, message);
4848
+ format += " " + arg;
4849
+ }
4850
+ const { maxLength = 10240 } = exporter;
4851
+ return format.split(/\r?\n/g).map((line) => {
4852
+ return line.slice(0, maxLength) + (line.length > maxLength ? "..." : "");
4853
+ }).join("\n");
4854
+ }
4855
+ constructor(options, service) {
4856
+ this.service = service;
4857
+ Object.assign(this, options);
4858
+ this.error = this._method("error", 0);
4859
+ this.info = this._method("info", 1);
4860
+ this.warn = this._method("warn", 2);
4861
+ this.debug = this._method("debug", 3);
4862
+ }
4863
+ _method(type, level) {
4864
+ return (...args) => {
4865
+ if (args.length === 1 && args[0] instanceof Error) {
4866
+ if (args[0].cause) this[type](args[0].cause);
4867
+ else if (isAggregateError(args[0])) {
4868
+ args[0].errors.forEach((error) => this[type](error));
4869
+ return;
4870
+ }
4871
+ }
4872
+ const sn = ++this.service._snMessage;
4873
+ const ts = Date.now();
4874
+ for (const exporter of this.service.exporters.values()) {
4875
+ if ((exporter.levels?.[this.name] ?? exporter.levels?.default ?? this.level ?? 1) < level) continue;
4876
+ const message = {
4877
+ sn,
4878
+ ts,
4879
+ type,
4880
+ level,
4881
+ name: this.name,
4882
+ ...this.meta,
4883
+ args
4884
+ };
4885
+ exporter.export(message);
4886
+ }
4887
+ };
4888
+ }
4889
+ };
4890
+ /** ANSI 16-color palette indexes used for logger name coloring. */
4891
+ const c16 = [
4892
+ 6,
4893
+ 2,
4894
+ 3,
4895
+ 4,
4896
+ 5,
4897
+ 1
4898
+ ];
4899
+ /** ANSI 256-color palette indexes used for logger name coloring. */
4900
+ const c256 = [
4901
+ 20,
4902
+ 21,
4903
+ 26,
4904
+ 27,
4905
+ 32,
4906
+ 33,
4907
+ 38,
4908
+ 39,
4909
+ 40,
4910
+ 41,
4911
+ 42,
4912
+ 43,
4913
+ 44,
4914
+ 45,
4915
+ 56,
4916
+ 57,
4917
+ 62,
4918
+ 63,
4919
+ 68,
4920
+ 69,
4921
+ 74,
4922
+ 75,
4923
+ 76,
4924
+ 77,
4925
+ 78,
4926
+ 79,
4927
+ 80,
4928
+ 81,
4929
+ 92,
4930
+ 93,
4931
+ 98,
4932
+ 99,
4933
+ 112,
4934
+ 113,
4935
+ 129,
4936
+ 134,
4937
+ 135,
4938
+ 148,
4939
+ 149,
4940
+ 160,
4941
+ 161,
4942
+ 162,
4943
+ 163,
4944
+ 164,
4945
+ 165,
4946
+ 166,
4947
+ 167,
4948
+ 168,
4949
+ 169,
4950
+ 170,
4951
+ 171,
4952
+ 172,
4953
+ 173,
4954
+ 178,
4955
+ 179,
4956
+ 184,
4957
+ 185,
4958
+ 196,
4959
+ 197,
4960
+ 198,
4961
+ 199,
4962
+ 200,
4963
+ 201,
4964
+ 202,
4965
+ 203,
4966
+ 204,
4967
+ 205,
4968
+ 206,
4969
+ 207,
4970
+ 208,
4971
+ 209,
4972
+ 214,
4973
+ 215,
4974
+ 220,
4975
+ 221
4976
+ ];
4977
+ /**
4978
+ * Built-in logging service.
4979
+ *
4980
+ * Call `ctx.logger()` to create a named logger, or call `ctx.logger.info()`
4981
+ * directly to log with the current fiber-derived name.
4982
+ */
4983
+ var LoggerService = class LoggerService {
4984
+ bufferSize = 1e3;
4985
+ buffer = [];
4986
+ ctx;
4987
+ _snMessage = 0;
4988
+ _snExporter = 0;
4989
+ exporters = /* @__PURE__ */ new Map();
4990
+ constructor(ctx) {
4991
+ const tracker = {
4992
+ property: "ctx",
4993
+ noShadow: true
4994
+ };
4995
+ const self = createCallable("logger", joinPrototype(Object.getPrototypeOf(this), Function.prototype), tracker);
4996
+ Object.assign(self, this);
4997
+ self.ctx = ctx;
4998
+ defineProperty(self, symbols.tracker, tracker);
4999
+ self.exporter({
5000
+ colors: 3,
5001
+ export: (message) => {
5002
+ self.buffer.push(message);
5003
+ if (self.buffer.length > self.bufferSize) self.buffer = self.buffer.slice(-self.bufferSize);
5004
+ }
5005
+ });
5006
+ return self;
5007
+ }
5008
+ /**
5009
+ * Register an exporter and dispose it with the current fiber.
5010
+ *
5011
+ * @param exporter — the sink that receives structured log messages.
5012
+ * @returns a disposer that removes the exporter.
5013
+ */
5014
+ exporter(exporter) {
5015
+ return this.ctx.effect(() => {
5016
+ const id = ++this._snExporter;
5017
+ this.exporters.set(id, exporter);
5018
+ return () => this.exporters.delete(id);
5019
+ }, "ctx.logger.exporter()");
5020
+ }
5021
+ _resolveConfig() {
5022
+ let intercept = this.ctx[symbols.intercept];
5023
+ const configs = [];
5024
+ while ("logger" in intercept) {
5025
+ if (Object.hasOwn(intercept, "logger")) configs.unshift(intercept["logger"]);
5026
+ intercept = Object.getPrototypeOf(intercept);
5027
+ }
5028
+ return Object.assign({}, ...configs);
5029
+ }
5030
+ [symbols.invoke](name) {
5031
+ const config = this._resolveConfig();
5032
+ const fiber = (this.ctx[symbols.shadow] ?? this.ctx).fiber;
5033
+ name ??= config.name;
5034
+ name ??= hyphenate(fiber.name);
5035
+ return new Logger({
5036
+ name,
5037
+ level: config.level,
5038
+ meta: { fiber: new WeakRef(fiber) }
5039
+ }, this);
5040
+ }
5041
+ static {
5042
+ for (const type of [
5043
+ "error",
5044
+ "info",
5045
+ "warn",
5046
+ "debug"
5047
+ ]) LoggerService.prototype[type] = function(...args) {
5048
+ return this()[type](...args);
5049
+ };
5050
+ }
5051
+ };
5052
+ function enhanceError(error) {
5053
+ const lines = error.stack.split("\n");
5054
+ lines.splice(0, 2, `Error: ${error.message}`);
5055
+ error.stack = lines.join("\n");
5056
+ return error;
5057
+ }
5058
+ const RESERVED_WORDS = ["prototype", "then"];
5059
+ function isSpecialProperty(prop) {
5060
+ return typeof prop === "symbol" || RESERVED_WORDS.includes(prop) || parseInt(prop).toString() === prop || prop.startsWith("_");
5061
+ }
5062
+ /**
5063
+ * Reflection and service-resolution layer installed as `ctx.reflect`.
5064
+ *
5065
+ * This service powers the context proxy, service registration, accessors, and
5066
+ * the mixins that expose core service methods directly on `ctx`.
5067
+ */
5068
+ var ReflectService = class {
5069
+ ctx;
5070
+ /** Proxy traps implementing service resolution for every context object. */
5071
+ static handler = {
5072
+ get: (target, prop, ctx) => {
5073
+ if (isSpecialProperty(prop)) return Reflect.get(target, prop, ctx);
5074
+ if (Reflect.has(target, prop)) return getTraceable(ctx, Reflect.get(target, prop, ctx));
5075
+ const error = /* @__PURE__ */ new Error(`cannot get property "${prop}" without inject`);
5076
+ try {
5077
+ const def = target.reflect.props[prop];
5078
+ if (def?.type === "accessor") return def.get.call(ctx, ctx[symbols.receiver], error);
5079
+ if (!ctx.fiber.runtime) return ctx.reflect.get(prop, false);
5080
+ return ctx.events.waterfall("internal/get", ctx, prop, error, () => {
5081
+ const key = target[symbols.isolate][prop];
5082
+ let fiber = (ctx[symbols.shadow] ?? ctx).fiber;
5083
+ while (true) {
5084
+ const impl = fiber.store?.[prop];
5085
+ if (impl) return getTraceable(ctx, impl.value);
5086
+ if (prop in fiber.inject) {
5087
+ error.message = `cannot get required service "${prop}" in inactive context`;
5088
+ throw error;
5089
+ }
5090
+ if (!fiber.runtime) throw error;
5091
+ if (fiber.parent[symbols.isolate][prop] !== key) throw error;
5092
+ fiber = fiber.parent.fiber;
5093
+ }
5094
+ });
5095
+ } catch (e) {
5096
+ throw e === error ? enhanceError(e) : e;
5097
+ }
5098
+ },
5099
+ set: (target, prop, value, ctx) => {
5100
+ if (isSpecialProperty(prop)) return Reflect.set(target, prop, value, ctx);
5101
+ const error = /* @__PURE__ */ new Error(`cannot set property "${prop}" without provide`);
5102
+ const def = target.reflect.props[prop];
5103
+ if (!def) {
5104
+ if (!ctx.fiber.runtime) return Reflect.set(target, prop, value, ctx);
5105
+ throw enhanceError(error);
5106
+ }
5107
+ try {
5108
+ if (def.type === "accessor") {
5109
+ if (!def.set) return false;
5110
+ return def.set.call(ctx, value, ctx[symbols.receiver], error);
5111
+ }
5112
+ return ctx.events.waterfall("internal/set", ctx, prop, value, error, () => {
5113
+ return ctx.reflect.set(prop, value, error);
5114
+ });
5115
+ } catch (e) {
5116
+ throw e === error ? enhanceError(e) : e;
5117
+ }
5118
+ },
5119
+ has: (target, prop) => {
5120
+ if (isSpecialProperty(prop)) return Reflect.has(target, prop);
5121
+ if (Reflect.has(target, prop)) return true;
5122
+ return !!target.reflect.props[prop];
5123
+ }
5124
+ };
5125
+ /** Service implementations, keyed by isolation label. */
5126
+ store = Object.create(null);
5127
+ /** Declared context properties (services and accessors), by name. */
5128
+ props = Object.create(null);
5129
+ constructor(ctx) {
5130
+ this.ctx = ctx;
5131
+ defineProperty(this, symbols.tracker, {
5132
+ property: "ctx",
5133
+ noShadow: true
5134
+ });
5135
+ this.mixin("reflect", [
5136
+ "get",
5137
+ "set",
5138
+ "provide",
5139
+ "accessor",
5140
+ "mixin"
5141
+ ]);
5142
+ this.mixin("fiber", ["runtime", "effect"]);
5143
+ this.mixin("registry", ["inject", "plugin"]);
5144
+ this.mixin("events", [
5145
+ "on",
5146
+ "once",
5147
+ "parallel",
5148
+ "emit",
5149
+ "serial",
5150
+ "bail",
5151
+ "waterfall"
5152
+ ]);
5153
+ }
5154
+ /**
5155
+ * Read a service from the store without the inject requirement.
5156
+ *
5157
+ * @param name — the service name.
5158
+ * @param strict — when `true`, only return implementations whose providing
5159
+ * fiber is currently active.
5160
+ * @returns the service value, or `undefined` when not (yet) provided.
5161
+ */
5162
+ get(name, strict = true) {
5163
+ return getTraceable(this.ctx, this._getImpl(name, strict)?.value);
5164
+ }
5165
+ _getImpl(name, strict = true) {
5166
+ const key = this.ctx[symbols.isolate][name];
5167
+ const impl = key && this.store[key];
5168
+ if (!impl) return;
5169
+ if (strict && impl.fiber.state !== 2) return;
5170
+ return impl;
5171
+ }
5172
+ /**
5173
+ * Overwrite a provided service's value.
5174
+ *
5175
+ * @param name — the service name.
5176
+ * @param value — the new service value.
5177
+ * @param error — carrier for the caller stack in diagnostics.
5178
+ * @returns `true` on success.
5179
+ * @throws when `name` was never provided, or was provided by another fiber.
5180
+ */
5181
+ set(name, value, error) {
5182
+ const key = this.ctx[symbols.isolate][name];
5183
+ const impl = this.store[key];
5184
+ if (!impl) throw new Error(`cannot set property "${name}" without provide`);
5185
+ if (impl.fiber !== this.ctx.fiber) throw new Error(`cannot set property "${name}" in multiple fibers`);
5186
+ impl.value = value;
5187
+ return true;
5188
+ }
5189
+ /**
5190
+ * Register a service implementation owned by the current fiber.
5191
+ *
5192
+ * See the `ctx.provide()` overload above for the full contract.
5193
+ *
5194
+ * @param name — the service name.
5195
+ * @param value — the service value.
5196
+ * @param check — optional availability predicate for dependents.
5197
+ * @returns a disposer that unregisters the service.
5198
+ */
5199
+ provide(name, value, check) {
5200
+ return this.ctx.fiber.effect(() => {
5201
+ if (!this.props[name]) this.props[name] ??= { type: "service" };
5202
+ else if (this.props[name].type !== "service") throw new Error(`property "${name}" is already declared as ${this.props[name].type}`);
5203
+ this.props[name] = { type: "service" };
5204
+ this.ctx.root[symbols.isolate][name] ??= Symbol(name);
5205
+ const key = this.ctx[symbols.isolate][name];
5206
+ const impl = {
5207
+ name,
5208
+ value,
5209
+ fiber: this.ctx.fiber,
5210
+ check
5211
+ };
5212
+ if (this.store[key]) throw new Error(`service "${name}" has been registered at <${this.store[key].fiber.name}>`);
5213
+ this.store[key] = impl;
5214
+ this.ctx.fiber.store[name] = impl;
5215
+ if (this.ctx.fiber.state === 2) this.notify([name]);
5216
+ return async () => {
5217
+ delete this.store[key];
5218
+ const fibers = this.notify([name]);
5219
+ await Promise.allSettled(fibers.map((fiber) => fiber.await()));
5220
+ delete this.ctx.fiber.store[name];
5221
+ };
5222
+ }, `ctx.provide(${JSON.stringify(name)})`);
5223
+ }
5224
+ /**
5225
+ * Re-evaluate every fiber that requires one of the given services.
5226
+ *
5227
+ * @param names — the service names that changed.
5228
+ * @param filter — restricts notification to matching isolation scopes.
5229
+ * @returns the fibers whose dependency state was refreshed.
5230
+ */
5231
+ notify(names, filter = (ctx, name) => ctx[symbols.isolate][name] === this.ctx[symbols.isolate][name]) {
5232
+ const fibers = [];
5233
+ for (const runtime of this.ctx.registry.values()) for (const fiber of runtime.fibers) {
5234
+ let hasUpdate = false;
5235
+ for (const name of names) {
5236
+ if (!(name in fiber.inject)) continue;
5237
+ if (!filter(fiber.ctx, name)) continue;
5238
+ hasUpdate = true;
5239
+ fiber._checkImpl(name);
5240
+ }
5241
+ if (!hasUpdate) continue;
5242
+ fiber._refresh();
5243
+ fibers.push(fiber);
5244
+ }
5245
+ for (const name of names) {
5246
+ const self = Object.create(this.ctx);
5247
+ self[symbols.filter] = (target) => filter(target, name);
5248
+ this.ctx.events.emit(self, "internal/service", name, this._getImpl(name, false)?.value);
5249
+ }
5250
+ return fibers;
5251
+ }
5252
+ /**
5253
+ * Define a computed context property backed by get/set hooks.
5254
+ *
5255
+ * @param name — the context property name.
5256
+ * @param options — the `get` hook and optional `set` hook.
5257
+ * @returns a disposer that removes the accessor.
5258
+ */
5259
+ accessor(name, options) {
5260
+ return this.ctx.fiber.effect(() => {
5261
+ if (name in this.props) throw new Error(`property "${name}" is already declared as ${this.props[name].type}`);
5262
+ this.props[name] = {
5263
+ type: "accessor",
5264
+ ...options
5265
+ };
5266
+ return () => delete this.props[name];
5267
+ }, `ctx.accessor(${JSON.stringify(name)})`);
5268
+ }
5269
+ /**
5270
+ * Expose selected members of a service directly on `ctx`.
5271
+ *
5272
+ * See the `ctx.mixin()` overload above for the full contract.
5273
+ *
5274
+ * @param source — a context property name or a source object.
5275
+ * @param mixins — keys to forward, or a source-key → ctx-key map.
5276
+ * @returns a disposer that removes all created accessors.
5277
+ */
5278
+ mixin(source, mixins) {
5279
+ const self = this;
5280
+ return this.ctx.fiber.effect(function* () {
5281
+ const entries = Array.isArray(mixins) ? mixins.map((key) => [key, key]) : Object.entries(mixins);
5282
+ const getTarget = (ctx, error) => {
5283
+ return ctx[source];
5284
+ };
5285
+ for (const [key, value] of entries) yield self.accessor(value, {
5286
+ get(receiver, error) {
5287
+ const service = getTarget(this, error);
5288
+ if (isNullable(service)) return service;
5289
+ const mixin = receiver ? withProps(receiver, service) : service;
5290
+ const value = Reflect.get(service, key, mixin);
5291
+ if (typeof value !== "function") return value;
5292
+ return value.bind(mixin ?? service);
5293
+ },
5294
+ set(value, receiver, error) {
5295
+ const service = getTarget(this, error);
5296
+ const mixin = receiver ? withProps(receiver, service) : service;
5297
+ return Reflect.set(service, key, value, mixin);
5298
+ }
5299
+ });
5300
+ }, `ctx.mixin(${JSON.stringify(source)})`);
5301
+ }
5302
+ /**
5303
+ * Attach this context's tracing wrapper to a value.
5304
+ *
5305
+ * @param value — the value to wrap.
5306
+ * @returns the traceable wrapper (or the value itself when not applicable).
5307
+ */
5308
+ trace(value) {
5309
+ return getTraceable(this.ctx, value);
5310
+ }
5311
+ /**
5312
+ * Wrap a callback so calls trace `this` and arguments to this context.
5313
+ *
5314
+ * @param callback — the function to wrap.
5315
+ * @returns a proxy delegating to `callback` with traced values.
5316
+ */
5317
+ bind(callback) {
5318
+ return new Proxy(callback, {
5319
+ apply: (target, thisArg, args) => {
5320
+ return Reflect.apply(target, this.trace(thisArg), args.map((arg) => this.trace(arg)));
5321
+ },
5322
+ construct: (target, args, newTarget) => {
5323
+ return Reflect.construct(target, args.map((arg) => this.trace(arg)), newTarget);
5324
+ }
5325
+ });
5326
+ }
5327
+ };
5328
+ const kValidationError = Symbol.for("ValidationError");
5329
+ /** Error raised when plugin configuration fails standard-schema validation. */
5330
+ var ValidationError = class extends TypeError {
5331
+ name = "ValidationError";
5332
+ /**
5333
+ * Build the aggregated message from schema issues.
5334
+ *
5335
+ * @param issues — the standard-schema issues, one message line each.
5336
+ */
5337
+ constructor(issues) {
5338
+ super(`invalid config:\n` + issues.map((issue) => {
5339
+ if (issue.path) return ` - ${issue.message} (at ${issue.path.join(".")})`;
5340
+ else return ` - ${issue.message}`;
5341
+ }).join("\n"));
5342
+ }
5343
+ };
5344
+ Object.defineProperty(ValidationError.prototype, kValidationError, { value: true });
5345
+ /**
5346
+ * Validate and normalize config for a plugin runtime before it starts.
5347
+ *
5348
+ * @param runtime — the plugin runtime whose `Config` schema to apply.
5349
+ * @param config — the raw user config.
5350
+ * @returns the validated config, or `config` unchanged if the runtime has no schema.
5351
+ * @throws {ValidationError} when validation reports issues.
5352
+ */
5353
+ function resolveConfig(runtime, config) {
5354
+ if (!runtime.Config) return config;
5355
+ const result = runtime.Config["~standard"].validate(config);
5356
+ if ("then" in result) throw new TypeError("Async config validation is not supported");
5357
+ if (result.issues) throw new ValidationError(result.issues);
5358
+ else return result.value;
5359
+ }
5360
+ const effectInertia = /* @__PURE__ */ new WeakMap();
5361
+ function runDisposable(dispose) {
5362
+ const result = dispose();
5363
+ return effectInertia.get(dispose)?.() ?? result;
5364
+ }
5365
+ /** Notify plugin teardown without allowing one observer to break ownership cleanup. */
5366
+ function emitPluginDisposed(context, fiber) {
5367
+ const args = ["internal/plugin", fiber];
5368
+ let callbacks;
5369
+ try {
5370
+ callbacks = context.events.dispatch("emit", args);
5371
+ } catch (error) {
5372
+ context.logger.error(error);
5373
+ return;
5374
+ }
5375
+ for (const callback of callbacks) try {
5376
+ const returned = callback(...args);
5377
+ Promise.resolve(returned).catch((error) => context.logger.error(error));
5378
+ } catch (error) {
5379
+ context.logger.error(error);
5380
+ }
5381
+ }
5382
+ /** Framework error with a stable machine-readable code. */
5383
+ var CordisError = class CordisError extends Error {
5384
+ code;
5385
+ /**
5386
+ * @param code — the stable error code; also the default message.
5387
+ * @param message — optional human-readable override.
5388
+ */
5389
+ constructor(code, message) {
5390
+ super(message ?? CordisError.Code[code]);
5391
+ this.code = code;
5392
+ }
5393
+ };
5394
+ /** Cordis error code definitions. */
5395
+ (function(CordisError) {
5396
+ CordisError.Code = { INACTIVE_EFFECT: "cannot create effect on inactive context" };
5397
+ })(CordisError || (CordisError = {}));
5398
+ const INACTIVE = "__INACTIVE__";
5399
+ /**
5400
+ * Runtime instance of one plugin application.
5401
+ *
5402
+ * A fiber tracks dependency state, validated config, lifecycle effects, and
5403
+ * cleanup for the plugin context returned by `ctx.plugin()`.
5404
+ */
5405
+ var Fiber = class {
5406
+ parent;
5407
+ inject;
5408
+ runtime;
5409
+ /** Unique id within the registry; 0 for the root fiber, `null` once disposed. */
5410
+ uid;
5411
+ /** The context this fiber's plugin runs in (extends the parent context). */
5412
+ ctx;
5413
+ /** The validated plugin config (updated by `update()`). */
5414
+ config;
5415
+ /** The raw plugin config, re-resolved before each activation. */
5416
+ _config;
5417
+ /** Current lifecycle state; transitions emit `internal/status`. */
5418
+ state = 0;
5419
+ /** Dispose this fiber: unload the plugin, then settle once cleanup finished. */
5420
+ dispose;
5421
+ /** Snapshot of required service implementations while loaded; `undefined` otherwise. */
5422
+ store;
5423
+ /** The in-flight load/unload transition, if one is currently running. */
5424
+ inertia;
5425
+ _hooks = Object.create(null);
5426
+ _disposables = new DisposableList();
5427
+ context;
5428
+ _error;
5429
+ _runner;
5430
+ _store = Object.create(null);
5431
+ /**
5432
+ * Create a fiber. Plugin authors normally obtain fibers from `ctx.plugin()`
5433
+ * rather than constructing them directly.
5434
+ *
5435
+ * @param parent — the context the plugin was loaded from.
5436
+ * @param config — raw config, validated against the runtime's schema.
5437
+ * @param inject — resolved dependency map (service name → intercept config).
5438
+ * @param runtime — the shared plugin runtime, or `null` for the root fiber.
5439
+ * @param getOuterStack — captures the caller stack for effect diagnostics.
5440
+ */
5441
+ constructor(parent, config, inject, runtime, getOuterStack) {
5442
+ this.parent = parent;
5443
+ this.inject = inject;
5444
+ this.runtime = runtime;
5445
+ this._config = config;
5446
+ const collect = (dispose) => {
5447
+ this._disposables.push(dispose);
5448
+ };
5449
+ if (runtime) {
5450
+ this.uid = parent.registry.counter;
5451
+ this.ctx = this.context = parent.extend({ fiber: this });
5452
+ const injectEntries = Object.entries(this.inject);
5453
+ if (injectEntries.length) {
5454
+ this.ctx[Context.intercept] = Object.create(parent[Context.intercept]);
5455
+ for (const [name, config] of injectEntries) {
5456
+ if (isNullable(config)) continue;
5457
+ this.ctx[Context.intercept][name] = config;
5458
+ }
5459
+ }
5460
+ this._runner = {
5461
+ epoch: INACTIVE,
5462
+ getOuterStack,
5463
+ execute: function() {
5464
+ if (isConstructor(runtime.callback)) {
5465
+ const instance = new runtime.callback(this.ctx, this.config);
5466
+ for (const hook of instance?.[symbols.initHooks] ?? []) hook();
5467
+ return instance?.[symbols.init]?.();
5468
+ } else return runtime.callback(this.ctx, this.config);
5469
+ },
5470
+ collect
5471
+ };
5472
+ this.dispose = parent.fiber.effect(() => {
5473
+ const remove = runtime.fibers.push(this);
5474
+ return async () => {
5475
+ this.uid = null;
5476
+ emitPluginDisposed(this.context, this);
5477
+ if (this.ctx.registry.has(runtime.callback)) {
5478
+ remove();
5479
+ if (!runtime.fibers.length) this.ctx.registry.delete(runtime.callback);
5480
+ }
5481
+ this._setEpoch(INACTIVE);
5482
+ if (!this.inertia) this._updateState(() => {
5483
+ this.inertia = this._unload();
5484
+ return 5;
5485
+ });
5486
+ while (this.inertia) await this.inertia;
5487
+ };
5488
+ }, "ctx.plugin()");
5489
+ try {
5490
+ this.context.emit("internal/plugin", this);
5491
+ } catch (error) {
5492
+ Promise.resolve(this.dispose()).catch((reason) => this.ctx.logger.error(reason));
5493
+ throw error;
5494
+ }
5495
+ if (this.uid !== null && parent.fiber.state !== 5) {
5496
+ for (const name of Object.keys(this.inject)) this._checkImpl(name);
5497
+ this._refresh();
5498
+ }
5499
+ } else {
5500
+ this.uid = 0;
5501
+ this.ctx = this.context = parent;
5502
+ this.state = 2;
5503
+ this.store = Object.create(null);
5504
+ this._runner = {
5505
+ epoch: "",
5506
+ getOuterStack,
5507
+ execute: () => {},
5508
+ collect
5509
+ };
5510
+ this.dispose = () => this.restart();
5511
+ }
5512
+ }
5513
+ /** The plugin's display name, inherited from the nearest named ancestor, else `'root'`. */
5514
+ get name() {
5515
+ let fiber = this;
5516
+ do {
5517
+ if (fiber.runtime?.name) return fiber.runtime.name;
5518
+ fiber = fiber.parent.fiber;
5519
+ } while (fiber !== fiber.parent.fiber);
5520
+ return "root";
5521
+ }
5522
+ /**
5523
+ * Throw if the fiber has already been disposed.
5524
+ *
5525
+ * @returns nothing when the fiber is still active.
5526
+ * @throws {CordisError} `INACTIVE_EFFECT` when the fiber's uid has been cleared.
5527
+ */
5528
+ assertActive() {
5529
+ if (this.uid !== null) return;
5530
+ throw new CordisError("INACTIVE_EFFECT");
5531
+ }
5532
+ _execute(runner) {
5533
+ const oldEpoch = runner.epoch;
5534
+ return composeError((info) => {
5535
+ const safeCollect = (dispose) => {
5536
+ if (typeof dispose === "function") runner.collect(dispose);
5537
+ else if (!isNullable(dispose)) throw new TypeError("Invalid effect");
5538
+ };
5539
+ const effect = runner.execute.call(this);
5540
+ if (typeof effect === "function") return runner.collect(effect);
5541
+ else if (isNullable(effect)) {} else if (!isObject(effect)) throw new TypeError("Invalid effect");
5542
+ else if ("then" in effect) return effect.then(safeCollect);
5543
+ else if (Symbol.iterator in effect) {
5544
+ info.error = /* @__PURE__ */ new Error();
5545
+ const iter = effect[Symbol.iterator]();
5546
+ while (true) {
5547
+ const result = iter.next();
5548
+ safeCollect(result.value);
5549
+ if (result.done) return;
5550
+ }
5551
+ } else if (Symbol.asyncIterator in effect) {
5552
+ const iter = effect[Symbol.asyncIterator]();
5553
+ return (async () => {
5554
+ await Promise.resolve();
5555
+ info.error = /* @__PURE__ */ new Error();
5556
+ while (true) {
5557
+ if (runner.epoch !== oldEpoch) return;
5558
+ const result = await iter.next();
5559
+ safeCollect(result.value);
5560
+ if (result.done) return;
5561
+ }
5562
+ })();
5563
+ } else throw new TypeError("Invalid effect");
5564
+ }, runner.getOuterStack);
5565
+ }
5566
+ effect(execute, label = "anonymous") {
5567
+ this.assertActive();
5568
+ if (this.state === 5) throw new CordisError("INACTIVE_EFFECT");
5569
+ const disposables = [];
5570
+ let disposing = false;
5571
+ let disposalTask;
5572
+ const dispose = () => {
5573
+ if (disposing) return disposalTask;
5574
+ disposing = true;
5575
+ let task;
5576
+ for (const disposable of disposables.splice(0).reverse()) if (task) task = task.then(() => runDisposable(disposable));
5577
+ else {
5578
+ const result = runDisposable(disposable);
5579
+ if (isObject(result) && "then" in result) task = result;
5580
+ }
5581
+ return disposalTask = task;
5582
+ };
5583
+ const meta = {
5584
+ label,
5585
+ children: []
5586
+ };
5587
+ const runner = {
5588
+ execute,
5589
+ epoch: true,
5590
+ collect: (dispose) => {
5591
+ disposables.push(dispose);
5592
+ this._disposables.delete(dispose);
5593
+ if (dispose[symbols.effect]) meta.children.push(dispose[symbols.effect]);
5594
+ },
5595
+ getOuterStack: buildOuterStack()
5596
+ };
5597
+ let task;
5598
+ let executing = true;
5599
+ let resolveSetup;
5600
+ let rejectSetup;
5601
+ let setupBarrier;
5602
+ let setupFailed = false;
5603
+ let inFlight;
5604
+ let removeWrapper = () => false;
5605
+ const waitForSetup = () => {
5606
+ setupBarrier ??= new Promise((resolve, reject) => {
5607
+ resolveSetup = resolve;
5608
+ rejectSetup = reject;
5609
+ });
5610
+ return setupBarrier;
5611
+ };
5612
+ const disposeAfter = (setup) => {
5613
+ return Promise.resolve(setup).then(() => dispose(), async (reason) => {
5614
+ await dispose();
5615
+ throw reason;
5616
+ });
5617
+ };
5618
+ const finalizeDisposal = (callback) => {
5619
+ let result;
5620
+ try {
5621
+ result = callback();
5622
+ } catch (error) {
5623
+ removeWrapper();
5624
+ throw error;
5625
+ }
5626
+ if (isObject(result) && "then" in result) {
5627
+ const pending = Promise.resolve(result).finally(() => {
5628
+ removeWrapper();
5629
+ if (inFlight === pending) inFlight = void 0;
5630
+ });
5631
+ return inFlight = pending;
5632
+ }
5633
+ removeWrapper();
5634
+ return result;
5635
+ };
5636
+ const wrapper = defineProperty(() => {
5637
+ if (!runner.epoch) return setupFailed ? inFlight : void 0;
5638
+ runner.epoch = false;
5639
+ return finalizeDisposal(() => {
5640
+ if (executing) return disposeAfter(waitForSetup());
5641
+ return task ? disposeAfter(task) : dispose();
5642
+ });
5643
+ }, symbols.effect, meta);
5644
+ effectInertia.set(wrapper, () => inFlight);
5645
+ removeWrapper = this._disposables.push(wrapper);
5646
+ try {
5647
+ task = this._execute(runner);
5648
+ } catch (reason) {
5649
+ executing = false;
5650
+ setupFailed = true;
5651
+ runner.epoch = false;
5652
+ let cleanup;
5653
+ try {
5654
+ cleanup = finalizeDisposal(dispose);
5655
+ } finally {
5656
+ rejectSetup?.(reason);
5657
+ }
5658
+ if (isObject(cleanup) && "then" in cleanup) cleanup.catch((error) => this.ctx.logger.error(error));
5659
+ throw reason;
5660
+ }
5661
+ executing = false;
5662
+ if (setupBarrier) Promise.resolve(task).then(resolveSetup, rejectSetup);
5663
+ task?.catch(() => {
5664
+ if (!runner.epoch) return dispose();
5665
+ return finalizeDisposal(dispose);
5666
+ }).catch((error) => this.ctx.logger.error(error));
5667
+ const disposeAsync = () => {
5668
+ if (!runner.epoch) return;
5669
+ runner.epoch = false;
5670
+ return finalizeDisposal(dispose);
5671
+ };
5672
+ wrapper.then = async (onFulfilled, onRejected) => {
5673
+ return Promise.resolve(task).then(() => disposeAsync).then(onFulfilled, onRejected);
5674
+ };
5675
+ return wrapper;
5676
+ }
5677
+ /**
5678
+ * Return metadata for currently registered effects.
5679
+ *
5680
+ * @returns one {@link EffectMeta} tree per labeled live effect.
5681
+ */
5682
+ getEffects() {
5683
+ return [...this._disposables].map((dispose) => dispose[symbols.effect]).filter(Boolean);
5684
+ }
5685
+ _getState() {
5686
+ if (this.uid === null) return 4;
5687
+ if (this._error) return 3;
5688
+ if (this._runner.epoch !== INACTIVE) return 2;
5689
+ return 0;
5690
+ }
5691
+ _updateState(callback) {
5692
+ const oldState = this.state;
5693
+ this.state = callback() ?? this._getState();
5694
+ if (oldState === this.state) return;
5695
+ this.context.emit("internal/status", this, oldState);
5696
+ if (oldState !== 2 && this.state !== 2) return;
5697
+ for (const key of Reflect.ownKeys(this.ctx.reflect.store)) {
5698
+ const impl = this.ctx.reflect.store[key];
5699
+ if (impl.fiber !== this) continue;
5700
+ this.ctx.reflect.notify([impl.name]);
5701
+ }
5702
+ }
5703
+ _checkImpl(name) {
5704
+ const impl = this.ctx.reflect._getImpl(name, true);
5705
+ if (!impl) return delete this._store[name];
5706
+ try {
5707
+ if (impl.check && !impl.check.call(getTraceable(this.ctx, impl.value))) return delete this._store[name];
5708
+ } catch (error) {
5709
+ impl.fiber.ctx.logger.error(error);
5710
+ return delete this._store[name];
5711
+ }
5712
+ this._store[name] = impl;
5713
+ }
5714
+ _refresh() {
5715
+ let epoch = false;
5716
+ epoch = "";
5717
+ for (const name of Object.keys(this.inject)) {
5718
+ const impl = this._store[name];
5719
+ if (!impl) {
5720
+ epoch = INACTIVE;
5721
+ break;
5722
+ }
5723
+ epoch += ":" + impl.fiber.uid;
5724
+ }
5725
+ this._setEpoch(epoch);
5726
+ }
5727
+ _setEpoch(epoch) {
5728
+ const oldEpoch = this._runner.epoch;
5729
+ if (epoch === oldEpoch) return;
5730
+ this._runner.epoch = epoch;
5731
+ if (this.inertia) return;
5732
+ this._updateState(() => {
5733
+ if (epoch !== INACTIVE && oldEpoch === INACTIVE) {
5734
+ this.inertia = this._reload();
5735
+ return 1;
5736
+ } else {
5737
+ this.inertia = this._unload();
5738
+ return 5;
5739
+ }
5740
+ });
5741
+ }
5742
+ _resolveConfig(config) {
5743
+ config = this.context.waterfall(this, "internal/config", config, () => config);
5744
+ return this.runtime ? resolveConfig(this.runtime, config) : config;
5745
+ }
5746
+ async _reload() {
5747
+ this.store = { ...this._store };
5748
+ const oldEpoch = this._runner.epoch;
5749
+ try {
5750
+ await Promise.resolve();
5751
+ if (this._runner.epoch === oldEpoch) {
5752
+ this.config = this._resolveConfig(this._config);
5753
+ await this._execute(this._runner);
5754
+ this._error = void 0;
5755
+ }
5756
+ } catch (reason) {
5757
+ this.ctx.logger.error(reason);
5758
+ this._error = reason;
5759
+ this._runner.epoch = INACTIVE;
5760
+ }
5761
+ this._updateState(() => {
5762
+ if (this._runner.epoch === oldEpoch) this.inertia = void 0;
5763
+ else {
5764
+ this.inertia = this._unload();
5765
+ return 5;
5766
+ }
5767
+ });
5768
+ }
5769
+ async _unload() {
5770
+ await Promise.all(this._disposables.clear().map(async (dispose) => {
5771
+ try {
5772
+ await composeError(async (info) => {
5773
+ await Promise.resolve();
5774
+ info.error = /* @__PURE__ */ new Error();
5775
+ await runDisposable(dispose);
5776
+ }, this._runner.getOuterStack);
5777
+ } catch (reason) {
5778
+ this.ctx.logger.error(reason);
5779
+ }
5780
+ }));
5781
+ this.store = void 0;
5782
+ this._updateState(() => {
5783
+ if (this._runner.epoch === INACTIVE) this.inertia = void 0;
5784
+ else {
5785
+ this.inertia = this._reload();
5786
+ return 1;
5787
+ }
5788
+ });
5789
+ }
5790
+ /**
5791
+ * Wait for current lifecycle work and rethrow startup errors.
5792
+ *
5793
+ * @returns this fiber, once it has settled into a stable state.
5794
+ * @throws the config-validation or plugin-startup error, if any.
5795
+ */
5796
+ async await() {
5797
+ while (this.inertia) await this.inertia;
5798
+ if (this._error) throw this._error;
5799
+ return this;
5800
+ }
5801
+ /**
5802
+ * Dispose and immediately reload this plugin with its current config.
5803
+ *
5804
+ * @returns a promise resolving once the reload settled.
5805
+ * @throws {CordisError} `INACTIVE_EFFECT` when the fiber is already disposed.
5806
+ */
5807
+ async restart() {
5808
+ this.assertActive();
5809
+ this._setEpoch(INACTIVE);
5810
+ this._refresh();
5811
+ await this.await();
5812
+ }
5813
+ /**
5814
+ * Validate and apply new config, then restart the plugin.
5815
+ *
5816
+ * Runs the `internal/update` waterfall first, so update hooks (and HMR)
5817
+ * can veto or replace the restart.
5818
+ *
5819
+ * @param config — the new raw config; validated before anything restarts.
5820
+ * @param noSave — hint for persistence hooks not to write the change back.
5821
+ * @returns nothing; the restart runs behind the `internal/update` waterfall.
5822
+ * @throws {ValidationError} when the new config fails validation.
5823
+ */
5824
+ update(config, noSave = false) {
5825
+ this.assertActive();
5826
+ this._config = config;
5827
+ if (this.state !== 2) {
5828
+ this._error = void 0;
5829
+ this._setEpoch(INACTIVE);
5830
+ this._refresh();
5831
+ return;
5832
+ }
5833
+ config = this._resolveConfig(config);
5834
+ this.context.waterfall(this, "internal/update", config, noSave, () => {
5835
+ this.config = config;
5836
+ this._error = void 0;
5837
+ return this.restart();
5838
+ });
5839
+ }
5840
+ };
5841
+ function isApplicable(object) {
5842
+ return object && typeof object === "object" && typeof object.apply === "function";
5843
+ }
5844
+ /**
5845
+ * Decorator for declaring service dependencies on classes or class methods.
5846
+ *
5847
+ * On classes it contributes to the plugin's static `inject` map. On methods it
5848
+ * delays the method call until the declared services are available.
5849
+ */
5850
+ /**
5851
+ * @param name — the required service name.
5852
+ * @param config — optional intercept config applied for that service.
5853
+ * @returns the class or method decorator.
5854
+ */
5855
+ function Inject(name, config) {
5856
+ return function(value, decorator) {
5857
+ if (decorator.kind === "class") {
5858
+ if (!Object.hasOwn(value, "inject")) {
5859
+ defineProperty(value, "inject", Object.create(Object.getPrototypeOf(value).inject ?? null));
5860
+ defineProperty(value.inject, symbols.checkProto, true);
5861
+ }
5862
+ value.inject[name] = config;
5863
+ } else if (decorator.kind === "method") {
5864
+ const inject = (value[symbols.metadata] ??= {}).inject ??= Object.create(null);
5865
+ inject[name] = config;
5866
+ decorator.addInitializer(function() {
5867
+ const property = this[symbols.tracker]?.property;
5868
+ (this[symbols.initHooks] ??= []).push(() => {
5869
+ this.ctx.inject(inject, (ctx) => {
5870
+ return value.call(property ? withProps(this, { [property]: ctx }) : this);
5871
+ });
5872
+ });
5873
+ });
5874
+ } else throw new Error("@Inject() can only be used on class or class methods");
5875
+ };
5876
+ }
5877
+ /** Utilities for normalizing plugin dependency declarations. */
5878
+ (function(Inject) {
5879
+ /**
5880
+ * Convert array/object/class-inherited inject metadata into a plain map.
5881
+ *
5882
+ * @param inject — the declaration to normalize; `null`/`undefined` add nothing.
5883
+ * @param result — the map to fill (service name → intercept config or `null`).
5884
+ * @returns `result`.
5885
+ */
5886
+ function resolve(inject, result = Object.create(null)) {
5887
+ if (!inject) return result;
5888
+ if (Array.isArray(inject)) for (const name of inject) result[name] = null;
5889
+ else if (Reflect.has(inject, symbols.checkProto)) {
5890
+ Object.assign(result, resolve(Object.getPrototypeOf(inject)));
5891
+ for (const name of Object.keys(inject)) result[name] = inject[name] ?? null;
5892
+ } else for (const name of Object.keys(inject)) result[name] = inject[name] ?? null;
5893
+ return result;
5894
+ }
5895
+ Inject.resolve = resolve;
5896
+ })(Inject || (Inject = {}));
5897
+ /**
5898
+ * Plugin registry installed as `ctx.registry` and mixed into every context.
5899
+ *
5900
+ * It normalizes plugin shapes, tracks plugin runtimes, starts fibers, and
5901
+ * exposes map-like inspection over active plugin callbacks.
5902
+ */
5903
+ var RegistryService = class {
5904
+ ctx;
5905
+ _counter = 0;
5906
+ _internal = /* @__PURE__ */ new Map();
5907
+ constructor(ctx) {
5908
+ this.ctx = ctx;
5909
+ defineProperty(this, symbols.tracker, {
5910
+ property: "ctx",
5911
+ noShadow: true
5912
+ });
5913
+ }
5914
+ /** Allocate the next fiber uid (increments on every read). */
5915
+ get counter() {
5916
+ return ++this._counter;
5917
+ }
5918
+ /** Number of registered plugin runtimes. */
5919
+ get size() {
5920
+ return this._internal.size;
5921
+ }
5922
+ /**
5923
+ * Resolve a supported plugin shape to its executable callback.
5924
+ *
5925
+ * @param plugin — a function, class, or `{ apply }` object plugin.
5926
+ * @returns the callback identifying the plugin, or `undefined` if invalid.
5927
+ */
5928
+ resolve(plugin) {
5929
+ try {
5930
+ if (typeof plugin === "function") return plugin;
5931
+ if (isApplicable(plugin)) return plugin.apply;
5932
+ } catch {}
5933
+ }
5934
+ /**
5935
+ * Look up the runtime record for a plugin.
5936
+ *
5937
+ * @param plugin — any supported plugin shape.
5938
+ * @returns the runtime, or `undefined` when the plugin is not registered.
5939
+ */
5940
+ get(plugin) {
5941
+ const key = this.resolve(plugin);
5942
+ return key && this._internal.get(key);
5943
+ }
5944
+ /**
5945
+ * Check whether a plugin has a registered runtime.
5946
+ *
5947
+ * @param plugin — any supported plugin shape.
5948
+ * @returns `true` when at least one fiber of the plugin exists.
5949
+ */
5950
+ has(plugin) {
5951
+ const key = this.resolve(plugin);
5952
+ return !!key && this._internal.has(key);
5953
+ }
5954
+ /**
5955
+ * Dispose every running fiber for a plugin and remove its runtime record.
5956
+ *
5957
+ * @param plugin — any supported plugin shape.
5958
+ * @returns the removed runtime, or `undefined` when none was registered.
5959
+ */
5960
+ delete(plugin) {
5961
+ const key = this.resolve(plugin);
5962
+ const runtime = key && this._internal.get(key);
5963
+ if (!runtime) return;
5964
+ this._internal.delete(key);
5965
+ for (const fiber of runtime.fibers) fiber.dispose();
5966
+ return runtime;
5967
+ }
5968
+ /** Iterate the registered plugin callbacks. */
5969
+ keys() {
5970
+ return this._internal.keys();
5971
+ }
5972
+ /** Iterate the registered plugin runtimes. */
5973
+ values() {
5974
+ return this._internal.values();
5975
+ }
5976
+ /** Iterate `[callback, runtime]` pairs. */
5977
+ entries() {
5978
+ return this._internal.entries();
5979
+ }
5980
+ /**
5981
+ * Visit every registered runtime.
5982
+ *
5983
+ * @param callback — receives each runtime and its identifying callback.
5984
+ */
5985
+ forEach(callback) {
5986
+ return this._internal.forEach(callback);
5987
+ }
5988
+ /**
5989
+ * Start a callback once the requested dependencies are available.
5990
+ *
5991
+ * @param inject — required services, as an array or a name → config map.
5992
+ * @param callback — plugin body called with `(ctx, config)`.
5993
+ * @returns the fiber; awaiting it settles once loading finished.
5994
+ */
5995
+ inject(inject, callback) {
5996
+ return this.plugin({
5997
+ inject,
5998
+ apply: callback,
5999
+ name: callback.name
6000
+ });
6001
+ }
6002
+ /**
6003
+ * Start a plugin in the current context and return its fiber.
6004
+ *
6005
+ * Creates (or reuses) the plugin's runtime record, then starts a new fiber
6006
+ * under the current context. Throws if `plugin` is not a supported shape or
6007
+ * if the current fiber is already disposed.
6008
+ *
6009
+ * @param plugin — a function, class, or `{ apply }` object plugin.
6010
+ * @param config — the plugin config, validated against its `Config` schema.
6011
+ * @param getOuterStack — captures the caller stack for effect diagnostics.
6012
+ * @returns the fiber; awaiting it settles once loading finished.
6013
+ */
6014
+ plugin(plugin, config, getOuterStack = buildOuterStack()) {
6015
+ const callback = this.resolve(plugin);
6016
+ if (!callback) throw new Error("invalid plugin, expect function or object with an \"apply\" method, received " + typeof plugin);
6017
+ this.ctx.fiber.assertActive();
6018
+ let runtime = this._internal.get(callback);
6019
+ if (!runtime) {
6020
+ let name = plugin.name;
6021
+ if (name === "apply") name = void 0;
6022
+ runtime = {
6023
+ name,
6024
+ callback,
6025
+ fibers: new DisposableList(),
6026
+ Config: plugin.Config
6027
+ };
6028
+ this._internal.set(callback, runtime);
6029
+ }
6030
+ const fiber = new Fiber(this.ctx, config, Inject.resolve(plugin.inject), runtime, getOuterStack);
6031
+ const wrapped = Object.create(fiber);
6032
+ wrapped.then = (onFulfilled, onRejected) => {
6033
+ return fiber.await().then(onFulfilled, onRejected);
6034
+ };
6035
+ return wrapped;
6036
+ }
6037
+ };
6038
+ /**
6039
+ * Root and child dependency containers for Cordis plugins.
6040
+ *
6041
+ * A context is a proxy: normal property reads go through the service resolver,
6042
+ * while `extend()`, `isolate()`, and `intercept()` create scoped child
6043
+ * contexts without mutating their parent.
6044
+ */
6045
+ var Context = class Context {
6046
+ /** Symbol key under which a disposer exposes its {@link EffectMeta} diagnostics tree. */
6047
+ static effect = symbols.effect;
6048
+ /** Symbol key for a context's listener filter, consulted on every event dispatch. */
6049
+ static filter = symbols.filter;
6050
+ /** Symbol key of the isolation map (see the `Context[symbols.isolate]` property). */
6051
+ static isolate = symbols.isolate;
6052
+ /** Symbol key of the intercept map (see the `Context[symbols.intercept]` property). */
6053
+ static intercept = symbols.intercept;
6054
+ /**
6055
+ * Returns true for Cordis context proxies and context prototypes.
6056
+ *
6057
+ * Works across realms and across multiple copies of cordis, because the
6058
+ * brand is keyed by a global symbol rather than by `instanceof`.
6059
+ *
6060
+ * @param value — the value to test.
6061
+ * @returns `true` if `value` is a Cordis context, narrowing its type.
6062
+ */
6063
+ static is(value) {
6064
+ return !!value?.[Context.is];
6065
+ }
6066
+ static {
6067
+ Context.is[Symbol.toPrimitive] = () => Symbol.for("cordis.is");
6068
+ Context.prototype[Context.is] = true;
6069
+ }
6070
+ /** Create the root context and install the built-in services. */
6071
+ constructor() {
6072
+ this[symbols.isolate] = Object.create(null);
6073
+ this[symbols.intercept] = Object.create(null);
6074
+ const self = new Proxy(this, ReflectService.handler);
6075
+ this.root = self;
6076
+ this.baseUrl = void 0;
6077
+ this.fiber = new Fiber(self, {}, Object.create(null), null, () => []);
6078
+ this.reflect = new ReflectService(self);
6079
+ this.registry = new RegistryService(self);
6080
+ this.events = new EventsService(self);
6081
+ this.logger = new LoggerService(self);
6082
+ this.fiber._disposables.clear();
6083
+ return self;
6084
+ }
6085
+ [Symbol.for("nodejs.util.inspect.custom")]() {
6086
+ return `Context <${this.fiber.name}>`;
6087
+ }
6088
+ /**
6089
+ * Create a child context with extra metadata on top of the current scope.
6090
+ *
6091
+ * The child prototypally inherits every property of this context; own
6092
+ * properties of `meta` shadow the inherited ones. The parent is not mutated.
6093
+ *
6094
+ * @param meta — own properties (including symbol keys) to define on the child.
6095
+ * @returns a child context inheriting from this one.
6096
+ */
6097
+ extend(meta = {}) {
6098
+ const shadow = Reflect.getOwnPropertyDescriptor(this, symbols.shadow)?.value;
6099
+ const self = Object.create(getTraceable(this, this));
6100
+ for (const prop of Reflect.ownKeys(meta)) Object.defineProperty(self, prop, Reflect.getOwnPropertyDescriptor(meta, prop));
6101
+ if (!shadow) return self;
6102
+ return Object.assign(Object.create(self), { [symbols.shadow]: shadow });
6103
+ }
6104
+ /**
6105
+ * Create a child context with an independent service scope for `name`.
6106
+ *
6107
+ * Below the returned context, reads and writes of the service `name`
6108
+ * resolve against the new label instead of the parent's, so a different
6109
+ * implementation can be provided without affecting the parent scope.
6110
+ * Passing the same `label` to two `isolate()` calls joins their scopes.
6111
+ *
6112
+ * @param name — the service name to isolate.
6113
+ * @param label — scope label to join; defaults to a fresh unique symbol.
6114
+ * @returns a child context whose `name` service resolves in the new scope.
6115
+ */
6116
+ isolate(name, label) {
6117
+ const shadow = Object.create(this[symbols.isolate]);
6118
+ shadow[name] = label ?? Symbol(name);
6119
+ return this.extend({ [symbols.isolate]: shadow });
6120
+ }
6121
+ intercept(name, config) {
6122
+ const intercept = Object.create(this[symbols.intercept]);
6123
+ intercept[name] = config;
6124
+ return this.extend({ [symbols.intercept]: intercept });
6125
+ }
6126
+ };
6127
+ /**
6128
+ * Base class for services that expose a named API on `ctx`.
6129
+ *
6130
+ * Subclasses call `super(ctx, name)` from their constructor. The service is
6131
+ * registered immediately and is automatically removed with the owning fiber.
6132
+ */
6133
+ var Service = class Service {
6134
+ ctx;
6135
+ /** Symbol key of an instance method run after construction (class plugins). */
6136
+ static init = symbols.init;
6137
+ /** Symbol key of the availability predicate passed to `ctx.provide()`. */
6138
+ static check = symbols.check;
6139
+ /** Symbol key of the phantom intercept-config type parameter. */
6140
+ static config = symbols.config;
6141
+ /** Symbol key of the call body making a service callable (e.g. `ctx.logger()`). */
6142
+ static invoke = symbols.invoke;
6143
+ /** Symbol key of the helper deriving an extended service instance. */
6144
+ static extend = symbols.extend;
6145
+ /** Symbol key of the tracker metadata used for context tracing. */
6146
+ static tracker = symbols.tracker;
6147
+ /** Symbol key of the intercept-config resolution helper below. */
6148
+ static resolveConfig = symbols.resolveConfig;
6149
+ /** The service name this instance is registered under. */
6150
+ name;
6151
+ /**
6152
+ * Register this instance as `name` in the current context.
6153
+ *
6154
+ * Calls `ctx.reflect.provide(name, this, this[Service.check])`, so the
6155
+ * service is unregistered automatically when the owning fiber unloads.
6156
+ * Services with a `[Service.invoke]` body return a callable instance.
6157
+ *
6158
+ * @param ctx — the context to register in (stored as `this.ctx`).
6159
+ * @param name — the service name; defaults to the static `provide` field.
6160
+ */
6161
+ constructor(ctx, name) {
6162
+ this.ctx = ctx;
6163
+ name ??= this.constructor["provide"];
6164
+ let self = this;
6165
+ const tracker = {
6166
+ associate: name,
6167
+ property: "ctx"
6168
+ };
6169
+ if (self[symbols.invoke]) self = createCallable(name, joinPrototype(Object.getPrototypeOf(this), Function.prototype), tracker);
6170
+ self.ctx = ctx;
6171
+ self.name = name;
6172
+ defineProperty(self, symbols.tracker, tracker);
6173
+ self.ctx.reflect.provide(name, self, this[symbols.check]);
6174
+ return self;
6175
+ }
6176
+ [symbols.filter](ctx) {
6177
+ return ctx[symbols.isolate][this.name] === this.ctx[symbols.isolate][this.name];
6178
+ }
6179
+ [symbols.extend](props) {
6180
+ let self;
6181
+ if (this[Service.invoke]) self = createCallable(this.name, this, this[symbols.tracker]);
6182
+ else self = Object.create(this);
6183
+ return Object.assign(self, props);
6184
+ }
6185
+ /**
6186
+ * Merge intercept config from ancestors with optional base and head values.
6187
+ *
6188
+ * Entries added closer to the root apply first; `base` is prepended and
6189
+ * `head` appended. Uses `Config.merge` when the service declares one,
6190
+ * otherwise a shallow `Object.assign`.
6191
+ *
6192
+ * @param base — lowest-precedence config merged before all intercepts.
6193
+ * @param head — highest-precedence config merged after all intercepts.
6194
+ * @returns the merged config.
6195
+ */
6196
+ [symbols.resolveConfig](base, head) {
6197
+ let intercept = this.ctx[Context.intercept];
6198
+ const configs = [];
6199
+ while (this.name in intercept) {
6200
+ if (Object.hasOwn(intercept, this.name)) configs.unshift(intercept[this.name]);
6201
+ intercept = Object.getPrototypeOf(intercept);
6202
+ }
6203
+ if (base) configs.unshift(base);
6204
+ if (head) configs.push(head);
6205
+ if (this["Config"]?.merge) return this["Config"].merge(...configs);
6206
+ else return Object.assign({}, ...configs);
6207
+ }
6208
+ static [Symbol.hasInstance](instance) {
6209
+ if (!instance) return false;
6210
+ let constructor = instance.constructor;
6211
+ while (constructor) {
6212
+ constructor = constructor.prototype?.constructor;
6213
+ if (constructor === this) return true;
6214
+ constructor &&= Object.getPrototypeOf(constructor);
6215
+ }
6216
+ return false;
6217
+ }
6218
+ };
6219
+ //#endregion
6220
+ //#region ../../core/po-core/src/schemas/brain.ts
6221
+ /** Bound and project untrusted descriptive manifests without carrying executable fields. */
6222
+ function parsePoWebBrainMetadata(value) {
6223
+ const record = (input) => input !== null && typeof input === "object" && !Array.isArray(input);
6224
+ const text = (input) => typeof input === "string" && input.length <= 16384;
6225
+ const identity = (input) => text(input) && input.trim().length > 0;
6226
+ const scope = (input) => input === "global" || input === "workspace" || input === "session";
6227
+ const list = (input) => Array.isArray(input) && input.length <= 4096;
6228
+ if (!record(value) || value.version !== 1 || !list(value.slots) || !list(value.fills) || !list(value.diagnostics)) return void 0;
6229
+ const slots = [];
6230
+ const fills = [];
6231
+ for (const slot of value.slots) {
6232
+ if (!record(slot) || !identity(slot.name) || !scope(slot.scope) || slot.kind !== "data" && slot.kind !== "component" || slot.description !== void 0 && !text(slot.description) || slot.parent !== void 0 && !identity(slot.parent)) return void 0;
6233
+ slots.push({
6234
+ name: slot.name,
6235
+ scope: slot.scope,
6236
+ kind: slot.kind,
6237
+ ...slot.description === void 0 ? {} : { description: slot.description },
6238
+ ...slot.parent === void 0 ? {} : { parent: slot.parent }
6239
+ });
6240
+ }
6241
+ for (const fill of value.fills) {
6242
+ if (!record(fill) || !identity(fill.id) || !scope(fill.scope) || fill.slot !== null && !identity(fill.slot) || fill.placement !== "verified" && fill.placement !== "unverified" || fill.placement === "verified" && fill.slot === null) return void 0;
6243
+ fills.push({
6244
+ id: fill.id,
6245
+ scope: fill.scope,
6246
+ slot: fill.slot,
6247
+ placement: fill.placement
6248
+ });
6249
+ }
6250
+ if (!value.diagnostics.every(text)) return void 0;
6251
+ const metadata = {
6252
+ version: 1,
6253
+ slots,
6254
+ fills,
6255
+ diagnostics: [...value.diagnostics]
6256
+ };
6257
+ return new TextEncoder().encode(JSON.stringify(metadata)).byteLength <= 1048576 ? metadata : void 0;
6258
+ }
6259
+ //#endregion
6260
+ //#region ../../core/po-core/src/schemas/hostServiceContracts.ts
6261
+ /** Public host capabilities. Their owning scope is the actual host binding, not a new lifetime. */
6262
+ const PO_HOST_SERVICE_CONTRACTS = [
6263
+ {
6264
+ name: PO_FS_SERVICE,
6265
+ description: "Read and change files through the current host filesystem."
6266
+ },
6267
+ {
6268
+ name: PO_SHELL_SERVICE,
6269
+ description: "Run commands through the current host shell capability."
6270
+ },
6271
+ {
6272
+ name: PO_SQLITE_SERVICE,
6273
+ description: "Open SQLite databases through the current host implementation."
6274
+ },
6275
+ {
6276
+ name: PO_CONFIG_SERVICE,
6277
+ description: "Read the configuration admitted for this session."
6278
+ },
6279
+ {
6280
+ name: PO_SESSION_STORAGE_SERVICE,
6281
+ description: "Read and persist session data through the host storage."
6282
+ },
6283
+ {
6284
+ name: PO_ISOLATE_SERVICE,
6285
+ description: "Run scripts in the isolate implementation supplied by the host."
6286
+ }
6287
+ ];
6288
+ //#endregion
6289
+ //#region ../../core/po-core/src/schemas/serverPlugin.ts
6290
+ /** The host service each scope level publishes for the packages installed into it. */
6291
+ const PO_SERVER_HOST_SERVICE = "po/server-host";
6292
+ function readPoServerHost(context) {
6293
+ return context.get(PO_SERVER_HOST_SERVICE);
6294
+ }
6295
+ function requirePoServerHost(context) {
6296
+ const service = readPoServerHost(context);
6297
+ if (!service) throw new Error("The Po server host is unavailable. Start a Po server first.");
6298
+ return service;
6299
+ }
6300
+ /** Read pure root metadata without initializing or mounting the root. */
6301
+ function composeServerProviderOverrides(...roots) {
6302
+ return (context) => roots.flatMap((root) => {
6303
+ if (typeof root !== "function" && typeof root !== "object" || root === null) return [];
6304
+ const callback = root.providerOverrides;
6305
+ return typeof callback === "function" ? callback(context) : [];
6306
+ });
6307
+ }
6308
+ /** Capture schema inference before heterogeneous methods enter a contribution array. */
6309
+ function defineServerMethod(definition, handler) {
6310
+ return { register: (host) => host.registerMethod(definition, handler) };
6311
+ }
6312
+ //#endregion
6313
+ //#region ../../core/po-core/src/schemas/globalServices.ts
6314
+ const PO_GLOBAL_SERVICES_SERVICE = "po/global-services";
6315
+ defineServiceContract(PO_GLOBAL_SERVICES_SERVICE, { scope: "global" });
6316
+ /** Longest a package factory (server plugin apply, MCP session, Pi factory) may take. */
6317
+ const LIVE_FACTORY_TIMEOUT_MS = 1e4;
6318
+ /**
6319
+ * Bounds one host-awaited step of package code.
6320
+ *
6321
+ * The abandoned promise keeps running, because a module cannot be cancelled; its late
6322
+ * rejection is observed here so it never surfaces as an unhandled rejection.
6323
+ */
6324
+ function withTimeout(work, ms, label) {
6325
+ let timer;
6326
+ const timeout = new Promise((_, reject) => {
6327
+ timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`${label} timed out after ${String(ms)} ms`)), ms);
6328
+ timer.unref?.();
6329
+ });
6330
+ work.catch(() => void 0);
6331
+ return Promise.race([work, timeout]).finally(() => clearTimeout(timer));
6332
+ }
6333
+ /** Imports a live package URL under a timeout, skipping and recording poisoned URLs. */
6334
+ async function guardedImport(url, importer, guard) {
6335
+ if (guard.poisoned?.has(url)) throw new Error("skipped: this package content failed to load earlier and retries only after it changes");
6336
+ try {
6337
+ return await withTimeout(Promise.resolve().then(() => importer(url)), guard.importTimeoutMs ?? 15e3, "import");
6338
+ } catch (error) {
6339
+ guard.poisoned?.add(url);
6340
+ throw error;
6341
+ }
6342
+ }
6343
+ //#endregion
6344
+ //#region ../../core/po-core/src/schemas/headless.ts
6345
+ /** Session-only contributions. This is not a Pi ExtensionAPI or a TUI adapter. */
6346
+ const PO_HEADLESS_HOST_SERVICE = "po/headless-host";
6347
+ const PO_HEADLESS_OWNER = Symbol.for("po/headless-owner");
6348
+ const PROMPT_ADMISSION_ERROR = "PoHeadlessPromptAdmissionError";
6349
+ /** Admission is a host boundary, not an advisory package-hook failure. */
6350
+ var PoHeadlessPromptAdmissionError = class extends Error {
6351
+ constructor(cause) {
6352
+ super(cause instanceof Error ? cause.message : String(cause), { cause });
6353
+ this.name = PROMPT_ADMISSION_ERROR;
6354
+ }
6355
+ };
6356
+ const SESSION_SETUP_ERROR = "PoSessionSetupError";
6357
+ /**
6358
+ * A session cannot start until the user fixes their setup, such as configuring a model.
6359
+ *
6360
+ * Its message is written for the user and says what to do, so a server returns it as is
6361
+ * rather than hiding it behind a generic internal error.
6362
+ */
6363
+ var PoSessionSetupError = class extends Error {
6364
+ constructor(message) {
6365
+ super(message);
6366
+ this.name = SESSION_SETUP_ERROR;
6367
+ }
6368
+ };
6369
+ /** Error identity must survive independently bundled server and extension graphs. */
6370
+ function isPoHeadlessPromptAdmissionError(error) {
6371
+ return error instanceof Error && error.name === PROMPT_ADMISSION_ERROR;
6372
+ }
6373
+ const TOOL_BUSY_ERROR = "PoHeadlessToolBusyError";
6374
+ /** The tool and its hooks have not started. */
6375
+ var PoHeadlessToolBusyError = class extends Error {
6376
+ constructor() {
6377
+ super("An operation is already running");
6378
+ this.name = TOOL_BUSY_ERROR;
6379
+ }
6380
+ };
6381
+ function isPoHeadlessToolBusyError(error) {
6382
+ return error instanceof Error && error.name === TOOL_BUSY_ERROR;
6383
+ }
6384
+ function readPoHeadlessOwner(context) {
6385
+ return context[PO_HEADLESS_OWNER];
6386
+ }
6387
+ let crcTable;
6388
+ function crc32(bytes, start, end) {
6389
+ if (crcTable === void 0) {
6390
+ crcTable = /* @__PURE__ */ new Uint32Array(256);
6391
+ for (let n = 0; n < 256; n++) {
6392
+ let c = n;
6393
+ for (let k = 0; k < 8; k++) c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
6394
+ crcTable[n] = c >>> 0;
6395
+ }
6396
+ }
6397
+ let crc = 4294967295;
6398
+ for (let i = start; i < end; i++) crc = crcTable[(crc ^ bytes[i]) & 255] ^ crc >>> 8;
6399
+ return (crc ^ 4294967295) >>> 0;
6400
+ }
6401
+ const PNG_SIGNATURE = [
6402
+ 137,
6403
+ 80,
6404
+ 78,
6405
+ 71,
6406
+ 13,
6407
+ 10,
6408
+ 26,
6409
+ 10
6410
+ ];
6411
+ function startsWith(bytes, prefix, offset = 0) {
6412
+ return prefix.every((byte, index) => bytes[offset + index] === byte);
6413
+ }
6414
+ /** Why the model API would reject this image, or undefined when it looks decodable. Only png, jpeg, gif and webp are checked. */
6415
+ function invalidImageReason(data, mimeType) {
6416
+ let bytes;
6417
+ try {
6418
+ bytes = Uint8Array.from(atob(data), (char) => char.charCodeAt(0));
6419
+ } catch {
6420
+ return "the data is not valid base64";
6421
+ }
6422
+ if (mimeType === "image/png") {
6423
+ if (!startsWith(bytes, PNG_SIGNATURE)) return "the data is not a PNG";
6424
+ const view = new DataView(bytes.buffer);
6425
+ let offset = 8;
6426
+ while (offset + 12 <= bytes.length) {
6427
+ const length = view.getUint32(offset);
6428
+ const end = offset + 8 + length;
6429
+ if (end + 4 > bytes.length) break;
6430
+ if (crc32(bytes, offset + 4, end) !== view.getUint32(end)) return "a PNG chunk failed its checksum";
6431
+ if (startsWith(bytes, [
6432
+ 73,
6433
+ 69,
6434
+ 78,
6435
+ 68
6436
+ ], offset + 4)) return void 0;
6437
+ offset = end + 4;
6438
+ }
6439
+ return "the PNG is truncated";
6440
+ }
6441
+ if (mimeType === "image/jpeg") return startsWith(bytes, [255, 216]) ? void 0 : "the data is not a JPEG";
6442
+ if (mimeType === "image/gif") return startsWith(bytes, [
6443
+ 71,
6444
+ 73,
6445
+ 70,
6446
+ 56
6447
+ ]) ? void 0 : "the data is not a GIF";
6448
+ if (mimeType === "image/webp") return startsWith(bytes, [
6449
+ 82,
6450
+ 73,
6451
+ 70,
6452
+ 70
6453
+ ]) && startsWith(bytes, [
6454
+ 87,
6455
+ 69,
6456
+ 66,
6457
+ 80
6458
+ ], 8) ? void 0 : "the data is not a WebP";
6459
+ }
6460
+ /** Keeps valid images and swaps an undecodable one for a text note, since one bad image fails the whole turn and every later one. */
6461
+ function dropInvalidImages(content) {
6462
+ return content.map((part) => {
6463
+ if (part.type !== "image") return part;
6464
+ const reason = invalidImageReason(part.data, part.mimeType);
6465
+ return reason === void 0 ? part : {
6466
+ type: "text",
6467
+ text: `[image omitted: ${reason}]`
6468
+ };
6469
+ });
6470
+ }
6471
+ /** Visibility controls model discovery only, never admission for external execution. */
6472
+ function isPoHeadlessToolModelVisible(tool) {
6473
+ const visibility = tool._meta?.ui?.visibility;
6474
+ return visibility === void 0 || visibility.includes("model");
6475
+ }
6476
+ /** Session skill discovery tools, adapted to the size of the active catalog. */
6477
+ const PO_LOAD_SKILL_TOOL = "load_skill";
6478
+ const PO_SEARCH_SKILLS_TOOL = "search_skills";
6479
+ function readPoHeadlessHost(context) {
6480
+ return context.get(PO_HEADLESS_HOST_SERVICE);
6481
+ }
6482
+ function requirePoHeadlessHost(context) {
6483
+ const host = readPoHeadlessHost(context);
6484
+ if (!host) throw new Error("This contribution requires the Po headless session host.");
6485
+ return host;
6486
+ }
6487
+ //#endregion
6488
+ //#region ../../core/po-core/src/server/serverScope.ts
6489
+ /** What one plugin build shares in one tree: its keyed values, and what each scope running it holds. */
6490
+ var PluginShare = class {
6491
+ values = /* @__PURE__ */ new Map();
6492
+ running = /* @__PURE__ */ new Map();
6493
+ get idle() {
6494
+ return this.values.size === 0 && this.running.size === 0;
6495
+ }
6496
+ };
6497
+ const resourceName = (key) => JSON.stringify(typeof key === "string" ? [key] : key);
6498
+ const depth = (level) => PO_SERVER_SCOPE_LEVELS.indexOf(level);
6499
+ const describe = (error) => error instanceof Error ? error.message : String(error);
6500
+ const PACKAGE_PROVENANCE = Symbol("package provenance");
6501
+ let scopesOpened = 0;
6502
+ let buildsSeen = 0;
6503
+ const builds = /* @__PURE__ */ new WeakMap();
6504
+ /** A stable log label for one plugin build; a reload imports a new module, and so a new build. */
6505
+ function buildOf(owner) {
6506
+ let build = builds.get(owner);
6507
+ if (build === void 0) builds.set(owner, build = ++buildsSeen);
6508
+ return `build#${build}`;
6509
+ }
6510
+ const nameOf = (owner) => {
6511
+ const name = owner.name;
6512
+ return typeof name === "string" ? name : void 0;
6513
+ };
6514
+ /** Publishes one binding as a native service of the root it is plugged into. */
6515
+ function bindingProvider(context, { binding, scope }) {
6516
+ if (binding.name === "po/global-services") new ScopedGlobalServices(context, binding.value, scope);
6517
+ else context.provide(binding.name, binding.value);
6518
+ }
6519
+ var ScopedGlobalServices = class extends Service {
6520
+ registry;
6521
+ scope;
6522
+ constructor(ctx, registry, scope) {
6523
+ super(ctx, PO_GLOBAL_SERVICES_SERVICE);
6524
+ this.registry = registry;
6525
+ this.scope = scope;
6526
+ }
6527
+ register(owner, contribution) {
6528
+ return this.registry.register(owner, contribution, this.scope.provenance(this.ctx.fiber));
6529
+ }
6530
+ };
6531
+ /**
6532
+ * The scope service each root publishes.
6533
+ *
6534
+ * Cordis traceable services rebind `ctx` to the caller, so a binding made through
6535
+ * `provide` unwinds with the plugin that made it.
6536
+ */
6537
+ var ScopeService = class extends Service {
6538
+ scope;
6539
+ level;
6540
+ constructor(ctx, scope) {
6541
+ super(ctx, PO_SERVER_SCOPE_SERVICE);
6542
+ this.scope = scope;
6543
+ this.level = scope.level;
6544
+ }
6545
+ async provide(contract, value) {
6546
+ return await this.ctx.effect(() => this.scope.bind(contract, value, this.scope.provenance(this.ctx.fiber)), `po scope provide ${contract.name}`);
6547
+ }
6548
+ snapshot() {
6549
+ return this.scope.snapshot();
6550
+ }
6551
+ resolve(contract) {
6552
+ return this.scope.resolve(contract);
6553
+ }
6554
+ emit(name, ...args) {
6555
+ this.scope.emit(name, ...args);
6556
+ }
6557
+ broadcast(name, ...args) {
6558
+ this.scope.broadcast(name, ...args);
6559
+ }
6560
+ plugin(owner) {
6561
+ return this.scope.share(owner);
6562
+ }
6563
+ };
6564
+ /**
6565
+ * Binds registrations to the Cordis fiber that calls the host service.
6566
+ *
6567
+ * The host itself is shared by every package at its level, but Cordis traceable
6568
+ * services rebind `ctx` to the caller. That lets a package's registration unwind
6569
+ * even when `apply` throws before it can return its disposer.
6570
+ */
6571
+ var ScopedPoServerHost = class extends Service {
6572
+ host;
6573
+ scope;
6574
+ context;
6575
+ constructor(ctx, host) {
6576
+ super(ctx, PO_SERVER_HOST_SERVICE);
6577
+ this.host = host;
6578
+ this.scope = host.scope;
6579
+ this.context = host.context;
6580
+ }
6581
+ registerApi(api) {
6582
+ const headless = this.scope === "session" ? readPoHeadlessHost(this.ctx) : void 0;
6583
+ if (headless) {
6584
+ const activity = headless.registerActivity({
6585
+ name: `api:${api.basePath}`,
6586
+ start: () => {
6587
+ const registration = this.host.registerApi(api);
6588
+ if (registration.mounted !== true) {
6589
+ registration.dispose();
6590
+ throw new Error(`package API '${api.basePath}' did not mount.`);
6591
+ }
6592
+ return () => {
6593
+ registration.dispose();
6594
+ };
6595
+ }
6596
+ });
6597
+ return {
6598
+ mounted: true,
6599
+ dispose: () => activity.dispose()
6600
+ };
6601
+ }
6602
+ const registration = this.host.registerApi(api);
6603
+ if (registration.mounted !== true) {
6604
+ registration.dispose();
6605
+ throw new Error(`package API '${api.basePath}' did not mount.`);
6606
+ }
6607
+ this.ctx.effect(() => () => registration.dispose(), "server package API registration");
6608
+ return registration;
6609
+ }
6610
+ registerChannel(channel) {
6611
+ const registration = this.host.registerChannel(channel);
6612
+ if (registration.mounted !== true) {
6613
+ registration.dispose();
6614
+ throw new Error(`hub channel '${channel.frameType}' did not mount.`);
6615
+ }
6616
+ this.ctx.effect(() => () => registration.dispose(), "server package channel registration");
6617
+ return registration;
6618
+ }
6619
+ registerMethod = (definition, handler) => {
6620
+ const registration = this.host.registerMethod(definition, handler);
6621
+ if (registration.mounted !== true) {
6622
+ registration.dispose();
6623
+ throw new Error(`plugin method '${definition.service}.${definition.method}' did not mount.`);
6624
+ }
6625
+ this.ctx.effect(() => () => registration.dispose(), "server package method registration");
6626
+ return registration;
6627
+ };
6628
+ mounted() {
6629
+ return this.host.mounted();
6630
+ }
6631
+ mountedChannels() {
6632
+ return this.host.mountedChannels();
6633
+ }
6634
+ };
6635
+ /** Publishes the host service from inside a root-level plugin, so it unwinds with the scope. */
6636
+ function serverHostProvider(context, host) {
6637
+ new ScopedPoServerHost(context, host);
6638
+ }
6639
+ /** Publishes the platform services from inside a root-level plugin, so they unwind with the scope. */
6640
+ function platformProvider(context, input) {
6641
+ const env = input.platform.env(input.cwd);
6642
+ context.provide(PO_FS_SERVICE, env);
6643
+ context.provide(PO_SHELL_SERVICE, env);
6644
+ context.provide(PO_SQLITE_SERVICE, input.platform.sqlite);
6645
+ context.provide(PO_SESSION_STORAGE_SERVICE, input.platform.sessions);
6646
+ if (input.platform.isolate !== void 0) context.provide(PO_ISOLATE_SERVICE, input.platform.isolate);
6647
+ if (input.platform.npm !== void 0) context.provide(PO_NPM_SERVICE, input.platform.npm);
6648
+ if (input.platform.electron !== void 0) context.provide(PO_ELECTRON_SERVICE, input.platform.electron);
6649
+ if (input.platform.browser !== void 0) context.provide(PO_BROWSER_SERVICE, input.platform.browser);
6650
+ if (input.platform.providerAuth !== void 0) context.provide(PO_PROVIDER_AUTH_SERVICE, input.platform.providerAuth);
6651
+ if (input.temporaryDirectory !== void 0) context.provide(PO_SESSION_FILES_SERVICE, { temporaryDirectory: input.temporaryDirectory });
6652
+ context.effect(() => () => env.cleanup(BACKGROUND_CONTEXT), "platform execution env");
6653
+ }
6654
+ /**
6655
+ * One level of the server IoC tree: its own cordis root, a parent link, the contracts bound here,
6656
+ * and the packages installed here.
6657
+ *
6658
+ * Separate roots rather than one shared root, because cordis re-checks every fiber of a root on each
6659
+ * service change; a hundred sessions in one root would make every change scan all of them. A binding
6660
+ * is instead mirrored into each descendant root as a native service, so a plugin injects an outer
6661
+ * level's service exactly as it injects its own.
6662
+ */
6663
+ var PoServerScope = class PoServerScope {
6664
+ level;
6665
+ parent;
6666
+ root = new Context();
6667
+ children = /* @__PURE__ */ new Set();
6668
+ bound = /* @__PURE__ */ new Map();
6669
+ mirrors = /* @__PURE__ */ new Map();
6670
+ /** A binding waiting here for the farther one it shadows to leave, so a repeat mirror waits too. */
6671
+ replacing = /* @__PURE__ */ new Map();
6672
+ hostFibers = /* @__PURE__ */ new Set();
6673
+ installed = /* @__PURE__ */ new Map();
6674
+ installs = Promise.resolve();
6675
+ /** Set once a package's apply never settled, to the bound it overran; its fiber may never finish disposing. */
6676
+ abandonedTimeoutMs;
6677
+ notice = () => void 0;
6678
+ disposing;
6679
+ /** The served mount table, read when a request routes through this level. */
6680
+ router;
6681
+ /** Kept by the outermost scope only: what each plugin build shares across the whole tree. */
6682
+ shares = /* @__PURE__ */ new Map();
6683
+ /** Names this scope in logs, as its level and the order it opened in. */
6684
+ label;
6685
+ /** The last graph logged for a failing binding, by name, so a retry that fails the same way stays quiet. */
6686
+ reported = /* @__PURE__ */ new Map();
6687
+ constructor(level, parent) {
6688
+ this.level = level;
6689
+ this.parent = parent;
6690
+ this.label = `${level}#${++scopesOpened}`;
6691
+ }
6692
+ /** Opens a scope below `parent`, with every binding visible from its ancestors already published. */
6693
+ static async open(level, parent) {
6694
+ if (parent?.disposing !== void 0) throw new Error(`The ${parent.level} scope is disposed.`);
6695
+ if (parent !== void 0 && depth(level) <= depth(parent.level)) throw new Error(`A ${level} scope cannot open below a ${parent.level} scope.`);
6696
+ const scope = new PoServerScope(level, parent);
6697
+ parent?.children.add(scope);
6698
+ try {
6699
+ await scope.root.plugin(ScopeService, scope);
6700
+ await Promise.all((parent?.visible() ?? []).map((binding) => scope.mirror(binding)));
6701
+ } catch (error) {
6702
+ await scope.dispose();
6703
+ throw error;
6704
+ }
6705
+ return scope;
6706
+ }
6707
+ get disposed() {
6708
+ return this.disposing !== void 0;
6709
+ }
6710
+ /**
6711
+ * Publishes what every package at this level reads: the owner's mount table as `po/server-host`,
6712
+ * and the platform services. They stay for the life of the scope; the owner still disposes the
6713
+ * mount table it handed in.
6714
+ */
6715
+ async serve(input) {
6716
+ if (this.disposed) throw new Error(`The ${this.level} scope is disposed.`);
6717
+ if (input.host.scope !== this.level) throw new Error(`A ${input.host.scope} host cannot serve a ${this.level} scope.`);
6718
+ this.hostFibers.add(await this.root.plugin(serverHostProvider, input.host));
6719
+ this.router = input.host;
6720
+ const hostContext = input.host.context;
6721
+ const cwd = hostContext?.cwd ?? hostContext?.workspaceRoot ?? input.platform.homeDirectory;
6722
+ this.hostFibers.add(await this.root.plugin(platformProvider, {
6723
+ platform: input.platform,
6724
+ cwd,
6725
+ temporaryDirectory: this.level === "session" ? hostContext?.environment?.[PO_SESSION_TEMP_DIR] : void 0
6726
+ }));
6727
+ }
6728
+ /**
6729
+ * Installs packages at this level, each as its own fiber in this root, one at a time.
6730
+ *
6731
+ * Installation only adds. A package installed from the same build (the same plugin object) is
6732
+ * skipped. One whose build changed is disposed and the new build applied; when that fails, the
6733
+ * previous build is applied again. A package missing from `packages` stays installed, because
6734
+ * which packages a session runs is its own composition's choice. Installs into one scope run one
6735
+ * at a time. Resolves with every package installed here, in install order.
6736
+ */
6737
+ install(packages, options = {}) {
6738
+ const run = this.installs.then(() => this.installAll(packages, options));
6739
+ this.installs = run.then(() => void 0, () => void 0);
6740
+ return run;
6741
+ }
6742
+ /**
6743
+ * Disposes the named packages installed here, in reverse install order, each bounded by the
6744
+ * cleanup time limit. Runs in order with installs. Resolves with every package still installed.
6745
+ */
6746
+ uninstall(names) {
6747
+ const run = this.installs.then(async () => {
6748
+ if (this.disposed) throw new Error(`The ${this.level} scope is disposed.`);
6749
+ for (const [name, { fiber }] of [...this.installed].reverse()) {
6750
+ if (!names.includes(name)) continue;
6751
+ this.installed.delete(name);
6752
+ await this.disposeFiber(name, fiber, LIVE_FACTORY_TIMEOUT_MS);
6753
+ }
6754
+ return [...this.installed.keys()];
6755
+ });
6756
+ this.installs = run.then(() => void 0, () => void 0);
6757
+ return run;
6758
+ }
6759
+ /**
6760
+ * Binds a contract owned by this level here and in every descendant, including ones opened later.
6761
+ * Settles once every descendant root publishes it, or a nearer binding of the same name shadows it
6762
+ * there. Hosts call this directly; plugins go through the scope service so the binding follows
6763
+ * their fiber.
6764
+ */
6765
+ async bind(contract, value, metadata = {
6766
+ owner: {
6767
+ kind: "host",
6768
+ packageName: null,
6769
+ origin: "unknown"
6770
+ },
6771
+ contracts: []
6772
+ }) {
6773
+ if (this.disposed) throw new Error(`The ${this.level} scope is disposed.`);
6774
+ 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.`);
6775
+ if (this.bound.has(contract.name)) throw new Error(`Contract '${contract.name}' is already provided in this ${this.level} scope.`);
6776
+ const binding = {
6777
+ name: contract.name,
6778
+ contract,
6779
+ metadata: projectServiceBindingMetadata(metadata),
6780
+ value,
6781
+ owner: this
6782
+ };
6783
+ this.bound.set(contract.name, binding);
6784
+ const withdraw = async () => {
6785
+ if (this.bound.get(contract.name) !== binding) return;
6786
+ this.bound.delete(contract.name);
6787
+ await Promise.all([...this.subtree()].map(async (scope) => {
6788
+ await scope.unmirror(binding);
6789
+ const outer = scope.nearest(contract.name);
6790
+ if (outer === void 0) return;
6791
+ await scope.mirror(outer).catch((error) => {
6792
+ this.notice(`binding '${contract.name}' from ${outer.owner.label} did not return to ${scope.label} (${describe(error)})`);
6793
+ });
6794
+ }));
6795
+ };
6796
+ try {
6797
+ await Promise.all([...this.subtree()].map((scope) => scope.mirror(binding)));
6798
+ } catch (error) {
6799
+ this.reportGraph(contract.name, error);
6800
+ await withdraw();
6801
+ throw error;
6802
+ }
6803
+ return withdraw;
6804
+ }
6805
+ /** Finds only the installed package that owns this fiber, including nested service fibers. */
6806
+ provenance(fiber) {
6807
+ const declared = fiber.ctx[PACKAGE_PROVENANCE];
6808
+ if (declared) return declared;
6809
+ for (;;) {
6810
+ for (const [name, entry] of this.installed) {
6811
+ if (entry.fiber.uid !== fiber.uid) continue;
6812
+ return {
6813
+ owner: {
6814
+ kind: "package",
6815
+ packageName: name,
6816
+ origin: entry.declaration?.origin ?? "unknown"
6817
+ },
6818
+ contracts: Object.values(entry.plugin.provides ?? {}).flat()
6819
+ };
6820
+ }
6821
+ if (fiber.parent.fiber === fiber) break;
6822
+ fiber = fiber.parent.fiber;
6823
+ }
6824
+ return {
6825
+ owner: {
6826
+ kind: "unknown",
6827
+ packageName: null,
6828
+ origin: "unknown"
6829
+ },
6830
+ contracts: []
6831
+ };
6832
+ }
6833
+ snapshot() {
6834
+ const scopes = [...this.ancestry()];
6835
+ const describeScope = (scope) => ({
6836
+ id: scope.label,
6837
+ level: scope.level
6838
+ });
6839
+ const result = {
6840
+ scope: describeScope(this),
6841
+ scopes: scopes.map(describeScope),
6842
+ packages: [],
6843
+ services: [],
6844
+ consumers: [],
6845
+ edges: [],
6846
+ diagnostics: []
6847
+ };
6848
+ const clientInventories = scopes.map((scope) => scope.router?.context?.clientPlugins);
6849
+ if (clientInventories.every((inventory) => inventory?.available)) result.clientPackages = clientInventories.flatMap((inventory, index) => inventory.packages.map((pkg) => ({
6850
+ scope: describeScope(scopes[index]),
6851
+ owner: {
6852
+ kind: pkg.owner.kind,
6853
+ packageName: pkg.owner.packageName,
6854
+ origin: pkg.owner.origin
6855
+ },
6856
+ web: parsePoWebBrainMetadata(pkg.web) ?? null
6857
+ })));
6858
+ for (const scope of scopes) {
6859
+ for (const [name, entry] of scope.installed) {
6860
+ const owner = {
6861
+ kind: "package",
6862
+ packageName: name,
6863
+ origin: entry.declaration?.origin ?? "unknown"
6864
+ };
6865
+ result.packages.push({
6866
+ scope: describeScope(scope),
6867
+ owner,
6868
+ web: entry.declaration?.webMetadata ?? null,
6869
+ native: entry.declaration?.nativeMetadata ?? null
6870
+ });
6871
+ const consumer = `${scope.label}:consumer:${name}`;
6872
+ result.consumers.push({
6873
+ id: consumer,
6874
+ name,
6875
+ scope: describeScope(scope),
6876
+ owner
6877
+ });
6878
+ const injections = /* @__PURE__ */ new Set([...Object.keys(entry.fiber.inject), ...(entry.plugin.injects?.[scope.level] ?? []).map((contract) => contract.name)]);
6879
+ for (const name of injections) result.edges.push({
6880
+ consumer,
6881
+ name,
6882
+ service: null,
6883
+ status: "waiting"
6884
+ });
6885
+ }
6886
+ for (const runtime of scope.root.registry.values()) for (const fiber of runtime.fibers) {
6887
+ if ([...scope.installed.values()].some((entry) => entry.fiber.uid === fiber.uid)) continue;
6888
+ const names = Object.keys(fiber.inject);
6889
+ if (!names.length) continue;
6890
+ const consumer = `${scope.label}:consumer:fiber:${fiber.uid}`;
6891
+ result.consumers.push({
6892
+ id: consumer,
6893
+ name: `fiber#${fiber.uid}`,
6894
+ scope: describeScope(scope),
6895
+ owner: scope.provenance(fiber).owner
6896
+ });
6897
+ for (const name of names) result.edges.push({
6898
+ consumer,
6899
+ name,
6900
+ service: null,
6901
+ status: "waiting"
6902
+ });
6903
+ }
6904
+ for (const key of Reflect.ownKeys(scope.root.reflect.store)) {
6905
+ const impl = scope.root.reflect.store[key];
6906
+ const mirror = [...scope.mirrors].find(([, fiber]) => fiber.uid === impl.fiber.uid)?.[0];
6907
+ if (mirror && mirror.owner !== scope) continue;
6908
+ const metadata = mirror?.metadata ?? scope.provenance(impl.fiber);
6909
+ const host = (metadata.owner.kind === "host" || [...scope.hostFibers].some((fiber) => fiber.uid === impl.fiber.uid) || impl.fiber === scope.root.fiber) && PO_HOST_SERVICE_CONTRACTS.find((contract) => contract.name === impl.name);
6910
+ const contract = metadata.contracts.find((contract) => contract.name === impl.name && contract.scope === scope.level);
6911
+ result.services.push({
6912
+ id: `${scope.label}:service:${impl.name}`,
6913
+ name: impl.name,
6914
+ scope: describeScope(scope),
6915
+ visibleFrom: describeScope(scope),
6916
+ owner: host ? {
6917
+ kind: "host",
6918
+ packageName: null,
6919
+ origin: "unknown"
6920
+ } : metadata.owner,
6921
+ public: !!contract || !!host,
6922
+ description: contract?.description ?? mirror?.contract.description ?? (host ? host.description : null)
6923
+ });
6924
+ }
6925
+ }
6926
+ for (const service of result.services) {
6927
+ const ownerIndex = scopes.findIndex((scope) => scope.label === service.scope.id);
6928
+ service.visibleFrom = describeScope(scopes[scopes.findLastIndex((scope, index) => index < ownerIndex && result.services.some((other) => other.scope.id === scope.label && other.name === service.name)) + 1]);
6929
+ }
6930
+ for (const edge of result.edges) {
6931
+ const consumer = result.consumers.find((consumer) => consumer.id === edge.consumer);
6932
+ const start = scopes.findIndex((scope) => scope.label === consumer.scope.id);
6933
+ const service = scopes.slice(start).flatMap((scope) => result.services.filter((service) => service.scope.id === scope.label && service.name === edge.name))[0];
6934
+ if (service) {
6935
+ edge.service = service.id;
6936
+ edge.status = "resolved";
6937
+ }
6938
+ }
6939
+ return structuredClone(result);
6940
+ }
6941
+ resolve(contract) {
6942
+ if (depth(contract.scope) > depth(this.level)) throw new Error(`A ${this.level} scope cannot see the ${contract.scope} contract '${contract.name}'.`);
6943
+ for (const scope of this.ancestry()) if (scope.level === contract.scope) return scope.bound.get(contract.name)?.value;
6944
+ }
6945
+ /**
6946
+ * The handler for an API, from this level or the nearest one above it that serves it. An API
6947
+ * declared at a level reaches every level below it, and a level that runs a package from an outer
6948
+ * level leaves that level's root-bound APIs to it; a level that declares the API itself wins.
6949
+ */
6950
+ apiHandler(basePath) {
6951
+ for (const scope of this.ancestry()) {
6952
+ const handler = scope.router?.handlerFor?.(basePath);
6953
+ if (handler !== void 0) return handler;
6954
+ }
6955
+ }
6956
+ /** Resolve only the nearest mounted API's parsed contract, never a caller supplied operation. */
6957
+ apiOperation(basePath, method, path) {
6958
+ for (const scope of this.ancestry()) {
6959
+ if (!scope.router?.handlerFor?.(basePath)) continue;
6960
+ for (const { declaration } of scope.installed.values()) {
6961
+ 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]));
6962
+ if (route) return route.id;
6963
+ }
6964
+ return;
6965
+ }
6966
+ }
6967
+ emit(name, ...args) {
6968
+ deliver([...this.ancestry()], name, args);
6969
+ }
6970
+ broadcast(name, ...args) {
6971
+ deliver([...this.subtree()], name, args);
6972
+ }
6973
+ /**
6974
+ * Disposes descendants first, then the packages installed here in reverse install order, then
6975
+ * this root; a binding made here unwinds with its provider.
6976
+ */
6977
+ dispose() {
6978
+ this.disposing ??= (async () => {
6979
+ await Promise.all([...this.children].map((child) => child.dispose()));
6980
+ this.parent?.children.delete(this);
6981
+ this.mirrors.clear();
6982
+ this.router = void 0;
6983
+ const packages = [...this.installed.values()].reverse();
6984
+ this.installed.clear();
6985
+ for (const { plugin, declaration, fiber } of packages) await this.disposeFiber(declaration?.packageName ?? plugin.name, fiber, LIVE_FACTORY_TIMEOUT_MS);
6986
+ const disposal = this.root.fiber.dispose();
6987
+ if (this.abandonedTimeoutMs === void 0) return await disposal;
6988
+ await withTimeout(disposal, this.abandonedTimeoutMs, `${this.level} scope dispose`).catch((error) => this.notice(describe(error)));
6989
+ })().finally(async () => {
6990
+ if (this.parent === void 0) await this.disposeShares();
6991
+ });
6992
+ return this.disposing;
6993
+ }
6994
+ /**
6995
+ * What the plugin build `owner` shares in this tree, seen from this scope. The outermost scope keeps
6996
+ * one store per build, so every level of one hub sees the same values and no two hubs ever do.
6997
+ */
6998
+ share(owner) {
6999
+ const top = this.outermost();
7000
+ const name = nameOf(owner);
7001
+ const build = buildOf(owner);
7002
+ 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.`);
7003
+ const storeOf = () => {
7004
+ let store = top.shares.get(owner);
7005
+ if (store === void 0) {
7006
+ store = new PluginShare();
7007
+ top.shares.set(owner, store);
7008
+ }
7009
+ return store;
7010
+ };
7011
+ const settle = (store) => {
7012
+ if (store.idle && top.shares.get(owner) === store) top.shares.delete(owner);
7013
+ };
7014
+ return {
7015
+ acquire: async (key, create, dispose) => {
7016
+ if (this.disposed) throw new Error(`The ${this.level} scope is disposed.`);
7017
+ const store = storeOf();
7018
+ const name = resourceName(key);
7019
+ let shared = store.values.get(name);
7020
+ if (shared === void 0) {
7021
+ const created = {
7022
+ value: Promise.resolve().then(create),
7023
+ holders: 0,
7024
+ disposeValue: dispose === void 0 ? void 0 : (value) => dispose(value)
7025
+ };
7026
+ store.values.set(name, created);
7027
+ created.value.catch(() => {
7028
+ if (store.values.get(name) === created) store.values.delete(name);
7029
+ settle(store);
7030
+ });
7031
+ shared = created;
7032
+ }
7033
+ const held = shared;
7034
+ held.holders += 1;
7035
+ let value;
7036
+ try {
7037
+ value = await held.value;
7038
+ } catch (error) {
7039
+ held.holders -= 1;
7040
+ throw error;
7041
+ }
7042
+ let released = false;
7043
+ return {
7044
+ value,
7045
+ release: async () => {
7046
+ if (released) return;
7047
+ released = true;
7048
+ held.holders -= 1;
7049
+ if (held.holders > 0 || store.values.get(name) !== held) return;
7050
+ store.values.delete(name);
7051
+ settle(store);
7052
+ await held.disposeValue?.(value);
7053
+ }
7054
+ };
7055
+ },
7056
+ run: (roots) => {
7057
+ if (this.disposed) throw new Error(`The ${this.level} scope is disposed.`);
7058
+ const store = storeOf();
7059
+ store.running.set(this, roots);
7060
+ return () => {
7061
+ if (store.running.get(this) === roots) store.running.delete(this);
7062
+ settle(store);
7063
+ };
7064
+ },
7065
+ outer: (from) => {
7066
+ const store = top.shares.get(owner);
7067
+ if (store === void 0) return [];
7068
+ const held = [];
7069
+ for (const scope of this.parent?.ancestry() ?? []) if (depth(scope.level) >= depth(from) && store.running.has(scope)) held.push(store.running.get(scope));
7070
+ return held;
7071
+ }
7072
+ };
7073
+ }
7074
+ async installAll(packages, options) {
7075
+ if (this.disposed) throw new Error(`The ${this.level} scope is disposed.`);
7076
+ const notice = options.onNotice ?? (() => {});
7077
+ this.notice = notice;
7078
+ if (packages.some((candidate) => "retained" in candidate && candidate.retained === true) && !readPoHeadlessHost(this.root)) throw new Error("Retained server candidates require a gated headless host");
7079
+ for (const candidate of packages) {
7080
+ const plugin = "declaration" in candidate ? candidate.plugin : candidate;
7081
+ const declaration = "declaration" in candidate ? candidate.declaration : void 0;
7082
+ const name = declaration?.packageName ?? plugin.name;
7083
+ const previous = this.installed.get(name);
7084
+ if (previous?.plugin === plugin) continue;
7085
+ if (previous !== void 0) {
7086
+ this.installed.delete(name);
7087
+ await this.disposeFiber(name, previous.fiber, options.factoryTimeoutMs ?? 1e4);
7088
+ }
7089
+ try {
7090
+ const fiber = await this.apply(name, plugin, declaration, options);
7091
+ this.installed.set(name, {
7092
+ plugin,
7093
+ ...declaration === void 0 ? {} : { declaration },
7094
+ fiber
7095
+ });
7096
+ } catch (error) {
7097
+ const message = `server package '${name}' did not install (${describe(error)})`;
7098
+ if (previous !== void 0) {
7099
+ const restored = await this.restore(name, previous, options, message);
7100
+ options.onPackageFailed?.({
7101
+ packageName: name,
7102
+ reason: describe(error),
7103
+ previous: restored ? "restored" : "lost"
7104
+ });
7105
+ continue;
7106
+ }
7107
+ options.onPackageFailed?.({
7108
+ packageName: name,
7109
+ reason: describe(error),
7110
+ previous: "none"
7111
+ });
7112
+ if (declaration?.required === true && !("initiallyEligible" in candidate && candidate.initiallyEligible === false)) throw new Error(message, { cause: error });
7113
+ notice(message);
7114
+ }
7115
+ }
7116
+ for (const candidate of packages) {
7117
+ const plugin = "declaration" in candidate ? candidate.plugin : candidate;
7118
+ const name = ("declaration" in candidate ? candidate.declaration.packageName : void 0) ?? plugin.name;
7119
+ if (this.installed.get(name)?.plugin !== plugin) continue;
7120
+ 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.`);
7121
+ }
7122
+ return [...this.installed.keys()];
7123
+ }
7124
+ /** Applies a replaced package's previous build again after its new build failed; true when it runs. */
7125
+ async restore(name, previous, options, message) {
7126
+ try {
7127
+ const fiber = await this.apply(name, previous.plugin, previous.declaration, options);
7128
+ this.installed.set(name, {
7129
+ ...previous,
7130
+ fiber
7131
+ });
7132
+ this.notice(`${message}; its previous build is restored.`);
7133
+ return true;
7134
+ } catch (rollbackError) {
7135
+ this.notice(`${message}; its previous build could not be restored (${describe(rollbackError)}).`);
7136
+ return false;
7137
+ }
7138
+ }
7139
+ /** Applies one package as its own fiber, bounded by the factory timeout, and reports how it settled. */
7140
+ async apply(name, plugin, declaration, options) {
7141
+ const startedAt = Date.now();
7142
+ const timeoutMs = options.factoryTimeoutMs ?? 1e4;
7143
+ const settled = (outcome) => options.onPackageSettled?.({
7144
+ packageName: name,
7145
+ durationMs: Date.now() - startedAt,
7146
+ outcome
7147
+ });
7148
+ let fiber;
7149
+ let applySettled = false;
7150
+ try {
7151
+ const metadata = {
7152
+ owner: {
7153
+ kind: "package",
7154
+ packageName: name,
7155
+ origin: declaration?.origin ?? "unknown"
7156
+ },
7157
+ contracts: Object.values(plugin.provides ?? {}).flat()
7158
+ };
7159
+ fiber = this.root.extend({
7160
+ [PACKAGE_PROVENANCE]: metadata,
7161
+ ...declaration ? { [PO_HEADLESS_OWNER]: declaration } : {}
7162
+ }).plugin(plugin);
7163
+ const applied = fiber.await();
7164
+ const markSettled = () => {
7165
+ applySettled = true;
7166
+ };
7167
+ applied.then(markSettled, markSettled);
7168
+ await withTimeout(applied, timeoutMs, `server package '${name}' apply`);
7169
+ settled("installed");
7170
+ return fiber;
7171
+ } catch (error) {
7172
+ settled(fiber && !applySettled ? "timed_out" : "failed");
7173
+ if (fiber && !applySettled) {
7174
+ this.abandonedTimeoutMs = Math.max(this.abandonedTimeoutMs ?? 0, timeoutMs);
7175
+ fiber.dispose().catch((disposeError) => this.notice(`abandoned server package '${name}' did not dispose (${describe(disposeError)})`));
7176
+ } else if (fiber) await this.disposeFiber(name, fiber, timeoutMs);
7177
+ throw error;
7178
+ }
7179
+ }
7180
+ /**
7181
+ * Disposes one package's fiber within `timeoutMs`. A package whose cleanup throws or never settles
7182
+ * is reported and left behind, so it cannot block the packages after it or the scope's teardown.
7183
+ */
7184
+ async disposeFiber(name, fiber, timeoutMs) {
7185
+ try {
7186
+ await withTimeout(fiber.dispose(), timeoutMs, `server package '${name}' dispose`);
7187
+ } catch (error) {
7188
+ this.abandonedTimeoutMs = Math.max(this.abandonedTimeoutMs ?? 0, timeoutMs);
7189
+ this.notice(`server package '${name}' did not dispose (${describe(error)})`);
7190
+ }
7191
+ }
7192
+ visible() {
7193
+ return [...this.parent?.visible() ?? [], ...this.bound.values()];
7194
+ }
7195
+ /**
7196
+ * Logs, once per distinct tree, which scopes bind `name`, whose binding each root mirrors, and
7197
+ * which Cordis fiber actually holds the service in that root.
7198
+ */
7199
+ reportGraph(name, error) {
7200
+ const top = this.outermost();
7201
+ const graph = [...top.subtree()].map((scope) => {
7202
+ const context = scope.router?.context;
7203
+ const cwd = context?.cwd ?? context?.workspaceRoot;
7204
+ const holds = [...scope.mirrors.keys()].filter((binding) => binding.name === name).map(({ owner }) => owner.label);
7205
+ const impl = scope.root.reflect._getImpl(name, false);
7206
+ const mirrored = impl && [...scope.mirrors].find(([, fiber]) => fiber === impl.fiber)?.[0];
7207
+ const cordis = impl === void 0 ? "none" : `<${impl.fiber.name}#${impl.fiber.uid}> state=${impl.fiber.state}${mirrored ? ` from ${mirrored.owner.label}` : ""}`;
7208
+ return `${" ".repeat(depth(scope.level))}${scope.label}${cwd ? ` ${cwd}` : ""} binds=${scope.bound.has(name) ? "yes" : "no"} mirrors=[${holds.join(", ")}] cordis=${cordis}`;
7209
+ }).join("\n");
7210
+ if (top.reported.get(name) === graph) return;
7211
+ top.reported.set(name, graph);
7212
+ this.notice(`binding '${name}' from ${this.label} failed (${describe(error)}); scope tree:\n${graph}`);
7213
+ }
7214
+ /** This scope, then each parent out to the root. */
7215
+ outermost() {
7216
+ return this.parent === void 0 ? this : this.parent.outermost();
7217
+ }
7218
+ /** Disposes every value the tree still holds, newest first; a failure is reported and the rest still go. */
7219
+ async disposeShares() {
7220
+ const values = [...this.shares.values()].flatMap((store) => [...store.values.values()]).reverse();
7221
+ this.shares.clear();
7222
+ for (const shared of values) try {
7223
+ await shared.disposeValue?.(await shared.value);
7224
+ } catch (error) {
7225
+ this.notice(`a shared server value did not dispose (${describe(error)})`);
7226
+ }
7227
+ }
7228
+ *ancestry() {
7229
+ yield this;
7230
+ if (this.parent !== void 0) yield* this.parent.ancestry();
7231
+ }
7232
+ *subtree() {
7233
+ if (this.disposed) return;
7234
+ yield this;
7235
+ for (const child of this.children) yield* child.subtree();
7236
+ }
7237
+ /** The binding of `name` this root publishes: the one bound nearest to it. */
7238
+ nearest(name) {
7239
+ for (const scope of this.ancestry()) {
7240
+ const binding = scope.bound.get(name);
7241
+ if (binding !== void 0) return binding;
7242
+ }
7243
+ }
7244
+ /**
7245
+ * Publishes a binding into this root and settles once it is live. Idempotent per binding, since a
7246
+ * child opening mid-bind is reached by both `open` and `bind`. A nearer level binding the same
7247
+ * name wins, as a level declaring an API itself does; Cordis holds one service per name in a root,
7248
+ * so the farther binding leaves first.
7249
+ */
7250
+ async mirror(binding) {
7251
+ if (this.disposed || this.nearest(binding.name) !== binding) return;
7252
+ const replacing = this.replacing.get(binding);
7253
+ if (replacing !== void 0) {
7254
+ await replacing;
7255
+ return await this.mirror(binding);
7256
+ }
7257
+ let fiber = this.mirrors.get(binding);
7258
+ if (fiber === void 0) {
7259
+ const shadowed = [...this.mirrors.keys()].filter((other) => other.name === binding.name);
7260
+ if (shadowed.length > 0) {
7261
+ const cleared = Promise.all(shadowed.map((other) => this.unmirror(other))).finally(() => this.replacing.delete(binding));
7262
+ this.replacing.set(binding, cleared.then(() => void 0, () => void 0));
7263
+ await cleared;
7264
+ return await this.mirror(binding);
7265
+ }
7266
+ fiber = this.root.plugin(bindingProvider, {
7267
+ binding,
7268
+ scope: this
7269
+ });
7270
+ this.mirrors.set(binding, fiber);
7271
+ }
7272
+ try {
7273
+ await fiber.await();
7274
+ } catch (error) {
7275
+ throw new Error(`${describe(error)} when ${binding.owner.label} published it into ${this.label}`, { cause: error });
7276
+ }
7277
+ }
7278
+ async unmirror(binding) {
7279
+ const fiber = this.mirrors.get(binding);
7280
+ this.mirrors.delete(binding);
7281
+ if (!this.disposed) await fiber?.dispose();
7282
+ }
7283
+ };
7284
+ /** Every scope receives the event even when an earlier one's listener throws. */
7285
+ function deliver(scopes, name, args) {
7286
+ const errors = [];
7287
+ for (const scope of scopes) {
7288
+ if (scope.disposed) continue;
7289
+ try {
7290
+ scope.root.events.emit(name, ...args);
7291
+ } catch (error) {
7292
+ errors.push(error);
7293
+ }
7294
+ }
7295
+ if (errors.length > 0) throw new AggregateError(errors, `${errors.length} scope listener(s) of '${name}' failed.`);
7296
+ }
7297
+ //#endregion
7298
+ export { IsInteger as $, readPoIsolate as $n, IsObjectNotArray as $t, IsVoid as A, addressId as An, EntriesRegExp as At, IsString as B, seqFromNumber as Bn, IsEqual as Bt, Priority as C, ok as Cn, Get as Ct, Partial as D, LabelsDoc as Dn, IsTypeArray as Dt, With as E, IdentityHistoryDoc as En, IsSet as Et, RecordValue as F, documentCreate as Fn, IsBigInt$1 as Ft, Null as G, withTelemetry as Gn, IsLessEqualThan as Gt, IsNumber as H, BACKGROUND_CONTEXT as Hn, IsGreaterEqualThan as Ht, IsTuple as I, materializeDocument as In, IsBoolean$2 as It, IsLiteralBoolean as J, PO_FS_SERVICE as Jn, IsMinLength as Jt, IsLiteral as K, withoutAbortSignal as Kn, IsLessThan as Kt, Tuple as L, materializeDocumentValue as Ln, IsClassInstance as Lt, IsRecord as M, checkRecordVersion as Mn, EveryAll as Mt, Record as N, defineDoc as Nn, HasPropertyKey as Nt, Omit as O, SessionIdentityDoc as On, Counted as Ot, RecordPattern as P, defineDocFamily as Pn, IsArray$1 as Pt, Integer as Q, readPoFs as Qn, IsObject$1 as Qt, IsUnion as R, resolveAddress as Rn, IsConstructor$1 as Rt, PO_CONFIG_SERVICE as S, getOrThrow as Sn, Assign as St, Instantiate as T, FastModeDoc as Tn, IsRegExp as Tt, Number$1 as U, awaitWithContext as Un, IsGreaterThan as Ut, String$1 as V, copyJson as Vn, IsFunction$1 as Vt, IsNull as W, withAbortSignal as Wn, IsInteger$1 as Wt, IsLiteralString as X, PO_SQLITE_SERVICE as Xn, IsNull$1 as Xt, IsLiteralNumber as Y, PO_SHELL_SERVICE as Yn, IsMultipleOf as Yt, Literal as Z, readPoBrowser as Zn, IsNumber$2 as Zt, PO_SERVER_HOST_SERVICE as _, fileMutationRunner as _n, Ref as _t, PoHeadlessPromptAdmissionError as a, Keys$1 as an, defineServiceContract as ar, Unreachable as at, requirePoServerHost as b, FileError as bn, _Array_ as bt, dropInvalidImages as c, Symbols as cn, IsEnum as ct, isPoHeadlessToolBusyError as d, PO_SESSION_FILES_SERVICE as dn, Unknown as dt, IsString$2 as en, readPoNpm as er, Boolean$1 as et, isPoHeadlessToolModelVisible as f, PO_SESSION_TEMP_DIR as fn, IsObject as ft, guardedImport as g, createSerialRunner as gn, IsRef as gt, requirePoHeadlessHost as h, poHomeDirectory as hn, Optional as ht, PO_SEARCH_SKILLS_TOOL as i, IsValueLike as in, PO_SERVER_SCOPE_SERVICE as ir, Hash as it, IsUndefined as j, checkRecordScope as jn, Every as jt, IsTemplateLiteral as k, SessionMetadataDoc as kn, Entries as kt, invalidImageReason as l, guard_exports as ln, Unsafe as lt, readPoHeadlessOwner as m, piAgentDirectory as mn, IsOptional as mt, PO_HEADLESS_HOST_SERVICE as n, IsUndefined$1 as nn, requirePoSqlite as nr, IsBigInt as nt, PoHeadlessToolBusyError as o, Some as on, readPoServerScope as or, Intersect as ot, readPoHeadlessHost as p, prepareSessionEnvironment as pn, _Object_ as pt, IsLiteralBigInt as q, PO_BROWSER_SERVICE as qn, IsMaxLength as qt, PO_LOAD_SKILL_TOOL as r, IsUnsafePropertyKey as rn, PO_SERVER_SCOPE_LEVELS as rr, IsCodec as rt, PoSessionSetupError as s, SomeAll as sn, requirePoServerScope as sr, IsIntersect as st, PoServerScope as t, IsSymbol$1 as tn, requirePoFs as tr, IsBoolean as tt, isPoHeadlessPromptAdmissionError as u, HOST_SLOT_METADATA as un, IsCyclic as ut, composeServerProviderOverrides as v, nodeHost as vn, ArrayOptions as vt, Evaluate as w, AgentLockDoc as wn, IsMap as wt, Service as x, err as xn, IsSchema as xt, defineServerMethod as y, ExecutionError as yn, IsArray as yt, Union as z, idFromNumber as zn, IsDeepEqual as zt };