@cortex-agent/server 2026.11.17 → 2026.12.5

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 (338) hide show
  1. package/README.md +5 -5
  2. package/THIRD_PARTY_NOTICES.txt +860 -294
  3. package/defaults/hooks/quota-stop.mjs +37 -0
  4. package/defaults/prompts/clean-workspace.md +5 -0
  5. package/dist/agent-adapter/claude/remote-mcp-proxy.js +1 -1
  6. package/dist/chunks/agent-runner-LVZVKBZX.js +4 -0
  7. package/dist/chunks/anthropic-messages-TT6454AA.js +8 -0
  8. package/dist/chunks/azure-openai-responses-52LR2XZD.js +4 -0
  9. package/dist/chunks/bedrock-converse-stream-EOZGYUNY.js +60 -0
  10. package/dist/chunks/child-runner-SMG2VOU5.js +4 -0
  11. package/dist/chunks/chunk-24DH4IR5.js +4 -0
  12. package/dist/chunks/chunk-25XKBRDT.js +70 -0
  13. package/dist/chunks/{chunk-VTL3Z2OP.js → chunk-2ABET62E.js} +1 -1
  14. package/dist/chunks/chunk-2BVUA256.js +4 -0
  15. package/dist/chunks/{chunk-4YLAGSDM.js → chunk-2WFL62UO.js} +1 -1
  16. package/dist/chunks/{chunk-LQTFDC67.js → chunk-335SSANX.js} +1 -1
  17. package/dist/chunks/chunk-377OPTXX.js +17 -0
  18. package/dist/chunks/chunk-3EZNVLBF.js +129 -0
  19. package/dist/chunks/{chunk-V6X7Y62J.js → chunk-3O6ZG5HA.js} +1 -1
  20. package/dist/chunks/{chunk-6AKUD3CF.js → chunk-3XLHL5YT.js} +1 -1
  21. package/dist/chunks/{chunk-2ATTYCRJ.js → chunk-4HRI75GU.js} +1 -1
  22. package/dist/chunks/chunk-4JBYLRPM.js +57 -0
  23. package/dist/chunks/chunk-4KKV7VKE.js +4 -0
  24. package/dist/chunks/chunk-4KQHDDC5.js +4 -0
  25. package/dist/chunks/chunk-4SWD4JMP.js +33 -0
  26. package/dist/chunks/chunk-52VCLZS5.js +4 -0
  27. package/dist/chunks/chunk-54P7TSY3.js +10 -0
  28. package/dist/chunks/chunk-5DVSAXOI.js +7 -0
  29. package/dist/chunks/chunk-5F3A62YS.js +4 -0
  30. package/dist/chunks/{chunk-S3MR37DL.js → chunk-5FHETFZM.js} +1 -1
  31. package/dist/chunks/{chunk-CEGSDGYQ.js → chunk-5LBLRAHS.js} +1 -1
  32. package/dist/chunks/chunk-5UYVNA3W.js +4 -0
  33. package/dist/chunks/chunk-6G3OYMCV.js +21 -0
  34. package/dist/chunks/chunk-7GGPYU5E.js +30 -0
  35. package/dist/chunks/chunk-7TYSMLUV.js +4 -0
  36. package/dist/chunks/chunk-7W7VYUTK.js +5 -0
  37. package/dist/chunks/chunk-AXYAZTTN.js +6 -0
  38. package/dist/chunks/chunk-B3NB243Z.js +4 -0
  39. package/dist/chunks/{chunk-XPPZ6Y3X.js → chunk-BKYP6AGM.js} +1 -1
  40. package/dist/chunks/{chunk-QUXPMNFQ.js → chunk-BVEDNESB.js} +1 -1
  41. package/dist/chunks/chunk-BWDJS6A4.js +12 -0
  42. package/dist/chunks/chunk-C6YVF7EI.js +4 -0
  43. package/dist/chunks/chunk-CEJIYYVE.js +15 -0
  44. package/dist/chunks/{chunk-5PAW3DEU.js → chunk-CI2RHH74.js} +4 -4
  45. package/dist/chunks/{chunk-OFEPDNRB.js → chunk-CMSOOLJB.js} +1 -1
  46. package/dist/chunks/chunk-CSVTYYLP.js +4 -0
  47. package/dist/chunks/chunk-DE5EGVKG.js +6 -0
  48. package/dist/chunks/{chunk-E6BYRULL.js → chunk-DK3RPZOQ.js} +1 -1
  49. package/dist/chunks/{chunk-ROVKOIHF.js → chunk-DK4UCK7L.js} +1 -1
  50. package/dist/chunks/chunk-DYLBVUAU.js +4 -0
  51. package/dist/chunks/{chunk-WBSE3EF3.js → chunk-FDC2GRBK.js} +1 -1
  52. package/dist/chunks/chunk-FE7HH5JS.js +18 -0
  53. package/dist/chunks/chunk-FYD57YRO.js +436 -0
  54. package/dist/chunks/chunk-G264APQN.js +5 -0
  55. package/dist/chunks/chunk-G4JYZFEO.js +11 -0
  56. package/dist/chunks/chunk-GFFM56U2.js +4 -0
  57. package/dist/chunks/chunk-GOS3P7KS.js +132 -0
  58. package/dist/chunks/{chunk-2VVRTJQN.js → chunk-HVN37UXD.js} +1 -1
  59. package/dist/chunks/{chunk-53TQNK7Z.js → chunk-IGZWZP7Z.js} +1 -1
  60. package/dist/chunks/{chunk-AFTBQRPN.js → chunk-IJ7XFQMI.js} +1 -1
  61. package/dist/chunks/{chunk-U23S37TT.js → chunk-IMMGYDAB.js} +1 -1
  62. package/dist/chunks/chunk-IOWBF7UK.js +10 -0
  63. package/dist/chunks/{chunk-MGYYSX7Y.js → chunk-ITGCWQFK.js} +1 -1
  64. package/dist/chunks/{chunk-QEL6CMLE.js → chunk-IVZ7QUEG.js} +1 -1
  65. package/dist/chunks/{chunk-EE3WT25T.js → chunk-IWY2HIFK.js} +1 -1
  66. package/dist/chunks/{chunk-KGJZAYQD.js → chunk-J7OBATRN.js} +1 -1
  67. package/dist/chunks/{chunk-NXZS5PEW.js → chunk-JGUEIW2W.js} +1 -1
  68. package/dist/chunks/chunk-JZ7U7RUK.js +351 -0
  69. package/dist/chunks/{chunk-VIMHSW6J.js → chunk-KJUQCCB5.js} +1 -1
  70. package/dist/chunks/{chunk-BUZQBTV2.js → chunk-KST6OY76.js} +1 -1
  71. package/dist/chunks/{chunk-KDPY2YA3.js → chunk-KZSAFVSY.js} +2 -2
  72. package/dist/chunks/chunk-LD2ZSH3M.js +903 -0
  73. package/dist/chunks/{chunk-RYLSRII6.js → chunk-LE6QPXN6.js} +1 -1
  74. package/dist/chunks/{chunk-TX46YMGI.js → chunk-LIIZI3HY.js} +1 -1
  75. package/dist/chunks/{chunk-3CZPBLB3.js → chunk-MJQ2D2OP.js} +1 -1
  76. package/dist/chunks/{chunk-P7TVR4GY.js → chunk-NHHR4DCF.js} +1 -1
  77. package/dist/chunks/chunk-NW4GW47L.js +4 -0
  78. package/dist/chunks/chunk-OALEJ6FG.js +60 -0
  79. package/dist/chunks/chunk-OIV4DIMB.js +4 -0
  80. package/dist/chunks/{chunk-T73GHMFB.js → chunk-OJ37ZWBG.js} +1 -1
  81. package/dist/chunks/{chunk-7GEBDPTT.js → chunk-OZXMPBUX.js} +1 -1
  82. package/dist/chunks/chunk-PG7452XE.js +4 -0
  83. package/dist/chunks/chunk-PJCUB7YJ.js +4 -0
  84. package/dist/chunks/{chunk-RA2BUYI3.js → chunk-PTS3J4DQ.js} +1 -1
  85. package/dist/chunks/{chunk-2ROGTDM2.js → chunk-PVVEEBUU.js} +1 -1
  86. package/dist/chunks/{chunk-W6AKCEYF.js → chunk-Q7BZLPBU.js} +1 -1
  87. package/dist/chunks/{chunk-SY2HV3V5.js → chunk-QC66ZXPP.js} +1 -1
  88. package/dist/chunks/chunk-QXFWIL4C.js +4 -0
  89. package/dist/chunks/{chunk-NRD57ICT.js → chunk-R2CCD4OF.js} +1 -1
  90. package/dist/chunks/{chunk-R52AVUQB.js → chunk-RG5GP4RB.js} +1 -1
  91. package/dist/chunks/{chunk-IKLTEWA3.js → chunk-RW2F2QNP.js} +1 -1
  92. package/dist/chunks/{chunk-XEBEWR6Y.js → chunk-RWPO3NZ3.js} +1 -1
  93. package/dist/chunks/chunk-SDUS2H3E.js +4 -0
  94. package/dist/chunks/chunk-SIHGKM4E.js +4 -0
  95. package/dist/chunks/{chunk-NNBSSISP.js → chunk-SKHFU5DI.js} +1 -1
  96. package/dist/chunks/{chunk-STUHNKQS.js → chunk-SM45TH22.js} +1 -1
  97. package/dist/chunks/chunk-T54CZKNJ.js +6 -0
  98. package/dist/chunks/chunk-TRXLIL7V.js +4 -0
  99. package/dist/chunks/{chunk-KUDK7GPS.js → chunk-UEEW2R4E.js} +1 -1
  100. package/dist/chunks/chunk-UHXPRU6G.js +10 -0
  101. package/dist/chunks/chunk-UPQVWHZ3.js +4 -0
  102. package/dist/chunks/{chunk-BDLKI2NT.js → chunk-VHX2GHBF.js} +1 -1
  103. package/dist/chunks/chunk-VOAKRJ4R.js +4 -0
  104. package/dist/chunks/{chunk-FP7ML72L.js → chunk-WU7RNAZD.js} +1 -1
  105. package/dist/chunks/chunk-WZC4TDDM.js +6 -0
  106. package/dist/chunks/chunk-X2TKJ7KR.js +11 -0
  107. package/dist/chunks/{chunk-H4QZ2P3Z.js → chunk-X5ND4H4P.js} +1 -1
  108. package/dist/chunks/{chunk-5A6CA5TM.js → chunk-Y3AOGNDT.js} +1 -1
  109. package/dist/chunks/chunk-Y6DGVTKM.js +6 -0
  110. package/dist/chunks/{chunk-LP7T32PW.js → chunk-YAEHSSR4.js} +1 -1
  111. package/dist/chunks/chunk-YWPBE5LP.js +4 -0
  112. package/dist/chunks/chunk-ZAVX7G2M.js +15 -0
  113. package/dist/chunks/chunk-ZD2M73XA.js +19 -0
  114. package/dist/chunks/chunk-ZD4O6NPV.js +4 -0
  115. package/dist/chunks/chunk-ZNAMETPQ.js +4 -0
  116. package/dist/chunks/chunk-ZY6N5LVQ.js +4 -0
  117. package/dist/chunks/chunk-ZYQ4TDTT.js +81 -0
  118. package/dist/chunks/cli-VB2N7HEK.js +55 -0
  119. package/dist/chunks/cloudflare-workers-ai-system-one-YKU742EC.js +4 -0
  120. package/dist/chunks/context-CI2FKEQE.js +4 -0
  121. package/dist/chunks/cost-CZRRSIUF.js +5 -0
  122. package/dist/chunks/dist-QCNQN6DY.js +4 -0
  123. package/dist/chunks/{easter-egg-3d-CZH7AYZ7.js → easter-egg-3d-XR5S2O3T.js} +1 -1
  124. package/dist/chunks/execution-repo-5TLV2NM4.js +4 -0
  125. package/dist/chunks/{executions-BN6OLLVM.js → executions-I3UUIGSL.js} +1 -1
  126. package/dist/chunks/file-Y5G56IUT.js +4 -0
  127. package/dist/chunks/github-copilot-BRU2SRRZ.js +4 -0
  128. package/dist/chunks/google-generative-ai-ZF5QEUZV.js +4 -0
  129. package/dist/chunks/google-vertex-4PJZZI3Y.js +4 -0
  130. package/dist/chunks/init-A6GY656J.js +4 -0
  131. package/dist/chunks/{install-cli-ABBD7DO5.js → install-cli-FALWKQYO.js} +1 -1
  132. package/dist/chunks/{interaction-ask-EE2UPR3Q.js → interaction-ask-O5HGF6CH.js} +1 -1
  133. package/dist/chunks/{interaction-plan-C446T2GZ.js → interaction-plan-JTVDN3BC.js} +1 -1
  134. package/dist/chunks/kimi-coding-ZCIBMDZ6.js +4 -0
  135. package/dist/chunks/{llama-cpp-classify-IA2F2H7A.js → llama-cpp-classify-NRUXAIGQ.js} +3 -3
  136. package/dist/chunks/local-client-stop-RS4AHNF4.js +4 -0
  137. package/dist/chunks/memory-cli-DIT4DQF3.js +11 -0
  138. package/dist/chunks/meta-JQH66YU7.js +4 -0
  139. package/dist/chunks/mistral-conversations-CXHOECUV.js +7 -0
  140. package/dist/chunks/model-resolver-GIBPYRKP.js +4 -0
  141. package/dist/chunks/monitor-Z2HKNY5E.js +4 -0
  142. package/dist/chunks/openai-codex-responses-U6DGMGDK.js +12 -0
  143. package/dist/chunks/openai-completions-PP4XLLOM.js +9 -0
  144. package/dist/chunks/{openai-decisions-P5UX7BWY.js → openai-decisions-JU6QQKEM.js} +1 -1
  145. package/dist/chunks/openai-responses-2SG757TL.js +6 -0
  146. package/dist/chunks/openrouter-images-32M7YZWC.js +4 -0
  147. package/dist/chunks/pi-messages-VSINMXN4.js +10 -0
  148. package/dist/chunks/radius-THYKWV4E.js +4 -0
  149. package/dist/chunks/remote-ops-2WBEFQ3E.js +14 -0
  150. package/dist/chunks/runner-5MKMRTIN.js +4 -0
  151. package/dist/chunks/runtime-DST3H5JP.js +4 -0
  152. package/dist/chunks/schedule-cli-V7Y2BBVY.js +4 -0
  153. package/dist/chunks/slack-R7SEJYMY.js +4 -0
  154. package/dist/chunks/start-ui-http-7K5JOLPU.js +43 -0
  155. package/dist/chunks/subagent-Z5IQ4L54.js +4 -0
  156. package/dist/chunks/tool-shims-YCXZWTST.js +4 -0
  157. package/dist/chunks/typesafe-system-one-M2DABJSZ.js +4 -0
  158. package/dist/chunks/ui-board-HQIE4RZG.js +5 -0
  159. package/dist/chunks/ui-decision-YBZDS4YW.js +4 -0
  160. package/dist/chunks/{ui-file-6PLXHSTB.js → ui-file-SRD4ILBS.js} +1 -1
  161. package/dist/chunks/ui-view-Z25MTZT7.js +4 -0
  162. package/dist/chunks/virtual-modules-H4DXPJZB.js +4 -0
  163. package/dist/chunks/{waitpoint-W5M3BE55.js → waitpoint-M6JZBSLT.js} +1 -1
  164. package/dist/chunks/workers-SQ2R32TK.js +4 -0
  165. package/dist/client-bundle/client.mjs +229 -62
  166. package/dist/client-bundle/manifest.json +2 -2
  167. package/dist/core/pi-sdk.js +1 -1
  168. package/dist/domain/auth/cc-auth-cli.js +1 -1
  169. package/dist/domain/mcp/bundled-server.js +1 -1
  170. package/dist/domain/mcp/feishu/client.js +1 -1
  171. package/dist/entry/app.js +138 -556
  172. package/dist/entry/browser-cli.js +1 -1
  173. package/dist/entry/cli.js +1 -1
  174. package/dist/entry/cortex-cli.js +1 -1
  175. package/dist/entry/daemon.js +3 -3
  176. package/dist/entry/hook-cli.js +1 -1
  177. package/dist/entry/production-app-bootstrap.js +1 -1
  178. package/dist/entry/production-evidence-export-cli.js +1 -1
  179. package/dist/entry/signal-cli.js +1 -1
  180. package/dist/tui/index.js +1 -1
  181. package/package.json +1 -1
  182. package/vendor/pi/CHANGELOG.md +330 -0
  183. package/vendor/pi/dist/codemode-worker.js +2 -0
  184. package/vendor/pi/dist/core/export-html/ansi-to-html.js +57 -20
  185. package/vendor/pi/dist/core/export-html/template.css +9 -0
  186. package/vendor/pi/dist/core/export-html/template.js +166 -46
  187. package/vendor/pi/dist/core/export-html/tool-renderer.js +5 -3
  188. package/vendor/pi/dist/core/extensions/loader.js +1 -1
  189. package/vendor/pi/dist/extensions/codemode/execute.js +15 -13
  190. package/vendor/pi/dist/modes/interactive/theme/theme.js +36 -23
  191. package/vendor/pi/dist/utils/image-resize-worker.js +1 -1
  192. package/vendor/pi/dist/utils/image-resize.js +1 -1
  193. package/vendor/pi/docs/cli.md +35 -12
  194. package/vendor/pi/docs/custom-provider.md +2 -0
  195. package/vendor/pi/docs/environment-variables.md +2 -0
  196. package/vendor/pi/docs/extensions.md +3192 -225
  197. package/vendor/pi/docs/keybindings.md +2 -2
  198. package/vendor/pi/docs/llama-cpp.md +27 -19
  199. package/vendor/pi/docs/mcp.md +6 -4
  200. package/vendor/pi/docs/message-types.md +1 -1
  201. package/vendor/pi/docs/models-configuration.md +9 -3
  202. package/vendor/pi/docs/models.md +2 -1
  203. package/vendor/pi/docs/nvidia-rtx-llama-cpp.md +5 -5
  204. package/vendor/pi/docs/packages.md +24 -0
  205. package/vendor/pi/docs/prompt-templates.md +1 -1
  206. package/vendor/pi/docs/providers.md +4 -2
  207. package/vendor/pi/docs/quickstart.md +7 -3
  208. package/vendor/pi/docs/rpc-commands.md +1 -1
  209. package/vendor/pi/docs/rpc.md +4 -2
  210. package/vendor/pi/docs/sessions.md +17 -3
  211. package/vendor/pi/docs/settings.md +6 -5
  212. package/vendor/pi/docs/slash-commands.md +3 -2
  213. package/vendor/pi/docs/terminal-setup.md +3 -1
  214. package/vendor/pi/docs/tmux.md +6 -0
  215. package/vendor/pi/docs/tui.md +4 -0
  216. package/vendor/pi/docs/windows.md +27 -0
  217. package/vendor/pi/examples/extensions/README.md +2 -1
  218. package/vendor/pi/examples/extensions/custom-provider-anthropic/index.ts +27 -31
  219. package/vendor/pi/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  220. package/vendor/pi/examples/extensions/custom-provider-anthropic/package.json +1 -1
  221. package/vendor/pi/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  222. package/vendor/pi/examples/extensions/debug-provider.ts +2 -2
  223. package/vendor/pi/examples/extensions/gondolin/index.ts +4 -7
  224. package/vendor/pi/examples/extensions/gondolin/package-lock.json +19 -29
  225. package/vendor/pi/examples/extensions/gondolin/package.json +2 -2
  226. package/vendor/pi/examples/extensions/plan-mode/index.ts +23 -13
  227. package/vendor/pi/examples/extensions/plan-mode/utils.ts +42 -16
  228. package/vendor/pi/examples/extensions/preset.ts +2 -0
  229. package/vendor/pi/examples/extensions/reload-runtime.ts +17 -5
  230. package/vendor/pi/examples/extensions/subagent/README.md +14 -11
  231. package/vendor/pi/examples/extensions/subagent/index.ts +392 -171
  232. package/vendor/pi/examples/extensions/todo.ts +7 -0
  233. package/vendor/pi/examples/extensions/tools.ts +2 -0
  234. package/vendor/pi/examples/extensions/with-deps/package-lock.json +2 -2
  235. package/vendor/pi/examples/extensions/with-deps/package.json +1 -1
  236. package/vendor/pi/examples/tsconfig.json +208 -0
  237. package/vendor/pi/package.json +15 -16
  238. package/vendor/pi/schemas/models.schema.json +66 -37
  239. package/vendor/pi/schemas/settings.schema.json +18 -1
  240. package/vendor/pi-ai/bedrock.js +1 -1
  241. package/vendor/pi-ai/oauth-load.js +1 -1
  242. package/web/dist/assets/{board-math-css-BgIyUG-C.js → board-math-css-DKX6FcUS.js} +1 -1
  243. package/web/dist/assets/index-D11wi0uG.js +540 -0
  244. package/web/dist/assets/index-JedYumhY.css +1 -0
  245. package/web/dist/assets/{index-C2eMpcuI.js → index-jl30Gy8P.js} +1 -1
  246. package/web/dist/index.html +2 -2
  247. package/dist/chunks/anthropic-messages-M732OMEE.js +0 -8
  248. package/dist/chunks/azure-openai-responses-RAKTV6JY.js +0 -4
  249. package/dist/chunks/bedrock-converse-stream-WNUGNZ27.js +0 -62
  250. package/dist/chunks/child-runner-MO5RT6FH.js +0 -4
  251. package/dist/chunks/chunk-3CPIMAYX.js +0 -30
  252. package/dist/chunks/chunk-3ORG56I5.js +0 -8
  253. package/dist/chunks/chunk-4EX2JJWB.js +0 -4
  254. package/dist/chunks/chunk-5DF5WJNM.js +0 -60
  255. package/dist/chunks/chunk-7GAYFN52.js +0 -18
  256. package/dist/chunks/chunk-AVXDF7AG.js +0 -4
  257. package/dist/chunks/chunk-BJGYGEZO.js +0 -6
  258. package/dist/chunks/chunk-BZDIAI5M.js +0 -125
  259. package/dist/chunks/chunk-CK3P345X.js +0 -133
  260. package/dist/chunks/chunk-CVC66CFV.js +0 -33
  261. package/dist/chunks/chunk-ETIBCA2S.js +0 -4
  262. package/dist/chunks/chunk-FF7UELTU.js +0 -4
  263. package/dist/chunks/chunk-FX6MOGLR.js +0 -11
  264. package/dist/chunks/chunk-G2V65UBA.js +0 -4
  265. package/dist/chunks/chunk-HGPBHTVD.js +0 -6
  266. package/dist/chunks/chunk-IYVZHGUQ.js +0 -5
  267. package/dist/chunks/chunk-JJDEQ6N2.js +0 -4
  268. package/dist/chunks/chunk-KDYEGGMW.js +0 -4
  269. package/dist/chunks/chunk-L6VCIGWS.js +0 -11
  270. package/dist/chunks/chunk-LACGULCN.js +0 -10
  271. package/dist/chunks/chunk-LAWOWPZX.js +0 -363
  272. package/dist/chunks/chunk-NNTQUHLO.js +0 -877
  273. package/dist/chunks/chunk-OE4KH3NJ.js +0 -4
  274. package/dist/chunks/chunk-OSEIQ7SS.js +0 -4
  275. package/dist/chunks/chunk-PZMGBKUR.js +0 -13
  276. package/dist/chunks/chunk-QBKCAIJG.js +0 -4
  277. package/dist/chunks/chunk-QMSSIDRQ.js +0 -70
  278. package/dist/chunks/chunk-QUUEQRIT.js +0 -4
  279. package/dist/chunks/chunk-RA6HKFBV.js +0 -4
  280. package/dist/chunks/chunk-RDW6FRF5.js +0 -4
  281. package/dist/chunks/chunk-RF4JLYBX.js +0 -6
  282. package/dist/chunks/chunk-SFX7V5O2.js +0 -10
  283. package/dist/chunks/chunk-SKHLZ6XY.js +0 -9
  284. package/dist/chunks/chunk-STCNHXPJ.js +0 -6
  285. package/dist/chunks/chunk-UT6DGZDO.js +0 -4
  286. package/dist/chunks/chunk-VBN2JSER.js +0 -5
  287. package/dist/chunks/chunk-VK5J556O.js +0 -4
  288. package/dist/chunks/chunk-VPVSKJGX.js +0 -6
  289. package/dist/chunks/chunk-VQUPKMDR.js +0 -4
  290. package/dist/chunks/chunk-WEZWKMYU.js +0 -4
  291. package/dist/chunks/chunk-XYSXL3KX.js +0 -4
  292. package/dist/chunks/chunk-Y3GFB5XM.js +0 -8
  293. package/dist/chunks/chunk-YAAKL3QS.js +0 -80
  294. package/dist/chunks/chunk-YB5LUJHS.js +0 -65
  295. package/dist/chunks/chunk-YKKEI5GI.js +0 -4
  296. package/dist/chunks/chunk-Z24SBRJK.js +0 -4
  297. package/dist/chunks/cli-5DBTRMHU.js +0 -53
  298. package/dist/chunks/cloudflare-workers-ai-system-one-32JCFHI3.js +0 -4
  299. package/dist/chunks/context-GQKWKFRM.js +0 -4
  300. package/dist/chunks/cost-OOO32GLC.js +0 -5
  301. package/dist/chunks/dist-V5FRMUFH.js +0 -4
  302. package/dist/chunks/execution-repo-XXL4FXC6.js +0 -4
  303. package/dist/chunks/file-H572PL2Z.js +0 -4
  304. package/dist/chunks/github-copilot-HAI2DA62.js +0 -4
  305. package/dist/chunks/google-generative-ai-2G4ITOZL.js +0 -4
  306. package/dist/chunks/google-vertex-PACHCMRZ.js +0 -4
  307. package/dist/chunks/init-75F4V7SK.js +0 -4
  308. package/dist/chunks/kimi-coding-HMJRKCPA.js +0 -4
  309. package/dist/chunks/local-client-stop-5YOLXGYT.js +0 -4
  310. package/dist/chunks/memory-cli-5SSF6YJM.js +0 -11
  311. package/dist/chunks/meta-KY3LNFV2.js +0 -4
  312. package/dist/chunks/mistral-conversations-VHP63CDS.js +0 -7
  313. package/dist/chunks/model-resolver-FVJNZ6NA.js +0 -4
  314. package/dist/chunks/openai-codex-responses-EHJ4AZBE.js +0 -12
  315. package/dist/chunks/openai-completions-CRAGQFCE.js +0 -9
  316. package/dist/chunks/openai-responses-IZ22NVQ7.js +0 -6
  317. package/dist/chunks/openrouter-images-W2JAMSRH.js +0 -4
  318. package/dist/chunks/pi-messages-MJEEQU2R.js +0 -10
  319. package/dist/chunks/radius-ZM7ZRMXF.js +0 -4
  320. package/dist/chunks/remote-ops-O5CR4RGA.js +0 -14
  321. package/dist/chunks/runner-S6R3US24.js +0 -4
  322. package/dist/chunks/runtime-6YLTA2ZD.js +0 -4
  323. package/dist/chunks/schedule-cli-4T4YC5V5.js +0 -4
  324. package/dist/chunks/slack-2CGM4SMY.js +0 -4
  325. package/dist/chunks/start-ui-http-3D7QNHGB.js +0 -43
  326. package/dist/chunks/subagent-OZGUOV3J.js +0 -4
  327. package/dist/chunks/tool-shims-IA2WELXJ.js +0 -4
  328. package/dist/chunks/typesafe-system-one-6ULACYD4.js +0 -4
  329. package/dist/chunks/ui-board-H4INJD6C.js +0 -5
  330. package/dist/chunks/ui-decision-6HHNROIT.js +0 -4
  331. package/dist/chunks/ui-view-6MDU4GXY.js +0 -4
  332. package/dist/chunks/virtual-modules-OFI7QKYH.js +0 -4
  333. package/dist/chunks/workers-GTFP75MS.js +0 -4
  334. package/vendor/pi/examples/extensions/sandbox/index.ts +0 -321
  335. package/vendor/pi/examples/extensions/sandbox/package-lock.json +0 -92
  336. package/vendor/pi/examples/extensions/sandbox/package.json +0 -19
  337. package/web/dist/assets/index-9lyu2S6W.css +0 -1
  338. package/web/dist/assets/index-C-hpzey7.js +0 -532
@@ -98,14 +98,12 @@
98
98
  }
99
99
  }
100
100
 
101
- // Sort children by timestamp
102
- function sortChildren(node) {
101
+ // Sort children by timestamp. Iterative: long sessions form chains deeper than the JS call stack.
102
+ for (const node of nodeMap.values()) {
103
103
  node.children.sort((a, b) =>
104
104
  new Date(a.entry.timestamp).getTime() - new Date(b.entry.timestamp).getTime()
105
105
  );
106
- node.children.forEach(sortChildren);
107
106
  }
108
- roots.forEach(sortChildren);
109
107
 
110
108
  return roots;
111
109
  }
@@ -134,14 +132,14 @@
134
132
  const path = [];
135
133
  let current = byId.get(targetId);
136
134
  while (current) {
137
- path.unshift(current);
135
+ path.push(current);
138
136
  // Stop if no parent or self-referencing (root)
139
137
  if (!current.parentId || current.parentId === current.id) {
140
138
  break;
141
139
  }
142
140
  current = byId.get(current.parentId);
143
141
  }
144
- return path;
142
+ return path.reverse();
145
143
  }
146
144
 
147
145
  // Tree node lookup for finding leaves
@@ -156,12 +154,12 @@
156
154
  // Build tree node map lazily
157
155
  if (!treeNodeMap) {
158
156
  treeNodeMap = new Map();
159
- const tree = buildTree();
160
- function mapNodes(node) {
157
+ const stack = [...buildTree()];
158
+ while (stack.length > 0) {
159
+ const node = stack.pop();
161
160
  treeNodeMap.set(node.entry.id, node);
162
- node.children.forEach(mapNodes);
161
+ for (const child of node.children) stack.push(child);
163
162
  }
164
- tree.forEach(mapNodes);
165
163
  }
166
164
 
167
165
  const node = treeNodeMap.get(nodeId);
@@ -185,16 +183,22 @@
185
183
  const multipleRoots = roots.length > 1;
186
184
 
187
185
  // Mark which subtrees contain the active leaf
186
+ // Iterative post-order: long sessions form chains deeper than the JS call stack.
188
187
  const containsActive = new Map();
189
- function markActive(node) {
190
- let has = activePathIds.has(node.entry.id);
191
- for (const child of node.children) {
192
- if (markActive(child)) has = true;
193
- }
194
- containsActive.set(node, has);
195
- return has;
188
+ const postOrder = [];
189
+ const pending = [...roots];
190
+ while (pending.length > 0) {
191
+ const node = pending.pop();
192
+ postOrder.push(node);
193
+ for (const child of node.children) pending.push(child);
194
+ }
195
+ for (let i = postOrder.length - 1; i >= 0; i--) {
196
+ const node = postOrder[i];
197
+ containsActive.set(
198
+ node,
199
+ activePathIds.has(node.entry.id) || node.children.some(child => containsActive.get(child))
200
+ );
196
201
  }
197
- roots.forEach(markActive);
198
202
 
199
203
  // Stack: [node, indent, justBranched, showConnector, isLast, gutters, isVirtualRootChild]
200
204
  const stack = [];
@@ -313,6 +317,76 @@
313
317
  return '';
314
318
  }
315
319
 
320
+ // ============================================================
321
+ // SYSTEM MESSAGES (pure data)
322
+ // ============================================================
323
+
324
+ function systemContentText(content) {
325
+ if (typeof content === 'string') return content;
326
+ if (Array.isArray(content)) {
327
+ return content.filter(c => c.type === 'text' && c.text).map(c => c.text).join('\n');
328
+ }
329
+ return '';
330
+ }
331
+
332
+ /** Full prompt text of a system message, mirroring getSystemMessageText() in pi-ai. */
333
+ function getSystemMessageText(msg) {
334
+ const parts = [systemContentText(msg.content)];
335
+ for (const value of Object.values(msg.sections || {})) {
336
+ if (value !== null) parts.push(value);
337
+ }
338
+ return parts.filter(part => part.length > 0).join('\n\n');
339
+ }
340
+
341
+ /** Text of a later system message, mirroring renderSystemMessageUpdate() in pi-ai. */
342
+ function renderSystemMessageUpdate(msg) {
343
+ const parts = [];
344
+ const text = systemContentText(msg.content);
345
+ if (text.length > 0) parts.push(text);
346
+ for (const [name, value] of Object.entries(msg.sections || {})) {
347
+ parts.push(value === null
348
+ ? `Removed system prompt section "${name}".`
349
+ : `Updated system prompt section "${name}":\n\n${value}`);
350
+ }
351
+ return parts.join('\n\n');
352
+ }
353
+
354
+ function carriesSystemState(entry) {
355
+ return (entry.type === 'message' && entry.message.role === 'system') ||
356
+ (entry.type === 'compaction' && entry.systemMessage);
357
+ }
358
+
359
+ /**
360
+ * Whether a system entry starts the prompt on its branch. Later system entries
361
+ * patch the prompt, so they render as updates instead of a full prompt.
362
+ */
363
+ function isLeadingSystemEntry(entry) {
364
+ let current = entry.parentId && entry.parentId !== entry.id ? byId.get(entry.parentId) : undefined;
365
+ while (current) {
366
+ if (carriesSystemState(current)) return false;
367
+ if (!current.parentId || current.parentId === current.id) break;
368
+ current = byId.get(current.parentId);
369
+ }
370
+ return true;
371
+ }
372
+
373
+ /** Short description of what a later system message changes, e.g. "project_context, -rules, tools +bash". */
374
+ function describeSystemUpdate(msg) {
375
+ const parts = [];
376
+ if (systemContentText(msg.content).length > 0) parts.push('instructions');
377
+ for (const [name, value] of Object.entries(msg.sections || {})) {
378
+ parts.push(value === null ? `-${name}` : name);
379
+ }
380
+ const toolChanges = [
381
+ ...(msg.toolsAdded || []).map(t => `+${t.name}`),
382
+ ...(msg.toolsRemoved || []).map(t => `-${t.name}`),
383
+ ];
384
+ if (toolChanges.length > 0) parts.push(`tools ${toolChanges.join(' ')}`);
385
+ return parts.join(', ');
386
+ }
387
+
388
+ const hasSystemEntries = entries.some(entry => entry.type === 'message' && entry.message.role === 'system');
389
+
316
390
  /**
317
391
  * Parse a skill block from message text.
318
392
  * Returns null if the text doesn't contain a skill block.
@@ -337,6 +411,13 @@
337
411
  case 'message': {
338
412
  const msg = entry.message;
339
413
  parts.push(msg.role);
414
+ if (msg.role === 'system') {
415
+ parts.push(isLeadingSystemEntry(entry) ? 'system prompt' : 'system update');
416
+ parts.push(getSystemMessageText(msg));
417
+ for (const name of Object.keys(msg.sections || {})) parts.push(name);
418
+ for (const tool of [...(msg.toolsAdded || []), ...(msg.toolsRemoved || [])]) parts.push(tool.name);
419
+ break;
420
+ }
340
421
  if (msg.content) parts.push(extractContent(msg.content));
341
422
  if (msg.role === 'bashExecution' && msg.command) parts.push(msg.command);
342
423
  break;
@@ -675,6 +756,13 @@
675
756
  const cmd = truncate(normalize(msg.command || ''));
676
757
  return labelHtml + `<span class="tree-role-tool">[bash]:</span> ${escapeHtml(cmd)}`;
677
758
  }
759
+ if (msg.role === 'system') {
760
+ if (isLeadingSystemEntry(entry)) {
761
+ return labelHtml + `<span class="tree-muted">[system prompt]</span>`;
762
+ }
763
+ const changes = describeSystemUpdate(msg);
764
+ return labelHtml + `<span class="tree-muted">[system update${changes ? ': ' + escapeHtml(truncate(changes)) : ''}]</span>`;
765
+ }
678
766
  return labelHtml + `<span class="tree-muted">[${escapeHtml(msg.role)}]</span>`;
679
767
  }
680
768
  case 'compaction':
@@ -1059,7 +1147,7 @@
1059
1147
 
1060
1148
  if (rendered.resultHtmlCollapsed && rendered.resultHtmlExpanded && rendered.resultHtmlCollapsed !== rendered.resultHtmlExpanded) {
1061
1149
  // Both collapsed and expanded differ - render expandable section
1062
- html += `<div class="tool-output expandable ansi-rendered" onclick="if(window.getSelection().toString())return;this.classList.toggle('expanded')">
1150
+ html += `<div class="tool-output expandable ansi-rendered" onclick="if(window.getSelection().toString()||event.target.closest('a'))return;this.classList.toggle('expanded')">
1063
1151
  <div class="output-preview">${rendered.resultHtmlCollapsed}</div>
1064
1152
  <div class="output-full">${rendered.resultHtmlExpanded}</div>
1065
1153
  </div>`;
@@ -1311,6 +1399,24 @@
1311
1399
  }
1312
1400
 
1313
1401
  if (msg.role === 'toolResult') return '';
1402
+
1403
+ if (msg.role === 'system') {
1404
+ let html = '';
1405
+ if (isLeadingSystemEntry(entry)) {
1406
+ const text = getSystemMessageText(msg);
1407
+ if (text) html += renderSystemPromptBlock('System Prompt', text);
1408
+ html += renderToolsList('Available Tools', msg.toolsAdded);
1409
+ } else {
1410
+ const text = renderSystemMessageUpdate(msg);
1411
+ const changes = describeSystemUpdate(msg);
1412
+ if (text) html += renderSystemPromptBlock(`System Prompt Update${changes ? ': ' + changes : ''}`, text);
1413
+ html += renderToolsList('Tools Added', msg.toolsAdded);
1414
+ if (msg.toolsRemoved && msg.toolsRemoved.length > 0) {
1415
+ html += `<div class="tools-list"><div class="tools-header">Tools Removed</div><div class="tools-content">${msg.toolsRemoved.map(t => `<div class="tool-item"><span class="tool-item-name">${escapeHtml(t.name)}</span></div>`).join('')}</div></div>`;
1416
+ }
1417
+ }
1418
+ return html ? `<div class="system-entry" id="${entryDomId}">${tsHtml}${html}</div>` : '';
1419
+ }
1314
1420
  }
1315
1421
 
1316
1422
  if (entry.type === 'model_change') {
@@ -1351,7 +1457,7 @@
1351
1457
  let userMessages = 0, assistantMessages = 0, toolResults = 0;
1352
1458
  let customMessages = 0, compactions = 0, branchSummaries = 0, toolCalls = 0;
1353
1459
  const tokens = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
1354
- const cost = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
1460
+ const cost = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 };
1355
1461
  const models = new Set();
1356
1462
 
1357
1463
  for (const entry of entryList) {
@@ -1367,10 +1473,18 @@
1367
1473
  tokens.cacheRead += msg.usage.cacheRead || 0;
1368
1474
  tokens.cacheWrite += msg.usage.cacheWrite || 0;
1369
1475
  if (msg.usage.cost) {
1476
+ const componentTotal =
1477
+ (msg.usage.cost.input || 0) +
1478
+ (msg.usage.cost.output || 0) +
1479
+ (msg.usage.cost.cacheRead || 0) +
1480
+ (msg.usage.cost.cacheWrite || 0);
1370
1481
  cost.input += msg.usage.cost.input || 0;
1371
1482
  cost.output += msg.usage.cost.output || 0;
1372
1483
  cost.cacheRead += msg.usage.cost.cacheRead || 0;
1373
1484
  cost.cacheWrite += msg.usage.cost.cacheWrite || 0;
1485
+ // Provider-reported totals can intentionally differ from catalog-estimated components.
1486
+ // Fall back to the component sum for sessions written before cost.total was recorded.
1487
+ cost.total += typeof msg.usage.cost.total === 'number' ? msg.usage.cost.total : componentTotal;
1374
1488
  }
1375
1489
  }
1376
1490
  toolCalls += msg.content.filter(c => c.type === 'toolCall').length;
@@ -1391,7 +1505,7 @@
1391
1505
  const globalStats = computeStats(entries);
1392
1506
 
1393
1507
  function renderHeader() {
1394
- const totalCost = globalStats.cost.input + globalStats.cost.output + globalStats.cost.cacheRead + globalStats.cost.cacheWrite;
1508
+ const totalCost = globalStats.cost.total;
1395
1509
 
1396
1510
  const tokenParts = [];
1397
1511
  if (globalStats.tokens.input) tokenParts.push(`↑${formatTokens(globalStats.tokens.input)}`);
@@ -1429,30 +1543,39 @@
1429
1543
  </div>
1430
1544
  </div>`;
1431
1545
 
1432
- // Render system prompt (user's base prompt, applies to all providers)
1433
- if (systemPrompt) {
1434
- const lines = systemPrompt.split('\n');
1435
- const previewLines = 10;
1436
- if (lines.length > previewLines) {
1437
- const preview = lines.slice(0, previewLines).join('\n');
1438
- const remaining = lines.length - previewLines;
1439
- html += `<div class="system-prompt expandable" onclick="if(window.getSelection().toString())return;this.classList.toggle('expanded')">
1440
- <div class="system-prompt-header">System Prompt</div>
1441
- <div class="system-prompt-preview">${escapeHtml(preview)}</div>
1442
- <div class="system-prompt-expand-hint">... (${remaining} more lines, click to expand)</div>
1443
- <div class="system-prompt-full">${escapeHtml(systemPrompt)}</div>
1444
- </div>`;
1445
- } else {
1446
- html += `<div class="system-prompt">
1447
- <div class="system-prompt-header">System Prompt</div>
1448
- <div class="system-prompt-full" style="display: block">${escapeHtml(systemPrompt)}</div>
1449
- </div>`;
1450
- }
1546
+ // Sessions with system entries render the prompt and tools in the transcript, where they
1547
+ // occur. Older sessions have none, so fall back to the exporting agent's current state.
1548
+ if (!hasSystemEntries) {
1549
+ if (systemPrompt) html += renderSystemPromptBlock('System Prompt', systemPrompt);
1550
+ html += renderToolsList('Available Tools', tools);
1451
1551
  }
1452
1552
 
1453
- if (tools && tools.length > 0) {
1454
- html += `<div class="tools-list">
1455
- <div class="tools-header">Available Tools</div>
1553
+ return html;
1554
+ }
1555
+
1556
+ function renderSystemPromptBlock(title, text) {
1557
+ const lines = text.split('\n');
1558
+ const previewLines = 10;
1559
+ if (lines.length > previewLines) {
1560
+ const preview = lines.slice(0, previewLines).join('\n');
1561
+ const remaining = lines.length - previewLines;
1562
+ return `<div class="system-prompt expandable" onclick="if(window.getSelection().toString())return;this.classList.toggle('expanded')">
1563
+ <div class="system-prompt-header">${escapeHtml(title)}</div>
1564
+ <div class="system-prompt-preview">${escapeHtml(preview)}</div>
1565
+ <div class="system-prompt-expand-hint">... (${remaining} more lines, click to expand)</div>
1566
+ <div class="system-prompt-full">${escapeHtml(text)}</div>
1567
+ </div>`;
1568
+ }
1569
+ return `<div class="system-prompt">
1570
+ <div class="system-prompt-header">${escapeHtml(title)}</div>
1571
+ <div class="system-prompt-full" style="display: block">${escapeHtml(text)}</div>
1572
+ </div>`;
1573
+ }
1574
+
1575
+ function renderToolsList(title, tools) {
1576
+ if (!tools || tools.length === 0) return '';
1577
+ return `<div class="tools-list">
1578
+ <div class="tools-header">${escapeHtml(title)}</div>
1456
1579
  <div class="tools-content">
1457
1580
  ${tools.map(t => {
1458
1581
  const hasParams = t.parameters && typeof t.parameters === 'object' && t.parameters.properties && Object.keys(t.parameters.properties).length > 0;
@@ -1477,9 +1600,6 @@
1477
1600
  }).join('')}
1478
1601
  </div>
1479
1602
  </div>`;
1480
- }
1481
-
1482
- return html;
1483
1603
  }
1484
1604
 
1485
1605
  // ============================================================
@@ -4,16 +4,16 @@
4
4
  * Renders custom tool calls and results to HTML by invoking their TUI renderers
5
5
  * and converting the ANSI output to HTML.
6
6
  */
7
- import { ansiLinesToHtml } from "./ansi-to-html.js";
7
+ import { keyHint, keyText } from "../../modes/interactive/components/keybinding-hints.js";
8
+ import { ansiLinesToHtml, stripAnsiEscapes } from "./ansi-to-html.js";
8
9
  /**
9
10
  * Create a tool HTML renderer.
10
11
  *
11
12
  * The renderer looks up tool definitions and invokes their renderCall/renderResult
12
13
  * methods, converting the resulting TUI Component output (ANSI) to HTML.
13
14
  */
14
- const ANSI_ESCAPE_REGEX = /\x1b\[[\d;]*m/g;
15
15
  function isBlankRenderedLine(line) {
16
- return line.replace(ANSI_ESCAPE_REGEX, "").trim().length === 0;
16
+ return stripAnsiEscapes(line).trim().length === 0;
17
17
  }
18
18
  function trimRenderedResultLines(lines) {
19
19
  let start = 0;
@@ -54,6 +54,8 @@ export function createToolHtmlRenderer(deps) {
54
54
  isError,
55
55
  durationMs: undefined,
56
56
  outputPad: 1,
57
+ keyText,
58
+ keyHint,
57
59
  };
58
60
  };
59
61
  return {
@@ -1,4 +1,4 @@
1
1
  import { createRequire as __cortexCreateRequire } from 'node:module';
2
2
  const require = __cortexCreateRequire(import.meta.url);
3
3
  const __cortexPackageRoot = new URL("../../../../../", import.meta.url);
4
- import{k as a,l as b,m as c,n as d,o as e,p as f}from"../../../../../dist/chunks/chunk-BJGYGEZO.js";import"../../../../../dist/chunks/chunk-RA6HKFBV.js";import"../../../../../dist/chunks/chunk-QUUEQRIT.js";import"../../../../../dist/chunks/chunk-B3XBQEFM.js";import"../../../../../dist/chunks/chunk-WHC7AYZD.js";export{a as clearExtensionCache,b as createExtensionRuntime,f as discoverAndLoadExtensions,c as loadExtensionFromFactory,d as loadExtensions,e as loadExtensionsCached};
4
+ import{m as a,n as b,o as c,p as d,q as e,r as f}from"../../../../../dist/chunks/chunk-WZC4TDDM.js";import"../../../../../dist/chunks/chunk-6G3OYMCV.js";import"../../../../../dist/chunks/chunk-2BVUA256.js";import"../../../../../dist/chunks/chunk-B3XBQEFM.js";import"../../../../../dist/chunks/chunk-WHC7AYZD.js";export{a as clearExtensionCache,b as createExtensionRuntime,f as discoverAndLoadExtensions,c as loadExtensionFromFactory,d as loadExtensions,e as loadExtensionsCached};
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __cortexCreateRequire } from 'node:module';
2
2
  const require = __cortexCreateRequire(import.meta.url);
3
3
  const __cortexPackageRoot = new URL("../../../../../", import.meta.url);
4
- import{E as y,F as G,G as V,I as de,J as fe,K as pe,N as X,O as K,P as me,Q as he,c as J,g as ce,n as ue}from"../../../../../dist/chunks/chunk-5DF5WJNM.js";import"../../../../../dist/chunks/chunk-FX6MOGLR.js";import"../../../../../dist/chunks/chunk-CK3P345X.js";import"../../../../../dist/chunks/chunk-ZQ7LGTSN.js";import"../../../../../dist/chunks/chunk-LACGULCN.js";import"../../../../../dist/chunks/chunk-3TGQSGG4.js";import{A as ae,B as le}from"../../../../../dist/chunks/chunk-QUUEQRIT.js";import"../../../../../dist/chunks/chunk-B3XBQEFM.js";import"../../../../../dist/chunks/chunk-WHC7AYZD.js";function Y(t){if(typeof t!="object"||t===null)return!1;let e=t.type;return e==="call"||e==="output"||e==="done"||e==="crash"||e==="started"||e==="idle"}var qe=3e5,Ce=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Re=new Set(["tools","ALL_TOOLS","console","text","image","exit","globalThis","store","load"]);function x(t){return t instanceof Error?t.message:String(t)}function ge(t){let e={};for(let[r,n]of Object.entries(t??{})){let s=JSON.stringify(n);s!==void 0&&(e[r]=s)}return e}var b=class extends Error{};function $(t,e){try{return JSON.parse(t)}catch{throw new b(`${e} is not valid JSON`)}}function $e(t){let e=$(t,"store writes");if(!Array.isArray(e))throw new b("store writes are not an array");let r={set:{},delete:[]};for(let n of e){if(!Array.isArray(n)||typeof n[0]!="string"||(n.length===2?typeof n[1]!="string":n.length!==1))throw new b("store writes contain a malformed entry");let[s,o]=n;o===void 0?r.delete.push(s):r.set[s]=$(o,`store value for ${JSON.stringify(s)}`)}return r}function Me(t){let e=$(t,"script error");if(typeof e!="object"||e===null)throw new b("script error is not an object");let{name:r,message:n,stack:s}=e;if(typeof n!="string"||r!==void 0&&typeof r!="string"||s!==void 0&&typeof s!="string")throw new b("script error is malformed");return{kind:"script",name:r,message:n,stack:s}}function _e(t){let e=new Set,r=new Set;for(let n of t){let s=n.name.split(".");if(s.length>2||!s.every(o=>Ce.test(o))||Re.has(s[0]))throw new Error(`Invalid global name "${n.name}"`);if(e.has(n.name))throw new Error(`Global "${n.name}" is already registered`);s.length===2&&r.add(s[0]),e.add(n.name)}for(let n of r)if(e.has(n))throw new Error(`Global "${n}" conflicts with the namespace "${n}"`)}var F=class{promise;resolveResult;channel;unsent=[];executors;control;delivered=new Set;signal;timer;output=[];calls=[];pending=new Map;finished=!1;constructor(e){if(this.promise=new Promise(s=>{this.resolveResult=s}),this.executors=e.executors,this.control=e.control,this.signal=e.signal,Number.isFinite(e.timeoutMs)&&(this.timer=setTimeout(()=>{this.finish({kind:"timeout",message:`Execution timed out after ${e.timeoutMs} ms`})},e.timeoutMs)),e.signal&&(e.signal.aborted?this.onAbort():e.signal.addEventListener("abort",this.onAbort,{once:!0})),this.finished)return;let r={code:e.code,tools:e.tools.map(s=>({name:s.name,jsName:s.jsName??y(s.name),description:s.description??""})),globals:e.globals.map(s=>({name:s.name,spread:s.spread===!0})),memoryLimitBytes:e.memoryLimitBytes,store:e.store,...e.deterministic?{deterministic:e.deterministic}:{}},n={message:s=>this.receive(s),failure:s=>this.finish(s)};new Promise(s=>s(e.launch(r,n))).then(s=>{if(this.finished){s.stop().catch(()=>{});return}this.channel=s;for(let o of this.unsent.splice(0))s.post(o)},s=>{this.finish({kind:"sandbox",message:x(s)})})}deliver(e,r,n,s){if(this.finished)return;if(!Number.isFinite(r))throw new Error(`The clock value of result ${e} is not a finite number`);if(!Number.isInteger(e)||e<1||this.delivered.has(e))throw new Error(`Result number ${e} is not a positive integer used once`);let o=this.pending.get(n);if(o===void 0)throw new Error(`Call ${n} is not waiting for a result`);if(!s.ok&&s.properties!==void 0){let{properties:c}=s;if(typeof c!="object"||c===null||Array.isArray(c))throw new Error(`The properties of result ${e} are not an object`)}let a=s.ok?s.value===void 0?void 0:JSON.stringify(s.value):s.message,i=!s.ok&&s.properties!==void 0?JSON.stringify(s.properties):void 0;this.delivered.add(e),this.pending.delete(n),o.record&&(o.record.status=s.ok?"ok":"error",o.record.durationMs=performance.now()-o.startedAt),this.post({type:"result",id:n,ok:s.ok,payload:a,seq:e,now:r,...i===void 0?{}:{properties:i}})}abort(e){return this.finish({kind:"aborted",message:e}),this.promise}onAbort=()=>{let e=this.signal?.reason;this.finish({kind:"aborted",message:e instanceof Error?e.message:"Execution aborted"})};post(e){this.channel?this.channel.post(e):this.unsent.push(e)}receive(e){try{this.handleMessage(e)}catch(r){this.finish({kind:"sandbox",message:r instanceof b?`Sandbox bridge broken: ${r.message}. The script may have modified built-ins such as a prototype's toJSON.`:`Sandbox host failed: ${x(r)}`})}}handleMessage(e){if(!this.finished){if(!Y(e))throw new b("unknown message from the worker");switch(e.type){case"output":this.output.push(e.item);break;case"call":if(this.pending.has(e.id))throw new b(`duplicate call id ${e.id}`);this.control?this.forwardCall(e,this.control):this.handleCall(e);break;case"started":this.control?.onStarted?.(e.fingerprint);break;case"idle":this.control?.onIdle?.(e.seq,e.issued);break;case"done":this.handleDone(e);break;case"crash":this.finish({kind:"sandbox",message:e.message});break}}}handleDone(e){if(!e.ok){this.finish(Me(e.error),void 0,void 0,e.during);return}let r=e.value===void 0?void 0:$(e.value,"return value");this.finish(void 0,r,$e(e.writes),e.during)}forwardCall(e,r){let{id:n,name:s,target:o}=e,a=e.args===void 0?void 0:$(e.args,"call arguments"),i=o==="tool"?{name:s,status:"cancelled",durationMs:0}:void 0;i&&this.calls.push(i),this.pending.set(n,{record:i,startedAt:performance.now(),controller:new AbortController}),r.onCall({id:n,target:o,name:s,args:a})}async handleCall(e){let{id:r,name:n}=e,s=e.target==="tool",o=s?{name:n,status:"cancelled",durationMs:0}:void 0;o&&this.calls.push(o);let a={record:o,startedAt:performance.now(),controller:new AbortController};this.pending.set(r,a);let i,c;try{let l=(s?this.executors.tools:this.executors.globals).get(n);if(!l)throw new Error(`Unknown ${s?"tool":"global"} "${n}"`);let d=e.args===void 0?void 0:JSON.parse(e.args),u=await l.execute(d,{signal:a.controller.signal});c={type:"result",id:r,ok:!0,payload:u===void 0?void 0:JSON.stringify(u)},i="ok"}catch(l){c={type:"result",id:r,ok:!1,payload:x(l)},i="error"}this.pending.delete(r)&&(o&&(o.status=i,o.durationMs=performance.now()-a.startedAt),this.post(c))}finish(e,r,n,s){if(this.finished)return;this.finished=!0,clearTimeout(this.timer),this.signal?.removeEventListener("abort",this.onAbort);let o=performance.now();for(let c of this.pending.values())c.record&&(c.record.durationMs=o-c.startedAt),c.controller.abort();this.pending.clear(),this.unsent=[];let a=s===void 0?{}:{during:{seq:s.seq,issued:s.issued}},i=e?{ok:!1,error:e,output:this.output,calls:this.calls,...a}:{ok:!0,value:r,output:this.output,calls:this.calls,storeWrites:n??{set:{},delete:[]},...a};if(!this.channel){this.resolveResult(i);return}this.channel.stop().catch(()=>{}).then(()=>this.resolveResult(i))}},O=class{toolsByName=new Map;globalsByName=new Map;timeoutMs;memoryLimitBytes;launch;running=new Set;closed=!1;constructor(e,r){this.timeoutMs=e.timeoutMs??qe,this.memoryLimitBytes=e.memoryLimitBytes,this.launch=r;for(let n of e.tools??[])this.registerTool(n);_e(e.globals??[]);for(let n of e.globals??[])this.globalsByName.set(n.name,n)}registerTool(e){if(this.toolsByName.has(e.name))throw new Error(`Tool "${e.name}" is already registered`);this.toolsByName.set(e.name,e)}unregisterTool(e){return this.toolsByName.delete(e)}get tools(){return[...this.toolsByName.values()]}get globals(){return[...this.globalsByName.values()]}execute(e,r={}){if(this.closed)return Promise.reject(new Error("Sandbox is closed"));let n=new Map(this.toolsByName),s=new F({code:e,tools:[...n.values()],globals:[...this.globalsByName.values()],executors:{tools:n,globals:this.globalsByName},timeoutMs:r.timeoutMs??this.timeoutMs,signal:r.signal,memoryLimitBytes:this.memoryLimitBytes,store:ge(r.store),launch:this.launch});return this.running.add(s),s.promise.finally(()=>this.running.delete(s))}start(e,r){if(this.closed)throw new Error("Sandbox is closed");if(!Number.isFinite(r.startedAt)||r.startedAt<0)throw new Error("startedAt must be a non-negative number of milliseconds since the epoch");if(!Number.isInteger(r.seed)||r.seed<0||r.seed>4294967295)throw new Error("seed must be a 32-bit unsigned integer");let n=r.tools??[];if(new Set(n.map(c=>c.name)).size!==n.length)throw new Error("Tool names must be unique");let s=n.map(c=>c.jsName??y(c.name));if(new Set(s).size!==n.length)throw new Error("Tool script names must be unique");let o=r.globals??[];_e(o);let a=new F({code:e,tools:n,globals:o,executors:{tools:new Map,globals:new Map},timeoutMs:r.timeoutMs??Number.POSITIVE_INFINITY,signal:r.signal,memoryLimitBytes:this.memoryLimitBytes,store:ge(r.store),deterministic:{startedAt:r.startedAt,seed:r.seed},control:{onStarted:r.onStarted,onCall:r.onCall,onIdle:r.onIdle},launch:this.launch});return this.running.add(a),{result:a.promise.finally(()=>this.running.delete(a)),deliver:(c,l,d,u)=>a.deliver(c,l,d,u),get finished(){return a.finished}}}async close(){this.closed=!0,await Promise.all([...this.running].map(e=>e.abort("Sandbox closed")))}};import{Worker as De}from"node:worker_threads";import{fileURLToPath as Ue}from"node:url";import{readFile as Ie}from"node:fs/promises";var Q=new Map;function M(t){let e=t??Ue(new URL("vendor/quickjs.wasm",__cortexPackageRoot)),r=Q.get(e);if(!r){let{WebAssembly:n}=globalThis;r=Ie(e).then(s=>n.compile(s)).catch(s=>{throw Q.delete(e),s}),Q.set(e,r)}return r}function Le(){return new URL(import.meta.url.endsWith(".ts")?"./worker.ts":"./worker.js",import.meta.url)}function He(t){return async(e,r)=>{let n;try{n=await(t.wasm??M())}catch(l){throw new Error(`Failed to load QuickJS: ${x(l)}`)}let s=new SharedArrayBuffer(4),o={...e,wasm:n,interrupt:s},a=t.acquireWorker?.(),i;try{i=new De(t.workerUrl??Le(),{workerData:o})}catch(l){throw a?.(),new Error(`Failed to start worker: ${x(l)}`)}a&&i.once("exit",a),i.on("message",l=>{typeof l=="object"&&l!==null&&("watch:import"in l||"watch:require"in l)||r.message(l)}),i.on("error",l=>{r.failure({kind:"sandbox",name:l instanceof Error?l.name:void 0,message:x(l)})}),i.on("exit",l=>{r.failure({kind:"sandbox",message:`Worker exited with code ${l} before the script settled`})});let c=async()=>{Atomics.store(new Int32Array(s),0,1),i.terminate().catch(()=>{}),i.unref()};try{t.onWorkerStarted?.(new Promise(l=>i.once("exit",()=>l())))}catch(l){throw c(),l}return{post:l=>i.postMessage(l),stop:c}}}var U=class extends O{constructor(e={}){super(e,He(e))}};var Ot=new TextDecoder;var Be=512*1024;var It=new TextDecoder,Dt=new TextEncoder;var z='image expects a non-empty image URL string, an object with image_url, or an image block { type: "image", data, mimeType }',we=`(function (bridge, toolsJson, globalsJson, storeJson) {
4
+ import{B as pe,C as me,D as he,G as K,H as Y,I as ge,J as _e,c as J,g as fe,x as y,y as V,z as X}from"../../../../../dist/chunks/chunk-4JBYLRPM.js";import"../../../../../dist/chunks/chunk-54P7TSY3.js";import{k as ue,o as G,p as de}from"../../../../../dist/chunks/chunk-CEJIYYVE.js";import"../../../../../dist/chunks/chunk-GOS3P7KS.js";import"../../../../../dist/chunks/chunk-ZQ7LGTSN.js";import"../../../../../dist/chunks/chunk-YWPBE5LP.js";import"../../../../../dist/chunks/chunk-SDUS2H3E.js";import"../../../../../dist/chunks/chunk-3TGQSGG4.js";import{G as le,H as ce}from"../../../../../dist/chunks/chunk-2BVUA256.js";import"../../../../../dist/chunks/chunk-B3XBQEFM.js";import"../../../../../dist/chunks/chunk-WHC7AYZD.js";function Q(t){if(typeof t!="object"||t===null)return!1;let e=t.type;return e==="call"||e==="output"||e==="done"||e==="crash"||e==="started"||e==="idle"}var Re=3e5,$e=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Me=new Set(["tools","ALL_TOOLS","console","text","image","exit","globalThis","store","load"]);function x(t){return t instanceof Error?t.message:String(t)}function we(t){let e={};for(let[r,n]of Object.entries(t??{})){let s=JSON.stringify(n);s!==void 0&&(e[r]=s)}return e}var b=class extends Error{};function $(t,e){try{return JSON.parse(t)}catch{throw new b(`${e} is not valid JSON`)}}function Ue(t){let e=$(t,"store writes");if(!Array.isArray(e))throw new b("store writes are not an array");let r={set:{},delete:[]};for(let n of e){if(!Array.isArray(n)||typeof n[0]!="string"||(n.length===2?typeof n[1]!="string":n.length!==1))throw new b("store writes contain a malformed entry");let[s,o]=n;o===void 0?r.delete.push(s):r.set[s]=$(o,`store value for ${JSON.stringify(s)}`)}return r}function Ie(t){let e=$(t,"script error");if(typeof e!="object"||e===null)throw new b("script error is not an object");let{name:r,message:n,stack:s}=e;if(typeof n!="string"||r!==void 0&&typeof r!="string"||s!==void 0&&typeof s!="string")throw new b("script error is malformed");return{kind:"script",name:r,message:n,stack:s}}function ye(t){let e=new Set,r=new Set;for(let n of t){let s=n.name.split(".");if(s.length>2||!s.every(o=>$e.test(o))||Me.has(s[0]))throw new Error(`Invalid global name "${n.name}"`);if(e.has(n.name))throw new Error(`Global "${n.name}" is already registered`);s.length===2&&r.add(s[0]),e.add(n.name)}for(let n of r)if(e.has(n))throw new Error(`Global "${n}" conflicts with the namespace "${n}"`)}var F=class{promise;resolveResult;channel;unsent=[];executors;control;delivered=new Set;signal;timer;output=[];calls=[];pending=new Map;finished=!1;constructor(e){if(this.promise=new Promise(s=>{this.resolveResult=s}),this.executors=e.executors,this.control=e.control,this.signal=e.signal,Number.isFinite(e.timeoutMs)&&(this.timer=setTimeout(()=>{this.finish({kind:"timeout",message:`Execution timed out after ${e.timeoutMs} ms`})},e.timeoutMs)),e.signal&&(e.signal.aborted?this.onAbort():e.signal.addEventListener("abort",this.onAbort,{once:!0})),this.finished)return;let r={code:e.code,tools:e.tools.map(s=>({name:s.name,jsName:s.jsName??y(s.name),description:s.description??""})),globals:e.globals.map(s=>({name:s.name,spread:s.spread===!0})),memoryLimitBytes:e.memoryLimitBytes,store:e.store,...e.deterministic?{deterministic:e.deterministic}:{}},n={message:s=>this.receive(s),failure:s=>this.finish(s)};new Promise(s=>s(e.launch(r,n))).then(s=>{if(this.finished){s.stop().catch(()=>{});return}this.channel=s;for(let o of this.unsent.splice(0))s.post(o)},s=>{this.finish({kind:"sandbox",message:x(s)})})}deliver(e,r,n,s){if(this.finished)return;if(!Number.isFinite(r))throw new Error(`The clock value of result ${e} is not a finite number`);if(!Number.isInteger(e)||e<1||this.delivered.has(e))throw new Error(`Result number ${e} is not a positive integer used once`);let o=this.pending.get(n);if(o===void 0)throw new Error(`Call ${n} is not waiting for a result`);if(!s.ok&&s.properties!==void 0){let{properties:c}=s;if(typeof c!="object"||c===null||Array.isArray(c))throw new Error(`The properties of result ${e} are not an object`)}let l=s.ok?s.value===void 0?void 0:JSON.stringify(s.value):s.message,i=!s.ok&&s.properties!==void 0?JSON.stringify(s.properties):void 0;this.delivered.add(e),this.pending.delete(n),o.record&&(o.record.status=s.ok?"ok":"error",o.record.durationMs=performance.now()-o.startedAt),this.post({type:"result",id:n,ok:s.ok,payload:l,seq:e,now:r,...i===void 0?{}:{properties:i}})}abort(e){return this.finish({kind:"aborted",message:e}),this.promise}onAbort=()=>{let e=this.signal?.reason;this.finish({kind:"aborted",message:e instanceof Error?e.message:"Execution aborted"})};post(e){this.channel?this.channel.post(e):this.unsent.push(e)}receive(e){try{this.handleMessage(e)}catch(r){this.finish({kind:"sandbox",message:r instanceof b?`Sandbox bridge broken: ${r.message}. The script may have modified built-ins such as a prototype's toJSON.`:`Sandbox host failed: ${x(r)}`})}}handleMessage(e){if(!this.finished){if(!Q(e))throw new b("unknown message from the worker");switch(e.type){case"output":this.output.push(e.item);break;case"call":if(this.pending.has(e.id))throw new b(`duplicate call id ${e.id}`);this.control?this.forwardCall(e,this.control):this.handleCall(e);break;case"started":this.control?.onStarted?.(e.fingerprint);break;case"idle":this.control?.onIdle?.(e.seq,e.issued);break;case"done":this.handleDone(e);break;case"crash":this.finish({kind:"sandbox",message:e.message});break}}}handleDone(e){if(!e.ok){this.finish(Ie(e.error),void 0,void 0,e.during);return}let r=e.value===void 0?void 0:$(e.value,"return value");this.finish(void 0,r,Ue(e.writes),e.during)}forwardCall(e,r){let{id:n,name:s,target:o}=e,l=e.args===void 0?void 0:$(e.args,"call arguments"),i=o==="tool"?{name:s,status:"cancelled",durationMs:0}:void 0;i&&this.calls.push(i),this.pending.set(n,{record:i,startedAt:performance.now(),controller:new AbortController}),r.onCall({id:n,target:o,name:s,args:l})}async handleCall(e){let{id:r,name:n}=e,s=e.target==="tool",o=s?{name:n,status:"cancelled",durationMs:0}:void 0;o&&this.calls.push(o);let l={record:o,startedAt:performance.now(),controller:new AbortController};this.pending.set(r,l);let i,c;try{let a=(s?this.executors.tools:this.executors.globals).get(n);if(!a)throw new Error(`Unknown ${s?"tool":"global"} "${n}"`);let d=e.args===void 0?void 0:JSON.parse(e.args),u=await a.execute(d,{signal:l.controller.signal});c={type:"result",id:r,ok:!0,payload:u===void 0?void 0:JSON.stringify(u)},i="ok"}catch(a){c={type:"result",id:r,ok:!1,payload:x(a)},i="error"}this.pending.delete(r)&&(o&&(o.status=i,o.durationMs=performance.now()-l.startedAt),this.post(c))}finish(e,r,n,s){if(this.finished)return;this.finished=!0,clearTimeout(this.timer),this.signal?.removeEventListener("abort",this.onAbort);let o=performance.now();for(let c of this.pending.values())c.record&&(c.record.durationMs=o-c.startedAt),c.controller.abort();this.pending.clear(),this.unsent=[];let l=s===void 0?{}:{during:{seq:s.seq,issued:s.issued}},i=e?{ok:!1,error:e,output:this.output,calls:this.calls,...l}:{ok:!0,value:r,output:this.output,calls:this.calls,storeWrites:n??{set:{},delete:[]},...l};if(!this.channel){this.resolveResult(i);return}this.channel.stop().catch(()=>{}).then(()=>this.resolveResult(i))}},O=class{toolsByName=new Map;globalsByName=new Map;timeoutMs;memoryLimitBytes;launch;running=new Set;closed=!1;constructor(e,r){this.timeoutMs=e.timeoutMs??Re,this.memoryLimitBytes=e.memoryLimitBytes,this.launch=r;for(let n of e.tools??[])this.registerTool(n);ye(e.globals??[]);for(let n of e.globals??[])this.globalsByName.set(n.name,n)}registerTool(e){if(this.toolsByName.has(e.name))throw new Error(`Tool "${e.name}" is already registered`);this.toolsByName.set(e.name,e)}unregisterTool(e){return this.toolsByName.delete(e)}get tools(){return[...this.toolsByName.values()]}get globals(){return[...this.globalsByName.values()]}execute(e,r={}){if(this.closed)return Promise.reject(new Error("Sandbox is closed"));let n=new Map(this.toolsByName),s=new F({code:e,tools:[...n.values()],globals:[...this.globalsByName.values()],executors:{tools:n,globals:this.globalsByName},timeoutMs:r.timeoutMs??this.timeoutMs,signal:r.signal,memoryLimitBytes:this.memoryLimitBytes,store:we(r.store),launch:this.launch});return this.running.add(s),s.promise.finally(()=>this.running.delete(s))}start(e,r){if(this.closed)throw new Error("Sandbox is closed");if(!Number.isFinite(r.startedAt)||r.startedAt<0)throw new Error("startedAt must be a non-negative number of milliseconds since the epoch");if(!Number.isInteger(r.seed)||r.seed<0||r.seed>4294967295)throw new Error("seed must be a 32-bit unsigned integer");let n=r.tools??[];if(new Set(n.map(c=>c.name)).size!==n.length)throw new Error("Tool names must be unique");let s=n.map(c=>c.jsName??y(c.name));if(new Set(s).size!==n.length)throw new Error("Tool script names must be unique");let o=r.globals??[];ye(o);let l=new F({code:e,tools:n,globals:o,executors:{tools:new Map,globals:new Map},timeoutMs:r.timeoutMs??Number.POSITIVE_INFINITY,signal:r.signal,memoryLimitBytes:this.memoryLimitBytes,store:we(r.store),deterministic:{startedAt:r.startedAt,seed:r.seed},control:{onStarted:r.onStarted,onCall:r.onCall,onIdle:r.onIdle},launch:this.launch});return this.running.add(l),{result:l.promise.finally(()=>this.running.delete(l)),deliver:(c,a,d,u)=>l.deliver(c,a,d,u),get finished(){return l.finished}}}async close(){this.closed=!0,await Promise.all([...this.running].map(e=>e.abort("Sandbox closed")))}};import{Worker as He}from"node:worker_threads";import{fileURLToPath as De}from"node:url";import{readFile as Le}from"node:fs/promises";var Z=new Map;function M(t){let e=t??De(new URL("vendor/quickjs.wasm",__cortexPackageRoot)),r=Z.get(e);if(!r){let{WebAssembly:n}=globalThis;r=Le(e).then(s=>n.compile(s)).catch(s=>{throw Z.delete(e),s}),Z.set(e,r)}return r}function Be(){return new URL(import.meta.url.endsWith(".ts")?"./worker.ts":"./worker.js",import.meta.url)}function Fe(t){return async(e,r)=>{let n;try{n=await(t.wasm??M())}catch(a){throw new Error(`Failed to load QuickJS: ${x(a)}`)}let s=new SharedArrayBuffer(4),o={...e,wasm:n,interrupt:s},l=t.acquireWorker?.(),i;try{i=new He(t.workerUrl??Be(),{workerData:o})}catch(a){throw l?.(),new Error(`Failed to start worker: ${x(a)}`)}l&&i.once("exit",l),i.on("message",a=>{typeof a=="object"&&a!==null&&("watch:import"in a||"watch:require"in a)||r.message(a)}),i.on("error",a=>{r.failure({kind:"sandbox",name:a instanceof Error?a.name:void 0,message:x(a)})}),i.on("exit",a=>{r.failure({kind:"sandbox",message:`Worker exited with code ${a} before the script settled`})});let c=async()=>{Atomics.store(new Int32Array(s),0,1),i.terminate().catch(()=>{}),i.unref()};try{t.onWorkerStarted?.(new Promise(a=>i.once("exit",()=>a())))}catch(a){throw c(),a}return{post:a=>i.postMessage(a),stop:c}}}var U=class extends O{constructor(e={}){super(e,Fe(e))}};var Pt=new TextDecoder;var ze=512*1024;var Lt=new TextDecoder,Ht=new TextEncoder;var z='image expects a non-empty image URL string, an object with image_url, or an image block { type: "image", data, mimeType }',be=`(function (bridge, toolsJson, globalsJson, storeJson) {
5
5
  "use strict";
6
6
 
7
7
  // Freeze every object reachable from the built-in globals, plus the intrinsics that are only
@@ -129,6 +129,8 @@ import{E as y,F as G,G as V,I as de,J as fe,K as pe,N as X,O as K,P as me,Q as h
129
129
  function format(value) {
130
130
  if (typeof value === "string") return value;
131
131
  if (value instanceof ErrorCtor) return errorText(value);
132
+ // JSON.stringify turns NaN and Infinity into "null".
133
+ if (typeof value === "number") return String(value);
132
134
  try {
133
135
  const json = stringify(value);
134
136
  return json === undefined ? String(value) : json;
@@ -475,33 +477,33 @@ import{E as y,F as G,G as V,I as de,J as fe,K as pe,N as X,O as K,P as me,Q as h
475
477
  return true;
476
478
  },
477
479
  };
478
- })`;function Fe(t){let e=2166136261;for(let r=0;r<t.length;r++)e^=t.charCodeAt(r),e=Math.imul(e,16777619);return(e>>>0).toString(16).padStart(8,"0")}var Gt=Fe(we);var Qt=256*1024;var nr=1<<20;var We=200,Se=500,Je=4,Ge=256*1024*1024,Ve=2;function je(){let t=Number(process.env.PI_CODEMODE_MAX_WORKERS);return Number.isInteger(t)&&t>0?t:Ve}var Z=6e4,ne=0,I=[];function Xe(t,e){return t?.aborted?Promise.resolve("aborted"):new Promise(r=>{let n=i=>{clearTimeout(a),t?.removeEventListener("abort",o);let c=I.indexOf(s);c>=0&&I.splice(c,1),r(i)},s=()=>n("reserved"),o=()=>n("aborted"),a=setTimeout(()=>n("timeout"),e);I.push(s),t?.addEventListener("abort",o,{once:!0}),ve()})}function ve(){for(;I.length>0&&ne<je();)ne++,I.shift()?.()}function ye(){ne--,ve()}var ke=new Set(["chat","image","classifier"]);function oe(t,e){return t.length>e?`${t.slice(0,e-3)}...`:t}function Ke(t){if(t===void 0)return"";try{return oe(JSON.stringify(t)??"",We)}catch{return""}}function Oe(t){return(t.content??[]).filter(e=>e.type==="text").map(e=>e.text).join(`
479
- `)}function ee(t){if(typeof t=="string"&&ke.has(t))return t;throw new Error(`Unknown model type ${JSON.stringify(t)}. Use "chat", "image", or "classifier".`)}function be(t){if(t!=null){if(typeof t!="string")throw new Error("provider must be a string");return t}}function te(t){let e={...t};return delete e.headers,e}function re(t){return`${/^[aeiou]/.test(t)?"an":"a"} ${t}`}function w(t){if(t==null)return String(t);if(Array.isArray(t))return t.length===0?"an empty array":"an array";if(typeof t=="object"){let e=Object.keys(t);return e.length===0?"{}":`{ ${e.slice(0,6).join(", ")}${e.length>6?", ...":""} }`}return typeof t=="string"?"a string":`a ${typeof t}`}var Ye='{ 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> } } } }';function Qe(t){let e=a=>new Error(`models.classify() ${a}. Expected context: ${Ye}. See "Classify" in ${K}.`);if(typeof t!="object"||t===null||Array.isArray(t))throw e(`expects a context object as its second argument, got ${w(t)}`);let{state:r,images:n,questions:s}=t;if(typeof r!="object"||r===null||Array.isArray(r))throw e(`context.state must be an object, got ${w(r)}`);if(n!==void 0){if(!Array.isArray(n))throw e(`context.images must be an array, got ${w(n)}`);n.forEach((a,i)=>{if(a?.type!=="image"||typeof a.data!="string"||typeof a.mimeType!="string")throw e(`context.images[${i}] must be an image block, got ${w(a)}`)})}if(typeof s!="object"||s===null||Array.isArray(s)||Object.keys(s).length===0)throw e(`context.questions must map question IDs to questions, got ${w(s)}`);let o=a=>a.length>0&&a.every(i=>typeof i=="string");for(let[a,i]of Object.entries(s)){let c=`context.questions.${a}`;if(typeof i!="object"||i===null||Array.isArray(i))throw e(`${c} must be a question object, got ${w(i)}`);let{type:l,instructions:d,criteria:u}=i;if(typeof d!="string")throw e(`${c}.instructions must be a string`);if(l==="choice"){if(typeof u!="object"||u===null||Array.isArray(u)||!o(Object.values(u)))throw e(`${c} is a "choice" question, so criteria must map each label to its meaning`)}else if(l==="score"){if(!Array.isArray(u)||!o(u))throw e(`${c} is a "score" question, so criteria must list the levels as strings, lowest first`)}else if(l==="bool"){let f=u;if(typeof f?.true!="string"||typeof f.false!="string")throw e(`${c} is a "bool" question, so criteria must be { true: string, false: string }`)}else throw e(`${c}.type must be "choice", "score", or "bool", got ${JSON.stringify(l)}`)}return t}function Ze(t){let e=n=>new Error(`models.generateImages() ${n}. Expected context: { input: [{ type: "text", text: <prompt> }, ...optional { type: "image", data: <base64>, mimeType } references] }. See "Generate images" in ${K}.`);if(typeof t!="object"||t===null||Array.isArray(t))throw e(`expects a context object as its second argument, got ${w(t)}`);let{input:r}=t;if(!Array.isArray(r)||r.length===0)throw e(`context.input must be a non-empty array of blocks, got ${w(r)}`);return r.forEach((n,s)=>{if(!(n?.type==="text"&&typeof n.text=="string")&&!(n?.type==="image"&&typeof n.data=="string"&&typeof n.mimeType=="string"))throw e(`context.input[${s}] must be a text or image block, got ${w(n)}`)}),t}function et(t){let e=0,r=[];return async n=>{e>=t&&await new Promise(s=>r.push(s)),e++;try{return await n()}finally{e--,r.shift()?.()}}}function tt(t){if(typeof t!="object"||t===null)return!1;let{set:e,delete:r}=t;return typeof e=="object"&&e!==null&&Array.isArray(r)&&r.every(n=>typeof n=="string")}function rt(t){let e=new Map;for(let r of t)if(!(r.type!=="custom"||r.customType!==X||!tt(r.data))){for(let n of r.data.delete)e.delete(n);for(let[n,s]of Object.entries(r.data.set))e.set(n,s)}return Object.fromEntries(e)}var st=1e4,se=4;function nt(t){return typeof t=="string"?t:JSON.stringify(t)??String(t)}function ot(t){let e=t.filter(o=>o.type==="text"&&!o.console).length,r=[],n=[],s=0;for(let o of t)o.type==="image"?r.push(o):o.console?n.push(o.text):(s++,r.push({type:"text",text:e>1?`==> text ${s}/${e} <==
480
+ })`;function We(t){let e=2166136261;for(let r=0;r<t.length;r++)e^=t.charCodeAt(r),e=Math.imul(e,16777619);return(e>>>0).toString(16).padStart(8,"0")}var Xt=We(be);var er=256*1024;var ir=1<<20;var Ge=200,ve=500,Ve=4,Xe=256*1024*1024,Ke=2;function ke(){let t=Number(process.env.PI_CODEMODE_MAX_WORKERS);return Number.isInteger(t)&&t>0?t:Ke}var ee=6e4,oe=0,I=[];function Ye(t,e){return t?.aborted?Promise.resolve("aborted"):new Promise(r=>{let n=i=>{clearTimeout(l),t?.removeEventListener("abort",o);let c=I.indexOf(s);c>=0&&I.splice(c,1),r(i)},s=()=>n("reserved"),o=()=>n("aborted"),l=setTimeout(()=>n("timeout"),e);I.push(s),t?.addEventListener("abort",o,{once:!0}),Oe()})}function Oe(){for(;I.length>0&&oe<ke();)oe++,I.shift()?.()}function xe(){oe--,Oe()}var Te=new Set(["chat","image","classifier"]);function ie(t,e){return t.length>e?`${G(t,e-3)}...`:t}function Qe(t){if(t===void 0)return"";try{return ie(JSON.stringify(t)??"",Ge)}catch{return""}}function Pe(t){return(t.content??[]).filter(e=>e.type==="text").map(e=>e.text).join(`
481
+ `)}function te(t){if(typeof t=="string"&&Te.has(t))return t;throw new Error(`Unknown model type ${JSON.stringify(t)}. Use "chat", "image", or "classifier".`)}function Ee(t){if(t!=null){if(typeof t!="string")throw new Error("provider must be a string");return t}}function re(t){let e={...t};return delete e.headers,e}function se(t){return`${/^[aeiou]/.test(t)?"an":"a"} ${t}`}function w(t){if(t==null)return String(t);if(Array.isArray(t))return t.length===0?"an empty array":"an array";if(typeof t=="object"){let e=Object.keys(t);return e.length===0?"{}":`{ ${e.slice(0,6).join(", ")}${e.length>6?", ...":""} }`}return typeof t=="string"?"a string":`a ${typeof t}`}var Ze='{ 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> } } } }';function et(t){let e=l=>new Error(`models.classify() ${l}. Expected context: ${Ze}. See "Classify" in ${Y}.`);if(typeof t!="object"||t===null||Array.isArray(t))throw e(`expects a context object as its second argument, got ${w(t)}`);let{state:r,images:n,questions:s}=t;if(typeof r!="object"||r===null||Array.isArray(r))throw e(`context.state must be an object, got ${w(r)}`);if(n!==void 0){if(!Array.isArray(n))throw e(`context.images must be an array, got ${w(n)}`);n.forEach((l,i)=>{if(l?.type!=="image"||typeof l.data!="string"||typeof l.mimeType!="string")throw e(`context.images[${i}] must be an image block, got ${w(l)}`)})}if(typeof s!="object"||s===null||Array.isArray(s)||Object.keys(s).length===0)throw e(`context.questions must map question IDs to questions, got ${w(s)}`);let o=l=>l.length>0&&l.every(i=>typeof i=="string");for(let[l,i]of Object.entries(s)){let c=`context.questions.${l}`;if(typeof i!="object"||i===null||Array.isArray(i))throw e(`${c} must be a question object, got ${w(i)}`);let{type:a,instructions:d,criteria:u}=i;if(typeof d!="string")throw e(`${c}.instructions must be a string`);if(a==="choice"){if(typeof u!="object"||u===null||Array.isArray(u)||!o(Object.values(u)))throw e(`${c} is a "choice" question, so criteria must map each label to its meaning`)}else if(a==="score"){if(!Array.isArray(u)||!o(u))throw e(`${c} is a "score" question, so criteria must list the levels as strings, lowest first`)}else if(a==="bool"){let f=u;if(typeof f?.true!="string"||typeof f.false!="string")throw e(`${c} is a "bool" question, so criteria must be { true: string, false: string }`)}else throw e(`${c}.type must be "choice", "score", or "bool", got ${JSON.stringify(a)}`)}return t}function tt(t){let e=n=>new Error(`models.generateImages() ${n}. Expected context: { input: [{ type: "text", text: <prompt> }, ...optional { type: "image", data: <base64>, mimeType } references] }. See "Generate images" in ${Y}.`);if(typeof t!="object"||t===null||Array.isArray(t))throw e(`expects a context object as its second argument, got ${w(t)}`);let{input:r}=t;if(!Array.isArray(r)||r.length===0)throw e(`context.input must be a non-empty array of blocks, got ${w(r)}`);return r.forEach((n,s)=>{if(!(n?.type==="text"&&typeof n.text=="string")&&!(n?.type==="image"&&typeof n.data=="string"&&typeof n.mimeType=="string"))throw e(`context.input[${s}] must be a text or image block, got ${w(n)}`)}),t}function rt(t){let e=0,r=[];return async n=>{e>=t&&await new Promise(s=>r.push(s)),e++;try{return await n()}finally{e--,r.shift()?.()}}}function st(t){if(typeof t!="object"||t===null)return!1;let{set:e,delete:r}=t;return typeof e=="object"&&e!==null&&Array.isArray(r)&&r.every(n=>typeof n=="string")}function nt(t){let e=new Map;for(let r of t)if(!(r.type!=="custom"||r.customType!==K||!st(r.data))){for(let n of r.data.delete)e.delete(n);for(let[n,s]of Object.entries(r.data.set))e.set(n,s)}return Object.fromEntries(e)}var ot=1e4,ne=4;function it(t){return typeof t=="string"?t:JSON.stringify(t)??String(t)}function at(t){let e=t.filter(o=>o.type==="text"&&!o.console).length,r=[],n=[],s=0;for(let o of t)o.type==="image"?r.push(o):o.console?n.push(o.text):(s++,r.push({type:"text",text:e>1?`==> text ${s}/${e} <==
480
482
  ${o.text}`:o.text}));return n.length>0&&r.push({type:"text",text:`<console_output>
481
483
  ${n.join(`
482
484
  `)}
483
- </console_output>`}),r}function xe(t){let e=[],r=[],n="",s=()=>{r.length>0&&e.push({type:"text",text:r.join("")}),r=[],n=""};for(let o of t){if(o.type!=="text"){s(),e.push(o);continue}n!==""&&!n.endsWith(`
485
+ </console_output>`}),r}function Se(t){let e=[],r=[],n="",s=()=>{r.length>0&&e.push({type:"text",text:r.join("")}),r=[],n=""};for(let o of t){if(o.type!=="text"){s(),e.push(o);continue}n!==""&&!n.endsWith(`
484
486
  `)&&(r.push(`
485
487
  `),n=`
486
- `),r.push(o.text),o.text!==""&&(n=o.text)}return s(),e}function it(t){return t.length===0?"No tool calls were made.":`Tool calls made before the failure (they are not undone): ${t.map(e=>`${e.name} (${e.status})`).join(", ")}`}function at(t,e){let{error:r}=t;return`${r.kind==="script"?r.stack??`${r.name??"Error"}: ${r.message}`:r.kind==="timeout"?`Script timed out: ${r.message}`:r.kind==="aborted"?`Script aborted: ${r.message}`:`Script sandbox failed: ${r.message}`}
488
+ `),r.push(o.text),o.text!==""&&(n=o.text)}return s(),e}function lt(t){return t.length===0?"No tool calls were made.":`Tool calls made before the failure (they are not undone): ${t.map(e=>`${e.name} (${e.status})`).join(", ")}`}function ct(t,e){let{error:r}=t;return`${r.kind==="script"?r.stack??`${r.name??"Error"}: ${r.message}`:r.kind==="timeout"?`Script timed out: ${r.message}`:r.kind==="aborted"?`Script aborted: ${r.message}`:`Script sandbox failed: ${r.message}`}
487
489
 
488
- ${it(e)}`}async function lt(t){try{return{path:await J("pi-codemode",".txt",t)}}catch(e){return{error:e instanceof Error?e.message:String(e)}}}var ct={"image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp"};async function ut(t){let e=new Map,r=async({data:s,mimeType:o})=>{let a=Buffer.from(s,"base64"),i=`${o}, ${ce(a.length)}`,c=ct[o];if(!c)throw new Error(`No file extension for image type ${o}`);try{return`[Image saved to ${await J("pi-codemode",c,a)} (${i})]`}catch(l){return`[Image (${i}) could not be saved: ${l instanceof Error?l.message:String(l)}]`}};return(await Promise.all(t.map(async s=>{if(s.type!=="image")return[s];let o=e.get(s.data);return o||(o=r(s),e.set(s.data,o)),[{type:"text",text:await o},s]}))).flat()}async function dt(t,e){let r=t.filter(f=>f.type==="text").map(f=>f.text),n=r.join(`
489
- `),s=e*se;if(r.length===0||n.length<=s)return{items:t};let o=Math.floor(s/2),a=s-o,i=n.length-o-a,c=n.slice(0,o),l=a>0?n.slice(-a):"",d=`Warning: truncated output (original token count: ${Math.ceil(n.length/se)})
490
+ ${lt(e)}`}async function ut(t){try{return{path:await J("pi-codemode",".txt",t)}}catch(e){return{error:e instanceof Error?e.message:String(e)}}}var dt={"image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp"};async function ft(t){let e=new Map,r=async({data:s,mimeType:o})=>{let l=Buffer.from(s,"base64"),i=`${o}, ${ue(l.length)}`,c=dt[o];if(!c)throw new Error(`No file extension for image type ${o}`);try{return`[Image saved to ${await J("pi-codemode",c,l)} (${i})]`}catch(a){return`[Image (${i}) could not be saved: ${a instanceof Error?a.message:String(a)}]`}};return(await Promise.all(t.map(async s=>{if(s.type!=="image")return[s];let o=e.get(s.data);return o||(o=r(s),e.set(s.data,o)),[{type:"text",text:await o},s]}))).flat()}async function pt(t,e){let r=t.filter(f=>f.type==="text").map(f=>f.text),n=r.join(`
491
+ `),s=e*ne;if(r.length===0||n.length<=s)return{items:t};let o=Math.floor(s/2),l=s-o,i=n.length-o-l,c=G(n,o),a=de(n,l),d=`Warning: truncated output (original token count: ${Math.ceil(n.length/ne)})
490
492
  Total output lines: ${n.split(`
491
493
  `).length}
492
494
 
493
- ${c}\u2026${Math.ceil(i/se)} tokens truncated\u2026${l}`,u=await lt(n);return d+="path"in u?`
495
+ ${c}\u2026${Math.ceil(i/ne)} tokens truncated\u2026${a}`,u=await ut(n);return d+="path"in u?`
494
496
 
495
497
  [Full output: ${u.path} (read with offset/limit)]`:`
496
498
 
497
- [Could not save the full output: ${u.error}]`,{items:[{type:"text",text:d},...t.filter(f=>f.type==="image")],..."path"in u?{fullOutputPath:u.path}:{}}}function ft(t,e){let{result:r}=e;if(t.outputSchema&&r.structuredContent!==void 0)return r.structuredContent;let n=Oe(r);if(e.isError)throw new Error(n||`Tool "${t.name}" failed`);return n}async function Ir(t,e,r,n,s,o={}){let a=performance.now(),{code:i,options:c}=V(e.code),l=[],d,u=0,f=p=>{u+=p},h=p=>{d=d?ue(d,p):p},g=()=>({calls:l.map(p=>({...p}))}),E=()=>n?.({content:[],details:g()});E();let j=s?he(s.tools):[],T=o.getToolGuidelines?.(),P=new Map(j.map(p=>[p.name,G(me(p,T?.get(p.name)))])),C=j.map(p=>({name:p.name,description:P.get(p.name),execute:async(S,{signal:H})=>{let q={id:`${t}/?`,name:p.name,args:Ke(S),status:"running"};l.push(q),E();let Ne=performance.now();if(!s)throw new Error("Tool calls need a session");let B=await s.executeTool(p.name,S,{signal:H});return q.id=B.toolCall.id,q.durationMs=performance.now()-Ne,B.isError?(q.status=H.aborted?"cancelled":"error",q.error=oe(Oe(B.result)||`Tool "${p.name}" failed`,Se)):q.status="ok",E(),ft(p,B)}})),v=c.timeoutMs??Number.POSITIVE_INFINITY,A=performance.now(),D=await Xe(r,Math.min(v,Z)),k=performance.now()-A;if(D!=="reserved"){let p=((performance.now()-a)/1e3).toFixed(1),S=r?.reason,H=D==="aborted"?`Script aborted: ${S instanceof Error?S.message:"Execution aborted"}`:v<=Z?`Script timed out: Execution timed out after ${v} ms while waiting for a free codemode worker`:`No codemode worker became free within ${Z/1e3} seconds. All ${je()} workers, shared by every session in this process, are held by other scripts. Retry after they finish.`;return{content:[{type:"text",text:`Script failed
499
+ [Could not save the full output: ${u.error}]`,{items:[{type:"text",text:d},...t.filter(f=>f.type==="image")],..."path"in u?{fullOutputPath:u.path}:{}}}function mt(t,e){let{result:r}=e;if(t.outputSchema&&r.structuredContent!==void 0)return r.structuredContent;let n=Pe(r);if(e.isError)throw new Error(n||`Tool "${t.name}" failed`);return n}async function Hr(t,e,r,n,s,o={}){let l=performance.now(),{code:i,options:c}=X(e.code),a=[],d,u=0,f=p=>{u+=p},h=p=>{d=d?fe(d,p):p},g=()=>({calls:a.map(p=>({...p}))}),E=()=>n?.({content:[],details:g()});E();let j=s?_e(s.tools):[],T=o.getToolGuidelines?.(),P=new Map(j.map(p=>[p.name,V(ge(p,T?.get(p.name)))])),C=j.map(p=>({name:p.name,description:P.get(p.name),execute:async(S,{signal:H})=>{let q={id:`${t}/?`,name:p.name,args:Qe(S),status:"running"};a.push(q),E();let Ce=performance.now();if(!s)throw new Error("Tool calls need a session");let B=await s.executeTool(p.name,S,{signal:H});return q.id=B.toolCall.id,q.durationMs=performance.now()-Ce,B.isError?(q.status=H.aborted?"cancelled":"error",q.error=ie(Pe(B.result)||`Tool "${p.name}" failed`,ve)):q.status="ok",E(),mt(p,B)}})),v=c.timeoutMs??Number.POSITIVE_INFINITY,A=performance.now(),D=await Ye(r,Math.min(v,ee)),k=performance.now()-A;if(D!=="reserved"){let p=((performance.now()-l)/1e3).toFixed(1),S=r?.reason,H=D==="aborted"?`Script aborted: ${S instanceof Error?S.message:"Execution aborted"}`:v<=ee?`Script timed out: Execution timed out after ${v} ms while waiting for a free codemode worker`:`No codemode worker became free within ${ee/1e3} seconds. All ${ke()} workers, shared by every session in this process, are held by other scripts. Retry after they finish.`;return{content:[{type:"text",text:`Script failed
498
500
  Wall time ${p} seconds
499
501
  Output:
500
502
  `},{type:"text",text:`Script error:
501
503
  ${H}
502
504
 
503
- The script did not start.`}],details:g(),isError:!0}}let N=!0,_,m;try{_=new U({tools:C,globals:[...pt(j,P,o),...o.models&&s?mt(s.modelRegistry,t,l,E,h,f):[]],timeoutMs:Math.max(1,Math.round(v-k)),memoryLimitBytes:Ge,wasm:M(ae()),workerUrl:le(),acquireWorker:()=>{if(!N)throw new Error("The script already settled");return N=!1,ye}});let p=s?rt(s.sessionManager.getBranch()):{};m=await _.execute(i,{signal:r,store:p})}finally{await _?.close(),N&&(N=!1,ye())}for(let p of l)p.status==="running"&&(p.status="cancelled");let R=[...m.output];if(m.ok){let{set:p,delete:S}=m.storeWrites;(Object.keys(p).length>0||S.length>0)&&o.appendEntry?.(X,{set:p,delete:S}),m.value!==void 0&&R.push({type:"text",text:nt(m.value)})}let L=ot(R);m.ok||L.push({type:"text",text:`Script error:
504
- ${at(m,l)}`}),u>0&&!L.some(p=>p.type==="image")&&L.push({type:"text",text:`Note: models.generateImages() returned ${u} image${u===1?"":"s"} that the script did not show. Show each image block of result.output with image(block).`});let W=await dt(xe(L),c.maxOutputTokens??st),Te=xe(await ut(W.items)),Pe=((performance.now()-a)/1e3).toFixed(1),Ae=`${m.ok?"Script completed":"Script failed"}
505
- Wall time ${Pe} seconds
505
+ The script did not start.`}],details:g(),isError:!0}}let N=!0,_,m;try{_=new U({tools:C,globals:[...ht(j,P,o),...o.models&&s?gt(s.modelRegistry,t,a,E,h,f):[]],timeoutMs:Math.max(1,Math.round(v-k)),memoryLimitBytes:Xe,wasm:M(le()),workerUrl:ce(),acquireWorker:()=>{if(!N)throw new Error("The script already settled");return N=!1,xe}});let p=s?nt(s.sessionManager.getBranch()):{};m=await _.execute(i,{signal:r,store:p})}finally{await _?.close(),N&&(N=!1,xe())}for(let p of a)p.status==="running"&&(p.status="cancelled");let R=[...m.output];if(m.ok){let{set:p,delete:S}=m.storeWrites;(Object.keys(p).length>0||S.length>0)&&o.appendEntry?.(K,{set:p,delete:S}),m.value!==void 0&&R.push({type:"text",text:it(m.value)})}let L=at(R);m.ok||L.push({type:"text",text:`Script error:
506
+ ${ct(m,a)}`}),u>0&&!L.some(p=>p.type==="image")&&L.push({type:"text",text:`Note: models.generateImages() returned ${u} image${u===1?"":"s"} that the script did not show. Show each image block of result.output with image(block).`});let W=await pt(Se(L),c.maxOutputTokens??ot),Ae=Se(await ft(W.items)),Ne=((performance.now()-l)/1e3).toFixed(1),qe=`${m.ok?"Script completed":"Script failed"}
507
+ Wall time ${Ne} seconds
506
508
  Output:
507
- `,ie=g();return W.fullOutputPath&&(ie.fullOutputPath=W.fullOutputPath),{content:[{type:"text",text:Ae},...Te],details:ie,...d?{usage:d}:{},...m.ok?{}:{isError:!0}}}function Ee(t,e){let r=y(e);return[t.name,...t.aliases??[]].some(n=>n===e||y(n)===r)}function pt(t,e,r){let n=new pe,s=o=>({name:y(o),description:e.get(o)??""});return[{name:"searchTools",spread:!0,execute:o=>{let[a,i]=o;if(typeof a!="string")throw new Error("searchTools() expects a query string");let c=i?.limit??de;if(typeof c!="number"||!Number.isInteger(c)||c<=0)throw new Error("searchTools() limit must be a positive integer");let l=i?.namespace;if(l!=null&&typeof l!="string")throw new Error("searchTools() namespace must be a string");let d=t.flatMap(u=>{let f=r.getToolNamespace?.(u.name);return l&&(!f||!Ee(f,l))?[]:[fe(u,f)]});return n.rank(a,d,c).map(u=>s(u.name))}},{name:"describeTool",spread:!0,execute:o=>{let[a]=o;if(typeof a!="string")throw new Error("describeTool() expects a tool name");let i=t.find(c=>c.name===a||y(c.name)===a);return i?e.get(i.name):void 0}},{name:"describeNamespace",spread:!0,execute:o=>{let[a]=o;if(typeof a!="string")throw new Error("describeNamespace() expects a namespace name");let i,c=[];for(let l of t){let d=r.getToolNamespace?.(l.name);!d||!Ee(d,a)||(i??=d,c.push(y(l.name)))}if(i)return{name:i.name,...i.description?{description:i.description}:{},...i.instructions?{instructions:i.instructions}:{},tools:c}}}]}function mt(t,e,r,n,s,o){let a=et(Je),i=0,c=async(d,u,[f,h],g,E)=>{let j=`List the ${u} models you can use with models.getAvailableOfType("${u}").`,T=f;if(typeof T?.provider!="string"||typeof T.id!="string"){let m=f==null?" models.getModelOfType() returns undefined for an unknown provider or id.":"";throw new Error(`${d}() expects ${re(u)} model as its first argument, got ${w(f)}.${m} ${j}`)}let P=T.provider,C=T.id,v=`${P}/${C}`,A=t.getModelOfType(u,P,C);if(!A){let m=[...ke].find(R=>R!==u&&t.getModelOfType(R,P,C)!==void 0);throw new Error(m?`"${v}" is ${re(m)} model, not ${re(u)} model. ${j}`:`Unknown ${u} model "${v}". ${j}`)}let D=g(h),k={id:`${e}/${d}/${++i}`,name:d,args:`${A.provider}/${A.id}`,status:"running"};r.push(k),n();let N=performance.now(),_=await a(()=>E(A,D));return k.durationMs=performance.now()-N,k.status=_.stopReason==="stop"?"ok":_.stopReason==="aborted"?"cancelled":"error",_.errorMessage&&(k.error=oe(_.errorMessage,Se)),_.usage&&(k.cost=_.usage.cost.total,s(_.usage)),n(),_};return Object.entries({"models.getModelsOfType":d=>{let[u,f]=d;return t.getModelsOfType(ee(u),be(f)).map(te)},"models.getAvailableOfType":async(d,{signal:u})=>{let[f,h]=d;return(await t.getAvailableOfType(ee(f),be(h),{signal:u})).map(te)},"models.getModelOfType":d=>{let[u,f,h]=d;if(typeof f!="string"||typeof h!="string")throw new Error(`models.getModelOfType(type, provider, id) expects three strings, got (${d.map(w).join(", ")}). The provider and the id are separate arguments, for example models.getModelOfType("classifier", "typesafe", "jev-latest").`);let g=t.getModelOfType(ee(u),f,h);return g===void 0?void 0:te(g)},"models.classify":(d,{signal:u})=>c("models.classify","classifier",d,Qe,(f,h)=>t.classify(f,h,{signal:u})),"models.generateImages":(d,{signal:u})=>c("models.generateImages","image",d,Ze,async(f,h)=>{let g=await t.generateImages(f,h,{signal:u});return o(g.output.filter(E=>E.type==="image").length),g})}).map(([d,u])=>({name:d,spread:!0,execute:u}))}export{Ir as executeCodemode,rt as readCodemodeStore};
509
+ `,ae=g();return W.fullOutputPath&&(ae.fullOutputPath=W.fullOutputPath),{content:[{type:"text",text:qe},...Ae],details:ae,...d?{usage:d}:{},...m.ok?{}:{isError:!0}}}function je(t,e){let r=y(e);return[t.name,...t.aliases??[]].some(n=>n===e||y(n)===r)}function ht(t,e,r){let n=new he,s=o=>({name:y(o),description:e.get(o)??""});return[{name:"searchTools",spread:!0,execute:o=>{let[l,i]=o;if(typeof l!="string")throw new Error("searchTools() expects a query string");let c=i?.limit??pe;if(typeof c!="number"||!Number.isInteger(c)||c<=0)throw new Error("searchTools() limit must be a positive integer");let a=i?.namespace;if(a!=null&&typeof a!="string")throw new Error("searchTools() namespace must be a string");let d=t.flatMap(u=>{let f=r.getToolNamespace?.(u.name);return a&&(!f||!je(f,a))?[]:[me(u,f)]});return n.rank(l,d,c).map(u=>s(u.name))}},{name:"describeTool",spread:!0,execute:o=>{let[l]=o;if(typeof l!="string")throw new Error("describeTool() expects a tool name");let i=t.find(c=>c.name===l||y(c.name)===l);return i?e.get(i.name):void 0}},{name:"describeNamespace",spread:!0,execute:o=>{let[l]=o;if(typeof l!="string")throw new Error("describeNamespace() expects a namespace name");let i,c=[];for(let a of t){let d=r.getToolNamespace?.(a.name);!d||!je(d,l)||(i??=d,c.push(y(a.name)))}if(i)return{name:i.name,...i.description?{description:i.description}:{},...i.instructions?{instructions:i.instructions}:{},tools:c}}}]}function gt(t,e,r,n,s,o){let l=rt(Ve),i=0,c=async(d,u,[f,h],g,E)=>{let j=`List the ${u} models you can use with models.getAvailableOfType("${u}").`,T=f;if(typeof T?.provider!="string"||typeof T.id!="string"){let m=f==null?" models.getModelOfType() returns undefined for an unknown provider or id.":"";throw new Error(`${d}() expects ${se(u)} model as its first argument, got ${w(f)}.${m} ${j}`)}let P=T.provider,C=T.id,v=`${P}/${C}`,A=t.getModelOfType(u,P,C);if(!A){let m=[...Te].find(R=>R!==u&&t.getModelOfType(R,P,C)!==void 0);throw new Error(m?`"${v}" is ${se(m)} model, not ${se(u)} model. ${j}`:`Unknown ${u} model "${v}". ${j}`)}let D=g(h),k={id:`${e}/${d}/${++i}`,name:d,args:`${A.provider}/${A.id}`,status:"running"};r.push(k),n();let N=performance.now(),_=await l(()=>E(A,D));return k.durationMs=performance.now()-N,k.status=_.stopReason==="stop"?"ok":_.stopReason==="aborted"?"cancelled":"error",_.errorMessage&&(k.error=ie(_.errorMessage,ve)),_.usage&&(k.cost=_.usage.cost.total,s(_.usage)),n(),_};return Object.entries({"models.getModelsOfType":d=>{let[u,f]=d;return t.getModelsOfType(te(u),Ee(f)).map(re)},"models.getAvailableOfType":async(d,{signal:u})=>{let[f,h]=d;return(await t.getAvailableOfType(te(f),Ee(h),{signal:u})).map(re)},"models.getModelOfType":d=>{let[u,f,h]=d;if(typeof f!="string"||typeof h!="string")throw new Error(`models.getModelOfType(type, provider, id) expects three strings, got (${d.map(w).join(", ")}). The provider and the id are separate arguments, for example models.getModelOfType("classifier", "typesafe", "jev-latest").`);let g=t.getModelOfType(te(u),f,h);return g===void 0?void 0:re(g)},"models.classify":(d,{signal:u})=>c("models.classify","classifier",d,et,(f,h)=>t.classify(f,h,{signal:u})),"models.generateImages":(d,{signal:u})=>c("models.generateImages","image",d,tt,async(f,h)=>{let g=await t.generateImages(f,h,{signal:u});return o(g.output.filter(E=>E.type==="image").length),g})}).map(([d,u])=>({name:d,spread:!0,execute:u}))}export{Hr as executeCodemode,nt as readCodemodeStore};