@cortex-agent/server 2026.10.27 → 2026.11.17

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 (258) hide show
  1. package/LICENSE +255 -21
  2. package/README.md +54 -7
  3. package/THIRD_PARTY_NOTICES.txt +1109 -278
  4. package/defaults/hooks/cortex-hook-api.mjs +2 -1
  5. package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +23 -15
  6. package/dist/agent-adapter/claude/remote-mcp-proxy.js +1 -1
  7. package/dist/chunks/{anthropic-messages-M3SMXACA.js → anthropic-messages-M732OMEE.js} +1 -1
  8. package/dist/chunks/{azure-openai-responses-76YWXHSB.js → azure-openai-responses-RAKTV6JY.js} +1 -1
  9. package/dist/chunks/bedrock-converse-stream-WNUGNZ27.js +62 -0
  10. package/dist/chunks/bowser-MLGGLXTZ.js +20 -0
  11. package/dist/chunks/child-runner-MO5RT6FH.js +4 -0
  12. package/dist/chunks/chunk-2ATTYCRJ.js +4 -0
  13. package/dist/chunks/{chunk-PXS5SHOV.js → chunk-2ROGTDM2.js} +1 -1
  14. package/dist/chunks/chunk-2VVRTJQN.js +4 -0
  15. package/dist/chunks/{chunk-OZGBWAT2.js → chunk-2YTYYG4K.js} +1 -1
  16. package/dist/chunks/chunk-3CPIMAYX.js +30 -0
  17. package/dist/chunks/{chunk-FXDIR3SQ.js → chunk-3CZPBLB3.js} +1 -1
  18. package/dist/chunks/chunk-3ORG56I5.js +8 -0
  19. package/dist/chunks/{chunk-LEUENXI2.js → chunk-4YLAGSDM.js} +1 -1
  20. package/dist/chunks/{chunk-HU6UIDEJ.js → chunk-53TQNK7Z.js} +1 -1
  21. package/dist/chunks/{chunk-4U7XXM4W.js → chunk-5A6CA5TM.js} +1 -1
  22. package/dist/chunks/{chunk-PBJ5MPPX.js → chunk-5DF5WJNM.js} +1 -1
  23. package/dist/chunks/chunk-5PAW3DEU.js +50 -0
  24. package/dist/chunks/{chunk-DXBSQXJL.js → chunk-7GAYFN52.js} +1 -1
  25. package/dist/chunks/chunk-7GEBDPTT.js +4 -0
  26. package/dist/chunks/{chunk-NR6U3WIZ.js → chunk-AFTBQRPN.js} +1 -1
  27. package/dist/chunks/chunk-AVXDF7AG.js +4 -0
  28. package/dist/chunks/chunk-BDLKI2NT.js +4 -0
  29. package/dist/chunks/{chunk-P52RMIYX.js → chunk-BJGYGEZO.js} +1 -1
  30. package/dist/chunks/chunk-BUZQBTV2.js +10 -0
  31. package/dist/chunks/chunk-BZDIAI5M.js +125 -0
  32. package/dist/chunks/{chunk-A34TDMIC.js → chunk-CEGSDGYQ.js} +1 -1
  33. package/dist/chunks/{chunk-Q7CE3UIE.js → chunk-CK3P345X.js} +69 -69
  34. package/dist/chunks/{chunk-YAEVYJAR.js → chunk-EE3WT25T.js} +1 -1
  35. package/dist/chunks/chunk-ETIBCA2S.js +4 -0
  36. package/dist/chunks/{chunk-REBNWCKI.js → chunk-FP7ML72L.js} +1 -1
  37. package/dist/chunks/{chunk-H2FP6DG4.js → chunk-H4QZ2P3Z.js} +1 -1
  38. package/dist/chunks/chunk-IA6IODY3.js +4 -0
  39. package/dist/chunks/{chunk-D3NXKK2L.js → chunk-IKLTEWA3.js} +1 -1
  40. package/dist/chunks/chunk-IYVZHGUQ.js +5 -0
  41. package/dist/chunks/chunk-JJDEQ6N2.js +4 -0
  42. package/dist/chunks/chunk-JKL3AK5D.js +106 -0
  43. package/dist/chunks/chunk-KDPY2YA3.js +129 -0
  44. package/dist/chunks/{chunk-SUFW24P4.js → chunk-KUDK7GPS.js} +1 -1
  45. package/dist/chunks/chunk-LAWOWPZX.js +363 -0
  46. package/dist/chunks/chunk-LEAV3FFG.js +4 -0
  47. package/dist/chunks/chunk-LP72AF56.js +45 -0
  48. package/dist/chunks/{chunk-KENCMLRE.js → chunk-LP7T32PW.js} +1 -1
  49. package/dist/chunks/chunk-LQTFDC67.js +4 -0
  50. package/dist/chunks/{chunk-HALUQ7ZF.js → chunk-MGYYSX7Y.js} +1 -1
  51. package/dist/chunks/chunk-NNBSSISP.js +4 -0
  52. package/dist/chunks/chunk-NNTQUHLO.js +877 -0
  53. package/dist/chunks/{chunk-PFMEUFJ7.js → chunk-NRD57ICT.js} +1 -1
  54. package/dist/chunks/{chunk-QWAQHHRS.js → chunk-NXZS5PEW.js} +1 -1
  55. package/dist/chunks/chunk-OFEPDNRB.js +4 -0
  56. package/dist/chunks/{chunk-6LZK4DDH.js → chunk-P7TVR4GY.js} +1 -1
  57. package/dist/chunks/chunk-QEL6CMLE.js +4 -0
  58. package/dist/chunks/chunk-QMSSIDRQ.js +70 -0
  59. package/dist/chunks/chunk-QUXPMNFQ.js +4 -0
  60. package/dist/chunks/chunk-R52AVUQB.js +5 -0
  61. package/dist/chunks/chunk-R6CGBSTC.js +22 -0
  62. package/dist/chunks/chunk-RA2BUYI3.js +6 -0
  63. package/dist/chunks/chunk-RDW6FRF5.js +4 -0
  64. package/dist/chunks/chunk-RF4JLYBX.js +6 -0
  65. package/dist/chunks/{chunk-YPK2CAIZ.js → chunk-ROVKOIHF.js} +1 -1
  66. package/dist/chunks/chunk-RYLSRII6.js +7 -0
  67. package/dist/chunks/{chunk-XNSSUVT6.js → chunk-S3MR37DL.js} +1 -1
  68. package/dist/chunks/chunk-SAJD4EKE.js +10 -0
  69. package/dist/chunks/chunk-SFX7V5O2.js +10 -0
  70. package/dist/chunks/chunk-STCNHXPJ.js +6 -0
  71. package/dist/chunks/{chunk-FOJQXLL2.js → chunk-SY2HV3V5.js} +1 -1
  72. package/dist/chunks/chunk-T73GHMFB.js +4 -0
  73. package/dist/chunks/chunk-TKFFQNAP.js +19 -0
  74. package/dist/chunks/chunk-TMV2ZDOI.js +18 -0
  75. package/dist/chunks/chunk-TX46YMGI.js +5 -0
  76. package/dist/chunks/chunk-U23S37TT.js +6 -0
  77. package/dist/chunks/chunk-UT6DGZDO.js +4 -0
  78. package/dist/chunks/{chunk-JERCOLY3.js → chunk-V35MFAUQ.js} +4 -6
  79. package/dist/chunks/chunk-V6X7Y62J.js +7 -0
  80. package/dist/chunks/chunk-V7K3KNDM.js +4 -0
  81. package/dist/chunks/{chunk-NAA7GF6Q.js → chunk-VBN2JSER.js} +1 -1
  82. package/dist/chunks/chunk-VIMHSW6J.js +4 -0
  83. package/dist/chunks/chunk-VK5J556O.js +4 -0
  84. package/dist/chunks/chunk-VPVSKJGX.js +6 -0
  85. package/dist/chunks/chunk-VTL3Z2OP.js +23 -0
  86. package/dist/chunks/{chunk-X2GYYRVM.js → chunk-VW7TLY3P.js} +1 -1
  87. package/dist/chunks/chunk-W34AK4SK.js +65 -0
  88. package/dist/chunks/chunk-W6AKCEYF.js +8 -0
  89. package/dist/chunks/chunk-WBSE3EF3.js +27 -0
  90. package/dist/chunks/chunk-WZYS2HAK.js +4 -0
  91. package/dist/chunks/{chunk-UNVEZI57.js → chunk-XEBEWR6Y.js} +1 -1
  92. package/dist/chunks/chunk-XPPZ6Y3X.js +8 -0
  93. package/dist/chunks/chunk-XYSXL3KX.js +4 -0
  94. package/dist/chunks/chunk-YAAKL3QS.js +80 -0
  95. package/dist/chunks/chunk-YB5LUJHS.js +65 -0
  96. package/dist/chunks/chunk-Z24SBRJK.js +4 -0
  97. package/dist/chunks/cloudflare-workers-ai-system-one-32JCFHI3.js +1 -1
  98. package/dist/chunks/context-GQKWKFRM.js +4 -0
  99. package/dist/chunks/cost-OOO32GLC.js +5 -0
  100. package/dist/chunks/dist-V5FRMUFH.js +4 -0
  101. package/dist/chunks/easter-egg-3d-CZH7AYZ7.js +4 -0
  102. package/dist/chunks/{event-streams-3JSFPOTZ.js → event-streams-AVE4MSS6.js} +1 -1
  103. package/dist/chunks/execution-repo-XXL4FXC6.js +4 -0
  104. package/dist/chunks/{executions-6ARGR3IO.js → executions-BN6OLLVM.js} +1 -1
  105. package/dist/chunks/file-H572PL2Z.js +4 -0
  106. package/dist/chunks/google-generative-ai-2G4ITOZL.js +4 -0
  107. package/dist/chunks/google-vertex-PACHCMRZ.js +4 -0
  108. package/dist/chunks/init-75F4V7SK.js +4 -0
  109. package/dist/chunks/{install-cli-4IZCSDFZ.js → install-cli-ABBD7DO5.js} +1 -1
  110. package/dist/chunks/{interaction-ask-G5T3H3CG.js → interaction-ask-EE2UPR3Q.js} +1 -1
  111. package/dist/chunks/{interaction-plan-E5V42MUP.js → interaction-plan-C446T2GZ.js} +1 -1
  112. package/dist/chunks/{llama-cpp-classify-OTXZWCMW.js → llama-cpp-classify-IA2F2H7A.js} +1 -1
  113. package/dist/chunks/local-client-stop-5YOLXGYT.js +4 -0
  114. package/dist/chunks/memory-cli-5SSF6YJM.js +11 -0
  115. package/dist/chunks/{mistral-conversations-34F66L3O.js → mistral-conversations-VHP63CDS.js} +1 -1
  116. package/dist/chunks/{model-resolver-N3DTAQ2S.js → model-resolver-FVJNZ6NA.js} +1 -1
  117. package/dist/chunks/{node-PTK2HCDV.js → node-DAO3SX7O.js} +1 -1
  118. package/dist/chunks/{openai-codex-2REL6UQU.js → openai-codex-JULCKICT.js} +1 -1
  119. package/dist/chunks/{openai-codex-responses-ZBVHREB3.js → openai-codex-responses-EHJ4AZBE.js} +1 -1
  120. package/dist/chunks/{openai-completions-VVIB26SH.js → openai-completions-CRAGQFCE.js} +1 -1
  121. package/dist/chunks/{openai-decisions-2N6ZRPZC.js → openai-decisions-P5UX7BWY.js} +1 -1
  122. package/dist/chunks/{openai-responses-735XA2ZX.js → openai-responses-IZ22NVQ7.js} +1 -1
  123. package/dist/chunks/{openrouter-images-3IKETHAC.js → openrouter-images-W2JAMSRH.js} +1 -1
  124. package/dist/chunks/{pi-messages-I3E4ZFHA.js → pi-messages-MJEEQU2R.js} +1 -1
  125. package/dist/chunks/{radius-HXRZVBDB.js → radius-ZM7ZRMXF.js} +1 -1
  126. package/dist/chunks/{remote-ops-BALZYKH6.js → remote-ops-O5CR4RGA.js} +1 -1
  127. package/dist/chunks/runner-S6R3US24.js +4 -0
  128. package/dist/chunks/schedule-cli-4T4YC5V5.js +4 -0
  129. package/dist/chunks/slack-2CGM4SMY.js +4 -0
  130. package/dist/chunks/start-ui-http-3D7QNHGB.js +43 -0
  131. package/dist/chunks/subagent-OZGUOV3J.js +4 -0
  132. package/dist/chunks/{time-KEHDQT6K.js → time-P6PE52WL.js} +1 -1
  133. package/dist/chunks/tool-shims-IA2WELXJ.js +4 -0
  134. package/dist/chunks/typesafe-system-one-6ULACYD4.js +1 -1
  135. package/dist/chunks/ui-board-H4INJD6C.js +5 -0
  136. package/dist/chunks/ui-decision-6HHNROIT.js +4 -0
  137. package/dist/chunks/{ui-file-GVH53O3X.js → ui-file-6PLXHSTB.js} +1 -1
  138. package/dist/chunks/ui-view-6MDU4GXY.js +4 -0
  139. package/dist/chunks/virtual-modules-OFI7QKYH.js +4 -0
  140. package/dist/chunks/waitpoint-W5M3BE55.js +5 -0
  141. package/dist/chunks/workers-GTFP75MS.js +4 -0
  142. package/dist/client-bundle/client.mjs +44 -31
  143. package/dist/client-bundle/manifest.json +2 -2
  144. package/dist/core/pi-sdk.js +1 -1
  145. package/dist/domain/auth/cc-auth-cli.js +1 -1
  146. package/dist/domain/mcp/bundled-server.js +1 -1
  147. package/dist/domain/mcp/feishu/client.js +4 -0
  148. package/dist/entry/app.js +201 -191
  149. package/dist/entry/browser-cli.js +10 -10
  150. package/dist/entry/cli.js +1 -1
  151. package/dist/entry/cortex-cli.js +1 -1
  152. package/dist/entry/daemon.js +4 -4
  153. package/dist/entry/hook-cli.js +2 -2
  154. package/dist/entry/production-app-bootstrap.js +1 -1
  155. package/dist/entry/production-evidence-export-cli.js +1 -1
  156. package/dist/entry/signal-cli.js +2 -2
  157. package/dist/tui/index.js +41 -41
  158. package/package.json +3 -3
  159. package/vendor/pi/dist/core/extensions/loader.js +1 -1
  160. package/vendor/pi/dist/extensions/codemode/execute.js +1 -1
  161. package/vendor/pi-ai/bedrock.js +1 -1
  162. package/vendor/pi-ai/oauth-load.js +1 -1
  163. package/web/dist/assets/{board-math-css-BmiXB1z5.js → board-math-css-BgIyUG-C.js} +1 -1
  164. package/web/dist/assets/index-9lyu2S6W.css +1 -0
  165. package/web/dist/assets/index-C-hpzey7.js +532 -0
  166. package/web/dist/assets/{index-XBRXpnC5.js → index-C2eMpcuI.js} +1 -1
  167. package/web/dist/assets/pdf-worker-DdZgk2mV.js +57 -0
  168. package/web/dist/assets/pdf.worker.min-Bz_KHX45.js +55 -0
  169. package/web/dist/index.html +2 -2
  170. package/web/dist/theme.css +22 -0
  171. package/dist/chunks/api-GM53PHIL-GFHEXXE6.js +0 -4
  172. package/dist/chunks/bedrock-converse-stream-5UPX4NTQ.js +0 -58
  173. package/dist/chunks/child-runner-3GHOWGZP.js +0 -4
  174. package/dist/chunks/chunk-2ZNLUY2U.js +0 -128
  175. package/dist/chunks/chunk-3F6WW7HR.js +0 -13
  176. package/dist/chunks/chunk-3OKHUVEM.js +0 -7
  177. package/dist/chunks/chunk-3THJYAEF.js +0 -4
  178. package/dist/chunks/chunk-3YHOCPQU.js +0 -10
  179. package/dist/chunks/chunk-4LLH5OWM.js +0 -10
  180. package/dist/chunks/chunk-52T37Y47.js +0 -8
  181. package/dist/chunks/chunk-7MU2AKNM.js +0 -4
  182. package/dist/chunks/chunk-AAA3UBIS.js +0 -4
  183. package/dist/chunks/chunk-ASYQHJVQ.js +0 -9
  184. package/dist/chunks/chunk-BGVHA2D4.js +0 -4
  185. package/dist/chunks/chunk-BKHDWCRT.js +0 -79
  186. package/dist/chunks/chunk-CQLH4UVX.js +0 -4
  187. package/dist/chunks/chunk-D6UA4BZC.js +0 -19
  188. package/dist/chunks/chunk-DGMNI4AO.js +0 -4
  189. package/dist/chunks/chunk-DHSA5ACV.js +0 -125
  190. package/dist/chunks/chunk-DPQPXBTP.js +0 -68
  191. package/dist/chunks/chunk-E7ZMYIY6.js +0 -30
  192. package/dist/chunks/chunk-EQITBTJC.js +0 -10
  193. package/dist/chunks/chunk-EXJA5RIX.js +0 -357
  194. package/dist/chunks/chunk-FH74NME3.js +0 -115
  195. package/dist/chunks/chunk-FOQ7VLIL.js +0 -17
  196. package/dist/chunks/chunk-J5DVLUKY.js +0 -6
  197. package/dist/chunks/chunk-JW2HFMTF.js +0 -4
  198. package/dist/chunks/chunk-KIGMAATV.js +0 -23
  199. package/dist/chunks/chunk-KIU5FAPY.js +0 -5
  200. package/dist/chunks/chunk-KIWMQPH7.js +0 -739
  201. package/dist/chunks/chunk-LMSQZ6TQ.js +0 -4
  202. package/dist/chunks/chunk-MEPASGPP.js +0 -6
  203. package/dist/chunks/chunk-MFAEUHMV.js +0 -28
  204. package/dist/chunks/chunk-NKDMKRSB.js +0 -68
  205. package/dist/chunks/chunk-NKXV32S6.js +0 -4
  206. package/dist/chunks/chunk-NVX5IPRN.js +0 -4
  207. package/dist/chunks/chunk-O3JW2F7D.js +0 -8
  208. package/dist/chunks/chunk-OISO5JXB.js +0 -4
  209. package/dist/chunks/chunk-OPYXNSMY.js +0 -4
  210. package/dist/chunks/chunk-PZMXHA6X.js +0 -9
  211. package/dist/chunks/chunk-QEOFEETJ.js +0 -4
  212. package/dist/chunks/chunk-REPYBMQS.js +0 -4
  213. package/dist/chunks/chunk-TAWLERZA.js +0 -4
  214. package/dist/chunks/chunk-TWAEABGG.js +0 -52
  215. package/dist/chunks/chunk-TZFLHVOQ.js +0 -7
  216. package/dist/chunks/chunk-UD3NMUHR.js +0 -12
  217. package/dist/chunks/chunk-W25TB3PU.js +0 -4
  218. package/dist/chunks/chunk-W5LGYSPZ.js +0 -4
  219. package/dist/chunks/chunk-XAJLZR7C.js +0 -28
  220. package/dist/chunks/chunk-XH6FMP3N.js +0 -71
  221. package/dist/chunks/chunk-XSRZHN63.js +0 -4
  222. package/dist/chunks/chunk-YG7OEPR2.js +0 -6
  223. package/dist/chunks/chunk-YHIWOGVL.js +0 -4
  224. package/dist/chunks/chunk-YZSHTWNM.js +0 -92
  225. package/dist/chunks/chunk-Z4H3VDHI.js +0 -4
  226. package/dist/chunks/client-XOGYH5UR.js +0 -4
  227. package/dist/chunks/config-DJSQI77S-335IXHSM.js +0 -4
  228. package/dist/chunks/context-VCQH5OB6.js +0 -4
  229. package/dist/chunks/cost-PGGFI7QJ.js +0 -5
  230. package/dist/chunks/dist-PUKMZ7GW.js +0 -4
  231. package/dist/chunks/easter-egg-3d-MO4MOEVF.js +0 -4
  232. package/dist/chunks/es5-VNTQPCKX.js +0 -4
  233. package/dist/chunks/execution-repo-ZLJTBWFC.js +0 -4
  234. package/dist/chunks/file-7BN7RCAY.js +0 -4
  235. package/dist/chunks/gateway-UCRPMR75.js +0 -36
  236. package/dist/chunks/google-generative-ai-2VXWLHWI.js +0 -4
  237. package/dist/chunks/google-vertex-UA36QP2U.js +0 -4
  238. package/dist/chunks/init-HA7FAQ73.js +0 -4
  239. package/dist/chunks/local-client-stop-SQRU7ZZM.js +0 -4
  240. package/dist/chunks/memory-cli-PYOILNN5.js +0 -11
  241. package/dist/chunks/models-L5VF4I5O-XXNJYQMQ.js +0 -4
  242. package/dist/chunks/runner-PLVZDGHB.js +0 -4
  243. package/dist/chunks/schedule-cli-OLASBBYJ.js +0 -4
  244. package/dist/chunks/slack-WAGSPZUX.js +0 -4
  245. package/dist/chunks/start-ui-http-QALT7C3P.js +0 -43
  246. package/dist/chunks/subagent-E3UC7ZHC.js +0 -4
  247. package/dist/chunks/tool-shims-Q6P6UXVC.js +0 -4
  248. package/dist/chunks/ui-board-4GYW6KKW.js +0 -5
  249. package/dist/chunks/ui-decision-U2FXSEC2.js +0 -4
  250. package/dist/chunks/ui-view-O7PLANT7.js +0 -4
  251. package/dist/chunks/virtual-modules-IDC5YKZJ.js +0 -4
  252. package/dist/chunks/waitpoint-2FGQBIAC.js +0 -5
  253. package/dist/chunks/workers-XN4PSTH6.js +0 -4
  254. package/vendor/aistatus/gateway-cli.js +0 -21
  255. package/web/dist/assets/index-DqWMdMkh.css +0 -1
  256. package/web/dist/assets/index-btKNdkvc.js +0 -525
  257. package/web/dist/assets/pdf-worker-Hp15W1QJ.js +0 -57
  258. package/web/dist/assets/pdf.worker.min-DnhTvCwe.js +0 -55
@@ -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 ue,b as fe}from"./chunk-BGYR4ID3.js";import{a as ke}from"./chunk-XIECJESP.js";import{a as Te}from"./chunk-V3AQJSWR.js";import{a as he}from"./chunk-CVC66CFV.js";import{a as ne}from"./chunk-23PRJECN.js";import{a as me,b as ye}from"./chunk-FF7UELTU.js";import{a as se,b as re,c as oe,d as ie,e as ae,f as N,h as le,i as ce,k as pe,l as ge,o as de}from"./chunk-QBKCAIJG.js";import{C as j,F as G,J as Z,L as Q,o as U,p as V,y as z}from"./chunk-PZMGBKUR.js";import{a as ee}from"./chunk-6R73ICDB.js";import{c as X,d as Y}from"./chunk-SKHLZ6XY.js";import"./chunk-D6VMBA4C.js";import{a as b}from"./chunk-USBJFDJ6.js";import{a as te}from"./chunk-K4NTZEDJ.js";import{h as J}from"./chunk-6AKUD3CF.js";import"./chunk-OSEIQ7SS.js";import{b as W}from"./chunk-CXT5IR5T.js";import"./chunk-WHC7AYZD.js";function Re(e,n){if(!e)return!1;let t=n.toLowerCase();for(let[s,u]of Object.entries(e))if(s.toLowerCase()===t&&u!==null&&u.trim().length>0)return!0;return!1}function Ce(e,n,t){if(n)return n;if(Re(t,"authorization")||Re(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 xe(e){return e.type==="text"}function Be(e){return e.type==="thinking"}function Pe(e){return e.type==="toolCall"}function Le(e){return e.type==="image"}function qe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function De(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 $(e){if(!qe(e)||!De(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 ze(e){if(e)try{let n=JSON.parse(e);return Array.isArray(n)&&n.length>0&&n.every($)?n:void 0}catch{return}}function je(e){if(e)try{let n=JSON.parse(e);return $(n)&&n.type==="reasoning.encrypted"&&typeof n.id=="string"&&n.id.length>0&&n.data.length>0?n:void 0}catch{return}}function _e(e,n){e.id??=n.id,e.format||=n.format,e.index??=n.index}function Ge(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,_e(t,n);return}if(n.type==="reasoning.summary"&&t?.type==="reasoning.summary"){t.summary+=n.summary,_e(t,n);return}e.push({...n})}var Ne=["reasoning","reasoning_content","reasoning_text"];function $e(e){return Ne.includes(e)}function Me(e,n){return e||(ee("PI_CACHE_RETENTION",n)==="long"?"long":"short")}var He=(e,n,t)=>{let s=new W,u=z(n,q(e).supportsMidConvoSystemMessages);return(async()=>{let r={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()},h,k=T=>{h!==void 0&&(T.thinkingSignature=JSON.stringify(h))};try{let T=Ce(e.provider,t?.apiKey,t?.headers),a=q(e),m=N(j(u.messages),a.supportsOpenAIGrammarTools),M=Me(t?.cacheRetention,t?.env),g=M==="none"?void 0:t?.sessionId,i=Ke(e,u,T,t?.headers,t?.identity,t?.fetch,g,a),f=We(e,u,t,a,M,m),p=await t?.onPayload?.(f,e);p!==void 0&&(f=p);let R={...t?.signal?{signal:t.signal}:{},...t?.timeoutMs!==void 0?{timeout:t.timeoutMs}:{},maxRetries:0},{data:A,response:I}=await ne(()=>i.chat.completions.create(f,R).withResponse(),{maxRetries:t?.maxRetries,maxRetryDelayMs:t?.maxRetryDelayMs,signal:t?.signal});await t?.onResponse?.({status:I.status,headers:te(I.headers)},e),s.push({type:"start",partial:r});let O=null,E=null,S=!1,v=new Map,w=new Map,B=r.content,l=o=>B.indexOf(o),F=o=>{let c=o.customInput?.property;if(c===void 0)return"";let x=o.arguments[c];return typeof x=="string"?x:""},H=(o,c,x)=>{let d=o.customInput;if(!d)return;let C=oe(d.jsonBuffer,d.property,c,x);return o.arguments={[d.property]:c},C},Se=o=>{let c=l(o);if(c!==-1){if(o.type==="text")s.push({type:"text_end",contentIndex:c,content:o.text,partial:r});else if(o.type==="thinking")k(o),s.push({type:"thinking_end",contentIndex:c,content:o.thinking,partial:r});else if(o.type==="toolCall"){if(o.customInput){let x=H(o,F(o),!0);x!==void 0&&s.push({type:"toolcall_delta",contentIndex:c,delta:x,partial:r})}else Object.assign(o,X(o.partialArgs));delete o.partialArgs,delete o.customInput,delete o.streamIndex,s.push({type:"toolcall_end",contentIndex:c,toolCall:o,partial:r})}}},we=()=>(O||(O={type:"text",text:""},B.push(O),s.push({type:"text_start",contentIndex:l(O),partial:r})),O),K=o=>(E||(E={type:"thinking",thinking:"",thinkingSignature:o},B.push(E),s.push({type:"thinking_start",contentIndex:l(E),partial:r})),E),Fe=o=>{let c=typeof o.index=="number"?o.index:void 0,x=o.function?.name??o.custom?.name??"",d=c!==void 0?v.get(c):void 0;if(!d&&o.id&&(d=w.get(o.id)),!d){let C=o.custom&&!o.function?m.get(x)??"input":void 0,P=C!==void 0;d={type:"toolCall",id:o.id||"",name:x,arguments:P?{[C]:""}:{},partialArgs:P?void 0:"",customInput:P?{property:C,jsonBuffer:{input:"",started:!1,closed:!1}}:void 0,streamIndex:c},c!==void 0&&v.set(c,d),o.id&&w.set(o.id,d),B.push(d),s.push({type:"toolcall_start",contentIndex:l(d),partial:r})}if(c!==void 0&&d.streamIndex===void 0&&(d.streamIndex=c,v.set(c,d)),o.id&&w.set(o.id,d),!d.name&&x&&(d.name=x),o.custom&&!o.function&&!d.customInput){let C=m.get(d.name)??"input";d.arguments={[C]:""},d.customInput={property:C,jsonBuffer:{input:"",started:!1,closed:!1}},delete d.partialArgs}return d};for await(let o of A){if(await t?.onProviderStreamEvent?.(o,e),!o||typeof o!="object")continue;r.responseId||=o.id,typeof o.model=="string"&&o.model.length>0&&o.model!==e.id&&(r.responseModel||=o.model),o.usage&&(r.usage=Ae(o.usage,e));let c=Array.isArray(o.choices)?o.choices[0]:void 0;if(c){if(!o.usage&&c.usage&&(r.usage=Ae(c.usage,e)),c.finish_reason){r.rawStopReason=c.finish_reason;let x=rt(c.finish_reason);r.stopReason=x.stopReason,x.errorMessage&&(r.errorMessage=x.errorMessage),S=!0}if(c.delta){let x=["reasoning_content","reasoning","reasoning_text"],d=c.delta,C=null;for(let y of x){let _=d[y];if(typeof _=="string"&&_.length>0){C=y;break}}if(C){let y=d[C];if(typeof y=="string"&&y.length>0){let _=e.provider==="opencode-go"&&C==="reasoning"?"reasoning_content":C,L=K(_);L.thinking+=y,s.push({type:"thinking_delta",contentIndex:l(L),delta:y,partial:r})}}let P=c.delta.reasoning_details;if(Array.isArray(P))for(let y of P)$(y)&&(K(""),h??=[],Ge(h,y));if(c.delta.content!==null&&c.delta.content!==void 0&&c.delta.content.length>0){let y=we();y.text+=c.delta.content,s.push({type:"text_delta",contentIndex:l(y),delta:c.delta.content,partial:r})}if(c?.delta?.tool_calls)for(let y of c.delta.tool_calls){let _=Fe(y);!_.id&&y.id&&(_.id=y.id,w.set(y.id,_));let L=y.function?.name??y.custom?.name;!_.name&&L&&(_.name=L);let D="";if(y.function?.arguments)D=y.function.arguments,_.partialArgs=(_.partialArgs??"")+y.function.arguments,_.arguments=Y(_.partialArgs);else if(y.custom?.input){let Oe=F(_)+y.custom.input;D=H(_,Oe,!1)??""}s.push({type:"toolcall_delta",contentIndex:l(_),delta:D,partial:r})}}}}for(let o of B)Se(o);if(t?.signal?.aborted)throw new Error("Request was aborted");if(r.stopReason==="aborted")throw new Error("Request was aborted");if(!S&&!a.supportsFinishReason&&(r.stopReason=r.content.some(o=>o.type==="toolCall")?"toolUse":"stop"),r.stopReason==="error")throw new Error(r.errorMessage||"Provider returned an error stop reason");if(a.supportsFinishReason&&!S||r.stopReason==="pending")throw new Error("Stream ended without finish_reason");s.push({type:"done",reason:r.stopReason,message:r}),s.end()}catch(T){for(let m of r.content)m.type==="thinking"&&k(m),delete m.index,delete m.partialArgs,delete m.customInput,delete m.streamIndex;r.stopReason=t?.signal?.aborted?"aborted":"error",r.errorMessage=ye(me(T));let a=T?.error?.metadata?.raw;a&&!r.errorMessage.includes(String(a))&&(r.errorMessage+=`
4
+ import{a as ke}from"./chunk-XIECJESP.js";import{a as Te}from"./chunk-V3AQJSWR.js";import{a as he}from"./chunk-CVC66CFV.js";import{a as me,b as ye}from"./chunk-FF7UELTU.js";import{a as ue,b as fe}from"./chunk-BGYR4ID3.js";import{c as X,d as Y}from"./chunk-SKHLZ6XY.js";import{a as ee}from"./chunk-6R73ICDB.js";import{a as ne}from"./chunk-23PRJECN.js";import{a as se,b as re,c as oe,d as ie,e as ae,f as N,h as le,i as ce,k as pe,l as ge,o as de}from"./chunk-QBKCAIJG.js";import{C as j,F as G,J as Z,L as Q,o as U,p as V,y as z}from"./chunk-PZMGBKUR.js";import"./chunk-D6VMBA4C.js";import{a as b}from"./chunk-USBJFDJ6.js";import{a as te}from"./chunk-K4NTZEDJ.js";import{h as J}from"./chunk-6AKUD3CF.js";import"./chunk-OSEIQ7SS.js";import{b as W}from"./chunk-CXT5IR5T.js";import"./chunk-WHC7AYZD.js";function Re(e,n){if(!e)return!1;let t=n.toLowerCase();for(let[s,u]of Object.entries(e))if(s.toLowerCase()===t&&u!==null&&u.trim().length>0)return!0;return!1}function Ce(e,n,t){if(n)return n;if(Re(t,"authorization")||Re(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 xe(e){return e.type==="text"}function Be(e){return e.type==="thinking"}function Pe(e){return e.type==="toolCall"}function Le(e){return e.type==="image"}function qe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function De(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 $(e){if(!qe(e)||!De(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 ze(e){if(e)try{let n=JSON.parse(e);return Array.isArray(n)&&n.length>0&&n.every($)?n:void 0}catch{return}}function je(e){if(e)try{let n=JSON.parse(e);return $(n)&&n.type==="reasoning.encrypted"&&typeof n.id=="string"&&n.id.length>0&&n.data.length>0?n:void 0}catch{return}}function _e(e,n){e.id??=n.id,e.format||=n.format,e.index??=n.index}function Ge(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,_e(t,n);return}if(n.type==="reasoning.summary"&&t?.type==="reasoning.summary"){t.summary+=n.summary,_e(t,n);return}e.push({...n})}var Ne=["reasoning","reasoning_content","reasoning_text"];function $e(e){return Ne.includes(e)}function Me(e,n){return e||(ee("PI_CACHE_RETENTION",n)==="long"?"long":"short")}var He=(e,n,t)=>{let s=new W,u=z(n,q(e).supportsMidConvoSystemMessages);return(async()=>{let r={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()},h,k=T=>{h!==void 0&&(T.thinkingSignature=JSON.stringify(h))};try{let T=Ce(e.provider,t?.apiKey,t?.headers),a=q(e),m=N(j(u.messages),a.supportsOpenAIGrammarTools),M=Me(t?.cacheRetention,t?.env),g=M==="none"?void 0:t?.sessionId,i=Ke(e,u,T,t?.headers,t?.identity,t?.fetch,g,a),f=We(e,u,t,a,M,m),p=await t?.onPayload?.(f,e);p!==void 0&&(f=p);let R={...t?.signal?{signal:t.signal}:{},...t?.timeoutMs!==void 0?{timeout:t.timeoutMs}:{},maxRetries:0},{data:A,response:I}=await ne(()=>i.chat.completions.create(f,R).withResponse(),{maxRetries:t?.maxRetries,maxRetryDelayMs:t?.maxRetryDelayMs,signal:t?.signal});await t?.onResponse?.({status:I.status,headers:te(I.headers)},e),s.push({type:"start",partial:r});let O=null,E=null,S=!1,v=new Map,w=new Map,B=r.content,l=o=>B.indexOf(o),F=o=>{let c=o.customInput?.property;if(c===void 0)return"";let x=o.arguments[c];return typeof x=="string"?x:""},H=(o,c,x)=>{let d=o.customInput;if(!d)return;let C=oe(d.jsonBuffer,d.property,c,x);return o.arguments={[d.property]:c},C},Se=o=>{let c=l(o);if(c!==-1){if(o.type==="text")s.push({type:"text_end",contentIndex:c,content:o.text,partial:r});else if(o.type==="thinking")k(o),s.push({type:"thinking_end",contentIndex:c,content:o.thinking,partial:r});else if(o.type==="toolCall"){if(o.customInput){let x=H(o,F(o),!0);x!==void 0&&s.push({type:"toolcall_delta",contentIndex:c,delta:x,partial:r})}else Object.assign(o,X(o.partialArgs));delete o.partialArgs,delete o.customInput,delete o.streamIndex,s.push({type:"toolcall_end",contentIndex:c,toolCall:o,partial:r})}}},we=()=>(O||(O={type:"text",text:""},B.push(O),s.push({type:"text_start",contentIndex:l(O),partial:r})),O),K=o=>(E||(E={type:"thinking",thinking:"",thinkingSignature:o},B.push(E),s.push({type:"thinking_start",contentIndex:l(E),partial:r})),E),Fe=o=>{let c=typeof o.index=="number"?o.index:void 0,x=o.function?.name??o.custom?.name??"",d=c!==void 0?v.get(c):void 0;if(!d&&o.id&&(d=w.get(o.id)),!d){let C=o.custom&&!o.function?m.get(x)??"input":void 0,P=C!==void 0;d={type:"toolCall",id:o.id||"",name:x,arguments:P?{[C]:""}:{},partialArgs:P?void 0:"",customInput:P?{property:C,jsonBuffer:{input:"",started:!1,closed:!1}}:void 0,streamIndex:c},c!==void 0&&v.set(c,d),o.id&&w.set(o.id,d),B.push(d),s.push({type:"toolcall_start",contentIndex:l(d),partial:r})}if(c!==void 0&&d.streamIndex===void 0&&(d.streamIndex=c,v.set(c,d)),o.id&&w.set(o.id,d),!d.name&&x&&(d.name=x),o.custom&&!o.function&&!d.customInput){let C=m.get(d.name)??"input";d.arguments={[C]:""},d.customInput={property:C,jsonBuffer:{input:"",started:!1,closed:!1}},delete d.partialArgs}return d};for await(let o of A){if(await t?.onProviderStreamEvent?.(o,e),!o||typeof o!="object")continue;r.responseId||=o.id,typeof o.model=="string"&&o.model.length>0&&o.model!==e.id&&(r.responseModel||=o.model),o.usage&&(r.usage=Ae(o.usage,e));let c=Array.isArray(o.choices)?o.choices[0]:void 0;if(c){if(!o.usage&&c.usage&&(r.usage=Ae(c.usage,e)),c.finish_reason){r.rawStopReason=c.finish_reason;let x=rt(c.finish_reason);r.stopReason=x.stopReason,x.errorMessage&&(r.errorMessage=x.errorMessage),S=!0}if(c.delta){let x=["reasoning_content","reasoning","reasoning_text"],d=c.delta,C=null;for(let y of x){let _=d[y];if(typeof _=="string"&&_.length>0){C=y;break}}if(C){let y=d[C];if(typeof y=="string"&&y.length>0){let _=e.provider==="opencode-go"&&C==="reasoning"?"reasoning_content":C,L=K(_);L.thinking+=y,s.push({type:"thinking_delta",contentIndex:l(L),delta:y,partial:r})}}let P=c.delta.reasoning_details;if(Array.isArray(P))for(let y of P)$(y)&&(K(""),h??=[],Ge(h,y));if(c.delta.content!==null&&c.delta.content!==void 0&&c.delta.content.length>0){let y=we();y.text+=c.delta.content,s.push({type:"text_delta",contentIndex:l(y),delta:c.delta.content,partial:r})}if(c?.delta?.tool_calls)for(let y of c.delta.tool_calls){let _=Fe(y);!_.id&&y.id&&(_.id=y.id,w.set(y.id,_));let L=y.function?.name??y.custom?.name;!_.name&&L&&(_.name=L);let D="";if(y.function?.arguments)D=y.function.arguments,_.partialArgs=(_.partialArgs??"")+y.function.arguments,_.arguments=Y(_.partialArgs);else if(y.custom?.input){let Oe=F(_)+y.custom.input;D=H(_,Oe,!1)??""}s.push({type:"toolcall_delta",contentIndex:l(_),delta:D,partial:r})}}}}for(let o of B)Se(o);if(t?.signal?.aborted)throw new Error("Request was aborted");if(r.stopReason==="aborted")throw new Error("Request was aborted");if(!S&&!a.supportsFinishReason&&(r.stopReason=r.content.some(o=>o.type==="toolCall")?"toolUse":"stop"),r.stopReason==="error")throw new Error(r.errorMessage||"Provider returned an error stop reason");if(a.supportsFinishReason&&!S||r.stopReason==="pending")throw new Error("Stream ended without finish_reason");s.push({type:"done",reason:r.stopReason,message:r}),s.end()}catch(T){for(let m of r.content)m.type==="thinking"&&k(m),delete m.index,delete m.partialArgs,delete m.customInput,delete m.streamIndex;r.stopReason=t?.signal?.aborted?"aborted":"error",r.errorMessage=ye(me(T));let a=T?.error?.metadata?.raw;a&&!r.errorMessage.includes(String(a))&&(r.errorMessage+=`
5
5
  ${a}`),s.push({type:"error",reason:r.stopReason,error:r}),s.end()}})(),s},At=(e,n,t)=>{Ce(e.provider,t?.apiKey,t?.headers);let s={...ce(e,n,t,t?.apiKey),toolChoice:t?.toolChoice},u=t?.reasoning?Q(e,t.reasoning):void 0;return He(e,n,{...s,reasoningEffort:u==="off"?void 0:u,thinkingBudgets:t?.thinkingBudgets})};function Ke(e,n,t,s,u,r,h,k=q(e)){let T={...J(e,u),...e.headers};if(e.provider==="github-copilot"){let a=ue(n.messages),m=fe({messages:n.messages,hasImages:a});Object.assign(T,m)}return h&&k.sendSessionAffinityHeaders&&(k.sessionAffinityFormat==="openrouter"?T["x-session-id"]=h:(k.sessionAffinityFormat==="openai"&&(T.session_id=h),T["x-client-request-id"]=h,T["x-session-affinity"]=h)),s&&Object.assign(T,s),new he({apiKey:t,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:r,defaultHeaders:T})}function We(e,n,t,s=q(e),u=Me(t?.cacheRetention,t?.env),r=N(j(n.messages),s.supportsOpenAIGrammarTools)){let h=G(n.messages,s.supportsMidConvoSystemMessages===!0&&s.supportsMidConvoToolAdditions===!0?"additions":"none"),k=st(e,n,s,{grammarToolInputProperties:r}),T=Ze(s,u),a={model:e.id,messages:k,stream:!0,prompt_cache_key:e.baseUrl.includes("api.openai.com")&&u!=="none"||u==="long"&&s.supportsLongCacheRetention?ke(t?.sessionId):void 0,prompt_cache_retention:u==="long"&&s.supportsLongCacheRetention?"24h":void 0};s.supportsUsageInStreaming!==!1&&(a.stream_options={include_usage:!0}),s.supportsStore&&(a.store=!1),t?.maxTokens&&(s.maxTokensField==="max_tokens"?a.max_tokens=t.maxTokens:a.max_completion_tokens=t.maxTokens),t?.temperature!==void 0&&(a.temperature=t.temperature),h.requestTools.length>0?(a.tools=Ee(h.requestTools,s),s.zaiToolStream&&(a.tool_stream=!0)):be(n.messages)&&(a.tools=[]),T&&Qe(k,a.tools,T),t?.toolChoice&&(a.tool_choice=t.toolChoice),s.vllmPriority!==void 0&&(a.priority=s.vllmPriority);let m=Je(s),M=Ue(e,t,a);if(s.thinkingFormat==="zai"&&e.reasoning){let i=a;if(i.thinking=t?.reasoningEffort?{type:"enabled",clear_thinking:!1}:{type:"disabled"},t?.reasoningEffort&&s.supportsReasoningEffort){let f=e.thinkingLevelMap?.[t.reasoningEffort],p=f===void 0?t.reasoningEffort:f;typeof p=="string"&&(i.reasoning_effort=p)}}else if(s.thinkingFormat==="qwen"&&e.reasoning){if(a.enable_thinking=!!t?.reasoningEffort,t?.reasoningEffort&&s.supportsReasoningEffort){let i=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort;typeof i=="string"&&(a.reasoning_effort=i)}}else if(s.thinkingFormat==="qwen-chat-template"&&e.reasoning)a.chat_template_kwargs={enable_thinking:!!t?.reasoningEffort,preserve_thinking:!0};else if(s.thinkingFormat==="chat-template"&&e.reasoning){let i=ve(e,t,s.chatTemplateKwargs,M);i&&(a.chat_template_kwargs=i)}else if(s.thinkingFormat==="baseten"&&e.reasoning){let i=a,f=ve(e,t,s.chatTemplateArgs,M);if(f&&(i.chat_template_args=f),s.supportsReasoningEffort){let p=t?.reasoningEffort,R=p?e.thinkingLevelMap?.[p]:e.thinkingLevelMap?.off,A=R===void 0?p:R;typeof A=="string"&&(i.reasoning_effort=A)}}else if(s.thinkingFormat==="deepseek"&&e.reasoning)t?.reasoningEffort?a.thinking={type:"enabled"}:e.thinkingLevelMap?.off!==null&&(a.thinking={type:"disabled"}),t?.reasoningEffort&&s.supportsReasoningEffort&&(a.reasoning_effort=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort);else if(s.thinkingFormat==="openrouter"&&e.reasoning){let i=a;t?.reasoningEffort?i.reasoning={effort:e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort}:e.thinkingLevelMap?.off!==null&&(i.reasoning={effort:e.thinkingLevelMap?.off??"none"})}else if(s.thinkingFormat==="ant-ling"&&e.reasoning&&t?.reasoningEffort){let i=e.thinkingLevelMap?.[t.reasoningEffort];typeof i=="string"&&(a.reasoning={effort:i})}else if(s.thinkingFormat==="together"&&e.reasoning){let i=a;i.reasoning={enabled:!!t?.reasoningEffort},t?.reasoningEffort&&s.supportsReasoningEffort&&(i.reasoning_effort=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort)}else if(s.thinkingFormat==="string-thinking"&&e.reasoning){let i=a;t?.reasoningEffort?i.thinking=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort:e.thinkingLevelMap?.off!==null&&(i.thinking=e.thinkingLevelMap?.off??"none")}else if(t?.reasoningEffort&&e.reasoning&&s.supportsReasoningEffort)a.reasoning_effort=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort;else if(!t?.reasoningEffort&&e.reasoning&&s.supportsReasoningEffort){let i=e.thinkingLevelMap?.off;typeof i=="string"&&(a.reasoning_effort=i)}if(m&&M!==void 0&&Object.assign(a,{[m]:M}),e.compat?.openRouterRouting&&(a.provider=e.compat.openRouterRouting),e.compat?.vercelGatewayRouting){let i=e.compat.vercelGatewayRouting;if(i.only||i.order){let f={};i.only&&(f.only=i.only),i.order&&(f.order=i.order),a.providerOptions={gateway:f}}}let g=le(e,t?.reasoningEffort??"off",t?.samplingParams);return g&&Object.assign(a,g),a}function Je(e){if(e.thinkingTokenBudgetField)return e.thinkingTokenBudgetField;if(e.supportsThinkingTokenBudget)return"thinking_token_budget"}function Ue(e,n,t){if(!n?.reasoningEffort||!e.reasoning)return;let s=t.max_tokens??t.max_completion_tokens??e.maxTokens,u=ge(pe(n.reasoningEffort,n.thinkingBudgets),s);return u>0?u:void 0}function ve(e,n,t,s){let u={};for(let[r,h]of Object.entries(t)){let k=Ve(e,n,h,s);k!==void 0&&(u[r]=k)}return Object.keys(u).length>0?u:void 0}function Ve(e,n,t,s){if(typeof t!="object"||t===null)return t;let u=n?.reasoningEffort;if(!u&&t.omitWhenOff)return;if(t.$var==="thinking.enabled")return!!u;if(t.$var==="thinking.budget")return s;let r=u?e.thinkingLevelMap?.[u]:e.thinkingLevelMap?.off;return r===void 0?u:typeof r=="string"?r:void 0}function Ze(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 Qe(e,n,t){Xe(e,t),et(n,t),Ye(e,t)}function Xe(e,n){for(let t of e)if(t.role==="system"||t.role==="developer"){tt(t,n);return}}function Ye(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")&&nt(s,n))return}}function et(e,n){if(!e||e.length===0)return;let t=e[e.length-1];t.cache_control=n}function tt(e,n){return Ie(e,n)}function nt(e,n){return e.role==="user"||e.role==="assistant"||e.role==="tool"?Ie(e,n):!1}function Ie(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 u=t[s];if(u?.type==="text"){let r=u;return r.cache_control=n,!0}}return!1}function st(e,n,t,s){let u=z(n,t.supportsMidConvoSystemMessages),r=[],h=g=>{if(g.includes("|")){let i=g.indexOf("|"),f=g.slice(0,i).replace(/[^a-zA-Z0-9_-]/g,"_"),p=g.slice(i+1).replace(/[^a-zA-Z0-9_-]/g,"_"),R=p.length>0?`${f}_${p}`:f;if(R.length<=40)return R;let A=Te(g).slice(0,8);return`${f.slice(0,Math.max(1,40-A.length-1))}_${A}`}return e.provider==="openai"&&g.length>40?g.slice(0,40):g},k=de(u.messages,e,g=>h(g)),T=G(u.messages,t.supportsMidConvoSystemMessages===!0&&t.supportsMidConvoToolAdditions===!0?"additions":"none"),a=e.reasoning&&t.supportsDeveloperRole?"developer":"system",m=null,M=0;for(let g=0;g<k.length;g++){let i=k[g];if(t.requiresAssistantAfterToolResult&&m==="toolResult"&&i.role==="user"&&r.push({role:"assistant",content:"I have processed the tool results."}),i.role==="system"){let f=M++>=T.foldedSystemMessages?i.toolsAdded??[]:[];if(f.length>0){let R={role:"system",tools:Ee(f,t)};r.push(R)}let p=g===0?U(i):V(i);p.length>0&&r.push({role:a,content:b(p)})}else if(i.role==="user")if(typeof i.content=="string")r.push({role:"user",content:b(i.content)});else{let f=i.content.filter(p=>p.type!=="text"||p.text.length>0).map(p=>p.type==="text"?{type:"text",text:b(p.text)}:{type:"image_url",image_url:{url:`data:${p.mimeType};base64,${p.data}`}});if(f.length===0)continue;r.push({role:"user",content:f})}else if(i.role==="assistant"){let f={role:"assistant",content:t.requiresAssistantAfterToolResult?"":null},p=i.content.filter(xe).filter(l=>l.text.trim().length>0).map(l=>({type:"text",text:b(l.text)})),R=p.map(l=>l.text).join(""),A=i.content.filter(Be),I=i.content.filter(Pe),O=A.map(l=>ze(l.thinkingSignature)).find(l=>l!==void 0),E=I.map(l=>je(l.thoughtSignature)).filter(l=>l!==void 0),S=O??(E.length>0?E:void 0),v=A.filter(l=>l.thinking.trim().length>0);if(v.length>0){if(t.requiresThinkingAsText){let l=v.map(F=>b(F.thinking)).join(`
6
6
 
7
7
  `);f.content=[{type:"text",text:l},...p]}else if(R.length>0&&(f.content=R),!S){let l=v[0].thinkingSignature;e.provider==="opencode-go"&&l==="reasoning"&&(l="reasoning_content"),l&&$e(l)&&(f[l]=v.map(F=>F.thinking).join(`
@@ -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"./chunk-23PRJECN.js";import{a as p,b as f}from"./chunk-FF7UELTU.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-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}
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};
@@ -1,6 +1,6 @@
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 A,b as O}from"./chunk-BGYR4ID3.js";import{a as G,b as U,c as N,d as D}from"./chunk-DXBSQXJL.js";import{a as L}from"./chunk-XIECJESP.js";import"./chunk-V3AQJSWR.js";import{a as x}from"./chunk-CVC66CFV.js";import{a as _}from"./chunk-23PRJECN.js";import{a as k,b}from"./chunk-FF7UELTU.js";import{f as P,h as I,i as w}from"./chunk-QBKCAIJG.js";import{C as y,F as C,L as M,y as R}from"./chunk-PZMGBKUR.js";import{a as E}from"./chunk-6R73ICDB.js";import"./chunk-SKHLZ6XY.js";import"./chunk-D6VMBA4C.js";import"./chunk-USBJFDJ6.js";import{a as S}from"./chunk-K4NTZEDJ.js";import{h as v}from"./chunk-6AKUD3CF.js";import"./chunk-OSEIQ7SS.js";import{b as T}from"./chunk-CXT5IR5T.js";import"./chunk-WHC7AYZD.js";var V=new Set(["openai","openai-codex","opencode"]),B=16,J="https://chatgpt.com/settings/usage",Q="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.",Y="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,a]of Object.entries(e))if(s.toLowerCase()===r&&a!==null&&a.trim().length>0)return!0;return!1}function K(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 q(e,t){return e||(E("PI_CACHE_RETENTION",t)==="long"?"long":"short")}function g(e){return{supportsDeveloperRole:e.compat?.supportsDeveloperRole??!0,supportsMidConvoSystemMessages:e.compat?.supportsMidConvoSystemMessages??!1,sessionAffinityFormat:e.compat?.sessionAffinityFormat??X(e),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 T,a=R(t,g(e).supportsMidConvoSystemMessages);return(async()=>{let u=g(e),c=Z(e,r,u),o={role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,...c===void 0?{}:{providerThinkingLevel:c},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 i=K(e.provider,r?.apiKey,r?.headers),n=q(r?.cacheRetention,r?.env)==="none"?void 0:r?.sessionId,f=P(y(a.messages),u.supportsOpenAIGrammarTools),l=se(e,a,i,r?.headers,r?.identity,r?.fetch,n),d=oe(e,a,r,u,f,c),m=await r?.onPayload?.(d,e);m!==void 0&&(d=m);let W={...r?.signal?{signal:r.signal}:{},...r?.timeoutMs!==void 0?{timeout:r.timeoutMs}:{},maxRetries:0},{data:$,response:h}=await _(()=>l.responses.create(d,W).withResponse(),{maxRetries:r?.maxRetries,maxRetryDelayMs:r?.maxRetryDelayMs,signal:r?.signal});if(await r?.onResponse?.({status:h.status,headers:S(h.headers)},e),s.push({type:"start",partial:o}),await D($,o,s,e,{onProviderStreamEvent:r?.onProviderStreamEvent,serviceTier:r?.serviceTier,grammarToolInputProperties:f,applyServiceTierPricing:(j,z)=>ie(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(i){for(let n of o.content)delete n.index,delete n.partialJson,delete n.customInput;o.stopReason=r?.signal?.aborted?"aborted":"error";let p=b(k(i),`${e.provider==="openai"?"OpenAI":e.provider} API error`);p.includes("subscription_sharing_usage_limit_exceeded")?o.errorMessage=`${p}
4
+ import{a as G,b as U,c as N,d as D}from"./chunk-7GAYFN52.js";import{a as L}from"./chunk-XIECJESP.js";import"./chunk-V3AQJSWR.js";import{a as x}from"./chunk-CVC66CFV.js";import{a as k,b}from"./chunk-FF7UELTU.js";import{a as A,b as O}from"./chunk-BGYR4ID3.js";import"./chunk-SKHLZ6XY.js";import{a as E}from"./chunk-6R73ICDB.js";import{a as _}from"./chunk-23PRJECN.js";import{f as P,h as I,i as w}from"./chunk-QBKCAIJG.js";import{C as y,F as C,L as M,y as R}from"./chunk-PZMGBKUR.js";import"./chunk-D6VMBA4C.js";import"./chunk-USBJFDJ6.js";import{a as S}from"./chunk-K4NTZEDJ.js";import{h as v}from"./chunk-6AKUD3CF.js";import"./chunk-OSEIQ7SS.js";import{b as T}from"./chunk-CXT5IR5T.js";import"./chunk-WHC7AYZD.js";var V=new Set(["openai","openai-codex","opencode"]),B=16,J="https://chatgpt.com/settings/usage",Q="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.",Y="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,a]of Object.entries(e))if(s.toLowerCase()===r&&a!==null&&a.trim().length>0)return!0;return!1}function K(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 q(e,t){return e||(E("PI_CACHE_RETENTION",t)==="long"?"long":"short")}function g(e){return{supportsDeveloperRole:e.compat?.supportsDeveloperRole??!0,supportsMidConvoSystemMessages:e.compat?.supportsMidConvoSystemMessages??!1,sessionAffinityFormat:e.compat?.sessionAffinityFormat??X(e),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 T,a=R(t,g(e).supportsMidConvoSystemMessages);return(async()=>{let u=g(e),c=Z(e,r,u),o={role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,...c===void 0?{}:{providerThinkingLevel:c},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 i=K(e.provider,r?.apiKey,r?.headers),n=q(r?.cacheRetention,r?.env)==="none"?void 0:r?.sessionId,f=P(y(a.messages),u.supportsOpenAIGrammarTools),l=se(e,a,i,r?.headers,r?.identity,r?.fetch,n),d=oe(e,a,r,u,f,c),m=await r?.onPayload?.(d,e);m!==void 0&&(d=m);let W={...r?.signal?{signal:r.signal}:{},...r?.timeoutMs!==void 0?{timeout:r.timeoutMs}:{},maxRetries:0},{data:$,response:h}=await _(()=>l.responses.create(d,W).withResponse(),{maxRetries:r?.maxRetries,maxRetryDelayMs:r?.maxRetryDelayMs,signal:r?.signal});if(await r?.onResponse?.({status:h.status,headers:S(h.headers)},e),s.push({type:"start",partial:o}),await D($,o,s,e,{onProviderStreamEvent:r?.onProviderStreamEvent,serviceTier:r?.serviceTier,grammarToolInputProperties:f,applyServiceTierPricing:(j,z)=>ie(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(i){for(let n of o.content)delete n.index,delete n.partialJson,delete n.customInput;o.stopReason=r?.signal?.aborted?"aborted":"error";let p=b(k(i),`${e.provider==="openai"?"OpenAI":e.provider} API error`);p.includes("subscription_sharing_usage_limit_exceeded")?o.errorMessage=`${p}
5
5
  Check your ChatGPT usage: ${J}`:p.includes("subscription_sharing_workplace_individual_usage_limit_exceeded")?o.errorMessage=`${p}
6
6
  ${Q}`:o.errorMessage=p,s.push({type:"error",reason:o.stopReason,error:o}),s.end()}})(),s},Ce=(e,t,r)=>{K(e.provider,r?.apiKey,r?.headers);let s={...w(e,t,r,r?.apiKey),toolChoice:r?.toolChoice},a=r?.reasoning?M(e,r.reasoning):void 0;return te(e,t,{...s,reasoningEffort:a==="off"?void 0:a})};function se(e,t,r,s,a,u,c){let o=g(e),i={...v(e,a),...e.headers};if(e.provider==="github-copilot"){let p=A(t.messages),n=O({messages:t.messages,hasImages:p});Object.assign(i,n)}return c&&(o.sessionAffinityFormat==="openrouter"?i["x-session-id"]=c:(o.sessionAffinityFormat==="openai"&&(i.session_id=c),i["x-client-request-id"]=c)),s&&Object.assign(i,s),new x({apiKey:r,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:u,defaultHeaders:i})}function oe(e,t,r,s,a,u){let c=C(t.messages,G(s)),o=U(e,t,V,{grammarToolInputProperties:a,supportsMidConvoSystemMessages:s.supportsMidConvoSystemMessages,supportsAdditionalTools:s.supportsAdditionalTools,supportsToolSearch:s.supportsToolSearch,toolOptions:{supportsStrictMode:s.supportsStrictMode,supportsOpenAIGrammarTools:s.supportsOpenAIGrammarTools},configurationUpdateEffort:u}),i=q(r?.cacheRetention,r?.env),p=H(e,r?.apiKey),n={model:e.id,input:o,stream:!0,prompt_cache_key:i==="none"?void 0:L(r?.sessionId),prompt_cache_retention:p?void 0:ee(s,i),prompt_cache_options:p?void 0:re(s,i),store:!1};r?.maxTokens&&s.supportsMaxOutputTokens&&!p&&(n.max_output_tokens=Math.max(r.maxTokens,B)),r?.temperature!==void 0&&!p&&(n.temperature=r?.temperature),r?.serviceTier!==void 0&&(n.service_tier=r.serviceTier),c.requestTools.length>0&&(n.tools=N(c.requestTools,{supportsStrictMode:s.supportsStrictMode,supportsOpenAIGrammarTools:s.supportsOpenAIGrammarTools})),r?.toolChoice!==void 0&&(n.tool_choice=r.toolChoice);let f=r?.reasoningEffort??(r?.reasoningSummary?"medium":void 0);if(e.reasoning){if(f){let d=r?.reasoningEffort?e.thinkingLevelMap?.[r.reasoningEffort]??r.reasoningEffort:f,m=u===void 0?d:Y;n.reasoning={effort:m,summary:r?.reasoningSummary||"auto"},n.include=["reasoning.encrypted_content"]}else e.provider!=="github-copilot"&&e.thinkingLevelMap?.off!==null&&(n.reasoning={effort:e.thinkingLevelMap?.off??"none"});e.provider==="xai"&&(n.include=["reasoning.encrypted_content"])}let l=I(e,f??"off",r?.samplingParams);return l&&Object.assign(n,l),n}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 ie(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,Ce as streamSimple};
@@ -1,4 +1,4 @@
1
1
  import { createRequire as __cortexCreateRequire } from 'node:module';
2
2
  const require = __cortexCreateRequire(import.meta.url);
3
3
  const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{a as k}from"./chunk-CVC66CFV.js";import{a as x}from"./chunk-23PRJECN.js";import{a as w,b as T}from"./chunk-FF7UELTU.js";import{a as _}from"./chunk-USBJFDJ6.js";import{a as y,b as R}from"./chunk-K4NTZEDJ.js";import{h as l}from"./chunk-6AKUD3CF.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=b(e,a,t?.headers,t?.fetch,t?.identity),n=M(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:v,response:g}=await x(()=>i.chat.completions.create(n,o).withResponse(),{maxRetries:t?.maxRetries,maxRetryDelayMs:t?.maxRetryDelayMs,signal:t?.signal});await t?.onResponse?.({status:g.status,headers:y(g.headers)},e);let u=v;r.responseId=u.id,u.usage&&(r.usage=P(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=T(w(a)),r}};function b(e,s,t,r,a){return new k({apiKey:s,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:r,defaultHeaders:R(l(e,a),e.headers,t)})}function M(e,s){let t=s.input.map(r=>r.type==="text"?{type:"text",text:_(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 P(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}};return o.cost.total=o.cost.input+o.cost.output+o.cost.cacheRead+o.cost.cacheWrite,o}export{H as generateImages};
4
+ import{a as k}from"./chunk-CVC66CFV.js";import{a as w,b as T}from"./chunk-FF7UELTU.js";import{a as x}from"./chunk-23PRJECN.js";import{a as _}from"./chunk-USBJFDJ6.js";import{a as y,b as R}from"./chunk-K4NTZEDJ.js";import{h as l}from"./chunk-6AKUD3CF.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=b(e,a,t?.headers,t?.fetch,t?.identity),n=M(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:v,response:g}=await x(()=>i.chat.completions.create(n,o).withResponse(),{maxRetries:t?.maxRetries,maxRetryDelayMs:t?.maxRetryDelayMs,signal:t?.signal});await t?.onResponse?.({status:g.status,headers:y(g.headers)},e);let u=v;r.responseId=u.id,u.usage&&(r.usage=P(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=T(w(a)),r}};function b(e,s,t,r,a){return new k({apiKey:s,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:r,defaultHeaders:R(l(e,a),e.headers,t)})}function M(e,s){let t=s.input.map(r=>r.type==="text"?{type:"text",text:_(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 P(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}};return o.cost.total=o.cost.input+o.cost.output+o.cost.cacheRead+o.cost.cacheWrite,o}export{H as generateImages};
@@ -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 y}from"./chunk-6R73ICDB.js";import{d as x}from"./chunk-SKHLZ6XY.js";import{c as h,d as p}from"./chunk-D6VMBA4C.js";import{a as k,b as w}from"./chunk-K4NTZEDJ.js";import{h as m}from"./chunk-6AKUD3CF.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 R(r){return r.length>8192?`${r.slice(0,8192)}\u2026`:r}function S(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,a=e??t,o=s?` (${s})`:"";return`${r.status} ${r.statusText}: ${a}${o}`}function _(r,t,n,e){let s=T(e),a=typeof s?.error?.code=="string"?s.error.code:void 0;return new g(S(n,e,s),a,{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:R(e)},timestampMs:Date.now()})}function E(){return{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}function b(r,t){t&&p(r,{type:"pi_messages_rewrite",timestamp:Date.now(),details:{...t}})}function M(r){let t={role:"assistant",content:[],api:r.api,provider:r.provider,model:r.id,usage:E(),stopReason:"pending",timestamp:Date.now()},n=new Map;return e=>{switch(e.type){case"done":return Object.assign(t,{stopReason:e.reason,usage:e.usage,responseId:e.responseId}),e.providerThinkingLevel!==void 0&&(t.providerThinkingLevel=e.providerThinkingLevel),b(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.providerThinkingLevel!==void 0&&(t.providerThinkingLevel=e.providerThinkingLevel),b(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,"");break;case"toolcall_delta":{let s=`${n.get(e.contentIndex)??""}${e.delta}`;n.set(e.contentIndex,s),t.content[e.contentIndex].arguments=x(s);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:a}=await n.read();e+=s?t.decode():t.decode(a,{stream:!0}),e=e.replace(/\r\n/g,`
4
+ import{d as x}from"./chunk-SKHLZ6XY.js";import{a as y}from"./chunk-6R73ICDB.js";import{c as h,d as p}from"./chunk-D6VMBA4C.js";import{a as k,b as w}from"./chunk-K4NTZEDJ.js";import{h as m}from"./chunk-6AKUD3CF.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 R(r){return r.length>8192?`${r.slice(0,8192)}\u2026`:r}function S(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,a=e??t,o=s?` (${s})`:"";return`${r.status} ${r.statusText}: ${a}${o}`}function _(r,t,n,e){let s=T(e),a=typeof s?.error?.code=="string"?s.error.code:void 0;return new g(S(n,e,s),a,{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:R(e)},timestampMs:Date.now()})}function E(){return{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}function b(r,t){t&&p(r,{type:"pi_messages_rewrite",timestamp:Date.now(),details:{...t}})}function M(r){let t={role:"assistant",content:[],api:r.api,provider:r.provider,model:r.id,usage:E(),stopReason:"pending",timestamp:Date.now()},n=new Map;return e=>{switch(e.type){case"done":return Object.assign(t,{stopReason:e.reason,usage:e.usage,responseId:e.responseId}),e.providerThinkingLevel!==void 0&&(t.providerThinkingLevel=e.providerThinkingLevel),b(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.providerThinkingLevel!==void 0&&(t.providerThinkingLevel=e.providerThinkingLevel),b(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,"");break;case"toolcall_delta":{let s=`${n.get(e.contentIndex)??""}${e.delta}`;n.set(e.contentIndex,s),t.content[e.contentIndex].arguments=x(s);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:a}=await n.read();e+=s?t.decode():t.decode(a,{stream:!0}),e=e.replace(/\r\n/g,`
5
5
  `);let o=e.indexOf(`
6
6
 
7
7
  `);for(;o!==-1;){let c=I(e.slice(0,o));c&&(yield c),e=e.slice(o+2),o=e.indexOf(`
@@ -1,4 +1,4 @@
1
1
  import { createRequire as __cortexCreateRequire } from 'node:module';
2
2
  const require = __cortexCreateRequire(import.meta.url);
3
3
  const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{b as _}from"./chunk-WEZWKMYU.js";import{a as p}from"./chunk-XBJOYU5Y.js";import{a as w}from"./chunk-XAXWLYH5.js";import"./chunk-IRWZ7UPF.js";import{a as f}from"./chunk-ILEML5IP.js";import"./chunk-WHC7AYZD.js";var v="127.0.0.1",m=1456,E="/oauth/callback",d=`http://${v}:${m}${E}`,A=6e4,g="browser",y="device-code",a="pi-gateway",O="gateway offline_access",S="urn:ietf:params:oauth:grant-type:device_code";async function L(o,r){let e=await fetch(new URL("/v1/oauth",o),{headers:{accept:"application/json"},signal:r});if(!e.ok)throw new Error(`Could not load Radius OAuth config from ${o}: ${e.status} ${await e.text()}`);let t=await e.json();if(typeof t.authorizationEndpoint!="string")throw new Error(`Invalid Radius OAuth config from ${o}`);return{authorizationEndpoint:t.authorizationEndpoint}}var c=class extends Error{status;oauthError;constructor(r,e,t,n){let i=e?t?`${e}: ${t}`:e:t||String(r);super(`${n}: ${i}`),this.status=r,this.oauthError=e}};async function R(o,r){let e=await o.text().catch(()=>""),t,n;if(e)try{let i=JSON.parse(e);t=typeof i.error=="string"?i.error:void 0,n=typeof i.error_description=="string"?i.error_description:void 0}catch{n=e}return new c(o.status,t,n,r)}async function u(o,r,e){let t;try{t=await fetch(new URL("/v1/oauth/token",o),{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:r,signal:e})}catch(i){throw e.aborted?new Error("Login cancelled"):i}if(!t.ok)throw await R(t,"Radius OAuth token request failed");let n=await t.json();return{type:"oauth",access:n.access_token,refresh:n.refresh_token,expires:Date.now()+n.expires_in*1e3-A,scope:n.scope}}async function C(o,r,e){let{verifier:t,challenge:n}=await w(),i=crypto.randomUUID(),l=new URL(r);l.search=new URLSearchParams({response_type:"code",client_id:a,redirect_uri:d,scope:O,code_challenge:n,code_challenge_method:"S256",handoff:"url",state:i}).toString();let h=await p({providerName:"Radius",host:v,port:m,path:E,state:i,complete:s=>u(o,new URLSearchParams({grant_type:"authorization_code",client_id:a,redirect_uri:d,code:s,code_verifier:t}),e.signal),signal:e.signal});e.notify({type:"progress",message:`Listening for OAuth callback on ${d}`}),e.notify({type:"auth_url",url:l.toString(),instructions:"Continue in your browser."});try{let s=await h.wait();if(!s)throw new Error("OAuth callback did not complete.");return s}finally{h.close()}}async function U(o,r){let e;try{e=await fetch(new URL("/v1/oauth/device",o),{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:a,scope:O}),signal:r})}catch(n){throw r.aborted?new Error("Login cancelled"):n}if(!e.ok)throw await R(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");return{device_code:t.device_code,user_code:t.user_code,verification_uri:t.verification_uri,expires_in:t.expires_in,interval:t.interval}}async function x(o,r){let e=await U(o,r.signal);return r.notify({type:"device_code",userCode:e.user_code,verificationUri:e.verification_uri,intervalSeconds:e.interval,expiresInSeconds:e.expires_in}),f({intervalSeconds:e.interval,expiresInSeconds:e.expires_in,signal:r.signal,poll:async()=>{try{return{status:"complete",value:await u(o,new URLSearchParams({grant_type:S,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 b(o){let r=_(o.gateway);return{name:o.name,async login(e){let t=await e.prompt({type:"select",message:`Sign in to ${o.name}:`,options:[{id:g,label:"Sign in with browser (recommended)"},{id:y,label:"Sign in with device code (when signing in from another device)"}]});if(t===y)return x(r,e);if(t===g){let n=await L(r,e.signal);return C(r,n.authorizationEndpoint,e)}throw new Error(`Unknown ${o.name} sign-in method: ${t}`)},async refresh(e,t){return await u(r,new URLSearchParams({grant_type:"refresh_token",client_id:a,refresh_token:e.refresh}),t)},async toAuth(e){return{apiKey:e.access}}}}export{b as createRadiusOAuth};
4
+ import{b as _}from"./chunk-WEZWKMYU.js";import{a as f}from"./chunk-ILEML5IP.js";import{a as p}from"./chunk-XBJOYU5Y.js";import{a as w}from"./chunk-XAXWLYH5.js";import"./chunk-IRWZ7UPF.js";import"./chunk-WHC7AYZD.js";var v="127.0.0.1",m=1456,E="/oauth/callback",d=`http://${v}:${m}${E}`,A=6e4,g="browser",y="device-code",a="pi-gateway",O="gateway offline_access",S="urn:ietf:params:oauth:grant-type:device_code";async function L(o,r){let e=await fetch(new URL("/v1/oauth",o),{headers:{accept:"application/json"},signal:r});if(!e.ok)throw new Error(`Could not load Radius OAuth config from ${o}: ${e.status} ${await e.text()}`);let t=await e.json();if(typeof t.authorizationEndpoint!="string")throw new Error(`Invalid Radius OAuth config from ${o}`);return{authorizationEndpoint:t.authorizationEndpoint}}var c=class extends Error{status;oauthError;constructor(r,e,t,n){let i=e?t?`${e}: ${t}`:e:t||String(r);super(`${n}: ${i}`),this.status=r,this.oauthError=e}};async function R(o,r){let e=await o.text().catch(()=>""),t,n;if(e)try{let i=JSON.parse(e);t=typeof i.error=="string"?i.error:void 0,n=typeof i.error_description=="string"?i.error_description:void 0}catch{n=e}return new c(o.status,t,n,r)}async function u(o,r,e){let t;try{t=await fetch(new URL("/v1/oauth/token",o),{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:r,signal:e})}catch(i){throw e.aborted?new Error("Login cancelled"):i}if(!t.ok)throw await R(t,"Radius OAuth token request failed");let n=await t.json();return{type:"oauth",access:n.access_token,refresh:n.refresh_token,expires:Date.now()+n.expires_in*1e3-A,scope:n.scope}}async function C(o,r,e){let{verifier:t,challenge:n}=await w(),i=crypto.randomUUID(),l=new URL(r);l.search=new URLSearchParams({response_type:"code",client_id:a,redirect_uri:d,scope:O,code_challenge:n,code_challenge_method:"S256",handoff:"url",state:i}).toString();let h=await p({providerName:"Radius",host:v,port:m,path:E,state:i,complete:s=>u(o,new URLSearchParams({grant_type:"authorization_code",client_id:a,redirect_uri:d,code:s,code_verifier:t}),e.signal),signal:e.signal});e.notify({type:"progress",message:`Listening for OAuth callback on ${d}`}),e.notify({type:"auth_url",url:l.toString(),instructions:"Continue in your browser."});try{let s=await h.wait();if(!s)throw new Error("OAuth callback did not complete.");return s}finally{h.close()}}async function U(o,r){let e;try{e=await fetch(new URL("/v1/oauth/device",o),{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:a,scope:O}),signal:r})}catch(n){throw r.aborted?new Error("Login cancelled"):n}if(!e.ok)throw await R(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");return{device_code:t.device_code,user_code:t.user_code,verification_uri:t.verification_uri,expires_in:t.expires_in,interval:t.interval}}async function x(o,r){let e=await U(o,r.signal);return r.notify({type:"device_code",userCode:e.user_code,verificationUri:e.verification_uri,intervalSeconds:e.interval,expiresInSeconds:e.expires_in}),f({intervalSeconds:e.interval,expiresInSeconds:e.expires_in,signal:r.signal,poll:async()=>{try{return{status:"complete",value:await u(o,new URLSearchParams({grant_type:S,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 b(o){let r=_(o.gateway);return{name:o.name,async login(e){let t=await e.prompt({type:"select",message:`Sign in to ${o.name}:`,options:[{id:g,label:"Sign in with browser (recommended)"},{id:y,label:"Sign in with device code (when signing in from another device)"}]});if(t===y)return x(r,e);if(t===g){let n=await L(r,e.signal);return C(r,n.authorizationEndpoint,e)}throw new Error(`Unknown ${o.name} sign-in method: ${t}`)},async refresh(e,t){return await u(r,new URLSearchParams({grant_type:"refresh_token",client_id:a,refresh_token:e.refresh}),t)},async toAuth(e){return{apiKey:e.access}}}}export{b as createRadiusOAuth};
@@ -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 E}from"./chunk-XNSSUVT6.js";import{a as R,b as L,c as N,d as P,e as K,f as G}from"./chunk-TJ4GQRT6.js";import{a as j,d as F}from"./chunk-TAWLERZA.js";import"./chunk-CQLH4UVX.js";import"./chunk-OKRK6JPY.js";import"./chunk-OE4KH3NJ.js";import"./chunk-KRXTI4JO.js";import{J as r}from"./chunk-DPQPXBTP.js";import{f as A,l as I,u as O}from"./chunk-J5DVLUKY.js";import"./chunk-WHC7AYZD.js";import*as B from"fs";import*as v from"path";import*as Z from"crypto";import{pathToFileURL as ee}from"url";var k=class{memoryCache=new Map;cacheDir;sessionId;constructor(e={}){this.cacheDir=e.cacheDir??R(A),this.sessionId=e.sessionId??process.env.CORTEX_SESSION_ID,N(this.cacheDir)}buildBlocks(e,l,f){if(!l||l.length===0)return[];let h=c=>L(c.deviceId?.trim()||e,c.path);return P(this.cacheDir,this.sessionId,c=>{let n=!1,o=[];for(let t of l)c.get(h(t))!==t.mtimeMs&&(f?.has(t.path)?(c.set(h(t),t.mtimeMs),n=!0):o.push(t));let{included:u,blocks:m,truncated:a}=K(o,t=>this.formatBlock(e,t));for(let t of u)c.set(h(t),t.mtimeMs),n=!0;return{value:(a.length>0?[...m,G(a.map(t=>`${e}:${t.path}`))]:m).map(t=>({type:"text",text:t})),changed:n}},this.memoryCache)}formatBlock(e,l){return`<system-reminder>
4
+ import{a as E}from"./chunk-S3MR37DL.js";import{a as R,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 F}from"./chunk-UT6DGZDO.js";import"./chunk-ETIBCA2S.js";import"./chunk-OKRK6JPY.js";import"./chunk-OE4KH3NJ.js";import"./chunk-QUXPMNFQ.js";import"./chunk-KRXTI4JO.js";import{K as r}from"./chunk-W34AK4SK.js";import{d as A,i as I,t as O}from"./chunk-Z24SBRJK.js";import"./chunk-VPVSKJGX.js";import"./chunk-WHC7AYZD.js";import*as B from"fs";import*as v from"path";import*as Z from"crypto";import{pathToFileURL as ee}from"url";var k=class{memoryCache=new Map;cacheDir;sessionId;constructor(e={}){this.cacheDir=e.cacheDir??R(A),this.sessionId=e.sessionId??process.env.CORTEX_SESSION_ID,N(this.cacheDir)}buildBlocks(e,l,f){if(!l||l.length===0)return[];let h=c=>L(c.deviceId?.trim()||e,c.path);return P(this.cacheDir,this.sessionId,c=>{let n=!1,o=[];for(let t of l)c.get(h(t))!==t.mtimeMs&&(f?.has(t.path)?(c.set(h(t),t.mtimeMs),n=!0):o.push(t));let{included:u,blocks:m,truncated:a}=K(o,t=>this.formatBlock(e,t));for(let t of u)c.set(h(t),t.mtimeMs),n=!0;return{value:(a.length>0?[...m,G(a.map(t=>`${e}:${t.path}`))]:m).map(t=>({type:"text",text:t})),changed:n}},this.memoryCache)}formatBlock(e,l){return`<system-reminder>
5
5
  Auto-loaded AGENTS.md from ${e}:${l.path} (ancestor of accessed path on remote device). These instructions apply to files under this directory on that device.
6
6
 
7
7
  `+l.content+`
@@ -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{qa as a,ra as b,sa as c}from"./chunk-YAAKL3QS.js";import"./chunk-QEL6CMLE.js";import"./chunk-TJ4GQRT6.js";import"./chunk-5A6CA5TM.js";import"./chunk-LMDWRRX4.js";import"./chunk-BZDIAI5M.js";import"./chunk-IA6IODY3.js";import"./chunk-IYVZHGUQ.js";import"./chunk-Y6ZEVVL5.js";import"./chunk-B3XBQEFM.js";import"./chunk-OFEPDNRB.js";import"./chunk-UT6DGZDO.js";import"./chunk-ETIBCA2S.js";import"./chunk-R6CGBSTC.js";import"./chunk-WZYS2HAK.js";import"./chunk-TMV2ZDOI.js";import"./chunk-SFX7V5O2.js";import"./chunk-VTL3Z2OP.js";import"./chunk-4YLAGSDM.js";import"./chunk-RDW6FRF5.js";import"./chunk-IKLTEWA3.js";import"./chunk-2VVRTJQN.js";import"./chunk-RF4JLYBX.js";import"./chunk-7GEBDPTT.js";import"./chunk-V7K3KNDM.js";import"./chunk-5T7IX5KN.js";import"./chunk-BDLKI2NT.js";import"./chunk-JJDEQ6N2.js";import"./chunk-MGYYSX7Y.js";import"./chunk-RA2BUYI3.js";import"./chunk-U23S37TT.js";import"./chunk-T73GHMFB.js";import"./chunk-NNBSSISP.js";import"./chunk-V35MFAUQ.js";import"./chunk-OKRK6JPY.js";import"./chunk-OE4KH3NJ.js";import"./chunk-VK5J556O.js";import"./chunk-LCKVYFMD.js";import"./chunk-5M4PFLRW.js";import"./chunk-QUXPMNFQ.js";import"./chunk-BUZQBTV2.js";import"./chunk-STCNHXPJ.js";import"./chunk-STUHNKQS.js";import"./chunk-NRD57ICT.js";import"./chunk-KRXTI4JO.js";import"./chunk-W34AK4SK.js";import"./chunk-TX46YMGI.js";import"./chunk-Q4UGYGU5.js";import"./chunk-AVXDF7AG.js";import"./chunk-3CPIMAYX.js";import"./chunk-VBN2JSER.js";import"./chunk-NXZS5PEW.js";import"./chunk-Z24SBRJK.js";import"./chunk-VPVSKJGX.js";import"./chunk-WHC7AYZD.js";export{c as _test,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{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-VIMHSW6J.js";import"./chunk-QEL6CMLE.js";import"./chunk-IA6IODY3.js";import{g as O}from"./chunk-W6AKCEYF.js";import"./chunk-RF4JLYBX.js";import"./chunk-JJDEQ6N2.js";import"./chunk-MGYYSX7Y.js";import"./chunk-RA2BUYI3.js";import"./chunk-U23S37TT.js";import"./chunk-T73GHMFB.js";import"./chunk-NNBSSISP.js";import"./chunk-V35MFAUQ.js";import"./chunk-OKRK6JPY.js";import"./chunk-OE4KH3NJ.js";import"./chunk-VK5J556O.js";import"./chunk-LCKVYFMD.js";import"./chunk-5M4PFLRW.js";import{b as E,c as x}from"./chunk-PMG4YGDU.js";import"./chunk-STUHNKQS.js";import"./chunk-TX46YMGI.js";import"./chunk-Q4UGYGU5.js";import"./chunk-AVXDF7AG.js";import"./chunk-3CPIMAYX.js";import"./chunk-VBN2JSER.js";import"./chunk-Z24SBRJK.js";import"./chunk-VPVSKJGX.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-S3MR37DL.js";import{a as C,e as x}from"./chunk-RYLSRII6.js";import{a as L}from"./chunk-NT32UURL.js";import"./chunk-I6OPDRVF.js";import"./chunk-UT6DGZDO.js";import"./chunk-ETIBCA2S.js";import"./chunk-LP72AF56.js";import"./chunk-N6BTQN7R.js";import"./chunk-OKRK6JPY.js";import"./chunk-OE4KH3NJ.js";import"./chunk-QUXPMNFQ.js";import"./chunk-KRXTI4JO.js";import{K as r}from"./chunk-W34AK4SK.js";import"./chunk-VBN2JSER.js";import"./chunk-Z24SBRJK.js";import"./chunk-VPVSKJGX.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};