@computesdk/loops 0.0.0-stage → 0.1.0

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 (380) hide show
  1. package/API.md +106 -0
  2. package/README.md +221 -2
  3. package/bin/loops.mjs +188 -0
  4. package/bin/pi-loops-ui.mjs +4 -0
  5. package/client.ts +208 -0
  6. package/dist/assets/abap-BdImnpbu.js +1 -0
  7. package/dist/assets/abnfDiagram-VCTEODGH-DPUvPEpH.js +1 -0
  8. package/dist/assets/actionscript-3-B3316cI-.js +1 -0
  9. package/dist/assets/ada-BIOnG6TC.js +1 -0
  10. package/dist/assets/ahk-BrbAagtO.js +1 -0
  11. package/dist/assets/ahk2-8Zs4aa1G.js +1 -0
  12. package/dist/assets/andromeeda-C4gqWexZ.js +1 -0
  13. package/dist/assets/angular-html-D_SYSyRt.js +1 -0
  14. package/dist/assets/angular-ts-DGq0tZX5.js +1 -0
  15. package/dist/assets/apache-Pmp26Uib.js +1 -0
  16. package/dist/assets/apex-DhZFqWV2.js +1 -0
  17. package/dist/assets/apl-ChzvTHjC.js +1 -0
  18. package/dist/assets/applescript-Co6uUVPk.js +1 -0
  19. package/dist/assets/ara-BRHolxvo.js +1 -0
  20. package/dist/assets/arc-C71M1We_.js +1 -0
  21. package/dist/assets/architectureDiagram-5GKGNRK7-C3PLmrM3.js +36 -0
  22. package/dist/assets/asciidoc-CSVQ5wI8.js +1 -0
  23. package/dist/assets/asm-D_Q5rh1f.js +1 -0
  24. package/dist/assets/astro-DTjqU0_L.js +1 -0
  25. package/dist/assets/aurora-x-D-2ljcwZ.js +1 -0
  26. package/dist/assets/awk-DMzUqQB5.js +1 -0
  27. package/dist/assets/ayu-dark-DYE7WIF3.js +1 -0
  28. package/dist/assets/ayu-light-BA47KaF1.js +1 -0
  29. package/dist/assets/ayu-mirage-32ctXXKs.js +1 -0
  30. package/dist/assets/ballerina-BFfxhgS-.js +1 -0
  31. package/dist/assets/bat-CickPsom.js +1 -0
  32. package/dist/assets/beancount-BgSHGh8x.js +1 -0
  33. package/dist/assets/berry-uYugtg8r.js +1 -0
  34. package/dist/assets/bibtex-CHM0blh-.js +1 -0
  35. package/dist/assets/bicep-Bmn6On1c.js +1 -0
  36. package/dist/assets/bird2-Bx8U0n9b.js +1 -0
  37. package/dist/assets/blade-k33SngOZ.js +1 -0
  38. package/dist/assets/blockDiagram-I7D4REHJ-DFshwmKE.js +129 -0
  39. package/dist/assets/bsl-DlhNcFeZ.js +1 -0
  40. package/dist/assets/c-BIGW1oBm.js +1 -0
  41. package/dist/assets/c3-Dp5svz6Z.js +1 -0
  42. package/dist/assets/c4Diagram-7LVT6UL2-Dh29QjGI.js +38 -0
  43. package/dist/assets/cadence-Bv_4Rxtq.js +1 -0
  44. package/dist/assets/cairo-KRGpt6FW.js +1 -0
  45. package/dist/assets/catppuccin-frappe-CZL1YF0i.js +1 -0
  46. package/dist/assets/catppuccin-latte-DH-8KZSZ.js +1 -0
  47. package/dist/assets/catppuccin-macchiato-B7yYVSCf.js +1 -0
  48. package/dist/assets/catppuccin-mocha-Ct7hS0mc.js +1 -0
  49. package/dist/assets/channel-6AEG2wiQ.js +1 -0
  50. package/dist/assets/chapel-DTp_pixX.js +1 -0
  51. package/dist/assets/chunk-2Q5K7J3B-qZ7USlsH.js +1 -0
  52. package/dist/assets/chunk-5VM5RSS4-YQpRymiv.js +15 -0
  53. package/dist/assets/chunk-F27PBJKO-D2O95m9O.js +1 -0
  54. package/dist/assets/chunk-IMKFNOWR-CftSjfdl.js +231 -0
  55. package/dist/assets/chunk-JWPE2WC7-_1wtK-EO.js +1 -0
  56. package/dist/assets/chunk-POPQ4Y6H-DJ2Xmp8X.js +1 -0
  57. package/dist/assets/chunk-SVP7TREG-CAtSHcje.js +88 -0
  58. package/dist/assets/chunk-TICWLB2K-1BASqzB5.js +206 -0
  59. package/dist/assets/chunk-XXDRQBXY-CWs6lP_i.js +1 -0
  60. package/dist/assets/clarity-Dn5IMItf.js +1 -0
  61. package/dist/assets/classDiagram-ZZMXUADV-WtwW3JUM.js +1 -0
  62. package/dist/assets/classDiagram-v2-VYDZK3BY-WtwW3JUM.js +1 -0
  63. package/dist/assets/clojure-P80f7IUj.js +1 -0
  64. package/dist/assets/cmake-D1j8_8rp.js +1 -0
  65. package/dist/assets/cobol-BBKr1ja6.js +1 -0
  66. package/dist/assets/codeowners-Bp6g37R7.js +1 -0
  67. package/dist/assets/codeql-DsOJ9woJ.js +1 -0
  68. package/dist/assets/coffee-Ch7k5sss.js +1 -0
  69. package/dist/assets/common-lisp-Cg-RD9OK.js +1 -0
  70. package/dist/assets/coq-BqXF5kFF.js +1 -0
  71. package/dist/assets/cose-bilkent-JH36ORCC-9dCpEIjz.js +1 -0
  72. package/dist/assets/cpp-BMRokrvK.js +1 -0
  73. package/dist/assets/crystal-LUwhHfY5.js +1 -0
  74. package/dist/assets/csharp-B_TYUkTI.js +1 -0
  75. package/dist/assets/css-Z72CF80r.js +1 -0
  76. package/dist/assets/csv-fuZLfV_i.js +1 -0
  77. package/dist/assets/cue-D82EKSYY.js +1 -0
  78. package/dist/assets/cynefin-OW5HDTMX-EFt_R8HZ.js +166 -0
  79. package/dist/assets/cynefinDiagram-5FMLGOSQ-BuManjb1.js +62 -0
  80. package/dist/assets/cypher-COkxafJQ.js +1 -0
  81. package/dist/assets/cytoscape.esm-BDkkwuE4.js +321 -0
  82. package/dist/assets/d-85-TOEBH.js +1 -0
  83. package/dist/assets/dagre-GXQ25YYZ-MovLAGVL.js +4 -0
  84. package/dist/assets/dark-plus-C3mMm8J8.js +1 -0
  85. package/dist/assets/dart-CtKP3W-j.js +1 -0
  86. package/dist/assets/dax-CEL-wOlO.js +1 -0
  87. package/dist/assets/defaultLocale-DX6XiGOO.js +1 -0
  88. package/dist/assets/desktop-BmXAJ9_W.js +1 -0
  89. package/dist/assets/diagram-S7CK7UJ4-BiJw5LQ6.js +30 -0
  90. package/dist/assets/diagram-UQ7AKVKN-DRsX_xa6.js +41 -0
  91. package/dist/assets/diagram-VSXAHHWV-B7m6F8Dm.js +3 -0
  92. package/dist/assets/diagram-VX7I27RA-x4wioeVA.js +24 -0
  93. package/dist/assets/diagram-Z3DM3KII-0KYjyvJF.js +24 -0
  94. package/dist/assets/diff-D97Zzqfu.js +1 -0
  95. package/dist/assets/docker-BcOcwvcX.js +1 -0
  96. package/dist/assets/dotenv-De0Btta0.js +1 -0
  97. package/dist/assets/dracula-BzJJZx-M.js +1 -0
  98. package/dist/assets/dracula-soft-BXkSAIEj.js +1 -0
  99. package/dist/assets/dream-maker-BtqSS_iP.js +1 -0
  100. package/dist/assets/ebnfDiagram-PWID7BFC-BZXmt3oU.js +1 -0
  101. package/dist/assets/edge-CJaD-t2L.js +1 -0
  102. package/dist/assets/elixir-DkJLSxtU.js +1 -0
  103. package/dist/assets/elm-DbKCFpqz.js +1 -0
  104. package/dist/assets/emacs-lisp-DaIrSCgJ.js +1 -0
  105. package/dist/assets/erDiagram-RLTQ6QDP-CrfcYtD6.js +99 -0
  106. package/dist/assets/erb-CSMaCouu.js +1 -0
  107. package/dist/assets/erlang-DsQrWhSR.js +1 -0
  108. package/dist/assets/everforest-dark-BgDCqdQA.js +1 -0
  109. package/dist/assets/everforest-light-C8M2exoo.js +1 -0
  110. package/dist/assets/fennel-BYunw83y.js +1 -0
  111. package/dist/assets/fish-BvzEVeQv.js +1 -0
  112. package/dist/assets/flowDiagram-HODETNUW-BqudKoEy.js +168 -0
  113. package/dist/assets/fluent-C4IJs8-o.js +1 -0
  114. package/dist/assets/fortran-fixed-form-CkoXwp7k.js +1 -0
  115. package/dist/assets/fortran-free-form-BxgE0vQu.js +1 -0
  116. package/dist/assets/fsharp-CXgrBDvD.js +1 -0
  117. package/dist/assets/ganttDiagram-EL5Y4UJY-OBWjueb8.js +292 -0
  118. package/dist/assets/gdresource-TyuKm33G.js +1 -0
  119. package/dist/assets/gdscript-DqcFQ5yU.js +1 -0
  120. package/dist/assets/gdshader-DkwncUOv.js +1 -0
  121. package/dist/assets/genie-D0YGMca9.js +1 -0
  122. package/dist/assets/gherkin-DyxjwDmM.js +1 -0
  123. package/dist/assets/git-commit-F4YmCXRG.js +1 -0
  124. package/dist/assets/git-rebase-r7XF79zn.js +1 -0
  125. package/dist/assets/gitGraphDiagram-WWUBYQGX-B30e199R.js +106 -0
  126. package/dist/assets/github-dark-DHJKELXO.js +1 -0
  127. package/dist/assets/github-dark-default-Cuk6v7N8.js +1 -0
  128. package/dist/assets/github-dark-dimmed-DH5Ifo-i.js +1 -0
  129. package/dist/assets/github-dark-high-contrast-E3gJ1_iC.js +1 -0
  130. package/dist/assets/github-light-DAi9KRSo.js +1 -0
  131. package/dist/assets/github-light-default-D7oLnXFd.js +1 -0
  132. package/dist/assets/github-light-high-contrast-BfjtVDDH.js +1 -0
  133. package/dist/assets/gleam-BspZqrRM.js +1 -0
  134. package/dist/assets/glimmer-js-Drrc9bTt.js +1 -0
  135. package/dist/assets/glimmer-ts-zeybXsvi.js +1 -0
  136. package/dist/assets/glsl-DplSGwfg.js +1 -0
  137. package/dist/assets/gn-8iBmfbXw.js +1 -0
  138. package/dist/assets/gnuplot-DdkO51Og.js +1 -0
  139. package/dist/assets/go-C27-OAKa.js +1 -0
  140. package/dist/assets/graphql-ChdNCCLP.js +1 -0
  141. package/dist/assets/groovy-gcz8RCvz.js +1 -0
  142. package/dist/assets/gruvbox-dark-hard-CFHQjOhq.js +1 -0
  143. package/dist/assets/gruvbox-dark-medium-GsRaNv29.js +1 -0
  144. package/dist/assets/gruvbox-dark-soft-CVdnzihN.js +1 -0
  145. package/dist/assets/gruvbox-light-hard-CH1njM8p.js +1 -0
  146. package/dist/assets/gruvbox-light-medium-DRw_LuNl.js +1 -0
  147. package/dist/assets/gruvbox-light-soft-hJgmCMqR.js +1 -0
  148. package/dist/assets/hack-Ck6-gGSS.js +1 -0
  149. package/dist/assets/haml-GN_XdMnF.js +1 -0
  150. package/dist/assets/handlebars-DPT5vKgj.js +1 -0
  151. package/dist/assets/haskell-Df6bDoY_.js +1 -0
  152. package/dist/assets/haxe-CfZj7gIn.js +1 -0
  153. package/dist/assets/hcl-BWvSN4gD.js +1 -0
  154. package/dist/assets/highlighted-body-JLMTFACH-DapGkHdb.js +1 -0
  155. package/dist/assets/hjson-D5-asLiD.js +1 -0
  156. package/dist/assets/hlsl-D3lLCCz7.js +1 -0
  157. package/dist/assets/horizon-BUw7H-hv.js +1 -0
  158. package/dist/assets/horizon-bright-CUuTKBJd.js +1 -0
  159. package/dist/assets/houston-DnULxvSX.js +1 -0
  160. package/dist/assets/html-BlS82ilI.js +1 -0
  161. package/dist/assets/html-derivative-DZhk3IEZ.js +1 -0
  162. package/dist/assets/http-jrhK8wxY.js +1 -0
  163. package/dist/assets/hurl-irOxFIW8.js +1 -0
  164. package/dist/assets/hxml-2-FPmUDs.js +1 -0
  165. package/dist/assets/hy-DFXneXwc.js +1 -0
  166. package/dist/assets/imba-DGztddWO.js +1 -0
  167. package/dist/assets/index-C_bKTXmh.js +900 -0
  168. package/dist/assets/index-hKoeppfe.css +1 -0
  169. package/dist/assets/infoDiagram-27XIBGKW-DPwVvB4K.js +2 -0
  170. package/dist/assets/ini-BEwlwnbL.js +1 -0
  171. package/dist/assets/init-Gi6I4Gst.js +1 -0
  172. package/dist/assets/ishikawaDiagram-5VMMS53U-B0fvRdQL.js +70 -0
  173. package/dist/assets/java-CylS5w8V.js +1 -0
  174. package/dist/assets/javascript-wDzz0qaB.js +1 -0
  175. package/dist/assets/jinja-DFQZVq3b.js +1 -0
  176. package/dist/assets/jison-wvAkD_A8.js +1 -0
  177. package/dist/assets/journeyDiagram-3NMN7TZE-CZBLF7ld.js +139 -0
  178. package/dist/assets/json-Cp-IABpG.js +1 -0
  179. package/dist/assets/json5-C9tS-k6U.js +1 -0
  180. package/dist/assets/jsonc-Des-eS-w.js +1 -0
  181. package/dist/assets/jsonl-DcaNXYhu.js +1 -0
  182. package/dist/assets/jsonnet-DFQXde-d.js +1 -0
  183. package/dist/assets/jssm-C2t-YnRu.js +1 -0
  184. package/dist/assets/jsx-g9-lgVsj.js +1 -0
  185. package/dist/assets/julia-Cu79e8SL.js +1 -0
  186. package/dist/assets/just-CMxyWJJc.js +1 -0
  187. package/dist/assets/kanagawa-dragon-BuwD2xS4.js +1 -0
  188. package/dist/assets/kanagawa-lotus-C3DzagqV.js +1 -0
  189. package/dist/assets/kanagawa-wave-DFGoQZhC.js +1 -0
  190. package/dist/assets/kanban-definition-UXKFOSKX-wTBJWh9T.js +89 -0
  191. package/dist/assets/kdl-DV7GczEv.js +1 -0
  192. package/dist/assets/kotlin-BdnUsdx6.js +1 -0
  193. package/dist/assets/kusto-wEQ09or8.js +1 -0
  194. package/dist/assets/laserwave-DUszq2jm.js +1 -0
  195. package/dist/assets/latex-DJVikpzR.js +1 -0
  196. package/dist/assets/layout-DYBs-gVA.js +1 -0
  197. package/dist/assets/lean-BZvkOJ9d.js +1 -0
  198. package/dist/assets/less-B1dDrJ26.js +1 -0
  199. package/dist/assets/light-plus-B7mTdjB0.js +1 -0
  200. package/dist/assets/linear-DTE3zVP_.js +1 -0
  201. package/dist/assets/liquid-B-duXHXw.js +1 -0
  202. package/dist/assets/llvm-BZoOZj88.js +1 -0
  203. package/dist/assets/log-2UxHyX5q.js +1 -0
  204. package/dist/assets/logo-BtOb2qkB.js +1 -0
  205. package/dist/assets/lua-BaeVxFsk.js +1 -0
  206. package/dist/assets/luau-nOZpfvQi.js +1 -0
  207. package/dist/assets/make-CHLpvVh8.js +1 -0
  208. package/dist/assets/markdown-Cvjx9yec.js +1 -0
  209. package/dist/assets/marko-BYgDmDgU.js +1 -0
  210. package/dist/assets/material-theme-D5KoaKCx.js +1 -0
  211. package/dist/assets/material-theme-darker-BfHTSMKl.js +1 -0
  212. package/dist/assets/material-theme-lighter-B0m2ddpp.js +1 -0
  213. package/dist/assets/material-theme-ocean-CyktbL80.js +1 -0
  214. package/dist/assets/material-theme-palenight-Csfq5Kiy.js +1 -0
  215. package/dist/assets/matlab-D7o27uSR.js +1 -0
  216. package/dist/assets/mdc-DF4WjDMn.js +1 -0
  217. package/dist/assets/mdx-Cmh6b_Ma.js +1 -0
  218. package/dist/assets/mermaid-CQcHuHx7.js +1 -0
  219. package/dist/assets/min-dark-CafNBF8u.js +1 -0
  220. package/dist/assets/min-light-CTRr51gU.js +1 -0
  221. package/dist/assets/mindmap-definition-YA3MSWOX-tV3HPpzU.js +96 -0
  222. package/dist/assets/mipsasm-CKIfxQSi.js +1 -0
  223. package/dist/assets/mojo-DJz3ZmWd.js +1 -0
  224. package/dist/assets/monokai-CR4piiQ-.js +1 -0
  225. package/dist/assets/moonbit-Bag4Rp_g.js +1 -0
  226. package/dist/assets/move-el3G9tDJ.js +1 -0
  227. package/dist/assets/narrat-DRg8JJMk.js +1 -0
  228. package/dist/assets/nextflow-BCxp2Aob.js +1 -0
  229. package/dist/assets/nextflow-groovy-CedDknKX.js +1 -0
  230. package/dist/assets/nginx-BpAMiNFr.js +1 -0
  231. package/dist/assets/night-owl-C39BiMTA.js +1 -0
  232. package/dist/assets/night-owl-light-CMTm3GFP.js +1 -0
  233. package/dist/assets/nim-nV83PyhX.js +1 -0
  234. package/dist/assets/nix-CwoSXNpI.js +1 -0
  235. package/dist/assets/nord-Ddv68eIx.js +1 -0
  236. package/dist/assets/nsis-BlV79W_Q.js +1 -0
  237. package/dist/assets/nushell-BXD5iret.js +1 -0
  238. package/dist/assets/objective-c-DXmwc3jG.js +1 -0
  239. package/dist/assets/objective-cpp-CLxacb5B.js +1 -0
  240. package/dist/assets/ocaml-C0hk2d4L.js +1 -0
  241. package/dist/assets/odin-BBf5iR-q.js +1 -0
  242. package/dist/assets/one-dark-pro-CxGP3dtY.js +1 -0
  243. package/dist/assets/one-light-C3Wv6jpd.js +1 -0
  244. package/dist/assets/openscad-C4EeE6gA.js +1 -0
  245. package/dist/assets/ordinal-Cboi1Yqb.js +1 -0
  246. package/dist/assets/org-6a7ccXN_.js +1 -0
  247. package/dist/assets/pascal-D93ZcfNL.js +1 -0
  248. package/dist/assets/pegDiagram-XKGWAZYB-B6Yznbb5.js +1 -0
  249. package/dist/assets/perl-5klg-GXX.js +1 -0
  250. package/dist/assets/php-DoruYMF0.js +1 -0
  251. package/dist/assets/pieDiagram-E7YTZNPT-B6QW8pJH.js +39 -0
  252. package/dist/assets/pkl-u5AG7uiY.js +1 -0
  253. package/dist/assets/plastic-3e1v2bzS.js +1 -0
  254. package/dist/assets/plsql-ChMvpjG-.js +1 -0
  255. package/dist/assets/po-BTJTHyun.js +1 -0
  256. package/dist/assets/poimandres-CS3Unz2-.js +1 -0
  257. package/dist/assets/polar-C0HS_06l.js +1 -0
  258. package/dist/assets/postcss-CXtECtnM.js +1 -0
  259. package/dist/assets/powerquery-CEu0bR-o.js +1 -0
  260. package/dist/assets/powershell-Dd0kTxKP.js +1 -0
  261. package/dist/assets/prisma-Vru482bI.js +1 -0
  262. package/dist/assets/prolog-CbFg5uaA.js +1 -0
  263. package/dist/assets/proto-C7zT0LnQ.js +1 -0
  264. package/dist/assets/pug-BtYPkAgq.js +1 -0
  265. package/dist/assets/puppet-BMWR74SV.js +1 -0
  266. package/dist/assets/purescript-CklMAg4u.js +1 -0
  267. package/dist/assets/python-B6aJPvgy.js +1 -0
  268. package/dist/assets/qml-3beO22l8.js +1 -0
  269. package/dist/assets/qmldir-C8lEn-DE.js +1 -0
  270. package/dist/assets/qss-IeuSbFQv.js +1 -0
  271. package/dist/assets/quadrantDiagram-AXDQQJYC-DgHGTtj0.js +7 -0
  272. package/dist/assets/r-Cf5RLm7j.js +1 -0
  273. package/dist/assets/racket-BqYA7rlc.js +1 -0
  274. package/dist/assets/railroadDiagram-O6MQD6OU-CgqVFEBK.js +1 -0
  275. package/dist/assets/raku-DXvB9xmW.js +1 -0
  276. package/dist/assets/razor-CyjPwjZj.js +1 -0
  277. package/dist/assets/rbs-CpoqiR4B.js +1 -0
  278. package/dist/assets/red-DMbB5_pp.js +1 -0
  279. package/dist/assets/reg-C-SQnVFl.js +1 -0
  280. package/dist/assets/regexp-CDVJQ6XC.js +1 -0
  281. package/dist/assets/rel-C3B-1QV4.js +1 -0
  282. package/dist/assets/requirementDiagram-BXWQKSXE-FmXMY-6j.js +84 -0
  283. package/dist/assets/riscv-BM1_JUlF.js +1 -0
  284. package/dist/assets/ron-D8l8udqQ.js +1 -0
  285. package/dist/assets/rose-pine-5qJOZa0Y.js +1 -0
  286. package/dist/assets/rose-pine-dawn-zx0QlTCp.js +1 -0
  287. package/dist/assets/rose-pine-moon-C9pEdX9L.js +1 -0
  288. package/dist/assets/rosmsg-BJDFO7_C.js +1 -0
  289. package/dist/assets/rst-CVOjT0e7.js +1 -0
  290. package/dist/assets/ruby-C8rp0wew.js +1 -0
  291. package/dist/assets/rust-DPvrY3IQ.js +1 -0
  292. package/dist/assets/sankeyDiagram-P5KCCOFB-AVMEYVKy.js +40 -0
  293. package/dist/assets/sas-BGn39htG.js +1 -0
  294. package/dist/assets/sass-Cj5Yp3dK.js +1 -0
  295. package/dist/assets/scala-CqE71os6.js +1 -0
  296. package/dist/assets/scheme-C98Dy4si.js +1 -0
  297. package/dist/assets/scss-Cw6XMfVs.js +1 -0
  298. package/dist/assets/sdbl-DVxCFoDh.js +1 -0
  299. package/dist/assets/sequenceDiagram-WJ2MYXX4-uOObReYi.js +162 -0
  300. package/dist/assets/shaderlab-Dg9Lc6iA.js +1 -0
  301. package/dist/assets/shellscript-Yzrsuije.js +1 -0
  302. package/dist/assets/shellsession-BADoaaVG.js +1 -0
  303. package/dist/assets/sizeCapture-INFHLROL-BPOPqqxk.js +1 -0
  304. package/dist/assets/slack-dark-BthQWCQV.js +1 -0
  305. package/dist/assets/slack-ochin-DqwNpetd.js +1 -0
  306. package/dist/assets/smalltalk-BOQMe2GC.js +1 -0
  307. package/dist/assets/smithy-cds9vsN8.js +1 -0
  308. package/dist/assets/snazzy-light-Bw305WKR.js +1 -0
  309. package/dist/assets/solarized-dark-UcubFVte.js +1 -0
  310. package/dist/assets/solarized-light-DCG28T6R.js +1 -0
  311. package/dist/assets/solidity-DijEV5ha.js +1 -0
  312. package/dist/assets/soy-zscZBeg6.js +1 -0
  313. package/dist/assets/sparql-rVzFXLq3.js +1 -0
  314. package/dist/assets/splunk-BtCnVYZw.js +1 -0
  315. package/dist/assets/sql-DkvoVjww.js +1 -0
  316. package/dist/assets/ssh-config-_ykCGR6B.js +1 -0
  317. package/dist/assets/stata-DACIj5bg.js +1 -0
  318. package/dist/assets/stateDiagram-D77RDMKH-C1lXHNdu.js +1 -0
  319. package/dist/assets/stateDiagram-v2-MP3YSRHH-BHg8O_NZ.js +1 -0
  320. package/dist/assets/stylus-BEDo0Tqx.js +1 -0
  321. package/dist/assets/surrealql-Cjom0U5J.js +1 -0
  322. package/dist/assets/svelte-D84K1R2Q.js +1 -0
  323. package/dist/assets/swift-C2oV4EkX.js +1 -0
  324. package/dist/assets/swimlanes-42K2YHIH-C52GOi05.js +1 -0
  325. package/dist/assets/swimlanesDiagram-VR7AAH4N-DLB_mWZL.js +8 -0
  326. package/dist/assets/synthwave-84-CbfX1IO0.js +1 -0
  327. package/dist/assets/system-verilog-0hqHdDBg.js +1 -0
  328. package/dist/assets/systemd-4A_iFExJ.js +1 -0
  329. package/dist/assets/talonscript-CkByrt1z.js +1 -0
  330. package/dist/assets/tasl-QIJgUcNo.js +1 -0
  331. package/dist/assets/tcl-dwOrl1Do.js +1 -0
  332. package/dist/assets/templ-Vpw5XpSW.js +1 -0
  333. package/dist/assets/terraform-BETggiCN.js +1 -0
  334. package/dist/assets/tex-D96PA37w.js +1 -0
  335. package/dist/assets/timeline-definition-24CTP7MA-T0BhAPL-.js +120 -0
  336. package/dist/assets/tokyo-night-hegEt444.js +1 -0
  337. package/dist/assets/toml-vGWfd6FD.js +1 -0
  338. package/dist/assets/ts-tags-Ls60c9xG.js +1 -0
  339. package/dist/assets/tsv-B_m7g4N7.js +1 -0
  340. package/dist/assets/tsx-COt5Ahok.js +1 -0
  341. package/dist/assets/turtle-BsS91CYL.js +1 -0
  342. package/dist/assets/twig-D9-LOF2p.js +1 -0
  343. package/dist/assets/typescript-BPQ3VLAy.js +1 -0
  344. package/dist/assets/typespec-ClX509-Q.js +1 -0
  345. package/dist/assets/typst-DamkJZ1Q.js +1 -0
  346. package/dist/assets/v-BGw2Nkan.js +1 -0
  347. package/dist/assets/vala-CsfeWuGM.js +1 -0
  348. package/dist/assets/vb-Cu-pLBUe.js +1 -0
  349. package/dist/assets/vennDiagram-4TSXK5OY-DSGCn4iB.js +34 -0
  350. package/dist/assets/verilog-nZwndyjY.js +1 -0
  351. package/dist/assets/vesper-DRje8inN.js +1 -0
  352. package/dist/assets/vhdl-CeAyd5Ju.js +1 -0
  353. package/dist/assets/viml-CJc9bBzg.js +1 -0
  354. package/dist/assets/vitesse-black-Bkuqu6BP.js +1 -0
  355. package/dist/assets/vitesse-dark-D0r3Knsf.js +1 -0
  356. package/dist/assets/vitesse-light-CVO1_9PV.js +1 -0
  357. package/dist/assets/vue-DSqPwMUe.js +1 -0
  358. package/dist/assets/vue-html-AaS7Mt5G.js +1 -0
  359. package/dist/assets/vue-vine-C0RcJ6UU.js +1 -0
  360. package/dist/assets/vyper-CDx5xZoG.js +1 -0
  361. package/dist/assets/wardleyDiagram-VM6X3IG4-BaCYx_03.js +78 -0
  362. package/dist/assets/wasm-CG6Dc4jp.js +1 -0
  363. package/dist/assets/wasm-MzD3tlZU.js +1 -0
  364. package/dist/assets/wenyan-BV7otONQ.js +1 -0
  365. package/dist/assets/wgsl-Dx-B1_4e.js +1 -0
  366. package/dist/assets/wikitext-BhOHFoWU.js +1 -0
  367. package/dist/assets/wit-5i3qLPDT.js +1 -0
  368. package/dist/assets/wolfram-lXgVvXCa.js +1 -0
  369. package/dist/assets/xml-sdJ4AIDG.js +1 -0
  370. package/dist/assets/xsl-CtQFsRM5.js +1 -0
  371. package/dist/assets/xychartDiagram-S5SC5T6Z-CgPwXvFv.js +7 -0
  372. package/dist/assets/yaml-Buea-lGh.js +1 -0
  373. package/dist/assets/zenscript-DVFEvuxE.js +1 -0
  374. package/dist/assets/zig-VOosw3JB.js +1 -0
  375. package/dist/fonts/geist-mono.woff2 +0 -0
  376. package/dist/fonts/geist-sans.woff2 +0 -0
  377. package/dist/index.html +14 -0
  378. package/dist/server.mjs +4787 -0
  379. package/package.json +76 -4
  380. package/src/shared/types.ts +180 -0
@@ -0,0 +1,4787 @@
1
+ // server/index.ts
2
+ import fs7 from "node:fs";
3
+ import { randomBytes } from "node:crypto";
4
+ import http from "node:http";
5
+ import path7 from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { execFile, execFileSync as execFileSync2, spawn as spawn5 } from "node:child_process";
8
+
9
+ // ../../node_modules/.pnpm/hono@4.13.14/node_modules/hono/dist/request/constants.js
10
+ var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
11
+
12
+ // ../../node_modules/.pnpm/hono@4.13.14/node_modules/hono/dist/utils/buffer.js
13
+ var bufferToFormData = (arrayBuffer, contentType) => {
14
+ return new Response(arrayBuffer, { headers: { "Content-Type": contentType.replace(/^[^;]+/, (mediaType) => mediaType.toLowerCase()) } }).formData();
15
+ };
16
+
17
+ // ../../node_modules/.pnpm/hono@4.13.14/node_modules/hono/dist/utils/body.js
18
+ var MAX_NESTED_OBJECTS = 1e4;
19
+ var isRawRequest = (request) => "headers" in request;
20
+ var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
21
+ const { all = false, dot = false } = options;
22
+ const mediaType = (isRawRequest(request) ? request.headers : request.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();
23
+ if (mediaType === "multipart/form-data" || mediaType === "application/x-www-form-urlencoded") return parseFormData(request, {
24
+ all,
25
+ dot
26
+ });
27
+ return {};
28
+ };
29
+ async function parseFormData(request, options) {
30
+ if (!isRawRequest(request) && request.bodyCache.formData) return convertFormDataToBodyData(await request.bodyCache.formData, options);
31
+ const headers = isRawRequest(request) ? request.headers : request.raw.headers;
32
+ const arrayBuffer = await request.arrayBuffer();
33
+ const formDataPromise = bufferToFormData(arrayBuffer, headers.get("Content-Type") || "");
34
+ if (!isRawRequest(request)) request.bodyCache.formData = formDataPromise;
35
+ const formData = await formDataPromise;
36
+ if (formData) return convertFormDataToBodyData(formData, options);
37
+ return {};
38
+ }
39
+ function convertFormDataToBodyData(formData, options) {
40
+ const form = /* @__PURE__ */ Object.create(null);
41
+ const nestingState = { count: 0 };
42
+ formData.forEach((value, key) => {
43
+ if (!(options.all || key.endsWith("[]"))) form[key] = value;
44
+ else handleParsingAllValues(form, key, value);
45
+ });
46
+ if (options.dot) Object.entries(form).forEach(([key, value]) => {
47
+ if (key.includes(".")) {
48
+ handleParsingNestedValues(form, key, value, nestingState);
49
+ delete form[key];
50
+ }
51
+ });
52
+ return form;
53
+ }
54
+ var handleParsingAllValues = (form, key, value) => {
55
+ if (form[key] !== void 0) {
56
+ if (Array.isArray(form[key])) form[key].push(value);
57
+ else form[key] = [form[key], value];
58
+ } else if (!key.endsWith("[]")) form[key] = value;
59
+ else form[key] = [value];
60
+ };
61
+ var handleParsingNestedValues = (form, key, value, state) => {
62
+ if (/(?:^|\.)__proto__\./.test(key)) return;
63
+ let nestedForm = form;
64
+ const keys = key.split(".", 34);
65
+ if (keys.length > 33) throwNestingLimitExceeded();
66
+ keys.forEach((key2, index) => {
67
+ if (index === keys.length - 1) nestedForm[key2] = value;
68
+ else {
69
+ if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
70
+ if (state.count++ >= MAX_NESTED_OBJECTS) throwNestingLimitExceeded();
71
+ nestedForm[key2] = /* @__PURE__ */ Object.create(null);
72
+ }
73
+ nestedForm = nestedForm[key2];
74
+ }
75
+ });
76
+ };
77
+ var throwNestingLimitExceeded = () => {
78
+ throw new Error("Nesting limit exceeded");
79
+ };
80
+
81
+ // ../../node_modules/.pnpm/hono@4.13.14/node_modules/hono/dist/utils/url.js
82
+ var splitPath = (path8) => {
83
+ const paths = path8.split("/");
84
+ if (paths[0] === "") paths.shift();
85
+ return paths;
86
+ };
87
+ var splitRoutingPath = (routePath) => {
88
+ const { groups, path: path8 } = extractGroupsFromPath(routePath);
89
+ const paths = splitPath(path8);
90
+ return replaceGroupMarks(paths, groups);
91
+ };
92
+ var extractGroupsFromPath = (path8) => {
93
+ const groups = [];
94
+ path8 = path8.replace(/\{[^}]+\}/g, (match2, index) => {
95
+ const mark = `@${index}`;
96
+ groups.push([mark, match2]);
97
+ return mark;
98
+ });
99
+ return {
100
+ groups,
101
+ path: path8
102
+ };
103
+ };
104
+ var replaceGroupMarks = (paths, groups) => {
105
+ for (let i = groups.length - 1; i >= 0; i--) {
106
+ const [mark] = groups[i];
107
+ for (let j = paths.length - 1; j >= 0; j--) if (paths[j].includes(mark)) {
108
+ paths[j] = paths[j].replace(mark, groups[i][1]);
109
+ break;
110
+ }
111
+ }
112
+ return paths;
113
+ };
114
+ var patternCache = {};
115
+ var getPattern = (label, next) => {
116
+ if (label === "*") return "*";
117
+ const match2 = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
118
+ if (match2) {
119
+ const cacheKey2 = `${label}#${next}`;
120
+ if (!patternCache[cacheKey2]) {
121
+ if (match2[2]) patternCache[cacheKey2] = next && next[0] !== ":" && next[0] !== "*" ? [
122
+ cacheKey2,
123
+ match2[1],
124
+ new RegExp(`^${match2[2]}(?=/${next})`)
125
+ ] : [
126
+ label,
127
+ match2[1],
128
+ new RegExp(`^${match2[2]}$`)
129
+ ];
130
+ else patternCache[cacheKey2] = [
131
+ label,
132
+ match2[1],
133
+ true
134
+ ];
135
+ }
136
+ return patternCache[cacheKey2];
137
+ }
138
+ return null;
139
+ };
140
+ var tryDecode = (str, decoder) => {
141
+ try {
142
+ return decoder(str);
143
+ } catch {
144
+ return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match2) => {
145
+ try {
146
+ return decoder(match2);
147
+ } catch {
148
+ return match2;
149
+ }
150
+ });
151
+ }
152
+ };
153
+ var tryDecodeURI = (str) => tryDecode(str, decodeURI);
154
+ var getPath = (request) => {
155
+ const url = request.url;
156
+ const start = url.indexOf("/", url.indexOf(":") + 4);
157
+ let i = start;
158
+ for (; i < url.length; i++) {
159
+ const charCode = url.charCodeAt(i);
160
+ if (charCode === 37) {
161
+ const queryIndex = url.indexOf("?", i);
162
+ const hashIndex = url.indexOf("#", i);
163
+ const end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);
164
+ const path8 = url.slice(start, end);
165
+ return tryDecodeURI(path8.includes("%25") ? path8.replace(/%25/g, "%2525") : path8);
166
+ } else if (charCode === 63 || charCode === 35) break;
167
+ }
168
+ return url.slice(start, i);
169
+ };
170
+ var getPathNoStrict = (request) => {
171
+ const result = getPath(request);
172
+ return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
173
+ };
174
+ var mergePath = (base, sub, ...rest) => {
175
+ if (rest.length) sub = mergePath(sub, ...rest);
176
+ return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
177
+ };
178
+ var checkOptionalParameter = (path8) => {
179
+ if (path8.charCodeAt(path8.length - 1) !== 63 || !path8.includes(":")) return null;
180
+ const segments = path8.split("/");
181
+ const results = [];
182
+ let basePath = "";
183
+ segments.forEach((segment) => {
184
+ if (segment !== "" && !/\:/.test(segment)) basePath += "/" + segment;
185
+ else if (/\:/.test(segment)) {
186
+ if (segment.charCodeAt(segment.length - 1) === 63) {
187
+ if (results.length === 0 && basePath === "") results.push("/");
188
+ else results.push(basePath);
189
+ const optionalSegment = segment.slice(0, -1);
190
+ basePath += "/" + optionalSegment;
191
+ results.push(basePath);
192
+ } else basePath += "/" + segment;
193
+ }
194
+ });
195
+ return results.filter((v, i, a) => a.indexOf(v) === i);
196
+ };
197
+ var tryDecodeURIComponent = (str) => str.indexOf("%") !== -1 ? tryDecode(str, decodeURIComponent_) : str;
198
+ var _decodeURI = (value) => {
199
+ if (value.indexOf("+") !== -1) value = value.replace(/\+/g, " ");
200
+ return tryDecodeURIComponent(value);
201
+ };
202
+ var _getQueryParam = (url, key, multiple) => {
203
+ const hashIndex = url.indexOf("#", 8);
204
+ if (hashIndex !== -1) url = url.slice(0, hashIndex);
205
+ let encoded;
206
+ if (!multiple && key && key.indexOf("%") === -1 && key.indexOf("+") === -1) {
207
+ const queryIndex = url.indexOf("?", 8);
208
+ let keyIndex2 = queryIndex;
209
+ if (keyIndex2 === -1) return;
210
+ if (!url.startsWith(key, keyIndex2 + 1)) keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
211
+ while (keyIndex2 !== -1) {
212
+ const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
213
+ if (trailingKeyCode === 61 || trailingKeyCode === 38 || isNaN(trailingKeyCode)) {
214
+ if (keyIndex2 > queryIndex && /(?:^|&)[^=&]*[%+]/.test(url.slice(queryIndex + 1, keyIndex2))) break;
215
+ if (trailingKeyCode === 61) {
216
+ const valueIndex = keyIndex2 + key.length + 2;
217
+ const endIndex = url.indexOf("&", valueIndex);
218
+ return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));
219
+ }
220
+ return "";
221
+ }
222
+ keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
223
+ }
224
+ encoded = /[%+]/.test(url);
225
+ if (!encoded) return;
226
+ }
227
+ const results = /* @__PURE__ */ Object.create(null);
228
+ encoded ??= /[%+]/.test(url);
229
+ let keyIndex = url.indexOf("?", 8);
230
+ while (keyIndex !== -1) {
231
+ const nextKeyIndex = url.indexOf("&", keyIndex + 1);
232
+ let valueIndex = url.indexOf("=", keyIndex);
233
+ if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) valueIndex = -1;
234
+ let name = url.slice(keyIndex + 1, valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex);
235
+ if (encoded) name = _decodeURI(name);
236
+ keyIndex = nextKeyIndex;
237
+ if (name === "") continue;
238
+ let value;
239
+ if (valueIndex === -1) value = "";
240
+ else {
241
+ value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);
242
+ if (encoded) value = _decodeURI(value);
243
+ }
244
+ if (multiple) {
245
+ if (!(results[name] && Array.isArray(results[name]))) results[name] = [];
246
+ results[name].push(value);
247
+ } else results[name] ??= value;
248
+ }
249
+ return key ? results[key] : results;
250
+ };
251
+ var getQueryParam = _getQueryParam;
252
+ var getQueryParams = (url, key) => {
253
+ return _getQueryParam(url, key, true);
254
+ };
255
+ var decodeURIComponent_ = decodeURIComponent;
256
+
257
+ // ../../node_modules/.pnpm/hono@4.13.14/node_modules/hono/dist/request.js
258
+ var HonoRequest = class {
259
+ /**
260
+ * `.raw` can get the raw Request object.
261
+ *
262
+ * @see {@link https://hono.dev/docs/api/request#raw}
263
+ *
264
+ * @example
265
+ * ```ts
266
+ * // For Cloudflare Workers
267
+ * app.post('/', async (c) => {
268
+ * const metadata = c.req.raw.cf?.hostMetadata?
269
+ * ...
270
+ * })
271
+ * ```
272
+ */
273
+ raw;
274
+ #validatedData;
275
+ #matchResult;
276
+ routeIndex = 0;
277
+ /**
278
+ * `.path` can get the pathname of the request.
279
+ *
280
+ * @see {@link https://hono.dev/docs/api/request#path}
281
+ *
282
+ * @example
283
+ * ```ts
284
+ * app.get('/about/me', (c) => {
285
+ * const pathname = c.req.path // `/about/me`
286
+ * })
287
+ * ```
288
+ */
289
+ path;
290
+ bodyCache = {};
291
+ constructor(request, path8 = "/", matchResult = [[]]) {
292
+ this.raw = request;
293
+ this.path = path8;
294
+ this.#matchResult = matchResult;
295
+ }
296
+ param(key) {
297
+ return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
298
+ }
299
+ #getDecodedParam(key) {
300
+ const paramKey = this.#matchResult[0][this.routeIndex]?.[1][key];
301
+ const param = this.#getParamValue(paramKey);
302
+ return param && tryDecodeURIComponent(param);
303
+ }
304
+ #getAllDecodedParams() {
305
+ const decoded = {};
306
+ const keys = Object.keys(this.#matchResult[0][this.routeIndex]?.[1] ?? {});
307
+ for (const key of keys) {
308
+ const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
309
+ if (value !== void 0) decoded[key] = tryDecodeURIComponent(value);
310
+ }
311
+ return decoded;
312
+ }
313
+ #getParamValue(paramKey) {
314
+ return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
315
+ }
316
+ query(key) {
317
+ return getQueryParam(this.url, key);
318
+ }
319
+ queries(key) {
320
+ return getQueryParams(this.url, key);
321
+ }
322
+ header(name) {
323
+ if (name) return this.raw.headers.get(name) ?? void 0;
324
+ const headerData = /* @__PURE__ */ Object.create(null);
325
+ this.raw.headers.forEach((value, key) => {
326
+ headerData[key] = value;
327
+ });
328
+ return headerData;
329
+ }
330
+ async parseBody(options) {
331
+ return parseBody(this, options);
332
+ }
333
+ #cachedBody = (key) => {
334
+ const { bodyCache, raw: raw2 } = this;
335
+ const cachedBody = bodyCache[key];
336
+ if (cachedBody) return cachedBody;
337
+ for (const anyCachedKey in bodyCache) return bodyCache[anyCachedKey].then((body) => {
338
+ if (anyCachedKey === "json") body = JSON.stringify(body);
339
+ const contentType = anyCachedKey === "formData" ? void 0 : raw2.headers.get("content-type");
340
+ return new Response(body, { headers: contentType ? { "Content-Type": contentType } : void 0 })[key]();
341
+ });
342
+ return bodyCache[key] = raw2[key]();
343
+ };
344
+ /**
345
+ * `.json()` can parse Request body of type `application/json`
346
+ *
347
+ * @see {@link https://hono.dev/docs/api/request#json}
348
+ *
349
+ * @example
350
+ * ```ts
351
+ * app.post('/entry', async (c) => {
352
+ * const body = await c.req.json()
353
+ * })
354
+ * ```
355
+ */
356
+ json() {
357
+ return this.#cachedBody("text").then((text) => JSON.parse(text));
358
+ }
359
+ /**
360
+ * `.text()` can parse Request body of type `text/plain`
361
+ *
362
+ * @see {@link https://hono.dev/docs/api/request#text}
363
+ *
364
+ * @example
365
+ * ```ts
366
+ * app.post('/entry', async (c) => {
367
+ * const body = await c.req.text()
368
+ * })
369
+ * ```
370
+ */
371
+ text() {
372
+ return this.#cachedBody("text");
373
+ }
374
+ /**
375
+ * `.arrayBuffer()` parse Request body as an `ArrayBuffer`
376
+ *
377
+ * @see {@link https://hono.dev/docs/api/request#arraybuffer}
378
+ *
379
+ * @example
380
+ * ```ts
381
+ * app.post('/entry', async (c) => {
382
+ * const body = await c.req.arrayBuffer()
383
+ * })
384
+ * ```
385
+ */
386
+ arrayBuffer() {
387
+ return this.#cachedBody("arrayBuffer");
388
+ }
389
+ /**
390
+ * `.bytes()` parses the request body as a `Uint8Array`.
391
+ *
392
+ * @see {@link https://hono.dev/docs/api/request#bytes}
393
+ *
394
+ * @example
395
+ * ```ts
396
+ * app.post('/entry', async (c) => {
397
+ * const body = await c.req.bytes()
398
+ * })
399
+ * ```
400
+ */
401
+ bytes() {
402
+ return this.#cachedBody("arrayBuffer").then((buffer) => new Uint8Array(buffer));
403
+ }
404
+ /**
405
+ * Parses the request body as a `Blob`.
406
+ * @example
407
+ * ```ts
408
+ * app.post('/entry', async (c) => {
409
+ * const body = await c.req.blob();
410
+ * });
411
+ * ```
412
+ * @see https://hono.dev/docs/api/request#blob
413
+ */
414
+ blob() {
415
+ return this.#cachedBody("blob");
416
+ }
417
+ /**
418
+ * Parses the request body as `FormData`.
419
+ * @example
420
+ * ```ts
421
+ * app.post('/entry', async (c) => {
422
+ * const body = await c.req.formData();
423
+ * });
424
+ * ```
425
+ * @see https://hono.dev/docs/api/request#formdata
426
+ */
427
+ formData() {
428
+ return this.#cachedBody("formData");
429
+ }
430
+ /**
431
+ * Adds validated data to the request.
432
+ *
433
+ * @param target - The target of the validation.
434
+ * @param data - The validated data to add.
435
+ */
436
+ addValidatedData(target, data) {
437
+ (this.#validatedData ??= {})[target] = data;
438
+ }
439
+ valid(target) {
440
+ return this.#validatedData?.[target];
441
+ }
442
+ /**
443
+ * `.url` can get the request url strings.
444
+ *
445
+ * @see {@link https://hono.dev/docs/api/request#url}
446
+ *
447
+ * @example
448
+ * ```ts
449
+ * app.get('/about/me', (c) => {
450
+ * const url = c.req.url // `http://localhost:8787/about/me`
451
+ * ...
452
+ * })
453
+ * ```
454
+ */
455
+ get url() {
456
+ return this.raw.url;
457
+ }
458
+ /**
459
+ * `.method` can get the method name of the request.
460
+ *
461
+ * @see {@link https://hono.dev/docs/api/request#method}
462
+ *
463
+ * @example
464
+ * ```ts
465
+ * app.get('/about/me', (c) => {
466
+ * const method = c.req.method // `GET`
467
+ * })
468
+ * ```
469
+ */
470
+ get method() {
471
+ return this.raw.method;
472
+ }
473
+ get [GET_MATCH_RESULT]() {
474
+ return this.#matchResult;
475
+ }
476
+ /**
477
+ * `.matchedRoutes` can return a matched route in the handler
478
+ *
479
+ * @deprecated
480
+ *
481
+ * Use matchedRoutes helper defined in "hono/route" instead.
482
+ *
483
+ * @see {@link https://hono.dev/docs/api/request#matchedroutes}
484
+ *
485
+ * @example
486
+ * ```ts
487
+ * app.use('*', async function logger(c, next) {
488
+ * await next()
489
+ * c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {
490
+ * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')
491
+ * console.log(
492
+ * method,
493
+ * ' ',
494
+ * path,
495
+ * ' '.repeat(Math.max(10 - path.length, 0)),
496
+ * name,
497
+ * i === c.req.routeIndex ? '<- respond from here' : ''
498
+ * )
499
+ * })
500
+ * })
501
+ * ```
502
+ */
503
+ get matchedRoutes() {
504
+ return this.#matchResult[0].map(([[, route]]) => route);
505
+ }
506
+ /**
507
+ * `.routePath` can retrieve the path registered within the handler
508
+ *
509
+ * @deprecated
510
+ *
511
+ * Use routePath helper defined in "hono/route" instead.
512
+ *
513
+ * @see {@link https://hono.dev/docs/api/request#routepath}
514
+ *
515
+ * @example
516
+ * ```ts
517
+ * app.get('/posts/:id', (c) => {
518
+ * return c.json({ path: c.req.routePath })
519
+ * })
520
+ * ```
521
+ */
522
+ get routePath() {
523
+ return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
524
+ }
525
+ };
526
+
527
+ // ../../node_modules/.pnpm/hono@4.13.14/node_modules/hono/dist/utils/html.js
528
+ var HtmlEscapedCallbackPhase = {
529
+ Stringify: 1,
530
+ BeforeStream: 2,
531
+ Stream: 3
532
+ };
533
+ var raw = (value, callbacks) => {
534
+ const escapedString = new String(value);
535
+ escapedString.isEscaped = true;
536
+ escapedString.callbacks = callbacks;
537
+ return escapedString;
538
+ };
539
+ var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
540
+ if (typeof str === "object" && !(str instanceof String)) {
541
+ if (!(str instanceof Promise)) str = str.toString();
542
+ if (str instanceof Promise) str = await str;
543
+ }
544
+ const callbacks = str.callbacks;
545
+ if (!callbacks?.length) return Promise.resolve(str);
546
+ if (buffer) buffer[0] += str;
547
+ else buffer = [str];
548
+ const resStr = Promise.all(callbacks.map((c) => c({
549
+ phase,
550
+ buffer,
551
+ context
552
+ }))).then((res) => Promise.all(res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))).then(() => buffer[0]));
553
+ if (preserveCallbacks) return raw(await resStr, callbacks);
554
+ else return resStr;
555
+ };
556
+
557
+ // ../../node_modules/.pnpm/hono@4.13.14/node_modules/hono/dist/context.js
558
+ var TEXT_PLAIN = "text/plain; charset=UTF-8";
559
+ var setDefaultContentType = (contentType, headers) => {
560
+ return {
561
+ "Content-Type": contentType,
562
+ ...headers
563
+ };
564
+ };
565
+ var createResponseInstance = (body, init) => new Response(body, init);
566
+ var Context = class {
567
+ #rawRequest;
568
+ #req;
569
+ /**
570
+ * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.
571
+ *
572
+ * @see {@link https://hono.dev/docs/api/context#env}
573
+ *
574
+ * @example
575
+ * ```ts
576
+ * // Environment object for Cloudflare Workers
577
+ * app.get('*', async c => {
578
+ * const counter = c.env.COUNTER
579
+ * })
580
+ * ```
581
+ */
582
+ env = {};
583
+ #var;
584
+ finalized = false;
585
+ /**
586
+ * `.error` can get the error object from the middleware if the Handler throws an error.
587
+ *
588
+ * @see {@link https://hono.dev/docs/api/context#error}
589
+ *
590
+ * @example
591
+ * ```ts
592
+ * app.use('*', async (c, next) => {
593
+ * await next()
594
+ * if (c.error) {
595
+ * // do something...
596
+ * }
597
+ * })
598
+ * ```
599
+ */
600
+ error;
601
+ #status;
602
+ #executionCtx;
603
+ #res;
604
+ #layout;
605
+ #renderer;
606
+ #notFoundHandler;
607
+ #preparedHeaders;
608
+ #matchResult;
609
+ #path;
610
+ /**
611
+ * Creates an instance of the Context class.
612
+ *
613
+ * @param req - The Request object.
614
+ * @param options - Optional configuration options for the context.
615
+ */
616
+ constructor(req, options) {
617
+ this.#rawRequest = req;
618
+ if (options) {
619
+ this.#executionCtx = options.executionCtx;
620
+ this.env = options.env;
621
+ this.#notFoundHandler = options.notFoundHandler;
622
+ this.#path = options.path;
623
+ this.#matchResult = options.matchResult;
624
+ }
625
+ }
626
+ /**
627
+ * `.req` is the instance of {@link HonoRequest}.
628
+ */
629
+ get req() {
630
+ this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
631
+ return this.#req;
632
+ }
633
+ /**
634
+ * @see {@link https://hono.dev/docs/api/context#event}
635
+ * The FetchEvent associated with the current request.
636
+ *
637
+ * @throws Will throw an error if the context does not have a FetchEvent.
638
+ */
639
+ get event() {
640
+ if (this.#executionCtx && "respondWith" in this.#executionCtx) return this.#executionCtx;
641
+ else throw Error("This context has no FetchEvent");
642
+ }
643
+ /**
644
+ * @see {@link https://hono.dev/docs/api/context#executionctx}
645
+ * The ExecutionContext associated with the current request.
646
+ *
647
+ * @throws Will throw an error if the context does not have an ExecutionContext.
648
+ */
649
+ get executionCtx() {
650
+ if (this.#executionCtx) return this.#executionCtx;
651
+ else throw Error("This context has no ExecutionContext");
652
+ }
653
+ /**
654
+ * @see {@link https://hono.dev/docs/api/context#res}
655
+ * The Response object for the current request.
656
+ */
657
+ get res() {
658
+ return this.#res ||= createResponseInstance(null, { headers: this.#preparedHeaders ??= new Headers() });
659
+ }
660
+ /**
661
+ * Sets the Response object for the current request.
662
+ *
663
+ * @param _res - The Response object to set.
664
+ */
665
+ set res(_res) {
666
+ if (this.#res && _res) {
667
+ _res = createResponseInstance(_res.body, _res);
668
+ for (const [k, v] of this.#res.headers.entries()) {
669
+ if (k === "content-type") continue;
670
+ if (k === "set-cookie") {
671
+ const cookies = this.#res.headers.getSetCookie();
672
+ _res.headers.delete("set-cookie");
673
+ for (const cookie of cookies) _res.headers.append("set-cookie", cookie);
674
+ } else _res.headers.set(k, v);
675
+ }
676
+ }
677
+ this.#res = _res;
678
+ this.finalized = true;
679
+ }
680
+ /**
681
+ * `.render()` can create a response within a layout.
682
+ *
683
+ * @see {@link https://hono.dev/docs/api/context#render-setrenderer}
684
+ *
685
+ * @example
686
+ * ```ts
687
+ * app.get('/', (c) => {
688
+ * return c.render('Hello!')
689
+ * })
690
+ * ```
691
+ */
692
+ render = (...args) => {
693
+ this.#renderer ??= (content) => this.html(content);
694
+ return this.#renderer(...args);
695
+ };
696
+ /**
697
+ * Sets the layout for the response.
698
+ *
699
+ * @param layout - The layout to set.
700
+ * @returns The layout function.
701
+ */
702
+ setLayout = (layout) => this.#layout = layout;
703
+ /**
704
+ * Gets the current layout for the response.
705
+ *
706
+ * @returns The current layout function.
707
+ */
708
+ getLayout = () => this.#layout;
709
+ /**
710
+ * `.setRenderer()` can set the layout in the custom middleware.
711
+ *
712
+ * @see {@link https://hono.dev/docs/api/context#render-setrenderer}
713
+ *
714
+ * @example
715
+ * ```tsx
716
+ * app.use('*', async (c, next) => {
717
+ * c.setRenderer((content) => {
718
+ * return c.html(
719
+ * <html>
720
+ * <body>
721
+ * <p>{content}</p>
722
+ * </body>
723
+ * </html>
724
+ * )
725
+ * })
726
+ * await next()
727
+ * })
728
+ * ```
729
+ */
730
+ setRenderer = (renderer) => {
731
+ this.#renderer = renderer;
732
+ };
733
+ /**
734
+ * `.header()` can set headers.
735
+ *
736
+ * @see {@link https://hono.dev/docs/api/context#header}
737
+ *
738
+ * @example
739
+ * ```ts
740
+ * app.get('/welcome', (c) => {
741
+ * // Set headers
742
+ * c.header('X-Message', 'Hello!')
743
+ * c.header('Content-Type', 'text/plain')
744
+ *
745
+ * // Append multiple headers using the append option (e.g. Vary)
746
+ * c.header('Vary', 'Accept-Encoding', { append: true })
747
+ * c.header('Vary', 'User-Agent', { append: true })
748
+ *
749
+ * return c.body('Thank you for coming')
750
+ * })
751
+ * ```
752
+ */
753
+ header = (name, value, options) => {
754
+ if (this.finalized) this.#res = createResponseInstance(this.#res.body, this.#res);
755
+ const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();
756
+ if (value === void 0) headers.delete(name);
757
+ else if (options?.append) headers.append(name, value);
758
+ else headers.set(name, value);
759
+ };
760
+ status = (status) => {
761
+ this.#status = status;
762
+ };
763
+ /**
764
+ * `.set()` can set the value specified by the key.
765
+ *
766
+ * @see {@link https://hono.dev/docs/api/context#set-get}
767
+ *
768
+ * @example
769
+ * ```ts
770
+ * app.use('*', async (c, next) => {
771
+ * c.set('message', 'Hono is hot!!')
772
+ * await next()
773
+ * })
774
+ * ```
775
+ */
776
+ set = (key, value) => {
777
+ this.#var ??= /* @__PURE__ */ new Map();
778
+ this.#var.set(key, value);
779
+ };
780
+ /**
781
+ * `.get()` can use the value specified by the key.
782
+ *
783
+ * @see {@link https://hono.dev/docs/api/context#set-get}
784
+ *
785
+ * @example
786
+ * ```ts
787
+ * app.get('/', (c) => {
788
+ * const message = c.get('message')
789
+ * return c.text(`The message is "${message}"`)
790
+ * })
791
+ * ```
792
+ */
793
+ get = (key) => {
794
+ return this.#var ? this.#var.get(key) : void 0;
795
+ };
796
+ /**
797
+ * `.var` can access the value of a variable.
798
+ *
799
+ * @see {@link https://hono.dev/docs/api/context#var}
800
+ *
801
+ * @example
802
+ * ```ts
803
+ * const result = c.var.client.oneMethod()
804
+ * ```
805
+ */
806
+ get var() {
807
+ if (!this.#var) return {};
808
+ return Object.fromEntries(this.#var);
809
+ }
810
+ #newResponse(data, arg2, headers) {
811
+ let responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders;
812
+ if (typeof arg2 === "object" && arg2.headers) {
813
+ responseHeaders ??= new Headers();
814
+ for (const [key, value] of new Headers(arg2.headers)) if (key === "set-cookie") responseHeaders.append(key, value);
815
+ else responseHeaders.set(key, value);
816
+ }
817
+ if (headers) {
818
+ if (!responseHeaders) {
819
+ let count = 0;
820
+ for (const k in headers) if (++count > 1 || typeof headers[k] !== "string") {
821
+ responseHeaders = new Headers();
822
+ break;
823
+ }
824
+ }
825
+ if (responseHeaders) for (const k in headers) {
826
+ const v = headers[k];
827
+ if (typeof v === "string") responseHeaders.set(k, v);
828
+ else {
829
+ responseHeaders.delete(k);
830
+ for (const v2 of v) responseHeaders.append(k, v2);
831
+ }
832
+ }
833
+ }
834
+ const status = typeof arg2 === "number" ? arg2 : arg2?.status ?? this.#status;
835
+ return createResponseInstance(data, {
836
+ status,
837
+ headers: responseHeaders ?? headers
838
+ });
839
+ }
840
+ newResponse = (...args) => this.#newResponse(...args);
841
+ /**
842
+ * `.body()` can return the HTTP response.
843
+ * You can set headers with `.header()` and set HTTP status code with `.status`.
844
+ * This can also be set in `.text()`, `.json()` and so on.
845
+ *
846
+ * @see {@link https://hono.dev/docs/api/context#body}
847
+ *
848
+ * @example
849
+ * ```ts
850
+ * app.get('/welcome', (c) => {
851
+ * // Set headers
852
+ * c.header('X-Message', 'Hello!')
853
+ * c.header('Content-Type', 'text/plain')
854
+ * // Set HTTP status code
855
+ * c.status(201)
856
+ *
857
+ * // Return the response body
858
+ * return c.body('Thank you for coming')
859
+ * })
860
+ * ```
861
+ */
862
+ body = (data, arg2, headers) => this.#newResponse(data, arg2, headers);
863
+ /**
864
+ * `.text()` can render text as `Content-Type:text/plain`.
865
+ *
866
+ * @see {@link https://hono.dev/docs/api/context#text}
867
+ *
868
+ * @example
869
+ * ```ts
870
+ * app.get('/say', (c) => {
871
+ * return c.text('Hello!')
872
+ * })
873
+ * ```
874
+ */
875
+ text = (text, arg2, headers) => {
876
+ return !this.#preparedHeaders && !this.#status && !arg2 && !headers && !this.finalized ? new Response(text) : this.#newResponse(text, arg2, setDefaultContentType(TEXT_PLAIN, headers));
877
+ };
878
+ /**
879
+ * `.json()` can render JSON as `Content-Type:application/json`.
880
+ *
881
+ * @see {@link https://hono.dev/docs/api/context#json}
882
+ *
883
+ * @example
884
+ * ```ts
885
+ * app.get('/api', (c) => {
886
+ * return c.json({ message: 'Hello!' })
887
+ * })
888
+ * ```
889
+ */
890
+ json = (object, arg2, headers) => {
891
+ return this.#newResponse(JSON.stringify(object), arg2, setDefaultContentType("application/json", headers));
892
+ };
893
+ html = (html, arg2, headers) => {
894
+ const res = (html2) => this.#newResponse(html2, arg2, setDefaultContentType("text/html; charset=UTF-8", headers));
895
+ return typeof html === "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);
896
+ };
897
+ /**
898
+ * `.redirect()` can Redirect, default status code is 302.
899
+ *
900
+ * @see {@link https://hono.dev/docs/api/context#redirect}
901
+ *
902
+ * @example
903
+ * ```ts
904
+ * app.get('/redirect', (c) => {
905
+ * return c.redirect('/')
906
+ * })
907
+ * app.get('/redirect-permanently', (c) => {
908
+ * return c.redirect('/', 301)
909
+ * })
910
+ * ```
911
+ */
912
+ redirect = (location, status) => {
913
+ const locationString = String(location);
914
+ this.header("Location", !/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString));
915
+ return this.newResponse(null, status ?? 302);
916
+ };
917
+ /**
918
+ * `.notFound()` can return the Not Found Response.
919
+ *
920
+ * @see {@link https://hono.dev/docs/api/context#notfound}
921
+ *
922
+ * @example
923
+ * ```ts
924
+ * app.get('/notfound', (c) => {
925
+ * return c.notFound()
926
+ * })
927
+ * ```
928
+ */
929
+ notFound = () => {
930
+ this.#notFoundHandler ??= () => createResponseInstance();
931
+ return this.#notFoundHandler(this);
932
+ };
933
+ };
934
+
935
+ // ../../node_modules/.pnpm/hono@4.13.14/node_modules/hono/dist/compose.js
936
+ var compose = (middleware, onError, onNotFound) => {
937
+ return (context, next) => {
938
+ let index = -1;
939
+ return dispatch(0);
940
+ async function dispatch(i) {
941
+ if (i <= index) throw new Error("next() called multiple times");
942
+ index = i;
943
+ let res;
944
+ let isError = false;
945
+ let handler;
946
+ if (middleware[i]) {
947
+ handler = middleware[i][0][0];
948
+ context.req.routeIndex = i;
949
+ } else handler = i === middleware.length && next || void 0;
950
+ if (handler) try {
951
+ res = await handler(context, () => dispatch(i + 1));
952
+ } catch (err) {
953
+ if (err instanceof Error && onError) {
954
+ context.error = err;
955
+ res = await onError(err, context);
956
+ isError = true;
957
+ } else throw err;
958
+ }
959
+ else if (context.finalized === false && onNotFound) res = await onNotFound(context);
960
+ if (res && (context.finalized === false || isError)) context.res = res;
961
+ return context;
962
+ }
963
+ };
964
+ };
965
+
966
+ // ../../node_modules/.pnpm/hono@4.13.14/node_modules/hono/dist/router.js
967
+ var METHODS = [
968
+ "get",
969
+ "post",
970
+ "put",
971
+ "delete",
972
+ "options",
973
+ "patch",
974
+ "query"
975
+ ];
976
+ var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
977
+ var UnsupportedPathError = class extends Error {
978
+ };
979
+
980
+ // ../../node_modules/.pnpm/hono@4.13.14/node_modules/hono/dist/utils/constants.js
981
+ var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
982
+
983
+ // ../../node_modules/.pnpm/hono@4.13.14/node_modules/hono/dist/hono-base.js
984
+ var notFoundHandler = (c) => {
985
+ return c.text("404 Not Found", 404);
986
+ };
987
+ var errorHandler = (err, c) => {
988
+ if ("getResponse" in err) {
989
+ const res = err.getResponse();
990
+ return c.newResponse(res.body, res);
991
+ }
992
+ console.error(err);
993
+ return c.text("Internal Server Error", 500);
994
+ };
995
+ var Hono = class Hono2 {
996
+ get;
997
+ post;
998
+ put;
999
+ delete;
1000
+ options;
1001
+ patch;
1002
+ query;
1003
+ all;
1004
+ on;
1005
+ use;
1006
+ router;
1007
+ getPath;
1008
+ _basePath = "/";
1009
+ #path = "/";
1010
+ routes = [];
1011
+ constructor(options = {}) {
1012
+ [...METHODS, "all"].forEach((method) => {
1013
+ this[method] = (args1, ...args) => {
1014
+ const methodName = method.toUpperCase();
1015
+ if (typeof args1 === "string") this.#path = args1;
1016
+ else this.#addRoute(methodName, this.#path, args1);
1017
+ args.forEach((handler) => {
1018
+ this.#addRoute(methodName, this.#path, handler);
1019
+ });
1020
+ return this;
1021
+ };
1022
+ });
1023
+ this.on = (method, path8, ...handlers) => {
1024
+ for (const p of [path8].flat()) {
1025
+ this.#path = p;
1026
+ for (const m of [method].flat()) {
1027
+ const methodName = m.toUpperCase();
1028
+ for (const handler of handlers) this.#addRoute(methodName, this.#path, handler);
1029
+ }
1030
+ }
1031
+ return this;
1032
+ };
1033
+ this.use = (arg1, ...handlers) => {
1034
+ if (typeof arg1 === "string") this.#path = arg1;
1035
+ else {
1036
+ this.#path = "*";
1037
+ handlers.unshift(arg1);
1038
+ }
1039
+ handlers.forEach((handler) => {
1040
+ this.#addRoute("ALL", this.#path, handler);
1041
+ });
1042
+ return this;
1043
+ };
1044
+ const { strict, ...optionsWithoutStrict } = options;
1045
+ Object.assign(this, optionsWithoutStrict);
1046
+ this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
1047
+ }
1048
+ #clone() {
1049
+ const clone = new Hono2({
1050
+ router: this.router,
1051
+ getPath: this.getPath
1052
+ });
1053
+ clone.errorHandler = this.errorHandler;
1054
+ clone.#notFoundHandler = this.#notFoundHandler;
1055
+ clone.routes = this.routes;
1056
+ return clone;
1057
+ }
1058
+ #notFoundHandler = notFoundHandler;
1059
+ errorHandler = errorHandler;
1060
+ /**
1061
+ * `.route()` allows grouping other Hono instance in routes.
1062
+ *
1063
+ * @see {@link https://hono.dev/docs/api/routing#grouping}
1064
+ *
1065
+ * @param {string} path - base Path
1066
+ * @param {Hono} app - other Hono instance
1067
+ * @returns {Hono} routed Hono instance
1068
+ *
1069
+ * @example
1070
+ * ```ts
1071
+ * const app = new Hono()
1072
+ * const app2 = new Hono()
1073
+ *
1074
+ * app2.get("/user", (c) => c.text("user"))
1075
+ * app.route("/api", app2) // GET /api/user
1076
+ * ```
1077
+ */
1078
+ route(path8, app2) {
1079
+ const subApp = this.basePath(path8);
1080
+ app2.routes.map((r) => {
1081
+ let handler;
1082
+ if (app2.errorHandler === errorHandler) handler = r.handler;
1083
+ else {
1084
+ handler = async (c, next) => (await compose([], app2.errorHandler)(c, () => r.handler(c, next))).res;
1085
+ handler[COMPOSED_HANDLER] = r.handler;
1086
+ }
1087
+ subApp.#addRoute(r.method, r.path, handler, r.basePath);
1088
+ });
1089
+ return this;
1090
+ }
1091
+ /**
1092
+ * `.basePath()` allows base paths to be specified.
1093
+ *
1094
+ * @see {@link https://hono.dev/docs/api/routing#base-path}
1095
+ *
1096
+ * @param {string} path - base Path
1097
+ * @returns {Hono} changed Hono instance
1098
+ *
1099
+ * @example
1100
+ * ```ts
1101
+ * const api = new Hono().basePath('/api')
1102
+ * ```
1103
+ */
1104
+ basePath(path8) {
1105
+ const subApp = this.#clone();
1106
+ subApp._basePath = mergePath(this._basePath, path8);
1107
+ return subApp;
1108
+ }
1109
+ /**
1110
+ * `.onError()` handles an error and returns a customized Response.
1111
+ *
1112
+ * @see {@link https://hono.dev/docs/api/hono#error-handling}
1113
+ *
1114
+ * @param {ErrorHandler} handler - request Handler for error
1115
+ * @returns {Hono} changed Hono instance
1116
+ *
1117
+ * @example
1118
+ * ```ts
1119
+ * app.onError((err, c) => {
1120
+ * console.error(`${err}`)
1121
+ * return c.text('Custom Error Message', 500)
1122
+ * })
1123
+ * ```
1124
+ */
1125
+ onError = (handler) => {
1126
+ this.errorHandler = handler;
1127
+ return this;
1128
+ };
1129
+ /**
1130
+ * `.notFound()` allows you to customize a Not Found Response.
1131
+ *
1132
+ * @see {@link https://hono.dev/docs/api/hono#not-found}
1133
+ *
1134
+ * @param {NotFoundHandler} handler - request handler for not-found
1135
+ * @returns {Hono} changed Hono instance
1136
+ *
1137
+ * @example
1138
+ * ```ts
1139
+ * app.notFound((c) => {
1140
+ * return c.text('Custom 404 Message', 404)
1141
+ * })
1142
+ * ```
1143
+ */
1144
+ notFound = (handler) => {
1145
+ this.#notFoundHandler = handler;
1146
+ return this;
1147
+ };
1148
+ /**
1149
+ * `.mount()` allows you to mount applications built with other frameworks into your Hono application.
1150
+ *
1151
+ * @deprecated Use `mount()` from `hono/mount` instead. `.mount()` will be removed in v5.
1152
+ *
1153
+ * @see {@link https://hono.dev/docs/api/hono#mount}
1154
+ *
1155
+ * @param {string} path - base Path
1156
+ * @param {Function} applicationHandler - other Request Handler
1157
+ * @param {MountOptions} [options] - options of `.mount()`
1158
+ * @returns {Hono} mounted Hono instance
1159
+ *
1160
+ * @example
1161
+ * ```ts
1162
+ * import { Router as IttyRouter } from 'itty-router'
1163
+ * import { Hono } from 'hono'
1164
+ * // Create itty-router application
1165
+ * const ittyRouter = IttyRouter()
1166
+ * // GET /itty-router/hello
1167
+ * ittyRouter.get('/hello', () => new Response('Hello from itty-router'))
1168
+ *
1169
+ * const app = new Hono()
1170
+ * app.mount('/itty-router', ittyRouter.handle)
1171
+ * ```
1172
+ *
1173
+ * @example
1174
+ * ```ts
1175
+ * const app = new Hono()
1176
+ * // Send the request to another application without modification.
1177
+ * app.mount('/app', anotherApp, {
1178
+ * replaceRequest: (req) => req,
1179
+ * })
1180
+ * ```
1181
+ */
1182
+ mount(path8, applicationHandler, options) {
1183
+ let replaceRequest;
1184
+ let optionHandler;
1185
+ if (options) {
1186
+ if (typeof options === "function") optionHandler = options;
1187
+ else {
1188
+ optionHandler = options.optionHandler;
1189
+ if (options.replaceRequest === false) replaceRequest = (request) => request;
1190
+ else replaceRequest = options.replaceRequest;
1191
+ }
1192
+ }
1193
+ const getOptions = optionHandler ? (c) => {
1194
+ const options2 = optionHandler(c);
1195
+ return Array.isArray(options2) ? options2 : [options2];
1196
+ } : (c) => {
1197
+ let executionContext = void 0;
1198
+ try {
1199
+ executionContext = c.executionCtx;
1200
+ } catch {
1201
+ }
1202
+ return [c.env, executionContext];
1203
+ };
1204
+ replaceRequest ||= (() => {
1205
+ const mergedPath = mergePath(this._basePath, path8);
1206
+ const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
1207
+ return (request) => {
1208
+ const url = new URL(request.url);
1209
+ url.pathname = this.getPath(request).slice(pathPrefixLength) || "/";
1210
+ return new Request(url, request);
1211
+ };
1212
+ })();
1213
+ const handler = async (c, next) => {
1214
+ const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
1215
+ if (res) return res;
1216
+ await next();
1217
+ };
1218
+ this.#addRoute("ALL", mergePath(path8, "*"), handler);
1219
+ return this;
1220
+ }
1221
+ #addRoute(method, path8, handler, baseRoutePath) {
1222
+ path8 = mergePath(this._basePath, path8);
1223
+ const r = {
1224
+ basePath: baseRoutePath !== void 0 ? mergePath(this._basePath, baseRoutePath) : this._basePath,
1225
+ path: path8,
1226
+ method,
1227
+ handler
1228
+ };
1229
+ this.router.add(method, path8, [handler, r]);
1230
+ this.routes.push(r);
1231
+ }
1232
+ #handleError(err, c) {
1233
+ if (err instanceof Error) return this.errorHandler(err, c);
1234
+ throw err;
1235
+ }
1236
+ #dispatch(request, executionCtx, env, method) {
1237
+ if (method === "HEAD") return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))();
1238
+ const path8 = this.getPath(request, { env });
1239
+ const matchResult = this.router.match(method, path8);
1240
+ const c = new Context(request, {
1241
+ path: path8,
1242
+ matchResult,
1243
+ env,
1244
+ executionCtx,
1245
+ notFoundHandler: this.#notFoundHandler
1246
+ });
1247
+ if (matchResult[0].length === 1) {
1248
+ let res;
1249
+ try {
1250
+ res = matchResult[0][0][0][0](c, async () => {
1251
+ c.res = await this.#notFoundHandler(c);
1252
+ });
1253
+ } catch (err) {
1254
+ return this.#handleError(err, c);
1255
+ }
1256
+ return res instanceof Promise ? res.then((resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);
1257
+ }
1258
+ const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
1259
+ return (async () => {
1260
+ try {
1261
+ const context = await composed(c);
1262
+ if (!context.finalized) throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");
1263
+ return context.res;
1264
+ } catch (err) {
1265
+ return this.#handleError(err, c);
1266
+ }
1267
+ })();
1268
+ }
1269
+ /**
1270
+ * `.fetch()` will be entry point of your app.
1271
+ *
1272
+ * @see {@link https://hono.dev/docs/api/hono#fetch}
1273
+ *
1274
+ * @param {Request} request - request Object of request
1275
+ * @param {Env} env - env Object
1276
+ * @param {ExecutionContext} executionCtx - context of execution
1277
+ * @returns {Response | Promise<Response>} response of request
1278
+ *
1279
+ */
1280
+ fetch = (request, ...rest) => {
1281
+ return this.#dispatch(request, rest[1], rest[0], request.method);
1282
+ };
1283
+ /**
1284
+ * `.request()` is a useful method for testing.
1285
+ * You can pass a URL or pathname to send a GET request.
1286
+ * app will return a Response object.
1287
+ * ```ts
1288
+ * test('GET /hello is ok', async () => {
1289
+ * const res = await app.request('/hello')
1290
+ * expect(res.status).toBe(200)
1291
+ * })
1292
+ * ```
1293
+ * @see https://hono.dev/docs/api/hono#request
1294
+ */
1295
+ request = (input, requestInit, Env, executionCtx) => {
1296
+ if (input instanceof Request) return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
1297
+ input = input.toString();
1298
+ return this.fetch(new Request(/^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`, requestInit), Env, executionCtx);
1299
+ };
1300
+ /**
1301
+ * `.fire()` automatically adds a global fetch event listener.
1302
+ * This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.
1303
+ * @deprecated
1304
+ * Use `fire` from `hono/service-worker` instead.
1305
+ * ```ts
1306
+ * import { Hono } from 'hono'
1307
+ * import { fire } from 'hono/service-worker'
1308
+ *
1309
+ * const app = new Hono()
1310
+ * // ...
1311
+ * fire(app)
1312
+ * ```
1313
+ * @see https://hono.dev/docs/api/hono#fire
1314
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API
1315
+ * @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/
1316
+ */
1317
+ fire = () => {
1318
+ addEventListener("fetch", (event) => {
1319
+ event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));
1320
+ });
1321
+ };
1322
+ };
1323
+
1324
+ // ../../node_modules/.pnpm/hono@4.13.14/node_modules/hono/dist/router/utils.js
1325
+ var createNullObject = () => /* @__PURE__ */ Object.create(null);
1326
+
1327
+ // ../../node_modules/.pnpm/hono@4.13.14/node_modules/hono/dist/router/reg-exp-router/matcher.js
1328
+ var emptyParam = [];
1329
+ function match(method, path8) {
1330
+ const matchers = this.buildAllMatchers();
1331
+ const match2 = ((method2, path9) => {
1332
+ const matcher = matchers[method2] || matchers["ALL"];
1333
+ const staticMatch = matcher[2][path9];
1334
+ if (staticMatch) return staticMatch;
1335
+ const match3 = path9.match(matcher[0]);
1336
+ if (!match3) return [[], emptyParam];
1337
+ const index = match3.indexOf("", 1);
1338
+ return [matcher[1][index], match3];
1339
+ });
1340
+ this.match = match2;
1341
+ return match2(method, path8);
1342
+ }
1343
+
1344
+ // ../../node_modules/.pnpm/hono@4.13.14/node_modules/hono/dist/router/reg-exp-router/node.js
1345
+ var LABEL_REG_EXP_STR = "[^/]+";
1346
+ var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
1347
+ var PATH_ERROR = /* @__PURE__ */ Symbol();
1348
+ var regExpMetaChars = /* @__PURE__ */ new Set(".\\+*[^]$()");
1349
+ function compareKey(a, b) {
1350
+ if (a.length === 1) return b.length === 1 ? a < b ? -1 : 1 : -1;
1351
+ if (b.length === 1) return 1;
1352
+ if (a === ".*" || a === "(?:|/.*)") return b === "(?:|/.*)" ? -1 : 1;
1353
+ else if (b === ".*" || b === "(?:|/.*)") return -1;
1354
+ if (a === "[^/]+") return 1;
1355
+ else if (b === "[^/]+") return -1;
1356
+ return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
1357
+ }
1358
+ var Node = class Node2 {
1359
+ #index;
1360
+ #varIndex;
1361
+ #children = createNullObject();
1362
+ insert(tokens, index, paramMap, context, isStatic) {
1363
+ let node = this;
1364
+ for (let i = 0, len = tokens.length; i < len; i++) {
1365
+ const token = tokens[i];
1366
+ const pattern = token.length === 1 ? token === "*" ? i === len - 1 ? [
1367
+ "",
1368
+ "",
1369
+ ".*"
1370
+ ] : [
1371
+ "",
1372
+ "",
1373
+ LABEL_REG_EXP_STR
1374
+ ] : null : token === "/*" ? [
1375
+ "",
1376
+ "",
1377
+ TAIL_WILDCARD_REG_EXP_STR
1378
+ ] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
1379
+ let nextNode;
1380
+ if (pattern) {
1381
+ const name = pattern[1];
1382
+ let regexpStr = pattern[2] || "[^/]+";
1383
+ if (name && pattern[2]) {
1384
+ if (regexpStr === ".*") throw PATH_ERROR;
1385
+ regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
1386
+ if (/\((?!\?:)/.test(regexpStr)) throw PATH_ERROR;
1387
+ if (regexpStr.length === 1 && regExpMetaChars.has(regexpStr)) throw PATH_ERROR;
1388
+ }
1389
+ nextNode = node.#children[regexpStr];
1390
+ if (!nextNode) {
1391
+ if (regexpStr !== ".*" && regexpStr !== "(?:|/.*)") {
1392
+ for (const k in node.#children) if ((regexpStr.length > 1 || k.length > 1) && k !== ".*" && k !== "(?:|/.*)") throw PATH_ERROR;
1393
+ }
1394
+ nextNode = node.#children[regexpStr] = new Node2();
1395
+ }
1396
+ if (name !== "") {
1397
+ nextNode.#varIndex ??= context.varIndex++;
1398
+ paramMap.push([name, nextNode.#varIndex]);
1399
+ }
1400
+ } else {
1401
+ nextNode = node.#children[token];
1402
+ if (!nextNode) {
1403
+ for (const k in node.#children) if (k.length > 1 && k !== ".*" && k !== "(?:|/.*)") throw PATH_ERROR;
1404
+ nextNode = node.#children[token] = new Node2();
1405
+ }
1406
+ }
1407
+ node = nextNode;
1408
+ }
1409
+ if (node.#index !== void 0) throw PATH_ERROR;
1410
+ node.#index = isStatic ? -1 : index;
1411
+ }
1412
+ buildRegExpStr() {
1413
+ const strList = Object.keys(this.#children).sort(compareKey).map((k) => {
1414
+ const c = this.#children[k];
1415
+ const childStr = c.buildRegExpStr();
1416
+ return childStr === "" ? "" : (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + childStr;
1417
+ }).filter(Boolean);
1418
+ if (typeof this.#index === "number" && this.#index !== -1) strList.unshift(`#${this.#index}`);
1419
+ if (strList.length === 0) return "";
1420
+ if (strList.length === 1) return strList[0];
1421
+ return "(?:" + strList.join("|") + ")";
1422
+ }
1423
+ };
1424
+
1425
+ // ../../node_modules/.pnpm/hono@4.13.14/node_modules/hono/dist/router/reg-exp-router/trie.js
1426
+ var Trie = class {
1427
+ #context = { varIndex: 0 };
1428
+ #root = new Node();
1429
+ #index = 0;
1430
+ paths = createNullObject();
1431
+ insert(path8, isStatic) {
1432
+ if (isStatic) {
1433
+ this.#root.insert(path8.split(""), 0, [], this.#context, true);
1434
+ return;
1435
+ }
1436
+ const paramAssoc = [];
1437
+ const groups = [];
1438
+ let markedPath = path8;
1439
+ for (let i = 0; ; ) {
1440
+ let replaced = false;
1441
+ markedPath = markedPath.replace(/\{[^}]+\}/g, (m) => {
1442
+ const mark = `@\\${i}`;
1443
+ groups[i] = [mark, m];
1444
+ i++;
1445
+ replaced = true;
1446
+ return mark;
1447
+ });
1448
+ if (!replaced) break;
1449
+ }
1450
+ const tokens = markedPath.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
1451
+ for (let i = groups.length - 1; i >= 0; i--) {
1452
+ const [mark] = groups[i];
1453
+ for (let j = tokens.length - 1; j >= 0; j--) if (tokens[j].indexOf(mark) !== -1) {
1454
+ tokens[j] = tokens[j].replace(mark, groups[i][1]);
1455
+ break;
1456
+ }
1457
+ }
1458
+ this.#root.insert(tokens, this.#index, paramAssoc, this.#context, false);
1459
+ this.paths[path8] = [this.#index++, paramAssoc];
1460
+ }
1461
+ buildRegExp() {
1462
+ let regexp = this.#root.buildRegExpStr();
1463
+ if (regexp === "") return [
1464
+ /^$/,
1465
+ [],
1466
+ []
1467
+ ];
1468
+ let captureIndex = 0;
1469
+ const indexReplacementMap = [];
1470
+ const paramReplacementMap = [];
1471
+ regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
1472
+ if (handlerIndex !== void 0) {
1473
+ indexReplacementMap[++captureIndex] = Number(handlerIndex);
1474
+ return "$()";
1475
+ }
1476
+ if (paramIndex !== void 0) {
1477
+ paramReplacementMap[Number(paramIndex)] = ++captureIndex;
1478
+ return "";
1479
+ }
1480
+ return "";
1481
+ });
1482
+ return [
1483
+ new RegExp(`^${regexp}`),
1484
+ indexReplacementMap,
1485
+ paramReplacementMap
1486
+ ];
1487
+ }
1488
+ };
1489
+
1490
+ // ../../node_modules/.pnpm/hono@4.13.14/node_modules/hono/dist/router/reg-exp-router/router.js
1491
+ var wildcardRegExpCache = createNullObject();
1492
+ function buildWildcardRegExp(path8) {
1493
+ return wildcardRegExpCache[path8] ??= new RegExp(`^${path8.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g, (match2, metaChar) => metaChar ? `\\${metaChar}` : match2 === "/*" ? TAIL_WILDCARD_REG_EXP_STR : match2 === "*" ? ".*" : `/:${LABEL_REG_EXP_STR}`)}$`);
1494
+ }
1495
+ function findMiddleware(middleware, path8) {
1496
+ for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) if (buildWildcardRegExp(k).test(path8)) return [...middleware[k]];
1497
+ }
1498
+ var RegExpRouter = class {
1499
+ name = "RegExpRouter";
1500
+ #middleware;
1501
+ #routes;
1502
+ #tries;
1503
+ constructor() {
1504
+ this.#middleware = { ["ALL"]: createNullObject() };
1505
+ this.#routes = { ["ALL"]: createNullObject() };
1506
+ this.#tries = { ["ALL"]: new Trie() };
1507
+ }
1508
+ #insertPath(method, path8) {
1509
+ try {
1510
+ this.#tries[method].insert(path8, !/\*|\/:/.test(path8));
1511
+ } catch (e) {
1512
+ throw e === PATH_ERROR ? new UnsupportedPathError(path8) : e;
1513
+ }
1514
+ }
1515
+ add(method, path8, handler) {
1516
+ const middleware = this.#middleware;
1517
+ const routes = this.#routes;
1518
+ if (!middleware) throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
1519
+ if (!middleware[method]) {
1520
+ this.#tries[method] = new Trie();
1521
+ for (const handlerMap of [middleware, routes]) {
1522
+ handlerMap[method] = createNullObject();
1523
+ for (const p in handlerMap["ALL"]) {
1524
+ handlerMap[method][p] = [...handlerMap["ALL"][p]];
1525
+ this.#insertPath(method, p);
1526
+ }
1527
+ }
1528
+ }
1529
+ if (path8 === "/*") path8 = "*";
1530
+ const methods = method === "ALL" ? Object.keys(middleware) : [method];
1531
+ if (/\*$/.test(path8)) {
1532
+ const re = buildWildcardRegExp(path8);
1533
+ for (const m of methods) if (!middleware[m][path8]) {
1534
+ this.#insertPath(m, path8);
1535
+ middleware[m][path8] = findMiddleware(middleware[m], path8) || findMiddleware(middleware["ALL"], path8) || [];
1536
+ }
1537
+ for (const handlerMap of [middleware, routes]) for (const m of methods) for (const p in handlerMap[m]) re.test(p) && handlerMap[m][p].push([handler, path8]);
1538
+ return;
1539
+ }
1540
+ const paths = checkOptionalParameter(path8) || [path8];
1541
+ for (const path9 of paths) for (const m of methods) {
1542
+ if (!routes[m][path9]) {
1543
+ this.#insertPath(m, path9);
1544
+ routes[m][path9] = findMiddleware(middleware[m], path9) || findMiddleware(middleware["ALL"], path9) || [];
1545
+ }
1546
+ routes[m][path9].push([handler, path9]);
1547
+ }
1548
+ }
1549
+ match = match;
1550
+ buildAllMatchers() {
1551
+ const matchers = createNullObject();
1552
+ for (const method of Object.keys(this.#routes)) matchers[method] = this.#buildMatcher(method);
1553
+ this.#middleware = this.#routes = this.#tries = void 0;
1554
+ wildcardRegExpCache = createNullObject();
1555
+ return matchers;
1556
+ }
1557
+ #buildMatcher(method) {
1558
+ const middleware = this.#middleware[method];
1559
+ const routes = this.#routes[method];
1560
+ const trie = this.#tries[method];
1561
+ const staticMap = createNullObject();
1562
+ const handlerData = [];
1563
+ const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
1564
+ for (const r of [middleware, routes]) for (const path8 in r) {
1565
+ const handlers = r[path8];
1566
+ const pathData = trie.paths[path8];
1567
+ if (!pathData) {
1568
+ staticMap[path8] = [handlers.map(([h]) => [h, createNullObject()]), emptyParam];
1569
+ continue;
1570
+ }
1571
+ handlerData[pathData[0]] = handlers.map(([h, handlerPath]) => [h, trie.paths[handlerPath][1].reduceRight((map, [key], i) => {
1572
+ map[key] = paramReplacementMap[pathData[1][i][1]];
1573
+ return map;
1574
+ }, createNullObject())]);
1575
+ }
1576
+ return [
1577
+ regexp,
1578
+ indexReplacementMap.map((i) => handlerData[i]),
1579
+ staticMap
1580
+ ];
1581
+ }
1582
+ };
1583
+
1584
+ // ../../node_modules/.pnpm/hono@4.13.14/node_modules/hono/dist/router/smart-router/router.js
1585
+ var SmartRouter = class {
1586
+ name = "SmartRouter";
1587
+ #routers = [];
1588
+ #routes = [];
1589
+ constructor(init) {
1590
+ this.#routers = init.routers;
1591
+ }
1592
+ add(method, path8, handler) {
1593
+ if (!this.#routes) throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
1594
+ this.#routes.push([
1595
+ method,
1596
+ path8,
1597
+ handler
1598
+ ]);
1599
+ }
1600
+ match(method, path8) {
1601
+ if (!this.#routes) throw new Error("Fatal error");
1602
+ const routers = this.#routers;
1603
+ const routes = this.#routes;
1604
+ const len = routers.length;
1605
+ let i = 0;
1606
+ let res;
1607
+ for (; i < len; i++) {
1608
+ const router = routers[i];
1609
+ try {
1610
+ for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) router.add(...routes[i2]);
1611
+ res = router.match(method, path8);
1612
+ } catch (e) {
1613
+ if (e instanceof UnsupportedPathError) continue;
1614
+ throw e;
1615
+ }
1616
+ this.match = router.match.bind(router);
1617
+ this.#routers = [router];
1618
+ this.#routes = void 0;
1619
+ break;
1620
+ }
1621
+ if (i === len) throw new Error("Fatal error");
1622
+ this.name = `SmartRouter + ${this.activeRouter.name}`;
1623
+ return res;
1624
+ }
1625
+ get activeRouter() {
1626
+ if (this.#routes || this.#routers.length !== 1) throw new Error("No active router has been determined yet.");
1627
+ return this.#routers[0];
1628
+ }
1629
+ };
1630
+
1631
+ // ../../node_modules/.pnpm/hono@4.13.14/node_modules/hono/dist/router/trie-router/node.js
1632
+ var emptyParams = createNullObject();
1633
+ var order = 0;
1634
+ var Node3 = class Node4 {
1635
+ #methods = [];
1636
+ #children = createNullObject();
1637
+ #patterns = [];
1638
+ #pattern;
1639
+ #params = emptyParams;
1640
+ insert(method, path8, handler) {
1641
+ let curNode = this;
1642
+ const parts = splitRoutingPath(path8);
1643
+ const possibleKeys = /* @__PURE__ */ new Set();
1644
+ let i = 0;
1645
+ for (const p of parts) {
1646
+ const nextP = parts[++i];
1647
+ const pattern = getPattern(p, nextP) || (nextP === void 0 && p && p.indexOf("*") === p.length - 1 ? p : null);
1648
+ const isParam = Array.isArray(pattern);
1649
+ const key = isParam ? pattern[0] : pattern || p;
1650
+ const child = curNode.#children[key] ||= new Node4();
1651
+ if (pattern && !child.#pattern) {
1652
+ child.#pattern = pattern;
1653
+ curNode.#patterns.push(child);
1654
+ }
1655
+ curNode = child;
1656
+ if (isParam) possibleKeys.add(pattern[1]);
1657
+ }
1658
+ curNode.#methods.push({ [method]: {
1659
+ handler,
1660
+ possibleKeys: [...possibleKeys],
1661
+ score: ++order
1662
+ } });
1663
+ }
1664
+ #pushHandlerSets(handlerSets, node, method, nodeParams, params) {
1665
+ for (let i = 0, len = node.#methods.length; i < len; i++) {
1666
+ const m = node.#methods[i];
1667
+ const handlerSet = m[method] || m["ALL"];
1668
+ if (handlerSet) {
1669
+ handlerSet.params = createNullObject();
1670
+ handlerSets.push(handlerSet);
1671
+ for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) {
1672
+ const key = handlerSet.possibleKeys[i2];
1673
+ handlerSet.params[key] = params?.[key] && !i2 ? params[key] : nodeParams[key] ?? params?.[key];
1674
+ }
1675
+ }
1676
+ }
1677
+ }
1678
+ search(method, path8) {
1679
+ const handlerSets = [];
1680
+ this.#params = emptyParams;
1681
+ let curNodes = [this];
1682
+ const parts = splitPath(path8);
1683
+ const curNodesQueue = [];
1684
+ const len = parts.length;
1685
+ let partOffsets = null;
1686
+ for (let i = 0; i < len; i++) {
1687
+ const part = parts[i];
1688
+ const isLast = i === len - 1;
1689
+ const tempNodes = [];
1690
+ for (let j = 0, len2 = curNodes.length; j < len2; j++) {
1691
+ const node = curNodes[j];
1692
+ const nextNode = node.#children[part];
1693
+ if (nextNode) {
1694
+ nextNode.#params = node.#params;
1695
+ if (isLast) {
1696
+ if (nextNode.#children["*"]) this.#pushHandlerSets(handlerSets, nextNode.#children["*"], method, node.#params);
1697
+ this.#pushHandlerSets(handlerSets, nextNode, method, node.#params);
1698
+ } else tempNodes.push(nextNode);
1699
+ }
1700
+ for (const child of node.#patterns) {
1701
+ const pattern = child.#pattern;
1702
+ const params = node.#params === emptyParams ? {} : { ...node.#params };
1703
+ if (typeof pattern === "string") {
1704
+ if (pattern === "*" || part.startsWith(pattern.slice(0, -1))) {
1705
+ this.#pushHandlerSets(handlerSets, child, method, node.#params);
1706
+ if (pattern === "*") {
1707
+ child.#params = params;
1708
+ tempNodes.push(child);
1709
+ }
1710
+ }
1711
+ continue;
1712
+ }
1713
+ const [, name, matcher] = pattern;
1714
+ if (!part && matcher === true) continue;
1715
+ if (matcher !== true) {
1716
+ if (!partOffsets) {
1717
+ partOffsets = [];
1718
+ let offset = path8[0] === "/" ? 1 : 0;
1719
+ for (let p = 0; p < len; p++) {
1720
+ partOffsets[p] = offset;
1721
+ offset += parts[p].length + 1;
1722
+ }
1723
+ }
1724
+ const restPathString = path8.slice(partOffsets[i]);
1725
+ const m = matcher.exec(restPathString);
1726
+ if (m) {
1727
+ if (!Object.hasOwn(params, name)) params[name] = m[0];
1728
+ this.#pushHandlerSets(handlerSets, child, method, node.#params, params);
1729
+ if (m[0].length === restPathString.length && child.#children["*"]) this.#pushHandlerSets(handlerSets, child.#children["*"], method, node.#params, params);
1730
+ for (const _ in child.#children) {
1731
+ child.#params = params;
1732
+ const componentCount = m[0].match(/\//g)?.length ?? 0;
1733
+ (curNodesQueue[componentCount] ||= []).push(child);
1734
+ break;
1735
+ }
1736
+ continue;
1737
+ }
1738
+ }
1739
+ if (matcher === true || matcher.test(part)) {
1740
+ if (!Object.hasOwn(params, name)) params[name] = part;
1741
+ if (isLast) {
1742
+ this.#pushHandlerSets(handlerSets, child, method, params, node.#params);
1743
+ if (child.#children["*"]) this.#pushHandlerSets(handlerSets, child.#children["*"], method, params, node.#params);
1744
+ } else {
1745
+ child.#params = params;
1746
+ tempNodes.push(child);
1747
+ }
1748
+ }
1749
+ }
1750
+ }
1751
+ const shifted = curNodesQueue.shift();
1752
+ curNodes = shifted ? tempNodes.concat(shifted) : tempNodes;
1753
+ }
1754
+ if (handlerSets[1]) handlerSets.sort((a, b) => {
1755
+ return a.score - b.score;
1756
+ });
1757
+ return [handlerSets.map(({ handler, params }) => [handler, params])];
1758
+ }
1759
+ };
1760
+
1761
+ // ../../node_modules/.pnpm/hono@4.13.14/node_modules/hono/dist/router/trie-router/router.js
1762
+ var TrieRouter = class {
1763
+ name = "TrieRouter";
1764
+ #node = new Node3();
1765
+ add(method, path8, handler) {
1766
+ for (const result of checkOptionalParameter(path8) || [path8]) this.#node.insert(method, result, handler);
1767
+ }
1768
+ match(method, path8) {
1769
+ return this.#node.search(method, path8);
1770
+ }
1771
+ };
1772
+
1773
+ // ../../node_modules/.pnpm/hono@4.13.14/node_modules/hono/dist/hono.js
1774
+ var Hono3 = class extends Hono {
1775
+ /**
1776
+ * Creates an instance of the Hono class.
1777
+ *
1778
+ * @param options - Optional configuration options for the Hono instance.
1779
+ */
1780
+ constructor(options = {}) {
1781
+ super(options);
1782
+ this.router = options.router ?? new SmartRouter({ routers: [new RegExpRouter(), new TrieRouter()] });
1783
+ }
1784
+ };
1785
+
1786
+ // ../../node_modules/.pnpm/hono@4.13.14/node_modules/hono/dist/utils/stream.js
1787
+ var StreamingApi = class {
1788
+ writer;
1789
+ encoder;
1790
+ writable;
1791
+ abortSubscribers = [];
1792
+ responseReadable;
1793
+ /**
1794
+ * Whether the stream has been aborted.
1795
+ */
1796
+ aborted = false;
1797
+ /**
1798
+ * Whether the stream has been closed normally.
1799
+ */
1800
+ closed = false;
1801
+ constructor(writable, _readable) {
1802
+ this.writable = writable;
1803
+ this.writer = writable.getWriter();
1804
+ this.encoder = new TextEncoder();
1805
+ const reader = _readable.getReader();
1806
+ this.abortSubscribers.push(async () => {
1807
+ await reader.cancel();
1808
+ });
1809
+ this.responseReadable = new ReadableStream({
1810
+ async pull(controller) {
1811
+ const { done, value } = await reader.read();
1812
+ done ? controller.close() : controller.enqueue(value);
1813
+ },
1814
+ cancel: () => {
1815
+ if (!this.closed) this.abort();
1816
+ }
1817
+ });
1818
+ }
1819
+ async write(input) {
1820
+ try {
1821
+ if (typeof input === "string") input = this.encoder.encode(input);
1822
+ await this.writer.write(input);
1823
+ } catch {
1824
+ }
1825
+ return this;
1826
+ }
1827
+ async writeln(input) {
1828
+ await this.write(input + "\n");
1829
+ return this;
1830
+ }
1831
+ sleep(ms) {
1832
+ return new Promise((res) => setTimeout(res, ms));
1833
+ }
1834
+ async close() {
1835
+ this.closed = true;
1836
+ try {
1837
+ await this.writer.close();
1838
+ } catch {
1839
+ }
1840
+ }
1841
+ async pipe(body) {
1842
+ this.writer.releaseLock();
1843
+ try {
1844
+ await body.pipeTo(this.writable, {
1845
+ preventClose: true,
1846
+ preventAbort: true
1847
+ });
1848
+ } finally {
1849
+ this.writer = this.writable.getWriter();
1850
+ }
1851
+ }
1852
+ onAbort(listener) {
1853
+ this.abortSubscribers.push(listener);
1854
+ }
1855
+ /**
1856
+ * Abort the stream.
1857
+ * You can call this method when stream is aborted by external event.
1858
+ */
1859
+ abort() {
1860
+ if (!this.aborted) {
1861
+ this.aborted = true;
1862
+ this.abortSubscribers.forEach((subscriber) => {
1863
+ try {
1864
+ Promise.resolve(subscriber()).catch(() => {
1865
+ });
1866
+ } catch {
1867
+ }
1868
+ });
1869
+ }
1870
+ }
1871
+ };
1872
+
1873
+ // ../../node_modules/.pnpm/hono@4.13.14/node_modules/hono/dist/helper/streaming/utils.js
1874
+ var isOldBunVersion = () => {
1875
+ const version = typeof Bun !== "undefined" ? Bun.version : void 0;
1876
+ if (version === void 0) return false;
1877
+ const result = version.startsWith("1.1") || version.startsWith("1.0") || version.startsWith("0.");
1878
+ isOldBunVersion = () => result;
1879
+ return result;
1880
+ };
1881
+
1882
+ // ../../node_modules/.pnpm/hono@4.13.14/node_modules/hono/dist/helper/streaming/sse.js
1883
+ var SSEStreamingApi = class extends StreamingApi {
1884
+ constructor(writable, readable) {
1885
+ super(writable, readable);
1886
+ }
1887
+ async writeSSE(message) {
1888
+ const dataLines = (await resolveCallback(message.data, HtmlEscapedCallbackPhase.Stringify, false, {})).split(/\r\n|\r|\n/).map((line) => {
1889
+ return `data: ${line}`;
1890
+ }).join("\n");
1891
+ for (const key of ["event", "id"]) {
1892
+ const value = message[key];
1893
+ if (value && /[\r\n]/.test(value)) throw new Error(`${key} must not contain "\\r" or "\\n"`);
1894
+ }
1895
+ const sseData = [
1896
+ message.event && `event: ${message.event}`,
1897
+ dataLines,
1898
+ message.id !== void 0 && `id: ${message.id}`,
1899
+ message.retry !== void 0 && `retry: ${message.retry}`
1900
+ ].filter(Boolean).join("\n") + "\n\n";
1901
+ await this.write(sseData);
1902
+ }
1903
+ };
1904
+ var run = async (stream2, cb, onError) => {
1905
+ try {
1906
+ await cb(stream2);
1907
+ } catch (e) {
1908
+ if (e instanceof Error && onError) {
1909
+ await onError(e, stream2);
1910
+ await stream2.writeSSE({
1911
+ event: "error",
1912
+ data: e.message
1913
+ });
1914
+ } else console.error(e);
1915
+ } finally {
1916
+ stream2.close();
1917
+ }
1918
+ };
1919
+ var contextStash = /* @__PURE__ */ new WeakMap();
1920
+ var streamSSE = (c, cb, onError) => {
1921
+ const { readable, writable } = new TransformStream();
1922
+ const stream2 = new SSEStreamingApi(writable, readable);
1923
+ if (isOldBunVersion()) c.req.raw.signal.addEventListener("abort", () => {
1924
+ if (!stream2.closed) stream2.abort();
1925
+ });
1926
+ contextStash.set(stream2.responseReadable, c);
1927
+ c.header("Transfer-Encoding", "chunked");
1928
+ c.header("Content-Type", "text/event-stream");
1929
+ c.header("Cache-Control", "no-cache");
1930
+ c.header("Connection", "keep-alive");
1931
+ run(stream2, cb, onError);
1932
+ return c.newResponse(stream2.responseReadable);
1933
+ };
1934
+
1935
+ // ../../node_modules/.pnpm/@hono+node-server@1.19.17_hono@4.13.14/node_modules/@hono/node-server/dist/index.mjs
1936
+ import { Http2ServerRequest as Http2ServerRequest2, constants as h2constants } from "http2";
1937
+ import { Http2ServerRequest } from "http2";
1938
+ import { Readable } from "stream";
1939
+ import crypto2 from "crypto";
1940
+ var RequestError = class extends Error {
1941
+ constructor(message, options) {
1942
+ super(message, options);
1943
+ this.name = "RequestError";
1944
+ }
1945
+ };
1946
+ var toRequestError = (e) => {
1947
+ if (e instanceof RequestError) {
1948
+ return e;
1949
+ }
1950
+ return new RequestError(e.message, { cause: e });
1951
+ };
1952
+ var GlobalRequest = global.Request;
1953
+ var Request2 = class extends GlobalRequest {
1954
+ constructor(input, options) {
1955
+ if (typeof input === "object" && getRequestCache in input) {
1956
+ input = input[getRequestCache]();
1957
+ }
1958
+ if (typeof options?.body?.getReader !== "undefined") {
1959
+ ;
1960
+ options.duplex ??= "half";
1961
+ }
1962
+ super(input, options);
1963
+ }
1964
+ };
1965
+ var newHeadersFromIncoming = (incoming) => {
1966
+ const headerRecord = [];
1967
+ const rawHeaders = incoming.rawHeaders;
1968
+ for (let i = 0; i < rawHeaders.length; i += 2) {
1969
+ const { [i]: key, [i + 1]: value } = rawHeaders;
1970
+ if (key.charCodeAt(0) !== /*:*/
1971
+ 58) {
1972
+ headerRecord.push([key, value]);
1973
+ }
1974
+ }
1975
+ return new Headers(headerRecord);
1976
+ };
1977
+ var wrapBodyStream = /* @__PURE__ */ Symbol("wrapBodyStream");
1978
+ var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
1979
+ const init = {
1980
+ method,
1981
+ headers,
1982
+ signal: abortController.signal
1983
+ };
1984
+ if (method === "TRACE") {
1985
+ init.method = "GET";
1986
+ const req = new Request2(url, init);
1987
+ Object.defineProperty(req, "method", {
1988
+ get() {
1989
+ return "TRACE";
1990
+ }
1991
+ });
1992
+ return req;
1993
+ }
1994
+ if (!(method === "GET" || method === "HEAD")) {
1995
+ if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
1996
+ init.body = new ReadableStream({
1997
+ start(controller) {
1998
+ controller.enqueue(incoming.rawBody);
1999
+ controller.close();
2000
+ }
2001
+ });
2002
+ } else if (incoming[wrapBodyStream]) {
2003
+ let reader;
2004
+ init.body = new ReadableStream({
2005
+ async pull(controller) {
2006
+ try {
2007
+ reader ||= Readable.toWeb(incoming).getReader();
2008
+ const { done, value } = await reader.read();
2009
+ if (done) {
2010
+ controller.close();
2011
+ } else {
2012
+ controller.enqueue(value);
2013
+ }
2014
+ } catch (error) {
2015
+ controller.error(error);
2016
+ }
2017
+ }
2018
+ });
2019
+ } else {
2020
+ init.body = Readable.toWeb(incoming);
2021
+ }
2022
+ }
2023
+ return new Request2(url, init);
2024
+ };
2025
+ var getRequestCache = /* @__PURE__ */ Symbol("getRequestCache");
2026
+ var requestCache = /* @__PURE__ */ Symbol("requestCache");
2027
+ var incomingKey = /* @__PURE__ */ Symbol("incomingKey");
2028
+ var urlKey = /* @__PURE__ */ Symbol("urlKey");
2029
+ var headersKey = /* @__PURE__ */ Symbol("headersKey");
2030
+ var abortControllerKey = /* @__PURE__ */ Symbol("abortControllerKey");
2031
+ var getAbortController = /* @__PURE__ */ Symbol("getAbortController");
2032
+ var requestPrototype = {
2033
+ get method() {
2034
+ return this[incomingKey].method || "GET";
2035
+ },
2036
+ get url() {
2037
+ return this[urlKey];
2038
+ },
2039
+ get headers() {
2040
+ return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
2041
+ },
2042
+ [getAbortController]() {
2043
+ this[getRequestCache]();
2044
+ return this[abortControllerKey];
2045
+ },
2046
+ [getRequestCache]() {
2047
+ this[abortControllerKey] ||= new AbortController();
2048
+ return this[requestCache] ||= newRequestFromIncoming(
2049
+ this.method,
2050
+ this[urlKey],
2051
+ this.headers,
2052
+ this[incomingKey],
2053
+ this[abortControllerKey]
2054
+ );
2055
+ }
2056
+ };
2057
+ [
2058
+ "body",
2059
+ "bodyUsed",
2060
+ "cache",
2061
+ "credentials",
2062
+ "destination",
2063
+ "integrity",
2064
+ "mode",
2065
+ "redirect",
2066
+ "referrer",
2067
+ "referrerPolicy",
2068
+ "signal",
2069
+ "keepalive"
2070
+ ].forEach((k) => {
2071
+ Object.defineProperty(requestPrototype, k, {
2072
+ get() {
2073
+ return this[getRequestCache]()[k];
2074
+ }
2075
+ });
2076
+ });
2077
+ ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
2078
+ Object.defineProperty(requestPrototype, k, {
2079
+ value: function() {
2080
+ return this[getRequestCache]()[k]();
2081
+ }
2082
+ });
2083
+ });
2084
+ Object.defineProperty(requestPrototype, /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), {
2085
+ value: function(depth, options, inspectFn) {
2086
+ const props = {
2087
+ method: this.method,
2088
+ url: this.url,
2089
+ headers: this.headers,
2090
+ nativeRequest: this[requestCache]
2091
+ };
2092
+ return `Request (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
2093
+ }
2094
+ });
2095
+ Object.setPrototypeOf(requestPrototype, Request2.prototype);
2096
+ var newRequest = (incoming, defaultHostname) => {
2097
+ const req = Object.create(requestPrototype);
2098
+ req[incomingKey] = incoming;
2099
+ const incomingUrl = incoming.url || "";
2100
+ if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
2101
+ (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
2102
+ if (incoming instanceof Http2ServerRequest) {
2103
+ throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
2104
+ }
2105
+ try {
2106
+ const url2 = new URL(incomingUrl);
2107
+ req[urlKey] = url2.href;
2108
+ } catch (e) {
2109
+ throw new RequestError("Invalid absolute URL", { cause: e });
2110
+ }
2111
+ return req;
2112
+ }
2113
+ const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
2114
+ if (!host) {
2115
+ throw new RequestError("Missing host header");
2116
+ }
2117
+ let scheme;
2118
+ if (incoming instanceof Http2ServerRequest) {
2119
+ scheme = incoming.scheme;
2120
+ if (!(scheme === "http" || scheme === "https")) {
2121
+ throw new RequestError("Unsupported scheme");
2122
+ }
2123
+ } else {
2124
+ scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
2125
+ }
2126
+ const url = new URL(`${scheme}://${host}${incomingUrl}`);
2127
+ if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
2128
+ throw new RequestError("Invalid host header");
2129
+ }
2130
+ req[urlKey] = url.href;
2131
+ return req;
2132
+ };
2133
+ var responseCache = /* @__PURE__ */ Symbol("responseCache");
2134
+ var getResponseCache = /* @__PURE__ */ Symbol("getResponseCache");
2135
+ var cacheKey = /* @__PURE__ */ Symbol("cache");
2136
+ var GlobalResponse = global.Response;
2137
+ var Response2 = class _Response {
2138
+ #body;
2139
+ #init;
2140
+ [getResponseCache]() {
2141
+ delete this[cacheKey];
2142
+ return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
2143
+ }
2144
+ constructor(body, init) {
2145
+ let headers;
2146
+ this.#body = body;
2147
+ if (init instanceof _Response) {
2148
+ const cachedGlobalResponse = init[responseCache];
2149
+ if (cachedGlobalResponse) {
2150
+ this.#init = cachedGlobalResponse;
2151
+ this[getResponseCache]();
2152
+ return;
2153
+ } else {
2154
+ this.#init = init.#init;
2155
+ headers = new Headers(init.#init.headers);
2156
+ }
2157
+ } else {
2158
+ this.#init = init;
2159
+ }
2160
+ if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
2161
+ ;
2162
+ this[cacheKey] = [init?.status || 200, body, headers || init?.headers];
2163
+ }
2164
+ }
2165
+ get headers() {
2166
+ const cache = this[cacheKey];
2167
+ if (cache) {
2168
+ if (!(cache[2] instanceof Headers)) {
2169
+ cache[2] = new Headers(
2170
+ cache[2] || { "content-type": "text/plain; charset=UTF-8" }
2171
+ );
2172
+ }
2173
+ return cache[2];
2174
+ }
2175
+ return this[getResponseCache]().headers;
2176
+ }
2177
+ get status() {
2178
+ return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
2179
+ }
2180
+ get ok() {
2181
+ const status = this.status;
2182
+ return status >= 200 && status < 300;
2183
+ }
2184
+ };
2185
+ ["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
2186
+ Object.defineProperty(Response2.prototype, k, {
2187
+ get() {
2188
+ return this[getResponseCache]()[k];
2189
+ }
2190
+ });
2191
+ });
2192
+ ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
2193
+ Object.defineProperty(Response2.prototype, k, {
2194
+ value: function() {
2195
+ return this[getResponseCache]()[k]();
2196
+ }
2197
+ });
2198
+ });
2199
+ Object.defineProperty(Response2.prototype, /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), {
2200
+ value: function(depth, options, inspectFn) {
2201
+ const props = {
2202
+ status: this.status,
2203
+ headers: this.headers,
2204
+ ok: this.ok,
2205
+ nativeResponse: this[responseCache]
2206
+ };
2207
+ return `Response (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
2208
+ }
2209
+ });
2210
+ Object.setPrototypeOf(Response2, GlobalResponse);
2211
+ Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
2212
+ async function readWithoutBlocking(readPromise) {
2213
+ return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
2214
+ }
2215
+ function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
2216
+ const cancel = (error) => {
2217
+ reader.cancel(error).catch(() => {
2218
+ });
2219
+ };
2220
+ writable.on("close", cancel);
2221
+ writable.on("error", cancel);
2222
+ (currentReadPromise ?? reader.read()).then(flow, handleStreamError);
2223
+ return reader.closed.finally(() => {
2224
+ writable.off("close", cancel);
2225
+ writable.off("error", cancel);
2226
+ });
2227
+ function handleStreamError(error) {
2228
+ if (error) {
2229
+ writable.destroy(error);
2230
+ }
2231
+ }
2232
+ function onDrain() {
2233
+ reader.read().then(flow, handleStreamError);
2234
+ }
2235
+ function flow({ done, value }) {
2236
+ try {
2237
+ if (done) {
2238
+ writable.end();
2239
+ } else if (!writable.write(value)) {
2240
+ writable.once("drain", onDrain);
2241
+ } else {
2242
+ return reader.read().then(flow, handleStreamError);
2243
+ }
2244
+ } catch (e) {
2245
+ handleStreamError(e);
2246
+ }
2247
+ }
2248
+ }
2249
+ function writeFromReadableStream(stream2, writable) {
2250
+ if (stream2.locked) {
2251
+ throw new TypeError("ReadableStream is locked.");
2252
+ } else if (writable.destroyed) {
2253
+ return;
2254
+ }
2255
+ return writeFromReadableStreamDefaultReader(stream2.getReader(), writable);
2256
+ }
2257
+ var buildOutgoingHttpHeaders = (headers) => {
2258
+ const res = {};
2259
+ if (!(headers instanceof Headers)) {
2260
+ headers = new Headers(headers ?? void 0);
2261
+ }
2262
+ const cookies = [];
2263
+ for (const [k, v] of headers) {
2264
+ if (k === "set-cookie") {
2265
+ cookies.push(v);
2266
+ } else {
2267
+ res[k] = v;
2268
+ }
2269
+ }
2270
+ if (cookies.length > 0) {
2271
+ res["set-cookie"] = cookies;
2272
+ }
2273
+ res["content-type"] ??= "text/plain; charset=UTF-8";
2274
+ return res;
2275
+ };
2276
+ var X_ALREADY_SENT = "x-hono-already-sent";
2277
+ if (typeof global.crypto === "undefined") {
2278
+ global.crypto = crypto2;
2279
+ }
2280
+ var outgoingEnded = /* @__PURE__ */ Symbol("outgoingEnded");
2281
+ var incomingDraining = /* @__PURE__ */ Symbol("incomingDraining");
2282
+ var DRAIN_TIMEOUT_MS = 500;
2283
+ var MAX_DRAIN_BYTES = 64 * 1024 * 1024;
2284
+ var drainIncoming = (incoming) => {
2285
+ const incomingWithDrainState = incoming;
2286
+ if (incoming.destroyed || incomingWithDrainState[incomingDraining]) {
2287
+ return;
2288
+ }
2289
+ incomingWithDrainState[incomingDraining] = true;
2290
+ if (incoming instanceof Http2ServerRequest2) {
2291
+ try {
2292
+ ;
2293
+ incoming.stream?.close?.(h2constants.NGHTTP2_NO_ERROR);
2294
+ } catch {
2295
+ }
2296
+ return;
2297
+ }
2298
+ let bytesRead = 0;
2299
+ const cleanup = () => {
2300
+ clearTimeout(timer);
2301
+ incoming.off("data", onData);
2302
+ incoming.off("end", cleanup);
2303
+ incoming.off("error", cleanup);
2304
+ };
2305
+ const forceClose = () => {
2306
+ cleanup();
2307
+ const socket = incoming.socket;
2308
+ if (socket && !socket.destroyed) {
2309
+ socket.destroySoon();
2310
+ }
2311
+ };
2312
+ const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);
2313
+ timer.unref?.();
2314
+ const onData = (chunk) => {
2315
+ bytesRead += chunk.length;
2316
+ if (bytesRead > MAX_DRAIN_BYTES) {
2317
+ forceClose();
2318
+ }
2319
+ };
2320
+ incoming.on("data", onData);
2321
+ incoming.on("end", cleanup);
2322
+ incoming.on("error", cleanup);
2323
+ incoming.resume();
2324
+ };
2325
+ var handleRequestError = () => new Response(null, {
2326
+ status: 400
2327
+ });
2328
+ var handleFetchError = (e) => new Response(null, {
2329
+ status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500
2330
+ });
2331
+ var handleResponseError = (e, outgoing) => {
2332
+ const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
2333
+ if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
2334
+ console.info("The user aborted a request.");
2335
+ } else {
2336
+ console.error(e);
2337
+ if (!outgoing.headersSent) {
2338
+ outgoing.writeHead(500, { "Content-Type": "text/plain" });
2339
+ }
2340
+ outgoing.end(`Error: ${err.message}`);
2341
+ outgoing.destroy(err);
2342
+ }
2343
+ };
2344
+ var flushHeaders = (outgoing) => {
2345
+ if ("flushHeaders" in outgoing && outgoing.writable) {
2346
+ outgoing.flushHeaders();
2347
+ }
2348
+ };
2349
+ var responseViaCache = async (res, outgoing) => {
2350
+ let [status, body, header] = res[cacheKey];
2351
+ let hasContentLength = false;
2352
+ if (!header) {
2353
+ header = { "content-type": "text/plain; charset=UTF-8" };
2354
+ } else if (header instanceof Headers) {
2355
+ hasContentLength = header.has("content-length");
2356
+ header = buildOutgoingHttpHeaders(header);
2357
+ } else if (Array.isArray(header)) {
2358
+ const headerObj = new Headers(header);
2359
+ hasContentLength = headerObj.has("content-length");
2360
+ header = buildOutgoingHttpHeaders(headerObj);
2361
+ } else {
2362
+ for (const key in header) {
2363
+ if (key.length === 14 && key.toLowerCase() === "content-length") {
2364
+ hasContentLength = true;
2365
+ break;
2366
+ }
2367
+ }
2368
+ }
2369
+ if (!hasContentLength) {
2370
+ if (typeof body === "string") {
2371
+ header["Content-Length"] = Buffer.byteLength(body);
2372
+ } else if (body instanceof Uint8Array) {
2373
+ header["Content-Length"] = body.byteLength;
2374
+ } else if (body instanceof Blob) {
2375
+ header["Content-Length"] = body.size;
2376
+ }
2377
+ }
2378
+ outgoing.writeHead(status, header);
2379
+ if (typeof body === "string" || body instanceof Uint8Array) {
2380
+ outgoing.end(body);
2381
+ } else if (body instanceof Blob) {
2382
+ outgoing.end(new Uint8Array(await body.arrayBuffer()));
2383
+ } else {
2384
+ flushHeaders(outgoing);
2385
+ await writeFromReadableStream(body, outgoing)?.catch(
2386
+ (e) => handleResponseError(e, outgoing)
2387
+ );
2388
+ }
2389
+ ;
2390
+ outgoing[outgoingEnded]?.();
2391
+ };
2392
+ var isPromise = (res) => typeof res.then === "function";
2393
+ var responseViaResponseObject = async (res, outgoing, options = {}) => {
2394
+ if (isPromise(res)) {
2395
+ if (options.errorHandler) {
2396
+ try {
2397
+ res = await res;
2398
+ } catch (err) {
2399
+ const errRes = await options.errorHandler(err);
2400
+ if (!errRes) {
2401
+ return;
2402
+ }
2403
+ res = errRes;
2404
+ }
2405
+ } else {
2406
+ res = await res.catch(handleFetchError);
2407
+ }
2408
+ }
2409
+ if (cacheKey in res) {
2410
+ return responseViaCache(res, outgoing);
2411
+ }
2412
+ const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
2413
+ if (res.body) {
2414
+ const reader = res.body.getReader();
2415
+ const values = [];
2416
+ let done = false;
2417
+ let currentReadPromise = void 0;
2418
+ if (resHeaderRecord["transfer-encoding"] !== "chunked") {
2419
+ let maxReadCount = 2;
2420
+ for (let i = 0; i < maxReadCount; i++) {
2421
+ currentReadPromise ||= reader.read();
2422
+ const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
2423
+ console.error(e);
2424
+ done = true;
2425
+ });
2426
+ if (!chunk) {
2427
+ if (i === 1) {
2428
+ await new Promise((resolve) => setTimeout(resolve));
2429
+ maxReadCount = 3;
2430
+ continue;
2431
+ }
2432
+ break;
2433
+ }
2434
+ currentReadPromise = void 0;
2435
+ if (chunk.value) {
2436
+ values.push(chunk.value);
2437
+ }
2438
+ if (chunk.done) {
2439
+ done = true;
2440
+ break;
2441
+ }
2442
+ }
2443
+ if (done && !("content-length" in resHeaderRecord)) {
2444
+ resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
2445
+ }
2446
+ }
2447
+ outgoing.writeHead(res.status, resHeaderRecord);
2448
+ values.forEach((value) => {
2449
+ ;
2450
+ outgoing.write(value);
2451
+ });
2452
+ if (done) {
2453
+ outgoing.end();
2454
+ } else {
2455
+ if (values.length === 0) {
2456
+ flushHeaders(outgoing);
2457
+ }
2458
+ await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
2459
+ }
2460
+ } else if (resHeaderRecord[X_ALREADY_SENT]) {
2461
+ } else {
2462
+ outgoing.writeHead(res.status, resHeaderRecord);
2463
+ outgoing.end();
2464
+ }
2465
+ ;
2466
+ outgoing[outgoingEnded]?.();
2467
+ };
2468
+ var getRequestListener = (fetchCallback, options = {}) => {
2469
+ const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
2470
+ if (options.overrideGlobalObjects !== false && global.Request !== Request2) {
2471
+ Object.defineProperty(global, "Request", {
2472
+ value: Request2
2473
+ });
2474
+ Object.defineProperty(global, "Response", {
2475
+ value: Response2
2476
+ });
2477
+ }
2478
+ return async (incoming, outgoing) => {
2479
+ let res, req;
2480
+ try {
2481
+ req = newRequest(incoming, options.hostname);
2482
+ let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
2483
+ if (!incomingEnded) {
2484
+ ;
2485
+ incoming[wrapBodyStream] = true;
2486
+ incoming.on("end", () => {
2487
+ incomingEnded = true;
2488
+ });
2489
+ if (incoming instanceof Http2ServerRequest2) {
2490
+ ;
2491
+ outgoing[outgoingEnded] = () => {
2492
+ if (!incomingEnded) {
2493
+ setTimeout(() => {
2494
+ if (!incomingEnded) {
2495
+ setTimeout(() => {
2496
+ drainIncoming(incoming);
2497
+ });
2498
+ }
2499
+ });
2500
+ }
2501
+ };
2502
+ }
2503
+ outgoing.on("finish", () => {
2504
+ if (!incomingEnded) {
2505
+ drainIncoming(incoming);
2506
+ }
2507
+ });
2508
+ }
2509
+ outgoing.on("close", () => {
2510
+ const abortController = req[abortControllerKey];
2511
+ if (abortController) {
2512
+ if (incoming.errored) {
2513
+ req[abortControllerKey].abort(incoming.errored.toString());
2514
+ } else if (!outgoing.writableFinished) {
2515
+ req[abortControllerKey].abort("Client connection prematurely closed.");
2516
+ }
2517
+ }
2518
+ if (!incomingEnded) {
2519
+ setTimeout(() => {
2520
+ if (!incomingEnded) {
2521
+ setTimeout(() => {
2522
+ drainIncoming(incoming);
2523
+ });
2524
+ }
2525
+ });
2526
+ }
2527
+ });
2528
+ res = fetchCallback(req, { incoming, outgoing });
2529
+ if (cacheKey in res) {
2530
+ return responseViaCache(res, outgoing);
2531
+ }
2532
+ } catch (e) {
2533
+ if (!res) {
2534
+ if (options.errorHandler) {
2535
+ res = await options.errorHandler(req ? e : toRequestError(e));
2536
+ if (!res) {
2537
+ return;
2538
+ }
2539
+ } else if (!req) {
2540
+ res = handleRequestError();
2541
+ } else {
2542
+ res = handleFetchError(e);
2543
+ }
2544
+ } else {
2545
+ return handleResponseError(e, outgoing);
2546
+ }
2547
+ }
2548
+ try {
2549
+ return await responseViaResponseObject(res, outgoing, options);
2550
+ } catch (e) {
2551
+ return handleResponseError(e, outgoing);
2552
+ }
2553
+ };
2554
+ };
2555
+
2556
+ // server/chats.ts
2557
+ import fs2 from "node:fs";
2558
+ import path2 from "node:path";
2559
+
2560
+ // server/pi-rpc.ts
2561
+ import { spawn } from "node:child_process";
2562
+ var PiRpc = class {
2563
+ proc = null;
2564
+ buffer = "";
2565
+ seq = 0;
2566
+ pending = /* @__PURE__ */ new Map();
2567
+ listeners = /* @__PURE__ */ new Set();
2568
+ uiListeners = /* @__PURE__ */ new Set();
2569
+ exitListeners = /* @__PURE__ */ new Set();
2570
+ stderr = "";
2571
+ exited = null;
2572
+ options;
2573
+ constructor(options) {
2574
+ this.options = options;
2575
+ }
2576
+ get running() {
2577
+ return !!this.proc && !this.exited;
2578
+ }
2579
+ get stderrText() {
2580
+ return this.stderr;
2581
+ }
2582
+ get cwd() {
2583
+ return this.options.cwd;
2584
+ }
2585
+ async start() {
2586
+ if (this.proc) return;
2587
+ const proc = spawn(this.options.command ?? "pi", ["--mode", "rpc", ...this.options.args ?? []], {
2588
+ cwd: this.options.cwd,
2589
+ env: { ...process.env, ...this.options.env },
2590
+ stdio: ["pipe", "pipe", "pipe"]
2591
+ });
2592
+ this.proc = proc;
2593
+ proc.stdout.setEncoding("utf8");
2594
+ proc.stdout.on("data", (chunk) => {
2595
+ this.buffer += chunk;
2596
+ let i;
2597
+ while ((i = this.buffer.indexOf("\n")) >= 0) {
2598
+ const line = this.buffer.slice(0, i).replace(/\r$/, "");
2599
+ this.buffer = this.buffer.slice(i + 1);
2600
+ if (!line.trim()) continue;
2601
+ let record;
2602
+ try {
2603
+ record = JSON.parse(line);
2604
+ } catch {
2605
+ continue;
2606
+ }
2607
+ this.dispatch(record);
2608
+ }
2609
+ });
2610
+ proc.stderr.setEncoding("utf8");
2611
+ proc.stderr.on("data", (chunk) => {
2612
+ this.stderr = (this.stderr + chunk).slice(-8e3);
2613
+ });
2614
+ const done = (code) => {
2615
+ if (this.exited) return;
2616
+ this.exited = { code };
2617
+ for (const [, p] of this.pending) p.reject(new Error(`pi exited (code ${code})${this.stderr ? `: ${this.stderr.slice(-400)}` : ""}`));
2618
+ this.pending.clear();
2619
+ for (const fn of this.exitListeners) {
2620
+ try {
2621
+ fn(code, this.stderr);
2622
+ } catch {
2623
+ }
2624
+ }
2625
+ };
2626
+ proc.on("exit", done);
2627
+ proc.on("error", (e) => {
2628
+ this.stderr += `
2629
+ spawn error: ${e.message}`;
2630
+ done(null);
2631
+ });
2632
+ }
2633
+ dispatch(record) {
2634
+ if (record.type === "response") {
2635
+ const p = this.pending.get(record.id);
2636
+ if (p) {
2637
+ this.pending.delete(record.id);
2638
+ if (record.success === false) p.reject(new Error(record.error ?? `${record.command} failed`));
2639
+ else p.resolve(record.data);
2640
+ } else if (!record.id) this.emit({ type: "parse_error", error: record.error });
2641
+ return;
2642
+ }
2643
+ if (record.type === "extension_ui_request") {
2644
+ for (const fn of this.uiListeners) {
2645
+ try {
2646
+ fn(record);
2647
+ } catch {
2648
+ }
2649
+ }
2650
+ this.emit(record);
2651
+ return;
2652
+ }
2653
+ this.emit(record);
2654
+ }
2655
+ emit(event) {
2656
+ for (const fn of this.listeners) {
2657
+ try {
2658
+ fn(event);
2659
+ } catch {
2660
+ }
2661
+ }
2662
+ }
2663
+ onEvent(fn) {
2664
+ this.listeners.add(fn);
2665
+ return () => {
2666
+ this.listeners.delete(fn);
2667
+ };
2668
+ }
2669
+ onUiRequest(fn) {
2670
+ this.uiListeners.add(fn);
2671
+ return () => {
2672
+ this.uiListeners.delete(fn);
2673
+ };
2674
+ }
2675
+ onExit(fn) {
2676
+ this.exitListeners.add(fn);
2677
+ return () => {
2678
+ this.exitListeners.delete(fn);
2679
+ };
2680
+ }
2681
+ /** Send one command and resolve with its `data`; rejects when the agent reports failure. */
2682
+ send(command, timeoutMs = 0) {
2683
+ if (!this.proc || this.exited) return Promise.reject(new Error("pi is not running"));
2684
+ const id = `c${++this.seq}`;
2685
+ const payload = JSON.stringify({ ...command, id }) + "\n";
2686
+ return new Promise((resolve, reject) => {
2687
+ this.pending.set(id, { resolve, reject });
2688
+ const timer = timeoutMs ? setTimeout(() => {
2689
+ if (this.pending.delete(id)) reject(new Error(`${command.type} timed out`));
2690
+ }, timeoutMs) : null;
2691
+ const settle = (fn) => {
2692
+ if (timer) clearTimeout(timer);
2693
+ fn();
2694
+ };
2695
+ const entry = this.pending.get(id);
2696
+ this.pending.set(id, { resolve: (d) => settle(() => resolve(d)), reject: (e) => settle(() => reject(e)) });
2697
+ try {
2698
+ this.proc.stdin.write(payload);
2699
+ } catch (e) {
2700
+ this.pending.delete(id);
2701
+ settle(() => reject(e));
2702
+ }
2703
+ });
2704
+ }
2705
+ /** Answer an extension dialog. Without an answer the extension's tool call waits forever. */
2706
+ async respondUi(id, response) {
2707
+ if (!this.proc || this.exited) return;
2708
+ const record = { type: "extension_ui_response", id, ...response };
2709
+ try {
2710
+ this.proc.stdin.write(JSON.stringify(record) + "\n");
2711
+ } catch {
2712
+ }
2713
+ }
2714
+ prompt(message, behavior) {
2715
+ return this.send({ type: "prompt", message, ...behavior ? { streamingBehavior: behavior } : {} });
2716
+ }
2717
+ async stop() {
2718
+ const proc = this.proc;
2719
+ if (!proc) return;
2720
+ try {
2721
+ proc.stdin.end();
2722
+ } catch {
2723
+ }
2724
+ await new Promise((resolve) => {
2725
+ if (this.exited) return resolve();
2726
+ const t = setTimeout(() => {
2727
+ try {
2728
+ proc.kill("SIGKILL");
2729
+ } catch {
2730
+ }
2731
+ resolve();
2732
+ }, 3e3);
2733
+ proc.once("exit", () => {
2734
+ clearTimeout(t);
2735
+ resolve();
2736
+ });
2737
+ });
2738
+ this.proc = null;
2739
+ }
2740
+ };
2741
+
2742
+ // server/runs.ts
2743
+ import fs from "node:fs";
2744
+ import path from "node:path";
2745
+ var pretty = (spec) => {
2746
+ const id = (spec ?? "").split("/").pop() ?? "";
2747
+ if (/deepseek/i.test(id)) return "DeepSeek";
2748
+ if (/kimi/i.test(id)) return "Kimi";
2749
+ if (/glm/i.test(id)) return "GLM";
2750
+ if (/qwen/i.test(id)) return "Qwen";
2751
+ return id || "model";
2752
+ };
2753
+ var letters = ["A", "B", "C", "D"];
2754
+ var STATE_DIR = path.join(".pi", "loops");
2755
+ var stateFile = (cwd, id) => path.join(cwd, STATE_DIR, `${id}.json`);
2756
+ function readState(cwd, id) {
2757
+ try {
2758
+ return JSON.parse(fs.readFileSync(stateFile(cwd, id), "utf8"));
2759
+ } catch {
2760
+ return null;
2761
+ }
2762
+ }
2763
+ var STATE_ENTRY = "loops-state";
2764
+ var roundOfEntry = (data) => {
2765
+ const judge = data?.judge ?? (data?.pick ? { pick: data.pick, why: data.why ?? null, human: !!data.human, scores: data.scores ?? {}, reasons: data.reasons ?? {} } : null);
2766
+ const pick = data?.pick ?? judge?.pick ?? null;
2767
+ return {
2768
+ ...data,
2769
+ attempts: data?.attempts ?? [],
2770
+ ...judge ? {
2771
+ judge,
2772
+ ...pick ? { pick, why: data?.why ?? judge?.why ?? null, human: data?.human ?? judge?.human ?? false, scores: data?.scores ?? judge?.scores ?? {}, reasons: data?.reasons ?? judge?.reasons ?? {}, ...data?.byModel ?? judge?.byModel ? { byModel: data?.byModel ?? judge?.byModel } : {} } : {}
2773
+ } : {},
2774
+ ...data?.archived ? { archived: data.archived } : data?.shots && !Array.isArray(data.shots) ? { archived: data.shots } : {}
2775
+ };
2776
+ };
2777
+ function stateFromEntries(entries, id) {
2778
+ const custom = entries.filter((e) => e.type === "custom");
2779
+ const snap = [...custom].reverse().find((e) => e.customType === STATE_ENTRY && (e.data?.run === id || e.data?.state?.id === id));
2780
+ if (!snap) return null;
2781
+ const base = snap.data?.state ?? snap.data;
2782
+ if (!base || typeof base !== "object" || Array.isArray(base)) return null;
2783
+ const snapAt = Number(snap.data?.at ?? 0);
2784
+ const rounds = /* @__PURE__ */ new Map();
2785
+ const consider = (round, at) => {
2786
+ const n = Number(round?.n);
2787
+ if (!n) return;
2788
+ const seen = rounds.get(n);
2789
+ if (!seen || at >= seen.at) rounds.set(n, { round, at });
2790
+ };
2791
+ for (const r of Array.isArray(base?.rounds) ? base.rounds : []) consider(roundOfEntry(r), snapAt);
2792
+ for (const e of custom) if (e.customType === "loops-round" && e.data?.run === id) consider(roundOfEntry(e.data), Number(e.data?.at ?? 0));
2793
+ const rebuilt = [...rounds.values()].sort((a, b) => a.round.n - b.round.n).map((c) => c.round);
2794
+ const newer = custom.filter((e) => e.customType === "loops-round" && e.data?.run === id && Number(e.data?.at ?? 0) > snapAt);
2795
+ const latest = newer.at(-1)?.data?.best;
2796
+ const winner = latest?.label && latest.round != null ? { ...base.best ?? {}, ...Object.fromEntries(Object.entries(latest).filter(([, v]) => v != null)) } : null;
2797
+ return {
2798
+ ...base,
2799
+ ...winner ? { best: winner } : {},
2800
+ id: String(base?.id ?? id),
2801
+ rounds: rebuilt
2802
+ };
2803
+ }
2804
+ var shotUrl = (runId, attemptName, file) => `/api/shot?run=${encodeURIComponent(runId)}&attempt=${encodeURIComponent(attemptName)}&f=${encodeURIComponent(file)}`;
2805
+ var archivedUrl = (runId, label, file) => file ? shotUrl(runId, label, file) : void 0;
2806
+ function runIds(entries) {
2807
+ const seen = [];
2808
+ for (const e of entries) {
2809
+ if (e.type !== "custom") continue;
2810
+ const id = e.customType === STATE_ENTRY ? e.data?.run ?? e.data?.state?.id : e.customType === "loops-run" ? e.data?.id : null;
2811
+ if (id && !seen.includes(String(id))) seen.push(String(id));
2812
+ }
2813
+ return seen;
2814
+ }
2815
+ function questionsOf(entries, now = Date.now()) {
2816
+ const answers = /* @__PURE__ */ new Map();
2817
+ for (const e of entries) if (e.type === "custom" && e.customType === "loops-answer" && e.data?.id) answers.set(String(e.data.id), { choice: String(e.data.choice ?? ""), at: Number(e.data.answeredAt ?? 0) });
2818
+ const byRun = /* @__PURE__ */ new Map();
2819
+ for (const e of entries) {
2820
+ if (e.type !== "custom" || e.customType !== "loops-question" || !e.data?.id) continue;
2821
+ const d = e.data;
2822
+ const answer = answers.get(String(d.id));
2823
+ const renamed = { "close-call": "close", veto: "veto", stall: "stall", apply: "apply", ask: "ask" };
2824
+ const q = {
2825
+ id: String(d.id),
2826
+ t: Number(d.createdAt ?? 0),
2827
+ round: d.round ?? void 0,
2828
+ kind: renamed[d.kind] ?? "ask",
2829
+ source: "loop",
2830
+ text: String(d.title ?? ""),
2831
+ detail: d.body ?? void 0,
2832
+ ...d.label ? { label: String(d.label) } : {},
2833
+ options: (d.options ?? []).map((o) => ({ label: typeof o === "string" ? o : String(o.label ?? "") })),
2834
+ ...answer ? { answered: { i: Math.max(0, (d.options ?? []).findIndex((o) => (typeof o === "string" ? o : o.label) === answer.choice)), t: answer.at } } : {},
2835
+ ...d.expiresAt && d.expiresAt < now && !answer ? { expired: true } : {}
2836
+ };
2837
+ const run3 = String(d.run ?? "");
2838
+ byRun.set(run3, [...byRun.get(run3) ?? [], q]);
2839
+ }
2840
+ return byRun;
2841
+ }
2842
+ function progressOf(entries, now = Date.now()) {
2843
+ const out = /* @__PURE__ */ new Map();
2844
+ for (const e of entries) {
2845
+ if (e.type !== "custom" || e.customType !== "loops-progress" || !e.data?.run) continue;
2846
+ const d = e.data;
2847
+ if (now - Number(d.at ?? 0) > 10 * 6e4) continue;
2848
+ out.set(String(d.run), { run: String(d.run), kind: String(d.kind ?? "visual"), round: d.round ?? null, phase: String(d.phase ?? ""), attempts: d.attempts ?? [], judge: d.judge ?? null, startedAt: Number(d.at ?? now) });
2849
+ }
2850
+ return out;
2851
+ }
2852
+ function buildRun({ cwd, id, entries, live }) {
2853
+ const mine = entries.filter((e) => e.type === "custom" && e.data?.run === id);
2854
+ const head = [...mine].reverse().find((e) => e.customType === "loops-run")?.data ?? {};
2855
+ const state = stateFromEntries(entries, id) ?? readState(cwd, id);
2856
+ const roundEntries = state?.rounds?.length ? state.rounds.map(roundOfEntry) : (() => {
2857
+ const byN = /* @__PURE__ */ new Map();
2858
+ for (const e of mine) if (e.customType === "loops-round" && e.data?.n) byN.set(Number(e.data.n), e.data);
2859
+ return [...byN.values()].sort((a, b) => (a.n ?? 0) - (b.n ?? 0));
2860
+ })();
2861
+ const shots = state?.shots ?? roundEntries.at(-1)?.shots ?? head.shots ?? [];
2862
+ const archived = {};
2863
+ for (const r of roundEntries) for (const [label, paths] of Object.entries(r.archived ?? {})) if (Array.isArray(paths) && paths.length) archived[label] = paths;
2864
+ for (const r of roundEntries) for (const a of r.attempts ?? []) if (a.shots?.length) archived[a.label] = a.shots;
2865
+ const unit = state?.metric?.unit ?? roundEntries.at(-1)?.metric?.unit ?? (head.kind === "bench" ? "ms" : "");
2866
+ const better = state?.metric?.better ?? roundEntries.at(-1)?.metric?.better ?? "lower";
2867
+ const baseCommit = state?.baseCommit ?? roundEntries.at(-1)?.baseCommit ?? head.baseCommit;
2868
+ const rules = state?.rules ?? roundEntries.at(-1)?.rules ?? [];
2869
+ const chosen = state?.best ?? {};
2870
+ const rounds = roundEntries.map((r) => {
2871
+ const attempts = (r.attempts ?? []).map((a, i) => {
2872
+ const score = r.scores?.[a.label] ?? a.bench?.value ?? void 0;
2873
+ const pick = chosen.round === r.n && chosen.label ? chosen.label : r.pick;
2874
+ const kept = pick === a.label;
2875
+ return {
2876
+ id: `${id}:${a.label}`,
2877
+ name: a.label,
2878
+ label: letters[i] ?? String(i + 1),
2879
+ model: pretty(a.model),
2880
+ style: a.style,
2881
+ status: a.status ?? "done",
2882
+ score,
2883
+ kept,
2884
+ humanPick: !!(kept && (r.human || chosen.round === r.n && !!chosen.label && chosen.label !== r.pick)),
2885
+ summary: a.summary || void 0,
2886
+ reason: r.reasons?.[a.label] || void 0,
2887
+ shot: archivedUrl(id, a.label, a.shots?.[0]) ?? archivedUrl(id, a.label, archived[a.label]?.[0]) ?? (shots.length && a.dir ? shotUrl(id, a.label, shots[0]) : void 0),
2888
+ tokens: a.tokens ?? void 0,
2889
+ cost: a.cost ?? void 0,
2890
+ hasSession: !!a.session,
2891
+ bench: a.bench ?? void 0,
2892
+ review: a.review ?? void 0,
2893
+ vetoed: a.review?.ok === false,
2894
+ unscored: !!(r.unseen ?? []).includes(a.label),
2895
+ dir: a.dir ?? void 0,
2896
+ commit: a.commit ?? void 0
2897
+ };
2898
+ });
2899
+ const current = r.scores?.CURRENT;
2900
+ const from = r.n > 1 ? { round: r.n - 1, label: "CURRENT" } : { round: 0, label: "baseline" };
2901
+ return {
2902
+ n: r.n,
2903
+ from,
2904
+ attempts,
2905
+ current: current != null || r.reasons?.CURRENT ? { score: current ?? void 0, reason: r.reasons?.CURRENT ?? void 0, shot: archivedUrl(id, "CURRENT", r.archived?.CURRENT?.[0]) ?? (shots.length ? shotUrl(id, "CURRENT", shots[0]) : void 0) } : void 0,
2906
+ pick: (chosen.round === r.n && chosen.label ? chosen.label : r.pick) ?? void 0,
2907
+ why: r.why ?? void 0,
2908
+ inProgress: false,
2909
+ shots: archived,
2910
+ sheet: r.sheet ? `/api/sheet?run=${encodeURIComponent(id)}&f=${encodeURIComponent(r.sheet)}` : void 0,
2911
+ judgeTokens: r.judgeTokens ?? void 0,
2912
+ judgeCost: r.judgeCost ?? void 0,
2913
+ startedAt: r.startedAt ?? void 0,
2914
+ endedAt: r.endedAt ?? void 0,
2915
+ inconclusive: !!r.inconclusive,
2916
+ unseen: r.unseen ?? [],
2917
+ ...r.escaped ? { escaped: r.escaped } : {}
2918
+ };
2919
+ });
2920
+ const lastStatus = state?.status ?? head.status ?? "done";
2921
+ let alive = false;
2922
+ if (live && live.run === id && lastStatus === "running") {
2923
+ alive = true;
2924
+ const n = live.round ?? rounds.length + 1;
2925
+ const attempts = (live.attempts ?? []).map((a, i) => ({
2926
+ id: `${id}:R${n}-${a.style}`,
2927
+ name: `R${n}-${a.style}`,
2928
+ label: letters[i] ?? String(i + 1),
2929
+ model: pretty(state?.models?.[a.style] ?? head.models?.[a.style]),
2930
+ style: a.style,
2931
+ status: a.status ?? "running",
2932
+ summary: a.text || void 0,
2933
+ hasSession: false,
2934
+ tokens: a.tokens || void 0
2935
+ }));
2936
+ const round = { n, from: { round: n - 1, label: "CURRENT" }, attempts, inProgress: true, judging: /judg/.test(live.phase ?? ""), why: void 0 };
2937
+ const at = rounds.findIndex((r) => r.n === n);
2938
+ if (at >= 0) rounds[at] = { ...rounds[at], inProgress: true, judging: round.judging };
2939
+ else rounds.push(round);
2940
+ }
2941
+ const bestRound = state?.best?.round ?? roundEntries.filter((r) => r.pick && r.pick !== "CURRENT").at(-1)?.n ?? 0;
2942
+ const bestEntry = roundEntries.filter((r) => r.n === bestRound).at(-1);
2943
+ const bestLabel = state?.best?.label ?? bestEntry?.best?.label ?? head.best ?? null;
2944
+ const bestScore = state?.best?.score ?? (bestLabel ? bestEntry?.scores?.[bestLabel] : void 0) ?? void 0;
2945
+ const scores = roundEntries.map((r) => (r.pick && r.pick !== "CURRENT" ? r.scores?.[r.pick] : r.scores?.CURRENT) ?? (r.scores?.CURRENT ?? null)).map((v) => typeof v === "number" ? v : null).filter((v) => v != null);
2946
+ const baseline = roundEntries[0]?.scores?.CURRENT ?? void 0;
2947
+ const log = [];
2948
+ const firstT = Number(roundEntries[0]?.startedAt ?? Date.parse(head.at ?? "") ?? Date.now());
2949
+ log.push({ t: Number.isFinite(firstT) ? firstT : Date.now(), kind: "start", text: `Started ${head.goal ?? state?.goal ?? ""}`.trim() });
2950
+ for (const r of roundEntries) {
2951
+ log.push({ t: Number(r.endedAt ?? r.at ?? Date.now()), kind: "judged", text: "", round: r.n, pick: r.pick ?? void 0, why: r.why ?? void 0, scores: r.scores ?? void 0 });
2952
+ }
2953
+ const wrote = state?.status ?? head.status ?? "done";
2954
+ const stalled = !alive && wrote === "running";
2955
+ const status = alive ? "running" : stalled ? "stalled" : wrote;
2956
+ if (!alive && (wrote === "done" || wrote === "aborted") && roundEntries.length) log.push({ t: Number(roundEntries.at(-1)?.endedAt ?? Date.now()), kind: "done", text: `finished after ${roundEntries.length} round(s)` });
2957
+ const tokens = roundEntries.reduce((sum, r) => sum + (r.attempts ?? []).reduce((s, a) => s + (a.tokens ?? 0), 0) + (r.judgeTokens ?? 0), 0) + (live ? (live.attempts ?? []).reduce((s, a) => s + (a.tokens ?? 0), 0) : 0);
2958
+ return {
2959
+ id,
2960
+ chat: head.chat ?? "",
2961
+ kind: head.kind ?? state?.kind ?? "visual",
2962
+ metric: unit ? { key: state?.metric?.key ?? "ms", unit, better } : void 0,
2963
+ baseline,
2964
+ name: head.name ?? goalName(state?.goal ?? head.goal ?? id),
2965
+ goal: state?.goal ?? head.goal ?? "",
2966
+ status: status === "aborted" ? "done" : status,
2967
+ alive,
2968
+ stopReason: stalled ? "no signal from the round \u2014 the process went away" : status === "aborted" ? "aborted" : void 0,
2969
+ rules: rules.map((text) => ({ text, source: "config" })),
2970
+ rounds,
2971
+ best: { round: bestRound, label: bestLabel ?? "base", score: bestScore, shot: bestLabel && shots.length ? shotUrl(id, bestLabel, shots[0]) : void 0, byHuman: !!(bestEntry && bestLabel && bestEntry.pick && bestEntry.pick !== bestLabel) || !!state?.best?.human },
2972
+ scores,
2973
+ maxRounds: Math.max(rounds.length, 1),
2974
+ tokens,
2975
+ log,
2976
+ pendingSteer: 0,
2977
+ pending: [],
2978
+ questions: [],
2979
+ cwd,
2980
+ baseCommit,
2981
+ editedBaseline: !!state?.editedBaseline,
2982
+ winnerFiles: state?.winner?.files ?? null
2983
+ };
2984
+ }
2985
+ function summarize(cwd, entries) {
2986
+ const ids = runIds(entries);
2987
+ const questions = questionsOf(entries);
2988
+ let open = 0, question, running = 0, lastT = 0, latest;
2989
+ for (const id of ids) {
2990
+ const mine = entries.filter((e) => e.type === "custom" && e.data?.run === id);
2991
+ const head = [...mine].reverse().find((e) => e.customType === "loops-run")?.data ?? {};
2992
+ const state = stateFromEntries(entries, id) ?? readState(cwd, id);
2993
+ const rounds = state?.rounds?.length ? state.rounds.map(roundOfEntry) : [...new Map(mine.filter((e) => e.customType === "loops-round" && e.data?.n).map((e) => [Number(e.data.n), e.data])).values()];
2994
+ const status = state?.status ?? head.status ?? "done";
2995
+ const seen = mine.filter((e) => e.customType === "loops-progress").map((e) => Number(e.data?.at ?? 0)).sort((a, b) => a - b).at(-1) ?? 0;
2996
+ const fresh = Date.now() - seen < 5 * 6e4;
2997
+ const alive = status === "running" && fresh;
2998
+ const stalled = status === "running" && !alive;
2999
+ if (alive) running++;
3000
+ const qs = (questions.get(id) ?? []).filter((q) => !q.answered && !q.expired);
3001
+ open += qs.length;
3002
+ if (qs.length && !question) question = { kind: qs[0].kind, round: qs[0].round, title: qs[0].text };
3003
+ const t = Number(rounds.at(-1)?.endedAt ?? rounds.at(-1)?.at ?? 0);
3004
+ if (t >= lastT) {
3005
+ lastT = t;
3006
+ const bestRound = state?.best?.round ?? rounds.filter((r) => r.pick && r.pick !== "CURRENT").at(-1)?.n;
3007
+ const bestEntry = rounds.find((r) => r.n === bestRound);
3008
+ latest = { name: goalName(state?.goal ?? head.goal ?? id), status: stalled ? "stalled" : status, kind: head.kind ?? state?.kind ?? "visual", score: state?.best?.score ?? (bestEntry?.pick ? bestEntry.scores?.[bestEntry.pick] : void 0), unit: state?.metric?.unit ?? rounds.at(-1)?.metric?.unit ?? "", rounds: rounds.length };
3009
+ }
3010
+ }
3011
+ return { loops: ids.length, running, open, question, lastT, latest };
3012
+ }
3013
+ function goalName(goal) {
3014
+ const words = goal.replace(/\s+/g, " ").trim().split(" ").slice(0, 4).join(" ");
3015
+ return words.length > 34 ? words.slice(0, 33) + "\u2026" : words || "loop";
3016
+ }
3017
+ function buildRuns({ cwd, entries, live }) {
3018
+ const questions = questionsOf(entries);
3019
+ const progress = progressOf(entries);
3020
+ return runIds(entries).map((id) => {
3021
+ const run3 = buildRun({ cwd, id, entries, live: live?.get(id) ?? progress.get(id) ?? null });
3022
+ run3.questions = questions.get(id) ?? [];
3023
+ return run3;
3024
+ });
3025
+ }
3026
+
3027
+ // server/chats.ts
3028
+ var toolLine = (name, args) => {
3029
+ const a = args ?? {};
3030
+ if (name === "bash") return `bash \xB7 ${String(a.command ?? "").split("\n")[0].slice(0, 90)}`;
3031
+ if (name === "read" || name === "write" || name === "edit") return `${name} \xB7 ${String(a.path ?? "").replace(process.cwd(), "")}`;
3032
+ if (name === "loop") return `loop \xB7 ${a.from ? `continue ${a.from}` : String(a.goal ?? "").slice(0, 70)}`;
3033
+ const first = Object.values(a).find((v) => typeof v === "string");
3034
+ return first ? `${name} \xB7 ${first.slice(0, 70)}` : name;
3035
+ };
3036
+ function autoNameFor(runs, sessionName, already) {
3037
+ if (already || sessionName || !runs.length) return null;
3038
+ const name = String(runs[0]?.name ?? "").trim();
3039
+ return name || null;
3040
+ }
3041
+ function itemsFromMessages(messages) {
3042
+ const items = [];
3043
+ const open = /* @__PURE__ */ new Map();
3044
+ for (const m of messages ?? []) {
3045
+ const ts = Number(m.timestamp ?? Date.now());
3046
+ if (m.role === "user") {
3047
+ const text = typeof m.content === "string" ? m.content : (m.content ?? []).filter((c) => c.type === "text").map((c) => c.text).join("\n");
3048
+ if (text?.trim()) items.push({ t: "user", ts, text: text.trim() });
3049
+ } else if (m.role === "assistant") {
3050
+ for (const c of m.content ?? []) {
3051
+ if (c.type === "text" && c.text?.trim()) items.push({ t: "text", ts, text: c.text.trim() });
3052
+ else if (c.type === "toolCall") {
3053
+ const item = { t: "tool", ts, cmd: toolLine(c.name, c.arguments) };
3054
+ items.push(item);
3055
+ if (c.id) open.set(c.id, item);
3056
+ }
3057
+ }
3058
+ } else if (m.role === "toolResult") {
3059
+ const item = open.get(m.toolCallId);
3060
+ if (item && item.t === "tool" && !item.out) {
3061
+ const text = (m.content ?? []).filter((c) => c.type === "text").map((c) => c.text).join("\n").trim();
3062
+ if (text) item.out = text.split("\n").find((l) => l.trim())?.slice(0, 140);
3063
+ }
3064
+ }
3065
+ }
3066
+ return items;
3067
+ }
3068
+ var Chat = class {
3069
+ id;
3070
+ options;
3071
+ pi;
3072
+ entries = [];
3073
+ cursor;
3074
+ items = [];
3075
+ live = null;
3076
+ liveLoops = /* @__PURE__ */ new Map();
3077
+ dialogs = [];
3078
+ notices = [];
3079
+ runs = [];
3080
+ model = null;
3081
+ started = false;
3082
+ refreshing = null;
3083
+ lastBroadcast = 0;
3084
+ stderr = "";
3085
+ file = null;
3086
+ sessionName = null;
3087
+ autoNamed = false;
3088
+ constructor(id, options) {
3089
+ this.id = id;
3090
+ this.options = options;
3091
+ this.model = options.model ?? null;
3092
+ this.pi = new PiRpc({
3093
+ command: options.piCommand,
3094
+ args: ["--session-dir", options.sessionDir, "--session-id", id, ...options.args ?? [], ...options.model ? ["--model", options.model] : []],
3095
+ cwd: options.cwd,
3096
+ onEvent: (event) => this.onEvent(event),
3097
+ onExit: (code) => {
3098
+ this.stderr = this.pi.stderrText;
3099
+ this.live = null;
3100
+ this.broadcast(true);
3101
+ if (code != null) this.touch();
3102
+ }
3103
+ });
3104
+ }
3105
+ get isUp() {
3106
+ return this.pi.running;
3107
+ }
3108
+ /** The newest session entry id: the cursor a client resumes from. */
3109
+ get entryCursor() {
3110
+ return this.cursor;
3111
+ }
3112
+ /** The repo this chat runs in. */
3113
+ get workspacePath() {
3114
+ return this.options.cwd;
3115
+ }
3116
+ /** The session file pi is writing, once it has one. */
3117
+ get sessionFile() {
3118
+ return this.file;
3119
+ }
3120
+ get busy() {
3121
+ return !!this.live?.busy;
3122
+ }
3123
+ touch() {
3124
+ try {
3125
+ this.options.onUpdate?.(this);
3126
+ } catch {
3127
+ }
3128
+ }
3129
+ async start() {
3130
+ if (this.started) return;
3131
+ this.started = true;
3132
+ await this.pi.start();
3133
+ this.pi.onUiRequest((request) => {
3134
+ if (["select", "confirm", "input", "editor"].includes(request.method)) this.dialogs.push(request);
3135
+ else if (request.method === "notify") {
3136
+ console.log(`[${this.id}] ${request.level ?? "info"}: ${request.message ?? ""}`);
3137
+ this.notices.push({ t: Date.now(), level: String(request.level ?? "info"), message: String(request.message ?? "") });
3138
+ this.notices = this.notices.slice(-20);
3139
+ }
3140
+ void this.refresh();
3141
+ this.broadcast(true);
3142
+ });
3143
+ if (!this.pi.running) {
3144
+ this.stderr = this.pi.stderrText;
3145
+ return;
3146
+ }
3147
+ await this.refresh(true);
3148
+ }
3149
+ async stop() {
3150
+ await this.pi.stop();
3151
+ }
3152
+ /** Re-read the session's entries (cursor-based) and messages, then rebuild the runs. */
3153
+ async refresh(full = false) {
3154
+ if (this.refreshing) return this.refreshing;
3155
+ this.refreshing = (async () => {
3156
+ try {
3157
+ if (full) this.cursor = void 0;
3158
+ const entries = await this.pi.send({ type: "get_entries", ...this.cursor ? { since: this.cursor } : {} });
3159
+ const got = entries.entries ?? [];
3160
+ if (this.cursor) this.entries = got.length ? [...this.entries, ...got] : this.entries;
3161
+ else this.entries = got;
3162
+ this.cursor = got.at(-1)?.id ?? this.cursor;
3163
+ const messages = await this.pi.send({ type: "get_messages" });
3164
+ if (process.env.LOOPS_UI_DEBUG) console.error(`[${this.id}] refresh: ${got.length} new entries, ${(messages.messages ?? []).map((m) => `${m.role}[${Array.isArray(m.content) ? m.content.map((c) => c.type).join("+") : typeof m.content}]`).join(" ")}`);
3165
+ this.items = itemsFromMessages(messages.messages ?? []);
3166
+ const state = await this.pi.send({ type: "get_state" }).catch(() => ({}));
3167
+ const st = state;
3168
+ if (st?.sessionName) this.sessionName = String(st.sessionName);
3169
+ if (st?.model?.id) this.model = `${st.model.provider ?? ""}/${st.model.id}`.replace(/^\//, "");
3170
+ this.runs = buildRuns({ cwd: this.options.cwd, entries: this.entries, live: this.liveLoops });
3171
+ const auto = autoNameFor(this.runs, this.sessionName, this.autoNamed);
3172
+ if (auto) {
3173
+ this.autoNamed = true;
3174
+ await this.rename(auto).catch(() => {
3175
+ });
3176
+ }
3177
+ } catch (e) {
3178
+ console.error(`[${this.id}] refresh failed:`, e.message ?? e);
3179
+ this.stderr = String(e.message ?? e);
3180
+ } finally {
3181
+ this.refreshing = null;
3182
+ this.broadcast(true);
3183
+ }
3184
+ })();
3185
+ return this.refreshing;
3186
+ }
3187
+ /** Rebuild just the runs (cheap): used while a round streams progress, so the canvas moves without re-reading messages. */
3188
+ rebuildRuns() {
3189
+ try {
3190
+ this.runs = buildRuns({ cwd: this.options.cwd, entries: this.entries, live: this.liveLoops });
3191
+ } catch {
3192
+ }
3193
+ }
3194
+ onEvent(event) {
3195
+ const type = event.type;
3196
+ if (type === "message_start" && event.message?.role === "assistant") {
3197
+ this.live = { busy: true, chat: this.id, startedAt: Date.now(), user: "", text: "", tools: [] };
3198
+ this.broadcast();
3199
+ } else if (type === "message_update") {
3200
+ const u = event.assistantMessageEvent;
3201
+ if (u?.type === "text_delta") {
3202
+ if (!this.live) this.live = { busy: true, chat: this.id, startedAt: Date.now(), user: "", text: "", tools: [] };
3203
+ this.live.text = (this.live.text ?? "") + (u.delta ?? "");
3204
+ this.broadcast();
3205
+ }
3206
+ } else if (type === "tool_execution_start") {
3207
+ if (!this.live) this.live = { busy: true, chat: this.id, startedAt: Date.now(), user: "", text: "", tools: [] };
3208
+ this.live.tools.push({ id: event.toolCallId, cmd: toolLine(event.toolName, event.args), done: false });
3209
+ if (event.toolName === "loop") this.live.text = "";
3210
+ this.broadcast();
3211
+ } else if (type === "tool_execution_update") {
3212
+ const details = event.partialResult?.details;
3213
+ if (event.toolName === "loop" && details?.run) {
3214
+ this.liveLoops.set(details.run, { run: details.run, kind: details.kind, round: details.round ?? null, phase: details.phase ?? "starting", attempts: details.attempts ?? [], judge: details.judge, spec: details.spec, startedAt: this.liveLoops.get(details.run)?.startedAt ?? Date.now() });
3215
+ this.rebuildRuns();
3216
+ this.broadcast();
3217
+ }
3218
+ } else if (type === "tool_execution_end") {
3219
+ const tool = this.live?.tools.find((t) => t.id === event.toolCallId);
3220
+ if (tool) tool.done = true;
3221
+ if (event.toolName === "loop") {
3222
+ this.liveLoops.clear();
3223
+ void this.refresh();
3224
+ }
3225
+ this.broadcast();
3226
+ } else if (type === "message_end") {
3227
+ void this.refresh();
3228
+ this.broadcast();
3229
+ } else if (type === "agent_settled" || type === "turn_end") {
3230
+ if (type === "agent_settled") this.live = null;
3231
+ void this.refresh();
3232
+ this.broadcast(true);
3233
+ } else if (type === "extension_ui_request") {
3234
+ } else if (type.startsWith("session_") || type === "compaction_start" || type === "compaction_end") {
3235
+ if (type === "session_idle" || type === "session_start") void this.refresh(true);
3236
+ }
3237
+ }
3238
+ /** Event + state push to every subscriber, coalesced: a streaming round emits hundreds of updates a second. */
3239
+ broadcast(force = false) {
3240
+ const now = Date.now();
3241
+ if (!force && now - this.lastBroadcast < 120) return;
3242
+ this.lastBroadcast = now;
3243
+ this.touch();
3244
+ }
3245
+ async prompt(text, behavior) {
3246
+ if (!this.live) this.live = { busy: true, chat: this.id, startedAt: Date.now(), user: text, text: "", tools: [] };
3247
+ this.broadcast(true);
3248
+ const r = await this.pi.prompt(text, behavior);
3249
+ setTimeout(() => void this.refresh(), 400);
3250
+ return r?.disposition ?? "started";
3251
+ }
3252
+ /** The child's own view of "am I busy": a turn that settled with no event reaching us must not strand the UI. */
3253
+ async settleIfIdle() {
3254
+ if (!this.live) return;
3255
+ try {
3256
+ const st = await this.pi.send({ type: "get_state" }, 5e3);
3257
+ if (st?.isStreaming === false && !st?.pendingMessageCount) {
3258
+ this.live = null;
3259
+ await this.refresh();
3260
+ }
3261
+ } catch {
3262
+ }
3263
+ }
3264
+ async answerUi(id, response) {
3265
+ this.dialogs = this.dialogs.filter((d) => d.id !== id);
3266
+ await this.pi.respondUi(id, response);
3267
+ this.broadcast(true);
3268
+ }
3269
+ async abort() {
3270
+ await this.pi.send({ type: "abort" }).catch(() => {
3271
+ });
3272
+ this.live = null;
3273
+ this.broadcast(true);
3274
+ }
3275
+ /** The newest session entry of a kind (`loops-doctor`, `loops-run`, …), for read-only views. */
3276
+ custom(type) {
3277
+ for (let i = this.entries.length - 1; i >= 0; i--) {
3278
+ const e = this.entries[i];
3279
+ if (e.type === "custom" && e.customType === type) return e.data ?? null;
3280
+ }
3281
+ return null;
3282
+ }
3283
+ /** Does this chat's session mention a run? Used to find a run's repo without the state-file index. */
3284
+ hasRun(run3) {
3285
+ return this.entries.some((e) => e.type === "custom" && (e.data?.run === run3 || e.customType === "loops-run" && e.data?.id === run3));
3286
+ }
3287
+ /** A run rebuilt from this chat's durable entries: the snapshot plus its rounds. */
3288
+ stateFor(run3) {
3289
+ return stateFromEntries(this.entries, run3);
3290
+ }
3291
+ /** The models this chat could run, and what each one can take (text only, or images too). */
3292
+ async availableModels() {
3293
+ try {
3294
+ const list = await this.pi.send({ type: "get_available_models" });
3295
+ return (list.models ?? []).map((m) => ({ id: `${m.provider}/${m.id}`, provider: m.provider, model: m.id, images: Array.isArray(m.input) ? m.input.includes("image") : null }));
3296
+ } catch {
3297
+ return [];
3298
+ }
3299
+ }
3300
+ async setModel(provider, model) {
3301
+ await this.pi.send({ type: "set_model", provider, modelId: model });
3302
+ this.model = `${provider}/${model}`;
3303
+ this.broadcast(true);
3304
+ }
3305
+ /** An attempt's transcript, straight from the session file the attempt forked into. */
3306
+ sessionItems(file) {
3307
+ try {
3308
+ const lines = fs2.readFileSync(file, "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l));
3309
+ const messages = lines.filter((e) => e.type === "message" && e.message).map((e) => e.message);
3310
+ return itemsFromMessages(messages);
3311
+ } catch {
3312
+ return [];
3313
+ }
3314
+ }
3315
+ /** Rename this chat: Pi stores it on the session, so it survives reloads and shows up in the TUI too. */
3316
+ async rename(name) {
3317
+ const clean = String(name ?? "").replace(/\s+/g, " ").trim().slice(0, 80);
3318
+ if (!clean) return;
3319
+ await this.pi.send({ type: "set_session_name", name: clean });
3320
+ this.sessionName = clean;
3321
+ this.broadcast(true);
3322
+ }
3323
+ get title() {
3324
+ if (this.sessionName) return this.sessionName;
3325
+ const name = [...this.entries].reverse().find((e) => e.type === "session_name" || e.type === "name");
3326
+ if (name?.name) return String(name.name);
3327
+ const firstUser = this.items.find((i) => i.t === "user");
3328
+ return firstUser ? firstUser.text.replace(/\s+/g, " ").slice(0, 46) : "New chat";
3329
+ }
3330
+ snapshot() {
3331
+ const runs = this.runs;
3332
+ return {
3333
+ chat: this.id,
3334
+ title: this.title,
3335
+ chats: [],
3336
+ items: this.items,
3337
+ live: this.live,
3338
+ runs,
3339
+ model: this.model,
3340
+ error: this.pi.running ? void 0 : this.stderr || void 0,
3341
+ questions: runs.flatMap((r) => r.questions),
3342
+ dialogs: this.dialogs,
3343
+ notices: this.notices.slice(-6),
3344
+ stderr: this.stderr || void 0
3345
+ };
3346
+ }
3347
+ };
3348
+ function listChats(sessionDir, cwd = process.cwd()) {
3349
+ let files = [];
3350
+ try {
3351
+ files = fs2.readdirSync(sessionDir).filter((f) => f.endsWith(".jsonl")).map((f) => {
3352
+ let summary;
3353
+ const full = path2.join(sessionDir, f);
3354
+ let title;
3355
+ let firstUser;
3356
+ const entries = [];
3357
+ try {
3358
+ for (const line of fs2.readFileSync(full, "utf8").split("\n")) {
3359
+ if (!line.trim()) continue;
3360
+ const e = JSON.parse(line);
3361
+ entries.push(e);
3362
+ if ((e.type === "session_name" || e.type === "name") && e.name) title = String(e.name);
3363
+ if (!firstUser && e.type === "message" && e.message?.role === "user") {
3364
+ const c = e.message.content;
3365
+ firstUser = typeof c === "string" ? c : (c ?? []).filter((x) => x.type === "text").map((x) => x.text).join(" ");
3366
+ }
3367
+ }
3368
+ } catch {
3369
+ }
3370
+ summary = summarize(cwd, entries);
3371
+ return { id: path2.basename(f, ".jsonl").replace(/^.*_/, ""), last: fs2.statSync(full).mtimeMs, title: title ?? (firstUser ? firstUser.replace(/\s+/g, " ").slice(0, 46) : void 0), summary };
3372
+ });
3373
+ } catch {
3374
+ return [];
3375
+ }
3376
+ return files.filter((f) => /^chat-/.test(f.id)).sort((a, b) => b.last - a.last).map((f) => ({ id: f.id, title: f.title ?? goalName("New chat"), ts: f.last, last: f.last, summary: f.summary }));
3377
+ }
3378
+ var ChatManager = class {
3379
+ chats = /* @__PURE__ */ new Map();
3380
+ listeners = /* @__PURE__ */ new Set();
3381
+ base;
3382
+ /** Where a chat lives. Set by the server from the workspace registry, which owns the persistence. */
3383
+ bind;
3384
+ constructor(options) {
3385
+ const { bind, ...base } = options;
3386
+ this.base = base;
3387
+ this.bind = bind;
3388
+ }
3389
+ onChange(fn) {
3390
+ this.listeners.add(fn);
3391
+ return () => {
3392
+ this.listeners.delete(fn);
3393
+ };
3394
+ }
3395
+ /** Chats in one workspace (or all of them, when no workspace is named). */
3396
+ list(ws) {
3397
+ const chats = listChats(ws?.sessionDir ?? "", ws?.path ?? process.cwd());
3398
+ return chats.map((c) => ({ ...c, ws: ws?.id }));
3399
+ }
3400
+ get(id) {
3401
+ return this.chats.get(id) ?? null;
3402
+ }
3403
+ async open(id) {
3404
+ const existing = this.chats.get(id);
3405
+ if (existing?.isUp) {
3406
+ await existing.start();
3407
+ return existing;
3408
+ }
3409
+ const where = this.bind(id);
3410
+ const chat = new Chat(id, { ...this.base, ...where, onUpdate: (c) => {
3411
+ for (const fn of this.listeners) {
3412
+ try {
3413
+ fn(c);
3414
+ } catch {
3415
+ }
3416
+ }
3417
+ } });
3418
+ this.chats.set(id, chat);
3419
+ await chat.start();
3420
+ return chat;
3421
+ }
3422
+ async close(id) {
3423
+ const chat = this.chats.get(id);
3424
+ this.chats.delete(id);
3425
+ await chat?.stop();
3426
+ }
3427
+ async closeAll() {
3428
+ await Promise.all([...this.chats.values()].map((c) => c.stop()));
3429
+ this.chats.clear();
3430
+ }
3431
+ openChats() {
3432
+ return [...this.chats.values()];
3433
+ }
3434
+ /** The workspace a live chat is running in (for artifact routes that only know the chat). */
3435
+ cwdOf(chat) {
3436
+ return this.chats.get(chat)?.workspacePath ?? null;
3437
+ }
3438
+ /** The open chat whose session mentions this run, for routes that only get a run id. */
3439
+ findRun(run3) {
3440
+ for (const chat of this.chats.values()) if (chat.hasRun(run3)) return chat;
3441
+ return null;
3442
+ }
3443
+ };
3444
+
3445
+ // server/live.ts
3446
+ import fs3 from "node:fs";
3447
+ import net from "node:net";
3448
+ import path3 from "node:path";
3449
+ import { spawn as spawn2 } from "node:child_process";
3450
+ var lives = /* @__PURE__ */ new Map();
3451
+ var IDLE_MS = 10 * 6e4;
3452
+ function serveCommand(cwd, agentDir2 = process.env.PI_AGENT_DIR ?? path3.join(process.env.HOME ?? "", ".pi", "agent")) {
3453
+ for (const f of [path3.join(cwd, ".pi", "loops.json"), path3.join(agentDir2, "loops.json")]) {
3454
+ try {
3455
+ const j = JSON.parse(fs3.readFileSync(f, "utf8"));
3456
+ if (typeof j?.serve === "string" && j.serve.trim()) return j.serve.trim();
3457
+ } catch {
3458
+ }
3459
+ }
3460
+ return null;
3461
+ }
3462
+ var freePort = () => new Promise((resolve, reject) => {
3463
+ const s = net.createServer();
3464
+ s.unref();
3465
+ s.on("error", reject);
3466
+ s.listen(0, "127.0.0.1", () => {
3467
+ const addr = s.address();
3468
+ const port = typeof addr === "object" && addr ? addr.port : 0;
3469
+ s.close(() => resolve(port));
3470
+ });
3471
+ });
3472
+ var reachable = (port, timeout = 700) => new Promise((resolve) => {
3473
+ const sock = net.connect({ port, host: "127.0.0.1" });
3474
+ const done = (ok) => {
3475
+ sock.destroy();
3476
+ resolve(ok);
3477
+ };
3478
+ sock.setTimeout(timeout);
3479
+ sock.on("connect", () => done(true));
3480
+ sock.on("timeout", () => done(false));
3481
+ sock.on("error", () => done(false));
3482
+ });
3483
+ var kill = (live) => {
3484
+ const pid = live.child.pid;
3485
+ if (pid) {
3486
+ try {
3487
+ process.kill(-pid, "SIGTERM");
3488
+ } catch {
3489
+ try {
3490
+ live.child.kill("SIGTERM");
3491
+ } catch {
3492
+ }
3493
+ }
3494
+ }
3495
+ setTimeout(() => {
3496
+ if (pid) {
3497
+ try {
3498
+ process.kill(-pid, "SIGKILL");
3499
+ } catch {
3500
+ }
3501
+ }
3502
+ }, 1500).unref();
3503
+ };
3504
+ var liveUrl = (run3) => {
3505
+ const live = lives.get(run3);
3506
+ if (live) live.usedAt = Date.now();
3507
+ return live?.url;
3508
+ };
3509
+ async function startLive({ cwd, run: run3, state: given }) {
3510
+ const existing = lives.get(run3);
3511
+ if (existing) {
3512
+ existing.usedAt = Date.now();
3513
+ return { url: existing.url, reused: true };
3514
+ }
3515
+ const state = given ?? readState(cwd, run3);
3516
+ if (!state) throw new Error(`no run ${run3}`);
3517
+ const dir = state.best?.dir ?? null;
3518
+ if (!dir) throw new Error(`${state.best?.label ?? "the winner"} has no worktree left (the run was cleaned up) \u2014 nothing to serve`);
3519
+ const serve = serveCommand(cwd);
3520
+ if (!serve) throw new Error("this repo has no `serve` in .pi/loops.json \u2014 there is no app to run (visual loops that only write files are judged on their screenshots)");
3521
+ const workdir = path3.join(cwd, dir);
3522
+ if (!fs3.existsSync(workdir)) throw new Error(`${dir} is gone \u2014 the run was cleaned up`);
3523
+ const port = await freePort();
3524
+ const log = path3.join(cwd, ".pi", "loops-ui", `live-${port}.log`);
3525
+ fs3.mkdirSync(path3.dirname(log), { recursive: true });
3526
+ const fd = fs3.openSync(log, "a");
3527
+ const child = spawn2("sh", ["-c", serve], { cwd: workdir, env: { ...process.env, PORT: String(port), HOST: "127.0.0.1" }, stdio: ["ignore", fd, fd], detached: true });
3528
+ fs3.closeSync(fd);
3529
+ const live = { run: run3, port, url: `http://localhost:${port}/`, child, startedAt: Date.now(), usedAt: Date.now() };
3530
+ lives.set(run3, live);
3531
+ let dead = false;
3532
+ child.on("exit", () => {
3533
+ dead = true;
3534
+ });
3535
+ const deadline = Date.now() + 6e4;
3536
+ while (Date.now() < deadline) {
3537
+ if (dead) break;
3538
+ if (await reachable(port)) return { url: live.url };
3539
+ await new Promise((r) => setTimeout(r, 400));
3540
+ }
3541
+ lives.delete(run3);
3542
+ kill(live);
3543
+ let tail = "";
3544
+ try {
3545
+ tail = fs3.readFileSync(log, "utf8").split("\n").filter(Boolean).slice(-3).join(" \xB7 ").slice(-300);
3546
+ } catch {
3547
+ }
3548
+ throw new Error(dead || !tail ? `\`${serve}\` did not come up on :${port}${tail ? ` \u2014 ${tail}` : ""}` : `\`${serve}\` is running but nothing answered on :${port} yet`);
3549
+ }
3550
+ function stopLive(run3) {
3551
+ const live = lives.get(run3);
3552
+ if (!live) return false;
3553
+ kill(live);
3554
+ lives.delete(run3);
3555
+ return true;
3556
+ }
3557
+ function stopAllLive() {
3558
+ for (const [run3] of lives) stopLive(run3);
3559
+ }
3560
+ setInterval(() => {
3561
+ for (const [run3, live] of lives) if (Date.now() - live.usedAt > IDLE_MS) stopLive(run3);
3562
+ }, 6e4).unref();
3563
+ for (const sig of ["SIGINT", "SIGTERM"]) process.on(sig, () => {
3564
+ stopAllLive();
3565
+ process.exit(0);
3566
+ });
3567
+ process.on("exit", () => stopAllLive());
3568
+
3569
+ // ../pi-loops/lib/config.ts
3570
+ import fs5 from "node:fs";
3571
+ import os2 from "node:os";
3572
+ import net2 from "node:net";
3573
+ import path5 from "node:path";
3574
+ import { spawn as spawn4 } from "node:child_process";
3575
+
3576
+ // ../pi-loops/lib/shot.ts
3577
+ import { spawn as spawn3 } from "node:child_process";
3578
+ import fs4 from "node:fs";
3579
+ import os from "node:os";
3580
+ import path4 from "node:path";
3581
+ var NAMES = [
3582
+ "google-chrome",
3583
+ "google-chrome-stable",
3584
+ "chromium",
3585
+ "chromium-browser",
3586
+ "chrome",
3587
+ "brave-browser",
3588
+ "microsoft-edge",
3589
+ "chrome-headless-shell",
3590
+ "headless-shell",
3591
+ "headless_shell"
3592
+ ];
3593
+ var PATHS = [
3594
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
3595
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
3596
+ "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser",
3597
+ "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
3598
+ "/headless-shell/headless-shell",
3599
+ // exe.dev VMs ship the headless shell Shelley drives here
3600
+ "/usr/lib/chromium/chromium",
3601
+ "/snap/bin/chromium",
3602
+ "/opt/google/chrome/chrome"
3603
+ ];
3604
+ var which = (cmd) => {
3605
+ for (const dir of (process.env.PATH ?? "").split(path4.delimiter)) {
3606
+ const p = path4.join(dir, cmd);
3607
+ if (fs4.existsSync(p)) return p;
3608
+ }
3609
+ return null;
3610
+ };
3611
+ var isPath = (c) => c.includes("/");
3612
+ function playwrightShells() {
3613
+ const root = process.env.PLAYWRIGHT_BROWSERS_PATH || path4.join(os.homedir(), ".cache", "ms-playwright");
3614
+ let entries;
3615
+ try {
3616
+ entries = fs4.readdirSync(root);
3617
+ } catch {
3618
+ return [];
3619
+ }
3620
+ const found = [];
3621
+ for (const e of entries.sort().reverse()) {
3622
+ if (e.startsWith("chromium_headless_shell-")) found.push(path4.join(root, e, "chrome-headless-shell-linux64", "chrome-headless-shell"), path4.join(root, e, "chrome-headless-shell-mac-arm64", "chrome-headless-shell"), path4.join(root, e, "chrome-headless-shell-mac-x64", "chrome-headless-shell"));
3623
+ else if (e.startsWith("chromium-")) found.push(path4.join(root, e, "chrome-linux", "chrome"), path4.join(root, e, "chrome-mac", "Chromium.app", "Contents", "MacOS", "Chromium"));
3624
+ }
3625
+ return found;
3626
+ }
3627
+ function chromeCandidates(explicit) {
3628
+ const named = [explicit, process.env.LOOPS_CHROME, process.env.CHROME, process.env.PUPPETEER_EXECUTABLE_PATH].filter((c) => !!c);
3629
+ const fromNames = NAMES.map(which).filter((p) => !!p);
3630
+ return [...named, ...fromNames, ...PATHS, ...playwrightShells()];
3631
+ }
3632
+ function findChrome(explicit) {
3633
+ for (const c of chromeCandidates(explicit)) {
3634
+ if (isPath(c)) {
3635
+ if (fs4.existsSync(c)) return c;
3636
+ continue;
3637
+ }
3638
+ const p = which(c);
3639
+ if (p) return p;
3640
+ }
3641
+ throw new Error("no Chrome/Chromium found \u2014 visual mode screenshots routes with headless Chrome. Any Chromium works: install one, `npx playwright install chromium-headless-shell` puts one where loops looks (~/.cache/ms-playwright), or point LOOPS_CHROME at a binary, e.g. LOOPS_CHROME=/usr/bin/chromium");
3642
+ }
3643
+ async function connect(wsUrl) {
3644
+ const sock = new WebSocket(wsUrl);
3645
+ const pending = /* @__PURE__ */ new Map();
3646
+ const listeners = /* @__PURE__ */ new Map();
3647
+ let id = 0;
3648
+ sock.addEventListener("message", (e) => {
3649
+ const m = JSON.parse(String(e.data));
3650
+ if (m.id) {
3651
+ const p = pending.get(m.id);
3652
+ if (!p) return;
3653
+ pending.delete(m.id);
3654
+ if (m.error) p.fail(new Error(m.error.message));
3655
+ else p.ok(m.result);
3656
+ return;
3657
+ }
3658
+ for (const fn of listeners.get(m.method) ?? []) {
3659
+ try {
3660
+ fn(m.params);
3661
+ } catch {
3662
+ }
3663
+ }
3664
+ });
3665
+ await new Promise((res, rej) => {
3666
+ sock.addEventListener("open", () => res());
3667
+ sock.addEventListener("error", () => rej(new Error("could not connect to the browser's DevTools endpoint")));
3668
+ });
3669
+ const send = (method, params = {}, sessionId) => new Promise((ok, fail) => {
3670
+ const n = ++id;
3671
+ pending.set(n, { ok, fail });
3672
+ sock.send(JSON.stringify({ id: n, method, params, ...sessionId ? { sessionId } : {} }));
3673
+ });
3674
+ return {
3675
+ send,
3676
+ close: () => {
3677
+ try {
3678
+ sock.close();
3679
+ } catch {
3680
+ }
3681
+ },
3682
+ on: (method, fn) => {
3683
+ const s = listeners.get(method) ?? /* @__PURE__ */ new Set();
3684
+ s.add(fn);
3685
+ listeners.set(method, s);
3686
+ return () => {
3687
+ s.delete(fn);
3688
+ };
3689
+ }
3690
+ };
3691
+ }
3692
+ function launch(bin) {
3693
+ const child = spawn3(bin, [
3694
+ "--headless=new",
3695
+ "--no-sandbox",
3696
+ "--disable-gpu",
3697
+ "--hide-scrollbars",
3698
+ "--disable-dev-shm-usage",
3699
+ "--remote-debugging-port=0",
3700
+ "about:blank"
3701
+ ], { stdio: ["ignore", "ignore", "pipe"], detached: true });
3702
+ const endpoint = new Promise((res, rej) => {
3703
+ let buf = "";
3704
+ const t = setTimeout(() => rej(new Error(`the browser did not open a DevTools endpoint: ${buf.split("\n").filter((l) => !/dbus|gpu|vulkan|fontconfig/i.test(l)).slice(-2).join(" ").slice(0, 240)}`)), 3e4);
3705
+ child.stderr?.on("data", (d) => {
3706
+ buf += String(d);
3707
+ const m = buf.match(/DevTools listening on (ws:\/\/\S+)/);
3708
+ if (m) {
3709
+ clearTimeout(t);
3710
+ res(m[1]);
3711
+ }
3712
+ });
3713
+ child.on("exit", (code) => {
3714
+ clearTimeout(t);
3715
+ rej(new Error(`the browser exited (${code}) before it was ready`));
3716
+ });
3717
+ });
3718
+ return { child, endpoint };
3719
+ }
3720
+ var kill2 = (child) => {
3721
+ const pid = child.pid;
3722
+ if (!pid) return;
3723
+ try {
3724
+ process.kill(-pid, "SIGTERM");
3725
+ } catch {
3726
+ try {
3727
+ child.kill("SIGTERM");
3728
+ } catch {
3729
+ }
3730
+ }
3731
+ setTimeout(() => {
3732
+ try {
3733
+ process.kill(-pid, "SIGKILL");
3734
+ } catch {
3735
+ }
3736
+ }, 1500).unref();
3737
+ };
3738
+ async function boxOf(to, selector) {
3739
+ await to("DOM.enable");
3740
+ const { root } = await to("DOM.getDocument", { depth: -1 });
3741
+ const { nodeId } = await to("DOM.querySelector", { nodeId: root.nodeId, selector });
3742
+ if (!nodeId) throw new Error(`no element matches ${selector}`);
3743
+ const { model } = await to("DOM.getBoxModel", { nodeId });
3744
+ const [x1, y1, , , x2, , , y2] = model.border;
3745
+ return { x: x1, y: y1, width: Math.max(x2 - x1, 1), height: Math.max(y2 - y1, 1) };
3746
+ }
3747
+ var MAX_HEIGHT = 12e3;
3748
+ async function capture({ url, out, width = 1440, height = 900, wait = 1500, loadTimeout = 30, viewport = false, selector, chrome, cwd = process.cwd() }) {
3749
+ const bin = findChrome(chrome);
3750
+ const { child, endpoint } = launch(bin);
3751
+ let cdp = null;
3752
+ try {
3753
+ cdp = await connect(await endpoint);
3754
+ const { targetId } = await cdp.send("Target.createTarget", { url: "about:blank" });
3755
+ const { sessionId } = await cdp.send("Target.attachToTarget", { targetId, flatten: true });
3756
+ const to = (method, params = {}) => cdp.send(method, params, sessionId);
3757
+ await to("Page.enable");
3758
+ await to("Network.enable");
3759
+ await to("Emulation.setDeviceMetricsOverride", { width, height, deviceScaleFactor: 1, mobile: false });
3760
+ const failures = [];
3761
+ let loaded = false;
3762
+ cdp.on("Page.loadEventFired", () => {
3763
+ loaded = true;
3764
+ });
3765
+ cdp.on("Network.loadingFailed", (p) => {
3766
+ if (p?.type === "Document") failures.push(p.errorText ?? "the document failed to load");
3767
+ });
3768
+ cdp.on("Network.responseReceived", (p) => {
3769
+ if (p?.type === "Document" && p.response?.status >= 400) failures.push(`HTTP ${p.response.status}`);
3770
+ });
3771
+ const nav = await to("Page.navigate", { url });
3772
+ if (nav?.errorText) failures.push(nav.errorText);
3773
+ for (const t0 = Date.now(); !loaded && !failures.length && Date.now() - t0 < loadTimeout * 1e3; ) await new Promise((r) => setTimeout(r, 100));
3774
+ if (wait) await new Promise((r) => setTimeout(r, wait));
3775
+ if (failures.length) throw new Error(`${url}: ${failures[0]}`);
3776
+ const layout = await to("Page.getLayoutMetrics");
3777
+ const pageSize = layout.cssContentSize ?? layout.contentSize;
3778
+ const clip = selector ? await boxOf(to, selector) : viewport ? { x: 0, y: 0, width, height } : { x: 0, y: 0, width: Math.max(Math.ceil(pageSize.width), width), height: Math.min(Math.max(Math.ceil(pageSize.height), height), MAX_HEIGHT) };
3779
+ const { data } = await to("Page.captureScreenshot", { format: "png", captureBeyondViewport: true, fromSurface: true, clip: { ...clip, scale: 1 } });
3780
+ const file = path4.resolve(cwd, out);
3781
+ fs4.mkdirSync(path4.dirname(file), { recursive: true });
3782
+ fs4.writeFileSync(file, Buffer.from(data, "base64"));
3783
+ return file;
3784
+ } finally {
3785
+ cdp?.close();
3786
+ kill2(child);
3787
+ }
3788
+ }
3789
+ var CANARY_ALPHABET = "ACDEFGHJKLPRTUVWXY34679";
3790
+ function canaryCode(random = Math.random, len = 4) {
3791
+ let out = "";
3792
+ for (let i = 0; i < len; i++) out += CANARY_ALPHABET[Math.floor(random() * CANARY_ALPHABET.length)] ?? "A";
3793
+ return out;
3794
+ }
3795
+ async function canaryImage({ code, out, chrome, cwd = process.cwd() }) {
3796
+ const html = `<!doctype html><meta charset="utf-8"><style>
3797
+ html,body{margin:0;width:360px;height:140px;background:#fff;display:flex;align-items:center;justify-content:center}
3798
+ p{margin:0;font:800 64px/1 ui-monospace,SFMono-Regular,monospace;letter-spacing:10px;color:#111}
3799
+ </style><p>${code}</p>`;
3800
+ return capture({ url: `data:text/html;charset=utf-8,${encodeURIComponent(html)}`, out, width: 360, height: 140, wait: 100, chrome, cwd });
3801
+ }
3802
+ if (false) {
3803
+ shot({ ...parseArgs(process.argv.slice(2)), log: (m) => console.error(m) }).then((f) => {
3804
+ console.log(f);
3805
+ }).catch((e) => {
3806
+ console.error(`shot: ${e.message}`);
3807
+ process.exit(1);
3808
+ });
3809
+ }
3810
+
3811
+ // ../pi-loops/lib/judge.ts
3812
+ var normCode = (v) => String(v ?? "").toUpperCase().replace(/[^A-Z0-9]/g, "");
3813
+ function sameCode(expected, said) {
3814
+ const a = normCode(expected), b = normCode(said);
3815
+ if (!a || !b) return false;
3816
+ if (a === b) return true;
3817
+ if (a.length < 4 || Math.abs(a.length - b.length) > 1) return false;
3818
+ let edits = 0;
3819
+ for (let i = 0, j = 0; (i < a.length || j < b.length) && edits <= 1; ) {
3820
+ if (a[i] === b[j]) {
3821
+ i++;
3822
+ j++;
3823
+ continue;
3824
+ }
3825
+ edits++;
3826
+ if (a.length > b.length) i++;
3827
+ else if (b.length > a.length) j++;
3828
+ else {
3829
+ i++;
3830
+ j++;
3831
+ }
3832
+ }
3833
+ return edits <= 1;
3834
+ }
3835
+
3836
+ // ../pi-loops/lib/config.ts
3837
+ var CONFIG_DEFAULTS = { attempts: 3, rounds: 1, timeoutMin: 15, tokenBudget: null, repeat: 2, minGain: 0.05, judgeSamples: 3, judgePairs: 2, judgePanel: true, council: true, models: {} };
3838
+ var SETUP = ["serve", "check", "bench", "metric", "protect"];
3839
+ var readJson = (f) => {
3840
+ try {
3841
+ return JSON.parse(fs5.readFileSync(f, "utf8"));
3842
+ } catch {
3843
+ return null;
3844
+ }
3845
+ };
3846
+ var agentDir = () => process.env.PI_AGENT_DIR ?? path5.join(os2.homedir(), ".pi", "agent");
3847
+ var configFiles = (cwd, dir = agentDir()) => ({ user: path5.join(dir, "loops.json"), project: path5.join(cwd, ".pi", "loops.json") });
3848
+ function settingsWithSources({ cwd, pi, agentDir: dir }) {
3849
+ const dirAbs = dir ?? agentDir();
3850
+ const out = {};
3851
+ for (const [k, v] of Object.entries(CONFIG_DEFAULTS)) out[k] = { value: v, source: "default" };
3852
+ const apply = (j, source) => {
3853
+ for (const [k, v] of Object.entries(j ?? {})) {
3854
+ if (k === "models") {
3855
+ out.models = { value: { ...out.models?.value ?? {}, ...v ?? {} }, source };
3856
+ continue;
3857
+ }
3858
+ out[k] = { value: v, source };
3859
+ }
3860
+ };
3861
+ for (const f of [path5.join(dirAbs, "settings.json"), path5.join(cwd, ".pi", "settings.json")]) {
3862
+ try {
3863
+ apply(readJson(f)?.loops ?? {}, "settings.json:loops");
3864
+ } catch {
3865
+ }
3866
+ }
3867
+ try {
3868
+ apply(pi?.getSettings?.()?.loops ?? {}, "settings.json:loops");
3869
+ } catch {
3870
+ }
3871
+ const { user, project } = configFiles(cwd, dirAbs);
3872
+ try {
3873
+ apply(readJson(user) ?? {}, "~/.pi/agent/loops.json");
3874
+ } catch {
3875
+ }
3876
+ try {
3877
+ apply(readJson(project) ?? {}, ".pi/loops.json");
3878
+ } catch {
3879
+ }
3880
+ return out;
3881
+ }
3882
+ function effectiveConfig(cwd, dir = agentDir(), pi) {
3883
+ const sourced = settingsWithSources({ cwd, pi, agentDir: dir });
3884
+ const project = configFiles(cwd, dir).project;
3885
+ return Object.entries(sourced).map(([key, s]) => {
3886
+ const source = s.source === "default" ? "default" : s.source === ".pi/loops.json" ? "project" : "user";
3887
+ return { key, value: s.value, source, ...s.source === "default" ? {} : { file: s.source === project ? path5.relative(cwd, project) : s.source } };
3888
+ }).sort((a, b) => SETUP.indexOf(a.key) - SETUP.indexOf(b.key) || a.key.localeCompare(b.key));
3889
+ }
3890
+ var selfWriting = false;
3891
+ var isSelfWriting = () => selfWriting;
3892
+ var lastSelfWrite = null;
3893
+ var isSelfWrite = (raw2) => lastSelfWrite !== null && raw2 === lastSelfWrite;
3894
+ var writeRaw = (file, json) => {
3895
+ const raw2 = JSON.stringify(json, null, 2) + "\n";
3896
+ selfWriting = true;
3897
+ try {
3898
+ fs5.mkdirSync(path5.dirname(file), { recursive: true });
3899
+ fs5.writeFileSync(file, raw2);
3900
+ lastSelfWrite = raw2;
3901
+ } finally {
3902
+ setTimeout(() => {
3903
+ selfWriting = false;
3904
+ }, 80);
3905
+ }
3906
+ };
3907
+ function writeSetting(cwd, key, value) {
3908
+ if (!/^[a-zA-Z][\w-]*$/.test(key) || key === "models") throw new Error(`cannot set "${key}" from here${key === "models" ? " \u2014 use /loop models" : ""}`);
3909
+ const file = configFiles(cwd).project;
3910
+ const cur = readJson(file) ?? {};
3911
+ const next = { ...cur, [key]: value === "" ? null : value };
3912
+ for (const k of Object.keys(next)) if (next[k] === null) delete next[k];
3913
+ writeRaw(file, next);
3914
+ }
3915
+ var WATCHED_KEYS = ["serve", "check", "bench", "metric", "protect", "attempts", "rounds", "judgeSamples", "judgePairs", "tokenBudget", "models"];
3916
+ var short = (v) => v === void 0 ? "none" : JSON.stringify(v);
3917
+ function diffConfig(before, after) {
3918
+ const keys = [.../* @__PURE__ */ new Set([...Object.keys(before ?? {}), ...Object.keys(after ?? {})])].filter((k) => k === "models" || WATCHED_KEYS.includes(k));
3919
+ return keys.map((key) => ({ key, from: short(before?.[key]), to: short(after?.[key]) })).filter((c) => c.from !== c.to);
3920
+ }
3921
+ function restoreConfig(cwd, before) {
3922
+ const file = configFiles(cwd).project;
3923
+ if (before && Object.keys(before).length) {
3924
+ writeRaw(file, before);
3925
+ return;
3926
+ }
3927
+ selfWriting = true;
3928
+ try {
3929
+ fs5.rmSync(file, { force: true });
3930
+ lastSelfWrite = "";
3931
+ } finally {
3932
+ setTimeout(() => {
3933
+ selfWriting = false;
3934
+ }, 80);
3935
+ }
3936
+ }
3937
+ function acceptConfig(cwd, after) {
3938
+ writeRaw(configFiles(cwd).project, after);
3939
+ }
3940
+ var freePort2 = () => new Promise((resolve, reject) => {
3941
+ const s = net2.createServer();
3942
+ s.unref();
3943
+ s.on("error", reject);
3944
+ s.listen(0, "127.0.0.1", () => {
3945
+ const a = s.address();
3946
+ const port = typeof a === "object" && a ? a.port : 0;
3947
+ s.close(() => resolve(port));
3948
+ });
3949
+ });
3950
+ var reachable2 = (port, timeout = 600) => new Promise((resolve) => {
3951
+ const sock = net2.connect({ port, host: "127.0.0.1" });
3952
+ const done = (ok) => {
3953
+ sock.destroy();
3954
+ resolve(ok);
3955
+ };
3956
+ sock.setTimeout(timeout);
3957
+ sock.on("connect", () => done(true));
3958
+ sock.on("timeout", () => done(false));
3959
+ sock.on("error", () => done(false));
3960
+ });
3961
+ var run2 = (cmd, args, opts) => new Promise((resolve) => {
3962
+ const started = Date.now();
3963
+ const limit = opts.timeout ?? 12e4;
3964
+ const child = spawn4(cmd, args, { cwd: opts.cwd, env: { ...process.env, ...opts.env ?? {} }, stdio: ["ignore", "pipe", "pipe"], detached: false });
3965
+ let out = "";
3966
+ let timedOut = false;
3967
+ const timer = setTimeout(() => {
3968
+ timedOut = true;
3969
+ try {
3970
+ child.kill("SIGKILL");
3971
+ } catch {
3972
+ }
3973
+ }, limit);
3974
+ child.stdout?.on("data", (d) => {
3975
+ out += d.toString();
3976
+ if (out.length > 1 << 23) out = out.slice(-(1 << 23));
3977
+ });
3978
+ child.stderr?.on("data", (d) => {
3979
+ out += d.toString();
3980
+ if (out.length > 1 << 23) out = out.slice(-(1 << 23));
3981
+ });
3982
+ child.on("error", (e) => {
3983
+ clearTimeout(timer);
3984
+ resolve({ code: 1, out: `${out}
3985
+ ${String(e)}`.trim(), timedOut });
3986
+ });
3987
+ child.on("close", (code) => {
3988
+ clearTimeout(timer);
3989
+ resolve({ code: code ?? 1, out: out.trim(), timedOut: timedOut || Date.now() - started >= limit });
3990
+ });
3991
+ });
3992
+ async function serveCheck(cwd, serve) {
3993
+ const t0 = Date.now();
3994
+ const port = await freePort2();
3995
+ const child = spawn4("sh", ["-c", serve], { cwd, env: { ...process.env, PORT: String(port) }, stdio: ["ignore", "pipe", "pipe"], detached: true });
3996
+ let log = "";
3997
+ child.stdout?.on("data", (d) => {
3998
+ log += d.toString();
3999
+ });
4000
+ child.stderr?.on("data", (d) => {
4001
+ log += d.toString();
4002
+ });
4003
+ let dead = false;
4004
+ child.on("exit", () => {
4005
+ dead = true;
4006
+ });
4007
+ const deadline = Date.now() + 45e3;
4008
+ let ok = false;
4009
+ while (!dead && Date.now() < deadline) {
4010
+ if (await reachable2(port)) {
4011
+ ok = true;
4012
+ break;
4013
+ }
4014
+ await new Promise((r) => setTimeout(r, 400));
4015
+ }
4016
+ if (child.pid) {
4017
+ try {
4018
+ process.kill(-child.pid, "SIGTERM");
4019
+ } catch {
4020
+ }
4021
+ setTimeout(() => {
4022
+ try {
4023
+ process.kill(-child.pid, "SIGKILL");
4024
+ } catch {
4025
+ }
4026
+ }, 800).unref();
4027
+ }
4028
+ const tail = log.split("\n").filter(Boolean).slice(-2).join(" \xB7 ").slice(-160);
4029
+ return { name: "serve", ok, detail: ok ? `booted on :${port}` : dead ? `exited \u2014 ${tail || "no output"}` : `nothing answered on :${port} in 45s${tail ? ` \u2014 ${tail}` : ""}`, ms: Date.now() - t0, fatal: true };
4030
+ }
4031
+ async function checkCheck(cwd, check) {
4032
+ const t0 = Date.now();
4033
+ const r = await run2("sh", ["-c", check], { cwd, timeout: 18e4 });
4034
+ const tail = r.out.split("\n").filter((l) => l.trim()).slice(-2).join(" \xB7 ").slice(-200);
4035
+ return {
4036
+ name: "check",
4037
+ ok: r.code === 0,
4038
+ ms: Date.now() - t0,
4039
+ fatal: true,
4040
+ detail: r.timedOut ? `did not finish in 180s` : r.code === 0 ? `passes (${tail || "no output"})` : `fails (exit ${r.code}) \u2014 ${tail}`
4041
+ };
4042
+ }
4043
+ async function visionCheck(cwd, spec) {
4044
+ const t0 = Date.now();
4045
+ const code = canaryCode();
4046
+ const dir = path5.join(cwd, ".pi", "loops", ".canary");
4047
+ const file = path5.join(dir, `canary-${code}.png`);
4048
+ try {
4049
+ fs5.mkdirSync(dir, { recursive: true });
4050
+ await canaryImage({ code, out: file, cwd });
4051
+ const r = await run2("pi", ["--print", "--no-session", "--model", spec, `Reply with JSON only: {"code":"<the 4-character code printed in this image>"} @${file}`], { cwd, timeout: 75e3 });
4052
+ const said = (r.out.match(/"code"\s*:\s*"([^"]*)"/) ?? [])[1] ?? "";
4053
+ if (sameCode(code, said)) return { name: `judge sees images (${spec})`, ok: true, detail: `read the code ${code} back`, ms: Date.now() - t0, fatal: false };
4054
+ const why = r.out.split("\n").filter((l) => l.trim() && !/reflection fetch failed/.test(l)).slice(-2).join(" \xB7 ").slice(-160);
4055
+ return {
4056
+ name: `judge sees images (${spec})`,
4057
+ ok: false,
4058
+ fatal: true,
4059
+ ms: Date.now() - t0,
4060
+ detail: r.timedOut ? `no answer in 75s \u2014 the model or provider stalled (an unavailable judge cannot score screenshots)` : said ? `said "${said}", expected ${code}` : `did not read the code \u2014 ${why || "no answer"}`
4061
+ };
4062
+ } catch (e) {
4063
+ return { name: `judge sees images (${spec})`, ok: false, detail: String(e.message ?? e).slice(0, 200), ms: Date.now() - t0, fatal: true };
4064
+ } finally {
4065
+ try {
4066
+ fs5.rmSync(file, { force: true });
4067
+ } catch {
4068
+ }
4069
+ }
4070
+ }
4071
+ async function doctor(cwd) {
4072
+ const cfg = Object.fromEntries(effectiveConfig(cwd).map((c) => [c.key, c.value]));
4073
+ const models = cfg.models ?? {};
4074
+ const [serve, tests, vision] = await Promise.all([
4075
+ cfg.serve ? serveCheck(cwd, String(cfg.serve)) : Promise.resolve({ name: "serve", ok: false, detail: "not set \u2014 visual loops that screenshot need it, and `run it` needs it", ms: 0, fatal: false }),
4076
+ cfg.check ? checkCheck(cwd, String(cfg.check)) : Promise.resolve({ name: "check", ok: false, detail: "not set \u2014 attempts are judged without tests passing", ms: 0, fatal: false }),
4077
+ models.judge ? visionCheck(cwd, String(models.judge)) : Promise.resolve({ name: "judge model", ok: false, detail: "not set \u2014 falls back to whatever model the session is on", ms: 0, fatal: true })
4078
+ ]);
4079
+ const checks = [serve, tests, vision];
4080
+ for (const role of ["safe", "bold"]) {
4081
+ const spec = models[role];
4082
+ checks.push(spec ? { name: `${role} model`, ok: true, detail: String(spec), ms: 0 } : { name: `${role} model`, ok: false, detail: "not set \u2014 falls back to the session's model", ms: 0 });
4083
+ }
4084
+ const fatal = checks.filter((c) => c.fatal && !c.ok).length;
4085
+ return { checks, verdict: fatal ? "will-fail" : checks.every((c) => c.ok) ? "ready" : "incomplete" };
4086
+ }
4087
+
4088
+ // server/workspaces.ts
4089
+ import fs6 from "node:fs";
4090
+ import path6 from "node:path";
4091
+ import { execFileSync } from "node:child_process";
4092
+ var slug = (p) => path6.basename(p).replace(/[^a-z0-9._-]+/gi, "-").toLowerCase() || "repo";
4093
+ var Workspaces = class {
4094
+ /** Where workspaces.json and the per-repo session dirs live. */
4095
+ root;
4096
+ file;
4097
+ data;
4098
+ byId = /* @__PURE__ */ new Map();
4099
+ chatMap;
4100
+ constructor({ root, cwd }) {
4101
+ this.root = root;
4102
+ this.file = path6.join(root, "workspaces.json");
4103
+ fs6.mkdirSync(root, { recursive: true });
4104
+ let data = { workspaces: [], chats: {} };
4105
+ if (fs6.existsSync(this.file)) {
4106
+ try {
4107
+ data = JSON.parse(fs6.readFileSync(this.file, "utf8"));
4108
+ } catch {
4109
+ try {
4110
+ fs6.renameSync(this.file, `${this.file}.corrupt-${Date.now()}`);
4111
+ } catch {
4112
+ }
4113
+ console.error(`[workspaces] could not read ${this.file}; kept a copy and rebuilding from sessions`);
4114
+ }
4115
+ }
4116
+ this.data = { workspaces: data.workspaces ?? [], chats: data.chats ?? {}, default: data.default };
4117
+ this.chatMap = new Map(Object.entries(this.data.chats));
4118
+ const first = this.add(cwd, { persist: false });
4119
+ this.restore();
4120
+ if (!this.data.default || !this.byId.has(this.data.default)) this.data.default = first.id;
4121
+ this.save();
4122
+ }
4123
+ save() {
4124
+ this.data.chats = Object.fromEntries(this.chatMap);
4125
+ try {
4126
+ const tmp = `${this.file}.tmp`;
4127
+ fs6.writeFileSync(tmp, JSON.stringify(this.data, null, 2) + "\n");
4128
+ fs6.renameSync(tmp, this.file);
4129
+ } catch {
4130
+ }
4131
+ }
4132
+ get defaultId() {
4133
+ return this.data.default ?? [...this.byId.keys()][0] ?? "";
4134
+ }
4135
+ list() {
4136
+ return [...this.byId.values()];
4137
+ }
4138
+ get(id) {
4139
+ return this.byId.get(id ?? "") ?? this.byId.get(this.defaultId) ?? null;
4140
+ }
4141
+ /** Add (or re-find) a repo. `persist: false` is used for the startup cwd. */
4142
+ add(dir, { persist = true } = {}) {
4143
+ const abs = path6.resolve(dir);
4144
+ const existing = [...this.byId.values()].find((w) => w.path === abs);
4145
+ if (existing) return existing;
4146
+ if (!fs6.existsSync(abs) || !fs6.statSync(abs).isDirectory()) throw new Error(`${abs} is not a directory`);
4147
+ const st = fs6.statSync(abs);
4148
+ if (!st.isDirectory()) throw new Error(`${abs} is not a directory`);
4149
+ let id = slug(abs);
4150
+ for (let i = 2; this.byId.has(id); i++) id = `${slug(abs)}-${i}`;
4151
+ const legacy = path6.join(abs, ".pi", "loops-ui", "sessions");
4152
+ const sessionDir = fs6.existsSync(legacy) ? legacy : path6.join(this.root, "workspaces", id, "sessions");
4153
+ const ws = { id, path: abs, sessionDir, title: path6.basename(abs) || abs };
4154
+ fs6.mkdirSync(ws.sessionDir, { recursive: true });
4155
+ this.byId.set(id, ws);
4156
+ if (persist) {
4157
+ this.data.workspaces = [...this.data.workspaces.filter((w) => w.path !== abs), { id, path: abs }];
4158
+ this.save();
4159
+ }
4160
+ return ws;
4161
+ }
4162
+ /** Register the persisted workspaces (their paths may have been deleted since), then rebuild from Pi sessions. */
4163
+ restore() {
4164
+ for (const w of this.data.workspaces) {
4165
+ try {
4166
+ this.add(w.path);
4167
+ } catch {
4168
+ }
4169
+ }
4170
+ this.recoverSessions();
4171
+ this.save();
4172
+ }
4173
+ /**
4174
+ * Chat -> repo is recoverable from Pi itself: each session header carries `cwd`, and the session dir names the
4175
+ * workspace. This runs on startup, so a lost or stale `workspaces.json` is a cache miss, not lost history.
4176
+ */
4177
+ recoverSessions() {
4178
+ const root = path6.join(this.root, "workspaces");
4179
+ let ids = [];
4180
+ try {
4181
+ ids = fs6.readdirSync(root);
4182
+ } catch {
4183
+ return;
4184
+ }
4185
+ for (const id of ids) {
4186
+ const dir = path6.join(root, id, "sessions");
4187
+ let files = [];
4188
+ try {
4189
+ files = fs6.readdirSync(dir).filter((f) => f.endsWith(".jsonl"));
4190
+ } catch {
4191
+ continue;
4192
+ }
4193
+ let cwd = null;
4194
+ for (const f of files) {
4195
+ try {
4196
+ const head = JSON.parse(fs6.readFileSync(path6.join(dir, f), "utf8").split("\n")[0]);
4197
+ if (typeof head?.cwd === "string" && head.cwd) {
4198
+ cwd = head.cwd;
4199
+ break;
4200
+ }
4201
+ } catch {
4202
+ }
4203
+ }
4204
+ let ws = this.byId.get(id) ?? null;
4205
+ if (!ws && cwd) {
4206
+ try {
4207
+ ws = this.add(cwd);
4208
+ if (ws.id !== id) ws.sessionDir = dir;
4209
+ } catch {
4210
+ }
4211
+ }
4212
+ if (!ws) continue;
4213
+ for (const f of files) {
4214
+ const chat = f.replace(/\.jsonl$/, "").replace(/^.*_/, "");
4215
+ if (/^chat-/.test(chat) && !this.chatMap.has(chat)) this.chatMap.set(chat, ws.id);
4216
+ }
4217
+ }
4218
+ }
4219
+ remove(id) {
4220
+ if (id === this.defaultId) throw new Error("cannot remove the workspace this app was started in");
4221
+ this.byId.delete(id);
4222
+ this.data.workspaces = this.data.workspaces.filter((w) => w.id !== id);
4223
+ for (const [chat, ws] of this.chatMap) if (ws === id) this.chatMap.delete(chat);
4224
+ this.save();
4225
+ }
4226
+ /** Which workspace a chat belongs to. Unknown ids fall back to the default (older chats predate the registry). */
4227
+ ofChat(chat) {
4228
+ return this.get(this.chatMap.get(chat)) ?? this.get();
4229
+ }
4230
+ bindChat(chat, ws) {
4231
+ if (this.byId.has(ws)) {
4232
+ this.chatMap.set(chat, ws);
4233
+ this.save();
4234
+ }
4235
+ }
4236
+ unbindChat(chat) {
4237
+ if (this.chatMap.delete(chat)) this.save();
4238
+ }
4239
+ /** A repo is loopable when git can name a commit in it; that is what the sidebar shows. */
4240
+ static loopable(dir) {
4241
+ try {
4242
+ execFileSync("git", ["rev-parse", "HEAD"], { cwd: dir, stdio: "pipe" });
4243
+ return true;
4244
+ } catch {
4245
+ return false;
4246
+ }
4247
+ }
4248
+ };
4249
+
4250
+ // server/index.ts
4251
+ var HERE = path7.dirname(fileURLToPath(import.meta.url));
4252
+ var APP_ROOT = path7.resolve(HERE, "..");
4253
+ var arg = (name, fallback) => {
4254
+ const i = process.argv.indexOf(`--${name}`);
4255
+ return i >= 0 ? process.argv[i + 1] : process.env[`LOOPS_UI_${name.toUpperCase().replace(/-/g, "_")}`] ?? fallback;
4256
+ };
4257
+ var PORT = Number(arg("port", "8001"));
4258
+ var HOST = arg("host", "127.0.0.1");
4259
+ var LOOPBACK = ["127.0.0.1", "localhost", "::1"].includes(HOST);
4260
+ var CWD = path7.resolve(arg("cwd", process.cwd()));
4261
+ var DEV = process.argv.includes("--dev") || process.env.NODE_ENV === "development";
4262
+ var VITE = arg("vite", "http://localhost:5173");
4263
+ var PI = arg("pi", "pi");
4264
+ var DATA = path7.resolve(arg("data", process.env.LOOPS_UI_DATA ?? path7.join(process.env.HOME ?? process.cwd(), ".pi", "loops-ui")));
4265
+ var MODEL = arg("model", void 0) || null;
4266
+ var EXTENSIONS = (arg("extensions", path7.resolve(APP_ROOT, "../pi-loops/extensions/loop.ts")) ?? "").split(",").filter(Boolean);
4267
+ function prerequisites() {
4268
+ const out = [];
4269
+ const onPath = PI.includes("/") || /^[A-Za-z]:\\/.test(PI) ? fs7.existsSync(PI) : (() => {
4270
+ try {
4271
+ execFileSync2(process.platform === "win32" ? "where" : "which", [PI], { stdio: ["ignore", "pipe", "ignore"] });
4272
+ return true;
4273
+ } catch {
4274
+ return false;
4275
+ }
4276
+ })();
4277
+ if (!onPath) out.push({ name: "pi", detail: `\`${PI}\` is not on PATH`, fix: "install Pi, or pass --pi <path to the pi binary>" });
4278
+ for (const e of EXTENSIONS) {
4279
+ if (!fs7.existsSync(e)) out.push({ name: "extension", detail: `${e} does not exist`, fix: "pi install npm:@computesdk/pi-loops, or pass --extensions <path to extensions/loop.ts>" });
4280
+ }
4281
+ return out;
4282
+ }
4283
+ var PROBLEMS = prerequisites();
4284
+ fs7.mkdirSync(DATA, { recursive: true });
4285
+ var TOKEN = (() => {
4286
+ const explicit = arg("token", void 0);
4287
+ const file = path7.join(DATA, "token");
4288
+ const stored = (() => {
4289
+ try {
4290
+ return fs7.readFileSync(file, "utf8").trim() || null;
4291
+ } catch {
4292
+ return null;
4293
+ }
4294
+ })();
4295
+ if (explicit) {
4296
+ if (!LOOPBACK) {
4297
+ try {
4298
+ fs7.writeFileSync(file, explicit + "\n", { mode: 384 });
4299
+ } catch {
4300
+ }
4301
+ }
4302
+ return explicit;
4303
+ }
4304
+ if (stored) return stored;
4305
+ if (LOOPBACK) return null;
4306
+ const made = randomBytes(24).toString("base64url");
4307
+ fs7.writeFileSync(file, made + "\n", { mode: 384 });
4308
+ return made;
4309
+ })();
4310
+ if (!LOOPBACK && !TOKEN) {
4311
+ console.error(`refusing to listen on ${HOST} without a token: this UI drives an agent that has bash. Pass --token <secret> (or let it generate one in ${DATA}/token).`);
4312
+ process.exit(2);
4313
+ }
4314
+ var workspaces = new Workspaces({ root: DATA, cwd: CWD });
4315
+ var manager = new ChatManager({
4316
+ piCommand: PI,
4317
+ args: EXTENSIONS.flatMap((e) => ["-e", e]),
4318
+ model: MODEL,
4319
+ // a chat's repo comes from the registry: the browser never hands us a path
4320
+ bind: (chat) => {
4321
+ const ws = workspaces.ofChat(chat);
4322
+ return { cwd: ws.path, sessionDir: ws.sessionDir };
4323
+ }
4324
+ });
4325
+ var wsOf = (chat) => chat ? workspaces.ofChat(chat) : workspaces.get();
4326
+ var wsOfRun = (run3) => {
4327
+ const byIndex = workspaces.list().find((w) => fs7.existsSync(path7.join(w.path, STATE_DIR, `${run3}.json`)));
4328
+ if (byIndex) return byIndex;
4329
+ const chat = manager.findRun(run3);
4330
+ return chat ? workspaces.ofChat(chat.id) : workspaces.get();
4331
+ };
4332
+ var chatsOf = (wsId) => wsId ? manager.list(workspaces.get(wsId)) : workspaces.list().flatMap((w) => manager.list(w));
4333
+ var withLive = (state) => {
4334
+ for (const run3 of state.runs ?? []) {
4335
+ const url = liveUrl(run3.id);
4336
+ if (url && run3.best) run3.best.live = url;
4337
+ }
4338
+ return state;
4339
+ };
4340
+ var streams = /* @__PURE__ */ new Set();
4341
+ var snapshotOf = (chat, wsId) => withLive({ ...chat.snapshot(), chats: chatsOf(wsId), workspaces: workspaces.list(), ws: wsId, proposals });
4342
+ manager.onChange((chat) => {
4343
+ const space = workspaces.ofChat(chat.id);
4344
+ const state = snapshotOf(chat, space.id);
4345
+ for (const s of streams) if (s.chat === chat.id) s.send("state", state, chat.entryCursor);
4346
+ });
4347
+ var watches = /* @__PURE__ */ new Map();
4348
+ var proposals = [];
4349
+ var watchOf = (wsId) => {
4350
+ const ws = workspaces.get(wsId);
4351
+ let w = watches.get(ws.id);
4352
+ if (!w) {
4353
+ const read = () => {
4354
+ try {
4355
+ return JSON.parse(fs7.readFileSync(path7.join(ws.path, ".pi", "loops.json"), "utf8"));
4356
+ } catch {
4357
+ return {};
4358
+ }
4359
+ };
4360
+ w = { cwd: ws.path, accepted: read() };
4361
+ watches.set(ws.id, w);
4362
+ try {
4363
+ fs7.watch(path7.join(ws.path, ".pi"), (_e, name) => {
4364
+ if (name && name !== "loops.json") return;
4365
+ clearTimeout(watchTimers.get(ws.id));
4366
+ watchTimers.set(ws.id, setTimeout(() => checkConfig(ws.id), 120));
4367
+ });
4368
+ } catch {
4369
+ }
4370
+ }
4371
+ return w;
4372
+ };
4373
+ var watchTimers = /* @__PURE__ */ new Map();
4374
+ function notifyProposals() {
4375
+ const payload = JSON.stringify({ type: "proposals", proposals });
4376
+ for (const s of streams) {
4377
+ try {
4378
+ s.send("proposals", proposals);
4379
+ } catch {
4380
+ }
4381
+ }
4382
+ }
4383
+ function checkConfig(wsId) {
4384
+ const w = watchOf(wsId);
4385
+ const CONFIG = path7.join(w.cwd, ".pi", "loops.json");
4386
+ const raw2 = (() => {
4387
+ try {
4388
+ return fs7.readFileSync(CONFIG, "utf8");
4389
+ } catch {
4390
+ return "";
4391
+ }
4392
+ })();
4393
+ if (isSelfWriting() || isSelfWrite(raw2)) {
4394
+ w.accepted = raw2.trim() ? JSON.parse(raw2) : {};
4395
+ return;
4396
+ }
4397
+ const next = raw2.trim() ? JSON.parse(raw2) : {};
4398
+ const changes = diffConfig(w.accepted, next);
4399
+ if (!changes.length) {
4400
+ w.accepted = next;
4401
+ return;
4402
+ }
4403
+ restoreConfig(w.cwd, w.accepted);
4404
+ proposals.push({ id: `p-${Date.now().toString(36)}`, at: Date.now(), file: `${w.cwd}/.pi/loops.json`, changes, before: w.accepted, after: next, ws: wsId });
4405
+ console.log(`[config] proposed: ${changes.map((c) => `${c.key}: ${c.from} \u2192 ${c.to}`).join("; ")} (held; file restored)`);
4406
+ notifyProposals();
4407
+ }
4408
+ var inside = (root, p) => {
4409
+ const abs = path7.resolve(root, p);
4410
+ return abs === root || abs.startsWith(root + path7.sep) ? abs : null;
4411
+ };
4412
+ var stateOf = (run3) => manager.findRun(run3)?.stateFor(run3) ?? readState(wsOfRun(run3).path, run3);
4413
+ var app = new Hono3();
4414
+ var ALLOWED_ORIGINS = (arg("allow-origin", "") ?? "").split(",").map((o) => o.trim()).filter(Boolean);
4415
+ var originAllowed = (origin) => !ALLOWED_ORIGINS.length || ALLOWED_ORIGINS.includes(origin) || ALLOWED_ORIGINS.includes("*");
4416
+ app.use("*", async (c, next) => {
4417
+ const origin = c.req.header("origin");
4418
+ if (origin && originAllowed(origin)) {
4419
+ c.header("access-control-allow-origin", origin);
4420
+ c.header("access-control-allow-headers", "authorization, content-type, last-event-id");
4421
+ c.header("access-control-allow-methods", "GET, POST, OPTIONS");
4422
+ c.header("vary", "origin");
4423
+ }
4424
+ if (c.req.method === "OPTIONS") return c.body(null, 204);
4425
+ await next();
4426
+ });
4427
+ app.use("/api/*", async (c, next) => {
4428
+ if (!TOKEN || c.req.path === "/api/health") return next();
4429
+ const given = c.req.header("authorization")?.replace(/^Bearer\s+/i, "") ?? c.req.query("token") ?? "";
4430
+ if (given !== TOKEN) return c.json({ error: "unauthorized" }, 401);
4431
+ await next();
4432
+ });
4433
+ app.use("/api/v1/*", async (c, next) => {
4434
+ if (!TOKEN) return next();
4435
+ const given = c.req.header("authorization")?.replace(/^Bearer\s+/i, "") ?? c.req.query("token") ?? "";
4436
+ if (given !== TOKEN) return c.json({ error: "unauthorized" }, 401);
4437
+ await next();
4438
+ });
4439
+ var api = new Hono3();
4440
+ api.get("/health", (c) => c.json({ ok: PROBLEMS.length === 0, problems: PROBLEMS, cwd: CWD, data: DATA, pi: PI, extensions: EXTENSIONS, workspaces: workspaces.list() }));
4441
+ api.get("/chats", (c) => c.json(chatsOf(c.req.query("ws"))));
4442
+ api.get("/chats/:id/events", async (c) => {
4443
+ const id = c.req.param("id");
4444
+ const chat = await manager.open(id);
4445
+ const space = workspaces.ofChat(id);
4446
+ return streamSSE(c, async (stream2) => {
4447
+ const send = (event, data, cursor) => stream2.writeSSE({ event, data: JSON.stringify(data), ...cursor ? { id: cursor } : {} }).catch(() => {
4448
+ });
4449
+ await send("state", snapshotOf(chat, space.id), chat.entryCursor);
4450
+ const entry = { chat: id, send };
4451
+ streams.add(entry);
4452
+ const ping = setInterval(() => {
4453
+ void stream2.writeSSE({ event: "ping", data: "{}" }).catch(() => {
4454
+ });
4455
+ }, 2e4);
4456
+ await new Promise((resolve) => stream2.onAbort(resolve));
4457
+ clearInterval(ping);
4458
+ streams.delete(entry);
4459
+ });
4460
+ });
4461
+ api.get("/state", async (c) => {
4462
+ const id = c.req.query("chat");
4463
+ if (!id) return c.json({ error: "chat required" }, 400);
4464
+ const chat = await manager.open(id);
4465
+ const ws = workspaces.ofChat(id);
4466
+ return c.json(withLive({ ...chat.snapshot(), chats: chatsOf(ws.id), workspaces: workspaces.list(), ws: ws.id, proposals }));
4467
+ });
4468
+ api.post("/chat", async (c) => {
4469
+ const body = await c.req.json().catch(() => ({}));
4470
+ const ws = workspaces.get(body.ws) ?? workspaces.get();
4471
+ const id = String(body.id ?? `chat-${Date.now().toString(36)}`).replace(/[^a-zA-Z0-9._-]/g, "").slice(0, 60);
4472
+ workspaces.bindChat(id, ws.id);
4473
+ watchOf(ws.id);
4474
+ await manager.open(id);
4475
+ return c.json({ chat: id, ws: ws.id, chats: chatsOf(ws.id) });
4476
+ });
4477
+ api.post("/chat/delete", async (c) => {
4478
+ const { chat: id } = await c.req.json();
4479
+ const chat = manager.get(String(id));
4480
+ const file = chat?.sessionFile ?? null;
4481
+ await manager.close(String(id));
4482
+ workspaces.unbindChat(String(id));
4483
+ if (file && fs7.existsSync(file)) {
4484
+ try {
4485
+ fs7.rmSync(file);
4486
+ } catch {
4487
+ }
4488
+ }
4489
+ return c.json({ ok: true });
4490
+ });
4491
+ api.get("/workspaces", (c) => c.json(workspaces.list()));
4492
+ api.post("/workspaces", async (c) => {
4493
+ const body = await c.req.json().catch(() => ({}));
4494
+ try {
4495
+ const dir = path7.resolve(String(body.path ?? "").replace(/^~(?=\/|$)/, process.env.HOME ?? "~"));
4496
+ if (!dir || dir === "/") throw new Error("a path is required");
4497
+ if (!fs7.existsSync(dir) || !fs7.statSync(dir).isDirectory()) throw new Error(`${dir} is not a directory`);
4498
+ const ws = workspaces.add(dir);
4499
+ watchOf(ws.id);
4500
+ return c.json({ ok: true, workspace: ws, loopable: Workspaces.loopable(ws.path) });
4501
+ } catch (e) {
4502
+ return c.json({ ok: false, error: String(e.message ?? e) }, 400);
4503
+ }
4504
+ });
4505
+ api.post("/workspaces/remove", async (c) => {
4506
+ const { id } = await c.req.json();
4507
+ try {
4508
+ workspaces.remove(String(id));
4509
+ return c.json({ ok: true });
4510
+ } catch (e) {
4511
+ return c.json({ ok: false, error: String(e.message ?? e) }, 400);
4512
+ }
4513
+ });
4514
+ api.post("/prompt", async (c) => {
4515
+ const { chat: id, text, behavior } = await c.req.json();
4516
+ const chat = await manager.open(String(id));
4517
+ const disposition = await chat.prompt(String(text), behavior === "steer" || behavior === "followUp" ? behavior : void 0);
4518
+ return c.json({ disposition });
4519
+ });
4520
+ api.post("/rename", async (c) => {
4521
+ const { chat: id, name } = await c.req.json();
4522
+ const chat = await manager.open(String(id));
4523
+ await chat.rename(String(name ?? ""));
4524
+ return c.json({ ok: true, title: chat.title });
4525
+ });
4526
+ api.post("/abort", async (c) => {
4527
+ const { chat: id } = await c.req.json();
4528
+ const chat = await manager.open(String(id));
4529
+ await chat.abort();
4530
+ return c.json({ ok: true });
4531
+ });
4532
+ api.post("/ui", async (c) => {
4533
+ const { chat: id, id: dialogId, response } = await c.req.json();
4534
+ const chat = await manager.open(String(id));
4535
+ await chat.answerUi(String(dialogId), response ?? {});
4536
+ return c.json({ ok: true });
4537
+ });
4538
+ api.post("/answer", async (c) => {
4539
+ const { chat: id, question, choice } = await c.req.json();
4540
+ const chat = await manager.open(String(id));
4541
+ await chat.prompt(`/loop answer ${String(question)} ${String(choice)}`);
4542
+ return c.json({ ok: true });
4543
+ });
4544
+ api.post("/steer", async (c) => {
4545
+ const { chat: id, run: run3, action, rule, attempt, text } = await c.req.json();
4546
+ const chat = await manager.open(String(id));
4547
+ const slash = (cmd) => chat.prompt(cmd);
4548
+ switch (String(action)) {
4549
+ case "pick":
4550
+ case "take":
4551
+ return c.json({ ok: true, sent: await slash(`/loop take ${attempt} ${run3}`) });
4552
+ case "apply":
4553
+ return c.json({ ok: true, sent: await slash(`/loop apply`) });
4554
+ case "stop":
4555
+ return c.json({ ok: true, sent: await slash(`/loop stop`) });
4556
+ case "clean":
4557
+ return c.json({ ok: true, sent: await slash(`/loop clean ${run3}`) });
4558
+ case "rule":
4559
+ return c.json({ ok: true, sent: await slash(`/loop rule ${run3} ${rule}`) });
4560
+ case "talk":
4561
+ return c.json({ ok: true, sent: await slash(`/loop talk ${attempt} ${text}`) });
4562
+ // everything else is a decision only the agent can make (another round, a different direction)
4563
+ case "more":
4564
+ return c.json({ ok: true, sent: await slash(`Continue loop ${run3} with ${Number(text) || 2} more rounds. Check loop_status first, then call loop({ from: "${run3}", rounds: ${Number(text) || 2} }).`) });
4565
+ default:
4566
+ return c.json({ error: `unknown action ${action}` }, 400);
4567
+ }
4568
+ });
4569
+ api.get("/ui", async (c) => {
4570
+ const id = c.req.query("chat");
4571
+ if (!id) return c.json([]);
4572
+ const chat = await manager.open(id);
4573
+ return c.json(chat.snapshot().dialogs ?? []);
4574
+ });
4575
+ api.get("/session", async (c) => {
4576
+ const run3 = c.req.query("run");
4577
+ const name = c.req.query("name");
4578
+ if (!run3 || !name) return c.json([]);
4579
+ const state = stateOf(run3);
4580
+ const file = state?.rounds?.flatMap((r) => r.attempts).find((a) => a.label === name)?.session ?? state?.rounds?.flatMap((r) => r.attempts).find((a) => a.label?.toLowerCase() === name.toLowerCase())?.session;
4581
+ if (!file || !fs7.existsSync(file)) return c.json([]);
4582
+ const chat = await manager.open(c.req.query("chat") ?? manager.list()[0]?.id ?? "");
4583
+ return c.json(chat.sessionItems(file));
4584
+ });
4585
+ api.post("/talk", async (c) => {
4586
+ const { chat: id, run: run3, name, text } = await c.req.json();
4587
+ const chat = await manager.open(String(id));
4588
+ await chat.prompt(`/loop talk ${name} ${String(text)}`);
4589
+ return c.json({ ok: true });
4590
+ });
4591
+ api.get("/talk", (c) => c.json([]));
4592
+ api.get("/shot", (c) => {
4593
+ const run3 = c.req.query("run") ?? "";
4594
+ const attempt = c.req.query("attempt") ?? "";
4595
+ const file = c.req.query("f") ?? "";
4596
+ const state = stateOf(run3);
4597
+ const repo = wsOfRun(run3).path;
4598
+ if (file.startsWith(STATE_DIR)) {
4599
+ const abs2 = inside(repo, file);
4600
+ if (!abs2 || !fs7.existsSync(abs2)) return c.notFound();
4601
+ return new Response(fs7.readFileSync(abs2), { headers: { "content-type": abs2.endsWith(".jpg") || abs2.endsWith(".jpeg") ? "image/jpeg" : "image/png", "cache-control": "no-cache" } });
4602
+ }
4603
+ const dir = attempt === "CURRENT" ? state?.best?.dir ?? null : state?.rounds?.flatMap((r) => r.attempts).find((a) => a.label === attempt || a.label?.toLowerCase() === attempt.toLowerCase())?.dir;
4604
+ if (!dir) return c.notFound();
4605
+ const abs = inside(repo, path7.join(dir, file));
4606
+ if (!abs || !fs7.existsSync(abs)) return c.notFound();
4607
+ return new Response(fs7.readFileSync(abs), { headers: { "content-type": abs.endsWith(".jpg") || abs.endsWith(".jpeg") ? "image/jpeg" : "image/png", "cache-control": "no-cache" } });
4608
+ });
4609
+ api.get("/sheet", (c) => {
4610
+ const file = c.req.query("f") ?? "";
4611
+ const ws = workspaces.list().find((w) => fs7.existsSync(path7.join(w.path, file))) ?? workspaces.get();
4612
+ const abs = inside(ws.path, file);
4613
+ if (!abs || !abs.includes(STATE_DIR) || !fs7.existsSync(abs)) return c.notFound();
4614
+ return new Response(fs7.readFileSync(abs), { headers: { "content-type": "image/png", "cache-control": "no-cache" } });
4615
+ });
4616
+ api.get("/diff", async (c) => {
4617
+ const run3 = c.req.query("run") ?? "";
4618
+ const name = c.req.query("name") ?? "";
4619
+ const state = stateOf(run3);
4620
+ if (!state) return c.text("");
4621
+ const attempts = (state.rounds ?? []).flatMap((r) => r.attempts);
4622
+ const attempt = attempts.find((a) => a.label === name || a.label?.toLowerCase() === name.toLowerCase() || a.style === name.toLowerCase());
4623
+ const to = attempt?.commit ?? state.best?.commit;
4624
+ const from = state.baseCommit;
4625
+ if (!to || !from) return c.text("");
4626
+ return c.text(await new Promise((resolve) => {
4627
+ execFile("git", ["diff", "--stat", `${from}..${to}`], { cwd: wsOfRun(run3).path, maxBuffer: 1 << 26 }, (_e, stat) => {
4628
+ execFile("git", ["diff", `${from}..${to}`], { cwd: wsOfRun(run3).path, maxBuffer: 1 << 26 }, (_e2, diff) => resolve(`${stat}
4629
+ ${diff}`.slice(0, 4e5)));
4630
+ });
4631
+ }));
4632
+ });
4633
+ api.post("/live", async (c) => {
4634
+ const { run: run3 } = await c.req.json();
4635
+ try {
4636
+ const cwd = wsOfRun(String(run3)).path;
4637
+ const { url, reused } = await startLive({ cwd, run: String(run3), state: stateOf(String(run3)) });
4638
+ return c.json({ ok: true, url, reused: !!reused });
4639
+ } catch (e) {
4640
+ return c.json({ ok: false, error: String(e.message ?? e) }, 400);
4641
+ }
4642
+ });
4643
+ api.post("/live/stop", async (c) => {
4644
+ const { run: run3 } = await c.req.json();
4645
+ return c.json({ ok: true, stopped: stopLive(String(run3)) });
4646
+ });
4647
+ api.get("/proposals", (c) => c.json(proposals));
4648
+ api.post("/proposals/:id/apply", (c) => {
4649
+ const p = proposals.find((x) => x.id === c.req.param("id"));
4650
+ if (!p) return c.json({ ok: false, error: "no such proposal" }, 404);
4651
+ const cwd = p.ws ? workspaces.get(p.ws).path : CWD;
4652
+ acceptConfig(cwd, p.after);
4653
+ const w = p.ws ? watches.get(p.ws) : null;
4654
+ if (w) w.accepted = p.after;
4655
+ proposals.splice(proposals.indexOf(p), 1);
4656
+ notifyProposals();
4657
+ return c.json({ ok: true });
4658
+ });
4659
+ api.post("/proposals/:id/keep", (c) => {
4660
+ const i = proposals.findIndex((x) => x.id === c.req.param("id"));
4661
+ if (i < 0) return c.json({ ok: false, error: "no such proposal" }, 404);
4662
+ proposals.splice(i, 1);
4663
+ notifyProposals();
4664
+ return c.json({ ok: true });
4665
+ });
4666
+ api.get("/config", (c) => {
4667
+ const ws = wsOf(c.req.query("chat"));
4668
+ watchOf(ws.id);
4669
+ return c.json({ cwd: ws.path, ws: ws.id, keys: effectiveConfig(ws.path) });
4670
+ });
4671
+ api.post("/config", async (c) => {
4672
+ const { key, value, chat } = await c.req.json();
4673
+ const ws = wsOf(chat);
4674
+ try {
4675
+ writeSetting(ws.path, String(key), value);
4676
+ const w = watchOf(ws.id);
4677
+ try {
4678
+ w.accepted = JSON.parse(fs7.readFileSync(path7.join(ws.path, ".pi", "loops.json"), "utf8"));
4679
+ } catch {
4680
+ }
4681
+ return c.json({ ok: true });
4682
+ } catch (e) {
4683
+ return c.json({ ok: false, error: String(e.message ?? e) }, 400);
4684
+ }
4685
+ });
4686
+ api.post("/doctor", async (c) => {
4687
+ const body = await c.req.json().catch(() => ({}));
4688
+ return c.json(await doctor(wsOf(body.chat).path));
4689
+ });
4690
+ api.get("/size", async (c) => {
4691
+ const run3 = c.req.query("run") ?? "";
4692
+ const state = stateOf(run3);
4693
+ if (!state) return c.json({ bytes: 0, dirs: 0 });
4694
+ const dirs = (state.rounds ?? []).flatMap((r) => r.attempts).map((a) => a.dir).filter(Boolean);
4695
+ const bytes = await new Promise((resolve) => execFile("du", ["-sk", ...dirs], { cwd: wsOfRun(run3).path }, (_e, out) => resolve(Number(String(out ?? "").split("\n").map((l) => Number(l.split(/\s+/)[0]) || 0).reduce((a, b) => a + b, 0)) * 1024)));
4696
+ return c.json({ bytes, dirs: dirs.length });
4697
+ });
4698
+ api.get("/files", (c) => {
4699
+ const run3 = c.req.query("run") ?? "";
4700
+ const state = stateOf(run3);
4701
+ if (!state) return c.json({ files: [] });
4702
+ try {
4703
+ const out = execFileSync2("git", ["diff", "--name-only", `${state.baseCommit}..${state.best?.commit ?? state.baseCommit}`], { cwd: wsOfRun(run3).path, encoding: "utf8", maxBuffer: 1 << 26 });
4704
+ return c.json({ files: out.split("\n").filter(Boolean) });
4705
+ } catch {
4706
+ return c.json({ files: [] });
4707
+ }
4708
+ });
4709
+ api.get("/chats/:id/runs", async (c) => {
4710
+ const chat = await manager.open(c.req.param("id"));
4711
+ return c.json(withLive(chat.snapshot()).runs);
4712
+ });
4713
+ api.get("/meta", (c) => c.json({
4714
+ name: "pi-loops-ui",
4715
+ api: 1,
4716
+ version: process.env.npm_package_version ?? "0.1.0",
4717
+ cwd: CWD,
4718
+ data: DATA,
4719
+ host: HOST,
4720
+ token: !!TOKEN,
4721
+ workspaces: workspaces.list()
4722
+ }));
4723
+ app.route("/api", api);
4724
+ app.route("/api/v1", api);
4725
+ var DIST = path7.join(APP_ROOT, "dist");
4726
+ app.get("*", async (c) => {
4727
+ const url = c.req.path;
4728
+ if (DEV) {
4729
+ const res = await fetch(VITE + url).catch(() => null);
4730
+ if (!res) return c.text("vite dev server is not up yet", 503);
4731
+ return new Response(res.body, { status: res.status, headers: { "content-type": res.headers.get("content-type") ?? "text/html" } });
4732
+ }
4733
+ const abs = inside(DIST, url === "/" ? "index.html" : url.replace(/^\//, ""));
4734
+ if (abs && fs7.existsSync(abs) && fs7.statSync(abs).isFile()) {
4735
+ const ext = path7.extname(abs);
4736
+ const type = ext === ".js" ? "text/javascript" : ext === ".css" ? "text/css" : ext === ".woff2" ? "font/woff2" : ext === ".svg" ? "image/svg+xml" : ext === ".png" ? "image/png" : "text/html";
4737
+ return new Response(fs7.readFileSync(abs), { headers: { "content-type": type } });
4738
+ }
4739
+ const index = path7.join(DIST, "index.html");
4740
+ if (!fs7.existsSync(index)) return c.text("run `npm run build` first", 500);
4741
+ return new Response(fs7.readFileSync(index), { headers: { "content-type": "text/html" } });
4742
+ });
4743
+ var server = http.createServer(getRequestListener(app.fetch));
4744
+ setInterval(() => {
4745
+ for (const chat of manager.openChats()) void chat.settleIfIdle();
4746
+ }, 4e3);
4747
+ function openBrowser(url) {
4748
+ if (process.argv.includes("--no-open") || process.env.LOOPS_UI_OPEN === "0") return;
4749
+ const [cmd, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", "", url]] : ["xdg-open", [url]];
4750
+ try {
4751
+ const p = spawn5(cmd, args, { stdio: "ignore", detached: true });
4752
+ p.on("error", () => {
4753
+ });
4754
+ p.unref();
4755
+ } catch {
4756
+ }
4757
+ }
4758
+ server.listen(PORT, HOST, () => {
4759
+ const reach = HOST === "0.0.0.0" ? "127.0.0.1" : HOST;
4760
+ const shown = reach.includes(":") ? `[${reach}]` : reach;
4761
+ const base = `http://${shown}:${PORT}`;
4762
+ const url = TOKEN ? `${base}/?server=${encodeURIComponent(base)}&token=${encodeURIComponent(TOKEN)}` : base;
4763
+ console.log(`
4764
+ open ${url}`);
4765
+ console.log(` ${HOST === "0.0.0.0" ? "all interfaces" : "loopback only"}${TOKEN ? " \xB7 token required" : ""}
4766
+ `);
4767
+ console.log(` data ${DATA}`);
4768
+ console.log(` repos ${workspaces.list().map((w) => w.path).join(", ") || "(none \u2014 add one in the app)"}`);
4769
+ console.log(` extensions ${EXTENSIONS.join(", ") || "(none)"}`);
4770
+ if (PROBLEMS.length) {
4771
+ console.log(`
4772
+ !! a loop cannot run here yet:`);
4773
+ for (const p of PROBLEMS) console.log(` ${p.name.padEnd(10)} ${p.detail}
4774
+ ${p.fix}`);
4775
+ console.log(` the app still serves; \`loops doctor\` checks the rest (serve, check, judge).`);
4776
+ }
4777
+ console.log();
4778
+ openBrowser(url);
4779
+ });
4780
+ var shutdown = async () => {
4781
+ stopAllLive();
4782
+ await manager.closeAll();
4783
+ server.close(() => process.exit(0));
4784
+ setTimeout(() => process.exit(0), 1500);
4785
+ };
4786
+ process.on("SIGINT", shutdown);
4787
+ process.on("SIGTERM", shutdown);