@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
@@ -0,0 +1,12 @@
1
+ import { createRequire as __cortexCreateRequire } from 'node:module';
2
+ const require = __cortexCreateRequire(import.meta.url);
3
+ const __cortexPackageRoot = new URL("../../", import.meta.url);
4
+ import{a as ce}from"./chunk-5F3A62YS.js";import{a as he}from"./chunk-DQJ6LLAS.js";import{a as me,b as H,c as ye,d as K}from"./chunk-FE7HH5JS.js";import{a as pe}from"./chunk-XIECJESP.js";import{a as be}from"./chunk-ZSV6TO7Q.js";import"./chunk-V3AQJSWR.js";import{a as ae}from"./chunk-OIV4DIMB.js";import"./chunk-BWDJS6A4.js";import"./chunk-6R73ICDB.js";import{h as de,k as le}from"./chunk-7TYSMLUV.js";import{C as se,I as ie,o as re,v as ne,z as oe}from"./chunk-DE5EGVKG.js";import{a as q,c as Q,d as ee}from"./chunk-D6VMBA4C.js";import"./chunk-USBJFDJ6.js";import{a as ue,c as fe}from"./chunk-ZD4O6NPV.js";import{a as J}from"./chunk-K4NTZEDJ.js";import{h as te}from"./chunk-3XLHL5YT.js";import"./chunk-X2TKJ7KR.js";import"./chunk-NW4GW47L.js";import{b as Z}from"./chunk-CXT5IR5T.js";import"./chunk-WHC7AYZD.js";var Be="https://chatgpt.com/backend-api",Pe="https://api.openai.com/auth",Ie=0,we=1e3,Fe=6e4,Ue=15e3,$e=3,ve=new Set(["openai","openai-codex","opencode"]),ze=1009,Je="websocket_connection_limit_reached",He="previous_response_not_found",Ke=16,Ge="medium",je=new Set(["completed","incomplete","failed","cancelled","queued","in_progress"]);function ge(e){if(e.stopReason==="pending")throw new Error("Codex stream ended without a stop reason");if(e.stopReason==="error"||e.stopReason==="aborted")throw new Error(e.errorMessage||"An unknown error occurred")}function Ve(e){return/GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(e)}function Xe(e,r){return e===429&&Ve(r)?!1:e===429||e===500||e===502||e===503||e===504?!0:/rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(r)}function Ye(e){let r=e.get("retry-after-ms");if(r!==null){let s=Number(r);if(Number.isFinite(s))return Math.max(0,s)}let t=e.get("retry-after");if(!t)return;let n=Number(t);if(Number.isFinite(n))return Math.max(0,n*1e3);let i=Date.parse(t);if(!Number.isNaN(i))return Math.max(0,i-Date.now())}var F=class extends Error{};function Ze(e,r){let t=r?.maxRetryDelayMs??Fe;if(t>0&&e>t)throw new F(`Server requested ${Math.ceil(e/1e3)}s retry delay (max: ${Math.ceil(t/1e3)}s)`);return e}function Ee(e,r){return new Promise((t,n)=>{if(r?.aborted){n(new Error("Request was aborted"));return}let i=()=>{clearTimeout(s),n(new Error("Request was aborted"))},s=setTimeout(()=>{r?.removeEventListener("abort",i),t()},e);r?.addEventListener("abort",i,{once:!0})})}function Se(e){if(e!==void 0){if(!Number.isFinite(e)||e<0)throw new Error(`Invalid timeoutMs: ${String(e)}`);return Math.floor(e)}}function Qe(){return typeof process>"u"||!(process.versions?.node||process.versions?.bun)?null:process.getBuiltinModule?.("node:zlib")??null}function et(e){let r=Qe();if(!r||typeof r.zstdCompressSync!="function")return null;try{let t=r.zstdCompressSync(e,{params:{[r.constants.ZSTD_c_compressionLevel]:$e}});return new Uint8Array(t)}catch{return null}}var tt=(e,r,t)=>{let n=new Z,i=ne(r,e.compat?.supportsMidConvoSystemMessages);return(async()=>{let s=rt(e,t),o={role:"assistant",content:[],api:"openai-codex-responses",provider:e.provider,model:e.id,...s===void 0?{}:{providerThinkingLevel:s},usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{let c=t?.apiKey;if(!c)throw new Error(`No API key for provider: ${e.provider}`);let a=Mt(c),p=de(oe(i.messages),e.compat?.supportsOpenAIGrammarTools??!1),d=t?.cacheRetention==="none"?void 0:t?.sessionId,u=pe(d),f=nt(e,i,t,u,p,s),l=await t?.onPayload?.(f,e);l!==void 0&&(f=l);let m=u||ce(),h={originator:"pi",...te(e,t?.identity)},g=Lt(h,e.headers,t?.headers,a,c,u),x=Wt(h,e.headers,t?.headers,a,c,m),y=JSON.stringify(f),S=Se(t?.timeoutMs),C=Se(t?.websocketConnectTimeoutMs),b=t?.transport||"auto",T=!1,O=b!=="sse"&&Me(d);if(O&&_e(d),b!=="sse"&&!O){let E=!1,k=!1,A=!1;for(;;){E=!1;try{if(await Ot(st(e.baseUrl),f,x,o,n,e,()=>{E=!0,T||(T=!0,n.push({type:"start",partial:o}))},S,C,d,a,p,t),t?.signal?.aborted)throw new Error("Request was aborted");ge(o),n.push({type:"done",reason:o.stopReason,message:o}),n.end();return}catch(v){let N=t?.signal?.aborted,D=!E&&ct(v),L=ut(v);if(!N&&L&&!A){A=!0;continue}if(!N&&D&&!k){k=!0;continue}if(N||at(v)&&!D||(ee(o,Q("provider_transport_failure",v,{configuredTransport:b,...E?{}:{fallbackTransport:"sse"},eventsEmitted:E,phase:E?"after_message_stream_start":"before_message_stream_start",requestBytes:new TextEncoder().encode(y).byteLength})),ht(d,v),E))throw v;_e(d);break}}}let Y=et(y);Y&&g.set("content-encoding","zstd");let De=Y??y,_,W,z=t?.maxRetries??Ie;for(let E=0;E<=z;E++){if(t?.signal?.aborted)throw new Error("Request was aborted");try{let k=S!==void 0&&S>0?AbortSignal.timeout(S):void 0,A=he([t?.signal,k]);try{_=await(t?.fetch??globalThis.fetch)(Oe(e.baseUrl),{method:"POST",headers:g,body:De,signal:A.signal})}catch(L){throw k?.aborted&&!t?.signal?.aborted?new Error(`Codex SSE response headers timed out after ${S}ms`):L}finally{A.cleanup()}if(await t?.onResponse?.({status:_.status,headers:J(_.headers)},e),_.ok)break;let v=await _.text();if(E<z&&Xe(_.status,v)){let L=Ye(_.headers),qe=L===void 0?we*2**E:Ze(L,t);await Ee(qe,t?.signal);continue}let N=new Response(v,{status:_.status,statusText:_.statusText}),D=await At(N);throw new Error(D.friendlyMessage||D.message)}catch(k){if(k instanceof Error&&(k.name==="AbortError"||k.message==="Request was aborted"))throw new Error("Request was aborted");if(W=k instanceof Error?k:new Error(String(k)),E<z&&!(W instanceof F)&&!W.message.includes("usage limit")){let A=we*2**E;await Ee(A,t?.signal);continue}throw W}}if(!_?.ok)throw W??new Error("Failed after retries");if(!_.body)throw new Error("No response body");if(T||(T=!0,n.push({type:"start",partial:o})),await it(_,o,n,e,p,t),t?.signal?.aborted)throw new Error("Request was aborted");ge(o),n.push({type:"done",reason:o.stopReason,message:o}),n.end()}catch(c){o.stopReason=t?.signal?.aborted?"aborted":"error",o.errorMessage=fe(ue(c)),n.push({type:"error",reason:o.stopReason,error:o}),n.end()}})(),n},Vt=(e,r,t)=>{let n=t?.apiKey;if(!n)throw new Error(`No API key for provider: ${e.provider}`);let i={...le(e,r,t,n),toolChoice:t?.toolChoice},s=t?.reasoning?ie(e,t.reasoning):"off",o=s!=="off"?s:e.reasoning?"none":void 0;return tt(e,r,{...i,reasoningEffort:o})};function rt(e,r){if(!(!e.compat?.supportsMidConvoEffort||r?.reasoningEffort===void 0))return Re(e,r.reasoningEffort)??void 0}function Re(e,r){return r==="none"?e.thinkingLevelMap?.off===void 0?"none":e.thinkingLevelMap.off:e.thinkingLevelMap?.[r]??r}function nt(e,r,t,n,i,s){let o=e.compat?.supportsStrictMode??!0,c=e.compat?.supportsOpenAIGrammarTools??!1,a=e.compat?.supportsAdditionalTools??!1,p=e.compat?.supportsToolSearch??!1,d=se(r.messages,me({supportsMidConvoSystemMessages:e.compat?.supportsMidConvoSystemMessages??!1,supportsAdditionalTools:a,supportsToolSearch:p})),u=H(e,r,ve,{grammarToolInputProperties:i,supportsMidConvoSystemMessages:e.compat?.supportsMidConvoSystemMessages??!1,supportsAdditionalTools:a,supportsToolSearch:p,toolOptions:{strict:null,supportsStrictMode:o,supportsOpenAIGrammarTools:c},configurationUpdateEffort:s}),f={model:e.id,store:!1,stream:!0,input:u,text:{verbosity:t?.textVerbosity||"low"},include:["reasoning.encrypted_content"],prompt_cache_key:n,tool_choice:t?.toolChoice??"auto",parallel_tool_calls:!0};if(t?.maxTokens&&(e.compat?.supportsMaxOutputTokens??!0)&&(f.max_output_tokens=Math.max(t.maxTokens,Ke)),t?.temperature!==void 0&&(f.temperature=t.temperature),t?.serviceTier!==void 0&&(f.service_tier=t.serviceTier),d.requestTools.length>0&&(f.tools=ye(d.requestTools,{strict:null,supportsStrictMode:o,supportsOpenAIGrammarTools:c})),t?.reasoningEffort!==void 0){let l=s===void 0?Re(e,t.reasoningEffort):Ge;l!==null&&(f.reasoning={effort:l,summary:t.reasoningSummary??"auto"})}else e.reasoning&&e.thinkingLevelMap?.off!==null&&(f.reasoning={effort:e.thinkingLevelMap?.off??"none"});return f}function ot(e,r){switch(r){case"flex":return .5;case"priority":return e.id==="gpt-5.5"?2.5:2;default:return 1}}function xe(e,r,t){let n=ot(t,r);n!==1&&(e.cost.input*=n,e.cost.output*=n,e.cost.cacheRead*=n,e.cost.cacheWrite*=n,e.cost.total=e.cost.input+e.cost.output+e.cost.cacheRead+e.cost.cacheWrite)}function Ce(e,r){return e==="default"&&(r==="flex"||r==="priority")?r:e??r}function Oe(e){let t=(e&&e.trim().length>0?e:Be).replace(/\/+$/,"");return t.endsWith("/codex/responses")?t:t.endsWith("/codex")?`${t}/responses`:`${t}/codex/responses`}function st(e){let r=new URL(Oe(e));return r.protocol==="https:"&&(r.protocol="wss:"),r.protocol==="http:"&&(r.protocol="ws:"),r.toString()}async function it(e,r,t,n,i,s){await K(Ae(lt(e,s?.signal),r,n,s?.onProviderStreamEvent),r,t,n,{serviceTier:s?.serviceTier,grammarToolInputProperties:i,resolveServiceTier:Ce,applyServiceTierPricing:(o,c)=>xe(o,c,n)})}var M=class extends Error{code;payload;constructor(r,t){super(r),this.name="CodexApiError",this.code=t?.code,this.payload=t?.payload,this.cause=t?.cause}},B=class extends Error{payload;constructor(r,t){super(r),this.name="CodexProtocolError",this.payload=t?.payload,this.cause=t?.cause}},U=class extends Error{constructor(r){super(q(r)),this.name="ProviderStreamEventCallbackError",this.cause=r}};function at(e){return e instanceof M||e instanceof B||e instanceof U}function ct(e){return e instanceof M&&e.code===Je}function ut(e){return e instanceof M&&e.code===He}function ft(e){let r=e.error&&typeof e.error=="object"?e.error:void 0;return{code:typeof e.code=="string"?e.code:typeof r?.code=="string"?r.code:void 0,message:typeof e.message=="string"?e.message:typeof r?.message=="string"?r.message:void 0}}async function*Ae(e,r,t,n){for await(let i of e){try{await n?.(i,t)}catch(o){throw new U(o)}let s=typeof i.type=="string"?i.type:void 0;if(s){if(s==="error"){let{code:o,message:c}=ft(i);throw new M(`Codex error: ${c||o||JSON.stringify(i)}`,{code:o,payload:i})}if(s==="response.failed"){let o=i.response,c=o?.error?.code,a=o?.error?.message;throw new M(a||"Codex response failed",{code:c,payload:i})}if(s==="response.done"||s==="response.completed"||s==="response.incomplete"){let o=i.response;typeof o?.end_turn=="boolean"&&(r.endTurn=o.end_turn);let c=o&&{...o,status:dt(o.status)};yield{...i,type:"response.completed",response:c};return}yield i}}}function dt(e){if(typeof e=="string")return je.has(e)?e:void 0}async function*lt(e,r){if(!e.body)return;let t=e.body.getReader(),n=new TextDecoder,i="",s=()=>{t.cancel().catch(()=>{})};r?.addEventListener("abort",s,{once:!0});try{for(;;){if(r?.aborted)throw new Error("Request was aborted");let{done:o,value:c}=await t.read();if(r?.aborted)throw new Error("Request was aborted");i+=o?n.decode():n.decode(c,{stream:!0}),o&&i.trim()&&(i+=`
5
+
6
+ `);let a=i.indexOf(`
7
+
8
+ `);for(;a!==-1;){let p=i.slice(0,a);i=i.slice(a+2);let d=p.split(`
9
+ `).filter(u=>u.startsWith("data:")).map(u=>u.slice(5).trim());if(d.length>0){let u=d.join(`
10
+ `).trim();if(u&&u!=="[DONE]")try{yield JSON.parse(u)}catch(f){throw new B(`Invalid Codex SSE JSON: ${q(f)}`,{cause:f,payload:u})}}a=i.indexOf(`
11
+
12
+ `)}if(o)break}}finally{r?.removeEventListener("abort",s);try{await t.cancel()}catch{}try{t.releaseLock()}catch{}}}var pt="responses_websockets=2026-02-06",mt=300*1e3,yt=2700*1e3,w=new Map,P=new Map,$=new Set;function X(e){let r=P.get(e);return r||(r={requests:0,connectionsCreated:0,connectionsReused:0,cachedContextRequests:0,storeTrueRequests:0,fullContextRequests:0,deltaRequests:0,lastInputItems:0,websocketFailures:0,sseFallbacks:0},P.set(e,r)),r}function Xt(e){let r=P.get(e);return r?{...r}:void 0}function Yt(e){if(e){P.delete(e),$.delete(e);return}P.clear(),$.clear()}function bt(e){let r=t=>{t.idleTimer&&clearTimeout(t.idleTimer),R(t.socket,1e3,"debug_close")};if(e){for(let t of w.get(e)?.values()??[])r(t);w.delete(e);return}for(let t of w.values())for(let n of t.values())r(n);w.clear()}ae(bt);function Me(e){return e?$.has(e):!1}function _e(e){if(!e)return;let r=X(e);r.sseFallbacks++,r.websocketFallbackActive=Me(e)}function ht(e,r){if(!e)return;$.add(e);let t=X(e);t.websocketFailures++,t.lastWebSocketError=q(r),t.websocketFallbackActive=!0}var G=null;async function wt(e){if(!e&&G)return G;if(typeof process<"u"&&process.versions?.bun){let t=class extends WebSocket{constructor(n,i){let s={};Array.isArray(i)||typeof i=="string"?s={protocols:i}:s={...i};let o=be(n.toString().replace(/^wss:/,"https:").replace(/^ws:/,"http:"),e);super(n,{...s,...o?{proxy:o.toString()}:{}})}};return e||(G=t),t}let r=globalThis.WebSocket;return typeof r!="function"?null:r}var V=class extends Error{code;reason;wasClean;constructor(r,t){super(r),this.name="WebSocketCloseError",this.code=t?.code,this.reason=t?.reason,this.wasClean=t?.wasClean}};function gt(e){let r=e.readyState;return typeof r=="number"?r:void 0}function I(e){let r=gt(e);return r===void 0||r===1}function Et(e){return Date.now()-e.createdAt>=yt}function R(e,r=1e3,t="done"){try{e.close(r,t)}catch{}}function ke(e,r,t){t.idleTimer&&clearTimeout(t.idleTimer),t.idleTimer=setTimeout(()=>{if(t.busy)return;R(t.socket,1e3,"idle_timeout");let n=w.get(e);n?.get(r)===t&&n.delete(r),n?.size===0&&w.delete(e)},mt)}async function j(e,r,t,n=Ue,i){let s=await wt(i);if(!s)throw new Error("WebSocket transport is not available in this runtime");let o=J(r);return delete o["OpenAI-Beta"],new Promise((c,a)=>{let p=!1,d,u;try{u=new s(e,{headers:o})}catch(y){a(y instanceof Error?y:new Error(String(y)));return}let f=()=>{d&&(clearTimeout(d),d=void 0),u.removeEventListener("open",m),u.removeEventListener("error",h),u.removeEventListener("close",g),t?.removeEventListener("abort",x)},l=(y,S)=>{p||(p=!0,f(),S&&R(u,1e3,S),a(y))},m=()=>{p||(p=!0,f(),c(u))},h=y=>{l(Le(y))},g=y=>{l(We(y))},x=()=>{l(new Error("Request was aborted"),"aborted")};u.addEventListener("open",m),u.addEventListener("error",h),u.addEventListener("close",g),t?.addEventListener("abort",x),n>0&&(d=setTimeout(()=>{l(new Error(`WebSocket connect timeout after ${n}ms`),"connect_timeout")},n)),t?.aborted&&x()})}async function St(e,r,t,n,i,s,o){if(!t){let u=await j(e,r,i,s,o);return{socket:u,reused:!1,release:()=>R(u)}}let c=w.get(t),a=c?.get(n);if(a){if(a.idleTimer&&(clearTimeout(a.idleTimer),a.idleTimer=void 0),!a.busy&&Et(a))R(a.socket,1e3,"connection_age_limit"),c?.delete(n),c?.size===0&&w.delete(t);else if(!a.busy&&I(a.socket))return a.busy=!0,{socket:a.socket,entry:a,reused:!0,release:({keep:u}={})=>{if(!u||!I(a.socket)){R(a.socket);let f=w.get(t);f?.get(n)===a&&f.delete(n),f?.size===0&&w.delete(t);return}a.busy=!1,ke(t,n,a)}};if(a.busy){let u=await j(e,r,i,s,o);return{socket:u,reused:!1,release:()=>{R(u)}}}I(a.socket)||(R(a.socket),c?.delete(n),c?.size===0&&w.delete(t))}let p=await j(e,r,i,s,o),d={socket:p,busy:!0,createdAt:Date.now()};return c=w.get(t),c||(c=new Map,w.set(t,c)),c.set(n,d),{socket:p,entry:d,reused:!1,release:({keep:u}={})=>{if(!u||!I(d.socket)){R(d.socket),d.idleTimer&&clearTimeout(d.idleTimer);let f=w.get(t);f?.get(n)===d&&f.delete(n),f?.size===0&&w.delete(t);return}d.busy=!1,ke(t,n,d)}}}function Le(e){if(e&&typeof e=="object"){let r="message"in e?e.message:void 0;if(typeof r=="string"&&r.length>0)return new Error(r);let t="error"in e?e.error:void 0;if(t instanceof Error&&t.message.length>0)return t;if(t&&typeof t=="object"&&"message"in t){let n=t.message;if(typeof n=="string"&&n.length>0)return new Error(n)}}return new Error("WebSocket error")}function We(e){if(e&&typeof e=="object"){let r="code"in e?e.code:void 0,t="reason"in e?e.reason:void 0,n="wasClean"in e?e.wasClean:void 0,i=typeof r=="number"?` ${r}`:"",s=typeof t=="string"&&t.length>0?` ${t}`:"";return!s&&r===ze&&(s=" message too big"),new V(`WebSocket closed${i}${s}`.trim(),{code:typeof r=="number"?r:void 0,reason:typeof t=="string"&&t.length>0?t:void 0,wasClean:typeof n=="boolean"?n:void 0})}return new Error("WebSocket closed")}async function _t(e){if(typeof e=="string")return e;if(e instanceof ArrayBuffer)return new TextDecoder().decode(new Uint8Array(e));if(ArrayBuffer.isView(e)){let r=e;return new TextDecoder().decode(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}if(e&&typeof e=="object"&&"arrayBuffer"in e){let t=await e.arrayBuffer();return new TextDecoder().decode(new Uint8Array(t))}return null}async function*kt(e,r,t){let n=[],i=null,s=!1,o=null,c=!1,a=()=>{if(!i)return;let l=i;i=null,l()},p=l=>{(async()=>{let m=null;try{if(!l||typeof l!="object"||!("data"in l)||(m=await _t(l.data),!m))return;let h=JSON.parse(m),g=typeof h.type=="string"?h.type:"";(g==="response.completed"||g==="response.done"||g==="response.incomplete")&&(c=!0,s=!0),n.push(h),a()}catch(h){o=new B(`Invalid Codex WebSocket JSON: ${q(h)}`,{cause:h,payload:m}),s=!0,a()}})()},d=l=>{o=Le(l),s=!0,a()},u=l=>{if(c){s=!0,a();return}o||(o=We(l)),s=!0,a()},f=()=>{o=new Error("Request was aborted"),s=!0,a()};e.addEventListener("message",p),e.addEventListener("error",d),e.addEventListener("close",u),r?.addEventListener("abort",f);try{for(;;){if(r?.aborted)throw new Error("Request was aborted");if(n.length>0){yield n.shift();continue}if(s)break;let l;await new Promise((m,h)=>{i=m,t!==void 0&&t>0&&(l=setTimeout(()=>{let g=new Error(`WebSocket idle timeout after ${t}ms`);o=g,s=!0,i=null,R(e,1e3,"idle_timeout"),h(g)},t))}).finally(()=>{l&&clearTimeout(l)})}if(o)throw o;if(!c)throw new Error("WebSocket stream closed before response.completed")}finally{e.removeEventListener("message",p),e.removeEventListener("error",d),e.removeEventListener("close",u),r?.removeEventListener("abort",f)}}function Te(e){let{input:r,previous_response_id:t,...n}=e;return n}function Tt(e,r){return JSON.stringify(e??[])===JSON.stringify(r??[])}function vt(e,r){return JSON.stringify(Te(e))===JSON.stringify(Te(r))}function Rt(e,r){if(!vt(e,r.lastRequestBody))return;let t=e.input??[],n=[...r.lastRequestBody.input??[],...r.lastResponseItems];if(t.length<n.length)return;let i=t.slice(0,n.length);if(Tt(i,n))return t.slice(n.length)}function xt(e,r){let t=e.continuation;if(!t)return r;let n=Rt(r,t);return!n||!t.lastResponseId?(e.continuation=void 0,r):{...r,previous_response_id:t.lastResponseId,input:n}}async function*Ct(e,r){let t=!1;for await(let n of e)t||(t=!0,r()),yield n}async function Ot(e,r,t,n,i,s,o,c,a,p,d,u,f){let{socket:l,entry:m,reused:h,release:g}=await St(e,t,p,d,f?.signal,a,f?.env),x=!0,y=f?.transport==="websocket-cached"||f?.transport==="auto",S=r,C=y&&m?xt(m,S):S,b=p?X(p):void 0;b&&(b.requests++,h?b.connectionsReused++:b.connectionsCreated++,y&&b.cachedContextRequests++,C.store===!0&&b.storeTrueRequests++,b.lastInputItems=C.input?.length??0,C.previous_response_id?(b.deltaRequests++,b.lastDeltaInputItems=C.input?.length??0,b.lastPreviousResponseId=C.previous_response_id):(b.fullContextRequests++,b.lastDeltaInputItems=void 0,b.lastPreviousResponseId=void 0));try{if(l.send(JSON.stringify({type:"response.create",...C})),await K(Ct(Ae(kt(l,f?.signal,c),n,s,f?.onProviderStreamEvent),o),n,i,s,{serviceTier:f?.serviceTier,grammarToolInputProperties:u,resolveServiceTier:Ce,applyServiceTierPricing:(T,O)=>xe(T,O,s)}),f?.signal?.aborted)x=!1;else if(y&&m&&n.responseId){let T=H(s,re({messages:[n]}),ve,{grammarToolInputProperties:u}).filter(O=>O.type!=="function_call_output"&&O.type!=="custom_tool_call_output");m.continuation={lastRequestBody:S,lastResponseId:n.responseId,lastResponseItems:T}}}catch(T){throw m&&(m.continuation=void 0),x=!1,T}finally{g({keep:x})}}async function At(e){let r=await e.text(),t=r||e.statusText||"Request failed",n;try{let s=JSON.parse(r)?.error;if(s){let o=s.code||s.type||"";if(/usage_limit_reached|usage_not_included|rate_limit_exceeded/i.test(o)||e.status===429){let c=s.plan_type?` (${s.plan_type.toLowerCase()} plan)`:"",a=s.resets_at?Math.max(0,Math.round((s.resets_at*1e3-Date.now())/6e4)):void 0,p=a!==void 0?` Try again in ~${a} min.`:"";n=`You have hit your ChatGPT usage limit${c}.${p}`.trim()}t=s.message||n||t}}catch{}return{message:t,friendlyMessage:n}}function Mt(e){try{let r=e.split(".");if(r.length!==3)throw new Error("Invalid token");let n=JSON.parse(atob(r[1]))?.[Pe]?.chatgpt_account_id;if(!n)throw new Error("No account ID in token");return n}catch{throw new Error("Failed to extract accountId from token")}}function Ne(e,r,t,n,i){let s=new Headers(e);for(let[o,c]of Object.entries(r||{}))s.set(o,c);for(let[o,c]of Object.entries(t||{}))c===null?s.delete(o):s.set(o,c);return s.set("Authorization",`Bearer ${i}`),s.set("chatgpt-account-id",n),s}function Lt(e,r,t,n,i,s){let o=Ne(e,r,t,n,i);return o.set("OpenAI-Beta","responses=experimental"),o.set("accept","text/event-stream"),o.set("content-type","application/json"),s&&(o.set("session-id",s),o.set("x-client-request-id",s)),o}function Wt(e,r,t,n,i,s){let o=Ne(e,r,t,n,i);return o.delete("accept"),o.delete("content-type"),o.delete("OpenAI-Beta"),o.delete("openai-beta"),o.set("OpenAI-Beta",pt),o.set("x-client-request-id",s),o.set("session-id",s),o}export{bt as closeOpenAICodexWebSocketSessions,Xt as getOpenAICodexWebSocketDebugStats,Yt as resetOpenAICodexWebSocketDebugStats,tt as stream,Vt as streamSimple};
@@ -0,0 +1,9 @@
1
+ import { createRequire as __cortexCreateRequire } from 'node:module';
2
+ const require = __cortexCreateRequire(import.meta.url);
3
+ const __cortexPackageRoot = new URL("../../", import.meta.url);
4
+ import{a as ve}from"./chunk-XIECJESP.js";import{a as _e}from"./chunk-4SWD4JMP.js";import{a as ie,b as ae}from"./chunk-UPQVWHZ3.js";import{a as he,b as me}from"./chunk-BGYR4ID3.js";import{a as oe}from"./chunk-V3AQJSWR.js";import{f as te}from"./chunk-BWDJS6A4.js";import{a as ee}from"./chunk-6R73ICDB.js";import{a as ue}from"./chunk-23PRJECN.js";import{b as fe,c as le,d as ce,e as pe,f as ge,g as de,h as H,j as ye,k as ke,m as Te,n as Re,q as xe}from"./chunk-7TYSMLUV.js";import{C as j,G as X,I as Y,v as z,z as G}from"./chunk-DE5EGVKG.js";import"./chunk-D6VMBA4C.js";import{a as q}from"./chunk-USBJFDJ6.js";import{a as ne,c as se}from"./chunk-ZD4O6NPV.js";import{a as re}from"./chunk-K4NTZEDJ.js";import{h as Q}from"./chunk-3XLHL5YT.js";import{b as U,c as Z}from"./chunk-X2TKJ7KR.js";import"./chunk-NW4GW47L.js";import{b as V}from"./chunk-CXT5IR5T.js";import"./chunk-WHC7AYZD.js";function Ce(e,n){if(!e)return!1;let t=n.toLowerCase();for(let[s,a]of Object.entries(e))if(s.toLowerCase()===t&&a!==null&&a.trim().length>0)return!0;return!1}function Ie(e,n,t){if(n)return n;if(Ce(t,"authorization")||Ce(t,"cf-aig-authorization"))return"unused";throw new Error(`No API key for provider: ${e}`)}function Be(e){for(let n of e)if(n.role==="toolResult"||n.role==="assistant"&&n.content.some(t=>t.type==="toolCall"))return!0;return!1}function Me(e){return e.type==="text"}function Le(e){return e.type==="thinking"}function Ne(e){return e.type==="toolCall"}function De(e){return e.type==="image"}function ze(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ge(e){return(e.id===void 0||e.id===null||typeof e.id=="string")&&(e.format===void 0||typeof e.format=="string")&&(e.index===void 0||typeof e.index=="number")}function K(e){if(!ze(e)||!Ge(e))return!1;switch(e.type){case"reasoning.summary":return typeof e.summary=="string";case"reasoning.encrypted":return typeof e.data=="string";case"reasoning.text":return typeof e.text=="string"&&(e.signature===void 0||e.signature===null||typeof e.signature=="string");default:return!1}}function je(e){if(e)try{let n=JSON.parse(e);return Array.isArray(n)&&n.length>0&&n.every(K)?n:void 0}catch{return}}function He(e){if(e)try{let n=JSON.parse(e);return K(n)&&n.type==="reasoning.encrypted"&&typeof n.id=="string"&&n.id.length>0&&n.data.length>0?n:void 0}catch{return}}function Ae(e,n){e.id??=n.id,e.format||=n.format,e.index??=n.index}function Ke(e,n){let t=e[e.length-1];if(n.type==="reasoning.text"&&t?.type==="reasoning.text"){t.text+=n.text,t.signature||=n.signature,Ae(t,n);return}if(n.type==="reasoning.summary"&&t?.type==="reasoning.summary"){t.summary+=n.summary,Ae(t,n);return}e.push({...n})}var We=["reasoning","reasoning_content","reasoning_text"];function $e(e){return We.includes(e)}function be(e,n){return e||(ee("PI_CACHE_RETENTION",n)==="long"?"long":"short")}var Je=(e,n,t)=>{let s=new V,a=z(n,D(e).supportsMidConvoSystemMessages);return(async()=>{let o={role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()},m,h=y=>{m!==void 0&&(y.thinkingSignature=JSON.stringify(m))};try{let y=Ie(e.provider,t?.apiKey,t?.headers),R=D(e),x=H(G(a.messages),R.supportsOpenAIGrammarTools),u=be(t?.cacheRetention,t?.env),g=u==="none"?void 0:t?.sessionId,d=Ve(e,a,y,t?.headers,t?.identity,t?.fetch,g,R),l=Ue(e,a,t,R,u,x),r=await t?.onPayload?.(l,e);r!==void 0&&(l=r);let p={...t?.signal?{signal:t.signal}:{},...t?.timeoutMs!==void 0?{timeout:t.timeoutMs}:{},maxRetries:0},{data:_,response:A}=await ue(()=>d.chat.completions.create(l,p).withResponse(),{maxRetries:t?.maxRetries,maxRetryDelayMs:t?.maxRetryDelayMs,signal:t?.signal});await t?.onResponse?.({status:A.status,headers:re(A.headers)},e),s.push({type:"start",partial:o});let E=null,b=null,w=!1,v=new Map,F=new Map,B=new Map,f=o.content,M=i=>f.indexOf(i),W=i=>({kind:"custom",property:i,buffer:{input:"",started:!1,closed:!1}}),Oe=i=>{let c=M(i);if(c!==-1){if(i.type==="text")s.push({type:"text_end",contentIndex:c,content:i.text,partial:o});else if(i.type==="thinking")h(i),s.push({type:"thinking_end",contentIndex:c,content:i.thinking,partial:o});else if(i.type==="toolCall"){let C=B.get(i).input;if(B.delete(i),C.kind==="custom"){let T=pe(C.buffer,C.property,void 0);T!==void 0&&s.push({type:"toolcall_delta",contentIndex:c,delta:T,partial:o})}else Object.assign(i,C.arguments.finish());s.push({type:"toolcall_end",contentIndex:c,toolCall:i,partial:o})}}},qe=()=>(E||(E={type:"text",text:""},f.push(E),s.push({type:"text_start",contentIndex:M(E),partial:o})),E),$=i=>(b||(b={type:"thinking",thinking:"",thinkingSignature:i},f.push(b),s.push({type:"thinking_start",contentIndex:M(b),partial:o})),b),Pe=i=>{let c=typeof i.index=="number"?i.index:void 0,C=i.function?.name??i.custom?.name??"",T=c!==void 0?v.get(c):void 0;if(!T&&i.id&&(T=F.get(i.id)),!T){let O=i.custom&&!i.function?x.get(C)??"input":void 0;T={type:"toolCall",id:i.id||"",name:C,arguments:O!==void 0?{[O]:""}:{}},B.set(T,{streamIndex:c,input:O!==void 0?W(O):{kind:"json",arguments:new te}}),c!==void 0&&v.set(c,T),i.id&&F.set(i.id,T),f.push(T),s.push({type:"toolcall_start",contentIndex:M(T),partial:o})}let I=B.get(T);if(c!==void 0&&I.streamIndex===void 0&&(I.streamIndex=c,v.set(c,T)),i.id&&F.set(i.id,T),!T.name&&C&&(T.name=C),i.custom&&!i.function&&I.input.kind!=="custom"){let O=x.get(T.name)??"input";T.arguments={[O]:""},I.input=W(O)}return{block:T,state:I}};for await(let i of _){if(await t?.onProviderStreamEvent?.(i,e),!i||typeof i!="object")continue;o.responseId||=i.id,typeof i.model=="string"&&i.model.length>0&&i.model!==e.id&&(o.responseModel||=i.model),i.usage&&(o.usage=Ee(i.usage,e));let c=Array.isArray(i.choices)?i.choices[0]:void 0;if(c){if(!i.usage&&c.usage&&(o.usage=Ee(c.usage,e)),c.finish_reason){o.rawStopReason=c.finish_reason;let C=at(c.finish_reason);o.stopReason=C.stopReason,C.errorMessage&&(o.errorMessage=C.errorMessage),w=!0}if(c.delta){let C=["reasoning_content","reasoning","reasoning_text"],T=c.delta,I=null;for(let k of C){let S=T[k];if(typeof S=="string"&&S.length>0){I=k;break}}if(I){let k=T[I];if(typeof k=="string"&&k.length>0){let S=e.provider==="opencode-go"&&I==="reasoning"?"reasoning_content":I,L=$(S);L.thinking+=k,s.push({type:"thinking_delta",contentIndex:M(L),delta:k,partial:o})}}let O=c.delta.reasoning_details;if(Array.isArray(O))for(let k of O)K(k)&&($(""),m??=[],Ke(m,k));if(c.delta.content!==null&&c.delta.content!==void 0&&c.delta.content.length>0){let k=qe();k.text+=c.delta.content,s.push({type:"text_delta",contentIndex:M(k),delta:c.delta.content,partial:o})}if(c?.delta?.tool_calls)for(let k of c.delta.tool_calls){let{block:S,state:L}=Pe(k);!S.id&&k.id&&(S.id=k.id,F.set(k.id,S));let J=k.function?.name??k.custom?.name;!S.name&&J&&(S.name=J);let N="",P=L.input;k.function?.arguments&&P.kind==="json"?(N=k.function.arguments,S.arguments=P.arguments.append(N)):k.custom?.input&&P.kind==="custom"&&(N=ce(P.buffer,P.property,k.custom.input)??"",S.arguments={[P.property]:P.buffer.input}),s.push({type:"toolcall_delta",contentIndex:M(S),delta:N,partial:o})}}}}for(let i of f)Oe(i);if(t?.signal?.aborted)throw new Error("Request was aborted");if(o.stopReason==="aborted")throw new Error("Request was aborted");if(!w&&!R.supportsFinishReason&&(o.stopReason=o.content.some(i=>i.type==="toolCall")?"toolUse":"stop"),o.stopReason==="error")throw new Error(o.errorMessage||"Provider returned an error stop reason");if(R.supportsFinishReason&&!w||o.stopReason==="pending")throw new Error("Stream ended without finish_reason");s.push({type:"done",reason:o.stopReason,message:o}),s.end()}catch(y){for(let x of o.content)x.type==="thinking"&&h(x);o.stopReason=t?.signal?.aborted?"aborted":"error",o.errorMessage=se(ne(y));let R=y?.error?.metadata?.raw;R&&!o.errorMessage.includes(String(R))&&(o.errorMessage+=`
5
+ ${R}`),s.push({type:"error",reason:o.stopReason,error:o}),s.end()}})(),s},Et=(e,n,t)=>{Ie(e.provider,t?.apiKey,t?.headers);let s={...ke(e,n,t,t?.apiKey),toolChoice:t?.toolChoice},a=t?.reasoning?Y(e,t.reasoning):void 0;return Je(e,n,{...s,reasoningEffort:a==="off"?void 0:a,thinkingBudgets:t?.thinkingBudgets})};function Ve(e,n,t,s,a,o,m,h=D(e)){let y={...Q(e,a),...e.headers};if(e.provider==="github-copilot"){let R=he(n.messages),x=me({messages:n.messages,hasImages:R});Object.assign(y,x)}return m&&h.sendSessionAffinityHeaders&&(h.sessionAffinityFormat==="openrouter"?y["x-session-id"]=m:(h.sessionAffinityFormat==="openai"&&(y.session_id=m),y["x-client-request-id"]=m,y["x-session-affinity"]=m)),s&&Object.assign(y,s),new _e({apiKey:t,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:o,defaultHeaders:y})}function Ue(e,n,t,s=D(e),a=be(t?.cacheRetention,t?.env),o=H(G(n.messages),s.supportsOpenAIGrammarTools)){let m=j(n.messages,s.supportsMidConvoSystemMessages===!0&&s.supportsMidConvoToolAdditions===!0?"additions":"none"),h=it(e,n,s,{grammarToolInputProperties:o}),y=Ye(s,a),R=s.promptCacheKeyMode??"auto",x=R==="enabled"||R==="auto"&&(e.baseUrl.includes("api.openai.com")||a==="long"&&s.supportsLongCacheRetention),u={model:e.id,messages:h,stream:!0,prompt_cache_key:a!=="none"&&x?ve(t?.sessionId):void 0,prompt_cache_retention:a==="long"&&s.supportsLongCacheRetention?"24h":void 0};s.supportsUsageInStreaming!==!1&&(u.stream_options={include_usage:!0}),s.supportsStore&&(u.store=!1),t?.maxTokens&&(s.maxTokensField==="max_tokens"?u.max_tokens=t.maxTokens:u.max_completion_tokens=t.maxTokens),t?.temperature!==void 0&&(u.temperature=t.temperature),m.requestTools.length>0?(u.tools=Fe(m.requestTools,s),s.zaiToolStream&&(u.tool_stream=!0)):s.requiresToolsWithToolHistory&&Be(n.messages)&&(u.tools=[]),y&&et(h,u.tools,y),t?.toolChoice&&(u.tool_choice=t.toolChoice),s.vllmPriority!==void 0&&(u.priority=s.vllmPriority);let g=Ze(s),d=Qe(e,t,u);if(s.thinkingFormat==="zai"&&e.reasoning){let r=u;if(r.thinking=t?.reasoningEffort?{type:"enabled",clear_thinking:!1}:{type:"disabled"},t?.reasoningEffort&&s.supportsReasoningEffort){let p=e.thinkingLevelMap?.[t.reasoningEffort],_=p===void 0?t.reasoningEffort:p;typeof _=="string"&&(r.reasoning_effort=_)}}else if(s.thinkingFormat==="qwen"&&e.reasoning){if(u.enable_thinking=!!t?.reasoningEffort,t?.reasoningEffort&&s.supportsReasoningEffort){let r=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort;typeof r=="string"&&(u.reasoning_effort=r)}}else if(s.thinkingFormat==="qwen-chat-template"&&e.reasoning)u.chat_template_kwargs={enable_thinking:!!t?.reasoningEffort,preserve_thinking:!0};else if(s.thinkingFormat==="chat-template"&&e.reasoning){let r=Se(e,t,s.chatTemplateKwargs,d);r&&(u.chat_template_kwargs=r)}else if(s.thinkingFormat==="baseten"&&e.reasoning){let r=u,p=Se(e,t,s.chatTemplateArgs,d);if(p&&(r.chat_template_args=p),s.supportsReasoningEffort){let _=t?.reasoningEffort,A=_?e.thinkingLevelMap?.[_]:e.thinkingLevelMap?.off,E=A===void 0?_:A;typeof E=="string"&&(r.reasoning_effort=E)}}else if(s.thinkingFormat==="deepseek"&&e.reasoning)t?.reasoningEffort?u.thinking={type:"enabled"}:e.thinkingLevelMap?.off!==null&&(u.thinking={type:"disabled"}),t?.reasoningEffort&&s.supportsReasoningEffort&&(u.reasoning_effort=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort);else if(s.thinkingFormat==="openrouter"&&e.reasoning){let r=u;t?.reasoningEffort?r.reasoning={effort:e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort}:e.thinkingLevelMap?.off!==null&&(r.reasoning={effort:e.thinkingLevelMap?.off??"none"})}else if(s.thinkingFormat==="ant-ling"&&e.reasoning&&t?.reasoningEffort){let r=e.thinkingLevelMap?.[t.reasoningEffort];typeof r=="string"&&(u.reasoning={effort:r})}else if(s.thinkingFormat==="together"&&e.reasoning){let r=u;r.reasoning={enabled:!!t?.reasoningEffort},t?.reasoningEffort&&s.supportsReasoningEffort&&(r.reasoning_effort=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort)}else if(s.thinkingFormat==="string-thinking"&&e.reasoning){let r=u;t?.reasoningEffort?r.thinking=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort:e.thinkingLevelMap?.off!==null&&(r.thinking=e.thinkingLevelMap?.off??"none")}else if(t?.reasoningEffort&&e.reasoning&&s.supportsReasoningEffort)u.reasoning_effort=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort;else if(!t?.reasoningEffort&&e.reasoning&&s.supportsReasoningEffort){let r=e.thinkingLevelMap?.off;typeof r=="string"&&(u.reasoning_effort=r)}if(g&&d!==void 0&&Object.assign(u,{[g]:d}),e.compat?.openRouterRouting&&(u.provider=e.compat.openRouterRouting),e.compat?.vercelGatewayRouting){let r=e.compat.vercelGatewayRouting;if(r.only||r.order){let p={};r.only&&(p.only=r.only),r.order&&(p.order=r.order),u.providerOptions={gateway:p}}}let l=ye(e,t?.reasoningEffort??"off",t?.samplingParams);return l&&Object.assign(u,l),u}function Ze(e){if(e.thinkingTokenBudgetField)return e.thinkingTokenBudgetField;if(e.supportsThinkingTokenBudget)return"thinking_token_budget"}function Qe(e,n,t){if(!n?.reasoningEffort||!e.reasoning)return;let s=t.max_tokens??t.max_completion_tokens??e.maxTokens,a=Re(Te(n.reasoningEffort,n.thinkingBudgets),s);return a>0?a:void 0}function Se(e,n,t,s){let a={};for(let[o,m]of Object.entries(t)){let h=Xe(e,n,m,s);h!==void 0&&(a[o]=h)}return Object.keys(a).length>0?a:void 0}function Xe(e,n,t,s){if(typeof t!="object"||t===null)return t;let a=n?.reasoningEffort;if(!a&&t.omitWhenOff)return;if(t.$var==="thinking.enabled")return!!a;if(t.$var==="thinking.budget")return s;let o=a?e.thinkingLevelMap?.[a]:e.thinkingLevelMap?.off;return o===void 0?a:typeof o=="string"?o:void 0}function Ye(e,n){if(e.cacheControlFormat!=="anthropic"||n==="none")return;let t=n==="long"&&e.supportsLongCacheRetention?"1h":void 0;return{type:"ephemeral",...t?{ttl:t}:{}}}function et(e,n,t){tt(e,t),st(n,t),nt(e,t)}function tt(e,n){for(let t of e)if(t.role==="system"||t.role==="developer"){ot(t,n);return}}function nt(e,n){for(let t=e.length-1;t>=0;t--){let s=e[t];if((s.role==="user"||s.role==="assistant"||s.role==="tool")&&rt(s,n))return}}function st(e,n){if(!e||e.length===0)return;let t=e[e.length-1];t.cache_control=n}function ot(e,n){return we(e,n)}function rt(e,n){return e.role==="user"||e.role==="assistant"||e.role==="tool"?we(e,n):!1}function we(e,n){let t=e.content;if(typeof t=="string")return t.length===0?!1:(e.content=[{type:"text",text:t,cache_control:n}],!0);if(!Array.isArray(t))return!1;for(let s=t.length-1;s>=0;s--){let a=t[s];if(a?.type==="text"){let o=a;return o.cache_control=n,!0}}return!1}function it(e,n,t,s){let a=z(n,t.supportsMidConvoSystemMessages),o=[],m=g=>{if(g.includes("|")){let d=g.indexOf("|"),l=g.slice(0,d).replace(/[^a-zA-Z0-9_-]/g,"_"),r=g.slice(d+1).replace(/[^a-zA-Z0-9_-]/g,"_"),p=r.length>0?`${l}_${r}`:l;if(p.length<=40)return p;let _=oe(g).slice(0,8);return`${l.slice(0,Math.max(1,40-_.length-1))}_${_}`}return e.provider==="openai"&&g.length>40?g.slice(0,40):g},h=xe(a.messages,e,g=>m(g)),y=j(a.messages,t.supportsMidConvoSystemMessages===!0&&t.supportsMidConvoToolAdditions===!0?"additions":"none"),R=e.reasoning&&t.supportsDeveloperRole?"developer":"system",x=null,u=0;for(let g=0;g<h.length;g++){let d=h[g];if(t.requiresAssistantAfterToolResult&&x==="toolResult"&&d.role==="user"&&o.push({role:"assistant",content:"I have processed the tool results."}),d.role==="system"){let l=u++>=y.foldedSystemMessages?d.toolsAdded??[]:[];if(l.length>0){let p={role:"system",tools:Fe(l,t)};o.push(p)}let r=g===0?U(d):Z(d);r.length>0&&o.push({role:R,content:q(r)})}else if(d.role==="user")if(typeof d.content=="string")o.push({role:"user",content:q(d.content)});else{let l=d.content.filter(r=>r.type!=="text"||r.text.length>0).map(r=>r.type==="text"?{type:"text",text:q(r.text)}:{type:"image_url",image_url:{url:`data:${r.mimeType};base64,${r.data}`}});if(l.length===0)continue;o.push({role:"user",content:l})}else if(d.role==="assistant"){let l={role:"assistant",content:t.requiresAssistantAfterToolResult||t.requiresNonNullAssistantContent?"":null},r=d.content.filter(Me).filter(f=>f.text.trim().length>0).map(f=>({type:"text",text:q(f.text)})),p=r.map(f=>f.text).join(""),_=d.content.filter(Le),A=d.content.filter(Ne),E=_.map(f=>je(f.thinkingSignature)).find(f=>f!==void 0),b=A.map(f=>He(f.thoughtSignature)).filter(f=>f!==void 0),w=E??(b.length>0?b:void 0),v=_.filter(f=>f.thinking.trim().length>0);if(v.length>0){if(t.requiresThinkingAsText){let f=v.map(M=>q(M.thinking)).join(`
6
+
7
+ `);l.content=[{type:"text",text:f},...r]}else if(p.length>0&&(l.content=p),!w){let f=v[0].thinkingSignature;e.provider==="opencode-go"&&f==="reasoning"&&(f="reasoning_content"),f&&$e(f)&&(l[f]=v.map(M=>M.thinking).join(`
8
+ `))}}else p.length>0&&(l.content=p);A.length>0&&(l.tool_calls=A.map(f=>{let M=s?.grammarToolInputProperties?.get(f.name);return M!==void 0?{id:f.id,type:"custom",custom:{name:f.name,input:q(le(f.name,f.arguments,M))}}:{id:f.id,type:"function",function:{name:f.name,arguments:JSON.stringify(f.arguments)}}})),w&&(l.reasoning_details=w),t.requiresReasoningContentOnAssistantMessages&&e.reasoning&&l.reasoning_content===void 0&&(l.reasoning_content="");let F=l.content;if(!(F!=null&&F.length>0)&&!l.tool_calls)continue;o.push(l)}else if(d.role==="toolResult"){let l=[],r=g;for(;r<h.length&&h[r].role==="toolResult";r++){let p=h[r],_=p.content.filter(Me).map(v=>v.text).join(`
9
+ `),A=p.content.some(v=>v.type==="image"),b=_.trim().length>0?_:A?"(see attached image)":"(no tool output)",w={role:"tool",content:q(b),tool_call_id:p.toolCallId};if(t.requiresToolResultName&&p.toolName&&(w.name=p.toolName),o.push(w),A&&e.input.includes("image"))for(let v of p.content)De(v)&&l.push({type:"image_url",image_url:{url:`data:${v.mimeType};base64,${v.data}`}})}g=r-1,l.length>0?(t.requiresAssistantAfterToolResult&&o.push({role:"assistant",content:"I have processed the tool results."}),o.push({role:"user",content:[{type:"text",text:"Attached image(s) from tool result:"},...l]}),x="user"):x="toolResult";continue}x=d.role}return o}function Fe(e,n){return e.map(t=>{let s=de(t,n.supportsOpenAIGrammarTools);if(s)return{type:"custom",custom:{name:t.name,description:t.description,format:{type:"grammar",grammar:{syntax:s.format,definition:s.definition}}}};let a=ge(t,n.supportsStrictMode!==!1);return{type:"function",function:{name:t.name,description:t.description,parameters:fe(t,a),...n.supportsStrictMode!==!1&&{strict:a??!1}}}})}function Ee(e,n){let t=e.prompt_tokens||0,s=e.prompt_tokens_details?.cached_tokens??e.prompt_cache_hit_tokens??e.cached_tokens??0,a=e.prompt_tokens_details?.cache_write_tokens||0,o=Math.max(0,t-s-a),m=e.completion_tokens||0,h={input:o,output:m,cacheRead:s,cacheWrite:a,reasoning:e.completion_tokens_details?.reasoning_tokens||e.reasoning_tokens||0,totalTokens:o+m+s+a,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return X(n,h),ie(n)&&ae(h,e),h}function at(e){if(e===null)return{stopReason:"stop"};switch(e){case"stop":case"end":return{stopReason:"stop"};case"length":return{stopReason:"length"};case"function_call":case"tool_calls":return{stopReason:"toolUse"};case"content_filter":return{stopReason:"error",errorMessage:"Provider finish_reason: content_filter"};case"network_error":return{stopReason:"error",errorMessage:"Provider finish_reason: network_error"};default:return{stopReason:"error",errorMessage:`Provider finish_reason: ${e}`}}}function ut(e){let n=e.provider,t=e.baseUrl,s=n==="zai"||n==="zai-coding-cn"||t.includes("api.z.ai")||t.includes("open.bigmodel.cn"),a=n==="together"||t.includes("api.together.ai")||t.includes("api.together.xyz"),o=n==="moonshotai"||n==="moonshotai-cn"||t.includes("api.moonshot."),m=n==="openrouter"||t.includes("openrouter.ai"),h=n==="cloudflare-workers-ai"||t.includes("api.cloudflare.com"),y=n==="cloudflare-ai-gateway"||t.includes("gateway.ai.cloudflare.com"),R=n==="nvidia"||t.includes("integrate.api.nvidia.com"),x=n==="ant-ling"||t.includes("api.ant-ling.com"),u=n==="cerebras"||t.includes("cerebras.ai"),g=n==="deepseek"||t.toLowerCase().includes("deepseek.com"),d=R||u||n==="xai"||t.includes("api.x.ai")||a||t.includes("chutes.ai")||g||s||o||n==="opencode"||t.includes("opencode.ai")||h||y||x,l=t.includes("chutes.ai")||g||o||y||a||R||x||s,r=n==="xai"||t.includes("api.x.ai"),p=n==="openai"||t.includes("api.openai.com"),_=n==="openrouter"&&e.id.startsWith("anthropic/")?"anthropic":void 0;return{supportsStore:!d,supportsDeveloperRole:p,supportsReasoningEffort:!r&&!s&&!o&&!a&&!y&&!R&&!x,supportsUsageInStreaming:!0,supportsFinishReason:!0,maxTokensField:l?"max_tokens":"max_completion_tokens",requiresToolResultName:!1,requiresAssistantAfterToolResult:!1,requiresNonNullAssistantContent:!1,requiresToolsWithToolHistory:!1,requiresThinkingAsText:!1,requiresReasoningContentOnAssistantMessages:g,thinkingFormat:g?"deepseek":s?"zai":a?"together":x?"ant-ling":m?"openrouter":"openai",openRouterRouting:{},vercelGatewayRouting:{},chatTemplateKwargs:{},chatTemplateArgs:{},zaiToolStream:!1,supportsThinkingTokenBudget:!1,thinkingTokenBudgetField:void 0,supportsStrictMode:!1,supportsOpenAIGrammarTools:!1,supportsMidConvoSystemMessages:!1,supportsMidConvoToolAdditions:!1,cacheControlFormat:_,sendSessionAffinityHeaders:m,sessionAffinityFormat:m?"openrouter":"openai",supportsLongCacheRetention:!(a||h||y||R||x)}}function D(e){let n=ut(e);return e.compat?{supportsStore:e.compat.supportsStore??n.supportsStore,supportsDeveloperRole:e.compat.supportsDeveloperRole??n.supportsDeveloperRole,supportsReasoningEffort:e.compat.supportsReasoningEffort??n.supportsReasoningEffort,supportsUsageInStreaming:e.compat.supportsUsageInStreaming??n.supportsUsageInStreaming,supportsFinishReason:e.compat.supportsFinishReason??n.supportsFinishReason,maxTokensField:e.compat.maxTokensField??n.maxTokensField,requiresToolResultName:e.compat.requiresToolResultName??n.requiresToolResultName,requiresAssistantAfterToolResult:e.compat.requiresAssistantAfterToolResult??n.requiresAssistantAfterToolResult,requiresNonNullAssistantContent:e.compat.requiresNonNullAssistantContent??n.requiresNonNullAssistantContent,requiresToolsWithToolHistory:e.compat.requiresToolsWithToolHistory??n.requiresToolsWithToolHistory,requiresThinkingAsText:e.compat.requiresThinkingAsText??n.requiresThinkingAsText,requiresReasoningContentOnAssistantMessages:e.compat.requiresReasoningContentOnAssistantMessages??n.requiresReasoningContentOnAssistantMessages,thinkingFormat:e.compat.thinkingFormat??n.thinkingFormat,openRouterRouting:e.compat.openRouterRouting??{},vercelGatewayRouting:e.compat.vercelGatewayRouting??n.vercelGatewayRouting,chatTemplateKwargs:e.compat.chatTemplateKwargs??n.chatTemplateKwargs,chatTemplateArgs:e.compat.chatTemplateArgs??n.chatTemplateArgs,zaiToolStream:e.compat.zaiToolStream??n.zaiToolStream,supportsThinkingTokenBudget:e.compat.supportsThinkingTokenBudget??n.supportsThinkingTokenBudget,thinkingTokenBudgetField:e.compat.thinkingTokenBudgetField??n.thinkingTokenBudgetField,supportsStrictMode:e.compat.supportsStrictMode??n.supportsStrictMode,supportsOpenAIGrammarTools:e.compat.supportsOpenAIGrammarTools??n.supportsOpenAIGrammarTools,supportsMidConvoSystemMessages:e.compat.supportsMidConvoSystemMessages??n.supportsMidConvoSystemMessages,supportsMidConvoToolAdditions:e.compat.supportsMidConvoToolAdditions??n.supportsMidConvoToolAdditions,cacheControlFormat:e.compat.cacheControlFormat??n.cacheControlFormat,sendSessionAffinityHeaders:e.compat.sendSessionAffinityHeaders??n.sendSessionAffinityHeaders,sessionAffinityFormat:e.compat.sessionAffinityFormat??n.sessionAffinityFormat,supportsLongCacheRetention:e.compat.supportsLongCacheRetention??n.supportsLongCacheRetention,promptCacheKeyMode:e.compat.promptCacheKeyMode,vllmPriority:e.compat.vllmPriority}:n}export{it as convertMessages,Je as stream,Et as streamSimple};
@@ -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{a as c,b as s,c as u,d as $}from"./chunk-KGJZAYQD.js";import{a as p,b as f}from"./chunk-FF7UELTU.js";import"./chunk-23PRJECN.js";import"./chunk-PZMGBKUR.js";import"./chunk-D6VMBA4C.js";import"./chunk-K4NTZEDJ.js";import"./chunk-6AKUD3CF.js";import"./chunk-OSEIQ7SS.js";import"./chunk-CXT5IR5T.js";import"./chunk-WHC7AYZD.js";var o="OpenAI Decisions",y=128;function w(r){let t=[r.criteria.true?`True means: ${r.criteria.true}`:"",r.criteria.false?`False means: ${r.criteria.false}`:""].filter(Boolean);return t.length>0?`${r.instructions}
4
+ import{a as c,b as s,c as u,d as $}from"./chunk-J7OBATRN.js";import"./chunk-23PRJECN.js";import"./chunk-DE5EGVKG.js";import"./chunk-D6VMBA4C.js";import{a as p,c as f}from"./chunk-ZD4O6NPV.js";import"./chunk-K4NTZEDJ.js";import"./chunk-3XLHL5YT.js";import"./chunk-X2TKJ7KR.js";import"./chunk-NW4GW47L.js";import"./chunk-CXT5IR5T.js";import"./chunk-WHC7AYZD.js";var o="OpenAI Decisions",y=128;function w(r){let t=[r.criteria.true?`True means: ${r.criteria.true}`:"",r.criteria.false?`False means: ${r.criteria.false}`:""].filter(Boolean);return t.length>0?`${r.instructions}
5
5
 
6
6
  ${t.join(`
7
7
  `)}`:r.instructions}function h(r,t){return t.type==="choice"?{type:"choice",name:r,instructions:t.instructions,choices:Object.entries(t.criteria).map(([e,i])=>i?{value:e,description:i}:{value:e})}:t.type==="score"?{type:"score",name:r,instructions:t.instructions,levels:t.criteria.map(e=>({label:e}))}:{type:"predicate",name:r,instructions:w(t)}}function d(r){let t=JSON.stringify(r.state),e=r.images??[];if(e.length===0)return t;if(e.length>y)throw new Error(`${o} accepts at most ${y} images, got ${e.length}`);return[{role:"user",content:[{type:"input_text",text:t},...e.map(i=>({type:"input_image",image_url:`data:${i.mimeType};base64,${i.data}`}))]}]}function g(r,t){if(!Array.isArray(r))throw new Error(`${o} returned invalid probabilities for ${t}`);return Object.fromEntries(r.map(e=>{if(!c(e)||typeof e.value!="string")throw new Error(`${o} returned invalid probabilities for ${t}`);return[e.value,s(o,e.probability,`probability for ${t}.${e.value}`)]}))}function m(r,t,e){if(e.type==="refusal")throw new Error(`${o} refused to answer ${r}`);if(t.type==="choice"){if(e.type!=="choice"||typeof e.choice!="string")throw new Error(`${o} did not return a choice answer for ${r}`);return{type:"choice",choice:e.choice,probabilities:g(e.probabilities,r),confidence:s(o,e.confidence,`confidence for ${r}`)}}if(t.type==="score"){if(e.type!=="score")throw new Error(`${o} did not return a score answer for ${r}`);return{type:"score",score:s(o,e.score,`score for ${r}`),confidence:s(o,e.confidence,`confidence for ${r}`)}}if(e.type!=="predicate")throw new Error(`${o} did not return a predicate answer for ${r}`);return{type:"bool",probability:s(o,e.probability,`probability for ${r}`)}}function E(r,t){if(!Array.isArray(r))throw new Error(`${o} returned an unexpected response`);let e=new Map;for(let i of r)c(i)&&typeof i.name=="string"&&e.set(i.name,i);return Object.fromEntries(Object.entries(t.questions).map(([i,n])=>{let a=e.get(i);if(!a)throw new Error(`${o} did not return an answer for ${i}`);return[i,m(i,n,a)]}))}var A=[504];function v(r){return r.status===504?`${o} error (504): the request timed out at the gateway. Very large inputs (above roughly 600K tokens) currently exceed its time limit.`:f(p(r),`${o} error`)}var j=async(r,t,e)=>{let i={api:r.api,provider:r.provider,model:r.id,answers:{},stopReason:"stop",timestamp:Date.now()};try{if(r.api!=="openai-decisions")throw new Error(`Unsupported classifier API: ${r.api}`);let n=await u(o,new URL("decisions",`${r.baseUrl.replace(/\/+$/u,"")}/`),r,{model:r.id,input:d(t),questions:Object.entries(t.questions).map(([b,l])=>h(b,l))},e,A);if(!c(n))throw new Error(`${o} returned an unexpected response`);let a=$(n.usage,r);return a&&(i.usage=a),i.answers=E(n.answers,t),i}catch(n){return i.answers={},i.stopReason=e?.signal?.aborted?"aborted":"error",i.errorMessage=v(n),i}};export{j as classify};
@@ -0,0 +1,6 @@
1
+ import { createRequire as __cortexCreateRequire } from 'node:module';
2
+ const require = __cortexCreateRequire(import.meta.url);
3
+ const __cortexPackageRoot = new URL("../../", import.meta.url);
4
+ import{a as U,b as K,c as N,d as D}from"./chunk-FE7HH5JS.js";import{a as G}from"./chunk-XIECJESP.js";import{a as L}from"./chunk-4SWD4JMP.js";import{a as w,b as x}from"./chunk-BGYR4ID3.js";import"./chunk-V3AQJSWR.js";import"./chunk-BWDJS6A4.js";import{a as S}from"./chunk-6R73ICDB.js";import{a as O}from"./chunk-23PRJECN.js";import{h as I,j as k,k as b}from"./chunk-7TYSMLUV.js";import{C as R,I as E,v as C,z as M}from"./chunk-DE5EGVKG.js";import"./chunk-D6VMBA4C.js";import"./chunk-USBJFDJ6.js";import{a as P,c as _}from"./chunk-ZD4O6NPV.js";import{a as A}from"./chunk-K4NTZEDJ.js";import{h as y}from"./chunk-3XLHL5YT.js";import"./chunk-X2TKJ7KR.js";import"./chunk-NW4GW47L.js";import{b as v}from"./chunk-CXT5IR5T.js";import"./chunk-WHC7AYZD.js";var V=new Set(["openai","openai-codex","opencode"]),B=16,Q="https://chatgpt.com/settings/usage",Y="You've reached your ChatGPT workspace's usage limit. Ask your workspace admin to increase it at admin.openai.com \u2192 Workspace \u2192 Usage limits.",J="medium";function H(e,t){return e.provider==="openai"&&e.baseUrl==="https://api.openai.com/v1"&&t!==void 0&&!t.startsWith("sk-")}function F(e,t){if(!e)return!1;let r=t.toLowerCase();for(let[s,i]of Object.entries(e))if(s.toLowerCase()===r&&i!==null&&i.trim().length>0)return!0;return!1}function q(e,t,r){if(t)return t;if(F(r,"authorization")||F(r,"cf-aig-authorization"))return"unused";throw new Error(`No API key for provider: ${e}`)}function X(e){return e.provider==="openrouter"||e.baseUrl.includes("openrouter.ai")?"openrouter":"openai"}function W(e,t){return e||(S("PI_CACHE_RETENTION",t)==="long"?"long":"short")}function h(e){return{supportsDeveloperRole:e.compat?.supportsDeveloperRole??!0,supportsMidConvoSystemMessages:e.compat?.supportsMidConvoSystemMessages??!1,sessionAffinityFormat:e.compat?.sessionAffinityFormat??X(e),promptCacheKeyMode:e.compat?.promptCacheKeyMode??"auto",supportsLongCacheRetention:e.compat?.supportsLongCacheRetention??!0,supportsStrictMode:e.compat?.supportsStrictMode??!1,supportsOpenAIGrammarTools:e.compat?.supportsOpenAIGrammarTools??!1,supportsAdditionalTools:e.compat?.supportsAdditionalTools??!1,supportsToolSearch:e.compat?.supportsToolSearch??!1,supportsExplicitPromptCacheMode:e.compat?.supportsExplicitPromptCacheMode??!1,supportsMaxOutputTokens:e.compat?.supportsMaxOutputTokens??!0,supportsMidConvoEffort:e.compat?.supportsMidConvoEffort??!1}}function Z(e,t,r){if(!(!r.supportsMidConvoEffort||!t?.reasoningEffort||H(e,t.apiKey)))return e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort}function ee(e,t){return t==="long"&&e.supportsLongCacheRetention&&!e.supportsExplicitPromptCacheMode?"24h":void 0}function re(e,t){if(e.supportsExplicitPromptCacheMode){if(t==="none")return{mode:"explicit"};if(t==="long"&&e.supportsLongCacheRetention)return{ttl:"30m"}}}var te=(e,t,r)=>{let s=new v,i=C(t,h(e).supportsMidConvoSystemMessages);return(async()=>{let u=h(e),p=Z(e,r,u),o={role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,...p===void 0?{}:{providerThinkingLevel:p},usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{let n=q(e.provider,r?.apiKey,r?.headers),f=W(r?.cacheRetention,r?.env)==="none"?void 0:r?.sessionId,a=I(M(i.messages),u.supportsOpenAIGrammarTools),m=se(e,i,n,r?.headers,r?.identity,r?.fetch,f),d=oe(e,i,r,u,a,p),l=await r?.onPayload?.(d,e);l!==void 0&&(d=l);let g={...r?.signal?{signal:r.signal}:{},...r?.timeoutMs!==void 0?{timeout:r.timeoutMs}:{},maxRetries:0},{data:$,response:T}=await O(()=>m.responses.create(d,g).withResponse(),{maxRetries:r?.maxRetries,maxRetryDelayMs:r?.maxRetryDelayMs,signal:r?.signal});if(await r?.onResponse?.({status:T.status,headers:A(T.headers)},e),s.push({type:"start",partial:o}),await D($,o,s,e,{onProviderStreamEvent:r?.onProviderStreamEvent,serviceTier:r?.serviceTier,grammarToolInputProperties:a,applyServiceTierPricing:(j,z)=>ae(j,z,e)}),r?.signal?.aborted)throw new Error("Request was aborted");if(o.stopReason==="pending")throw new Error("OpenAI Responses stream ended without a stop reason");if(o.stopReason==="aborted"||o.stopReason==="error")throw new Error(o.errorMessage||"An unknown error occurred");s.push({type:"done",reason:o.stopReason,message:o}),s.end()}catch(n){o.stopReason=r?.signal?.aborted?"aborted":"error";let c=_(P(n),`${e.provider==="openai"?"OpenAI":e.provider} API error`);c.includes("subscription_sharing_usage_limit_exceeded")?o.errorMessage=`${c}
5
+ Check your ChatGPT usage: ${Q}`:c.includes("subscription_sharing_workplace_individual_usage_limit_exceeded")?o.errorMessage=`${c}
6
+ ${Y}`:o.errorMessage=c,s.push({type:"error",reason:o.stopReason,error:o}),s.end()}})(),s},Me=(e,t,r)=>{q(e.provider,r?.apiKey,r?.headers);let s={...b(e,t,r,r?.apiKey),toolChoice:r?.toolChoice},i=r?.reasoning?E(e,r.reasoning):void 0;return te(e,t,{...s,reasoningEffort:i==="off"?void 0:i})};function se(e,t,r,s,i,u,p){let o=h(e),n={...y(e,i),...e.headers};if(e.provider==="github-copilot"){let c=w(t.messages),f=x({messages:t.messages,hasImages:c});Object.assign(n,f)}return p&&(o.sessionAffinityFormat==="openrouter"?n["x-session-id"]=p:(o.sessionAffinityFormat==="openai"&&(n["session-id"]=p),n["x-client-request-id"]=p)),s&&Object.assign(n,s),new L({apiKey:r,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:u,defaultHeaders:n})}function oe(e,t,r,s,i,u){let p=R(t.messages,U(s)),o=K(e,t,V,{grammarToolInputProperties:i,supportsMidConvoSystemMessages:s.supportsMidConvoSystemMessages,supportsAdditionalTools:s.supportsAdditionalTools,supportsToolSearch:s.supportsToolSearch,toolOptions:{supportsStrictMode:s.supportsStrictMode,supportsOpenAIGrammarTools:s.supportsOpenAIGrammarTools},configurationUpdateEffort:u}),n=W(r?.cacheRetention,r?.env),c=n!=="none"&&s.promptCacheKeyMode!=="disabled",f=H(e,r?.apiKey),a={model:e.id,input:o,stream:!0,prompt_cache_key:c?G(r?.sessionId):void 0,prompt_cache_retention:f?void 0:ee(s,n),prompt_cache_options:f?void 0:re(s,n),store:!1};r?.maxTokens&&s.supportsMaxOutputTokens&&!f&&(a.max_output_tokens=Math.max(r.maxTokens,B)),r?.temperature!==void 0&&!f&&(a.temperature=r?.temperature),r?.serviceTier!==void 0&&(a.service_tier=r.serviceTier),p.requestTools.length>0&&(a.tools=N(p.requestTools,{supportsStrictMode:s.supportsStrictMode,supportsOpenAIGrammarTools:s.supportsOpenAIGrammarTools})),r?.toolChoice!==void 0&&(a.tool_choice=r.toolChoice);let m=r?.reasoningEffort??(r?.reasoningSummary?"medium":void 0);if(e.reasoning){if(m){let l=r?.reasoningEffort?e.thinkingLevelMap?.[r.reasoningEffort]??r.reasoningEffort:m,g=u===void 0?l:J;a.reasoning={effort:g,summary:r?.reasoningSummary||"auto"},a.include=["reasoning.encrypted_content"]}else e.provider!=="github-copilot"&&e.thinkingLevelMap?.off!==null&&(a.reasoning={effort:e.thinkingLevelMap?.off??"none"});e.provider==="xai"&&(a.include=["reasoning.encrypted_content"])}let d=k(e,m??"off",r?.samplingParams);return d&&Object.assign(a,d),a}function ne(e,t){switch(t){case"flex":return .5;case"priority":case"fast":return e.id==="gpt-5.5"?2.5:2;default:return 1}}function ae(e,t,r){let s=ne(r,t);s!==1&&(e.cost.input*=s,e.cost.output*=s,e.cost.cacheRead*=s,e.cost.cacheWrite*=s,e.cost.total=e.cost.input+e.cost.output+e.cost.cacheRead+e.cost.cacheWrite)}export{te as stream,Me as streamSimple};
@@ -0,0 +1,4 @@
1
+ import { createRequire as __cortexCreateRequire } from 'node:module';
2
+ const require = __cortexCreateRequire(import.meta.url);
3
+ const __cortexPackageRoot = new URL("../../", import.meta.url);
4
+ import{a as w}from"./chunk-4SWD4JMP.js";import{a as k}from"./chunk-23PRJECN.js";import{a as v}from"./chunk-USBJFDJ6.js";import{a as y,c as R}from"./chunk-ZD4O6NPV.js";import{a as x,b as _}from"./chunk-K4NTZEDJ.js";import{h as l}from"./chunk-3XLHL5YT.js";import"./chunk-X2TKJ7KR.js";import"./chunk-WHC7AYZD.js";var H=async(e,s,t)=>{let r={api:e.api,provider:e.provider,model:e.id,output:[],stopReason:"stop",timestamp:Date.now()};try{let a=t?.apiKey;if(!a)throw new Error(`No API key for provider: ${e.provider}`);let i=P(e,a,t?.headers,t?.fetch,t?.identity),n=b(e,s),c=await t?.onPayload?.(n,e);c!==void 0&&(n=c);let o={...t?.signal?{signal:t.signal}:{},...t?.timeoutMs!==void 0?{timeout:t.timeoutMs}:{},maxRetries:0},{data:T,response:g}=await k(()=>i.chat.completions.create(n,o).withResponse(),{maxRetries:t?.maxRetries,maxRetryDelayMs:t?.maxRetryDelayMs,signal:t?.signal});await t?.onResponse?.({status:g.status,headers:x(g.headers)},e);let u=T;r.responseId=u.id,u.usage&&(r.usage=M(u.usage,e));let p=u.choices[0];if(p){let m=p.message.content;typeof m=="string"&&m.length>0&&r.output.push({type:"text",text:m});for(let d of p.message.images??[]){let f=typeof d.image_url=="string"?d.image_url:d.image_url?.url;if(!f?.startsWith("data:"))continue;let h=f.match(/^data:([^;]+);base64,(.+)$/);h&&r.output.push({type:"image",mimeType:h[1],data:h[2]})}}return r}catch(a){return r.stopReason=t?.signal?.aborted?"aborted":"error",r.errorMessage=R(y(a)),r}};function P(e,s,t,r,a){return new w({apiKey:s,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:r,defaultHeaders:_(l(e,a),e.headers,t)})}function b(e,s){let t=s.input.map(r=>r.type==="text"?{type:"text",text:v(r.text)}:{type:"image_url",image_url:{url:`data:${r.mimeType};base64,${r.data}`}});return{model:e.id,messages:[{role:"user",content:t}],stream:!1,modalities:e.output.includes("text")?["image","text"]:["image"]}}function M(e,s){let t=e.prompt_tokens||0,r=e.prompt_tokens_details?.cached_tokens||0,a=e.prompt_tokens_details?.cache_write_tokens||0,i=a>0?Math.max(0,r-a):r,n=Math.max(0,t-i-a),c=e.completion_tokens||0,o={input:n,output:c,cacheRead:i,cacheWrite:a,totalTokens:n+c+i+a,cost:{input:s.cost.input/1e6*n,output:s.cost.output/1e6*c,cacheRead:s.cost.cacheRead/1e6*i,cacheWrite:s.cost.cacheWrite/1e6*a,total:0,totalFromProvider:!1}};return o.cost.total=o.cost.input+o.cost.output+o.cost.cacheRead+o.cost.cacheWrite,o}export{H as generateImages};
@@ -0,0 +1,10 @@
1
+ import { createRequire as __cortexCreateRequire } from 'node:module';
2
+ const require = __cortexCreateRequire(import.meta.url);
3
+ const __cortexPackageRoot = new URL("../../", import.meta.url);
4
+ import{f as w}from"./chunk-BWDJS6A4.js";import{a as y}from"./chunk-6R73ICDB.js";import{c as h,d as p}from"./chunk-D6VMBA4C.js";import{a as b,b as k}from"./chunk-K4NTZEDJ.js";import{h as x}from"./chunk-3XLHL5YT.js";import{d as m}from"./chunk-X2TKJ7KR.js";import{b as f}from"./chunk-CXT5IR5T.js";import"./chunk-WHC7AYZD.js";var g=class extends Error{code;diagnosticDetails;constructor(t,n,e){super(t),this.name="PiMessagesResponseError",this.code=n,this.diagnosticDetails=e}};function T(r){try{let t=JSON.parse(r),n=t?.error;return t&&typeof n=="object"&&n!==null&&!Array.isArray(n)?t:void 0}catch{return}}function S(r){return r.length>8192?`${m(r,0,8192)}\u2026`:r}function _(r,t,n){let e=typeof n?.error?.message=="string"?n.error.message:void 0,s=typeof n?.error?.code=="string"?n.error.code:void 0,o=e??t,a=s?` (${s})`:"";return`${r.status} ${r.statusText}: ${o}${a}`}function R(r,t,n,e){let s=T(e),o=typeof s?.error?.code=="string"?s.error.code:void 0;return new g(_(n,e,s),o,{version:1,provider:r.provider,model:r.id,url:t.toString(),status:n.status,statusText:n.statusText,...s?.error===void 0?{}:{error:s.error},...s?{}:{body:S(e)},timestampMs:Date.now()})}function M(){return{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}function I(r,t){t&&p(r,{type:"pi_messages_rewrite",timestamp:Date.now(),details:{...t}})}function O(r){let t={role:"assistant",content:[],api:r.api,provider:r.provider,model:r.id,usage:M(),stopReason:"pending",timestamp:Date.now()},n=new Map;return e=>{if("contentIndex"in e){let s=e.contentIndex,o=e.type.endsWith("_start")?t.content.length:t.content.length-1;if(typeof s!="number"||!Number.isInteger(s)||s<0||s>o)throw new Error(`Invalid contentIndex ${JSON.stringify(s)} in pi-messages ${e.type} event`)}switch(e.type){case"done":return Object.assign(t,{stopReason:e.reason,usage:e.usage,responseId:e.responseId}),e.responseModel!==void 0&&(t.responseModel=e.responseModel),e.providerThinkingLevel!==void 0&&(t.providerThinkingLevel=e.providerThinkingLevel),I(t,e.rewrite),{type:"done",reason:e.reason,message:t};case"error":return Object.assign(t,{stopReason:e.reason,usage:e.usage,errorMessage:e.errorMessage,responseId:e.responseId}),e.responseModel!==void 0&&(t.responseModel=e.responseModel),e.providerThinkingLevel!==void 0&&(t.providerThinkingLevel=e.providerThinkingLevel),I(t,e.rewrite),{type:"error",reason:e.reason,error:t};case"start":break;case"text_start":t.content[e.contentIndex]={type:"text",text:""};break;case"text_delta":t.content[e.contentIndex].text+=e.delta;break;case"text_end":Object.assign(t.content[e.contentIndex],{text:e.content,textSignature:e.contentSignature});break;case"thinking_start":t.content[e.contentIndex]={type:"thinking",thinking:""};break;case"thinking_delta":t.content[e.contentIndex].thinking+=e.delta;break;case"thinking_end":Object.assign(t.content[e.contentIndex],{thinking:e.content,thinkingSignature:e.contentSignature,redacted:e.redacted});break;case"toolcall_start":t.content[e.contentIndex]={type:"toolCall",id:e.id,name:e.toolName,arguments:{}},n.set(e.contentIndex,new w);break;case"toolcall_delta":{let s=n.get(e.contentIndex);s!==void 0&&(t.content[e.contentIndex].arguments=s.append(e.delta));break}case"toolcall_end":return Object.assign(t.content[e.contentIndex],e.toolCall),n.delete(e.contentIndex),{type:"toolcall_end",contentIndex:e.contentIndex,toolCall:t.content[e.contentIndex],partial:t}}return{...e,partial:t}}}async function*$(r){let t=new TextDecoder,n=r.getReader(),e="";try{for(;;){let{done:s,value:o}=await n.read();e+=s?t.decode():t.decode(o,{stream:!0}),e=e.replace(/\r\n/g,`
5
+ `);let a=e.indexOf(`
6
+
7
+ `);for(;a!==-1;){let c=E(e.slice(0,a));c&&(yield c),e=e.slice(a+2),a=e.indexOf(`
8
+
9
+ `)}if(s)break}if(e.trim()){let s=E(e);s&&(yield s)}}finally{n.releaseLock()}}function E(r){let t=r.split(`
10
+ `).find(n=>n.startsWith("data:"))?.slice(5).trim();return t&&t!=="[DONE]"?JSON.parse(t):void 0}function D(r,t,n){let e=n?"aborted":"error",s={role:"assistant",content:[],api:r.api,provider:r.provider,model:r.id,usage:M(),stopReason:e,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()};return!n&&t instanceof g&&p(s,h("pi_messages_response_failure",t,t.diagnosticDetails)),{type:"error",reason:e,error:s}}function P(r,t){return r||(y("PI_CACHE_RETENTION",t)==="long"?"long":void 0)}var C=(r,t,n)=>{let e=new f,s=O(r);return(async()=>{try{let o=n?.apiKey;if(!o)throw new Error(`No API key provided for provider "${r.provider}"`);let a=new URL(`${r.baseUrl.replace(/\/+$/u,"")}/messages`);n?.debug&&a.searchParams.set("debug","1");let c={model:r.id,context:t,options:{temperature:n?.temperature,maxTokens:n?.maxTokens,reasoning:n?.reasoning,cacheRetention:P(n?.cacheRetention,n?.env),sessionId:n?.sessionId,toolChoice:n?.toolChoice}},l=await n?.onPayload?.(c,r);l!==void 0&&(c=l);let i=await(n?.fetch??globalThis.fetch)(a,{method:"POST",headers:k(x(r,n?.identity),{authorization:`Bearer ${o}`,accept:"text/event-stream","content-type":"application/json"},n?.headers),body:JSON.stringify(c),signal:n?.signal});if(await n?.onResponse?.({status:i.status,headers:b(i.headers)},r),!i.ok){let d=await i.text();throw R(r,a,i,d)}if(!i.body)throw new Error(`${r.provider} response has no body`);for await(let d of $(i.body)){await n?.onProviderStreamEvent?.(d,r);let u=s(d);if(e.push(u),u.type==="done"||u.type==="error")return}throw new Error(`${r.provider} stream ended without a terminal event`)}catch(o){e.push(D(r,o,n?.signal?.aborted??!1))}})(),e},U=(r,t,n)=>{let e=n;return C(r,t,{...n,reasoning:n?.reasoning,toolChoice:n?.toolChoice,debug:e?.debug})};export{g as PiMessagesResponseError,C as stream,U as streamSimple};
@@ -0,0 +1,4 @@
1
+ import { createRequire as __cortexCreateRequire } from 'node:module';
2
+ const require = __cortexCreateRequire(import.meta.url);
3
+ const __cortexPackageRoot = new URL("../../", import.meta.url);
4
+ import{b as v}from"./chunk-DYLBVUAU.js";import{a as d}from"./chunk-RWPO3NZ3.js";import{a as _}from"./chunk-ILEML5IP.js";import{a as w}from"./chunk-XBJOYU5Y.js";import{a as f}from"./chunk-XAXWLYH5.js";import"./chunk-IRWZ7UPF.js";import"./chunk-X2TKJ7KR.js";import"./chunk-WHC7AYZD.js";var y="127.0.0.1",E=1456,O="/oauth/callback",u=`http://${y}:${E}${O}`,S=6e4,g="browser",m="device-code",a="pi-gateway",R="gateway offline_access",U="urn:ietf:params:oauth:grant-type:device_code";async function L(i,r){let e=await fetch(new URL("/v1/oauth",i),{headers:{accept:"application/json"},signal:r});if(!e.ok)throw new Error(`Could not load Radius OAuth config from ${i}: ${e.status} ${await e.text()}`);let t=await e.json(),o=d(t.authorizationEndpoint);if(!o)throw new Error(`Invalid Radius OAuth config from ${i}`);return{authorizationEndpoint:o}}var c=class extends Error{status;oauthError;constructor(r,e,t,o){let n=e?t?`${e}: ${t}`:e:t||String(r);super(`${o}: ${n}`),this.status=r,this.oauthError=e}};async function A(i,r){let e=await i.text().catch(()=>""),t,o;if(e)try{let n=JSON.parse(e);t=typeof n.error=="string"?n.error:void 0,o=typeof n.error_description=="string"?n.error_description:void 0}catch{o=e}return new c(i.status,t,o,r)}async function h(i,r,e){let t;try{t=await fetch(new URL("/v1/oauth/token",i),{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:r,signal:e})}catch(n){throw e.aborted?new Error("Login cancelled"):n}if(!t.ok)throw await A(t,"Radius OAuth token request failed");let o=await t.json();return{type:"oauth",access:o.access_token,refresh:o.refresh_token,expires:Date.now()+o.expires_in*1e3-S,scope:o.scope}}async function C(i,r,e){let{verifier:t,challenge:o}=await f(),n=crypto.randomUUID(),l=new URL(r);l.search=new URLSearchParams({response_type:"code",client_id:a,redirect_uri:u,scope:R,code_challenge:o,code_challenge_method:"S256",handoff:"url",state:n}).toString();let p=await w({providerName:"Radius",host:y,port:E,path:O,state:n,complete:s=>h(i,new URLSearchParams({grant_type:"authorization_code",client_id:a,redirect_uri:u,code:s,code_verifier:t}),e.signal),signal:e.signal});e.notify({type:"progress",message:`Listening for OAuth callback on ${u}`}),e.notify({type:"auth_url",url:l.toString(),instructions:"Continue in your browser."});try{let s=await p.wait();if(!s)throw new Error("OAuth callback did not complete.");return s}finally{p.close()}}async function x(i,r){let e;try{e=await fetch(new URL("/v1/oauth/device",i),{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:a,scope:R}),signal:r})}catch(n){throw r.aborted?new Error("Login cancelled"):n}if(!e.ok)throw await A(e,"Radius OAuth device authorization failed");let t=await e.json();if(!t.device_code||!t.user_code||!t.verification_uri||!t.expires_in)throw new Error("Radius OAuth device authorization response is missing required fields");let o=d(t.verification_uri);if(!o)throw new Error("Untrusted verification_uri in Radius OAuth device authorization response");return{device_code:t.device_code,user_code:t.user_code,verification_uri:o,expires_in:t.expires_in,interval:t.interval}}async function k(i,r){let e=await x(i,r.signal);return r.notify({type:"device_code",userCode:e.user_code,verificationUri:e.verification_uri,intervalSeconds:e.interval,expiresInSeconds:e.expires_in}),_({intervalSeconds:e.interval,expiresInSeconds:e.expires_in,signal:r.signal,poll:async()=>{try{return{status:"complete",value:await h(i,new URLSearchParams({grant_type:U,client_id:a,device_code:e.device_code}),r.signal)}}catch(t){if(!(t instanceof c))throw t;switch(t.oauthError){case"authorization_pending":return{status:"pending"};case"slow_down":return{status:"slow_down"};case"expired_token":return{status:"failed",message:"Device authorization expired."};case"access_denied":return{status:"failed",message:"Device authorization was denied."};default:throw t}}}})}function I(i){let r=v(i.gateway);return{name:i.name,async login(e){let t=await e.prompt({type:"select",message:`Sign in to ${i.name}:`,options:[{id:g,label:"Sign in with browser (recommended)"},{id:m,label:"Sign in with device code (when signing in from another device)"}]});if(t===m)return k(r,e);if(t===g){let o=await L(r,e.signal);return C(r,o.authorizationEndpoint,e)}throw new Error(`Unknown ${i.name} sign-in method: ${t}`)},async refresh(e,t){return await h(r,new URLSearchParams({grant_type:"refresh_token",client_id:a,refresh_token:e.refresh}),t)},async toAuth(e){return{apiKey:e.access}}}}export{I as createRadiusOAuth};
@@ -0,0 +1,14 @@
1
+ import { createRequire as __cortexCreateRequire } from 'node:module';
2
+ const require = __cortexCreateRequire(import.meta.url);
3
+ const __cortexPackageRoot = new URL("../../", import.meta.url);
4
+ import{a as S}from"./chunk-5FHETFZM.js";import{a as F,b as L,c as N,d as P,e as K,f as G}from"./chunk-TJ4GQRT6.js";import{a as j,c as R}from"./chunk-ZNAMETPQ.js";import"./chunk-4KQHDDC5.js";import"./chunk-QXFWIL4C.js";import"./chunk-Y6ZEVVL5.js";import"./chunk-OKRK6JPY.js";import"./chunk-52VCLZS5.js";import"./chunk-BVEDNESB.js";import"./chunk-KRXTI4JO.js";import{K as o}from"./chunk-W34AK4SK.js";import{e as v,j as I,v as O}from"./chunk-T54CZKNJ.js";import"./chunk-WHC7AYZD.js";import*as T from"fs";import*as A from"path";import*as Q from"crypto";import{pathToFileURL as re}from"url";var M=class{memoryCache=new Map;cacheDir;sessionId;constructor(e={}){this.cacheDir=e.cacheDir??F(v),this.sessionId=e.sessionId??process.env.CORTEX_SESSION_ID,N(this.cacheDir)}buildBlocks(e,u,g){if(!u||u.length===0)return[];let d=a=>L(a.deviceId?.trim()||e,a.path);return P(this.cacheDir,this.sessionId,a=>{let p=!1,s=[];for(let t of u)a.get(d(t))!==t.mtimeMs&&(g?.has(t.path)?(a.set(d(t),t.mtimeMs),p=!0):s.push(t));let{included:r,blocks:m,truncated:c}=K(s,t=>this.formatBlock(e,t));for(let t of r)a.set(d(t),t.mtimeMs),p=!0;return{value:(c.length>0?[...m,G(c.map(t=>`${e}:${t.path}`))]:m).map(t=>({type:"text",text:t})),changed:p}},this.memoryCache)}formatBlock(e,u){return`<system-reminder>
5
+ Auto-loaded AGENTS.md from ${e}:${u.path} (ancestor of accessed path on remote device). These instructions apply to files under this directory on that device.
6
+
7
+ `+u.content+`
8
+ </system-reminder>`}},B=null;function q(){return B||(B=new M),B}function H(i,e,u){if(!e||e.length===0)return[];let g;if(u){let d=e.filter(a=>Y(a.path,u));d.length>0&&(g=new Set(d.map(a=>a.path)))}return q().buildBlocks(i,e,g)}function Y(i,e){return i===e?!0:i.replace(/\\/g,"/")===e.replace(/\\/g,"/")}import{readFileSync as ee}from"fs";import*as z from"path";var te=z.join(I,"machines.json");function U(i=te){try{let e=JSON.parse(ee(i,"utf-8"));return Object.entries(e).map(([u,g])=>({name:u,windows:g?.win===!0}))}catch{return[]}}function W(i){return i.length===0?"":` Known devices: ${i.map(u=>u.windows?`${u.name} (Windows)`:u.name).join(", ")}. May be offline; failed calls list currently online devices.`}function J(i,e){return Array.isArray(e)?`${i}. Online devices: ${e.length>0?e.join(", "):"none"}`:i}async function $(i,e,u,g,d){let{body:a}=await j("POST",`${i.webhookBaseUrl}/webhook/remote-command`,{device:e,action:u,params:g,timeout:d},R(i));if(!a.success)throw new Error(J(a.error||"Command failed",a.onlineDevices));return a.data}var X=A.join(O,"tool-results"),oe={remote_bash:3e4,remote_grep:2e4,remote_glob:1e5};function k(i,e){let u=oe[i];if(e.length<=u)return e;T.mkdirSync(X,{recursive:!0});let g=`${i}-${Date.now()}-${Q.randomBytes(4).toString("hex")}`,d=A.join(X,`${g}.txt`);T.writeFileSync(d,e,"utf8");let a=(e.length/1024).toFixed(2),p=e.slice(0,2e3);return["<persisted-output>",`Output too large (${a} KB). Full output saved to local file:`,` ${d}`,"","Preview (first 2 KB):",p,"...","</persisted-output>"].join(`
9
+ `)}var w=null;try{w=(await import("sharp")).default}catch{}var C=25e3,V=1568;function E(i){return Math.ceil(i*.125)}async function ne(i,e,u,g){if(!w)return{data:i,mimeType:e,width:u||0,height:g||0};let d=Buffer.from(i,"base64"),a=await w(d).metadata(),p=a.width||u||0,s=a.height||g||0,r=e,m=Math.max(p,s),c=d;if(m>V){let y=V/m;p=Math.round(p*y),s=Math.round(s*y),c=await w(d).resize(p,s,{fit:"inside",withoutEnlargement:!0}).toBuffer()}let n;r==="image/png"?n=await w(c).png({compressionLevel:6}).toBuffer():r==="image/webp"?n=await w(c).webp({quality:85}).toBuffer():(n=await w(c).jpeg({quality:85}).toBuffer(),r="image/jpeg");let t=n.toString("base64"),l=E(t.length);if(l>C){(r==="image/png"||r==="image/webp")&&(n=await w(n).jpeg({quality:80}).toBuffer(),r="image/jpeg",t=n.toString("base64"),l=E(t.length));let y=[70,55,40,30];for(let b of y){if(l<=C)break;n=await w(c).resize(p,s,{fit:"inside",withoutEnlargement:!0}).jpeg({quality:b}).toBuffer(),r="image/jpeg",t=n.toString("base64"),l=E(t.length)}let x=[.75,.5,.35];for(let b of x){if(l<=C)break;let f=Math.round(p*b),_=Math.round(s*b);n=await w(d).resize(f,_,{fit:"inside",withoutEnlargement:!0}).jpeg({quality:30}).toBuffer(),t=n.toString("base64"),l=E(t.length)}}let h=await w(n).metadata();return{data:t,mimeType:r,width:h.width||p,height:h.height||s}}var Z=1800,ie=" `<device>:<path>` refers to a path on that device.";function $e(i,e){let g=["remote_bash","remote_read","remote_write","remote_edit","remote_glob","remote_grep"].find(s=>!e.toolAllowlist||e.toolAllowlist.has(s)),d=W(U()),a=(s,r)=>r+(s===g?ie+d:""),p=(s,r,m)=>e.clean?[]:H(s,r,m);i.tool("remote_bash",a("remote_bash","Run a remote shell command via cortex-client; Windows uses git-bash."),{device:o.string().describe("Target device name."),command:o.string().describe("Shell command to execute"),timeout:o.number().int().min(1).max(Z).optional().describe(`Timeout in seconds (default: 120, max: ${Z})`),description:o.string().optional().describe("Command summary for logging"),run_in_background:o.boolean().optional().describe("Run command in background, return PID immediately; timeout is ignored")},async({device:s,command:r,timeout:m,description:c,run_in_background:n})=>{try{let t=(m??120)*1e3,l=await $(e,s,"bash",{command:r,timeout:t,run_in_background:n||!1},t+5e3),h=[];l.stdout&&h.push(l.stdout),l.stderr&&h.push(`[stderr]
10
+ ${l.stderr}`),l.exitCode!==0&&h.push(`[exit code: ${l.exitCode}]`);let y=h.join(`
11
+ `)||"(no output)",x=k("remote_bash",y),b=l.exitCode!==void 0&&l.exitCode!==0;return{content:[{type:"text",text:x}],...b?{isError:!0}:{}}}catch(t){return{content:[{type:"text",text:`remote_bash error: ${t.message}`}],isError:!0}}}),i.tool("remote_read",a("remote_read","Read a remote absolute path: numbered text, inline images (PNG/JPEG/GIF/WebP/BMP), or PDF documents."),{device:o.string().describe("Target device name."),file_path:o.string().describe("Absolute path to the file to read"),offset:o.number().optional().describe("Line number to start reading from (0-based)"),limit:o.number().optional().describe("Number of lines to read")},{readOnlyHint:!0},async({device:s,file_path:r,offset:m,limit:c})=>{try{if(!S(r))return{content:[{type:"text",text:"file_path must be absolute"}],isError:!0};let n=await $(e,s,"read",{file_path:r,offset:m,limit:c}),t=p(s,n.cortexMDs,r);if(n.image){let{data:l,mimeType:h,width:y,height:x,originalSize:b}=n.image;try{let f=await ne(l,h,y,x),_=E(f.data.length),D=[`Image: ${r}`,`Original: ${y||"?"}x${x||"?"} ${h} (${(b/1024).toFixed(1)} KB)`];return f.width!==y||f.height!==x||f.mimeType!==h?D.push(`Processed: ${f.width}x${f.height} ${f.mimeType} (~${_} tokens)`):D.push(`~${_} tokens`),{content:[{type:"text",text:D.join(`
12
+ `)},{type:"image",data:f.data,mimeType:f.mimeType},...t]}}catch(f){return{content:[{type:"text",text:`Image detected (${h}, ${y||"?"}x${x||"?"}, ${(b/1024).toFixed(1)} KB) but processing failed: ${f.message}`},...t]}}}if(n.pdf){let{data:l,originalSize:h}=n.pdf;return{content:[{type:"text",text:`PDF: ${r} (${(h/1024).toFixed(1)} KB)`},{type:"resource",resource:{uri:re(r).href,mimeType:"application/pdf",blob:l}},...t]}}return{content:[{type:"text",text:n.content||"(empty file)"},...t]}}catch(n){return{content:[{type:"text",text:`remote_read error: ${n.message}`}],isError:!0}}}),i.tool("remote_write",a("remote_write","Write/overwrite a remote file at an absolute path; creates parent directories."),{device:o.string().describe("Target device name."),file_path:o.string().describe("Absolute path to the file to write"),content:o.string().describe("Content to write to the file")},async({device:s,file_path:r,content:m})=>{try{if(!S(r))return{content:[{type:"text",text:"file_path must be absolute"}],isError:!0};let c=await $(e,s,"write",{file_path:r,content:m}),n=p(s,c?.cortexMDs,r);return{content:[{type:"text",text:`File written: ${r}`},...n]}}catch(c){return{content:[{type:"text",text:`remote_write error: ${c.message}`}],isError:!0}}}),i.tool("remote_edit",a("remote_edit","Replace text in a remote file at an absolute path. old_string must be unique unless replace_all=true."),{device:o.string().describe("Target device name."),file_path:o.string().describe("Absolute path to the file to edit"),old_string:o.string().describe("The text to replace"),new_string:o.string().describe("The replacement text"),replace_all:o.boolean().optional().describe("Replace all occurrences (default: false)")},async({device:s,file_path:r,old_string:m,new_string:c,replace_all:n})=>{try{if(!S(r))return{content:[{type:"text",text:"file_path must be absolute"}],isError:!0};let t=await $(e,s,"edit",{file_path:r,old_string:m,new_string:c,replace_all:n||!1}),l=p(s,t?.cortexMDs,r);return{content:[{type:"text",text:`File edited: ${r}`},...l]}}catch(t){return{content:[{type:"text",text:`remote_edit error: ${t.message}`}],isError:!0}}}),i.tool("remote_glob",a("remote_glob","List remote file paths matching a glob."),{device:o.string().describe("Target device name."),pattern:o.string().describe("Glob pattern to match files against"),path:o.string().optional().describe("Directory to search in (absolute path)")},{readOnlyHint:!0},async({device:s,pattern:r,path:m})=>{try{let c=await $(e,s,"glob",{pattern:r,path:m}),n=c.files||[];if(n.length===0)return{content:[{type:"text",text:"No files matched the pattern."}]};let t=n.join(`
13
+ `);return c.truncated&&(t+=`
14
+ [... truncated at ${n.length} results]`),{content:[{type:"text",text:k("remote_glob",t)}]}}catch(c){return{content:[{type:"text",text:`remote_glob error: ${c.message}`}],isError:!0}}}),i.tool("remote_grep",a("remote_grep","Search remote file contents with ripgrep; return matching lines, paths, or counts."),{device:o.string().describe("Target device name."),pattern:o.string().describe("Regex pattern to search for"),path:o.string().optional().describe("File or directory to search in"),glob:o.string().optional().describe('Glob pattern to filter files (e.g. "*.ts", "*.{ts,tsx}")'),type:o.string().optional().describe('File type to search (e.g. "js", "py", "rust")'),output_mode:o.enum(["content","files_with_matches","count"]).optional().describe("Output mode (default: files_with_matches)"),"-A":o.number().optional().describe("Lines to show after each match"),"-B":o.number().optional().describe("Lines to show before each match"),"-C":o.number().optional().describe("Context lines before and after each match"),context:o.number().optional().describe("Alias for -C"),"-i":o.boolean().optional().describe("Case insensitive search"),"-n":o.boolean().optional().describe("Show line numbers (default: true for content mode)"),head_limit:o.number().optional().describe("Limit output entries (default: 250, 0 for unlimited)"),offset:o.number().optional().describe("Skip first N entries before applying head_limit"),multiline:o.boolean().optional().describe("Enable multiline matching (pattern can span lines)")},{readOnlyHint:!0},async({device:s,pattern:r,path:m,glob:c,type:n,output_mode:t,context:l,head_limit:h,offset:y,multiline:x,...b})=>{try{let _=(await $(e,s,"grep",{pattern:r,path:m,glob:c,type:n,output_mode:t,"-A":b["-A"],"-B":b["-B"],"-C":b["-C"],context:l,"-i":b["-i"],"-n":b["-n"],head_limit:h,offset:y,multiline:x})).output||"(no matches)";return{content:[{type:"text",text:k("remote_grep",_)}]}}catch(f){return{content:[{type:"text",text:`remote_grep error: ${f.message}`}],isError:!0}}})}export{$e as registerRemoteOpsTools};
@@ -0,0 +1,4 @@
1
+ import { createRequire as __cortexCreateRequire } from 'node:module';
2
+ const require = __cortexCreateRequire(import.meta.url);
3
+ const __cortexPackageRoot = new URL("../../", import.meta.url);
4
+ import{a,b,c,d}from"./chunk-VOAKRJ4R.js";import"./chunk-ZYQ4TDTT.js";import"./chunk-IVZ7QUEG.js";import"./chunk-TJ4GQRT6.js";import"./chunk-Y3AOGNDT.js";import"./chunk-LMDWRRX4.js";import"./chunk-3EZNVLBF.js";import"./chunk-IA6IODY3.js";import"./chunk-UHXPRU6G.js";import"./chunk-B3XBQEFM.js";import"./chunk-CMSOOLJB.js";import"./chunk-ZNAMETPQ.js";import"./chunk-4KQHDDC5.js";import"./chunk-QXFWIL4C.js";import"./chunk-Y6ZEVVL5.js";import"./chunk-R6CGBSTC.js";import"./chunk-WZYS2HAK.js";import"./chunk-TMV2ZDOI.js";import"./chunk-IOWBF7UK.js";import"./chunk-2ABET62E.js";import"./chunk-2WFL62UO.js";import"./chunk-PG7452XE.js";import"./chunk-RW2F2QNP.js";import"./chunk-HVN37UXD.js";import"./chunk-Y6DGVTKM.js";import"./chunk-OZXMPBUX.js";import"./chunk-V7K3KNDM.js";import"./chunk-5T7IX5KN.js";import"./chunk-VHX2GHBF.js";import"./chunk-C6YVF7EI.js";import"./chunk-ITGCWQFK.js";import"./chunk-PTS3J4DQ.js";import"./chunk-IMMGYDAB.js";import"./chunk-OJ37ZWBG.js";import"./chunk-SKHFU5DI.js";import"./chunk-V35MFAUQ.js";import"./chunk-OKRK6JPY.js";import"./chunk-52VCLZS5.js";import"./chunk-B3NB243Z.js";import"./chunk-LCKVYFMD.js";import"./chunk-5M4PFLRW.js";import"./chunk-BVEDNESB.js";import"./chunk-KST6OY76.js";import"./chunk-AXYAZTTN.js";import"./chunk-SM45TH22.js";import"./chunk-R2CCD4OF.js";import"./chunk-KRXTI4JO.js";import"./chunk-W34AK4SK.js";import"./chunk-LIIZI3HY.js";import"./chunk-Q4UGYGU5.js";import"./chunk-TRXLIL7V.js";import"./chunk-7GGPYU5E.js";import"./chunk-7W7VYUTK.js";import"./chunk-JGUEIW2W.js";import"./chunk-T54CZKNJ.js";import"./chunk-WHC7AYZD.js";export{d as _test,c as parentQuotaPurpose,b as runSubagent,a as supportsSubagents};
@@ -0,0 +1,4 @@
1
+ import { createRequire as __cortexCreateRequire } from 'node:module';
2
+ const require = __cortexCreateRequire(import.meta.url);
3
+ const __cortexPackageRoot = new URL("../../", import.meta.url);
4
+ import{a,b,c,d,e,f}from"./chunk-G4JYZFEO.js";import"./chunk-24DH4IR5.js";import"./chunk-EQIMHXC4.js";import"./chunk-IRWZ7UPF.js";import"./chunk-6G3OYMCV.js";import"./chunk-CEJIYYVE.js";import"./chunk-2BVUA256.js";import"./chunk-AWFUHWQK.js";import"./chunk-B3XBQEFM.js";import"./chunk-WHC7AYZD.js";export{b as McpOAuthCredentialStore,f as McpServerConnection,d as McpServerLog,a as McpSignInCancelledError,e as createDefaultTransport,c as signInMcpServer};
@@ -0,0 +1,4 @@
1
+ import { createRequire as __cortexCreateRequire } from 'node:module';
2
+ const require = __cortexCreateRequire(import.meta.url);
3
+ const __cortexPackageRoot = new URL("../../", import.meta.url);
4
+ import{c as S,d as w,e as p,f as v,h as g,k as h,l as m,p as A,r as j,s as C,t as M,u as D}from"./chunk-KJUQCCB5.js";import"./chunk-IVZ7QUEG.js";import"./chunk-IA6IODY3.js";import{g as O}from"./chunk-Q7BZLPBU.js";import"./chunk-Y6DGVTKM.js";import"./chunk-C6YVF7EI.js";import"./chunk-ITGCWQFK.js";import"./chunk-PTS3J4DQ.js";import"./chunk-IMMGYDAB.js";import"./chunk-OJ37ZWBG.js";import"./chunk-SKHFU5DI.js";import"./chunk-V35MFAUQ.js";import"./chunk-OKRK6JPY.js";import"./chunk-52VCLZS5.js";import"./chunk-B3NB243Z.js";import"./chunk-LCKVYFMD.js";import"./chunk-5M4PFLRW.js";import{b as E,c as x}from"./chunk-PMG4YGDU.js";import"./chunk-SM45TH22.js";import"./chunk-LIIZI3HY.js";import"./chunk-Q4UGYGU5.js";import"./chunk-TRXLIL7V.js";import"./chunk-7GGPYU5E.js";import"./chunk-7W7VYUTK.js";import"./chunk-T54CZKNJ.js";import"./chunk-WHC7AYZD.js";var f=["list","get","add","edit","pause","resume","remove"],_={"--type":"type","--interval":"interval","--time":"time","--day":"day","--delay":"delay","--message":"message","--project":"project","--model":"model","--thinking":"thinking","--pre-check":"preCheck","--idempotency-key":"idempotencyKey"},I=["interval","time","day","delay","message","project","model","thinking","preCheck"],L={list:["project"],get:[],add:["type",...I,"idempotencyKey"],edit:I,pause:[],resume:[],remove:[]},T={interval:["interval"],daily:["time"],weekly:["day","time"],once:["delay"]},N=new Set(["get","edit","pause","resume","remove"]),c=class extends Error{validValues;hint;constructor(t,n,r="cortex schedule --help"){super(t),this.validValues=n,this.hint=r}};function y(e){return Object.entries(_).filter(([,t])=>e.includes(t)).map(([t])=>t)}function R(e,t,n,r){let i=_[t[n]];if(!i||!L[e].includes(i)){let o=[...y(L[e]),...e==="remove"?["--dry-run"]:[]];throw new c(`Unknown option for '${e}': '${t[n]}'.`,o.length?o:["(none)"])}if(t[n+1]===void 0||t[n+1].startsWith("--"))throw new c(`Missing value for ${t[n]}.`);r[i]=t[n+1]}function b(e,t,n){let r={id:"",flags:{},dryRun:!1},i=[];for(let s=0;s<t.length;s+=1)e==="remove"&&t[s]==="--dry-run"?r.dryRun=!0:t[s].startsWith("-")?R(e,t,s++,r.flags):i.push(t[s]);let o=N.has(e)?1:0;if(i.length!==o)throw new c(o?`'${e}' takes one schedule id.`:`Unexpected argument: '${i[0]}'.`,void 0,o?`cortex schedule ${e} <id>`:void 0);return r.id=i[0]??"",r.flags.message==="-"&&(r.flags.message=n()),r}var G=["createdAt","nextRun","lastRun","runAt","pausedAt","lastSkipped"];function k(e){let t={...e};for(let n of G)typeof e[n]=="number"&&(t[n]=new Date(e[n]).toISOString());return t}function u(e,t){if(!e)throw new c(`Schedule not found: '${t}'.`,void 0,"cortex schedule list");return k(e)}async function W({flags:e},t){if(!e.type)throw new c("Missing --type.",[...S]);let n=h(e.model,e.thinking);m(e.model,n);let r=g({type:e.type,message:e.message,projectId:e.project,selection:n,preCheck:e.preCheck,interval:e.interval,time:e.time,dayOfWeek:e.day,delay:e.delay}),i=T[r.type],o=["interval","time","day","delay"].filter(d=>e[d]!==void 0&&!i.includes(d));if(o.length)throw new c(`${y(o).join(", ")} does not apply to --type ${r.type}.`,y(i));let{task:s,created:l}=await j(t,r,{idempotencyKey:e.idempotencyKey});return{ok:!0,created:l,schedule:k(s)}}var K={message:e=>({message:e}),project:e=>({projectId:e}),preCheck:e=>({preCheck:e}),interval:e=>({intervalMs:p(e,"interval")}),time:e=>({time:e}),day:e=>({dayOfWeek:v(e)}),delay:e=>({runAt:Date.now()+p(e,"delay")})};async function U({id:e,flags:t},n){let r=await n.findTask(e);u(r,e);let{model:i,thinking:o,...s}=t,l=Object.assign({},...Object.entries(s).map(([$,F])=>K[$](F))),d=h(i,o,r?.selection);return m(i,d),d&&(l.selection=d),{ok:!0,schedule:u(await C(n,e,l),e)}}async function V({id:e,dryRun:t},n){return t?{ok:!0,dry_run:!0,would_remove:u(await n.findTask(e),e)}:{ok:!0,id:e,removed:await n.removeTask(e)}}async function H({flags:e},t){let n=(await t.read()).tasks.filter(r=>!e.project||r.projectId===e.project);return{ok:!0,count:n.length,schedules:n.map(k)}}var P={list:H,get:async({id:e},t)=>({ok:!0,schedule:u(await t.findTask(e),e)}),add:W,edit:U,pause:async({id:e},t)=>({ok:!0,schedule:u(await M(t,e),e)}),resume:async({id:e},t)=>({ok:!0,schedule:u(await D(t,e),e)}),remove:V};function a(e,t,n){return{exitCode:1,stdout:"",stderr:E(e,{validValues:t,hint:n})}}function z(e){return e instanceof c?a(e.message,e.validValues,e.hint):e instanceof w?a(e.message,void 0,"cortex schedule --help"):a(e.message)}async function Z(e,t={}){if(e.includes("--help")||e.includes("-h"))return{exitCode:0,stdout:O(),stderr:""};let[n,...r]=e;if(!n)return a("Missing subcommand for 'schedule'.",[...f]);if(!f.includes(n))return a(`Unknown subcommand: '${n}'.`,[...f]);try{let i=b(n,r,t.readStdin??x),o=await P[n](i,t.repo??A);return{exitCode:0,stdout:JSON.stringify(o,null,2),stderr:""}}catch(i){return z(i)}}export{Z as runScheduleCli};
@@ -0,0 +1,4 @@
1
+ import { createRequire as __cortexCreateRequire } from 'node:module';
2
+ const require = __cortexCreateRequire(import.meta.url);
3
+ const __cortexPackageRoot = new URL("../../", import.meta.url);
4
+ import{b as w,c as E}from"./chunk-5FHETFZM.js";import{a as C,e as x}from"./chunk-LE6QPXN6.js";import{a as L}from"./chunk-NT32UURL.js";import"./chunk-I6OPDRVF.js";import"./chunk-ZNAMETPQ.js";import"./chunk-4KQHDDC5.js";import"./chunk-QXFWIL4C.js";import"./chunk-Y6ZEVVL5.js";import"./chunk-LP72AF56.js";import"./chunk-N6BTQN7R.js";import"./chunk-OKRK6JPY.js";import"./chunk-52VCLZS5.js";import"./chunk-BVEDNESB.js";import"./chunk-KRXTI4JO.js";import{K as r}from"./chunk-W34AK4SK.js";import"./chunk-7W7VYUTK.js";import"./chunk-T54CZKNJ.js";import{e as T}from"./chunk-WHC7AYZD.js";var k=T(x(),1);import*as S from"fs";import*as b from"path";function v(e){return{slack:e.slackBotToken?new k.WebClient(e.slackBotToken):null,fallbackChannel:e.channel??void 0,ctx:e}}function y(){return new C({globalCapacity:m("CORTEX_SLACK_RL_GLOBAL_CAPACITY",20),globalRefillPerSec:m("CORTEX_SLACK_RL_GLOBAL_REFILL_PER_SEC",1),perChannelCapacity:m("CORTEX_SLACK_RL_CHANNEL_CAPACITY",1),perChannelRefillPerSec:m("CORTEX_SLACK_RL_CHANNEL_REFILL_PER_SEC",1)})}function m(e,t){let l=process.env[e];return l?Number(l):t}var R=null;async function A(e,{channel:t,filePath:l,fileName:s,title:h,initialComment:p}){let a=R??(R=y()),{resolved:o,size:c}=L(l),f=S.readFileSync(o),i=s||b.basename(o),n=w(t,"slack:");p&&(await a.acquire("chat.postMessage",n),await e.chat.postMessage({channel:n,text:p})),await a.acquire("files.getUploadURLExternal",n);let d=await e.files.getUploadURLExternal({filename:i,length:c});if(!d?.upload_url||!d?.file_id)throw new Error("Slack upload initialization failed: missing upload_url or file_id");let u=await fetch(d.upload_url,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:f});if(!u.ok){let _=await u.text().catch(()=>""),g=_?`: ${_.slice(0,300)}`:"";throw new Error(`Slack file upload failed (${u.status} ${u.statusText})${g}`)}return await a.acquire("files.completeUploadExternal",n),await e.files.completeUploadExternal({files:[{id:d.file_id,title:h||i}],channel_id:n}),{path:o,fileName:i,size:c}}function $(e,t){e.tool("slack_send_file","Share a local or remote-device file in the Slack chat.",{file_path:r.string().describe("File path to upload. Local path, or an absolute path on `device`."),file_name:r.string().optional().describe("Optional filename override shown in Slack"),title:r.string().optional().describe("Optional file title shown in Slack"),comment:r.string().optional().describe("Optional comment to accompany the file"),device:r.string().optional().describe("Connected device to read from; omit for this server.")},async({file_path:l,file_name:s,title:h,comment:p,device:a})=>{try{let o=t.fallbackChannel;if(!o)throw new Error("No routing channel available");if(!t.slack)throw new Error("Missing SLACK_BOT_TOKEN");let c=(i,n)=>A(t.slack,{channel:o,filePath:i,fileName:n,title:h,initialComment:p||void 0}),f=a?await E(t.ctx,a,l,i=>c(i.localPath,s||i.name)):await c(l,s);return{content:[{type:"text",text:`File uploaded${a?` from ${a}`:""}: ${f.fileName} (${f.size} bytes)`}]}}catch(o){return{content:[{type:"text",text:`Failed to upload file: ${o.message}`}],isError:!0}}})}export{$ as registerSlackTools,v as slackDepsFor,A as uploadFileToSlack};