uigraph 1.0.0 → 1.0.2

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 (323) hide show
  1. package/README.md +30 -51
  2. package/dist/bin.mjs +1608 -59037
  3. package/dist/viewer/assets/abnfDiagram-VCTEODGH-D7zWJuPJ.js +1 -0
  4. package/dist/viewer/assets/actor-avatar-Bu-mKKXB.js +1 -0
  5. package/dist/viewer/assets/{api-adapters-CnQpLiWI.js → api-adapters-tfr51BsS.js} +1 -1
  6. package/dist/viewer/assets/{api-endpoints-DCA5GNpC.js → api-endpoints-D-Whnnwd.js} +9 -9
  7. package/dist/viewer/assets/{api-group-endpoints-page-Di42W69y.js → api-group-endpoints-page-B9R1EI4i.js} +9 -9
  8. package/dist/viewer/assets/{arc-Cn8owoDw.js → arc-DauzQXFu.js} +1 -1
  9. package/dist/viewer/assets/architectureDiagram-5GKGNRK7-CXzgHd-c.js +36 -0
  10. package/dist/viewer/assets/{arrow-left-DWcMgM2U.js → arrow-left-DpQqmf17.js} +1 -1
  11. package/dist/viewer/assets/avatar-DAFUyk1i.js +43 -0
  12. package/dist/viewer/assets/badge-hR3QvPWv.js +1 -0
  13. package/dist/viewer/assets/better-delete-confirmation-modal-CGEQ5O4X.js +1 -0
  14. package/dist/viewer/assets/better-dialog-DcIxFWwk.js +1 -0
  15. package/dist/viewer/assets/{blockDiagram-I7D4REHJ-CbYzOsL_.js → blockDiagram-I7D4REHJ-CFHWUw4z.js} +2 -2
  16. package/dist/viewer/assets/{brands-Bd4RklRx.js → brands-DtmA1AhP.js} +1 -1
  17. package/dist/viewer/assets/button-DZj74qS7.js +1 -0
  18. package/dist/viewer/assets/{c4Diagram-7LVT6UL2-CLkVbphC.js → c4Diagram-7LVT6UL2-BHSggPKI.js} +6 -6
  19. package/dist/viewer/assets/{calendar-C0xdI_ag.js → calendar-Bolgc8E5.js} +1 -1
  20. package/dist/viewer/assets/channel-CNRSofFP.js +1 -0
  21. package/dist/viewer/assets/{check-XjanpAFg.js → check-BpmCQNbj.js} +1 -1
  22. package/dist/viewer/assets/checkbox-CFJfXL6R.js +1 -0
  23. package/dist/viewer/assets/{chevron-down-R7pQzyLD.js → chevron-down-DDsUE_xz.js} +1 -1
  24. package/dist/viewer/assets/{chevron-up-CRPypfOs.js → chevron-up-DVznKMGv.js} +1 -1
  25. package/dist/viewer/assets/{chunk-2Q5K7J3B-CcvtugCu.js → chunk-2Q5K7J3B-CNfz5YDQ.js} +1 -1
  26. package/dist/viewer/assets/{chunk-5VM5RSS4-CpZHHr12.js → chunk-5VM5RSS4-CwIhjvMe.js} +1 -1
  27. package/dist/viewer/assets/{chunk-F27PBJKO-DeAl4iOc.js → chunk-F27PBJKO-YFexFJof.js} +1 -1
  28. package/dist/viewer/assets/{chunk-IMKFNOWR-BfrPe7pS.js → chunk-IMKFNOWR-GY2yrvuo.js} +1 -1
  29. package/dist/viewer/assets/{chunk-JWPE2WC7-DDjyvUmZ.js → chunk-JWPE2WC7-xd0JGvne.js} +1 -1
  30. package/dist/viewer/assets/chunk-OB3PAWPO-DJIP1M4r.js +12 -0
  31. package/dist/viewer/assets/{chunk-POPQ4Y6H-DkDb0mzz.js → chunk-POPQ4Y6H-Bh6rizEy.js} +1 -1
  32. package/dist/viewer/assets/{chunk-SVP7TREG-D-K2XIGs.js → chunk-SVP7TREG-DtNrjvpq.js} +1 -1
  33. package/dist/viewer/assets/{chunk-TICWLB2K-DWMQQx6z.js → chunk-TICWLB2K-DrERwtw8.js} +1 -1
  34. package/dist/viewer/assets/{chunk-XXDRQBXY-DfkljAyM.js → chunk-XXDRQBXY-fYo04iwY.js} +1 -1
  35. package/dist/viewer/assets/{circle-alert-pm13M-Ef.js → circle-alert-Bl7DXYD_.js} +1 -1
  36. package/dist/viewer/assets/classDiagram-ZZMXUADV-D7PO-ME9.js +1 -0
  37. package/dist/viewer/assets/classDiagram-v2-VYDZK3BY-D7PO-ME9.js +1 -0
  38. package/dist/viewer/assets/color-input-ClkkG_kZ.js +11 -0
  39. package/dist/viewer/assets/{common-Y7ySZBdh.js → common-DLCsGQ-t.js} +1 -1
  40. package/dist/viewer/assets/{component-icons-D1BDAuEt.js → component-icons-MJ61E9nt.js} +2 -2
  41. package/dist/viewer/assets/{copy-CN4K2f_R.js → copy-DMJJonQF.js} +1 -1
  42. package/dist/viewer/assets/cose-bilkent-JH36ORCC-Dplz8nVT.js +1 -0
  43. package/dist/viewer/assets/cross-button-D5qst1tj.js +1 -0
  44. package/dist/viewer/assets/{cynefin-OW5HDTMX-yz-uw9Kz.js → cynefin-OW5HDTMX-DiBs4CI8.js} +1 -1
  45. package/dist/viewer/assets/cynefinDiagram-5FMLGOSQ-COXS8-dI.js +62 -0
  46. package/dist/viewer/assets/{dagre-GXQ25YYZ-zjZDwXOe.js → dagre-GXQ25YYZ-K8qvfG8D.js} +2 -2
  47. package/dist/viewer/assets/dashboard-diagrams-page-Cb0xNr4W.js +2 -0
  48. package/dist/viewer/assets/dashboard-diagrams-page-inner-CD--zr5q.js +1 -0
  49. package/dist/viewer/assets/dashboard-docs-page-BfWR9Ai9.js +2 -0
  50. package/dist/viewer/assets/dashboard-docs-page-inner-BLbX-YwF.js +67 -0
  51. package/dist/viewer/assets/dashboard-layout-sTeeHNsZ.js +1 -0
  52. package/dist/viewer/assets/dashboard-lens-layout-D-tu_4kn.js +1 -0
  53. package/dist/viewer/assets/dashboard-map-frame-page-7pDmbTSe.js +1 -0
  54. package/dist/viewer/assets/dashboard-plans-page-CfwOZ34A.js +1 -0
  55. package/dist/viewer/assets/dashboard-service-apis-k93fjW51.js +1 -0
  56. package/dist/viewer/assets/{dashboard-service-diagrams-CIjk95Jk.js → dashboard-service-diagrams-BIWUxX-Y.js} +3 -3
  57. package/dist/viewer/assets/dashboard-service-docs-CnniTD6Q.js +1 -0
  58. package/dist/viewer/assets/{dashboard-service-overview-CzePVPjl.js → dashboard-service-overview-CGBu4omY.js} +5 -5
  59. package/dist/viewer/assets/dashboard-services-DEscIO2O.js +1 -0
  60. package/dist/viewer/assets/{db-type-badge-DOgu1Pyc.js → db-type-badge-UbPgpwQf.js} +2 -2
  61. package/dist/viewer/assets/debounce-Cp8eREM4-D7o-Pzb-.js +2 -0
  62. package/dist/viewer/assets/{dependencies-CYdEztHw.js → dependencies-DK2GDlhQ.js} +1 -1
  63. package/dist/viewer/assets/{dependency-graph-DbyfN-rC.js → dependency-graph-xBEnCS0J.js} +3 -3
  64. package/dist/viewer/assets/{diagram-S7CK7UJ4-q-NHkUCx.js → diagram-S7CK7UJ4-D-liadVe.js} +2 -2
  65. package/dist/viewer/assets/diagram-UQ7AKVKN-CnA8mgXp.js +41 -0
  66. package/dist/viewer/assets/{diagram-VSXAHHWV-DZc1kHGx.js → diagram-VSXAHHWV-Ck7dgRFR.js} +2 -2
  67. package/dist/viewer/assets/diagram-VX7I27RA-Cm1LHbu3.js +24 -0
  68. package/dist/viewer/assets/diagram-Z3DM3KII-DV3yBUCB.js +24 -0
  69. package/dist/viewer/assets/diagram-live-preview-DzJ7Nxp1.js +2 -0
  70. package/dist/viewer/assets/{diagram-portal-page-CWxuok9E.js → diagram-portal-page-gguGLULH.js} +24 -24
  71. package/dist/viewer/assets/{diagrams-C1xkRPqT.js → diagrams-BqBSv2eb.js} +4 -4
  72. package/dist/viewer/assets/dialog-D7wzTt0L.js +6 -0
  73. package/dist/viewer/assets/{doc-file-content-B06roi8L.js → doc-file-content-Be0au9Vo.js} +4 -4
  74. package/dist/viewer/assets/{download-CLdCXVsO.js → download-DhyZ3g4F.js} +1 -1
  75. package/dist/viewer/assets/ebnfDiagram-PWID7BFC-BXbHVQvG.js +1 -0
  76. package/dist/viewer/assets/{editor-vqK4qAnB.js → editor-F9o4zoeB.js} +2 -2
  77. package/dist/viewer/assets/{erDiagram-RLTQ6QDP-BWuA-aqV.js → erDiagram-RLTQ6QDP-DMfiWput.js} +2 -2
  78. package/dist/viewer/assets/{file-text-BvszilVL.js → file-text-BFqJQ67P.js} +1 -1
  79. package/dist/viewer/assets/flow-diagram-preview-B83UU1n_.js +1 -0
  80. package/dist/viewer/assets/{flowDiagram-HODETNUW-Db0QtNj4.js → flowDiagram-HODETNUW-BNFS2Mkr.js} +1 -1
  81. package/dist/viewer/assets/ganttDiagram-EL5Y4UJY-DFDsYJNp.js +292 -0
  82. package/dist/viewer/assets/gitGraphDiagram-WWUBYQGX-BVHabPDp.js +106 -0
  83. package/dist/viewer/assets/global-loader-XJO9_e0l.js +1 -0
  84. package/dist/viewer/assets/{globe-Jl6eIZmG.js → globe-CJ35KsQW.js} +1 -1
  85. package/dist/viewer/assets/gql-FFIj8zdp.js +1 -0
  86. package/dist/viewer/assets/{grid-scroll-body-CPqSxU6-.js → grid-scroll-body-DC5pYDPJ.js} +2 -2
  87. package/dist/viewer/assets/iconBase-DtqdW2XR.js +1 -0
  88. package/dist/viewer/assets/index-B6MxYIzs.js +1 -0
  89. package/dist/viewer/assets/index-BC5xdBQU.js +48 -0
  90. package/dist/viewer/assets/index-BIrx3oY4.js +1 -0
  91. package/dist/viewer/assets/{index-jm22RWpY.js → index-BZGsDmUx.js} +5 -5
  92. package/dist/viewer/assets/{index-Poftp9f1.js → index-BZXhpoWr.js} +4 -4
  93. package/dist/viewer/assets/index-Bn2bqqMd.js +1 -0
  94. package/dist/viewer/assets/{index-HU5pz3kj.js → index-BpCVYTvP.js} +36 -36
  95. package/dist/viewer/assets/{index-Bt2YHgxl.js → index-CBOYhBKJ.js} +1 -1
  96. package/dist/viewer/assets/index-CH7cEAxj.js +17 -0
  97. package/dist/viewer/assets/index-CIf0GId3.js +74 -0
  98. package/dist/viewer/assets/{index-D7MEHpJf.js → index-Ck66Ic_p.js} +4 -4
  99. package/dist/viewer/assets/index-Cp9mIQ8F.js +1 -0
  100. package/dist/viewer/assets/{index-c6Bxcoqm.js → index-DDmBuMKI.js} +1 -1
  101. package/dist/viewer/assets/{index-BSyJbFDG.js → index-DY3BFyb6.js} +1 -1
  102. package/dist/viewer/assets/{index-BS94XVnd.js → index-DkzZ-ZvR.js} +1 -1
  103. package/dist/viewer/assets/{index-C_43VC19.js → index-PglMbhys.js} +1 -1
  104. package/dist/viewer/assets/infoDiagram-27XIBGKW-CG-wwxBf.js +2 -0
  105. package/dist/viewer/assets/input--C59pq6j.js +1 -0
  106. package/dist/viewer/assets/{ishikawaDiagram-5VMMS53U-C4PzFnZ4.js → ishikawaDiagram-5VMMS53U-BlgV7ceJ.js} +2 -2
  107. package/dist/viewer/assets/{journeyDiagram-3NMN7TZE-Dpn3bBNo.js → journeyDiagram-3NMN7TZE-Cn03_Xl6.js} +2 -2
  108. package/dist/viewer/assets/{kanban-definition-UXKFOSKX-CJ99H4G6.js → kanban-definition-UXKFOSKX-CJogvDPY.js} +6 -6
  109. package/dist/viewer/assets/{layout-Bfvxt_D5.js → layout-B26eC4yQ.js} +1 -1
  110. package/dist/viewer/assets/{lens-run-page-DZneics-.js → lens-run-page-Ba1ppzJt.js} +3 -3
  111. package/dist/viewer/assets/lens-runs-page-BnUS57LM.js +1 -0
  112. package/dist/viewer/assets/{link-2-C75goIOt.js → link-2-D1e0xznG.js} +1 -1
  113. package/dist/viewer/assets/linked-project-dot-BY1gEES9.js +543 -0
  114. package/dist/viewer/assets/{loader-circle-C5jZoM7X.js → loader-circle-CiqyoJF7.js} +1 -1
  115. package/dist/viewer/assets/{merge-Cy7YkrN7.js → merge-BhOMvhW1.js} +1 -1
  116. package/dist/viewer/assets/mermaid.core-BDgZg3kW.js +312 -0
  117. package/dist/viewer/assets/method-badge-DErZP7y5.js +1 -0
  118. package/dist/viewer/assets/{mindmap-definition-YA3MSWOX-yQCKA-K4.js → mindmap-definition-YA3MSWOX-DFkLu0ac.js} +2 -2
  119. package/dist/viewer/assets/nav-links-DZWMpwMR.js +61 -0
  120. package/dist/viewer/assets/{network-COWNXGMM.js → network-B1apzT1s.js} +1 -1
  121. package/dist/viewer/assets/{nosql-editor-modal-DTiWkc_r.js → nosql-editor-modal-CvH0SWAi.js} +5 -5
  122. package/dist/viewer/assets/not-found-page-C-fn8QeM.js +1 -0
  123. package/dist/viewer/assets/organization-dependency-graph-page-BryP-iJL.js +1 -0
  124. package/dist/viewer/assets/pegDiagram-XKGWAZYB-g1cM14-L.js +1 -0
  125. package/dist/viewer/assets/{pieDiagram-E7YTZNPT-DqnkpCX4.js → pieDiagram-E7YTZNPT-WEnDsMY3.js} +2 -2
  126. package/dist/viewer/assets/{plus-DQakmTjA.js → plus-DbyuOgKB.js} +1 -1
  127. package/dist/viewer/assets/popover-476u3TN0.js +1 -0
  128. package/dist/viewer/assets/preload-helper-BlTxHScW.js +1 -0
  129. package/dist/viewer/assets/{quadrantDiagram-AXDQQJYC-iQjJfars.js → quadrantDiagram-AXDQQJYC-NdfQCpzF.js} +2 -2
  130. package/dist/viewer/assets/query-D9oj6LGx.js +50 -0
  131. package/dist/viewer/assets/{quill-rCHj4fCw.js → quill-Cde5JMRD.js} +1 -1
  132. package/dist/viewer/assets/railroadDiagram-O6MQD6OU-BYhlXlMY.js +1 -0
  133. package/dist/viewer/assets/{react-BNzYaZuG.js → react-Bx48XWN4.js} +1 -1
  134. package/dist/viewer/assets/react-flow-wrapper-BcbvHgxz.js +277 -0
  135. package/dist/viewer/assets/{requirementDiagram-BXWQKSXE-Bv-Vh1dW.js → requirementDiagram-BXWQKSXE-C25Bcm2L.js} +2 -2
  136. package/dist/viewer/assets/{sankeyDiagram-P5KCCOFB-C__uD07f.js → sankeyDiagram-P5KCCOFB-h8LiCsgk.js} +2 -2
  137. package/dist/viewer/assets/scroll-area-RagrStGj.js +6 -0
  138. package/dist/viewer/assets/{search-DW-qhXLk.js → search-vw7ucoOs.js} +1 -1
  139. package/dist/viewer/assets/section-loader-C4hOfhQS.js +1 -0
  140. package/dist/viewer/assets/section-not-found-BnrXiPog.js +1 -0
  141. package/dist/viewer/assets/select-D9fbrr7O.js +1 -0
  142. package/dist/viewer/assets/{sequenceDiagram-WJ2MYXX4-1RbvcHwO.js → sequenceDiagram-WJ2MYXX4-CDRVvD30.js} +2 -2
  143. package/dist/viewer/assets/{service-context-C17u_Fw9.js → service-context-D5nBtU18.js} +1 -1
  144. package/dist/viewer/assets/{service-database-list-page-cYuDHIls.js → service-database-list-page-DBjaDLVy.js} +2 -2
  145. package/dist/viewer/assets/service-database-page-CenNCgwf.js +2 -0
  146. package/dist/viewer/assets/service-database-page-inner-gS51TQTZ.js +85 -0
  147. package/dist/viewer/assets/{service-doc-Dir8g83J.js → service-doc-C-jHqT1U.js} +4 -4
  148. package/dist/viewer/assets/{service-doc-preview-modal-bJ6tJ5YR.js → service-doc-preview-modal-5sX6FOu1.js} +2 -2
  149. package/dist/viewer/assets/service-layout-Bf0vZBCH.js +1 -0
  150. package/dist/viewer/assets/service-pages-CFikvX4t.js +1 -0
  151. package/dist/viewer/assets/{services-Crqkffr5.js → services-Ivav34WC.js} +4 -4
  152. package/dist/viewer/assets/{share-2-BmYmqN4k.js → share-2-CQEaWbfH.js} +1 -1
  153. package/dist/viewer/assets/sizeCapture-INFHLROL-BJ6ndnPM.js +1 -0
  154. package/dist/viewer/assets/stateDiagram-D77RDMKH-B_tNCX3o.js +1 -0
  155. package/dist/viewer/assets/stateDiagram-v2-MP3YSRHH-Dl9wqdli.js +1 -0
  156. package/dist/viewer/assets/{style-DgSU0bQl.js → style-BPesJvJr.js} +8 -8
  157. package/dist/viewer/assets/super-circle-loader-DSkos6uP.js +1 -0
  158. package/dist/viewer/assets/super-logo-loader-Cxlbn6MB.js +1 -0
  159. package/dist/viewer/assets/swimlanes-42K2YHIH-CzURzYwf.js +1 -0
  160. package/dist/viewer/assets/swimlanesDiagram-VR7AAH4N-DrIlwFtk.js +8 -0
  161. package/dist/viewer/assets/table-B4pFND-o.js +1 -0
  162. package/dist/viewer/assets/textarea-Clgdv3Oi.js +1 -0
  163. package/dist/viewer/assets/{timeline-definition-24CTP7MA-C4yuLwUH.js → timeline-definition-24CTP7MA-D0YXQE1U.js} +2 -2
  164. package/dist/viewer/assets/ui-graph-logo-gHowu5gP.js +1 -0
  165. package/dist/viewer/assets/{upload-CRsS43j9.js → upload-CYb3nN_5.js} +1 -1
  166. package/dist/viewer/assets/{uploads-BOQHX9l4.js → uploads-CX2kdXbM.js} +8 -8
  167. package/dist/viewer/assets/{use-debounced-value-Ba-kkCUY.js → use-debounced-value-BpNFJd3C.js} +1 -1
  168. package/dist/viewer/assets/{use-localstorage-DIisTx-J.js → use-localstorage-D233xVb0.js} +1 -1
  169. package/dist/viewer/assets/use-permissions-BvmxJJ5r.js +1 -0
  170. package/dist/viewer/assets/{use-scoped-storage-C4RzED-E.js → use-scoped-storage-DL1XVp1j.js} +1 -1
  171. package/dist/viewer/assets/useMutation-D5ZHwHsx.js +1 -0
  172. package/dist/viewer/assets/useQuery-Dhe6uxrL.js +1 -0
  173. package/dist/viewer/assets/{vennDiagram-4TSXK5OY-BCtqXZqe.js → vennDiagram-4TSXK5OY-SSjHlqCQ.js} +2 -2
  174. package/dist/viewer/assets/{wardleyDiagram-VM6X3IG4-D3OtZJoT.js → wardleyDiagram-VM6X3IG4-CZWNdQxH.js} +2 -2
  175. package/dist/viewer/assets/{xychartDiagram-S5SC5T6Z-DxLL2CHH.js → xychartDiagram-S5SC5T6Z-B2qAGeb0.js} +2 -2
  176. package/dist/viewer/assets/zod-BMU4UTQt.js +1 -0
  177. package/dist/viewer/index.html +10 -1
  178. package/package.json +57 -57
  179. package/dist/abort-signals-B4fc3ahg.mjs +0 -34
  180. package/dist/agents.md +0 -28
  181. package/dist/anthropic-messages-KPxCHqBN.mjs +0 -14327
  182. package/dist/auth-storage-BvNH97p9.mjs +0 -2180
  183. package/dist/azure-openai-config-BbeCSg4y.mjs +0 -55
  184. package/dist/azure-openai-responses-BRzy8RfL.mjs +0 -182
  185. package/dist/classifier-shared-DBUHiTGw.mjs +0 -105
  186. package/dist/cli-2R6QQFp1.mjs +0 -451
  187. package/dist/cloudflare-workers-ai-system-one-BfqwmRQf.mjs +0 -44
  188. package/dist/config-D8DMGzIq.mjs +0 -647
  189. package/dist/cross-spawn-B2jIQPlu.mjs +0 -404
  190. package/dist/diagnostics-xdSgQR8t.mjs +0 -131
  191. package/dist/dist-BRyghrKX.mjs +0 -404
  192. package/dist/dist-D0EzrblG.mjs +0 -12161
  193. package/dist/dist-EKhnHWHG.mjs +0 -140221
  194. package/dist/dist-pQtuusFv.mjs +0 -1243
  195. package/dist/easter-egg-3d-C9_btlWn.mjs +0 -1225
  196. package/dist/env-api-keys-uytNub6O.mjs +0 -122
  197. package/dist/error-body-FhmCtR7m.mjs +0 -101
  198. package/dist/esm-D5isprgl.mjs +0 -1533
  199. package/dist/esm-DnqE4pfM.mjs +0 -104876
  200. package/dist/execute-BoTKl80U.mjs +0 -1715
  201. package/dist/github-copilot-headers-DWcTgoXr.mjs +0 -22
  202. package/dist/google-generative-ai-Brs5YpJo.mjs +0 -332
  203. package/dist/google-shared-2CyYa4VE.mjs +0 -33438
  204. package/dist/google-vertex-DZDUQPKa.mjs +0 -378
  205. package/dist/hash-DN7ukSfd.mjs +0 -16
  206. package/dist/headers-GhQHLk-3.mjs +0 -17
  207. package/dist/jiti-9kWALm4Y.mjs +0 -5439
  208. package/dist/jiti-loader-f21DrY1K.mjs +0 -27
  209. package/dist/jiti-static-loader-BI_w28l7.mjs +0 -41704
  210. package/dist/json-parse-B2mHg7o7.mjs +0 -381
  211. package/dist/keybinding-hints-D0nLU3ZH.mjs +0 -17899
  212. package/dist/lib-Dj1gKQJc.mjs +0 -24379
  213. package/dist/llama-cpp-classify-C73BoMYd.mjs +0 -344
  214. package/dist/mistral-conversations-DXVR7znL.mjs +0 -698
  215. package/dist/models-DBdii9gQ.mjs +0 -1255
  216. package/dist/multipart-parser-DLw9Z0uJ.mjs +0 -298
  217. package/dist/node-B0NU8X55.mjs +0 -2479
  218. package/dist/node-B8gaKm9g.mjs +0 -23
  219. package/dist/openai-I3_AqKDX.mjs +0 -17357
  220. package/dist/openai-codex-responses-PcZHDuBD.mjs +0 -1198
  221. package/dist/openai-completions-a_mH01ii.mjs +0 -994
  222. package/dist/openai-decisions-Du8y4mQG.mjs +0 -142
  223. package/dist/openai-prompt-cache-Bc6qNWt0.mjs +0 -8
  224. package/dist/openai-responses-a9lV_U7O.mjs +0 -270
  225. package/dist/openai-responses-shared-CDs_PBiH.mjs +0 -598
  226. package/dist/openrouter-images-D0Zc8Cjs.mjs +0 -125
  227. package/dist/photon_rs-DCvMOMu0.mjs +0 -4252
  228. package/dist/pi-messages-B5ietIBq.mjs +0 -306
  229. package/dist/plan-prompt.md +0 -56
  230. package/dist/prompt.md +0 -44
  231. package/dist/provider-env-BJhgA66g.mjs +0 -37
  232. package/dist/provider-retry-DXYM7rVE.mjs +0 -79
  233. package/dist/runtime-DTkBxiaM.mjs +0 -2822
  234. package/dist/sanitize-unicode-CqChtoM6.mjs +0 -26
  235. package/dist/shell-836_JFnI.mjs +0 -162
  236. package/dist/source-CKPndhKl.mjs +0 -478
  237. package/dist/src-DNm2QRm3.mjs +0 -5028
  238. package/dist/system-one-shared-DUAFtNa8.mjs +0 -75
  239. package/dist/token-DEUkymby.mjs +0 -56
  240. package/dist/token-util-Cx5S4eKt.mjs +0 -3
  241. package/dist/tool-DHDYqsyG.mjs +0 -6673
  242. package/dist/transform-messages-BClk99Vn.mjs +0 -477
  243. package/dist/typesafe-system-one-D2d8j8hZ.mjs +0 -24
  244. package/dist/typescript-Br-vsRJV.mjs +0 -6737
  245. package/dist/uuid-CNCZqNBb.mjs +0 -49
  246. package/dist/v2-1z8ijsD3.mjs +0 -6120
  247. package/dist/viewer/assets/abnfDiagram-VCTEODGH-j5YaKnl9.js +0 -1
  248. package/dist/viewer/assets/actor-avatar-DqmoY8Xc.js +0 -1
  249. package/dist/viewer/assets/architectureDiagram-5GKGNRK7-D80cJKz_.js +0 -36
  250. package/dist/viewer/assets/avatar-BI7D-Aia.js +0 -43
  251. package/dist/viewer/assets/badge-870-A4Y6.js +0 -1
  252. package/dist/viewer/assets/better-delete-confirmation-modal-Dib31LVb.js +0 -1
  253. package/dist/viewer/assets/better-dialog-D3AAiahr.js +0 -1
  254. package/dist/viewer/assets/button-DadqadpO.js +0 -1
  255. package/dist/viewer/assets/channel-DRkt3LIn.js +0 -1
  256. package/dist/viewer/assets/checkbox-BXpR079x.js +0 -1
  257. package/dist/viewer/assets/classDiagram-ZZMXUADV-G5CebNaC.js +0 -1
  258. package/dist/viewer/assets/classDiagram-v2-VYDZK3BY-G5CebNaC.js +0 -1
  259. package/dist/viewer/assets/color-input-Efm-lxDy.js +0 -11
  260. package/dist/viewer/assets/cose-bilkent-JH36ORCC-CrSHFmnp.js +0 -1
  261. package/dist/viewer/assets/cross-button-5Sr5rWVP.js +0 -1
  262. package/dist/viewer/assets/cynefinDiagram-5FMLGOSQ-Bdl_eBdu.js +0 -62
  263. package/dist/viewer/assets/dashboard-diagrams-page-DMupOe1m.js +0 -2
  264. package/dist/viewer/assets/dashboard-diagrams-page-inner-Dh0yKh2A.js +0 -1
  265. package/dist/viewer/assets/dashboard-docs-page-DWJ1qOQz.js +0 -2
  266. package/dist/viewer/assets/dashboard-docs-page-inner-Fs6G3oGo.js +0 -67
  267. package/dist/viewer/assets/dashboard-layout-D36InAaB.js +0 -1
  268. package/dist/viewer/assets/dashboard-lens-layout-Cv1Xx3hY.js +0 -1
  269. package/dist/viewer/assets/dashboard-map-frame-page-CTn61NUO.js +0 -1
  270. package/dist/viewer/assets/dashboard-plans-page-DxFJkrgK.js +0 -1
  271. package/dist/viewer/assets/dashboard-service-apis-BHtD9s5z.js +0 -1
  272. package/dist/viewer/assets/dashboard-service-docs-Uv_1uxxO.js +0 -1
  273. package/dist/viewer/assets/dashboard-services-CUP-L4Jg.js +0 -1
  274. package/dist/viewer/assets/diagram-UQ7AKVKN-DhFcurW6.js +0 -41
  275. package/dist/viewer/assets/diagram-VX7I27RA-DE1nREE8.js +0 -24
  276. package/dist/viewer/assets/diagram-Z3DM3KII-CSrYcCbc.js +0 -24
  277. package/dist/viewer/assets/diagram-live-preview-i5doxXLH.js +0 -2
  278. package/dist/viewer/assets/dialog-D_HtNS17.js +0 -6
  279. package/dist/viewer/assets/ebnfDiagram-PWID7BFC-BfL8m_sf.js +0 -1
  280. package/dist/viewer/assets/flow-diagram-preview-T0Z4iMVU.js +0 -1
  281. package/dist/viewer/assets/ganttDiagram-EL5Y4UJY-CsITpniw.js +0 -292
  282. package/dist/viewer/assets/gitGraphDiagram-WWUBYQGX-B4eCBGoe.js +0 -106
  283. package/dist/viewer/assets/iconBase-BoDZfJgC.js +0 -1
  284. package/dist/viewer/assets/index-5E1tJ7yK.js +0 -125
  285. package/dist/viewer/assets/index-7XpV2DRw.js +0 -1
  286. package/dist/viewer/assets/index-C0Rs3s9Z.js +0 -1
  287. package/dist/viewer/assets/index-CzHjJWeV.js +0 -1
  288. package/dist/viewer/assets/index-DcEA6SIV.js +0 -74
  289. package/dist/viewer/assets/infoDiagram-27XIBGKW-lTebN5Ix.js +0 -2
  290. package/dist/viewer/assets/input-YvHTVS0E.js +0 -1
  291. package/dist/viewer/assets/lens-runs-page-DoAOObxx.js +0 -1
  292. package/dist/viewer/assets/linked-project-dot-Ds2uEmJ9.js +0 -543
  293. package/dist/viewer/assets/mermaid.core-BCRBv8Us.js +0 -312
  294. package/dist/viewer/assets/method-badge-DMYDKdDZ.js +0 -1
  295. package/dist/viewer/assets/nav-links-8vT2ixiI.js +0 -61
  296. package/dist/viewer/assets/not-found-page-CnfLlhS4.js +0 -1
  297. package/dist/viewer/assets/organization-dependency-graph-page-3xqIxjNx.js +0 -1
  298. package/dist/viewer/assets/pegDiagram-XKGWAZYB-CMXqeAum.js +0 -1
  299. package/dist/viewer/assets/popover-CN9ni1N3.js +0 -1
  300. package/dist/viewer/assets/railroadDiagram-O6MQD6OU-CfqToX3W.js +0 -1
  301. package/dist/viewer/assets/react-flow-wrapper-BPlRstyO.js +0 -276
  302. package/dist/viewer/assets/scroll-area-BodE-n7W.js +0 -6
  303. package/dist/viewer/assets/section-loader-BzpYM_Nx.js +0 -1
  304. package/dist/viewer/assets/select-DDtnmSET.js +0 -1
  305. package/dist/viewer/assets/service-database-page-CMi1wF4h.js +0 -2
  306. package/dist/viewer/assets/service-database-page-inner-CoqAj93L.js +0 -85
  307. package/dist/viewer/assets/service-layout-0NMm_bKG.js +0 -1
  308. package/dist/viewer/assets/service-pages-dfnc91SU.js +0 -1
  309. package/dist/viewer/assets/sizeCapture-INFHLROL-BRJi3gCg.js +0 -1
  310. package/dist/viewer/assets/stateDiagram-D77RDMKH-DdLsfxgy.js +0 -1
  311. package/dist/viewer/assets/stateDiagram-v2-MP3YSRHH-DFwg8Qki.js +0 -1
  312. package/dist/viewer/assets/super-circle-loader-D8MElOMh.js +0 -1
  313. package/dist/viewer/assets/super-logo-loader-DJYiRbCS.js +0 -1
  314. package/dist/viewer/assets/swimlanes-42K2YHIH-AuYjrPqh.js +0 -1
  315. package/dist/viewer/assets/swimlanesDiagram-VR7AAH4N-0nIGA8_4.js +0 -8
  316. package/dist/viewer/assets/table-Bi4Auk9Z.js +0 -1
  317. package/dist/viewer/assets/textarea-MgxZ5x6-.js +0 -1
  318. package/dist/viewer/assets/ui-graph-logo-D4jRhd4z.js +0 -1
  319. package/dist/viewer/assets/use-permissions-6JVET753.js +0 -1
  320. package/dist/viewer/assets/useMutation-CmVaR9zz.js +0 -1
  321. package/dist/viewer/assets/useQuery-B8yYhO0c.js +0 -1
  322. package/dist/viewer/assets/zod-Dc4H6VVJ.js +0 -1
  323. package/dist/virtual-modules-DnCx0Gdx.mjs +0 -340
@@ -1,1715 +0,0 @@
1
- import { D as combineUsage, M as formatSize, R as writeOutputFile, a as CODEMODE_DOCS_PATH, d as parseCodemodeSource, f as renderToolSample, l as getCodemodeCallableTools, o as CODEMODE_STORE_ENTRY_TYPE, p as toCodemodeIdentifier, r as createToolSearchDocument, t as Bm25Ranker, u as toCodemodeDeclaration } from "./tool-DHDYqsyG.mjs";
2
- import { C as getQuickJSWasmPath, g as getCodemodeWorkerSpecifier } from "./config-D8DMGzIq.mjs";
3
- import { createRequire } from "node:module";
4
- import { readFile } from "node:fs/promises";
5
- import { Worker } from "node:worker_threads";
6
- //#region node_modules/.pnpm/@earendil-works+pi-codemode@1.2.0/node_modules/@earendil-works/pi-codemode/dist/runtime/protocol.js
7
- function isWorkerToHostMessage(value) {
8
- if (typeof value !== "object" || value === null) return false;
9
- const type = value.type;
10
- return type === "call" || type === "output" || type === "done" || type === "crash" || type === "started" || type === "idle";
11
- }
12
- //#endregion
13
- //#region node_modules/.pnpm/@earendil-works+pi-codemode@1.2.0/node_modules/@earendil-works/pi-codemode/dist/runtime/execution.js
14
- /**
15
- * Host side of an execution, shared by every place a VM can run.
16
- *
17
- * The host owns everything the script must not influence: the tool table, call records, output,
18
- * the deadline, the caller's abort signal, and the decoding of what the VM reports. The VM itself
19
- * runs somewhere a {@link VmLauncher} decides: a worker thread (`CodemodeSandbox`), the calling
20
- * thread (`InlineCodemodeSandbox`), or another isolate reached over RPC (`RemoteCodemodeSandbox`).
21
- * The two sides only exchange the messages in `protocol.ts`, so the launchers differ in transport
22
- * and termination, not in behavior.
23
- *
24
- * Lifecycle of one execution:
25
- * 1. The constructor arms the deadline and abort listener, then asks the launcher for a channel.
26
- * 2. Messages from the VM arrive through {@link VmEvents.message}; tool calls run here and their
27
- * results go back through {@link VmChannel.post}. Replies produced before the launcher has
28
- * returned its channel are queued and flushed when it arrives.
29
- * 3. The first terminal event wins: `done`, `crash`, a launcher failure, the deadline, or an abort.
30
- * `finish()` aborts pending tool calls, stops the channel, and resolves the result once the
31
- * channel reports it stopped. Later events are ignored.
32
- *
33
- * The launcher, not this class, is responsible for actually stopping a running VM: a worker is
34
- * terminated, an in-thread VM is interrupted and disposed, and a remote VM is told to stop at its
35
- * next exchange.
36
- */
37
- const DEFAULT_TIMEOUT_MS = 3e5;
38
- const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
39
- const RESERVED_GLOBALS = /* @__PURE__ */ new Set([
40
- "tools",
41
- "ALL_TOOLS",
42
- "console",
43
- "text",
44
- "image",
45
- "exit",
46
- "globalThis",
47
- "store",
48
- "load"
49
- ]);
50
- function errorMessage(error) {
51
- return error instanceof Error ? error.message : String(error);
52
- }
53
- function serializeStore(store) {
54
- const serialized = {};
55
- for (const [key, value] of Object.entries(store ?? {})) {
56
- const json = JSON.stringify(value);
57
- if (json !== void 0) serialized[key] = json;
58
- }
59
- return serialized;
60
- }
61
- /**
62
- * The prelude that serializes values for the host runs in the same VM as the script, so a script
63
- * that patches built-ins (for example `Array.prototype.toJSON`) can make it send malformed data.
64
- * Payloads that do not decode throw this error, and the execution fails as a sandbox error.
65
- */
66
- var BridgeError = class extends Error {};
67
- function parseBridgeJson(json, what) {
68
- try {
69
- return JSON.parse(json);
70
- } catch {
71
- throw new BridgeError(`${what} is not valid JSON`);
72
- }
73
- }
74
- function parseStoreWrites(json) {
75
- const entries = parseBridgeJson(json, "store writes");
76
- if (!Array.isArray(entries)) throw new BridgeError("store writes are not an array");
77
- const writes = {
78
- set: {},
79
- delete: []
80
- };
81
- for (const entry of entries) {
82
- if (!Array.isArray(entry) || typeof entry[0] !== "string" || (entry.length === 2 ? typeof entry[1] !== "string" : entry.length !== 1)) throw new BridgeError("store writes contain a malformed entry");
83
- const [key, value] = entry;
84
- if (value === void 0) writes.delete.push(key);
85
- else writes.set[key] = parseBridgeJson(value, `store value for ${JSON.stringify(key)}`);
86
- }
87
- return writes;
88
- }
89
- function parseScriptError(json) {
90
- const parsed = parseBridgeJson(json, "script error");
91
- if (typeof parsed !== "object" || parsed === null) throw new BridgeError("script error is not an object");
92
- const { name, message, stack } = parsed;
93
- if (typeof message !== "string" || name !== void 0 && typeof name !== "string" || stack !== void 0 && typeof stack !== "string") throw new BridgeError("script error is malformed");
94
- return {
95
- kind: "script",
96
- name,
97
- message,
98
- stack
99
- };
100
- }
101
- /** Checks global names: identifiers or `namespace.member`, not shadowing a built-in global or each other. */
102
- function checkGlobals(globals) {
103
- const names = /* @__PURE__ */ new Set();
104
- const namespaces = /* @__PURE__ */ new Set();
105
- for (const global of globals) {
106
- const parts = global.name.split(".");
107
- if (parts.length > 2 || !parts.every((part) => IDENTIFIER.test(part)) || RESERVED_GLOBALS.has(parts[0])) throw new Error(`Invalid global name "${global.name}"`);
108
- if (names.has(global.name)) throw new Error(`Global "${global.name}" is already registered`);
109
- if (parts.length === 2) namespaces.add(parts[0]);
110
- names.add(global.name);
111
- }
112
- for (const name of namespaces) if (names.has(name)) throw new Error(`Global "${name}" conflicts with the namespace "${name}"`);
113
- }
114
- /** One script run in its own VM. */
115
- var Execution = class {
116
- promise;
117
- resolveResult;
118
- channel;
119
- /** Replies produced before the launcher returned the channel. */
120
- unsent = [];
121
- executors;
122
- control;
123
- /** Result numbers `deliver()` used. */
124
- delivered = /* @__PURE__ */ new Set();
125
- signal;
126
- timer;
127
- output = [];
128
- calls = [];
129
- pending = /* @__PURE__ */ new Map();
130
- /** Whether the execution has its outcome. */
131
- finished = false;
132
- constructor(options) {
133
- this.promise = new Promise((resolve) => {
134
- this.resolveResult = resolve;
135
- });
136
- this.executors = options.executors;
137
- this.control = options.control;
138
- this.signal = options.signal;
139
- if (Number.isFinite(options.timeoutMs)) this.timer = setTimeout(() => {
140
- this.finish({
141
- kind: "timeout",
142
- message: `Execution timed out after ${options.timeoutMs} ms`
143
- });
144
- }, options.timeoutMs);
145
- if (options.signal) {
146
- if (options.signal.aborted) this.onAbort();
147
- else options.signal.addEventListener("abort", this.onAbort, { once: true });
148
- }
149
- if (this.finished) return;
150
- const data = {
151
- code: options.code,
152
- tools: options.tools.map((tool) => ({
153
- name: tool.name,
154
- jsName: tool.jsName ?? toCodemodeIdentifier(tool.name),
155
- description: tool.description ?? ""
156
- })),
157
- globals: options.globals.map((global) => ({
158
- name: global.name,
159
- spread: global.spread === true
160
- })),
161
- memoryLimitBytes: options.memoryLimitBytes,
162
- store: options.store,
163
- ...options.deterministic ? { deterministic: options.deterministic } : {}
164
- };
165
- const events = {
166
- message: (message) => this.receive(message),
167
- failure: (error) => this.finish(error)
168
- };
169
- new Promise((resolve) => resolve(options.launch(data, events))).then((channel) => {
170
- if (this.finished) {
171
- channel.stop().catch(() => void 0);
172
- return;
173
- }
174
- this.channel = channel;
175
- for (const message of this.unsent.splice(0)) channel.post(message);
176
- }, (error) => {
177
- this.finish({
178
- kind: "sandbox",
179
- message: errorMessage(error)
180
- });
181
- });
182
- }
183
- /** `CodemodeRun.deliver()`. */
184
- deliver(seq, now, id, outcome) {
185
- if (this.finished) return;
186
- if (!Number.isFinite(now)) throw new Error(`The clock value of result ${seq} is not a finite number`);
187
- if (!Number.isInteger(seq) || seq < 1 || this.delivered.has(seq)) throw new Error(`Result number ${seq} is not a positive integer used once`);
188
- const pending = this.pending.get(id);
189
- if (pending === void 0) throw new Error(`Call ${id} is not waiting for a result`);
190
- if (!outcome.ok && outcome.properties !== void 0) {
191
- const { properties } = outcome;
192
- if (typeof properties !== "object" || properties === null || Array.isArray(properties)) throw new Error(`The properties of result ${seq} are not an object`);
193
- }
194
- const payload = outcome.ok ? outcome.value === void 0 ? void 0 : JSON.stringify(outcome.value) : outcome.message;
195
- const properties = !outcome.ok && outcome.properties !== void 0 ? JSON.stringify(outcome.properties) : void 0;
196
- this.delivered.add(seq);
197
- this.pending.delete(id);
198
- if (pending.record) {
199
- pending.record.status = outcome.ok ? "ok" : "error";
200
- pending.record.durationMs = performance.now() - pending.startedAt;
201
- }
202
- this.post({
203
- type: "result",
204
- id,
205
- ok: outcome.ok,
206
- payload,
207
- seq,
208
- now,
209
- ...properties === void 0 ? {} : { properties }
210
- });
211
- }
212
- abort(message) {
213
- this.finish({
214
- kind: "aborted",
215
- message
216
- });
217
- return this.promise;
218
- }
219
- onAbort = () => {
220
- const reason = this.signal?.reason;
221
- this.finish({
222
- kind: "aborted",
223
- message: reason instanceof Error ? reason.message : "Execution aborted"
224
- });
225
- };
226
- post(message) {
227
- if (this.channel) this.channel.post(message);
228
- else this.unsent.push(message);
229
- }
230
- /** An exception here would escape into the launcher's transport and leave the execution unsettled. */
231
- receive(message) {
232
- try {
233
- this.handleMessage(message);
234
- } catch (error) {
235
- this.finish({
236
- kind: "sandbox",
237
- message: error instanceof BridgeError ? `Sandbox bridge broken: ${error.message}. The script may have modified built-ins such as a prototype's toJSON.` : `Sandbox host failed: ${errorMessage(error)}`
238
- });
239
- }
240
- }
241
- handleMessage(message) {
242
- if (this.finished) return;
243
- if (!isWorkerToHostMessage(message)) throw new BridgeError("unknown message from the worker");
244
- switch (message.type) {
245
- case "output":
246
- this.output.push(message.item);
247
- break;
248
- case "call":
249
- if (this.pending.has(message.id)) throw new BridgeError(`duplicate call id ${message.id}`);
250
- if (this.control) this.forwardCall(message, this.control);
251
- else this.handleCall(message);
252
- break;
253
- case "started":
254
- this.control?.onStarted?.(message.fingerprint);
255
- break;
256
- case "idle":
257
- this.control?.onIdle?.(message.seq, message.issued);
258
- break;
259
- case "done":
260
- this.handleDone(message);
261
- break;
262
- case "crash": this.finish({
263
- kind: "sandbox",
264
- message: message.message
265
- });
266
- }
267
- }
268
- handleDone(message) {
269
- if (!message.ok) {
270
- this.finish(parseScriptError(message.error), void 0, void 0, message.during);
271
- return;
272
- }
273
- const value = message.value === void 0 ? void 0 : parseBridgeJson(message.value, "return value");
274
- this.finish(void 0, value, parseStoreWrites(message.writes), message.during);
275
- }
276
- /** A host-controlled run: record the call and hand it to the caller, which answers with `deliver()`. */
277
- forwardCall(message, control) {
278
- const { id, name, target } = message;
279
- const args = message.args === void 0 ? void 0 : parseBridgeJson(message.args, "call arguments");
280
- const record = target === "tool" ? {
281
- name,
282
- status: "cancelled",
283
- durationMs: 0
284
- } : void 0;
285
- if (record) this.calls.push(record);
286
- this.pending.set(id, {
287
- record,
288
- startedAt: performance.now(),
289
- controller: new AbortController()
290
- });
291
- control.onCall({
292
- id,
293
- target,
294
- name,
295
- args
296
- });
297
- }
298
- async handleCall(message) {
299
- const { id, name } = message;
300
- const isTool = message.target === "tool";
301
- const record = isTool ? {
302
- name,
303
- status: "cancelled",
304
- durationMs: 0
305
- } : void 0;
306
- if (record) this.calls.push(record);
307
- const pending = {
308
- record,
309
- startedAt: performance.now(),
310
- controller: new AbortController()
311
- };
312
- this.pending.set(id, pending);
313
- let status;
314
- let reply;
315
- try {
316
- const tool = (isTool ? this.executors.tools : this.executors.globals).get(name);
317
- if (!tool) throw new Error(`Unknown ${isTool ? "tool" : "global"} "${name}"`);
318
- const args = message.args === void 0 ? void 0 : JSON.parse(message.args);
319
- const value = await tool.execute(args, { signal: pending.controller.signal });
320
- reply = {
321
- type: "result",
322
- id,
323
- ok: true,
324
- payload: value === void 0 ? void 0 : JSON.stringify(value)
325
- };
326
- status = "ok";
327
- } catch (error) {
328
- reply = {
329
- type: "result",
330
- id,
331
- ok: false,
332
- payload: errorMessage(error)
333
- };
334
- status = "error";
335
- }
336
- if (!this.pending.delete(id)) return;
337
- if (record) {
338
- record.status = status;
339
- record.durationMs = performance.now() - pending.startedAt;
340
- }
341
- this.post(reply);
342
- }
343
- finish(error, value, writes, during) {
344
- if (this.finished) return;
345
- this.finished = true;
346
- clearTimeout(this.timer);
347
- this.signal?.removeEventListener("abort", this.onAbort);
348
- const now = performance.now();
349
- for (const pending of this.pending.values()) {
350
- if (pending.record) pending.record.durationMs = now - pending.startedAt;
351
- pending.controller.abort();
352
- }
353
- this.pending.clear();
354
- this.unsent = [];
355
- const ended = during === void 0 ? {} : { during: {
356
- seq: during.seq,
357
- issued: during.issued
358
- } };
359
- const result = error ? {
360
- ok: false,
361
- error,
362
- output: this.output,
363
- calls: this.calls,
364
- ...ended
365
- } : {
366
- ok: true,
367
- value,
368
- output: this.output,
369
- calls: this.calls,
370
- storeWrites: writes ?? {
371
- set: {},
372
- delete: []
373
- },
374
- ...ended
375
- };
376
- if (!this.channel) {
377
- this.resolveResult(result);
378
- return;
379
- }
380
- this.channel.stop().catch(() => void 0).then(() => this.resolveResult(result));
381
- }
382
- };
383
- /**
384
- * Tool table, defaults, and in-flight executions; the behavior every sandbox shares. Subclasses
385
- * only choose where the VM runs by passing a {@link VmLauncher}.
386
- *
387
- * The script sees `tools.<name>(args)` for every registered tool, `ALL_TOOLS`, the output helpers
388
- * `text`, `image`, `exit`, and `console.*`, `store`/`load`, and the configured globals; nothing
389
- * else (no timers, `fetch`, `process`, `require`, modules). Each `execute()` gets its own VM; the
390
- * sandbox only holds the tool table and defaults. `close()` aborts in-flight executions.
391
- */
392
- var CodemodeSandboxBase = class {
393
- toolsByName = /* @__PURE__ */ new Map();
394
- globalsByName = /* @__PURE__ */ new Map();
395
- timeoutMs;
396
- memoryLimitBytes;
397
- launch;
398
- running = /* @__PURE__ */ new Set();
399
- closed = false;
400
- constructor(options, launch) {
401
- this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
402
- this.memoryLimitBytes = options.memoryLimitBytes;
403
- this.launch = launch;
404
- for (const tool of options.tools ?? []) this.registerTool(tool);
405
- checkGlobals(options.globals ?? []);
406
- for (const global of options.globals ?? []) this.globalsByName.set(global.name, global);
407
- }
408
- /** Throws if a tool with the same name is already registered. */
409
- registerTool(tool) {
410
- if (this.toolsByName.has(tool.name)) throw new Error(`Tool "${tool.name}" is already registered`);
411
- this.toolsByName.set(tool.name, tool);
412
- }
413
- unregisterTool(name) {
414
- return this.toolsByName.delete(name);
415
- }
416
- get tools() {
417
- return [...this.toolsByName.values()];
418
- }
419
- get globals() {
420
- return [...this.globalsByName.values()];
421
- }
422
- /**
423
- * `code` is an async function body: `return` and top-level `await` work.
424
- * Never rejects for script failures; those come back as `{ ok: false }`.
425
- * The script can use `store(key, value)` and `load(key)` on `options.store`.
426
- */
427
- execute(code, options = {}) {
428
- if (this.closed) return Promise.reject(/* @__PURE__ */ new Error("Sandbox is closed"));
429
- const tools = new Map(this.toolsByName);
430
- const execution = new Execution({
431
- code,
432
- tools: [...tools.values()],
433
- globals: [...this.globalsByName.values()],
434
- executors: {
435
- tools,
436
- globals: this.globalsByName
437
- },
438
- timeoutMs: options.timeoutMs ?? this.timeoutMs,
439
- signal: options.signal,
440
- memoryLimitBytes: this.memoryLimitBytes,
441
- store: serializeStore(options.store),
442
- launch: this.launch
443
- });
444
- this.running.add(execution);
445
- return execution.promise.finally(() => this.running.delete(execution));
446
- }
447
- /**
448
- * Run `code` deterministically, with the caller answering its calls: the same script, start time, seed, tools,
449
- * globals, and store, answered with the same results in the same `seq` order, makes the same calls with the same
450
- * arguments and produces the same output, on any VM with the same fingerprint. A host can therefore replay it
451
- * after a restart. The VM runs in UTC, its clock reads `startedAt` and then the `now` of the result being
452
- * processed, its randomness comes from `seed`, and `WeakRef` and `FinalizationRegistry` do not exist.
453
- *
454
- * The sandbox's own tools and globals are not used: the run declares its own, and every call goes to
455
- * `options.onCall`. Never rejects for script failures; abort through `options.signal` to end the run with an
456
- * error the script cannot catch.
457
- */
458
- start(code, options) {
459
- if (this.closed) throw new Error("Sandbox is closed");
460
- if (!Number.isFinite(options.startedAt) || options.startedAt < 0) throw new Error("startedAt must be a non-negative number of milliseconds since the epoch");
461
- if (!Number.isInteger(options.seed) || options.seed < 0 || options.seed > 4294967295) throw new Error("seed must be a 32-bit unsigned integer");
462
- const tools = options.tools ?? [];
463
- if (new Set(tools.map((tool) => tool.name)).size !== tools.length) throw new Error("Tool names must be unique");
464
- const scriptNames = tools.map((tool) => tool.jsName ?? toCodemodeIdentifier(tool.name));
465
- if (new Set(scriptNames).size !== tools.length) throw new Error("Tool script names must be unique");
466
- const globals = options.globals ?? [];
467
- checkGlobals(globals);
468
- const execution = new Execution({
469
- code,
470
- tools,
471
- globals,
472
- executors: {
473
- tools: /* @__PURE__ */ new Map(),
474
- globals: /* @__PURE__ */ new Map()
475
- },
476
- timeoutMs: options.timeoutMs ?? Number.POSITIVE_INFINITY,
477
- signal: options.signal,
478
- memoryLimitBytes: this.memoryLimitBytes,
479
- store: serializeStore(options.store),
480
- deterministic: {
481
- startedAt: options.startedAt,
482
- seed: options.seed
483
- },
484
- control: {
485
- onStarted: options.onStarted,
486
- onCall: options.onCall,
487
- onIdle: options.onIdle
488
- },
489
- launch: this.launch
490
- });
491
- this.running.add(execution);
492
- return {
493
- result: execution.promise.finally(() => this.running.delete(execution)),
494
- deliver: (seq, now, id, outcome) => execution.deliver(seq, now, id, outcome),
495
- get finished() {
496
- return execution.finished;
497
- }
498
- };
499
- }
500
- /** Aborts in-flight executions (they resolve with `kind: "aborted"`) and rejects new ones. */
501
- async close() {
502
- this.closed = true;
503
- await Promise.all([...this.running].map((execution) => execution.abort("Sandbox closed")));
504
- }
505
- };
506
- //#endregion
507
- //#region node_modules/.pnpm/@earendil-works+pi-codemode@1.2.0/node_modules/@earendil-works/pi-codemode/dist/wasm.js
508
- const modules = /* @__PURE__ */ new Map();
509
- /**
510
- * Read and compile the QuickJS wasm once per path. `path` defaults to the file in the installed
511
- * `quickjs-wasi` package; pass it when that file lives elsewhere, for example embedded in a Bun
512
- * compiled executable. A failed load is retried on the next call.
513
- */
514
- function loadQuickJSWasm(path) {
515
- const resolved = path ?? createRequire(import.meta.url).resolve("quickjs-wasi/quickjs.wasm");
516
- let module = modules.get(resolved);
517
- if (!module) {
518
- const { WebAssembly } = globalThis;
519
- module = readFile(resolved).then((bytes) => WebAssembly.compile(bytes)).catch((error) => {
520
- modules.delete(resolved);
521
- throw error;
522
- });
523
- modules.set(resolved, module);
524
- }
525
- return module;
526
- }
527
- //#endregion
528
- //#region node_modules/.pnpm/@earendil-works+pi-codemode@1.2.0/node_modules/@earendil-works/pi-codemode/dist/runtime/host.js
529
- function defaultWorkerUrl() {
530
- return new URL(import.meta.url.endsWith(".ts") ? "./worker.ts" : "./worker.js", import.meta.url);
531
- }
532
- /**
533
- * Each execution gets its own worker thread and QuickJS VM. A fresh worker per run keeps
534
- * termination simple: a runaway script, including one that only spins the microtask queue, is
535
- * killed with `terminate()` and cannot poison a later run. Before terminating, the host sets a
536
- * shared interrupt flag that the VM polls, because Bun's `terminate()` cannot stop a thread that
537
- * is spinning in wasm.
538
- */
539
- function workerLauncher(wasm, workerUrl) {
540
- return async (data, events) => {
541
- let module;
542
- try {
543
- module = await (wasm ?? loadQuickJSWasm());
544
- } catch (error) {
545
- throw new Error(`Failed to load QuickJS: ${errorMessage(error)}`);
546
- }
547
- const interrupt = new SharedArrayBuffer(4);
548
- const workerData = {
549
- ...data,
550
- wasm: module,
551
- interrupt
552
- };
553
- let worker;
554
- try {
555
- worker = new Worker(workerUrl, { workerData });
556
- } catch (error) {
557
- throw new Error(`Failed to start worker: ${errorMessage(error)}`);
558
- }
559
- worker.on("message", (message) => {
560
- if (typeof message === "object" && message !== null && ("watch:import" in message || "watch:require" in message)) return;
561
- events.message(message);
562
- });
563
- worker.on("error", (error) => {
564
- events.failure({
565
- kind: "sandbox",
566
- name: error instanceof Error ? error.name : void 0,
567
- message: errorMessage(error)
568
- });
569
- });
570
- worker.on("exit", (code) => {
571
- events.failure({
572
- kind: "sandbox",
573
- message: `Worker exited with code ${code} before the script settled`
574
- });
575
- });
576
- return {
577
- post: (message) => worker.postMessage(message),
578
- stop: async () => {
579
- Atomics.store(new Int32Array(interrupt), 0, 1);
580
- await worker.terminate().catch(() => void 0);
581
- }
582
- };
583
- };
584
- }
585
- /**
586
- * Runs JavaScript in a QuickJS VM (a separate wasm instance) inside a worker thread. The worker
587
- * keeps script execution off the host thread: QuickJS runs synchronously, so a spinning script on
588
- * the host thread would block its event loop. Requires `node:worker_threads` (Node or Bun); see
589
- * `InlineCodemodeSandbox` and `RemoteCodemodeSandbox` in `@earendil-works/pi-codemode/portable`
590
- * for other runtimes.
591
- */
592
- var CodemodeSandbox = class extends CodemodeSandboxBase {
593
- constructor(options = {}) {
594
- super(options, workerLauncher(options.wasm, options.workerUrl ?? defaultWorkerUrl()));
595
- }
596
- };
597
- new TextDecoder();
598
- (function(SuppressedError) {
599
- return function(env) {
600
- function fail(e) {
601
- env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
602
- env.hasError = true;
603
- }
604
- var r, s = 0;
605
- function next() {
606
- while (r = env.stack.pop()) try {
607
- if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
608
- if (r.dispose) {
609
- var result = r.dispose.call(r.value);
610
- if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
611
- fail(e);
612
- return next();
613
- });
614
- } else s |= 1;
615
- } catch (e) {
616
- fail(e);
617
- }
618
- if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
619
- if (env.hasError) throw env.error;
620
- }
621
- return next();
622
- };
623
- })(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
624
- var e = new Error(message);
625
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
626
- });
627
- new TextDecoder();
628
- new TextEncoder();
629
- //#endregion
630
- //#region node_modules/.pnpm/@earendil-works+pi-codemode@1.2.0/node_modules/@earendil-works/pi-codemode/dist/runtime/prelude-source.js
631
- /**
632
- * JavaScript evaluated inside the QuickJS VM before the script runs.
633
- *
634
- * The VM is its own wasm instance, so nothing here guards a realm boundary.
635
- * The prelude keeps the host bridge in a closure so the script cannot call it
636
- * directly, and builds `tools`, `ALL_TOOLS`, the output helpers (`text`, `image`,
637
- * `exit`, `console`), and globals on top of it. Tool arguments and results cross
638
- * as JSON strings and are parsed on this side.
639
- *
640
- * Output helpers: `text(value)` appends a text item (non-strings are
641
- * JSON-stringified), `image(urlOrItem)` appends an image from a base64 `data:` URL, an
642
- * `{ image_url }` object, or an image block `{ type: "image", data, mimeType }`, and `exit()` ends the script
643
- * successfully. `console.*` appends text items marked as console output.
644
- *
645
- * `store(key, value)` and `load(key)` are synchronous: they work on a snapshot of
646
- * JSON text passed in as `storeJson`, and the keys the script wrote are reported
647
- * with a successful "done".
648
- *
649
- * Evaluates to a function `(bridge, toolsJson, globalsJson, storeJson) => { settle, run, stalled }`.
650
- * `settle(id, ok, payload, propertiesJson)` settles call `id`; a rejection's `Error` gets the own properties of the
651
- * `propertiesJson` object, except `name`, `message`, and `stack`.
652
- * `toolsJson` lists `{ name, jsName, description }`: `tools[jsName]` and `tools[name]` call the
653
- * tool, and `ALL_TOOLS` lists `{ name: jsName, description }`.
654
- * `stalled()` reports a script that has not finished while no host call is pending: with no timers
655
- * or I/O in the VM, nothing can ever resume it.
656
- * `globalsJson` lists `{ name, spread }`; `a.b` names are grouped into a frozen `a` object.
657
- * `bridge(kind, a, b, c)` with kind "call" or "global" (id, name, argsJson),
658
- * "output" ("text" or "console", text) or ("image", data, mimeType), or "done" (ok, valueJsonOrErrorJson, writesJson).
659
- *
660
- * Before anything else the prelude freezes the built-ins and makes the built-in globals read-only.
661
- * The prelude shares them with the script, so a script that patched one (for example
662
- * `Array.prototype.toJSON`) could otherwise corrupt what the prelude reports to the host.
663
- */
664
- const MAX_STORE_VALUE_CHARS = 262144;
665
- const MAX_STORE_TOTAL_CHARS = 1048576;
666
- /**
667
- * Output one script may produce with `text()`, `image()`, and `console.*`: characters of text and
668
- * base64 image data, and items. The host keeps all output until the script ends, so without a
669
- * limit a script that prints in a loop grows the host's memory until it crashes. The item limit
670
- * covers loops that print empty strings.
671
- */
672
- const MAX_OUTPUT_CHARS = 16777216;
673
- const MAX_OUTPUT_ITEMS = 1e5;
674
- const IMAGE_HELPER_EXPECTS = "image expects a non-empty image URL string, an object with image_url, or an image block { type: \"image\", data, mimeType }";
675
- const PRELUDE_SOURCE = `(function (bridge, toolsJson, globalsJson, storeJson) {
676
- "use strict";
677
-
678
- // Freeze every object reachable from the built-in globals, plus the intrinsics that are only
679
- // reachable from instances (iterator and generator prototypes, %TypedArray%).
680
- //
681
- // Freezing alone breaks ordinary code through the "override mistake": a data property that is
682
- // read-only on a prototype cannot be assigned on an instance either, so
683
- // this.name = "MyError" in an Error subclass would throw. Commonly overridden properties
684
- // become accessors whose setter defines an own property on the instance instead.
685
- (function lockdown() {
686
- const OVERRIDABLE = new Set(["constructor", "name", "message", "toString", "toLocaleString", "valueOf", "toJSON"]);
687
- const seen = new Set([globalThis]);
688
- const queue = [];
689
- const add = (value) => {
690
- if ((typeof value === "object" && value !== null) || typeof value === "function") {
691
- if (!seen.has(value)) {
692
- seen.add(value);
693
- queue.push(value);
694
- }
695
- }
696
- };
697
-
698
- // Accessors from an object literal have no own prototype object, unlike function expressions,
699
- // whose prototype.constructor would be converted again without end.
700
- function allowOverride(object, key, value, enumerable) {
701
- const { get, set } = Object.getOwnPropertyDescriptor(
702
- {
703
- get accessor() {
704
- return value;
705
- },
706
- set accessor(next) {
707
- if (this === object) {
708
- throw new TypeError("Cannot assign to read only property '" + String(key) + "' of a built-in");
709
- }
710
- if ((typeof this !== "object" || this === null) && typeof this !== "function") return;
711
- Object.defineProperty(this, key, { value: next, writable: true, enumerable: true, configurable: true });
712
- },
713
- },
714
- "accessor",
715
- );
716
- Object.defineProperty(object, key, { get, set, enumerable, configurable: false });
717
- add(get);
718
- add(set);
719
- }
720
-
721
- for (const key of Reflect.ownKeys(globalThis)) {
722
- const descriptor = Object.getOwnPropertyDescriptor(globalThis, key);
723
- add(descriptor.value);
724
- add(descriptor.get);
725
- add(descriptor.set);
726
- if ("value" in descriptor && descriptor.configurable) {
727
- Object.defineProperty(globalThis, key, { writable: false, configurable: false });
728
- }
729
- }
730
- add(Object.getPrototypeOf(function* () {}));
731
- add(Object.getPrototypeOf(async function () {}));
732
- add(Object.getPrototypeOf(async function* () {}));
733
- add(Object.getPrototypeOf(Int8Array));
734
- add(Object.getPrototypeOf([][Symbol.iterator]()));
735
- add(Object.getPrototypeOf(new Map()[Symbol.iterator]()));
736
- add(Object.getPrototypeOf(new Set()[Symbol.iterator]()));
737
- add(Object.getPrototypeOf(""[Symbol.iterator]()));
738
- add(Object.getPrototypeOf(/a/[Symbol.matchAll]("")));
739
- if (typeof Iterator === "function") {
740
- if (typeof Iterator.prototype.map === "function") add(Object.getPrototypeOf([].values().map((x) => x)));
741
- if (typeof Iterator.from === "function") add(Object.getPrototypeOf(Iterator.from({ next() {} })));
742
- }
743
-
744
- while (queue.length > 0) {
745
- const object = queue.pop();
746
- add(Object.getPrototypeOf(object));
747
- const descriptors = Object.getOwnPropertyDescriptors(object);
748
- for (const key of Reflect.ownKeys(descriptors)) {
749
- const descriptor = descriptors[key];
750
- if ("value" in descriptor) {
751
- add(descriptor.value);
752
- if (
753
- descriptor.writable &&
754
- descriptor.configurable &&
755
- (object === Object.prototype || OVERRIDABLE.has(key))
756
- ) {
757
- allowOverride(object, key, descriptor.value, descriptor.enumerable);
758
- }
759
- } else {
760
- add(descriptor.get);
761
- add(descriptor.set);
762
- }
763
- }
764
- Object.freeze(object);
765
- }
766
- })();
767
- const stringify = JSON.stringify;
768
- const parse = JSON.parse;
769
- const promiseThen = Promise.prototype.then;
770
- const ErrorCtor = Error;
771
- const TypeErrorCtor = TypeError;
772
- const RangeErrorCtor = RangeError;
773
- const pending = new Map();
774
- let nextId = 1;
775
- let finished = false;
776
- // Thrown by exit() to unwind the script after it already reported success.
777
- const EXIT = Object.freeze({});
778
-
779
- function done(ok, payload, writes) {
780
- if (finished) return;
781
- finished = true;
782
- bridge("done", ok, payload, writes);
783
- }
784
-
785
- function serialize(value) {
786
- return value === undefined ? undefined : stringify(value);
787
- }
788
-
789
- // QuickJS stacks list frames only. Prefix "Name: message" like V8 so the
790
- // text reads the same as a Node error, and drop this prelude's frames.
791
- function errorText(error) {
792
- const head = error.message ? error.name + ": " + error.message : String(error.name);
793
- const frames =
794
- typeof error.stack === "string"
795
- ? error.stack.split("\\n").filter((line) => line.trim() && !line.includes("codemode-prelude.js"))
796
- : [];
797
- return [head, ...frames].join("\\n");
798
- }
799
-
800
- function format(value) {
801
- if (typeof value === "string") return value;
802
- if (value instanceof ErrorCtor) return errorText(value);
803
- try {
804
- const json = stringify(value);
805
- return json === undefined ? String(value) : json;
806
- } catch {
807
- return String(value);
808
- }
809
- }
810
-
811
- // The host requires string fields. A script can set an error's name or message to anything, so
812
- // they are coerced, and a value whose coercion throws gets a placeholder.
813
- function describeError(error) {
814
- try {
815
- if (error instanceof ErrorCtor) {
816
- return stringify({ name: String(error.name), message: String(error.message), stack: errorText(error) });
817
- }
818
- return stringify({ message: String(format(error)) });
819
- } catch {
820
- return stringify({ message: "The script threw a value that cannot be described" });
821
- }
822
- }
823
-
824
- function caller(kind, name, spread) {
825
- return (...args) =>
826
- new Promise((resolve, reject) => {
827
- let json;
828
- try {
829
- json = serialize(spread ? args : args[0]);
830
- } catch (error) {
831
- reject(error);
832
- return;
833
- }
834
- const id = nextId++;
835
- pending.set(id, { resolve, reject });
836
- bridge(kind, id, name, json);
837
- });
838
- }
839
-
840
- const tools = Object.create(null);
841
- const allTools = [];
842
- for (const { name, jsName, description } of parse(toolsJson)) {
843
- const fn = caller("call", name);
844
- // The first tool wins when two names normalize to the same identifier.
845
- if (!(jsName in tools)) {
846
- tools[jsName] = fn;
847
- allTools.push(Object.freeze({ name: jsName, description }));
848
- }
849
- if (!(name in tools)) tools[name] = fn;
850
- }
851
- Object.freeze(tools);
852
- Object.freeze(allTools);
853
-
854
- // Reading a member that does not exist throws an error that names the close matches, instead of
855
- // a later "not a function". \`in\` checks still work.
856
- const comparable = (name) => name.toLowerCase().replace(/[^a-z0-9]/g, "");
857
- function guard(target, label, names, hint) {
858
- return new Proxy(target, {
859
- get(object, property, receiver) {
860
- if (typeof property !== "string" || property in object || property in Object.prototype || property === "then" || property === "toJSON") {
861
- return Reflect.get(object, property, receiver);
862
- }
863
- const wanted = comparable(property);
864
- const exact = names.filter((name) => comparable(name) === wanted);
865
- const close = exact.length > 0 ? exact : names.filter((name) => wanted && (comparable(name).includes(wanted) || wanted.includes(comparable(name))));
866
- let message = label + "." + property + " does not exist.";
867
- if (close.length > 0) message += " Did you mean " + close.slice(0, 5).map((name) => label + "." + name).join(", ") + "?";
868
- else if (names.length <= 20) message += " Available: " + names.join(", ") + ".";
869
- if (hint) message += " " + hint;
870
- message += ' Check for a member with "' + property + '" in ' + label + ".";
871
- throw new TypeErrorCtor(message);
872
- },
873
- });
874
- }
875
- const toolsProxy = guard(
876
- tools,
877
- "tools",
878
- allTools.map((tool) => tool.name),
879
- "ALL_TOOLS lists every tool; searchTools(query) finds tools by topic.",
880
- );
881
-
882
- const namespaces = new Map();
883
- for (const { name, spread } of parse(globalsJson)) {
884
- const fn = caller("global", name, spread);
885
- const dot = name.indexOf(".");
886
- if (dot === -1) {
887
- Object.defineProperty(globalThis, name, { value: fn, enumerable: true });
888
- continue;
889
- }
890
- const namespace = name.slice(0, dot);
891
- if (!namespaces.has(namespace)) namespaces.set(namespace, Object.create(null));
892
- namespaces.get(namespace)[name.slice(dot + 1)] = fn;
893
- }
894
- for (const [namespace, members] of namespaces) {
895
- Object.freeze(members);
896
- const value = guard(members, namespace, Object.keys(members));
897
- Object.defineProperty(globalThis, namespace, { value, enumerable: true });
898
- }
899
-
900
- // key -> JSON text. Sizes count key and JSON characters.
901
- const stored = new Map(Object.entries(parse(storeJson)));
902
- const writes = new Map();
903
- let storedChars = 0;
904
- for (const [key, json] of stored) storedChars += key.length + json.length;
905
-
906
- const STORE_HINT =
907
- "store() is for small state such as IDs or summaries. Show images with image(), keep large data in variables, or write it to a file with a tool.";
908
-
909
- function checkKey(name, key) {
910
- if (typeof key !== "string") throw new TypeError(name + "() key must be a string");
911
- }
912
-
913
- function store(key, value) {
914
- checkKey("store", key);
915
- const previous = stored.has(key) ? key.length + stored.get(key).length : 0;
916
- if (value === undefined) {
917
- stored.delete(key);
918
- storedChars -= previous;
919
- writes.set(key, undefined);
920
- return;
921
- }
922
- let json;
923
- try {
924
- json = stringify(value);
925
- } catch (error) {
926
- throw new TypeError("store(" + stringify(key) + ") value is not JSON-serializable: " + format(error));
927
- }
928
- if (json === undefined) {
929
- throw new TypeError("store(" + stringify(key) + ") value is not JSON-serializable");
930
- }
931
- if (json.length > ${MAX_STORE_VALUE_CHARS}) {
932
- throw new RangeError(
933
- "store(" + stringify(key) + ") value has " + json.length + " characters of JSON, more than the limit of ${MAX_STORE_VALUE_CHARS}. " +
934
- STORE_HINT,
935
- );
936
- }
937
- const next = storedChars - previous + key.length + json.length;
938
- if (next > ${MAX_STORE_TOTAL_CHARS}) {
939
- throw new RangeError(
940
- "store is full: stored values would exceed ${MAX_STORE_TOTAL_CHARS} characters of JSON. Delete keys with store(key, undefined). " +
941
- STORE_HINT,
942
- );
943
- }
944
- stored.set(key, json);
945
- storedChars = next;
946
- writes.set(key, json);
947
- }
948
-
949
- function load(key) {
950
- checkKey("load", key);
951
- const json = stored.get(key);
952
- return json === undefined ? undefined : parse(json);
953
- }
954
-
955
- function serializeWrites() {
956
- const entries = [];
957
- for (const [key, json] of writes) entries.push(json === undefined ? [key] : [key, json]);
958
- return stringify(entries);
959
- }
960
-
961
- Object.defineProperty(globalThis, "store", { value: store, enumerable: true });
962
- Object.defineProperty(globalThis, "load", { value: load, enumerable: true });
963
-
964
- let outputChars = 0;
965
- let outputItems = 0;
966
-
967
- // Past the output limits the script fails: done() reports the error, so catching it does not
968
- // resume output, and the host ends the script.
969
- function output(kind, data, mimeType) {
970
- if (finished) return;
971
- outputChars += data.length;
972
- outputItems++;
973
- if (outputChars > ${MAX_OUTPUT_CHARS} || outputItems > ${MAX_OUTPUT_ITEMS}) {
974
- const error = new RangeErrorCtor(
975
- "script output exceeded the limit of ${MAX_OUTPUT_CHARS} characters or ${MAX_OUTPUT_ITEMS} text(), image(), and console calls. " +
976
- "Print a summary instead, or write large data to a file with a tool.",
977
- );
978
- done(false, describeError(error));
979
- throw error;
980
- }
981
- bridge("output", kind, data, mimeType);
982
- }
983
-
984
- // Primitives become their string form, everything else JSON.
985
- function outputText(value) {
986
- if (value === undefined || value === null || typeof value !== "object" && typeof value !== "function") {
987
- return String(value);
988
- }
989
- const json = stringify(value);
990
- return json === undefined ? String(value) : json;
991
- }
992
-
993
- function text(value) {
994
- let rendered;
995
- try {
996
- rendered = outputText(value);
997
- } catch (error) {
998
- throw new TypeErrorCtor(error instanceof ErrorCtor ? error.message : String(error));
999
- }
1000
- output("text", rendered);
1001
- }
1002
-
1003
- function imageUrl(value) {
1004
- if (typeof value === "string") return value;
1005
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
1006
- throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});
1007
- }
1008
- if (value.image_url !== undefined) {
1009
- if (typeof value.image_url !== "string") throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});
1010
- return value.image_url;
1011
- }
1012
- if (typeof value.type !== "string") throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});
1013
- if (value.type !== "image") {
1014
- throw new TypeErrorCtor('image only accepts image blocks, got "' + value.type + '"');
1015
- }
1016
- if (typeof value.data !== "string" || value.data === "") throw new TypeErrorCtor("image expected image block data");
1017
- if (value.data.toLowerCase().startsWith("data:")) return value.data;
1018
- return "data:;base64," + value.data;
1019
- }
1020
-
1021
- // Base64 of the signatures of the formats providers accept inline (PNG, JPEG except
1022
- // JPEG-LS, GIF, "RIFF....WEBP"). Signatures start at byte 0, so their encodings are prefixes.
1023
- const IMAGE_SIGNATURES = [
1024
- ["image/png", /^iVBORw0KGg/],
1025
- ["image/jpeg", /^[/]9j[/](?!9)/],
1026
- ["image/gif", /^R0lGOD[dl]h/],
1027
- ["image/webp", /^UklG.{8}RUJQ/],
1028
- ];
1029
-
1030
- function image(value) {
1031
- const url = imageUrl(value);
1032
- if (url === "") throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});
1033
- const colon = url.indexOf(":");
1034
- const scheme = colon === -1 ? "" : url.slice(0, colon).toLowerCase();
1035
- if (scheme === "http" || scheme === "https") {
1036
- throw new TypeErrorCtor("remote image URLs are not supported in tool outputs. Pass a base64 data URI instead");
1037
- }
1038
- const comma = url.indexOf(",");
1039
- const header = comma === -1 ? [] : url.slice(colon + 1, comma).split(";");
1040
- if (scheme !== "data" || comma === -1 || header.slice(1).every((part) => part.toLowerCase() !== "base64")) {
1041
- throw new TypeErrorCtor("invalid image output. Pass a base64 data URI instead");
1042
- }
1043
- // Providers reject the whole request on a bad image, and a persisted image block would be
1044
- // resent on every later turn. Line breaks from wrapped base64 are dropped. The declared type
1045
- // is ignored in favor of the detected one, as providers also reject mismatches.
1046
- const data = url.slice(comma + 1).replace(/\\s+/g, "");
1047
- if (data.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(data)) {
1048
- throw new TypeErrorCtor("invalid image output. The image data is not valid base64 (truncated or corrupted?)");
1049
- }
1050
- const head = data.slice(0, 16);
1051
- const signature = IMAGE_SIGNATURES.find(([, pattern]) => pattern.test(head));
1052
- if (!signature) {
1053
- throw new TypeErrorCtor("invalid image output. The image data is not a PNG, JPEG, GIF, or WebP image");
1054
- }
1055
- output("image", data, signature[0]);
1056
- }
1057
-
1058
- function exit() {
1059
- let writesJson;
1060
- try {
1061
- writesJson = serializeWrites();
1062
- } catch (error) {
1063
- done(false, describeError(error));
1064
- throw EXIT;
1065
- }
1066
- done(true, undefined, writesJson);
1067
- throw EXIT;
1068
- }
1069
-
1070
- const console = {};
1071
- for (const level of ["log", "info", "warn", "error", "debug"]) {
1072
- console[level] = (...args) => {
1073
- output("console", args.map(format).join(" "));
1074
- };
1075
- }
1076
- Object.freeze(console);
1077
-
1078
- Object.defineProperty(globalThis, "tools", { value: toolsProxy, enumerable: true });
1079
- Object.defineProperty(globalThis, "ALL_TOOLS", { value: allTools, enumerable: true });
1080
- Object.defineProperty(globalThis, "console", { value: console, enumerable: true });
1081
- Object.defineProperty(globalThis, "text", { value: text, enumerable: true });
1082
- Object.defineProperty(globalThis, "image", { value: image, enumerable: true });
1083
- Object.defineProperty(globalThis, "exit", { value: exit, enumerable: true });
1084
-
1085
- return {
1086
- settle(id, ok, payload, propertiesJson) {
1087
- const entry = pending.get(id);
1088
- if (!entry) return;
1089
- pending.delete(id);
1090
- if (!ok) {
1091
- const error = new ErrorCtor(payload);
1092
- if (propertiesJson !== undefined) {
1093
- const properties = parse(propertiesJson);
1094
- for (const key of Object.keys(properties)) {
1095
- if (key === "name" || key === "message" || key === "stack") continue;
1096
- Object.defineProperty(error, key, { value: properties[key], writable: true, enumerable: true, configurable: true });
1097
- }
1098
- }
1099
- entry.reject(error);
1100
- return;
1101
- }
1102
- let value;
1103
- try {
1104
- value = payload === undefined ? undefined : parse(payload);
1105
- } catch (error) {
1106
- entry.reject(error);
1107
- return;
1108
- }
1109
- entry.resolve(value);
1110
- },
1111
- run(fn) {
1112
- let promise;
1113
- try {
1114
- promise = fn(toolsProxy, console);
1115
- } catch (error) {
1116
- done(false, describeError(error));
1117
- return;
1118
- }
1119
- promiseThen.call(
1120
- promise,
1121
- (value) => {
1122
- let json;
1123
- try {
1124
- json = serialize(value);
1125
- } catch (error) {
1126
- done(false, describeError(error));
1127
- return;
1128
- }
1129
- done(true, json, serializeWrites());
1130
- },
1131
- (error) => {
1132
- done(false, describeError(error));
1133
- },
1134
- );
1135
- },
1136
- stalled() {
1137
- if (finished || pending.size > 0) return false;
1138
- done(
1139
- false,
1140
- stringify({
1141
- name: "Error",
1142
- message:
1143
- "The script is waiting on a promise that can never settle: no tool call is pending, and timers do not exist here.",
1144
- }),
1145
- );
1146
- return true;
1147
- },
1148
- };
1149
- })`;
1150
- //#endregion
1151
- //#region node_modules/.pnpm/@earendil-works+pi-codemode@1.2.0/node_modules/@earendil-works/pi-codemode/dist/runtime/vm.js
1152
- /** FNV-1a over UTF-16 code units, as 8 hex digits: identifies the prelude in the fingerprint. */
1153
- function fnv1a(text) {
1154
- let hash = 2166136261;
1155
- for (let index = 0; index < text.length; index++) {
1156
- hash ^= text.charCodeAt(index);
1157
- hash = Math.imul(hash, 16777619);
1158
- }
1159
- return (hash >>> 0).toString(16).padStart(8, "0");
1160
- }
1161
- fnv1a(PRELUDE_SOURCE);
1162
- //#endregion
1163
- //#region node_modules/.pnpm/@earendil-works+pi-coding-agent@1.2.0_@aws-sdk+credential-provider-node@3.972.86_@model_cb83c1bd7a7ff5cede8c43e329c5cf76/node_modules/@earendil-works/pi-coding-agent/dist/extensions/codemode/execute.js
1164
- /**
1165
- * Runs one codemode script in the sandbox. Split from tool.ts and loaded through
1166
- * execute.lazy.ts so the sandbox runtime only loads when a script runs.
1167
- */
1168
- const ARGS_PREVIEW_CHARS = 200;
1169
- const ERROR_PREVIEW_CHARS = 500;
1170
- /** `models.classify()` and `models.generateImages()` calls one script may have in flight; `Promise.all` over many items queues the rest. */
1171
- const MAX_CONCURRENT_MODEL_CALLS = 4;
1172
- /**
1173
- * Heap limit for the QuickJS VM. The worker shares pi's process, so without a limit a runaway
1174
- * script can grow to wasm32's 4 GiB and take the session down. Overruns throw
1175
- * `InternalError: out of memory` inside the script.
1176
- */
1177
- const CODEMODE_MEMORY_LIMIT_BYTES = 268435456;
1178
- const MODEL_TYPES = /* @__PURE__ */ new Set([
1179
- "chat",
1180
- "image",
1181
- "classifier"
1182
- ]);
1183
- function truncateText(text, maxChars) {
1184
- return text.length > maxChars ? `${text.slice(0, maxChars - 3)}...` : text;
1185
- }
1186
- function previewArgs(args) {
1187
- if (args === void 0) return "";
1188
- try {
1189
- return truncateText(JSON.stringify(args) ?? "", ARGS_PREVIEW_CHARS);
1190
- } catch {
1191
- return "";
1192
- }
1193
- }
1194
- function textOf(result) {
1195
- return (result.content ?? []).filter((block) => block.type === "text").map((block) => block.text).join("\n");
1196
- }
1197
- function toModelType(value) {
1198
- if (typeof value === "string" && MODEL_TYPES.has(value)) return value;
1199
- throw new Error(`Unknown model type ${JSON.stringify(value)}. Use "chat", "image", or "classifier".`);
1200
- }
1201
- function toProvider(value) {
1202
- if (value === void 0 || value === null) return void 0;
1203
- if (typeof value !== "string") throw new Error("provider must be a string");
1204
- return value;
1205
- }
1206
- /** Catalog entry for scripts. `headers` is dropped because models.json headers can carry credentials. */
1207
- function toModelInfo(model) {
1208
- const info = { ...model };
1209
- delete info.headers;
1210
- return info;
1211
- }
1212
- /** `an image`, `a classifier`. */
1213
- function withArticle(word) {
1214
- return `${/^[aeiou]/.test(word) ? "an" : "a"} ${word}`;
1215
- }
1216
- /** A script value in an error message: `undefined`, `a string`, `an array`, or its keys (`{ prompt }`). */
1217
- function describeValue(value) {
1218
- if (value === void 0 || value === null) return String(value);
1219
- if (Array.isArray(value)) return value.length === 0 ? "an empty array" : "an array";
1220
- if (typeof value === "object") {
1221
- const keys = Object.keys(value);
1222
- if (keys.length === 0) return "{}";
1223
- return `{ ${keys.slice(0, 6).join(", ")}${keys.length > 6 ? ", ..." : ""} }`;
1224
- }
1225
- return typeof value === "string" ? "a string" : `a ${typeof value}`;
1226
- }
1227
- const CLASSIFIER_CONTEXT_SHAPE = "{ state: { ... }, images?: [{ type: \"image\", data: <base64>, mimeType }], questions: { <id>: { type: \"choice\", instructions, criteria: { <label>: <meaning> } } | { type: \"score\", instructions, criteria: [<lowest level>, ..., <highest level>] } | { type: \"bool\", instructions, criteria: { true: <meaning>, false: <meaning> } } } }";
1228
- /** Check a script's classifier context, so mistakes fail with the expected shape instead of a provider error. */
1229
- function checkClassifierContext(context) {
1230
- const fail = (problem) => /* @__PURE__ */ new Error(`models.classify() ${problem}. Expected context: ${CLASSIFIER_CONTEXT_SHAPE}. See "Classify" in ${CODEMODE_DOCS_PATH}.`);
1231
- if (typeof context !== "object" || context === null || Array.isArray(context)) throw fail(`expects a context object as its second argument, got ${describeValue(context)}`);
1232
- const { state, images, questions } = context;
1233
- if (typeof state !== "object" || state === null || Array.isArray(state)) throw fail(`context.state must be an object, got ${describeValue(state)}`);
1234
- if (images !== void 0) {
1235
- if (!Array.isArray(images)) throw fail(`context.images must be an array, got ${describeValue(images)}`);
1236
- images.forEach((image, index) => {
1237
- if (image?.type !== "image" || typeof image.data !== "string" || typeof image.mimeType !== "string") throw fail(`context.images[${index}] must be an image block, got ${describeValue(image)}`);
1238
- });
1239
- }
1240
- if (typeof questions !== "object" || questions === null || Array.isArray(questions) || Object.keys(questions).length === 0) throw fail(`context.questions must map question IDs to questions, got ${describeValue(questions)}`);
1241
- const isStrings = (values) => values.length > 0 && values.every((value) => typeof value === "string");
1242
- for (const [id, question] of Object.entries(questions)) {
1243
- const at = `context.questions.${id}`;
1244
- if (typeof question !== "object" || question === null || Array.isArray(question)) throw fail(`${at} must be a question object, got ${describeValue(question)}`);
1245
- const { type, instructions, criteria } = question;
1246
- if (typeof instructions !== "string") throw fail(`${at}.instructions must be a string`);
1247
- if (type === "choice") {
1248
- if (typeof criteria !== "object" || criteria === null || Array.isArray(criteria) || !isStrings(Object.values(criteria))) throw fail(`${at} is a "choice" question, so criteria must map each label to its meaning`);
1249
- } else if (type === "score") {
1250
- if (!Array.isArray(criteria) || !isStrings(criteria)) throw fail(`${at} is a "score" question, so criteria must list the levels as strings, lowest first`);
1251
- } else if (type === "bool") {
1252
- const labels = criteria;
1253
- if (typeof labels?.true !== "string" || typeof labels.false !== "string") throw fail(`${at} is a "bool" question, so criteria must be { true: string, false: string }`);
1254
- } else throw fail(`${at}.type must be "choice", "score", or "bool", got ${JSON.stringify(type)}`);
1255
- }
1256
- return context;
1257
- }
1258
- /** Check a script's image context, so mistakes such as `{ prompt }` fail with the expected shape. */
1259
- function checkImagesContext(context) {
1260
- const fail = (problem) => /* @__PURE__ */ new Error(`models.generateImages() ${problem}. Expected context: { input: [{ type: "text", text: <prompt> }, ...optional { type: "image", data: <base64>, mimeType } references] }. See "Generate images" in ${CODEMODE_DOCS_PATH}.`);
1261
- if (typeof context !== "object" || context === null || Array.isArray(context)) throw fail(`expects a context object as its second argument, got ${describeValue(context)}`);
1262
- const { input } = context;
1263
- if (!Array.isArray(input) || input.length === 0) throw fail(`context.input must be a non-empty array of blocks, got ${describeValue(input)}`);
1264
- input.forEach((block, index) => {
1265
- if (block?.type === "text" && typeof block.text === "string") return;
1266
- if (block?.type === "image" && typeof block.data === "string" && typeof block.mimeType === "string") return;
1267
- throw fail(`context.input[${index}] must be a text or image block, got ${describeValue(block)}`);
1268
- });
1269
- return context;
1270
- }
1271
- /** Runs at most `limit` calls at once, in call order. */
1272
- function createLimiter(limit) {
1273
- let active = 0;
1274
- const waiting = [];
1275
- return async (run) => {
1276
- if (active >= limit) await new Promise((resolve) => waiting.push(resolve));
1277
- active++;
1278
- try {
1279
- return await run();
1280
- } finally {
1281
- active--;
1282
- waiting.shift()?.();
1283
- }
1284
- };
1285
- }
1286
- function isStoreEntryData(data) {
1287
- if (typeof data !== "object" || data === null) return false;
1288
- const { set, delete: deleted } = data;
1289
- return typeof set === "object" && set !== null && Array.isArray(deleted) && deleted.every((key) => typeof key === "string");
1290
- }
1291
- /** Values of `load()`: the `codemode-store` entries on the branch, applied from the root. */
1292
- function readCodemodeStore(branch) {
1293
- const store = /* @__PURE__ */ new Map();
1294
- for (const entry of branch) {
1295
- if (entry.type !== "custom" || entry.customType !== "codemode-store" || !isStoreEntryData(entry.data)) continue;
1296
- for (const key of entry.data.delete) store.delete(key);
1297
- for (const [key, value] of Object.entries(entry.data.set)) store.set(key, value);
1298
- }
1299
- return Object.fromEntries(store);
1300
- }
1301
- /** Default token budget for script output. */
1302
- const DEFAULT_MAX_OUTPUT_TOKENS = 1e4;
1303
- /** Characters per token when estimating. */
1304
- const CHARS_PER_TOKEN = 4;
1305
- /** Like the script's `text()`: strings as is, other values as compact JSON. */
1306
- function valueText(value) {
1307
- if (typeof value === "string") return value;
1308
- return JSON.stringify(value) ?? String(value);
1309
- }
1310
- /**
1311
- * Lay out the script's output so the model can tell items apart: providers join adjacent text
1312
- * blocks with a newline or with nothing. With more than one text item (`text()` or the returned
1313
- * value), each starts with a `==> text N/M <==` line. `console.*` lines follow all other output in
1314
- * one `<console_output>` block.
1315
- */
1316
- function formatOutput(output) {
1317
- const total = output.filter((item) => item.type === "text" && !item.console).length;
1318
- const items = [];
1319
- const consoleLines = [];
1320
- let index = 0;
1321
- for (const item of output) if (item.type === "image") items.push(item);
1322
- else if (item.console) consoleLines.push(item.text);
1323
- else {
1324
- index++;
1325
- items.push({
1326
- type: "text",
1327
- text: total > 1 ? `==> text ${index}/${total} <==\n${item.text}` : item.text
1328
- });
1329
- }
1330
- if (consoleLines.length > 0) items.push({
1331
- type: "text",
1332
- text: `<console_output>\n${consoleLines.join("\n")}\n</console_output>`
1333
- });
1334
- return items;
1335
- }
1336
- /**
1337
- * Join adjacent text items into one, each part starting on its own line. The separator check looks
1338
- * at the last non-empty part, not the joined text: reading the end of a growing concatenation makes
1339
- * V8 copy it on every item, which is quadratic (#10678).
1340
- */
1341
- function joinAdjacentText(items) {
1342
- const joined = [];
1343
- let parts = [];
1344
- let lastPart = "";
1345
- const flush = () => {
1346
- if (parts.length > 0) joined.push({
1347
- type: "text",
1348
- text: parts.join("")
1349
- });
1350
- parts = [];
1351
- lastPart = "";
1352
- };
1353
- for (const item of items) {
1354
- if (item.type !== "text") {
1355
- flush();
1356
- joined.push(item);
1357
- continue;
1358
- }
1359
- if (lastPart !== "" && !lastPart.endsWith("\n")) {
1360
- parts.push("\n");
1361
- lastPart = "\n";
1362
- }
1363
- parts.push(item.text);
1364
- if (item.text !== "") lastPart = item.text;
1365
- }
1366
- flush();
1367
- return joined;
1368
- }
1369
- function formatCallSummary(calls) {
1370
- if (calls.length === 0) return "No tool calls were made.";
1371
- return `Tool calls made before the failure (they are not undone): ${calls.map((call) => `${call.name} (${call.status})`).join(", ")}`;
1372
- }
1373
- function formatError(result, calls) {
1374
- const { error } = result;
1375
- return `${error.kind === "script" ? error.stack ?? `${error.name ?? "Error"}: ${error.message}` : error.kind === "timeout" ? `Script timed out: ${error.message}` : error.kind === "aborted" ? `Script aborted: ${error.message}` : `Script sandbox failed: ${error.message}`}\n\n${formatCallSummary(calls)}`;
1376
- }
1377
- /** Write the full text output to a temp file, like bash does for truncated output. */
1378
- async function spillOutput(text) {
1379
- try {
1380
- return { path: await writeOutputFile("pi-codemode", ".txt", text) };
1381
- } catch (error) {
1382
- return { error: error instanceof Error ? error.message : String(error) };
1383
- }
1384
- }
1385
- /** File extensions of the image types `image()` accepts. Must list every type the sandbox's `image()` detects. */
1386
- const IMAGE_EXTENSIONS = {
1387
- "image/png": ".png",
1388
- "image/jpeg": ".jpg",
1389
- "image/gif": ".gif",
1390
- "image/webp": ".webp"
1391
- };
1392
- /**
1393
- * Save each image to a temp file and put a text item with its path before it. The model sees the
1394
- * image but has no other way to reach its bytes: scripts cannot write files, and `write` only takes
1395
- * text. Images shown more than once are saved once.
1396
- */
1397
- async function saveImages(items) {
1398
- const labels = /* @__PURE__ */ new Map();
1399
- const label = async ({ data, mimeType }) => {
1400
- const bytes = Buffer.from(data, "base64");
1401
- const kind = `${mimeType}, ${formatSize(bytes.length)}`;
1402
- const extension = IMAGE_EXTENSIONS[mimeType];
1403
- if (!extension) throw new Error(`No file extension for image type ${mimeType}`);
1404
- try {
1405
- return `[Image saved to ${await writeOutputFile("pi-codemode", extension, bytes)} (${kind})]`;
1406
- } catch (error) {
1407
- return `[Image (${kind}) could not be saved: ${error instanceof Error ? error.message : String(error)}]`;
1408
- }
1409
- };
1410
- return (await Promise.all(items.map(async (item) => {
1411
- if (item.type !== "image") return [item];
1412
- let pending = labels.get(item.data);
1413
- if (!pending) {
1414
- pending = label(item);
1415
- labels.set(item.data, pending);
1416
- }
1417
- return [{
1418
- type: "text",
1419
- text: await pending
1420
- }, item];
1421
- }))).flat();
1422
- }
1423
- /**
1424
- * Apply the token budget: when the combined text exceeds it, the text items become one
1425
- * item that keeps the start and end of the text, and images follow it. The full text is written to
1426
- * a temp file.
1427
- */
1428
- async function truncateOutput(items, maxTokens) {
1429
- const texts = items.filter((item) => item.type === "text").map((item) => item.text);
1430
- const combined = texts.join("\n");
1431
- const budget = maxTokens * CHARS_PER_TOKEN;
1432
- if (texts.length === 0 || combined.length <= budget) return { items };
1433
- const headChars = Math.floor(budget / 2);
1434
- const tailChars = budget - headChars;
1435
- const removed = combined.length - headChars - tailChars;
1436
- const head = combined.slice(0, headChars);
1437
- const tail = tailChars > 0 ? combined.slice(-tailChars) : "";
1438
- let text = `Warning: truncated output (original token count: ${Math.ceil(combined.length / CHARS_PER_TOKEN)})\nTotal output lines: ${combined.split("\n").length}\n\n${head}…${Math.ceil(removed / CHARS_PER_TOKEN)} tokens truncated…${tail}`;
1439
- const spilled = await spillOutput(combined);
1440
- text += "path" in spilled ? `\n\n[Full output: ${spilled.path} (read with offset/limit)]` : `\n\n[Could not save the full output: ${spilled.error}]`;
1441
- return {
1442
- items: [{
1443
- type: "text",
1444
- text
1445
- }, ...items.filter((item) => item.type === "image")],
1446
- ..."path" in spilled ? { fullOutputPath: spilled.path } : {}
1447
- };
1448
- }
1449
- /**
1450
- * The value a script receives for a nested call: a tool that declares
1451
- * `outputSchema` resolves to its `structuredContent`, also for error results that carry one (such
1452
- * as MCP results with `isError`); any other tool resolves to its text content. Other failures
1453
- * reject with the tool's error text.
1454
- */
1455
- function toScriptValue(tool, outcome) {
1456
- const { result } = outcome;
1457
- if (tool.outputSchema && result.structuredContent !== void 0) return result.structuredContent;
1458
- const text = textOf(result);
1459
- if (outcome.isError) throw new Error(text || `Tool "${tool.name}" failed`);
1460
- return text;
1461
- }
1462
- /**
1463
- * Run one script. Without a session context (a plain Agent or a direct call) scripts cannot call
1464
- * tools, `store()` starts empty, and writes are dropped.
1465
- */
1466
- async function executeCodemode(toolCallId, input, signal, onUpdate, ctx, options = {}) {
1467
- const startedAt = performance.now();
1468
- const { code, options: sourceOptions } = parseCodemodeSource(input.code);
1469
- const calls = [];
1470
- let modelUsage;
1471
- let generatedImages = 0;
1472
- const addGeneratedImages = (count) => {
1473
- generatedImages += count;
1474
- };
1475
- const addModelUsage = (usage) => {
1476
- modelUsage = modelUsage ? combineUsage(modelUsage, usage) : usage;
1477
- };
1478
- const snapshot = () => ({ calls: calls.map((call) => ({ ...call })) });
1479
- const publish = () => onUpdate?.({
1480
- content: [],
1481
- details: snapshot()
1482
- });
1483
- publish();
1484
- const callable = ctx ? getCodemodeCallableTools(ctx.tools) : [];
1485
- const guidelines = options.getToolGuidelines?.();
1486
- const samples = new Map(callable.map((tool) => [tool.name, renderToolSample(toCodemodeDeclaration(tool, guidelines?.get(tool.name)))]));
1487
- const sandbox = new CodemodeSandbox({
1488
- tools: callable.map((tool) => ({
1489
- name: tool.name,
1490
- description: samples.get(tool.name),
1491
- execute: async (args, { signal: callSignal }) => {
1492
- const record = {
1493
- id: `${toolCallId}/?`,
1494
- name: tool.name,
1495
- args: previewArgs(args),
1496
- status: "running"
1497
- };
1498
- calls.push(record);
1499
- publish();
1500
- const callStartedAt = performance.now();
1501
- if (!ctx) throw new Error("Tool calls need a session");
1502
- const outcome = await ctx.executeTool(tool.name, args, { signal: callSignal });
1503
- record.id = outcome.toolCall.id;
1504
- record.durationMs = performance.now() - callStartedAt;
1505
- if (outcome.isError) {
1506
- record.status = callSignal.aborted ? "cancelled" : "error";
1507
- record.error = truncateText(textOf(outcome.result) || `Tool "${tool.name}" failed`, ERROR_PREVIEW_CHARS);
1508
- } else record.status = "ok";
1509
- publish();
1510
- return toScriptValue(tool, outcome);
1511
- }
1512
- })),
1513
- globals: [...createDiscoveryGlobals(callable, samples, options), ...options.models && ctx ? createModelGlobals(ctx.modelRegistry, toolCallId, calls, publish, addModelUsage, addGeneratedImages) : []],
1514
- timeoutMs: sourceOptions.timeoutMs ?? Number.POSITIVE_INFINITY,
1515
- memoryLimitBytes: CODEMODE_MEMORY_LIMIT_BYTES,
1516
- wasm: loadQuickJSWasm(getQuickJSWasmPath()),
1517
- workerUrl: getCodemodeWorkerSpecifier()
1518
- });
1519
- let result;
1520
- try {
1521
- const store = ctx ? readCodemodeStore(ctx.sessionManager.getBranch()) : {};
1522
- result = await sandbox.execute(code, {
1523
- signal,
1524
- store
1525
- });
1526
- } finally {
1527
- await sandbox.close();
1528
- }
1529
- for (const call of calls) if (call.status === "running") call.status = "cancelled";
1530
- const scriptOutput = [...result.output];
1531
- if (result.ok) {
1532
- const { set, delete: deleted } = result.storeWrites;
1533
- if (Object.keys(set).length > 0 || deleted.length > 0) options.appendEntry?.(CODEMODE_STORE_ENTRY_TYPE, {
1534
- set,
1535
- delete: deleted
1536
- });
1537
- if (result.value !== void 0) scriptOutput.push({
1538
- type: "text",
1539
- text: valueText(result.value)
1540
- });
1541
- }
1542
- const items = formatOutput(scriptOutput);
1543
- if (!result.ok) items.push({
1544
- type: "text",
1545
- text: `Script error:\n${formatError(result, calls)}`
1546
- });
1547
- if (generatedImages > 0 && !items.some((item) => item.type === "image")) items.push({
1548
- type: "text",
1549
- text: `Note: models.generateImages() returned ${generatedImages} image${generatedImages === 1 ? "" : "s"} that the script did not show. Show each image block of result.output with image(block).`
1550
- });
1551
- const truncated = await truncateOutput(joinAdjacentText(items), sourceOptions.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS);
1552
- const output = joinAdjacentText(await saveImages(truncated.items));
1553
- const wallTime = ((performance.now() - startedAt) / 1e3).toFixed(1);
1554
- const header = `${result.ok ? "Script completed" : "Script failed"}\nWall time ${wallTime} seconds\nOutput:\n`;
1555
- const details = snapshot();
1556
- if (truncated.fullOutputPath) details.fullOutputPath = truncated.fullOutputPath;
1557
- return {
1558
- content: [{
1559
- type: "text",
1560
- text: header
1561
- }, ...output],
1562
- details,
1563
- ...modelUsage ? { usage: modelUsage } : {},
1564
- ...result.ok ? {} : { isError: true }
1565
- };
1566
- }
1567
- /**
1568
- * Whether `query` names the namespace: its name or one of its aliases, as written or as the same
1569
- * script identifier (`dev-radius` and `dev_radius` are both `dev_radius`).
1570
- */
1571
- function isNamespaceName(namespace, query) {
1572
- const queryId = toCodemodeIdentifier(query);
1573
- return [namespace.name, ...namespace.aliases ?? []].some((name) => name === query || toCodemodeIdentifier(name) === queryId);
1574
- }
1575
- /**
1576
- * `searchTools()`, `describeTool()`, and `describeNamespace()`: ranked search and lookup over the
1577
- * script's nested tools and their namespaces.
1578
- */
1579
- function createDiscoveryGlobals(tools, samples, options) {
1580
- const ranker = new Bm25Ranker();
1581
- const entry = (name) => ({
1582
- name: toCodemodeIdentifier(name),
1583
- description: samples.get(name) ?? ""
1584
- });
1585
- return [
1586
- {
1587
- name: "searchTools",
1588
- spread: true,
1589
- execute: (args) => {
1590
- const [query, searchOptions] = args;
1591
- if (typeof query !== "string") throw new Error("searchTools() expects a query string");
1592
- const limit = searchOptions?.limit ?? 8;
1593
- if (typeof limit !== "number" || !Number.isInteger(limit) || limit <= 0) throw new Error("searchTools() limit must be a positive integer");
1594
- const namespace = searchOptions?.namespace;
1595
- if (namespace !== void 0 && namespace !== null && typeof namespace !== "string") throw new Error("searchTools() namespace must be a string");
1596
- const documents = tools.flatMap((tool) => {
1597
- const toolNamespace = options.getToolNamespace?.(tool.name);
1598
- if (namespace && (!toolNamespace || !isNamespaceName(toolNamespace, namespace))) return [];
1599
- return [createToolSearchDocument(tool, toolNamespace)];
1600
- });
1601
- return ranker.rank(query, documents, limit).map((match) => entry(match.name));
1602
- }
1603
- },
1604
- {
1605
- name: "describeTool",
1606
- spread: true,
1607
- execute: (args) => {
1608
- const [name] = args;
1609
- if (typeof name !== "string") throw new Error("describeTool() expects a tool name");
1610
- const tool = tools.find((candidate) => candidate.name === name || toCodemodeIdentifier(candidate.name) === name);
1611
- return tool ? samples.get(tool.name) : void 0;
1612
- }
1613
- },
1614
- {
1615
- name: "describeNamespace",
1616
- spread: true,
1617
- execute: (args) => {
1618
- const [name] = args;
1619
- if (typeof name !== "string") throw new Error("describeNamespace() expects a namespace name");
1620
- let namespace;
1621
- const names = [];
1622
- for (const tool of tools) {
1623
- const toolNamespace = options.getToolNamespace?.(tool.name);
1624
- if (!toolNamespace || !isNamespaceName(toolNamespace, name)) continue;
1625
- namespace ??= toolNamespace;
1626
- names.push(toCodemodeIdentifier(tool.name));
1627
- }
1628
- if (!namespace) return void 0;
1629
- return {
1630
- name: namespace.name,
1631
- ...namespace.description ? { description: namespace.description } : {},
1632
- ...namespace.instructions ? { instructions: namespace.instructions } : {},
1633
- tools: names
1634
- };
1635
- }
1636
- }
1637
- ];
1638
- }
1639
- /**
1640
- * `models.*` for scripts: the model registry methods documented in docs/codemode.md.
1641
- * Classifier and image calls appear as nested call rows so the renderer shows them, and their usage
1642
- * goes to `addUsage`. Rows show only the model, never prompts or image data.
1643
- */
1644
- function createModelGlobals(models, toolCallId, calls, publish, addUsage, addGeneratedImages) {
1645
- const limit = createLimiter(MAX_CONCURRENT_MODEL_CALLS);
1646
- let callCount = 0;
1647
- /**
1648
- * Resolve the script's model by provider and id only, check the context, then run the call as a
1649
- * nested call row. A script-supplied baseUrl or headers must never receive the credentials.
1650
- */
1651
- const runModelCall = async (name, type, [model, context], checkContext, run) => {
1652
- const listHint = `List the ${type} models you can use with models.getAvailableOfType("${type}").`;
1653
- const given = model;
1654
- if (typeof given?.provider !== "string" || typeof given.id !== "string") {
1655
- const undefinedHint = model === void 0 || model === null ? " models.getModelOfType() returns undefined for an unknown provider or id." : "";
1656
- throw new Error(`${name}() expects ${withArticle(type)} model as its first argument, got ${describeValue(model)}.${undefinedHint} ${listHint}`);
1657
- }
1658
- const provider = given.provider;
1659
- const id = given.id;
1660
- const ref = `${provider}/${id}`;
1661
- const resolved = models.getModelOfType(type, provider, id);
1662
- if (!resolved) {
1663
- const actualType = [...MODEL_TYPES].find((other) => other !== type && models.getModelOfType(other, provider, id) !== void 0);
1664
- throw new Error(actualType ? `"${ref}" is ${withArticle(actualType)} model, not ${withArticle(type)} model. ${listHint}` : `Unknown ${type} model "${ref}". ${listHint}`);
1665
- }
1666
- const checked = checkContext(context);
1667
- const record = {
1668
- id: `${toolCallId}/${name}/${++callCount}`,
1669
- name,
1670
- args: `${resolved.provider}/${resolved.id}`,
1671
- status: "running"
1672
- };
1673
- calls.push(record);
1674
- publish();
1675
- const startedAt = performance.now();
1676
- const result = await limit(() => run(resolved, checked));
1677
- record.durationMs = performance.now() - startedAt;
1678
- record.status = result.stopReason === "stop" ? "ok" : result.stopReason === "aborted" ? "cancelled" : "error";
1679
- if (result.errorMessage) record.error = truncateText(result.errorMessage, ERROR_PREVIEW_CHARS);
1680
- if (result.usage) {
1681
- record.cost = result.usage.cost.total;
1682
- addUsage(result.usage);
1683
- }
1684
- publish();
1685
- return result;
1686
- };
1687
- return Object.entries({
1688
- "models.getModelsOfType": (args) => {
1689
- const [type, provider] = args;
1690
- return models.getModelsOfType(toModelType(type), toProvider(provider)).map(toModelInfo);
1691
- },
1692
- "models.getAvailableOfType": async (args, { signal }) => {
1693
- const [type, provider] = args;
1694
- return (await models.getAvailableOfType(toModelType(type), toProvider(provider), { signal })).map(toModelInfo);
1695
- },
1696
- "models.getModelOfType": (args) => {
1697
- const [type, provider, id] = args;
1698
- if (typeof provider !== "string" || typeof id !== "string") throw new Error(`models.getModelOfType(type, provider, id) expects three strings, got (${args.map(describeValue).join(", ")}). The provider and the id are separate arguments, for example models.getModelOfType("classifier", "typesafe", "jev-latest").`);
1699
- const model = models.getModelOfType(toModelType(type), provider, id);
1700
- return model === void 0 ? void 0 : toModelInfo(model);
1701
- },
1702
- "models.classify": (args, { signal }) => runModelCall("models.classify", "classifier", args, checkClassifierContext, (resolved, context) => models.classify(resolved, context, { signal })),
1703
- "models.generateImages": (args, { signal }) => runModelCall("models.generateImages", "image", args, checkImagesContext, async (resolved, context) => {
1704
- const result = await models.generateImages(resolved, context, { signal });
1705
- addGeneratedImages(result.output.filter((block) => block.type === "image").length);
1706
- return result;
1707
- })
1708
- }).map(([name, execute]) => ({
1709
- name,
1710
- spread: true,
1711
- execute
1712
- }));
1713
- }
1714
- //#endregion
1715
- export { executeCodemode, readCodemodeStore };