@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,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- var f=class extends Error{status;body;constructor(r,e){super(`HTTP ${r}`),this.name="HTTPStatusError",this.status=r,this.body=e}};function h(r,e){return`${r.replace(/\/+$/,"")}/${e.replace(/^\/+/,"")}`}function y(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}async function v(r,e={}){let n=new AbortController,a=e.timeoutMs??3e3,l=setTimeout(()=>{n.abort(new Error(`Request timed out after ${a}ms`))},a),o=e.signal,c=()=>{n.abort(o?.reason)};o&&(o.aborted?n.abort(o.reason):o.addEventListener("abort",c,{once:!0}));try{let s=new Headers(e.headers??{}),t=e.body;t!=null&&typeof t!="string"&&!(t instanceof URLSearchParams)&&!(t instanceof FormData)&&!(t instanceof Blob)&&!(t instanceof ArrayBuffer)&&(t=JSON.stringify(t)),typeof t=="string"&&!s.has("content-type")&&s.set("content-type","application/json");let i=await fetch(r,{...e,headers:s,body:t,signal:n.signal}),u=await i.text(),d=u?p(u):null;if(!i.ok)throw new f(i.status,d);return d}finally{clearTimeout(l),o?.removeEventListener("abort",c)}}function p(r){try{return JSON.parse(r)}catch{return r}}export{f as a,h as b,y as c,v as d};
@@ -1,6 +0,0 @@
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 i,b as m}from"./chunk-7MU2AKNM.js";import{f as g}from"./chunk-LMSQZ6TQ.js";import{e as f,f as y}from"./chunk-BGVHA2D4.js";import{e as l}from"./chunk-NAA7GF6Q.js";import{mkdirSync as a,existsSync as u,readFileSync as D,writeFileSync as S,lstatSync as h,readlinkSync as d,unlinkSync as I,symlinkSync as _,copyFileSync as x}from"fs";import*as o from"path";var p=l("pi-agent-dir"),j=f(),O=y();function N(t){let r=t?.userAuthPath??j,n=t?.agentDir??i,e=o.join(n,"auth.json");if(u(r)){if(a(n,{recursive:!0}),u(e)||R(e))try{if(h(e).isSymbolicLink()&&d(e)===r&&process.platform!=="win32")return;I(e)}catch(s){p.warn(`Failed to inspect/remove existing ${e}: ${s.message}`);return}process.platform==="win32"?x(r,e):_(r,e)}}function R(t){try{return h(t).isSymbolicLink()?!u(t):!1}catch{return!1}}var k=o.join(i,"agents");function $(t){g({defaultsDir:t?.defaultsDir,rolesDir:t?.rolesDir,legacyDir:t?.legacyDir??k})}function T(){a(i,{recursive:!0}),a(m,{recursive:!0}),$(),E()}function E(t){let r=o.join(t?.agentDir??i,"settings.json"),n=A(r);if(n.transport!=="sse")try{S(r,`${JSON.stringify({...n,transport:"sse"},null,2)}
5
- `)}catch(e){p.warn(`Failed to pin PI transport in ${r}: ${e.message}`)}}function U(t,r){let n=o.join(r?.agentDir??i,"settings.json"),e=A(n),s=e.compaction,c=s&&typeof s=="object"&&!Array.isArray(s)?s:{};if(c.reserveTokens!==t)try{S(n,`${JSON.stringify({...e,compaction:{...c,reserveTokens:t}},null,2)}
6
- `)}catch(P){p.warn(`Failed to set PI compaction reserve in ${n}: ${P.message}`)}}function A(t){try{let r=JSON.parse(D(t,"utf-8"));return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}catch{return{}}}export{O as a,N as b,$ as c,T as d,U as e};
@@ -1,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- var a=["anthropic-messages","openai-completions","openai-responses","google-generative-ai"],c=/^[a-zA-Z0-9_-]+$/,p="cortex-gateway",m={"anthropic-messages":"anthropic","openai-completions":"openai","openai-responses":"openai","google-generative-ai":"google"};function f(e){return m[e]}function d(e,o){return e==="anthropic-messages"?"anthropic":o}function u(e,o,s){return`${e.replace(/\/+$/,"")}/m/${o}/${d(s,o)}`}function l(e){let o=[],s=e.name?.trim()??"";s?c.test(s)||o.push("name-charset"):o.push("name-required"),a.includes(e.api)||o.push("api-invalid");let n=e.upstreamUrl?.trim()??"";n?/^https?:\/\/\S+$/i.test(n)||o.push("upstream-scheme"):o.push("upstream-required");let t=e.models??[];if(t.length===0)o.push("models-required");else{let r=t.map(i=>i.id?.trim()??"");r.some(i=>!i)?o.push("model-id-required"):new Set(r).size!==r.length&&o.push("model-id-duplicate")}return o}function g(e){return{...e,name:e.name?.trim()??"",upstreamUrl:e.upstreamUrl?.trim()??"",models:(e.models??[]).map(o=>({...o,id:o.id?.trim()??""}))}}function h(e,o){let s={baseUrl:u(o,e.name,e.api),api:e.api,apiKey:p,models:e.models.map(n=>{let t={id:n.id};return n.contextWindow!==void 0&&(t.contextWindow=n.contextWindow),n.maxTokens!==void 0&&(t.maxTokens=n.maxTokens),n.reasoning!==void 0&&(t.reasoning=n.reasoning),t})};return e.headers&&Object.keys(e.headers).length>0&&(s.headers=e.headers),e.compat&&Object.keys(e.compat).length>0&&(s.compat=e.compat),s}function x(e){return(Array.isArray(e.models)?e.models:[]).filter(s=>!!s&&typeof s=="object").map(s=>{let n={id:String(s.id??"")};return typeof s.contextWindow=="number"&&(n.contextWindow=s.contextWindow),typeof s.maxTokens=="number"&&(n.maxTokens=s.maxTokens),typeof s.reasoning=="boolean"&&(n.reasoning=s.reasoning),n})}export{a,c as b,f as c,d,l as e,g as f,h as g,x as h};
@@ -1,92 +0,0 @@
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 K}from"./chunk-JERCOLY3.js";import{e as x}from"./chunk-WHC7AYZD.js";var g=x(K(),1);import*as _ from"fs";import*as m from"path";import*as E from"os";var v=m.join(E.homedir(),".aistatus"),T=m.join(v,"gateway.yaml"),A=100,C=new Set(["host","port","mode","auth","status_check","max_body_size_mb","websocket","endpoint_modes","endpoints"]),P={anthropic:"https://api.anthropic.com",openai:"https://api.openai.com",google:"https://generativelanguage.googleapis.com","openai-codex":"https://chatgpt.com/backend-api",deepseek:"https://api.deepseek.com"},I={anthropic:["x-api-key",""],openai:["authorization","Bearer "],bearer:["authorization","Bearer "],google:["x-goog-api-key",""]},Y={ANTHROPIC_API_KEY:"anthropic",OPENAI_API_KEY:"openai",GEMINI_API_KEY:"google",DEEPSEEK_API_KEY:"deepseek"},w={openrouter:{base_url:"https://openrouter.ai/api/v1",env:"OPENROUTER_API_KEY"},deepseek:{base_url:"https://api.deepseek.com",env:"DEEPSEEK_API_KEY"},together:{base_url:"https://api.together.xyz/v1",env:"TOGETHER_API_KEY"},groq:{base_url:"https://api.groq.com/openai/v1",env:"GROQ_API_KEY"}};function O(e){return typeof e=="string"&&e.startsWith("$")?process.env[e.slice(1)]??"":e}function S(e){let t=[];for(let a of e){let s=O(String(a));s&&t.push(s)}return t}function N(e){if(e==null)return{};if(typeof e!="object"||Array.isArray(e))throw new Error("model_fallbacks must be a mapping");let t={};for(let[a,s]of Object.entries(e)){let n=String(a).trim();if(!n)throw new Error("source model must be a non-empty string");if(!Array.isArray(s)||s.length===0)throw new Error(`model_fallbacks[${JSON.stringify(n)}] fallback list must be a non-empty list`);let o=[];for(let u of s){let i=String(u).trim();if(!i)throw new Error(`model_fallbacks[${JSON.stringify(n)}] fallback target must be a non-empty string`);o.push(i)}t[n]=o}return t}function k(e,t){let a=S(t.keys??[]),s=t.auth_style??(e in I?e:"bearer"),n=t.base_url??P[e]??"",o=[];for(let r of t.fallbacks??[]){let h=O(r.key??r.api_key??"");o.push({name:r.name??"fallback",base_url:r.base_url,api_key:h,auth_style:r.auth_style??"bearer",model_prefix:r.model_prefix??"",model_map:r.model_map??{},translate:r.translate??null})}let u=t.passthrough!==!1,i=N(t.model_fallbacks);return{name:e,base_url:n,auth_style:s,keys:a,passthrough:u,fallbacks:o,model_fallbacks:i}}function R(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.keys(e).some(a=>["keys","base_url","auth_style","passthrough","fallbacks","model_fallbacks"].includes(a))}function D(e){if(e===void 0)return A;if(typeof e!="number"||!Number.isFinite(e)||e<=0)throw new Error("max_body_size_mb must be a finite number greater than zero");return e}function j(e){let t=e.host??"127.0.0.1",a=e.port??9880,s=e.status_check!==!1,n=e.websocket!==!1,o=D(e.max_body_size_mb),u={},i=[];for(let c of Object.keys(e)){if(C.has(c))continue;let l=e[c];if(!(!l||typeof l!="object"||Array.isArray(l))){if(R(l)){u.default??={},u.default[c]=k(c,l);continue}for(let[f,d]of Object.entries(l))!d||typeof d!="object"||Array.isArray(d)||(u[f]??={},u[f][c]=k(c,d),i.includes(f)||i.push(f))}}let r=Object.keys(u),h=e.mode??i[0]??r[0]??"default",b=u[h]?h:r[0]??"default";u[b]??={};let y,p=e.auth;if(p){let c=S(p.keys??[]);y={enabled:p.enabled!==!1&&c.length>0,keys:c,header:p.header??"authorization",public_paths:p.public_paths??["/health"]}}return{host:t,port:a,status_check:s,websocket:n,max_body_size_mb:o,mode:b,auth:y,endpoints:u[b],endpoint_modes:u}}function z(e="127.0.0.1",t=9880){let a={};for(let[n,o]of Object.entries(Y)){let u=process.env[n];if(!u)continue;let i=o in I?o:"bearer",r=P[o]??"";a[o]={name:o,base_url:r,auth_style:i,keys:[u],passthrough:!0,fallbacks:[],model_fallbacks:{}}}let s=process.env.OPENROUTER_API_KEY;if(s){let n=w.openrouter.base_url;for(let[o,u]of Object.entries(a)){let i=o!=="openai"?`${o}/`:"openai/",r=o==="anthropic"?"anthropic-to-openai":null;u.fallbacks.push({name:"openrouter",base_url:n,api_key:s,model_prefix:i,model_map:{},auth_style:"bearer",translate:r})}}return{host:e,port:t,status_check:!0,websocket:!0,max_body_size_mb:A,mode:"default",endpoints:a,endpoint_modes:{default:a}}}function M(e){let t=e??T;if(!_.existsSync(t))return z();let a=_.readFileSync(t,"utf-8"),s=g.default.parse(a)??{};return j(s)}function $(){return`# aistatus gateway configuration
5
- # Docs: https://aistatus.cc/docs
6
- #
7
- # After editing, start with:
8
- # npx aistatus-gateway start
9
- #
10
- # Or skip this file entirely with auto-discovery:
11
- # npx aistatus-gateway start --auto
12
-
13
- port: 9880
14
- max_body_size_mb: 100
15
-
16
- # Proxy WebSocket upgrades as well as HTTP (default true). Clients that speak both \u2014 such as
17
- # PI's Codex backend \u2014 fall back to SSE over HTTP when this is off.
18
- # websocket: true
19
-
20
- # \u2500\u2500 Authentication \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
21
- # auth:
22
- # keys:
23
- # - $GATEWAY_API_KEY
24
- # # header: authorization # default: Bearer scheme
25
- # # public_paths: ["/health"] # default
26
-
27
- # \u2500\u2500 Anthropic (for Claude Code) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
28
- anthropic:
29
- # Multiple keys \u2192 automatic rotation on rate-limit / 5xx
30
- keys:
31
- - $ANTHROPIC_API_KEY
32
- # - sk-ant-your-second-key
33
-
34
- # Hybrid mode: when true (default), the caller's own API key is
35
- # tried after managed keys, before fallbacks.
36
- # Set to false to use only managed keys.
37
- # Automatic model-level degradation order.
38
- # When a model is unhealthy, later tasks can switch to the first healthy fallback.
39
- # model_fallbacks:
40
- # claude-opus-4-6:
41
- # - claude-sonnet-4-6
42
- # - claude-haiku-4-5
43
-
44
- fallbacks:
45
- # OpenRouter serves Claude models via OpenAI-compatible API
46
- - name: openrouter
47
- base_url: https://openrouter.ai/api/v1
48
- key: $OPENROUTER_API_KEY
49
- model_prefix: "anthropic/"
50
- translate: anthropic-to-openai
51
-
52
- # \u2500\u2500 OpenAI (for Codex) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
53
- openai:
54
- keys:
55
- - $OPENAI_API_KEY
56
-
57
- fallbacks:
58
- - name: openrouter
59
- base_url: https://openrouter.ai/api/v1
60
- key: $OPENROUTER_API_KEY
61
- model_prefix: "openai/"
62
-
63
- # DeepSeek as budget fallback (different models)
64
- # - name: deepseek
65
- # base_url: https://api.deepseek.com
66
- # key: $DEEPSEEK_API_KEY
67
- # model_map:
68
- # gpt-4o: deepseek-chat
69
- # gpt-4o-mini: deepseek-chat
70
-
71
- # \u2500\u2500 OpenAI Codex (ChatGPT Plus/Pro OAuth subscription) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
72
- # Codex uses OAuth bearer tokens tied to a ChatGPT subscription, NOT a static
73
- # API key. The gateway transparently passes through the caller's own bearer
74
- # token; no managed keys are set here.
75
- openai-codex:
76
- base_url: https://chatgpt.com/backend-api
77
- auth_style: bearer
78
- passthrough: true
79
-
80
- # \u2500\u2500 DeepSeek \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
81
- deepseek:
82
- keys:
83
- - $DEEPSEEK_API_KEY
84
- base_url: https://api.deepseek.com
85
- auth_style: bearer
86
- passthrough: true
87
-
88
- # \u2500\u2500 Google (for Gemini CLI) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
89
- # google:
90
- # keys:
91
- # - $GEMINI_API_KEY
92
- `}export{A as a,C as b,P as c,I as d,j as e,z as f,M as g,$ as h};
@@ -1,4 +0,0 @@
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{K as L,L as M,O as v,P as V,R as w,S as P,U as m,Z as $,_ as d,a as y,aa as z,ba as O,c as _,ca as A,da as U,e as E,ea as H,fa as x,ga as B,k as S,l as k,o as f,q as R,r as q,t as I,v as T}from"./chunk-FOQ7VLIL.js";var b=class{constructor(e){this._server=e}requestStream(e,t,s){return this._server.requestStream(e,t,s)}createMessageStream(e,t){let s=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!s?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let i=e.messages[e.messages.length-1],r=Array.isArray(i.content)?i.content:[i.content],n=r.some(a=>a.type==="tool_result"),o=e.messages.length>1?e.messages[e.messages.length-2]:void 0,u=o?Array.isArray(o.content)?o.content:[o.content]:[],c=u.some(a=>a.type==="tool_use");if(n){if(r.some(a=>a.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let a=new Set(u.filter(h=>h.type==="tool_use").map(h=>h.id)),l=new Set(r.filter(h=>h.type==="tool_result").map(h=>h.toolUseId));if(a.size!==l.size||![...a].every(h=>l.has(h)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},w,t)}elicitInputStream(e,t){let s=this._server.getClientCapabilities(),i=e.mode??"form";switch(i){case"url":{if(!s?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!s?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let r=i==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:r},m,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,s){return this._server.getTaskResult({taskId:e},t,s)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}};var D=class extends z{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(v.options.map((s,i)=>[s,i])),this.isMessageIgnored=(s,i)=>{let r=this._loggingLevels.get(i);return r?this.LOG_LEVEL_SEVERITY.get(s)<this.LOG_LEVEL_SEVERITY.get(r):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new A,this.setRequestHandler(q,s=>this._oninitialize(s)),this.setNotificationHandler(I,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(V,async(s,i)=>{let r=i.sessionId||i.requestInfo?.headers["mcp-session-id"]||void 0,{level:n}=s.params,o=v.safeParse(n);return o.success&&this._loggingLevels.set(r,o.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new b(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=O(this._capabilities,e)}setRequestHandler(e,t){let i=E(e)?.method;if(!i)throw new Error("Schema is missing a method literal");let r;if(y(i)){let o=i;r=o._zod?.def?.value??o.value}else{let o=i;r=o._def?.value??o.value}if(typeof r!="string")throw new Error("Schema method literal must be a string");if(r==="tools/call"){let o=async(u,c)=>{let a=_(M,u);if(!a.success){let p=a.error instanceof Error?a.error.message:String(a.error);throw new d(f.InvalidParams,`Invalid tools/call request: ${p}`)}let{params:l}=a.data,h=await Promise.resolve(t(u,c));if(l.task){let p=_(T,h);if(!p.success){let G=p.error instanceof Error?p.error.message:String(p.error);throw new d(f.InvalidParams,`Invalid task creation result: ${G}`)}return p.data}let g=_(L,h);if(!g.success){let p=g.error instanceof Error?g.error.message:String(g.error);throw new d(f.InvalidParams,`Invalid tools/call result: ${p}`)}return g.data};return super.setRequestHandler(e,o)}return super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){H(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&U(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:k.includes(t)?t:S,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},R)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let s=e.messages[e.messages.length-1],i=Array.isArray(s.content)?s.content:[s.content],r=i.some(c=>c.type==="tool_result"),n=e.messages.length>1?e.messages[e.messages.length-2]:void 0,o=n?Array.isArray(n.content)?n.content:[n.content]:[],u=o.some(c=>c.type==="tool_use");if(r){if(i.some(c=>c.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let c=new Set(o.filter(l=>l.type==="tool_use").map(l=>l.id)),a=new Set(i.filter(l=>l.type==="tool_result").map(l=>l.toolUseId));if(c.size!==a.size||![...c].every(l=>a.has(l)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},P,t):this.request({method:"sampling/createMessage",params:e},w,t)}async elicitInput(e,t){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let i=e;return this.request({method:"elicitation/create",params:i},m,t)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let i=e.mode==="form"?e:{...e,mode:"form"},r=await this.request({method:"elicitation/create",params:i},m,t);if(r.action==="accept"&&r.content&&i.requestedSchema)try{let o=this._jsonSchemaValidator.getValidator(i.requestedSchema)(r.content);if(!o.valid)throw new d(f.InvalidParams,`Elicitation response content does not match requested schema: ${o.errorMessage}`)}catch(n){throw n instanceof d?n:new d(f.InternalError,`Error validating elicitation response: ${n instanceof Error?n.message:String(n)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},$,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};import j from"node:process";var N=class{constructor(e=j.stdin,t=j.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new x,this._started=!1,this._ondata=s=>{this._readBuffer.append(s),this.processReadBuffer()},this._onerror=s=>{this.onerror?.(s)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(t=>{let s=B(e);this._stdout.write(s)?t():this._stdout.once("drain",t)})}};export{D as a,N as b};
@@ -1,4 +0,0 @@
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 m}from"./chunk-FH74NME3.js";import"./chunk-KIGMAATV.js";import"./chunk-N6BTQN7R.js";import"./chunk-4LLH5OWM.js";import{k as p}from"./chunk-6LZK4DDH.js";import"./chunk-J5DVLUKY.js";import"./chunk-WHC7AYZD.js";var c=null;function t(){return c||(c=m()),c}var S={error:(...e)=>console.error("[lark:error]",...e),warn:(...e)=>console.error("[lark:warn]",...e),info:(...e)=>console.error("[lark:info]",...e),debug:(...e)=>console.error("[lark:debug]",...e),trace:(...e)=>console.error("[lark:trace]",...e)};function I(e){let r=e.domain==="lark"?t().Domain.Lark:t().Domain.Feishu;return new(t()).Client({appId:e.appId,appSecret:e.appSecret,appType:t().AppType.SelfBuild,domain:r,logger:S,loggerLevel:t().LoggerLevel.warn})}function w(e,r){let o=a=>new Proxy(a,{get(l,s,u){let n=Reflect.get(l,s,u);return typeof n=="function"?(d,i)=>r().then(f=>{let k=t().withUserAccessToken(f),g={...i??{},lark:{...i?.lark??{},...k.lark}};return n.call(l,d,g)}):n&&typeof n=="object"?o(n):n}});return o(e)}function F(e=process.env){let r=e.FEISHU_APP_ID,o=e.FEISHU_APP_SECRET;if(!r||!o)return null;let a=e.FEISHU_DOMAIN||void 0,l=I({appId:r,appSecret:o,domain:a});return e.FEISHU_AUTH_MODE==="user"?w(l,()=>p({appId:r,appSecret:o,domain:a})):l}export{F as buildFeishuClientFromEnv,I as createFeishuClient,S as stderrLogger,w as wrapWithUserToken};
@@ -1,4 +0,0 @@
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 o,b as E,c as _,d as S,e as r,f as D,g as e,h as i}from"./chunk-YZSHTWNM.js";import"./chunk-JERCOLY3.js";import"./chunk-WHC7AYZD.js";export{S as AUTH_STYLES,_ as DEFAULT_BASE_URLS,o as DEFAULT_MAX_BODY_SIZE_MB,E as RESERVED_KEYS,D as autoDiscover,r as fromDict,i as generateConfig,e as loadConfig};
@@ -1,4 +0,0 @@
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 a,c as b,d as c,e as d,f as e,g as f}from"./chunk-TAWLERZA.js";import"./chunk-CQLH4UVX.js";import"./chunk-OKRK6JPY.js";import"./chunk-OE4KH3NJ.js";import"./chunk-WHC7AYZD.js";export{a as DEFAULT_WEBHOOK_PORT,f as registerContextTools,e as resolveCortexContext,b as toolContextFromEnv,d as webSessionId,c as webhookAuthHeaders};
@@ -1,5 +0,0 @@
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 y,h as s}from"./chunk-UD3NMUHR.js";import"./chunk-HALUQ7ZF.js";import"./chunk-KRXTI4JO.js";import{J as $}from"./chunk-DPQPXBTP.js";import"./chunk-Q4UGYGU5.js";import"./chunk-W5LGYSPZ.js";import"./chunk-E7ZMYIY6.js";import"./chunk-NAA7GF6Q.js";import"./chunk-J5DVLUKY.js";import"./chunk-WHC7AYZD.js";function A(m){m.tool("cost_query","Report daily/monthly spending, budgets and remaining amounts, API/plan split, source breakdown, and token usage.",{projectId:$.string().optional().describe("Scope the report to one project. Omit for the global view.")},{readOnlyHint:!0},async({projectId:h})=>{try{let n=h??null,t=await y(n),{dailyBudget:i,monthlyBudget:d,budgetScope:g}=t,a=new Date,r=l=>String(l).padStart(2,"0"),b=`${a.getFullYear()}-${r(a.getMonth()+1)}-${r(a.getDate())}`,x=`${a.getFullYear()}-${r(a.getMonth()+1)}`,c=t.byMode.today.total,u=t.byMode.month.total,F=t.byMode.today.api,S=t.byMode.today.plan,P=t.byMode.month.api,f=t.byMode.month.plan,j=(c/i*100).toFixed(1),M=(u/d*100).toFixed(1),o=[n?`Project: ${n} (${g==="project"?"per-project budget":"global budget"})`:"Scope: all projects (global budget)",`Today (${b}): $${c.toFixed(2)} / $${i} (${j}%, ${t.entryCount} sessions in window)`,` API: $${F.toFixed(2)} | Plan: $${S.toFixed(2)}`,`Month (${x}): $${u.toFixed(2)} / $${d} (${M}%)`,` API: $${P.toFixed(2)} | Plan: $${f.toFixed(2)}`,`Remaining today: $${(i-c).toFixed(2)}`,`Remaining month: $${(d-u).toFixed(2)}`];if(t.bySource&&Object.keys(t.bySource).length>0){o.push(""),o.push("By source:");for(let[l,p]of Object.entries(t.bySource))o.push(` ${l}: today $${p.today.toFixed(2)} | month $${p.month.toFixed(2)}`)}let e=t.tokens;return e&&(e.total.input>0||e.total.output>0)&&(o.push(""),o.push(`Tokens today: ${s(e.today.input)} in / ${s(e.today.output)} out`),o.push(`Tokens month: ${s(e.month.input)} in / ${s(e.month.output)} out`)),{content:[{type:"text",text:o.join(`
5
- `)}]}}catch(n){return{content:[{type:"text",text:`Failed to query cost: ${n.message}`}],isError:!0}}})}export{A as registerCostTools};
@@ -1,4 +0,0 @@
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{$ as Fa,$a as Lb,A as X,Aa as hb,B as Y,Ba as ib,C as Z,Ca as jb,D as _,Da as kb,E as da,Ea as lb,F as ea,Fa as ob,G as fa,Ga as pb,H as ga,Ha as qb,I as ha,Ia as rb,J as ia,Ja as sb,K as ja,Ka as tb,L as ka,La as ub,M as la,Ma as vb,N as ma,Na as wb,O as na,Oa as xb,P as oa,Pa as zb,Q as pa,Qa as Ab,R as qa,Ra as Bb,S as ra,Sa as Cb,T as sa,Ta as Db,U as ta,Ua as Eb,V as za,Va as Fb,W as Aa,Wa as Gb,X as Ba,Xa as Hb,Y as Ca,Ya as Ib,Z as Da,Za as Jb,_ as Ea,_a as Kb,aa as Ga,ab as Mb,ba as Ha,bb as Nb,ca as Ia,cb as Ob,d as q,da as Ja,db as Pb,e as r,ea as Ka,eb as Qb,f as s,fa as La,fb as Rb,g as D,ga as Ma,gb as Sb,h as E,ha as Na,hb as Tb,i as F,ia as Oa,ib as Ub,j as G,ja as Pa,jb as Vb,k as H,ka as Qa,kb as Wb,l as I,la as Ra,m as J,ma as Sa,n as K,na as Ta,o as L,oa as Ua,p as M,pa as Va,q as N,qa as Wa,r as O,ra as Xa,s as P,sa as Ya,t as Q,ta as Za,u as R,ua as _a,v as S,va as cb,w as T,wa as db,x as U,xa as eb,y as V,ya as fb,z as W,za as gb}from"./chunk-KIWMQPH7.js";import{L as ab,N as bb,j as h,l as i}from"./chunk-EXJA5RIX.js";import{b as mb,c as nb}from"./chunk-HGPBHTVD.js";import{k as $a}from"./chunk-Y3GFB5XM.js";import"./chunk-EQIMHXC4.js";import{d as yb}from"./chunk-FXDIR3SQ.js";import"./chunk-WEZWKMYU.js";import"./chunk-VQUPKMDR.js";import"./chunk-YKKEI5GI.js";import"./chunk-KDYEGGMW.js";import"./chunk-ZNZFWSPH.js";import"./chunk-PZMGBKUR.js";import"./chunk-6R73ICDB.js";import"./chunk-SKHLZ6XY.js";import"./chunk-D6VMBA4C.js";import"./chunk-6AKUD3CF.js";import{a as t,b as u}from"./chunk-4EX2JJWB.js";import{a as $,g as aa,l as ba,p as ca}from"./chunk-P52RMIYX.js";import"./chunk-RA6HKFBV.js";import"./chunk-NR6U3WIZ.js";import"./chunk-UNVEZI57.js";import"./chunk-OSEIQ7SS.js";import"./chunk-CXT5IR5T.js";import{e as x,f as y,g as z,h as A,i as B,j as C,r as xa,v as ya}from"./chunk-PBJ5MPPX.js";import"./chunk-LACGULCN.js";import{a as v,b as w}from"./chunk-FX6MOGLR.js";import{Aa as m,Ba as n,Ca as o,Ea as p,Ga as ua,Ia as va,Ja as wa,ia as j,sa as k,za as l}from"./chunk-Q7CE3UIE.js";import"./chunk-3TGQSGG4.js";import"./chunk-ZQ7LGTSN.js";import{G as e,H as f,M as g,s as a,v as b,w as c,x as d}from"./chunk-QUUEQRIT.js";import"./chunk-AWFUHWQK.js";import"./chunk-OPYXNSMY.js";import"./chunk-G2V65UBA.js";import"./chunk-NHD2ESHA.js";import"./chunk-B3XBQEFM.js";import"./chunk-JERCOLY3.js";import"./chunk-WHC7AYZD.js";export{_a as AgentSession,jb as AgentSessionRuntime,yb as ArminComponent,zb as AssistantMessageComponent,Ab as BashExecutionComponent,wb as BorderedLoader,Bb as BranchSummaryMessageComponent,e as CONFIG_DIR_NAME,E as CURRENT_SESSION_VERSION,Cb as CompactionSummaryMessageComponent,cb as CredentialSynchronizationError,Db as CustomEditor,Eb as CustomMessageComponent,O as DEFAULT_COMPACTION_SETTINGS,y as DEFAULT_MAX_BYTES,x as DEFAULT_MAX_LINES,eb as DefaultPackageManager,gb as DefaultResourceLoader,qb as DynamicBorder,xb as ExtensionEditorComponent,tb as ExtensionInputComponent,ga as ExtensionRunner,ub as ExtensionSelectorComponent,Fb as FooterComponent,Qb as InteractiveMode,Gb as LoginDialogComponent,ta as ModelRegistry,db as ModelRuntime,Hb as ModelSelectorComponent,Ib as OAuthSelectorComponent,nb as ProjectTrustStore,Sb as RpcClient,M as SessionManager,vb as SessionSelectorComponent,h as SettingsManager,Jb as SettingsSelectorComponent,Vb as ShowImagesSelectorComponent,Kb as SkillInvocationMessageComponent,j as Theme,Wb as ThemeSelectorComponent,Lb as ThinkingSelectorComponent,Mb as ToolExecutionComponent,Nb as TreeSelectorComponent,Ob as UserMessageComponent,Pb as UserMessageSelectorComponent,f as VERSION,Ya as VIRTUAL_MODEL_STATE_ENTRY,J as buildContextEntries,L as buildSessionContext,K as buildSessionProjection,P as calculateContextTokens,Y as collectEntriesForBranchSummary,X as compact,D as convertToLlm,s as convertToPng,pb as copyToClipboard,lb as createAgentSession,ib as createAgentSessionFromServices,kb as createAgentSessionRuntime,hb as createAgentSessionServices,Ba as createBashTool,Aa as createBashToolDefinition,ob as createCodemodeExtension,Wa as createCodingTools,Ha as createEditTool,Ga as createEditToolDefinition,$ as createEventBus,ba as createExtensionRuntime,Ja as createFindTool,Ia as createFindToolDefinition,La as createGrepTool,Ka as createGrepToolDefinition,za as createLocalBashOperations,Oa as createLocalPowerShellOperations,Na as createLsTool,Ma as createLsToolDefinition,rb as createMcpExtension,Qa as createPowerShellTool,Pa as createPowerShellToolDefinition,Xa as createReadOnlyTools,Ta as createReadTool,Sa as createReadToolDefinition,aa as createSyntheticSourceInfo,sb as createToolSearchExtension,Va as createWriteTool,Ua as createWriteToolDefinition,ha as defineTool,Ra as detectSupportedImageMimeTypeFromFile,ca as discoverAndLoadExtensions,S as estimateTokens,U as findCutPoint,T as findTurnStartIndex,u as formatDimensionNote,ya as formatReadLineRange,z as formatSize,ea as formatSkillsForPrompt,_ as generateBranchSummary,Da as generateDiffString,V as generateSummary,W as generateSummaryWithUsage,Ca as generateUnifiedPatch,g as getAgentDir,c as getDocsPath,d as getExamplesPath,m as getLanguageFromPath,Q as getLastAssistantUsage,H as getLatestCompactionEntry,n as getMarkdownTheme,a as getPackageDir,w as getPowerShellConfig,b as getReadmePath,o as getSelectListTheme,p as getSettingsListTheme,v as getShellConfig,mb as hasTrustRequiringProjectResources,l as highlightCode,k as initTheme,ia as isBashToolResult,la as isEditToolResult,oa as isFindToolResult,na as isGrepToolResult,pa as isLsToolResult,ja as isPowerShellToolResult,ka as isReadToolResult,qa as isToolCallEventType,ma as isWriteToolResult,va as keyHint,ua as keyText,fb as loadProjectContextFiles,fa as loadSkills,da as loadSkillsFromDir,Ub as main,F as migrateSessionEntries,i as parseArgs,q as parseFrontmatter,G as parseSessionEntries,Za as parseSkillBlock,Z as prepareBranchEntries,wa as rawKeyHint,$a as readStoredCredential,Fa as renderDiff,t as resizeImage,bb as resolveCliModel,ab as resolveModelScopeWithDiagnostics,Rb as runPrintMode,Tb as runRpcMode,N as serializeConversation,I as sessionEntryToContextMessages,R as shouldCompact,r as stripFrontmatter,A as truncateHead,C as truncateLine,B as truncateTail,xa as truncateToVisualLines,Ea as withFileMutationQueue,ra as wrapRegisteredTool,sa as wrapRegisteredTools};
@@ -1,4 +0,0 @@
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 Dt,b as Pt,c as kt}from"./chunk-FXDIR3SQ.js";import{E as ft,Fa as Xt,d as wt,i as Yt,j as Tt,l as Et,n as Lt,o as Rt,qa as W}from"./chunk-Q7CE3UIE.js";import"./chunk-3TGQSGG4.js";import"./chunk-ZQ7LGTSN.js";import"./chunk-QUUEQRIT.js";import"./chunk-OPYXNSMY.js";import"./chunk-B3XBQEFM.js";import"./chunk-WHC7AYZD.js";var it=.7,G=.1,rt=1.3,Jt=.1;function Vt(i,t,e,o){let n=[];for(let s=0;s<t;s++)for(let u=0;u<i;u++){let h=e(u,s);h&&n.push({home:[u,s,0],color:h})}return{columns:i,rows:t,blocks:n,cameraDistance:o.cameraDistance,radius:Math.hypot(i/2,t/2,1+it/2),widthShare:o.widthShare,puzzleMoves:s=>o.puzzleMoves(s,n.length),origin:o.origin}}var jt=[228,138,122],Qt=[79,142,179],te=[234,182,93],ee=["ccc.","b.c.","bb.y","b..y"],ne={c:jt,b:Qt,y:te};function se(i){return Vt(4,4,(t,e)=>ne[ee[e][t]],{cameraDistance:10,widthShare:.35,puzzleMoves:t=>t<.4?2:1,origin:i})}function oe(i){return Vt(Dt,Pt,(t,e)=>kt(t,e)?i:void 0,{cameraDistance:80,widthShare:.45,puzzleMoves:(t,e)=>Math.round(e*(.03+t*.04)),origin:void 0})}var ct=G+rt+3,q=.3,tt=12,at=1,Zt=.6,dt=q*tt+at+Zt,ie=[[1,0,0],[-1,0,0],[0,1,0],[0,-1,0],[1,0,0],[-1,0,0],[0,1,0],[0,-1,0],[0,0,1],[0,0,-1]];function ce(i,t){let{columns:e,rows:o}=i,n=i.blocks.map(r=>r.home),s=[n],u=new Set,h=t*7919+1,b=()=>Q(h++),f=([r,m,y])=>((y+1)*o+m)*e+r;for(let r=0;r<tt;r++){let m=new Set(n.map(f)),y=[...n],c=new Set,d=i.puzzleMoves(b());for(let A=0;A<d;A++){let l=[];for(let Y=0;Y<n.length;Y++){if(c.has(Y))continue;let[I,k,R]=n[Y];for(let[p,L,E]of ie){let T=[I+p,k+L,R+E];T[0]<0||T[0]>=e||T[1]<0||T[1]>=o||T[2]<-1||T[2]>1||m.has(f(T))||l.push({block:Y,target:T})}}let M=l.filter(Y=>!u.has(Y.block)),a=M.length>0?M:l,x=a[Math.floor(b()*a.length)];if(!x)break;m.add(f(x.target)),y[x.block]=x.target,c.add(x.block)}u.clear();for(let A of c)u.add(A);n=y,s.push(n)}return s}var re=1e3/30,Wt=.35,Gt=.55,Kt=.12,Ot=G+Gt+Kt+Wt,ae=.5,le=1.1,he=2.5,fe=2,ue=.018,vt=[[255,255,255],[170,195,255],[255,225,170],[255,190,205]],V=5,me=.3,B=6,$=3,Ct=32,Ut=8,Nt=3,de=.5,xt=[1,8,2,16,4,32,64,128],ut=Array.from({length:256},(i,t)=>String.fromCharCode(10240+t)),J=Bt([-.45,-.6,.75]),mt=Bt([J[0],J[1],J[2]+1]);function Bt(i){let t=Math.hypot(i[0],i[1],i[2]);return[i[0]/t,i[1]/t,i[2]/t]}function Z(i){return i<0?0:i>1?1:i}function N(i){let t=Z(i);return t*t*t*(t*(t*6-15)+10)}function xe(i){let t=1-Z(i);return 1-t*t*t}function z(i,t,e){return[i[0]+(t[0]-i[0])*e,i[1]+(t[1]-i[1])*e,i[2]+(t[2]-i[2])*e]}function Q(i){let t=Math.imul(i^2654435769,2246822507);return t^=t>>>13,t=Math.imul(t,3266489909),t^=t>>>16,(t>>>0)/4294967296}function $t([i,t,e]){return .2126*i+.7152*t+.0722*e>128}function et(i){let{r:t,g:e,b:o}=Et(i);return[t,e,o]}function ge(i,t){return i.trim()===""?0:/^[.,:;'`\-_·]$/.test(i)?2:/^[\u2500-\u257f]$/.test(i)?3:4+Math.floor(t*3)}var pe=new Intl.Segmenter;function Me(i,t,e,o){let n=s=>et(Yt(s));return i.map(s=>{let u=[],h,b,f=!1,r=!1,m=d=>{let A=d===""?["0"]:d.split(";");for(let l=0;l<A.length;l++){let M=A[l].split(":").map(x=>Number.parseInt(x,10)),a=M[0]??0;if(a===38||a===48){let x;if(M.length>1)x=M.slice(1).filter(I=>!Number.isNaN(I));else{let I=Number.parseInt(A[l+1]??"",10),k=I===5?2:I===2?4:1;x=A.slice(l+1,l+1+k).map(R=>Number.parseInt(R,10)),l+=k}let Y;x[0]===5&&x[1]!==void 0?Y=n(x[1]):x[0]===2&&x.length>=4&&(Y=[x[1],x[2],x[3]]),Y&&(a===38?h=Y:b=Y)}else a===0?(h=void 0,b=void 0,f=!1,r=!1):a===2?f=!0:a===22?f=!1:a===7?r=!0:a===27?r=!1:a>=30&&a<=37?h=n(a-30):a>=90&&a<=97?h=n(a-90+8):a===39?h=void 0:a>=40&&a<=47?b=n(a-40):a>=100&&a<=107?b=n(a-100+8):a===49&&(b=void 0)}},y=d=>{for(let{segment:A}of pe.segment(d)){let l=wt(A);if(l===0||u.length+l>t)continue;let M=h??e,a=b;r&&(M=b??o,a=h??e),f&&(M=z(M,a??o,.4));let x={text:A,width:l,fg:M,bg:a,delay:0,ink:0,seed:0};u.push(x),l===2&&u.push({...x,text:"",width:0})}},c=0;for(;c<s.length;){let d=s.indexOf("\x1B",c);if(d===-1){y(s.slice(c));break}d>c&&y(s.slice(c,d));let A=s[d+1];if(A==="["){let l=d+2;for(;l<s.length&&(s.charCodeAt(l)<64||s.charCodeAt(l)>126);)l++;s[l]==="m"&&m(s.slice(d+2,l)),c=l+1}else if(A==="]"||A==="_"||A==="P"||A==="^"){let l=s.indexOf("\x07",d+2),M=s.indexOf("\x1B\\",d+2);if(l===-1&&M===-1)break;c=l!==-1&&(M===-1||l<M)?l+1:M+2}else c=d+2}return u})}function ye(i,t,e){let[o,n,s,u,h,b]=[Math.sin(i),Math.cos(i),Math.sin(t),Math.cos(t),Math.sin(e),Math.cos(e)],f=[n,0,o,0,1,0,-o,0,n],r=[1,0,0,0,u,-s,0,s,u],m=[b,-h,0,h,b,0,0,0,1];return Ft(m,Ft(r,f))}function Ft(i,t){let e=new Array(9);for(let o=0;o<3;o++)for(let n=0;n<3;n++)e[o*3+n]=i[o*3]*t[n]+i[o*3+1]*t[3+n]+i[o*3+2]*t[6+n];return e}var st=1.4,Ht=Math.PI*2/dt,be=.6,Ae=ct+q*tt+at+Zt/2;function qt(i){let t=i-G;if(t<=0)return 0;let e=t/st;return e<1?Ht*st*(e**6-3*e**5+2.5*e**4):Ht*(st*.5+t-st)}var Se=Math.PI*2-qt(Ae)%(Math.PI*2);function gt(i){return qt(i)+Se*N((i-G)/rt)}function zt(i){let t=gt(i);return t-be*Math.sin(t)}var pt=class{bits=new Uint8Array(0);counts=new Uint8Array(0);rgb=new Float32Array(0);haloAmount=new Float32Array(0);haloRgb=new Float32Array(0);width=0;height=0;depth=new Float32Array(0);faceIds=new Uint16Array(0);dirty;haloDirty;cameraDistance;constructor(t){this.cameraDistance=t}render(t,e,o,n,s,u){let h=t*2,b=e*4;if(t!==this.width||e!==this.height)this.width=t,this.height=e,this.bits=new Uint8Array(t*e),this.counts=new Uint8Array(t*e),this.rgb=new Float32Array(t*e*3),this.haloAmount=new Float32Array(t*e),this.haloRgb=new Float32Array(t*e*3),this.haloDirty=void 0,this.depth=new Float32Array(h*b).fill(1/0),this.faceIds=new Uint16Array(h*b),this.dirty=void 0;else if(this.dirty){let{minX:g,minY:_,maxX:S,maxY:D}=this.dirty;for(let w=_;w<=D;w++)this.bits.fill(0,w*t+g,w*t+S+1),this.counts.fill(0,w*t+g,w*t+S+1),this.rgb.fill(0,(w*t+g)*3,(w*t+S+1)*3);this.dirty=void 0}if(this.haloDirty){let{minX:g,minY:_,maxX:S,maxY:D}=this.haloDirty;for(let w=_;w<=D;w++)this.haloAmount.fill(0,w*t+g,w*t+S+1),this.haloRgb.fill(0,(w*t+g)*3,(w*t+S+1)*3);this.haloDirty=void 0}let f=ye(o.yaw,o.pitch,o.roll),{centerX:r,centerY:m,scale:y}=o,c=this.cameraDistance,d=[f[6]*c,f[7]*c,f[8]*c],A=$t(s),l=this.visibleFaces(f,d,o,n,h,b,A);if(l.length===0)return;let M=h,a=b,x=-1,Y=-1;for(let g of l)M=Math.min(M,g.minX),a=Math.min(a,g.minY),x=Math.max(x,g.maxX),Y=Math.max(Y,g.maxY);if(x<M||Y<a)return;let I=this.depth,k=this.faceIds;for(let g=0;g<l.length;g++){let _=l[g],S=_.axis,D=(S+1)%3,w=(S+2)%3,v=d[S],U=d[D],C=d[w],F=f[S]/y,lt=f[D]/y,O=f[w]/y,H=(_.minX+.5-r)/y;for(let K=_.minY;K<=_.maxY;K++){let ht=(K+.5-m)/y,yt=f[S]*H+f[3+S]*ht-f[6+S]*c,bt=f[D]*H+f[3+D]*ht-f[6+D]*c,At=f[w]*H+f[3+w]*ht-f[6+w]*c,nt=K*h+_.minX;for(let St=_.minX;St<=_.maxX;St++,nt++){let j=(_.plane-v)/yt;if(j>0&&j<I[nt]){let It=U+j*bt,_t=C+j*At;It>=_.uMin&&It<=_.uMax&&_t>=_.vMin&&_t<=_.vMax&&(I[nt]=j,k[nt]=g+1)}yt+=F,bt+=lt,At+=O}}}let R=this.bits,p=this.counts,L=this.rgb,E=t,T=e,X=-1,P=-1;for(let g=a;g<=Y;g++){let _=g*h+M;for(let S=M;S<=x;S++,_++){let D=k[_];if(D===0)continue;let w=l[D-1],v=Z(.15-c*(1-I[_])*.12)*(A?.5:1);k[_]=0,I[_]=1/0;let U=S>>1,C=g>>2,F=C*t+U;R[F]|=xt[(g&3)*2+(S&1)],p[F]++,L[F*3]+=w.red+(s[0]-w.red)*v,L[F*3+1]+=w.green+(s[1]-w.green)*v,L[F*3+2]+=w.blue+(s[2]-w.blue)*v,U<E&&(E=U),U>X&&(X=U),C<T&&(T=C),C>P&&(P=C)}}X>=0&&(this.dirty={minX:E,minY:T,maxX:X,maxY:P}),u>0&&this.renderHalo(u)}renderHalo(t){let e=this.dirty;if(!e)return;let{width:o,height:n,counts:s,rgb:u}=this,h=Math.max(0,e.minX-B),b=Math.min(o-1,e.maxX+B),f=Math.max(0,e.minY-$),r=Math.min(n-1,e.maxY+$),m=b-h+1,y=M=>{let a=Array.from({length:M*2+1},(Y,I)=>M+1-Math.abs(I-M)),x=a.reduce((Y,I)=>Y+I,0);return a.map(Y=>Y/x)},c=y(B),d=y($),A=e.maxY-e.minY+1,l=new Float32Array(A*m*4);for(let M=e.minY;M<=e.maxY;M++)for(let a=h;a<=b;a++){let x=0,Y=0,I=0,k=0;for(let p=-B;p<=B;p++){let L=a+p;if(L<e.minX||L>e.maxX)continue;let E=M*o+L,T=s[E];if(T===0)continue;let X=c[p+B]/8;x+=T*X,Y+=u[E*3]*X,I+=u[E*3+1]*X,k+=u[E*3+2]*X}let R=((M-e.minY)*m+(a-h))*4;l[R]=x,l[R+1]=Y,l[R+2]=I,l[R+3]=k}for(let M=f;M<=r;M++)for(let a=h;a<=b;a++){let x=0,Y=0,I=0,k=0;for(let E=-$;E<=$;E++){let T=M+E;if(T<e.minY||T>e.maxY)continue;let X=d[E+$],P=((T-e.minY)*m+(a-h))*4;x+=l[P]*X,Y+=l[P+1]*X,I+=l[P+2]*X,k+=l[P+3]*X}let R=M*o+a,p=s[R];if(p>0&&p/8>x&&(x=p/8,Y=u[R*3]/p*x,I=u[R*3+1]/p*x,k=u[R*3+2]/p*x),x<=0)continue;let L=Math.round(t*Math.min(1,x)**.7*Ct)/Ct;L<=0||(this.haloAmount[R]=L,this.haloRgb[R*3]=Math.round(Y/x/V)*V,this.haloRgb[R*3+1]=Math.round(I/x/V)*V,this.haloRgb[R*3+2]=Math.round(k/x/V)*V)}this.haloDirty={minX:h,minY:f,maxX:b,maxY:r}}visibleFaces(t,e,o,n,s,u,h){let b=[],f=this.cameraDistance;for(let r of n)for(let m=0;m<3;m++){let y=(m+1)%3,c=(m+2)%3;for(let d of[-1,1]){let A=d>0?r.max[m]:r.min[m];if((e[m]-A)*d<=0||n.some(g=>g!==r&&(d>0?g.min[m]:g.max[m])===A&&g.min[y]<=r.min[y]&&g.max[y]>=r.max[y]&&g.min[c]<=r.min[c]&&g.max[c]>=r.max[c]))continue;let M=1/0,a=1/0,x=-1/0,Y=-1/0,I=[0,0,0];for(let g of[r.min[y],r.max[y]])for(let _ of[r.min[c],r.max[c]]){I[m]=A,I[y]=g,I[c]=_;let S=t[0]*I[0]+t[1]*I[1]+t[2]*I[2],D=t[3]*I[0]+t[4]*I[1]+t[5]*I[2],w=t[6]*I[0]+t[7]*I[1]+t[8]*I[2],v=o.scale*f/(f-w),U=o.centerX+S*v,C=o.centerY+D*v;M=Math.min(M,U),a=Math.min(a,C),x=Math.max(x,U),Y=Math.max(Y,C)}let k={minX:Math.max(0,Math.floor(M)),minY:Math.max(0,Math.floor(a)),maxX:Math.min(s-1,Math.ceil(x)),maxY:Math.min(u-1,Math.ceil(Y))};if(k.maxX<k.minX||k.maxY<k.minY)continue;let R=t[m]*d,p=t[3+m]*d,L=t[6+m]*d,E=Math.max(0,R*J[0]+p*J[1]+L*J[2]),T=Math.max(0,R*.8-L*.3),X=h?0:Math.max(0,R*mt[0]+p*mt[1]+L*mt[2])**24*.6*255,P=h?Math.min(1,.55+E*.45+T*.1):.45+E*.78+T*.25;b.push({axis:m,plane:A,uMin:r.min[y],uMax:r.max[y],vMin:r.min[c],vMax:r.max[c],...k,red:Math.min(255,r.color[0]*P+X),green:Math.min(255,r.color[1]*P+X),blue:Math.min(255,r.color[2]*P+X)})}}return b}},ot=!1;async function Te(i,t,e){if(ot)return;ot=!0;let o=await i.queryTerminalColors({timeoutMs:100}),n=W.appearance==="dark",s=(r,m)=>r?[r.r,r.g,r.b]:m,u={foreground:s(o.foreground,et(W.colors.text)),background:s(o.background,n?[0,0,0]:[255,255,255])};if(i.hasOverlay()){ot=!1;return}let h=e.kind==="armin"?oe(et(W.colors.accent)):se({column:e.column,row:e.row}),b=new Mt(i,t,h,u,()=>{ot=!1,f.hide()}),f=i.showOverlay(b,{anchor:"top-left",width:"100%",maxHeight:"100%"})}var Mt=class{tui;screen;model;foreground;background;onDone;startTime=performance.now();lastRender=performance.now();timer;exit;shuffle;screenWidth=-1;screenHeight=-1;stars=[];cells=[];ansiCache=new Map;raster;constructor(t,e,o,n,s){this.tui=t,this.screen=e,this.model=o,this.raster=new pt(o.cameraDistance),this.foreground=n.foreground,this.background=n.background,this.onDone=s,this.timer=setInterval(()=>{this.exit&&this.exitProgress()>=1||performance.now()-this.lastRender>1e3?this.finish():this.tui.requestRender()},re),this.timer.unref?.()}close(){if(this.exit){this.finish();return}let t=this.elapsed(),e=zt(t),o=Math.PI*2;this.exit={start:performance.now(),time:t,yaw:e,targetYaw:Math.ceil(e/o)*o,offsets:this.blockOffsets(t)}}handleInput(t){let e=ft();(e.matches(t,"tui.select.cancel")||e.matches(t,"app.clear"))&&this.close()}handleMouse(t){return t.type==="click"&&this.close(),{handled:!0,render:!1}}invalidate(){this.screenWidth=-1,this.screenHeight=-1,this.ansiCache.clear()}render(t){let e=Math.max(1,this.tui.terminal.rows),o=this.foreground,n=this.background;this.lastRender=performance.now(),(t!==this.screenWidth||e!==this.screenHeight)&&(this.screenWidth=t,this.screenHeight=e,this.cells=this.prepareCells(t,o),this.stars=this.prepareStars(t,e));let s,u,h,b,f;if(this.exit){let p=this.exitProgress(),L=Z(p/.8),E=1-N(L);s=Math.min(this.exit.time,Ot)*(1-p),u=this.pose(t,e,this.flyProgress(this.exit.time)*E,this.exit.time),u.yaw=this.exit.yaw+(this.exit.targetYaw-this.exit.yaw)*xe(L),u.pitch*=E,u.roll*=E,h=this.hintAlpha(this.exit.time)*(1-N(p/.2)),b=this.starAlpha(this.exit.time)*(1-N(p/.3));let T=1-N(p/.5);f=this.exit.offsets.map(([X,P,g])=>[X*T,P*T,g*T])}else{let p=this.elapsed();s=p,u=this.pose(t,e,this.flyProgress(p),p),h=this.hintAlpha(p),b=this.starAlpha(p),f=this.blockOffsets(p)}let{columns:r,rows:m}=this.model,y=this.model.blocks.map((p,L)=>{let[E,T,X]=f[L],P=p.home[0]-r/2+E,g=p.home[1]-m/2+T;return{min:[P,g,X-it/2],max:[P+1,g+1,X+it/2],color:p.color}}),c=this.raster;c.render(t,e,u,y,n,$t(n)?me:0);let d=(p,L)=>{let E=c.haloAmount[p];if(E<=0)return L;let T=c.haloRgb;return z(L??n,[T[p*3],T[p*3+1],T[p*3+2]],E)},A=N(s/ae),l=N(s/.6)*.3,M=s<Ot||A<1,a=this.hint(t,e,h,n),x=Math.floor(s*14),Y=this.elapsed(),I=Math.round(b*Ut)/Ut,k=p=>{if(I<=0)return;let L=this.stars[p];if(!L)return;let E=Math.round((.5+.5*Math.sin(Y*L.speed+L.phase))*Nt)/Nt;return{text:L.glyph,fg:z(n,z(o,L.tint,.5),L.strength*(.7+.3*E)*I)}},R=[];for(let p=0;p<e;p++){let L=this.cells[p]??[],E="",T=-1,X=-1,P=(g,_,S)=>{let D=_?this.pack(_):-1,w=S?this.pack(S):-1;D!==T&&g!==" "&&(E+=_?this.ansi(D,!1):"\x1B[39m",T=D),w!==X&&(E+=S?this.ansi(w,!0):"\x1B[49m",X=w),E+=g};for(let g=0;g<t;g++){let _=p*t+g,S=M?L[g]:void 0,D=d(_,S?.bg&&A<1?z(S.bg,n,A):void 0);if(a&&p===a.row&&g>=a.start&&g<a.start+a.text.length){let O=g-a.start;P(a.text[O],O<a.keyLength?a.keyColor:a.color,D);continue}let w=c.bits[_];if(w){let O=V*c.counts[_],H=c.rgb,K=[Math.round(H[_*3]/O)*V,Math.round(H[_*3+1]/O)*V,Math.round(H[_*3+2]/O)*V];P(ut[w],K,D);continue}if(!S){let O=k(_);P(O?.text??" ",O?.fg,D);continue}let v=(s-S.delay)/Wt;if(v<0&&S.width===2&&!c.bits[_+1]){P(S.text,z(S.fg,n,l),D),g++;continue}if(v<0&&S.width===1){P(S.text,z(S.fg,n,l),D);continue}let U=v<0?S.ink:Math.round(S.ink*(1-Z(v)));if(U<=0){let O=k(_);P(O?.text??" ",O?.fg,D);continue}let C=0,F=0;for(let O=0;F<U&&O<32;O++){let H=xt[Math.floor(Q(S.seed*7919+x*131+O)*8)];C&H||(C|=H,F++)}let lt=l+(1-l)*Z(v)**.8;P(ut[C],z(S.fg,n,lt),D)}R.push(`${E}\x1B[0m`)}return R}elapsed(){return(performance.now()-this.startTime)/1e3}exitProgress(){return this.exit?Z((performance.now()-this.exit.start)/1e3/le):0}finish(){this.timer&&(clearInterval(this.timer),this.timer=void 0,this.onDone())}blockOffsets(t){let e=this.model.blocks,o=()=>e.map(()=>[0,0,0]);if(t<ct)return o();let n=Math.floor((t-ct)/dt),s=t-ct-n*dt;this.shuffle?.cycle!==n&&(this.shuffle={cycle:n,steps:ce(this.model,n)});let u=this.shuffle.steps,h=(f,r)=>{let m=e[r].home;return[f[0]-m[0],f[1]-m[1],f[2]-m[2]]},b=q*tt;if(s<b){let f=Math.floor(s/q),r=N((s-f*q)/q);return u[f].map((m,y)=>{let c=h(m,y),d=h(u[f+1][y],y);return[c[0]+(d[0]-c[0])*r,c[1]+(d[1]-c[1])*r,c[2]+(d[2]-c[2])*r]})}if(s<b+at){let f=(s-b)/at,r=1-N(f),m=Math.sin(Math.PI*Z(f))*.8;return u[tt].map((y,c)=>{let[d,A,l]=h(y,c);return[d*r,A*r,l*r+(c%2===0?m:-m)]})}return o()}flyProgress(t){return N((t-G)/rt)}starAlpha(t){return N((t-he)/fe)}hintAlpha(t){return N((t-G-rt)/de)}pose(t,e,o,n){let{columns:s,rows:u,cameraDistance:h,radius:b,widthShare:f,origin:r}=this.model,m=b*(h/(h-b)),y=r?2*(h-it/2)/h:Jt,c=Math.max(y,Math.min(t*2*f,(e*4-8)*.48)/m),d=t,A=e*2-2,l=r?r.column*2+s:d,M=r?r.row*4+u:A;return{centerX:l+(d-l)*o,centerY:M+(A-M)*o,scale:y*(c/y)**o,yaw:zt(n),pitch:.3*Math.sin(gt(n))*o,roll:.06*Math.sin(2*gt(n))*o}}hint(t,e,o,n){if(o<=0)return;let s=Xt(ft().getKeys("tui.select.cancel")[0]??"escape"),u=`${s} to return`;if(!(u.length>t))return{row:e-2,start:Math.floor((t-u.length)/2),text:u,keyLength:s.length,keyColor:z(n,et(W.colors.muted),o),color:z(n,et(W.colors.dim),o)}}prepareStars(t,e){let o=new Array(t*e);for(let n=0;n<t*e;n++){if(Q(n*3+20973)>=ue)continue;let s=u=>Q(n*7+u*40503);o[n]={glyph:ut[xt[Math.floor(s(1)*8)]],tint:vt[Math.floor(s(2)*vt.length)],strength:.1+s(3)*.12,phase:s(4)*Math.PI*2,speed:.4+s(5)*.8}}return o}prepareCells(t,e){let o=Me(this.screen,t,e,this.background),n=Math.max(1,this.tui.terminal.rows),{columns:s,rows:u,origin:h}=this.model,b=h?h.column+s/2:t/2,f=h?h.row+u/4:n/2,r=Math.hypot(Math.max(b,t-b),Math.max(f,n-f)*2);for(let m=0;m<o.length;m++){let y=o[m];for(let c=0;c<y.length;c++){let d=y[c],A=d.width===0?y[c-1]:d,l=Q(m*65537+c);if(d.width!==0){let M=Math.hypot(c-b,(m-f)*2)/r;d.delay=G+M*Gt+l*Kt}else d.delay=A.delay;d.seed=m*65537+c,d.ink=ge(A.text,l)}}if(h)for(let m=h.row;m<h.row+Math.ceil(u/2);m++){let y=o[m];if(y)for(let c=h.column;c<h.column+s;c++){let d=y[c];d&&(d.text=" ",d.width=1,d.ink=0,d.bg=void 0)}}return o}pack(t){return Math.round(t[0])<<16|Math.round(t[1])<<8|Math.round(t[2])}ansi(t,e){let o=t*2+(e?1:0),n=this.ansiCache.get(o);if(n===void 0){let s=Tt(t>>16&255,t>>8&255,t&255),u=W.getColorMode();n=e?Rt(s,u):Lt(s,u),this.ansiCache.set(o,n)}return n}};export{Mt as EasterEgg3dAnimation,Te as playEasterEgg3d};
@@ -1,4 +0,0 @@
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 k}from"./chunk-WHC7AYZD.js";var x=k((m,P)=>{(function(g,d){typeof m=="object"&&typeof P=="object"?P.exports=d():typeof define=="function"&&define.amd?define([],d):typeof m=="object"?m.bowser=d():g.bowser=d()})(m,(function(){return(function(g){var d={};function b(u){if(d[u])return d[u].exports;var i=d[u]={i:u,l:!1,exports:{}};return g[u].call(i.exports,i,i.exports,b),i.l=!0,i.exports}return b.m=g,b.c=d,b.d=function(u,i,n){b.o(u,i)||Object.defineProperty(u,i,{enumerable:!0,get:n})},b.r=function(u){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(u,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(u,"__esModule",{value:!0})},b.t=function(u,i){if(1&i&&(u=b(u)),8&i||4&i&&typeof u=="object"&&u&&u.__esModule)return u;var n=Object.create(null);if(b.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:u}),2&i&&typeof u!="string")for(var f in u)b.d(n,f,function(e){return u[e]}.bind(null,f));return n},b.n=function(u){var i=u&&u.__esModule?function(){return u.default}:function(){return u};return b.d(i,"a",i),i},b.o=function(u,i){return Object.prototype.hasOwnProperty.call(u,i)},b.p="",b(b.s=90)})({17:function(g,d,b){"use strict";d.__esModule=!0,d.default=void 0;var u=b(18),i=(function(){function n(){}return n.getFirstMatch=function(f,e){var t=e.match(f);return t&&t.length>0&&t[1]||""},n.getSecondMatch=function(f,e){var t=e.match(f);return t&&t.length>1&&t[2]||""},n.matchAndReturnConst=function(f,e,t){if(f.test(e))return t},n.getWindowsVersionName=function(f){switch(f){case"NT":return"NT";case"XP":return"XP";case"NT 5.0":return"2000";case"NT 5.1":return"XP";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}},n.getMacOSVersionName=function(f){var e=f.split(".").splice(0,2).map((function(l){return parseInt(l,10)||0}));e.push(0);var t=e[0],r=e[1];if(t===10)switch(r){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}switch(t){case 11:return"Big Sur";case 12:return"Monterey";case 13:return"Ventura";case 14:return"Sonoma";case 15:return"Sequoia";default:return}},n.getAndroidVersionName=function(f){var e=f.split(".").splice(0,2).map((function(t){return parseInt(t,10)||0}));if(e.push(0),!(e[0]===1&&e[1]<5))return e[0]===1&&e[1]<6?"Cupcake":e[0]===1&&e[1]>=6?"Donut":e[0]===2&&e[1]<2?"Eclair":e[0]===2&&e[1]===2?"Froyo":e[0]===2&&e[1]>2?"Gingerbread":e[0]===3?"Honeycomb":e[0]===4&&e[1]<1?"Ice Cream Sandwich":e[0]===4&&e[1]<4?"Jelly Bean":e[0]===4&&e[1]>=4?"KitKat":e[0]===5?"Lollipop":e[0]===6?"Marshmallow":e[0]===7?"Nougat":e[0]===8?"Oreo":e[0]===9?"Pie":void 0},n.getVersionPrecision=function(f){return f.split(".").length},n.compareVersions=function(f,e,t){t===void 0&&(t=!1);var r=n.getVersionPrecision(f),l=n.getVersionPrecision(e),s=Math.max(r,l),a=0,o=n.map([f,e],(function(c){var h=s-n.getVersionPrecision(c),M=c+new Array(h+1).join(".0");return n.map(M.split("."),(function(p){return new Array(20-p.length).join("0")+p})).reverse()}));for(t&&(a=s-Math.min(r,l)),s-=1;s>=a;){if(o[0][s]>o[1][s])return 1;if(o[0][s]===o[1][s]){if(s===a)return 0;s-=1}else if(o[0][s]<o[1][s])return-1}},n.map=function(f,e){var t,r=[];if(Array.prototype.map)return Array.prototype.map.call(f,e);for(t=0;t<f.length;t+=1)r.push(e(f[t]));return r},n.find=function(f,e){var t,r;if(Array.prototype.find)return Array.prototype.find.call(f,e);for(t=0,r=f.length;t<r;t+=1){var l=f[t];if(e(l,t))return l}},n.assign=function(f){for(var e,t,r=f,l=arguments.length,s=new Array(l>1?l-1:0),a=1;a<l;a++)s[a-1]=arguments[a];if(Object.assign)return Object.assign.apply(Object,[f].concat(s));var o=function(){var c=s[e];typeof c=="object"&&c!==null&&Object.keys(c).forEach((function(h){r[h]=c[h]}))};for(e=0,t=s.length;e<t;e+=1)o();return f},n.getBrowserAlias=function(f){return u.BROWSER_ALIASES_MAP[f]},n.getBrowserTypeByAlias=function(f){return u.BROWSER_MAP[f]||""},n})();d.default=i,g.exports=d.default},18:function(g,d,b){"use strict";d.__esModule=!0,d.ENGINE_MAP=d.OS_MAP=d.PLATFORMS_MAP=d.BROWSER_MAP=d.BROWSER_ALIASES_MAP=void 0,d.BROWSER_ALIASES_MAP={AmazonBot:"amazonbot","Amazon Silk":"amazon_silk","Android Browser":"android",BaiduSpider:"baiduspider",Bada:"bada",BingCrawler:"bingcrawler",Brave:"brave",BlackBerry:"blackberry","ChatGPT-User":"chatgpt_user",Chrome:"chrome",ClaudeBot:"claudebot",Chromium:"chromium",Diffbot:"diffbot",DuckDuckBot:"duckduckbot",DuckDuckGo:"duckduckgo",Electron:"electron",Epiphany:"epiphany",FacebookExternalHit:"facebookexternalhit",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot",GPTBot:"gptbot","Internet Explorer":"ie",InternetArchiveCrawler:"internetarchivecrawler","K-Meleon":"k_meleon",LibreWolf:"librewolf",Linespider:"linespider",Maxthon:"maxthon","Meta-ExternalAds":"meta_externalads","Meta-ExternalAgent":"meta_externalagent","Meta-ExternalFetcher":"meta_externalfetcher","Meta-WebIndexer":"meta_webindexer","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver","OAI-SearchBot":"oai_searchbot",Omgilibot:"omgilibot",Opera:"opera","Opera Coast":"opera_coast","Pale Moon":"pale_moon",PerplexityBot:"perplexitybot","Perplexity-User":"perplexity_user",PhantomJS:"phantomjs",PingdomBot:"pingdombot",Puffin:"puffin",QQ:"qq",QQLite:"qqlite",QupZilla:"qupzilla",Roku:"roku",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SlackBot:"slackbot",SeaMonkey:"seamonkey",Sleipnir:"sleipnir","Sogou Browser":"sogou",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat",YahooSlurp:"yahooslurp","Yandex Browser":"yandex",YandexBot:"yandexbot",YouBot:"youbot"},d.BROWSER_MAP={amazonbot:"AmazonBot",amazon_silk:"Amazon Silk",android:"Android Browser",baiduspider:"BaiduSpider",bada:"Bada",bingcrawler:"BingCrawler",blackberry:"BlackBerry",brave:"Brave",chatgpt_user:"ChatGPT-User",chrome:"Chrome",claudebot:"ClaudeBot",chromium:"Chromium",diffbot:"Diffbot",duckduckbot:"DuckDuckBot",duckduckgo:"DuckDuckGo",edge:"Microsoft Edge",electron:"Electron",epiphany:"Epiphany",facebookexternalhit:"FacebookExternalHit",firefox:"Firefox",focus:"Focus",generic:"Generic",google_search:"Google Search",googlebot:"Googlebot",gptbot:"GPTBot",ie:"Internet Explorer",internetarchivecrawler:"InternetArchiveCrawler",k_meleon:"K-Meleon",librewolf:"LibreWolf",linespider:"Linespider",maxthon:"Maxthon",meta_externalads:"Meta-ExternalAds",meta_externalagent:"Meta-ExternalAgent",meta_externalfetcher:"Meta-ExternalFetcher",meta_webindexer:"Meta-WebIndexer",mz:"MZ Browser",naver:"NAVER Whale Browser",oai_searchbot:"OAI-SearchBot",omgilibot:"Omgilibot",opera:"Opera",opera_coast:"Opera Coast",pale_moon:"Pale Moon",perplexitybot:"PerplexityBot",perplexity_user:"Perplexity-User",phantomjs:"PhantomJS",pingdombot:"PingdomBot",puffin:"Puffin",qq:"QQ Browser",qqlite:"QQ Browser Lite",qupzilla:"QupZilla",roku:"Roku",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",slackbot:"SlackBot",sleipnir:"Sleipnir",sogou:"Sogou Browser",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yahooslurp:"YahooSlurp",yandex:"Yandex Browser",yandexbot:"YandexBot",youbot:"YouBot"},d.PLATFORMS_MAP={bot:"bot",desktop:"desktop",mobile:"mobile",tablet:"tablet",tv:"tv"},d.OS_MAP={Android:"Android",Bada:"Bada",BlackBerry:"BlackBerry",ChromeOS:"Chrome OS",HarmonyOS:"HarmonyOS",iOS:"iOS",Linux:"Linux",MacOS:"macOS",PlayStation4:"PlayStation 4",Roku:"Roku",Tizen:"Tizen",WebOS:"WebOS",Windows:"Windows",WindowsPhone:"Windows Phone"},d.ENGINE_MAP={Blink:"Blink",EdgeHTML:"EdgeHTML",Gecko:"Gecko",Presto:"Presto",Trident:"Trident",WebKit:"WebKit"}},90:function(g,d,b){"use strict";d.__esModule=!0,d.default=void 0;var u,i=(u=b(91))&&u.__esModule?u:{default:u},n=b(18);function f(t,r){for(var l=0;l<r.length;l++){var s=r[l];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(t,s.key,s)}}var e=(function(){function t(){}var r,l,s;return t.getParser=function(a,o,c){if(o===void 0&&(o=!1),c===void 0&&(c=null),typeof a!="string")throw new Error("UserAgent should be a string");return new i.default(a,o,c)},t.parse=function(a,o){return o===void 0&&(o=null),new i.default(a,o).getResult()},r=t,s=[{key:"BROWSER_MAP",get:function(){return n.BROWSER_MAP}},{key:"ENGINE_MAP",get:function(){return n.ENGINE_MAP}},{key:"OS_MAP",get:function(){return n.OS_MAP}},{key:"PLATFORMS_MAP",get:function(){return n.PLATFORMS_MAP}}],(l=null)&&f(r.prototype,l),s&&f(r,s),t})();d.default=e,g.exports=d.default},91:function(g,d,b){"use strict";d.__esModule=!0,d.default=void 0;var u=t(b(92)),i=t(b(93)),n=t(b(94)),f=t(b(95)),e=t(b(17));function t(l){return l&&l.__esModule?l:{default:l}}var r=(function(){function l(a,o,c){if(o===void 0&&(o=!1),c===void 0&&(c=null),a==null||a==="")throw new Error("UserAgent parameter can't be empty");this._ua=a;var h=!1;typeof o=="boolean"?(h=o,this._hints=c):this._hints=o!=null&&typeof o=="object"?o:null,this.parsedResult={},h!==!0&&this.parse()}var s=l.prototype;return s.getHints=function(){return this._hints},s.hasBrand=function(a){if(!this._hints||!Array.isArray(this._hints.brands))return!1;var o=a.toLowerCase();return this._hints.brands.some((function(c){return c.brand&&c.brand.toLowerCase()===o}))},s.getBrandVersion=function(a){if(this._hints&&Array.isArray(this._hints.brands)){var o=a.toLowerCase(),c=this._hints.brands.find((function(h){return h.brand&&h.brand.toLowerCase()===o}));return c?c.version:void 0}},s.getUA=function(){return this._ua},s.test=function(a){return a.test(this._ua)},s.parseBrowser=function(){var a=this;this.parsedResult.browser={};var o=e.default.find(u.default,(function(c){if(typeof c.test=="function")return c.test(a);if(Array.isArray(c.test))return c.test.some((function(h){return a.test(h)}));throw new Error("Browser's test function is not valid")}));return o&&(this.parsedResult.browser=o.describe(this.getUA(),this)),this.parsedResult.browser},s.getBrowser=function(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()},s.getBrowserName=function(a){return a?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""},s.getBrowserVersion=function(){return this.getBrowser().version},s.getOS=function(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()},s.parseOS=function(){var a=this;this.parsedResult.os={};var o=e.default.find(i.default,(function(c){if(typeof c.test=="function")return c.test(a);if(Array.isArray(c.test))return c.test.some((function(h){return a.test(h)}));throw new Error("Browser's test function is not valid")}));return o&&(this.parsedResult.os=o.describe(this.getUA())),this.parsedResult.os},s.getOSName=function(a){var o=this.getOS().name;return a?String(o).toLowerCase()||"":o||""},s.getOSVersion=function(){return this.getOS().version},s.getPlatform=function(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()},s.getPlatformType=function(a){a===void 0&&(a=!1);var o=this.getPlatform().type;return a?String(o).toLowerCase()||"":o||""},s.parsePlatform=function(){var a=this;this.parsedResult.platform={};var o=e.default.find(n.default,(function(c){if(typeof c.test=="function")return c.test(a);if(Array.isArray(c.test))return c.test.some((function(h){return a.test(h)}));throw new Error("Browser's test function is not valid")}));return o&&(this.parsedResult.platform=o.describe(this.getUA())),this.parsedResult.platform},s.getEngine=function(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()},s.getEngineName=function(a){return a?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""},s.parseEngine=function(){var a=this;this.parsedResult.engine={};var o=e.default.find(f.default,(function(c){if(typeof c.test=="function")return c.test(a);if(Array.isArray(c.test))return c.test.some((function(h){return a.test(h)}));throw new Error("Browser's test function is not valid")}));return o&&(this.parsedResult.engine=o.describe(this.getUA())),this.parsedResult.engine},s.parse=function(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this},s.getResult=function(){return e.default.assign({},this.parsedResult)},s.satisfies=function(a){var o=this,c={},h=0,M={},p=0;if(Object.keys(a).forEach((function(v){var A=a[v];typeof A=="string"?(M[v]=A,p+=1):typeof A=="object"&&(c[v]=A,h+=1)})),h>0){var _=Object.keys(c),S=e.default.find(_,(function(v){return o.isOS(v)}));if(S){var y=this.satisfies(c[S]);if(y!==void 0)return y}var F=e.default.find(_,(function(v){return o.isPlatform(v)}));if(F){var w=this.satisfies(c[F]);if(w!==void 0)return w}}if(p>0){var B=Object.keys(M),O=e.default.find(B,(function(v){return o.isBrowser(v,!0)}));if(O!==void 0)return this.compareVersion(M[O])}},s.isBrowser=function(a,o){o===void 0&&(o=!1);var c=this.getBrowserName().toLowerCase(),h=a.toLowerCase(),M=e.default.getBrowserTypeByAlias(h);return o&&M&&(h=M.toLowerCase()),h===c},s.compareVersion=function(a){var o=[0],c=a,h=!1,M=this.getBrowserVersion();if(typeof M=="string")return a[0]===">"||a[0]==="<"?(c=a.substr(1),a[1]==="="?(h=!0,c=a.substr(2)):o=[],a[0]===">"?o.push(1):o.push(-1)):a[0]==="="?c=a.substr(1):a[0]==="~"&&(h=!0,c=a.substr(1)),o.indexOf(e.default.compareVersions(M,c,h))>-1},s.isOS=function(a){return this.getOSName(!0)===String(a).toLowerCase()},s.isPlatform=function(a){return this.getPlatformType(!0)===String(a).toLowerCase()},s.isEngine=function(a){return this.getEngineName(!0)===String(a).toLowerCase()},s.is=function(a,o){return o===void 0&&(o=!1),this.isBrowser(a,o)||this.isOS(a)||this.isPlatform(a)},s.some=function(a){var o=this;return a===void 0&&(a=[]),a.some((function(c){return o.is(c)}))},l})();d.default=r,g.exports=d.default},92:function(g,d,b){"use strict";d.__esModule=!0,d.default=void 0;var u,i=(u=b(17))&&u.__esModule?u:{default:u},n=/version\/(\d+(\.?_?\d+)+)/i,f=[{test:[/gptbot/i],describe:function(e){var t={name:"GPTBot"},r=i.default.getFirstMatch(/gptbot\/(\d+(\.\d+)+)/i,e)||i.default.getFirstMatch(n,e);return r&&(t.version=r),t}},{test:[/chatgpt-user/i],describe:function(e){var t={name:"ChatGPT-User"},r=i.default.getFirstMatch(/chatgpt-user\/(\d+(\.\d+)+)/i,e)||i.default.getFirstMatch(n,e);return r&&(t.version=r),t}},{test:[/oai-searchbot/i],describe:function(e){var t={name:"OAI-SearchBot"},r=i.default.getFirstMatch(/oai-searchbot\/(\d+(\.\d+)+)/i,e)||i.default.getFirstMatch(n,e);return r&&(t.version=r),t}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe:function(e){var t={name:"ClaudeBot"},r=i.default.getFirstMatch(/(?:claudebot|claude-web|claude-user|claude-searchbot)\/(\d+(\.\d+)+)/i,e)||i.default.getFirstMatch(n,e);return r&&(t.version=r),t}},{test:[/omgilibot/i,/webzio-extended/i],describe:function(e){var t={name:"Omgilibot"},r=i.default.getFirstMatch(/(?:omgilibot|webzio-extended)\/(\d+(\.\d+)+)/i,e)||i.default.getFirstMatch(n,e);return r&&(t.version=r),t}},{test:[/diffbot/i],describe:function(e){var t={name:"Diffbot"},r=i.default.getFirstMatch(/diffbot\/(\d+(\.\d+)+)/i,e)||i.default.getFirstMatch(n,e);return r&&(t.version=r),t}},{test:[/perplexitybot/i],describe:function(e){var t={name:"PerplexityBot"},r=i.default.getFirstMatch(/perplexitybot\/(\d+(\.\d+)+)/i,e)||i.default.getFirstMatch(n,e);return r&&(t.version=r),t}},{test:[/perplexity-user/i],describe:function(e){var t={name:"Perplexity-User"},r=i.default.getFirstMatch(/perplexity-user\/(\d+(\.\d+)+)/i,e)||i.default.getFirstMatch(n,e);return r&&(t.version=r),t}},{test:[/youbot/i],describe:function(e){var t={name:"YouBot"},r=i.default.getFirstMatch(/youbot\/(\d+(\.\d+)+)/i,e)||i.default.getFirstMatch(n,e);return r&&(t.version=r),t}},{test:[/meta-webindexer/i],describe:function(e){var t={name:"Meta-WebIndexer"},r=i.default.getFirstMatch(/meta-webindexer\/(\d+(\.\d+)+)/i,e)||i.default.getFirstMatch(n,e);return r&&(t.version=r),t}},{test:[/meta-externalads/i],describe:function(e){var t={name:"Meta-ExternalAds"},r=i.default.getFirstMatch(/meta-externalads\/(\d+(\.\d+)+)/i,e)||i.default.getFirstMatch(n,e);return r&&(t.version=r),t}},{test:[/meta-externalagent/i],describe:function(e){var t={name:"Meta-ExternalAgent"},r=i.default.getFirstMatch(/meta-externalagent\/(\d+(\.\d+)+)/i,e)||i.default.getFirstMatch(n,e);return r&&(t.version=r),t}},{test:[/meta-externalfetcher/i],describe:function(e){var t={name:"Meta-ExternalFetcher"},r=i.default.getFirstMatch(/meta-externalfetcher\/(\d+(\.\d+)+)/i,e)||i.default.getFirstMatch(n,e);return r&&(t.version=r),t}},{test:[/googlebot/i],describe:function(e){var t={name:"Googlebot"},r=i.default.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,e)||i.default.getFirstMatch(n,e);return r&&(t.version=r),t}},{test:[/linespider/i],describe:function(e){var t={name:"Linespider"},r=i.default.getFirstMatch(/(?:linespider)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,e)||i.default.getFirstMatch(n,e);return r&&(t.version=r),t}},{test:[/amazonbot/i],describe:function(e){var t={name:"AmazonBot"},r=i.default.getFirstMatch(/amazonbot\/(\d+(\.\d+)+)/i,e)||i.default.getFirstMatch(n,e);return r&&(t.version=r),t}},{test:[/bingbot/i],describe:function(e){var t={name:"BingCrawler"},r=i.default.getFirstMatch(/bingbot\/(\d+(\.\d+)+)/i,e)||i.default.getFirstMatch(n,e);return r&&(t.version=r),t}},{test:[/baiduspider/i],describe:function(e){var t={name:"BaiduSpider"},r=i.default.getFirstMatch(/baiduspider\/(\d+(\.\d+)+)/i,e)||i.default.getFirstMatch(n,e);return r&&(t.version=r),t}},{test:[/duckduckbot/i],describe:function(e){var t={name:"DuckDuckBot"},r=i.default.getFirstMatch(/duckduckbot\/(\d+(\.\d+)+)/i,e)||i.default.getFirstMatch(n,e);return r&&(t.version=r),t}},{test:[/ia_archiver/i],describe:function(e){var t={name:"InternetArchiveCrawler"},r=i.default.getFirstMatch(/ia_archiver\/(\d+(\.\d+)+)/i,e)||i.default.getFirstMatch(n,e);return r&&(t.version=r),t}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe:function(){return{name:"FacebookExternalHit"}}},{test:[/slackbot/i,/slack-imgProxy/i],describe:function(e){var t={name:"SlackBot"},r=i.default.getFirstMatch(/(?:slackbot|slack-imgproxy)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,e)||i.default.getFirstMatch(n,e);return r&&(t.version=r),t}},{test:[/yahoo!?[\s/]*slurp/i],describe:function(){return{name:"YahooSlurp"}}},{test:[/yandexbot/i,/yandexmobilebot/i],describe:function(){return{name:"YandexBot"}}},{test:[/pingdom/i],describe:function(){return{name:"PingdomBot"}}},{test:[/opera/i],describe:function(e){var t={name:"Opera"},r=i.default.getFirstMatch(n,e)||i.default.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/opr\/|opios/i],describe:function(e){var t={name:"Opera"},r=i.default.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,e)||i.default.getFirstMatch(n,e);return r&&(t.version=r),t}},{test:[/SamsungBrowser/i],describe:function(e){var t={name:"Samsung Internet for Android"},r=i.default.getFirstMatch(n,e)||i.default.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/Whale/i],describe:function(e){var t={name:"NAVER Whale Browser"},r=i.default.getFirstMatch(n,e)||i.default.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/PaleMoon/i],describe:function(e){var t={name:"Pale Moon"},r=i.default.getFirstMatch(n,e)||i.default.getFirstMatch(/(?:PaleMoon)[\s/](\d+(?:\.\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/MZBrowser/i],describe:function(e){var t={name:"MZ Browser"},r=i.default.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,e)||i.default.getFirstMatch(n,e);return r&&(t.version=r),t}},{test:[/focus/i],describe:function(e){var t={name:"Focus"},r=i.default.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,e)||i.default.getFirstMatch(n,e);return r&&(t.version=r),t}},{test:[/swing/i],describe:function(e){var t={name:"Swing"},r=i.default.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,e)||i.default.getFirstMatch(n,e);return r&&(t.version=r),t}},{test:[/coast/i],describe:function(e){var t={name:"Opera Coast"},r=i.default.getFirstMatch(n,e)||i.default.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe:function(e){var t={name:"Opera Touch"},r=i.default.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(n,e);return r&&(t.version=r),t}},{test:[/yabrowser/i],describe:function(e){var t={name:"Yandex Browser"},r=i.default.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(n,e);return r&&(t.version=r),t}},{test:[/ucbrowser/i],describe:function(e){var t={name:"UC Browser"},r=i.default.getFirstMatch(n,e)||i.default.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/Maxthon|mxios/i],describe:function(e){var t={name:"Maxthon"},r=i.default.getFirstMatch(n,e)||i.default.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/epiphany/i],describe:function(e){var t={name:"Epiphany"},r=i.default.getFirstMatch(n,e)||i.default.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/puffin/i],describe:function(e){var t={name:"Puffin"},r=i.default.getFirstMatch(n,e)||i.default.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/sleipnir/i],describe:function(e){var t={name:"Sleipnir"},r=i.default.getFirstMatch(n,e)||i.default.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/k-meleon/i],describe:function(e){var t={name:"K-Meleon"},r=i.default.getFirstMatch(n,e)||i.default.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/micromessenger/i],describe:function(e){var t={name:"WeChat"},r=i.default.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(n,e);return r&&(t.version=r),t}},{test:[/qqbrowser/i],describe:function(e){var t={name:/qqbrowserlite/i.test(e)?"QQ Browser Lite":"QQ Browser"},r=i.default.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(n,e);return r&&(t.version=r),t}},{test:[/msie|trident/i],describe:function(e){var t={name:"Internet Explorer"},r=i.default.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/\sedg\//i],describe:function(e){var t={name:"Microsoft Edge"},r=i.default.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/edg([ea]|ios)/i],describe:function(e){var t={name:"Microsoft Edge"},r=i.default.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/vivaldi/i],describe:function(e){var t={name:"Vivaldi"},r=i.default.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/seamonkey/i],describe:function(e){var t={name:"SeaMonkey"},r=i.default.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/sailfish/i],describe:function(e){var t={name:"Sailfish"},r=i.default.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,e);return r&&(t.version=r),t}},{test:[/silk/i],describe:function(e){var t={name:"Amazon Silk"},r=i.default.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/phantom/i],describe:function(e){var t={name:"PhantomJS"},r=i.default.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/slimerjs/i],describe:function(e){var t={name:"SlimerJS"},r=i.default.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(e){var t={name:"BlackBerry"},r=i.default.getFirstMatch(n,e)||i.default.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/(web|hpw)[o0]s/i],describe:function(e){var t={name:"WebOS Browser"},r=i.default.getFirstMatch(n,e)||i.default.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/bada/i],describe:function(e){var t={name:"Bada"},r=i.default.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/tizen/i],describe:function(e){var t={name:"Tizen"},r=i.default.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(n,e);return r&&(t.version=r),t}},{test:[/qupzilla/i],describe:function(e){var t={name:"QupZilla"},r=i.default.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(n,e);return r&&(t.version=r),t}},{test:[/librewolf/i],describe:function(e){var t={name:"LibreWolf"},r=i.default.getFirstMatch(/(?:librewolf)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/firefox|iceweasel|fxios/i],describe:function(e){var t={name:"Firefox"},r=i.default.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/electron/i],describe:function(e){var t={name:"Electron"},r=i.default.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/sogoumobilebrowser/i,/metasr/i,/se 2\.[x]/i],describe:function(e){var t={name:"Sogou Browser"},r=i.default.getFirstMatch(/(?:sogoumobilebrowser)[\s/](\d+(\.?_?\d+)+)/i,e),l=i.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),s=i.default.getFirstMatch(/se ([\d.]+)x/i,e),a=r||l||s;return a&&(t.version=a),t}},{test:[/MiuiBrowser/i],describe:function(e){var t={name:"Miui"},r=i.default.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:function(e){return!!e.hasBrand("DuckDuckGo")||e.test(/\sDdg\/[\d.]+$/i)},describe:function(e,t){var r={name:"DuckDuckGo"};if(t){var l=t.getBrandVersion("DuckDuckGo");if(l)return r.version=l,r}var s=i.default.getFirstMatch(/\sDdg\/([\d.]+)$/i,e);return s&&(r.version=s),r}},{test:function(e){return e.hasBrand("Brave")},describe:function(e,t){var r={name:"Brave"};if(t){var l=t.getBrandVersion("Brave");if(l)return r.version=l,r}return r}},{test:[/chromium/i],describe:function(e){var t={name:"Chromium"},r=i.default.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(n,e);return r&&(t.version=r),t}},{test:[/chrome|crios|crmo/i],describe:function(e){var t={name:"Chrome"},r=i.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/GSA/i],describe:function(e){var t={name:"Google Search"},r=i.default.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:function(e){var t=!e.test(/like android/i),r=e.test(/android/i);return t&&r},describe:function(e){var t={name:"Android Browser"},r=i.default.getFirstMatch(n,e);return r&&(t.version=r),t}},{test:[/playstation 4/i],describe:function(e){var t={name:"PlayStation 4"},r=i.default.getFirstMatch(n,e);return r&&(t.version=r),t}},{test:[/safari|applewebkit/i],describe:function(e){var t={name:"Safari"},r=i.default.getFirstMatch(n,e);return r&&(t.version=r),t}},{test:[/.*/i],describe:function(e){var t=e.search("\\(")!==-1?/^(.*)\/(.*)[ \t]\((.*)/:/^(.*)\/(.*) /;return{name:i.default.getFirstMatch(t,e),version:i.default.getSecondMatch(t,e)}}}];d.default=f,g.exports=d.default},93:function(g,d,b){"use strict";d.__esModule=!0,d.default=void 0;var u,i=(u=b(17))&&u.__esModule?u:{default:u},n=b(18),f=[{test:[/Roku\/DVP/],describe:function(e){var t=i.default.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,e);return{name:n.OS_MAP.Roku,version:t}}},{test:[/windows phone/i],describe:function(e){var t=i.default.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,e);return{name:n.OS_MAP.WindowsPhone,version:t}}},{test:[/windows /i],describe:function(e){var t=i.default.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,e),r=i.default.getWindowsVersionName(t);return{name:n.OS_MAP.Windows,version:t,versionName:r}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(e){var t={name:n.OS_MAP.iOS},r=i.default.getSecondMatch(/(Version\/)(\d[\d.]+)/,e);return r&&(t.version=r),t}},{test:[/macintosh/i],describe:function(e){var t=i.default.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,e).replace(/[_\s]/g,"."),r=i.default.getMacOSVersionName(t),l={name:n.OS_MAP.MacOS,version:t};return r&&(l.versionName=r),l}},{test:[/(ipod|iphone|ipad)/i],describe:function(e){var t=i.default.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,e).replace(/[_\s]/g,".");return{name:n.OS_MAP.iOS,version:t}}},{test:[/OpenHarmony/i],describe:function(e){var t=i.default.getFirstMatch(/OpenHarmony\s+(\d+(\.\d+)*)/i,e);return{name:n.OS_MAP.HarmonyOS,version:t}}},{test:function(e){var t=!e.test(/like android/i),r=e.test(/android/i);return t&&r},describe:function(e){var t=i.default.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,e),r=i.default.getAndroidVersionName(t),l={name:n.OS_MAP.Android,version:t};return r&&(l.versionName=r),l}},{test:[/(web|hpw)[o0]s/i],describe:function(e){var t=i.default.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,e),r={name:n.OS_MAP.WebOS};return t&&t.length&&(r.version=t),r}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(e){var t=i.default.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,e)||i.default.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,e)||i.default.getFirstMatch(/\bbb(\d+)/i,e);return{name:n.OS_MAP.BlackBerry,version:t}}},{test:[/bada/i],describe:function(e){var t=i.default.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,e);return{name:n.OS_MAP.Bada,version:t}}},{test:[/tizen/i],describe:function(e){var t=i.default.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,e);return{name:n.OS_MAP.Tizen,version:t}}},{test:[/linux/i],describe:function(){return{name:n.OS_MAP.Linux}}},{test:[/CrOS/],describe:function(){return{name:n.OS_MAP.ChromeOS}}},{test:[/PlayStation 4/],describe:function(e){var t=i.default.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,e);return{name:n.OS_MAP.PlayStation4,version:t}}}];d.default=f,g.exports=d.default},94:function(g,d,b){"use strict";d.__esModule=!0,d.default=void 0;var u,i=(u=b(17))&&u.__esModule?u:{default:u},n=b(18),f=[{test:[/googlebot/i],describe:function(){return{type:n.PLATFORMS_MAP.bot,vendor:"Google"}}},{test:[/linespider/i],describe:function(){return{type:n.PLATFORMS_MAP.bot,vendor:"Line"}}},{test:[/amazonbot/i],describe:function(){return{type:n.PLATFORMS_MAP.bot,vendor:"Amazon"}}},{test:[/gptbot/i],describe:function(){return{type:n.PLATFORMS_MAP.bot,vendor:"OpenAI"}}},{test:[/chatgpt-user/i],describe:function(){return{type:n.PLATFORMS_MAP.bot,vendor:"OpenAI"}}},{test:[/oai-searchbot/i],describe:function(){return{type:n.PLATFORMS_MAP.bot,vendor:"OpenAI"}}},{test:[/baiduspider/i],describe:function(){return{type:n.PLATFORMS_MAP.bot,vendor:"Baidu"}}},{test:[/bingbot/i],describe:function(){return{type:n.PLATFORMS_MAP.bot,vendor:"Bing"}}},{test:[/duckduckbot/i],describe:function(){return{type:n.PLATFORMS_MAP.bot,vendor:"DuckDuckGo"}}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe:function(){return{type:n.PLATFORMS_MAP.bot,vendor:"Anthropic"}}},{test:[/omgilibot/i,/webzio-extended/i],describe:function(){return{type:n.PLATFORMS_MAP.bot,vendor:"Webz.io"}}},{test:[/diffbot/i],describe:function(){return{type:n.PLATFORMS_MAP.bot,vendor:"Diffbot"}}},{test:[/perplexitybot/i],describe:function(){return{type:n.PLATFORMS_MAP.bot,vendor:"Perplexity AI"}}},{test:[/perplexity-user/i],describe:function(){return{type:n.PLATFORMS_MAP.bot,vendor:"Perplexity AI"}}},{test:[/youbot/i],describe:function(){return{type:n.PLATFORMS_MAP.bot,vendor:"You.com"}}},{test:[/ia_archiver/i],describe:function(){return{type:n.PLATFORMS_MAP.bot,vendor:"Internet Archive"}}},{test:[/meta-webindexer/i],describe:function(){return{type:n.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/meta-externalads/i],describe:function(){return{type:n.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/meta-externalagent/i],describe:function(){return{type:n.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/meta-externalfetcher/i],describe:function(){return{type:n.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe:function(){return{type:n.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/slackbot/i,/slack-imgProxy/i],describe:function(){return{type:n.PLATFORMS_MAP.bot,vendor:"Slack"}}},{test:[/yahoo/i],describe:function(){return{type:n.PLATFORMS_MAP.bot,vendor:"Yahoo"}}},{test:[/yandexbot/i,/yandexmobilebot/i],describe:function(){return{type:n.PLATFORMS_MAP.bot,vendor:"Yandex"}}},{test:[/pingdom/i],describe:function(){return{type:n.PLATFORMS_MAP.bot,vendor:"Pingdom"}}},{test:[/huawei/i],describe:function(e){var t=i.default.getFirstMatch(/(can-l01)/i,e)&&"Nova",r={type:n.PLATFORMS_MAP.mobile,vendor:"Huawei"};return t&&(r.model=t),r}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe:function(){return{type:n.PLATFORMS_MAP.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe:function(){return{type:n.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(){return{type:n.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe:function(){return{type:n.PLATFORMS_MAP.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe:function(){return{type:n.PLATFORMS_MAP.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe:function(){return{type:n.PLATFORMS_MAP.tablet}}},{test:function(e){var t=e.test(/ipod|iphone/i),r=e.test(/like (ipod|iphone)/i);return t&&!r},describe:function(e){var t=i.default.getFirstMatch(/(ipod|iphone)/i,e);return{type:n.PLATFORMS_MAP.mobile,vendor:"Apple",model:t}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe:function(){return{type:n.PLATFORMS_MAP.mobile,vendor:"Nexus"}}},{test:[/Nokia/i],describe:function(e){var t=i.default.getFirstMatch(/Nokia\s+([0-9]+(\.[0-9]+)?)/i,e),r={type:n.PLATFORMS_MAP.mobile,vendor:"Nokia"};return t&&(r.model=t),r}},{test:[/[^-]mobi/i],describe:function(){return{type:n.PLATFORMS_MAP.mobile}}},{test:function(e){return e.getBrowserName(!0)==="blackberry"},describe:function(){return{type:n.PLATFORMS_MAP.mobile,vendor:"BlackBerry"}}},{test:function(e){return e.getBrowserName(!0)==="bada"},describe:function(){return{type:n.PLATFORMS_MAP.mobile}}},{test:function(e){return e.getBrowserName()==="windows phone"},describe:function(){return{type:n.PLATFORMS_MAP.mobile,vendor:"Microsoft"}}},{test:function(e){var t=Number(String(e.getOSVersion()).split(".")[0]);return e.getOSName(!0)==="android"&&t>=3},describe:function(){return{type:n.PLATFORMS_MAP.tablet}}},{test:function(e){return e.getOSName(!0)==="android"},describe:function(){return{type:n.PLATFORMS_MAP.mobile}}},{test:[/smart-?tv|smarttv/i],describe:function(){return{type:n.PLATFORMS_MAP.tv}}},{test:[/netcast/i],describe:function(){return{type:n.PLATFORMS_MAP.tv}}},{test:function(e){return e.getOSName(!0)==="macos"},describe:function(){return{type:n.PLATFORMS_MAP.desktop,vendor:"Apple"}}},{test:function(e){return e.getOSName(!0)==="windows"},describe:function(){return{type:n.PLATFORMS_MAP.desktop}}},{test:function(e){return e.getOSName(!0)==="linux"},describe:function(){return{type:n.PLATFORMS_MAP.desktop}}},{test:function(e){return e.getOSName(!0)==="playstation 4"},describe:function(){return{type:n.PLATFORMS_MAP.tv}}},{test:function(e){return e.getOSName(!0)==="roku"},describe:function(){return{type:n.PLATFORMS_MAP.tv}}}];d.default=f,g.exports=d.default},95:function(g,d,b){"use strict";d.__esModule=!0,d.default=void 0;var u,i=(u=b(17))&&u.__esModule?u:{default:u},n=b(18),f=[{test:function(e){return e.getBrowserName(!0)==="microsoft edge"},describe:function(e){if(/\sedg\//i.test(e))return{name:n.ENGINE_MAP.Blink};var t=i.default.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,e);return{name:n.ENGINE_MAP.EdgeHTML,version:t}}},{test:[/trident/i],describe:function(e){var t={name:n.ENGINE_MAP.Trident},r=i.default.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:function(e){return e.test(/presto/i)},describe:function(e){var t={name:n.ENGINE_MAP.Presto},r=i.default.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:function(e){var t=e.test(/gecko/i),r=e.test(/like gecko/i);return t&&!r},describe:function(e){var t={name:n.ENGINE_MAP.Gecko},r=i.default.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/(apple)?webkit\/537\.36/i],describe:function(){return{name:n.ENGINE_MAP.Blink}}},{test:[/(apple)?webkit/i],describe:function(e){var t={name:n.ENGINE_MAP.WebKit},r=i.default.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}}];d.default=f,g.exports=d.default}})}))});export default x();
@@ -1,4 +0,0 @@
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 a,g as b,h as c}from"./chunk-LEUENXI2.js";import"./chunk-HALUQ7ZF.js";import"./chunk-Q4UGYGU5.js";import"./chunk-W5LGYSPZ.js";import"./chunk-NAA7GF6Q.js";import"./chunk-J5DVLUKY.js";import"./chunk-WHC7AYZD.js";export{b as ExecutionRepo,a as TERMINAL_STATUSES,c as executionRepo};
@@ -1,4 +0,0 @@
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 g,c as F}from"./chunk-XNSSUVT6.js";import{a as y}from"./chunk-PXS5SHOV.js";import{a as h}from"./chunk-NT32UURL.js";import"./chunk-LMDWRRX4.js";import"./chunk-TAWLERZA.js";import"./chunk-CQLH4UVX.js";import"./chunk-OKRK6JPY.js";import"./chunk-OE4KH3NJ.js";import"./chunk-KRXTI4JO.js";import{J as l}from"./chunk-DPQPXBTP.js";import"./chunk-NAA7GF6Q.js";import"./chunk-J5DVLUKY.js";import"./chunk-WHC7AYZD.js";import*as b from"fs";import*as d from"path";function m(e){return{content:[{type:"text",text:typeof e=="string"?e:JSON.stringify(e,null,2)}]}}function w(e){return{content:[{type:"text",text:e}],isError:!0}}var S="Feishu is not configured (missing FEISHU_APP_ID / FEISHU_APP_SECRET). Set them in the Cortex config and restart, and grant the app docx/drive/wiki/bitable/sheets scopes.";function x(e){let t=e;if(t&&typeof t.code=="number"&&t.code!==0)throw new Error(`Feishu API error ${t.code}: ${t.msg??"unknown"}`);return t?.data??t}async function _(e,t){if(!e)return w(S);try{return await t(e)}catch(i){return w(`Feishu operation failed: ${i.message}`)}}function E(e){let t=d.extname(e).toLowerCase();return{".pdf":"pdf",".doc":"doc",".xls":"xls",".ppt":"ppt",".mp4":"mp4",".opus":"opus"}[t]||"stream"}async function N(e,t,i){let n=await e.im.v1.file.create({data:{file_type:E(i),file_name:i,file:b.readFileSync(t)}}),c=x(n).file_key;if(!c)throw new Error("Feishu file upload failed: no file_key returned");return c}async function k(e,{channel:t,filePath:i,fileName:n,title:c}){let{resolved:r,size:a}=h(i),p=n||d.basename(r),f=g(t,"feishu:"),s=await y(e,r,a),u=s?"image":"file",o=JSON.stringify(s?{image_key:s}:{file_key:await N(e,r,p)});return await e.im.v1.message.create({params:{receive_id_type:"chat_id"},data:{receive_id:f,msg_type:u,content:o}}),{path:r,fileName:p,size:a}}function z(e,t){e.tool("feishu_send_file","Share a local or remote-device file in Feishu.",{file_path:l.string().describe("File path to upload. Local path, or an absolute path on `device`."),file_name:l.string().optional().describe("Optional filename override shown in Feishu"),title:l.string().optional().describe("Optional file title shown in Feishu"),channel:l.string().optional().describe("Optional chat/channel ID (uses route context if not provided)"),device:l.string().optional().describe("Connected device to read from; omit for this server.")},async({file_path:i,file_name:n,title:c,channel:r,device:a})=>_(t.client,async p=>{let f=r||t.fallbackChannel||"";if(!f)throw new Error("No Feishu channel available (no session channel or channel parameter)");let s=(o,v)=>k(p,{channel:f,filePath:o,fileName:v,title:c});if(!a){let o=await s(i,n);return m(`File uploaded: ${o.fileName} (${o.size} bytes)`)}let u=await F(t.ctx,a,i,o=>s(o.localPath,n||o.name));return m(`File uploaded from ${a}: ${u.fileName} (${u.size} bytes)`)}))}export{z as registerFileTools,k as uploadFileToFeishu};
@@ -1,36 +0,0 @@
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 pt}from"./chunk-XSRZHN63.js";import{a as mt,b as de,c as pe,d as D,e as me,f as gt,g as B,h as ge}from"./chunk-YZSHTWNM.js";import{a as he}from"./chunk-JERCOLY3.js";import{e as fe}from"./chunk-WHC7AYZD.js";var Dt=fe(he(),1);import*as d from"fs";import*as b from"path";import*as Mt from"os";import*as Ut from"crypto";import*as g from"fs";import*as q from"path";import*as E from"fs";import*as W from"path";import*as Ct from"os";import*as x from"fs";import*as Pt from"os";import*as z from"path";import{randomUUID as fn}from"crypto";var _e={500:15,502:10,503:10,529:30},ye=10;function Et(t){return t>=500}var L=60,ke=5;function _t(){return{cooldownUntil:0,errors:[],totalRequests:0,totalErrors:0}}function I(){return Date.now()/1e3}var we=500,Tt=class{_state=new Map;_modelState=new Map;_getState(t,e){if(e!=null){let s=`${t}\0${e}`,r=this._modelState.get(s);return r||(r=_t(),this._modelState.set(s,r),this._modelState.size>we&&this._evictModelState()),r}let n=this._state.get(t);return n||(n=_t(),this._state.set(t,n)),n}_evictModelState(){let t=I()-L*2;for(let[e,n]of this._modelState)(n.errors.length>0?n.errors[n.errors.length-1]:0)<t&&n.cooldownUntil<I()&&this._modelState.delete(e)}isHealthy(t,e){let n=this._getState(t,e),s=I();if(s<n.cooldownUntil)return!1;let r=s-L,o=0;for(let i of n.errors)i>r&&o++;return o<ke}recordError(t,e,n){let s=this._getState(t,n),r=I();if(s.totalRequests++,!Et(e))return;s.errors.push(r),s.errors.length>50&&s.errors.splice(0,s.errors.length-50),s.totalErrors++;let o=_e[e]??ye;s.cooldownUntil=Math.max(s.cooldownUntil,r+o)}soonestCooldown(t){let e=null,n=I();for(let s of t){let r=this._state.get(s),o=r?Math.max(0,r.cooldownUntil-n):0;(!e||o<e.remaining)&&(e={id:s,remaining:o})}return e}recordSuccess(t,e){let n=this._getState(t,e);n.totalRequests++,n.cooldownUntil=0}errorCount(t,e){return this._getState(t,e).totalErrors}summary(){let t=I(),e={};for(let[n,s]of this._state){let r=t-L,o=0;for(let i of s.errors)i>r&&o++;e[n]={healthy:this.isHealthy(n),recent_errors:o,total_errors:s.totalErrors,total_requests:s.totalRequests,cooldown_remaining:Math.max(0,Math.round((s.cooldownUntil-t)*10)/10)}}if(this._modelState.size>0){let n={};for(let[s,r]of this._modelState){let[o,i]=s.split("\0"),a=t-L,c=0;for(let u of r.errors)u>a&&c++;let l=`${o}/${i}`;n[l]={healthy:this.isHealthy(o,i),recent_errors:c,total_errors:r.totalErrors,total_requests:r.totalRequests,cooldown_remaining:Math.max(0,Math.round((r.cooldownUntil-t)*10)/10)}}e.model_health=n}return e}},ot=["model","provider","billing_mode"];function Ot(t){return t===void 0?[]:Array.isArray(t)?[...t]:[t]}var be=256*1024,Se=64,ve=/^(\d{4}-\d{2})\.jsonl$/,Ee=class{constructor(t){this.projectDir=t}files=new Map;providerIds=new Map;providers=[];modelIds=new Map;models=[];billingModeIds=new Map;billingModes=[];interners={provider:t=>X(t,this.providerIds,this.providers),model:t=>X(t,this.modelIds,this.models),billingMode:t=>X(t,this.billingModeIds,this.billingModes)};prewarm(t="month"){this.syncFiles(t)}report(t="month",e){let n=Ot(e),s=nt(t),r=this.syncFiles(t),o=n.map(l=>this.groupNames(l)),i=o.map(l=>Math.max(l.length,1)),a=It(),c=new Map;for(let l of r){let u=this.files.get(l);u&&Re(u.columns,s,n,i,a,c)}return Be(t,n,i,a,c,o)}syncFiles(t){let e=Te(this.projectDir,nt(t));for(let n of e)this.syncFile(n);return e}syncFile(t){let e=g.statSync(t),n=this.files.get(t);if(!n||Oe(t,n,e)){this.files.set(t,this.loadFile(t));return}e.size>n.readOffset&&this.extendFile(t,n)}loadFile(t){let e=xe(),n=yt(t,0,s=>{kt(e,s,this.interners)});return{columns:e,readOffset:n.readOffset,guard:st(t,n.readOffset),dev:n.stat.dev,ino:n.stat.ino,mtimeMs:n.stat.mtimeMs,ctimeMs:n.stat.ctimeMs}}extendFile(t,e){let n=yt(t,e.readOffset,s=>{kt(e.columns,s,this.interners)});e.readOffset=n.readOffset,e.guard=st(t,n.readOffset),e.dev=n.stat.dev,e.ino=n.stat.ino,e.mtimeMs=n.stat.mtimeMs,e.ctimeMs=n.stat.ctimeMs}groupNames(t){return t==="model"?this.models:t==="billing_mode"?this.billingModes:this.providers}};function nt(t,e=new Date){if(t==="today")return new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime();if(t==="week")return e.getTime()-7*864e5;if(t==="month")return e.getTime()-30*864e5;if(t==="all")return null;throw new Error(`Unsupported period: ${t}`)}function Te(t,e){if(!g.existsSync(t))return[];let n=e===null?null:Ue(new Date(e));return g.readdirSync(t).filter(s=>s.endsWith(".jsonl")).map(s=>q.join(t,s)).filter(s=>Me(s,n,e)).sort()}function Me(t,e,n){if(e===null||n===null)return!0;let s=q.basename(t).match(ve);return s===null||s[1]>=e?!0:g.statSync(t).mtimeMs>=n}function Ue(t){let e=String(t.getUTCMonth()+1).padStart(2,"0");return`${t.getUTCFullYear()}-${e}`}function Oe(t,e,n){return n.dev!==e.dev||n.ino!==e.ino||n.size<e.readOffset||n.size===e.readOffset&&$e(e,n)?!0:!st(t,e.readOffset).equals(e.guard)}function $e(t,e){return e.mtimeMs!==t.mtimeMs||e.ctimeMs!==t.ctimeMs}function st(t,e){let n=Math.min(e,Se);if(n===0)return Buffer.alloc(0);let s=g.openSync(t,"r");try{let r=Buffer.allocUnsafe(n),o=g.readSync(s,r,0,n,e-n);return r.subarray(0,o)}finally{g.closeSync(s)}}function yt(t,e,n){let s=g.openSync(t,"r");try{return{readOffset:Ie(s,e,n),stat:g.fstatSync(s)}}finally{g.closeSync(s)}}function Ie(t,e,n){let s=Buffer.allocUnsafe(be),r=Buffer.alloc(0),o=e;for(;;){let i=g.readSync(t,s,0,s.length,o);if(i===0)break;o+=i,r=Ne(Buffer.concat([r,s.subarray(0,i)]),n)}return o-r.length}function Ne(t,e){let n=0;for(;;){let s=t.indexOf(10,n);if(s<0)return Buffer.from(t.subarray(n));Ae(t.subarray(n,s),e),n=s+1}}function Ae(t,e){if(t.length!==0)try{e(JSON.parse(t.toString("utf8")))}catch{}}function xe(){return{timestamps:[],providerIds:[],modelIds:[],billingModeIds:[],inputs:[],outputs:[],costs:[],fallbacks:[],latencies:[]}}function kt(t,e,n){t.timestamps.push(Ce(e.ts)),t.providerIds.push(n.provider(String(e.provider??"unknown"))),t.modelIds.push(n.model(String(e.model??"unknown"))),t.billingModeIds.push(n.billingMode(String(e.billing_mode??"unknown"))),t.inputs.push(Z(e.in)),t.outputs.push(Z(e.out)),t.costs.push(rt(e.cost)),t.fallbacks.push(e.fallback?1:0),t.latencies.push(Z(e.latency_ms))}function Ce(t){if(typeof t!="string")return Number.NEGATIVE_INFINITY;let e=Date.parse(t);return Number.isFinite(e)?e:Number.NEGATIVE_INFINITY}function Re(t,e,n,s,r,o){let i=n.map(a=>De(t,a));for(let a=0;a<t.timestamps.length;a++)e!==null&&t.timestamps[a]<e||($t(r,t,a,!1),i.length>0&&je(o,Fe(i,s,a),t,a))}function Fe(t,e,n){let s=0;for(let r=0;r<t.length;r++)s=s*e[r]+t[r][n];return s}function Pe(t,e){let n=new Array(e.length),s=t;for(let r=e.length-1;r>=0;r--)n[r]=s%e[r],s=Math.floor(s/e[r]);return n}function De(t,e){return e==="model"?t.modelIds:e==="billing_mode"?t.billingModeIds:t.providerIds}function je(t,e,n,s){let r=t.get(e)??It();$t(r,n,s,!0),t.set(e,r)}function $t(t,e,n,s){t.requests++,t.input_tokens+=e.inputs[n],t.output_tokens+=e.outputs[n];let r=t.cost_usd+e.costs[n];t.cost_usd=s?At(r):r,t.fallback_requests+=e.fallbacks[n],t.latency_sum+=e.latencies[n]}function Be(t,e,n,s,r,o){let i={summary:qe(s,t)};if(e.length===0)return i;let a=e.length===1?`${e[0]}s`:"rows";return i[a]=Le(e,n,r,o),i}function Le(t,e,n,s){let r=[...n].map(([o,i])=>{let a=Pe(o,e);return We(t.map((c,l)=>[c,s[l][a[l]]??"unknown"]),i)});return r.sort((o,i)=>rt(i.cost_usd)-rt(o.cost_usd)||He(t,o,i)),r}function He(t,e,n){for(let s of t){let r=String(e[s]??"").localeCompare(String(n[s]??""));if(r!==0)return r}return 0}function qe(t,e){return{period:e,requests:t.requests,input_tokens:t.input_tokens,output_tokens:t.output_tokens,cost_usd:At(t.cost_usd),avg_latency_ms:Nt(t),fallback_requests:t.fallback_requests}}function We(t,e){return{...Object.fromEntries(t),requests:e.requests,input_tokens:e.input_tokens,output_tokens:e.output_tokens,cost_usd:e.cost_usd,avg_latency_ms:Nt(e),fallback_requests:e.fallback_requests}}function It(){return{requests:0,input_tokens:0,output_tokens:0,cost_usd:0,fallback_requests:0,latency_sum:0}}function Nt(t){return t.requests===0?0:Math.round(t.latency_sum/t.requests*100)/100}function X(t,e,n){let s=e.get(t);if(s!==void 0)return s;let r=n.length;return e.set(t,r),n.push(t),r}function Z(t){let e=Number(t);return Number.isFinite(e)?Math.floor(e):0}function rt(t){let e=Number(t);return Number.isFinite(e)?e:0}function At(t){return Math.round(t*1e8)/1e8}var ze=class{_baseDir;_projectDir;_aggregateIndex;constructor(t,e){this._baseDir=t??b.join(Mt.homedir(),".aistatus","usage");let n=e??process.cwd(),s=Ut.createHash("sha256").update(n).digest("hex").slice(0,12);this._projectDir=b.join(this._baseDir,"projects",s),d.mkdirSync(this._projectDir,{recursive:!0}),this._ensureManifest(n),this._aggregateIndex=new Ee(this._projectDir)}append(t){let e=this._monthKey(t.ts),n=b.join(this._projectDir,`${e}.jsonl`);d.appendFileSync(n,JSON.stringify(t)+`
5
- `,"utf-8")}aggregate(t="month",e){return this._aggregateIndex.report(t,e)}prewarm(t="month"){this._aggregateIndex.prewarm(t)}read(t="month",e=!1){let n=e?this._allProjectDirs():[this._projectDir],s=Ge(t),r=[];for(let o of n){if(!d.existsSync(o))continue;let i=d.readdirSync(o).filter(a=>a.endsWith(".jsonl")).sort();for(let a of i){let c=b.join(o,a),l=d.readFileSync(c,"utf-8");for(let u of l.split(`
6
- `)){if(!u.trim())continue;let f;try{f=JSON.parse(u)}catch{continue}if(s){let h=wt(f.ts);if(!h||h<s)continue}f.project||(f.project=b.basename(o)),r.push(f)}}}return r}exportCsv(t,e){let n=["ts","project","provider","model","in","out","cost","fallback","latency_ms"],s=n.join(","),r=t.map(o=>n.map(i=>String(o[i]??"")).join(","));d.mkdirSync(b.dirname(e),{recursive:!0}),d.writeFileSync(e,[s,...r].join(`
7
- `)+`
8
- `,"utf-8")}exportJson(t,e){d.mkdirSync(b.dirname(e),{recursive:!0}),d.writeFileSync(e,JSON.stringify(t,null,2),"utf-8")}_ensureManifest(t){let e=b.join(this._projectDir,"manifest.json");if(d.existsSync(e))return;let n={path:t,created:new Date().toISOString()};d.writeFileSync(e,JSON.stringify(n,null,2),"utf-8")}_allProjectDirs(){let t=b.join(this._baseDir,"projects");return d.existsSync(t)?d.readdirSync(t).map(e=>b.join(t,e)).filter(e=>d.statSync(e).isDirectory()):[]}_monthKey(t){let e=wt(t)??new Date,n=e.getUTCFullYear(),s=String(e.getUTCMonth()+1).padStart(2,"0");return`${n}-${s}`}};function wt(t){if(!t||typeof t!="string")return null;let e=new Date(t);return isNaN(e.getTime())?null:e}function Ge(t){let e=nt(t);return e===null?null:new Date(e)}var xt=class{storage;uploader;constructor(t,e){this.storage=t??new ze,this.uploader=e??null}recordUsage(t){let e=new Set(["ts","provider","model","in","out","cost","fallback","latency_ms","billing_mode","cache_creation_in","cache_read_in"]),n={ts:new Date().toISOString(),provider:t.provider,model:t.model,in:t.input_tokens,out:t.output_tokens,cost:it(t.cost??0),fallback:t.fallback,latency_ms:t.latency_ms,billing_mode:t.billing_mode};if(t.cache_creation_input_tokens&&(n.cache_creation_in=t.cache_creation_input_tokens),t.cache_read_input_tokens&&(n.cache_read_in=t.cache_read_input_tokens),t.metadata)for(let[s,r]of Object.entries(t.metadata))e.has(s)||(n[s]=r);return this.storage.append(n),this.uploader?.upload(n),n}prewarm(t="month"){this.storage.prewarm?.(t)}report(t="month",e){if(typeof this.storage.aggregate=="function")return this.storage.aggregate(t,e);let n=this.storage.read(t),s=Ot(e),r={summary:Je(n,t)};return s.length===0||(r[s.length===1?`${s[0]}s`:"rows"]=Ke(n,s)),r}summary(t="month"){return this.report(t).summary}byModel(t="month"){return this.report(t,"model").models}byProvider(t="month"){return this.report(t,"provider").providers}};function Je(t,e){let n=t.length,s=t.reduce((a,c)=>a+A(c.in),0),r=t.reduce((a,c)=>a+A(c.out),0),o=it(t.reduce((a,c)=>a+H(c.cost),0)),i=t.reduce((a,c)=>a+A(c.latency_ms),0);return{period:e,requests:n,input_tokens:s,output_tokens:r,cost_usd:o,avg_latency_ms:n?Math.round(i/n*100)/100:0,fallback_requests:t.filter(a=>a.fallback).length}}function Ke(t,e){let n=new Map;for(let r of t){let o=e.map(c=>String(r[c]??"unknown")),i=JSON.stringify(o),a=n.get(i)??{names:o,bucket:Ve()};Qe(a.bucket,r),n.set(i,a)}let s=[...n.values()].map(({names:r,bucket:o})=>Xe(e,r,o));return s.sort((r,o)=>H(o.cost_usd)-H(r.cost_usd)||Ye(e,r,o)),s}function Ye(t,e,n){for(let s of t){let r=String(e[s]??"").localeCompare(String(n[s]??""));if(r!==0)return r}return 0}function Ve(){return{requests:0,input_tokens:0,output_tokens:0,cost_usd:0,fallback_requests:0,latency_sum:0}}function Qe(t,e){t.requests++,t.input_tokens+=A(e.in),t.output_tokens+=A(e.out),t.cost_usd=it(t.cost_usd+H(e.cost)),e.fallback&&t.fallback_requests++,t.latency_sum+=A(e.latency_ms)}function Xe(t,e,n){return{...Object.fromEntries(t.map((s,r)=>[s,e[r]])),requests:n.requests,input_tokens:n.input_tokens,output_tokens:n.output_tokens,cost_usd:n.cost_usd,avg_latency_ms:n.requests?Math.round(n.latency_sum/n.requests*100)/100:0,fallback_requests:n.fallback_requests}}function A(t){let e=Number(t);return Number.isFinite(e)?Math.floor(e):0}function H(t){let e=Number(t);return Number.isFinite(e)?e:0}function it(t){return Math.round(t*1e8)/1e8}var Ze="https://aistatus.cc",tn=3600,Rt=class{_baseUrl;_ttlSeconds;_memoryCache=new Map;_cachePath;_pendingRefreshes=new Map;constructor(t=Ze,e=tn){this._baseUrl=t.replace(/\/+$/,""),this._ttlSeconds=e,this._cachePath=W.join(Ct.homedir(),".aistatus","usage","pricing-cache.json")}calculateCost(t,e,n,s){return bt(this.getPricing(t,e),n,s)}async calculateCostAsync(t,e,n,s){return bt(await this._getPricingAfterRefresh(t,e),n,s)}calculateCostWithCache(t,e,n,s,r,o){return St(this.getPricing(t,e),n,s,r,o)}async calculateCostWithCacheAsync(t,e,n,s,r,o){let i=await this._getPricingAfterRefresh(t,e);return St(i,n,s,r,o)}getPricing(t,e){let n=this._normalizeKey(t,e),s=Date.now()/1e3,r=this._memoryCache.get(n);if(r&&this._isFresh(r,s))return r.pricing;let o=this._readFileCache(),i=o[n];return i&&this._isFresh(i,s)?(this._memoryCache.set(n,i),i.pricing):(this._refreshPricing(n,t,e,o),null)}async _getPricingAfterRefresh(t,e){let n=this._normalizeKey(t,e),s=this.getPricing(t,e);if(s)return s;await this._pendingRefreshes.get(n);let r=Date.now()/1e3,o=this._memoryCache.get(n);if(o&&this._isFresh(o,r))return o.pricing;let i=this._readFileCache()[n];return!i||!this._isFresh(i,r)?null:(this._memoryCache.set(n,i),i.pricing)}_refreshPricing(t,e,n,s){let r=this._pendingRefreshes.get(t);if(r)return r;let o=this._fetchAndCachePricing(t,e,n,s).catch(()=>{}).finally(()=>this._pendingRefreshes.delete(t));return this._pendingRefreshes.set(t,o),o}async _fetchAndCachePricing(t,e,n,s){let r=await this._fetchPricing(e,n);if(r==null)return;let o={ts:Date.now()/1e3,pricing:r};this._memoryCache.set(t,o),s[t]=o,this._writeFileCache(s)}async _fetchPricing(t,e){let[n,s]=this._splitModel(t,e),r=this._candidateQueries(s),o=[];for(let h of r)try{let m=`${this._baseUrl}/api/models?q=${encodeURIComponent(h)}`,p=await fetch(m,{signal:AbortSignal.timeout(3e3)});if(!p.ok)continue;if(o=(await p.json()).models??[],o.length>0)break}catch{continue}let i=this._pickModelMatch(n,s,o);if(!i)return null;let a=i.pricing??{},c=j(a.prompt),l=j(a.completion);if(c==null&&l==null)return null;let u=j(a.input_cache_read),f=j(a.input_cache_write);return{input_per_million:c==null?null:c*1e6,output_per_million:l==null?null:l*1e6,input_cache_read_per_million:u==null?null:u*1e6,input_cache_write_per_million:f==null?null:f*1e6}}_pickModelMatch(t,e,n){let s=N(`${t}/${e}`),r=N(e);for(let o of n)if(N(String(o.id??""))===s)return o;for(let o of n)if(N(String(o.id??"")).endsWith(`/${r}`))return o;for(let o of n)if(N(String(o.id??"")).includes(r))return o;return n[0]??null}_readFileCache(){try{if(!E.existsSync(this._cachePath))return{};let t=JSON.parse(E.readFileSync(this._cachePath,"utf-8"));if(typeof t=="object"&&t!==null)return t}catch{}return{}}_writeFileCache(t){let e=W.dirname(this._cachePath);E.mkdirSync(e,{recursive:!0});let n=`${this._cachePath}.tmp.${process.pid}`;E.writeFileSync(n,JSON.stringify(t,null,2),"utf-8"),E.renameSync(n,this._cachePath)}_normalizeKey(t,e){let[n,s]=this._splitModel(t,e);return`${n}/${s}`}_splitModel(t,e){if(e.includes("/")){let n=e.indexOf("/");return[e.slice(0,n),e.slice(n+1)]}return[t,e]}_isFresh(t,e){if(!t)return!1;let n=j(t.ts);return n!=null&&e-n<this._ttlSeconds}_candidateQueries(t){let e=[t],n=N(t);n!==t&&e.push(n);let s=en(t);e.push(...s),e.push(...s.map(i=>i.replace(/\./g,"-"))),e.push(n.replace(/\./g,"-")),e.push(n.replace(/-/g," "));let r=[],o=new Set;for(let i of e){let a=i.trim();!a||o.has(a)||(o.add(a),r.push(a))}return r}};function bt(t,e,n){if(!t)return 0;let{input_per_million:s,output_per_million:r}=t;if(s==null&&r==null)return 0;let o=s==null?0:Math.max(e,0)/1e6*s,i=r==null?0:Math.max(n,0)/1e6*r;return Ft(o+i)}function St(t,e,n,s,r){if(!t)return 0;let{input_per_million:o,output_per_million:i}=t;if(o==null&&i==null)return 0;let a=o==null?0:Math.max(e,0)/1e6*o,c=i==null?0:Math.max(n,0)/1e6*i,l=o==null?0:t.input_cache_write_per_million??o*1.25,u=o==null?0:t.input_cache_read_per_million??o*.1,f=Math.max(s,0)/1e6*l,h=Math.max(r,0)/1e6*u;return Ft(a+c+f+h)}function Ft(t){return Math.round(t*1e8)/1e8}function N(t){return t.toLowerCase().trim().replace(/(?<=\d)-(?=\d)/g,".")}function en(t){let e=t.toLowerCase().trim().match(/^(.+?)-(\d+)-(\d+)-(\d{8})$/);if(!e)return[];let[,n,s,r]=e;return[`${n}-${s}.${r}`]}function j(t){if(t==null)return null;let e=Number(t);return Number.isFinite(e)?e:null}var nn=z.join(Pt.homedir(),".aistatus"),at=z.join(nn,"config.yaml"),sn={name:null,org:null,email:null,uploadEnabled:!1},rn={};function ct(t={}){let e=t.env??process.env,n=t.skipFile?{}:on(t.filePath),s=an(e);return cn(rn,s,n,sn)}function on(t=at){if(!x.existsSync(t))return{};let e=x.readFileSync(t,"utf-8");if(!e.trim())return{};let n=Dt.default.parse(e);return un(n)?jt({name:T(n.name),org:T(n.org),email:T(n.email),uploadEnabled:lt(n.uploadEnabled??n.upload_enabled)}):{}}function an(t){return jt({name:T(t.AISTATUS_NAME),org:T(t.AISTATUS_ORG),email:T(t.AISTATUS_EMAIL),uploadEnabled:lt(t.AISTATUS_UPLOAD_ENABLED)})}function cn(...t){return{name:tt(...t.map(e=>e.name)),org:tt(...t.map(e=>e.org)),email:tt(...t.map(e=>e.email)),uploadEnabled:ln(...t.map(e=>e.uploadEnabled))}}function jt(t){return{name:T(t.name),org:T(t.org),email:T(t.email),uploadEnabled:lt(t.uploadEnabled)}}function T(t){if(t!==void 0){if(t===null)return null;if(typeof t=="string")return t}}function lt(t){if(typeof t=="boolean")return t;if(typeof t!="string")return;let e=t.trim().toLowerCase();if(["1","true","yes","on"].includes(e))return!0;if(["0","false","no","off"].includes(e))return!1}function tt(...t){for(let e of t)if(e!==void 0)return e;return null}function ln(...t){for(let e of t)if(e!==void 0)return e;return!1}function un(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Bt="0.0.11",hn="https://aistatus.cc",vt=100,dn=1e3,pn=6e4,mn=1e4,Lt=5e3,Ht=Symbol.for(`aistatus.usage-upload-queues@${Bt}`);function et(t,e){return t.length>e?t.slice(0,e):t}async function qt(t,e){let n,s=new Promise(r=>{n=setTimeout(r,Math.max(0,e))});try{await Promise.race([t,s])}finally{clearTimeout(n)}}var gn=class{constructor(t){this.url=t,setInterval(()=>{this.flush()},pn).unref?.()}enqueued=0;exitMark=0;records=[];head=null;inflight=null;push(t){this.records.push(t),this.enqueued+=1;let e=(this.head?.records.length??0)+this.records.length-dn;e>0&&this.records.splice(0,e),this.records.length>=vt&&!this.head&&this.flush()}hasWork(){return this.head!==null||this.records.length>0}flush(){return this.inflight??=this.drain().finally(()=>{this.inflight=null}),this.inflight}async flushAll(){this.inflight&&await this.inflight,this.hasWork()&&await this.flush()}async drain(){for(;;){if(!this.head){if(this.records.length===0)return;this.head={id:fn(),records:this.records.splice(0,vt)}}if(!await this.send(this.head))return;this.head=null}}async send(t){let e;try{let o={batch_id:t.id,sdk_version:Bt,records:t.records};e=JSON.stringify(o)}catch{return!0}let n=new AbortController,s,r=new Promise((o,i)=>{s=setTimeout(()=>{n.abort(),i(new Error("usage upload timed out"))},mn),s.unref?.()});try{let o=await Promise.race([fetch(this.url,{method:"POST",headers:{"Content-Type":"application/json"},body:e,signal:n.signal}),r]);return await Promise.race([o.text(),r]).catch(()=>{}),!(o.status===429||o.status>=500)}catch{return!1}finally{clearTimeout(s)}}};function ut(){return globalThis[Ht]}function _n(t){for(let e of t.values())e.enqueued!==e.exitMark&&e.hasWork()&&(e.exitMark=e.enqueued,e.flush())}function yn(t){let e=ut();if(!e){let s=new Map;globalThis[Ht]=s,typeof process<"u"&&typeof process.on=="function"&&process.on("beforeExit",()=>_n(s)),e=s}let n=e.get(t);return n||(n=new gn(t),e.set(t,n)),n}async function Wt(t=Lt){let e=ut();!e||e.size===0||await qt(Promise.all([...e.values()].map(n=>n.flushAll())).then(()=>{}),t)}var zt=class{config;url;constructor(t,e=hn){this.config=t,this.url=pt(e,"/api/usage/upload")}setConfig(t){this.config=t}get enabled(){return!!(this.config.uploadEnabled&&this.config.name&&this.config.email)}upload(t){if(this.enabled)try{yn(this.url).push(this.buildRecord(t))}catch{}}async flush(t=Lt){let e=ut()?.get(this.url);e&&await qt(e.flushAll(),t)}buildRecord(t){return{ts:t.ts,name:et(this.config.name,200),organization:this.config.org?et(this.config.org,200):null,email:et(this.config.email,254),provider:t.provider,model:t.model,input_tokens:t.in??0,output_tokens:t.out??0,cache_creation_input_tokens:t.cache_creation_in??0,cache_read_input_tokens:t.cache_read_in??0,cost_usd:t.cost??0,latency_ms:t.latency_ms??0}}};import*as J from"fs";import*as Zt from"os";import*as te from"path";import*as ee from"http";import*as C from"url";import*as O from"fs";import*as K from"path";import{timingSafeEqual as kn}from"crypto";import*as $ from"fs";import*as ne from"os";import*as Y from"path";import*as ae from"http";import*as V from"net";import*as ce from"stream";import*as le from"tls";function Gt(t,e,n){if(!t||!t.enabled||(t.public_paths??["/health"]).some(c=>e===c||e.startsWith(c+"/")))return!0;let r=(t.header??"authorization").toLowerCase(),o=n[r],i=Array.isArray(o)?o[0]??"":o??"",a;return r==="authorization"?a=i.toLowerCase().startsWith("bearer ")?i.slice(7).trim():i.trim():a=i.trim(),a?t.keys.some(c=>{let l=Buffer.from(c,"utf-8"),u=Buffer.from(a,"utf-8");return l.length!==u.length?!1:kn(l,u)}):!1}function wn(t){let e=JSON.parse(t.toString("utf-8")),n=[],s=e.system;if(s){if(typeof s=="string")n.push({role:"system",content:s});else if(Array.isArray(s)){let o=s.filter(i=>i.type==="text").map(i=>i.text??"").join(`
9
- `);o&&n.push({role:"system",content:o})}}for(let o of e.messages??[]){let i=o.role??"user",a=o.content;if(typeof a=="string")n.push({role:i,content:a});else if(Array.isArray(a)){let c=a.filter(l=>l.type==="text").map(l=>l.text??"");c.length>0?n.push({role:i,content:c.join(`
10
- `)}):n.push({role:i,content:JSON.stringify(a)})}}let r={model:e.model??"",messages:n};for(let o of["max_tokens","temperature","top_p","stream"])o in e&&(r[o]=e[o]);return"stop_sequences"in e&&(r.stop=e.stop_sequences),e.stream&&(r.stream_options={include_usage:!0}),Buffer.from(JSON.stringify(r),"utf-8")}function bn(t,e=""){let n=JSON.parse(t.toString("utf-8")),s="",r="end_turn",o=n.choices??[];if(o.length>0){let c=o[0];s=c.message?.content??"";let l=c.finish_reason??"stop";r={stop:"end_turn",length:"max_tokens"}[l]??"end_turn"}let i=n.usage??{},a={id:`msg_${n.id??"gw"}`,type:"message",role:"assistant",model:e||n.model||"",content:[{type:"text",text:s}],stop_reason:r,stop_sequence:null,usage:{input_tokens:i.prompt_tokens??0,output_tokens:i.completion_tokens??0}};return Buffer.from(JSON.stringify(a),"utf-8")}function M(t,e){return Buffer.from(`event: ${t}
11
- data: ${JSON.stringify(e)}
12
-
13
- `,"utf-8")}async function*Sn(t,e=""){let n=`msg_gw_${Math.floor(Date.now()/1e3)}`;yield M("message_start",{type:"message_start",message:{id:n,type:"message",role:"assistant",model:e,content:[],stop_reason:null,stop_sequence:null,usage:{input_tokens:0,output_tokens:0}}}),yield M("content_block_start",{type:"content_block_start",index:0,content_block:{type:"text",text:""}});let s=0,r="",o=!1;for await(let i of t)for(r+=i.toString("utf-8");r.includes(`
14
-
15
- `);){let a=r.indexOf(`
16
-
17
- `),c=r.slice(0,a).trim();if(r=r.slice(a+2),!!c)for(let l of c.split(`
18
- `)){if(!l.startsWith("data:"))continue;let u=l.slice(5).trim();if(u==="[DONE]"){if(o)return;o=!0,yield M("content_block_stop",{type:"content_block_stop",index:0}),yield M("message_delta",{type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{output_tokens:s}}),yield M("message_stop",{type:"message_stop"});return}let f;try{f=JSON.parse(u)}catch{continue}if(f.usage&&typeof f.usage=="object"){let S=f.usage;S.completion_tokens!=null&&(s=S.completion_tokens)}let h=f.choices??[];if(h.length===0)continue;let p=(h[0].delta??{}).content;if(typeof p=="string"&&p&&(yield M("content_block_delta",{type:"content_block_delta",index:0,delta:{type:"text_delta",text:p}})),h[0].finish_reason){if(o)return;o=!0,yield M("content_block_stop",{type:"content_block_stop",index:0}),yield M("message_delta",{type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{output_tokens:s}}),yield M("message_stop",{type:"message_stop"});return}}}}var vn=Y.join(ne.homedir(),".aistatus","quota.json"),En=[["five_hour","5h"],["seven_day","7d"]];function ht(t,e,n,s=1/0){let r=t.get(e);if(r===null||r.trim()==="")return null;let o=Number(r);return Number.isFinite(o)&&o>=n&&o<=s?o:null}function Tn(t,e,n){let s=`anthropic-ratelimit-unified-${n}`,r=ht(t,`${s}-utilization`,0,1),o=ht(t,`${s}-reset`,0);return r===null||o===null?null:{type:e,utilization:r,resets_at:o}}function Mn(t){return t==="5h"||t==="five_hour"?"five_hour":t==="7d"||t==="seven_day"?"seven_day":null}function Un(t){if(t.get("anthropic-ratelimit-unified-status")!=="rejected")return null;let e=Mn(t.get("anthropic-ratelimit-unified-representative-claim")),n=ht(t,"anthropic-ratelimit-unified-reset",0);return e&&n!==null?{type:e,utilization:1,resets_at:n}:null}function On(t){let e=En.flatMap(([s,r])=>{let o=Tn(t,s,r);return o?[o]:[]});if(e.length>0)return e;let n=Un(t);return n?[n]:[]}function $n(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;return(e.type==="five_hour"||e.type==="seven_day")&&typeof e.utilization=="number"&&Number.isFinite(e.utilization)&&e.utilization>=0&&e.utilization<=1&&typeof e.resets_at=="number"&&Number.isFinite(e.resets_at)&&e.resets_at>=0}function In(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;return typeof e.provider=="string"&&e.provider.length>0&&typeof e.mode=="string"&&e.mode.length>0&&typeof e.observed_at=="number"&&Number.isFinite(e.observed_at)&&Array.isArray(e.windows)&&e.windows.length>0&&e.windows.every($n)}function Nn(t){try{let e=JSON.parse($.readFileSync(t,"utf8"));return e.version===1&&Array.isArray(e.providers)?e.providers.filter(In):[]}catch{return[]}}var An=class{constructor(t=vn){this.filePath=t;for(let e of Nn(t))this.snapshots.set(e.provider,e)}snapshots=new Map;list(t){let e=[...this.snapshots.values()].filter(n=>!t||n.provider===t).sort((n,s)=>n.provider.localeCompare(s.provider));return structuredClone(e)}observe(t,e,n=Date.now()){if(e.status!==429&&(e.status<200||e.status>=300))return!1;let s=On(t);return s.length===0?!1:(this.snapshots.set(e.provider,{provider:e.provider,mode:e.mode,windows:s,observed_at:Math.floor(n/1e3)}),this.persistBestEffort(),!0)}persistBestEffort(){try{$.mkdirSync(Y.dirname(this.filePath),{recursive:!0});let t=`${this.filePath}.${process.pid}.tmp`,e={version:1,providers:this.list()};$.writeFileSync(t,`${JSON.stringify(e)}
19
- `,{encoding:"utf8",mode:384}),$.renameSync(t,this.filePath)}catch(t){console.warn(`[gateway] Failed to persist quota snapshot: ${t.message}`)}}},xn=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","content-length","content-encoding","content-type"]),Cn=1024*1024;function se(t,e){t.headers.forEach((n,s)=>{let r=s.toLowerCase();xn.has(r)||r.startsWith("x-gateway-")||(e[s]=n)})}function Rn(t){let e={};for(let n of t.split(",")){let s=n.indexOf("=");s<=0||(e[decodeURIComponent(n.slice(0,s))]=decodeURIComponent(n.slice(s+1)))}return e}function Jt(t,e){let n=t.match(/^\/m\/([^/]+)\/([^/]+)\/([^/]+)\/(.*)$/);if(n){let[,a,c,l,u]=n;if(!e[a])return{kind:"unknown-mode",mode:a};if(e[a][l])return{kind:"route",epName:l,pathStr:u,mode:a,metadata:Rn(c)}}let s=t.match(/^\/m\/([^/]+)\/([^/]+)\/(.*)$/);if(s){let[,a,c,l]=s;return e[a]?{kind:"route",epName:c,pathStr:l,mode:a}:{kind:"unknown-mode",mode:a}}let r=t.match(/^\/([^/]+)\/(.*)$/);if(!r)return{kind:"not-found"};let[,o,i]=r;return{kind:"route",epName:o,pathStr:i}}function y(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function Kt(t,e=mt){let n=e*Cn;return new Promise((s,r)=>{let o=[],i=0;t.on("data",a=>{if(i+=a.length,i>n){t.destroy(),r(new Error("Request body too large"));return}o.push(a)}),t.on("end",()=>s(Buffer.concat(o))),t.on("error",r)})}function Fn(t){if(t.length===0)return"";try{return JSON.parse(t.toString("utf-8")).model??""}catch{return""}}function G(t,e,n){return{id:t,base_url:e.base_url,api_key:n,auth_style:e.auth_style,model_prefix:"",model_map:{},translate:null}}function Yt(t,e){if(e==="anthropic")return t.headers["x-api-key"]??"";if(e==="google")return t.headers["x-goog-api-key"]??"";let n=t.headers.authorization??"";return n.toLowerCase().startsWith("bearer ")?n.slice(7):n}function Pn(t,e){let n={},s=new Set(["host","authorization","x-api-key","x-goog-api-key","content-length","transfer-encoding","connection"]);for(let[i,a]of Object.entries(t.headers))!s.has(i.toLowerCase())&&typeof a=="string"&&(n[i]=a);let[r,o]=D[e.auth_style]??D.bearer;return n[r]=o+e.api_key,n}function Dn(t,e){try{let n=JSON.parse(t.toString("utf-8"));return n.model?(n.model=e,Buffer.from(JSON.stringify(n),"utf-8")):t}catch{return t}}function jn(t,e){try{let n=JSON.parse(t.toString("utf-8")),s=n.model;return s?(s in e.model_map?n.model=e.model_map[s]:e.model_prefix&&(n.model=e.model_prefix+s),Buffer.from(JSON.stringify(n),"utf-8")):t}catch{return t}}function Bn(t,e){let n;try{n=JSON.parse(t.toString("utf-8"))}catch{return null}let s=e||n.model||"",r=n.usage??{},o=Ln(s,r);return s||o.inputTokens||o.outputTokens?o:null}function Ln(t,e){let n=re(t,e);return n||{model:t,inputTokens:_(e.input_tokens??e.prompt_tokens??0),outputTokens:_(e.output_tokens??e.completion_tokens??0),cacheCreationInputTokens:_(e.cache_creation_input_tokens??0),cacheReadInputTokens:_(e.cache_read_input_tokens??0)}}function re(t,e){let n=e.input_tokens_details;if(!n||typeof n!="object"||Array.isArray(n))return null;let s=n,r=_(s.cached_tokens??0),o=_(s.cache_write_tokens??0),i=_(e.input_tokens??0);return{model:t,inputTokens:Math.max(0,i-r-o),outputTokens:_(e.output_tokens??0),cacheCreationInputTokens:o,cacheReadInputTokens:r}}function Hn(t,e){return e.includes("/")?e.split("/",1)[0]:t.id.startsWith("anthropic")?"anthropic":t.id.startsWith("openai")?"openai":t.id.startsWith("google")?"google":t.id.startsWith("openrouter")?"openrouter":t.id.split(":",1)[0]||"unknown"}function qn(t){try{let e=JSON.parse(t.toString("utf-8")).thinking;return!e||typeof e!="object"?!1:e.type==="enabled"||e.type==="auto"}catch{return!1}}function Wn(t){try{let e=JSON.parse(t.toString("utf-8"));if(!Array.isArray(e.messages))return t;let n=!1;for(let s of e.messages)zn(s)&&(n=!0);return n?Buffer.from(JSON.stringify(e),"utf-8"):t}catch{return t}}function zn(t){if(t.role!=="assistant"||!Array.isArray(t.content))return!1;let e=t.content;if(e.some(s=>s.type==="thinking"))return!1;let n=e.findIndex(s=>s.type==="text");return n<0?!1:(e.splice(n,0,{type:"thinking",thinking:""}),!0)}function _(t){try{let e=Number(t??0);return Number.isFinite(e)?Math.floor(e):0}catch{return 0}}function Gn(t,e){y(e,200,{status:"ok",mode:t.mode,endpoints:Object.keys(t.endpoints)})}function Jn(t,e,n){let s=Object.fromEntries(Object.entries(t.endpoints).map(([i,a])=>[i,Kn(i,a,e)])),r=e.summary(),o=r.model_health;delete r.model_health,y(n,200,{mode:t.mode,available_modes:Object.keys(t.endpoint_modes),endpoints:s,health_detail:r,model_health:o??{}})}function Kn(t,e,n){let s=[];for(let o=0;o<e.keys.length;o++){let i=`${t}:key:${o}`;s.push({id:i,type:"primary",healthy:n.isHealthy(i)})}if(e.keys.length===0||e.passthrough){let o=`${t}:passthrough`;s.push({id:o,type:"passthrough",healthy:n.isHealthy(o)})}for(let o of e.fallbacks){let i=`${t}:fb:${o.name}`;s.push({id:i,type:"fallback",name:o.name,healthy:n.isHealthy(i)})}let r=e.keys.length===0?"passthrough":e.passthrough?"hybrid":"managed";return{backends:s,mode:r}}function Yn(t,e,n){if(e.format==="records"){Qn(t,e,n);return}Zn(t,e,n)}function Vn(t,e,n){let s=typeof e.provider=="string"?e.provider:void 0;y(n,200,{providers:t.list(s)})}function Qn(t,e,n){let s=Xn(t.storage.read("all"),e.since),r=Math.max(0,_(e.limit??1e3)),o=Math.max(0,_(e.offset??0)),i=r>0?s.slice(o,o+r):s.slice(o);y(n,200,{records:i})}function Xn(t,e){if(!e)return t;let n=new Date(e);return isNaN(n.getTime())?t:t.filter(s=>{let r=new Date(s.ts);return!isNaN(r.getTime())&&r>n})}function Zn(t,e,n){let s=e.period??"today",r=e.group_by??"",o=ts(r);es(s,o,r,n)&&y(n,200,t.report(s,o??[]))}function ts(t){if(t.trim()==="")return[];let e=t.split(",").map(r=>r.trim()),n=e.every(r=>ot.includes(r)),s=new Set(e).size===e.length;return n&&s?e:null}function es(t,e,n,s){let r=["today","week","month","all"];return r.includes(t)?e!==null?!0:(y(s,400,{error:{message:`Invalid group_by: ${n}. Must be distinct keys from ${ot.join(",")}`,type:"gateway_error"}}),!1):(y(s,400,{error:{message:`Invalid period: ${t}. Must be one of ${r.join(",")}`,type:"gateway_error"}}),!1)}async function Vt(t,e){if(!t.status_check)return;let n=ns(t);if(n.size===0)return;let s=await ss([...n].sort());if(s.size!==0)for(let r of Object.values(t.endpoints))rs(r,s,e)}function ns(t){let e=new Set;for(let n of Object.values(t.endpoints))for(let[s,r]of Object.entries(n.model_fallbacks)){e.add(s);for(let o of r)e.add(o)}return e}async function ss(t){let{StatusAPI:e}=await import("./api-GM53PHIL-GFHEXXE6.js"),{Status:n}=await import("./models-L5VF4I5O-XXNJYQMQ.js"),s=new e,r=await Promise.allSettled(t.map(i=>s.checkModel(i))),o=new Set;for(let i=0;i<t.length;i++){let a=r[i];a.status==="fulfilled"&&(a.value.status===n.DEGRADED||a.value.status===n.DOWN)&&o.add(t[i])}return o}function rs(t,e,n){let s=new Set(Object.keys(t.model_fallbacks));for(let o of Object.values(t.model_fallbacks))for(let i of o)s.add(i);let r=[...s].filter(o=>e.has(o));if(r.length!==0)for(let o of os(t))for(let i of r)n.recordError(o,529,i),console.log(`[gateway] Pre-marked ${o} model unhealthy from global status: ${i}`)}function os(t){let e=t.keys.map((n,s)=>`${t.name}:key:${s}`);(t.keys.length===0||t.passthrough)&&e.push(`${t.name}:passthrough`);for(let n of t.fallbacks)e.push(`${t.name}:fb:${n.name}`);return e}async function dt(t){let{backend:e,usage:n,elapsedMs:s,metadata:r,pricing:o,tracker:i}=t,a=Hn(e,n.model),c=n.model||`${a}/unknown`,l=await is(o,a,c,n);i.recordUsage({provider:a,model:c,cost:l,metadata:r,input_tokens:n.inputTokens,output_tokens:n.outputTokens,cache_creation_input_tokens:n.cacheCreationInputTokens,cache_read_input_tokens:n.cacheReadInputTokens,latency_ms:s,fallback:e.id.includes(":fb:"),billing_mode:t.billingMode||t.defaultBillingMode})}async function is(t,e,n,s){return s.cacheCreationInputTokens>0||s.cacheReadInputTokens>0?t.calculateCostWithCacheAsync(e,n,s.inputTokens,s.outputTokens,s.cacheCreationInputTokens,s.cacheReadInputTokens):t.calculateCostAsync(e,n,s.inputTokens,s.outputTokens)}var as=new Set(["response.completed","response.incomplete","response.done"]);function Qt(t){return{model:t,inputTokens:0,outputTokens:0,cacheCreationInputTokens:0,cacheReadInputTokens:0}}async function cs(t){if(!t.body)return{kind:"buffer",body:Buffer.alloc(0)};let e=t.body.getReader(),n=await e.read();if(n.done||!n.value)return{kind:"buffer",body:Buffer.alloc(0)};let s=Buffer.from(n.value);if(ls(s))return{kind:"event-stream",reader:us(s,e)};let r=[s];for(;;){let o=await e.read();if(o.done)break;o.value&&r.push(Buffer.from(o.value))}return{kind:"buffer",body:Buffer.concat(r)}}function ls(t){let e=t.subarray(0,64).toString("utf-8").replace(/^[\s]+/,"");return/^(event|data|id|retry):/.test(e)||e.startsWith(":")}function us(t,e){let n=t;return{async read(){if(n){let s=n;return n=null,{done:!1,value:s}}return e.read()}}}async function fs(t){let e=t.bodyReader??t.upstream.body?.getReader();if(hs(t),!e){t.res.end();return}let n=new ie(t.originalModel),s=[],r;try{r=await ds(t,e,n,s)}catch(i){throw Xt(t.res),i}if(!r){Xt(t.res);return}t.res.end();let o=s.length>0?Buffer.concat(s):void 0;t.dumpApiCall(t.requestBody,o,t.originalModel,t.backend.id,t.elapsedMs),n.hasUsage()&&await _s(t,n.usage)}function Xt(t){t.once("error",()=>{}),t.destroy(new Error("upstream stream interrupted"))}function hs(t){let e={};se(t.upstream,e),e["content-type"]="text/event-stream",e["cache-control"]="no-cache",e.connection="keep-alive",e["x-gateway-backend"]=t.backend.id,t.fallbackHeader&&(e["x-gateway-model-fallback"]=t.fallbackHeader),t.res.writeHead(200,e)}async function ds(t,e,n,s){try{return await ps(t,e,n,s),!0}catch(r){if(r instanceof oe)return n.hasTerminalEvent();throw r}}async function ps(t,e,n,s){let r=gs(e,n,s);if(t.backend.translate==="anthropic-to-openai"){for await(let o of Sn(r,t.originalModel))t.res.write(o);return}for await(let o of r)t.res.write(o)}var oe=class extends Error{};async function ms(t){try{return await t.read()}catch{throw new oe("upstream stream read failed")}}async function*gs(t,e,n){for(;;){let{done:s,value:r}=await ms(t);if(s||!r)return;let o=Buffer.from(r);e.push(o.toString("utf-8")),n.push(o),yield o}}async function _s(t,e){await dt({backend:t.backend,usage:e,elapsedMs:t.elapsedMs,billingMode:t.billingMode,defaultBillingMode:t.defaultBillingMode,metadata:t.metadata,pricing:t.pricing,tracker:t.tracker})}var ie=class{usage;initialModel;buffer="";terminalEvent=!1;constructor(t){this.initialModel=t,this.usage=Qt(t)}applyMessage(t){try{this.applyPayload(JSON.parse(t))}catch{}}reset(){this.usage=Qt(this.initialModel),this.terminalEvent=!1}push(t){for(this.buffer+=t;this.buffer.includes(`
20
-
21
- `);){let e=this.buffer.indexOf(`
22
-
23
- `),n=this.buffer.slice(0,e).trim();this.buffer=this.buffer.slice(e+2);for(let s of n.split(`
24
- `))this.parseLine(s)}}hasUsage(){return this.usage.inputTokens>0||this.usage.outputTokens>0}hasTerminalEvent(){return this.terminalEvent}parseLine(t){if(!t.startsWith("data:"))return;let e=t.slice(5).trim();if(e==="[DONE]"){this.terminalEvent=!0;return}try{this.applyPayload(JSON.parse(e))}catch{}}applyPayload(t){if(!this.applyResponsesPayload(t)){if(t.type==="message_stop"&&(this.terminalEvent=!0),t.type==="message_start"&&t.message?.usage){let e=t.message.usage;this.usage.inputTokens=_(e.input_tokens??0),this.usage.cacheCreationInputTokens=_(e.cache_creation_input_tokens??0),this.usage.cacheReadInputTokens=_(e.cache_read_input_tokens??0)}t.type==="message_delta"&&t.usage&&(this.usage.outputTokens=_(t.usage.output_tokens??0)),t.usage&&this.applyGenericUsage(t.usage)}}applyResponsesPayload(t){let e=typeof t?.type=="string"?t.type:"";if(!e.startsWith("response."))return!1;let n=t.response;if(!n||typeof n!="object"||(!this.usage.model&&typeof n.model=="string"&&(this.usage.model=n.model),!as.has(e)))return!0;this.terminalEvent=!0;let s=n.usage;if(!s||typeof s!="object")return!0;let r=re(this.usage.model,s);return r&&(this.usage.inputTokens=r.inputTokens,this.usage.outputTokens=r.outputTokens,this.usage.cacheCreationInputTokens=r.cacheCreationInputTokens,this.usage.cacheReadInputTokens=r.cacheReadInputTokens),!0}applyGenericUsage(t){this.usage.inputTokens=_(t.input_tokens??t.prompt_tokens??this.usage.inputTokens),this.usage.outputTokens=_(t.output_tokens??t.completion_tokens??this.usage.outputTokens),this.usage.cacheCreationInputTokens=_(t.cache_creation_input_tokens??this.usage.cacheCreationInputTokens),this.usage.cacheReadInputTokens=_(t.cache_read_input_tokens??this.usage.cacheReadInputTokens)}},ys=32*1024*1024,ks=0,ws=1,bs=2,Ss=8,vs=class{constructor(t,e=ys){this.onMessage=t,this.maxMessageBytes=e}buffer=Buffer.alloc(0);fragments=[];fragmentBytes=0;skippingMessage=!1;disabled=!1;get isDisabled(){return this.disabled}push(t){if(!this.disabled)try{for(this.buffer=this.buffer.length===0?t:Buffer.concat([this.buffer,t]);this.readFrame(););}catch{this.disable()}}disable(){this.disabled=!0,this.buffer=Buffer.alloc(0),this.fragments=[],this.fragmentBytes=0}readFrame(){if(this.buffer.length<2)return!1;let t=this.buffer[0],e=this.buffer[1],n=(t&128)!==0,s=t&15,r=(e&128)!==0,o=2,i=e&127;if(i===126){if(this.buffer.length<o+2)return!1;i=this.buffer.readUInt16BE(o),o+=2}else if(i===127){if(this.buffer.length<o+8)return!1;let l=this.buffer.readBigUInt64BE(o);if(l>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("frame length out of range");i=Number(l),o+=8}let a=null;if(r){if(this.buffer.length<o+4)return!1;a=this.buffer.subarray(o,o+4),o+=4}if(this.buffer.length<o+i)return!1;let c=this.buffer.subarray(o,o+i);return this.buffer=this.buffer.subarray(o+i),s>=Ss||this.collect(s,n,a?Es(c,a):c),!0}collect(t,e,n){if(t===ws||t===bs)this.fragments=[],this.fragmentBytes=0,this.skippingMessage=!1;else if(t!==ks)return;if(this.fragmentBytes+=n.length,this.fragmentBytes>this.maxMessageBytes&&(this.skippingMessage=!0,this.fragments=[]),this.skippingMessage||this.fragments.push(n),!e)return;let s=this.skippingMessage?null:Buffer.concat(this.fragments);this.fragments=[],this.fragmentBytes=0,this.skippingMessage=!1,s&&this.onMessage(s.toString("utf-8"))}};function Es(t,e){let n=Buffer.allocUnsafe(t.length);for(let s=0;s<t.length;s++)n[s]=t[s]^e[s&3];return n}var Ts=new Set(["host","authorization","x-api-key","x-goog-api-key","content-length","transfer-encoding","sec-websocket-extensions"]),Ms=64*1024,Us=3e4;async function Os(t){let{socket:e,backend:n}=t;e.on("error",()=>{});let s=new URL(n.base_url),o=`${s.pathname.replace(/\/+$/,"")}/${t.pathStr}${t.search}`,i;try{i=await $s(s)}catch(a){return t.health.recordError(n.id,502),U(e,502,`Upstream connection error: ${a}`)}i.on("error",()=>{});try{i.write(Is(t.req,n,s,o));let a=await Ns(i);if(a.status!==101){t.health.recordError(n.id,a.status),e.write(a.raw),i.pipe(e).on("end",()=>e.end());return}t.health.recordSuccess(n.id),e.write(a.raw),t.head.length>0&&i.write(t.head),As(t,i,a.rest)}catch(a){i.destroy(),t.health.recordError(n.id,502),U(e,502,`Upstream handshake failed: ${a}`)}}function $s(t){let e=t.protocol==="https:"||t.protocol==="wss:",n=t.port?Number(t.port):e?443:80;return new Promise((s,r)=>{let o=e?le.connect({host:t.hostname,port:n,servername:t.hostname,ALPNProtocols:["http/1.1"]}):V.connect({host:t.hostname,port:n}),i=()=>{o.setNoDelay(!0),o.removeListener("error",a),s(o)},a=c=>{o.destroy(),r(c)};o.once(e?"secureConnect":"connect",i),o.once("error",a)})}function Is(t,e,n,s){let r=[`GET ${s} HTTP/1.1`,`host: ${n.host}`];for(let[a,c]of Object.entries(t.headers))if(!Ts.has(a.toLowerCase())){if(typeof c=="string")r.push(`${a}: ${c}`);else if(Array.isArray(c))for(let l of c)r.push(`${a}: ${l}`)}let[o,i]=D[e.auth_style]??D.bearer;return r.push(`${o}: ${i}${e.api_key}`),`${r.join(`\r
25
- `)}\r
26
- \r
27
- `}function Ns(t){return new Promise((e,n)=>{let s=Buffer.alloc(0),r=setTimeout(()=>i(new Error("upstream handshake timed out")),Us),o=l=>{s=Buffer.concat([s,l]);let u=s.indexOf(`\r
28
- \r
29
- `);if(u<0){s.length>Ms&&i(new Error("upstream handshake head too large"));return}let f=u+4,h=s.subarray(0,s.indexOf(`\r
30
- `)).toString("latin1"),m=Number.parseInt(h.split(" ")[1]??"",10);if(!Number.isFinite(m))return i(new Error(`malformed upstream status line: ${h}`));i(null,{status:m,raw:s.subarray(0,f),rest:s.subarray(f)})},i=(l,u)=>{clearTimeout(r),t.removeListener("data",o),t.removeListener("error",a),t.removeListener("close",c),l?n(l):e(u)},a=l=>i(l),c=()=>i(new Error("upstream closed before completing the handshake"));t.on("data",o),t.once("error",a),t.once("close",c)})}function As(t,e,n){let{socket:s}=t;s instanceof V.Socket&&s.setNoDelay(!0);let r=new vs(xs(t)),o=new ce.Transform({transform(a,c,l){r.push(a),l(null,a)}}),i=()=>{s.destroy(),e.destroy()};s.on("error",i),s.on("close",i),e.on("error",i),e.on("close",i),n.length>0&&(r.push(n),s.write(n)),e.pipe(o).pipe(s),s.pipe(e)}function xs(t){let e=new ie(""),n=null;return s=>{if(n===null&&(n=Date.now()),e.applyMessage(s),!e.hasTerminalEvent())return;let r=Date.now()-n,o=e.usage,i=e.hasUsage();n=null,e.reset(),i&&(t.health.recordSuccess(t.backend.id),o.model&&t.health.recordSuccess(t.backend.id,o.model),dt({backend:t.backend,usage:o,elapsedMs:r,billingMode:t.billingMode,defaultBillingMode:t.defaultBillingMode,metadata:t.metadata,pricing:t.pricing,tracker:t.tracker}).catch(a=>console.warn("[gateway] websocket usage accounting failed:",a)))}}function U(t,e,n){let s=JSON.stringify({error:{message:n,type:"gateway_error"}});t.end(`HTTP/1.1 ${e} ${ae.STATUS_CODES[e]??"Error"}\r
31
- content-type: application/json\r
32
- content-length: ${Buffer.byteLength(s)}\r
33
- connection: close\r
34
- \r
35
- ${s}`)}var ft=class extends Error{status;body;constructor(t,e){super(`Upstream error: ${t}`),this.status=t,this.body=e}},Cs=class{config;health;usage;uploader;quota;pricing;_keyIdx={};_pidFile;_server=null;_dumpDir;constructor(t,e){t.endpoint_modes||(t.endpoint_modes={[t.mode??"default"]:t.endpoints}),t.mode||(t.mode=Object.keys(t.endpoint_modes)[0]??"default"),t.endpoints||(t.endpoints=t.endpoint_modes[t.mode]??{}),this.config=t,this.health=new Tt,this.uploader=new zt(ct()),this.usage=new xt(void 0,this.uploader),this.quota=new An,this.pricing=new Rt,this._pidFile=e??null,this._dumpDir=process.env.GATEWAY_DUMP_DIR||null,this._dumpDir&&O.mkdirSync(this._dumpDir,{recursive:!0})}reloadConfig(t){(t.host!==this.config.host||t.port!==this.config.port)&&console.warn(`[gateway] host/port change ignored on reload (already bound to ${this.config.host}:${this.config.port})`),t.host=this.config.host,t.port=this.config.port,(!t.endpoint_modes||Object.keys(t.endpoint_modes).length===0)&&(t.endpoint_modes={[t.mode??"default"]:t.endpoints??{}});let e=Object.keys(t.endpoint_modes),n=this.config.mode,s=t.endpoint_modes[n]?n:e[0]??"default";t.mode=s,t.endpoints=t.endpoint_modes[s]??{},this.config=t,this._keyIdx={},console.log("[gateway] Config reloaded"),Vt(this.config,this.health).catch(r=>{console.warn("[gateway] post-reload health precheck failed:",r)})}reloadUploadConfig(t){this.uploader.setConfig(t),console.log(`[gateway] Upload config reloaded (usage upload ${this.uploader.enabled?"enabled":"disabled"})`)}async run(){await Vt(this.config,this.health);let t=ee.createServer((s,r)=>{this._handleRequest(s,r).catch(o=>{console.error("[gateway] Unhandled error:",o),r.headersSent||(r.writeHead(500,{"content-type":"application/json"}),r.end(JSON.stringify({error:{message:"Internal server error",type:"gateway_error"}})))})});t.on("upgrade",(s,r,o)=>{this._handleUpgrade(s,r,o).catch(i=>{console.error("[gateway] Unhandled upgrade error:",i),r.destroy()})}),this._server=t,await new Promise((s,r)=>{t.listen(this.config.port,this.config.host,()=>s()),t.on("error",r)}),this._prewarmUsage(),this._writePidFile(),this._printBanner();let e=!1,n=()=>{if(e)return;e=!0,console.log("[gateway] Shutdown signal received, stopping gracefully..."),this._removePidFile(),setTimeout(()=>process.exit(0),5e3).unref();let s=new Promise(o=>t.close(()=>o())),r=new Promise(o=>setTimeout(o,1e3).unref());Promise.race([s,r]).then(()=>Wt(3e3)).finally(()=>{console.log("[gateway] Gateway stopped"),process.exit(0)})};process.on("SIGTERM",n),process.on("SIGINT",n)}_prewarmUsage(){try{this.usage.prewarm("month")}catch(t){console.warn("[gateway] Usage index prewarm failed:",t)}}async _handleRequest(t,e){let n=C.parse(t.url??"/",!0),s=n.pathname??"/";if(!Gt(this.config.auth,s,t.headers))return y(e,401,{error:{message:"Unauthorized: invalid or missing API key",type:"auth_error"}});if(s==="/health"&&t.method==="GET")return Gn(this.config,e);if(s==="/status"&&t.method==="GET")return Jn(this.config,this.health,e);if(s==="/usage"&&t.method==="GET")return Yn(this.usage,n.query,e);if(s==="/quota"&&t.method==="GET")return Vn(this.quota,n.query,e);if(s==="/mode"&&t.method==="POST")return this._handleModeSwitch(t,e);let r=Jt(s,this.config.endpoint_modes);if(r.kind==="unknown-mode")return y(e,400,{error:{message:`Unknown mode: ${r.mode}`,type:"gateway_error"}});if(r.kind==="not-found")return y(e,404,{error:{message:`Not found: ${s}`,type:"gateway_error"}});await this._handleProxy(t,e,r.epName,r.pathStr,n.query,r.mode,r.metadata)}async _handleUpgrade(t,e,n){let s=C.parse(t.url??"/",!0),r=s.pathname??"/";if(!this.config.websocket)return U(e,501,"WebSocket proxying is disabled");if(!Gt(this.config.auth,r,t.headers))return U(e,401,"Unauthorized: invalid or missing API key");let o=Jt(r,this.config.endpoint_modes);if(o.kind==="unknown-mode")return U(e,400,`Unknown mode: ${o.mode}`);if(o.kind==="not-found")return U(e,404,`Not found: ${r}`);let i=this._resolveEndpoint(o.epName,o.mode);if(!i)return U(e,404,`Unknown endpoint: ${o.epName}`);let c=this._buildBackendList(i.endpoint,t)[0]??this._pickSoonestCooldownBackend(i.endpoint,t);if(!c)return U(e,503,"All backends unavailable");let l=new C.URLSearchParams(s.query).toString();await Os({req:t,socket:e,head:n,backend:c,pathStr:o.pathStr,search:l?`?${l}`:"",billingMode:i.billingMode,defaultBillingMode:this.config.mode,metadata:o.metadata,health:this.health,pricing:this.pricing,tracker:this.usage})}_resolveEndpoint(t,e){let s=(e?this.config.endpoint_modes[e]??this.config.endpoints:this.config.endpoints)[t];if(s)return{endpoint:s,billingMode:e||this.config.mode};if(e)return null;for(let[r,o]of Object.entries(this.config.endpoint_modes)){if(r===this.config.mode)continue;let i=o[t];if(i)return{endpoint:i,billingMode:r}}return null}async _handleProxy(t,e,n,s,r,o,i){let a=this._resolveEndpoint(n,o);if(!a)return y(e,404,{error:{message:`Unknown endpoint: ${n}`,type:"gateway_error"}});let{endpoint:c,billingMode:l}=a,u=await Kt(t,this.config.max_body_size_mb),f=Fn(u),h=this._buildBackendList(c,t);if(h.length===0){let p=this._pickSoonestCooldownBackend(c,t);if(p)h=[p];else return y(e,503,{error:{message:"All backends unavailable",type:"gateway_error"}})}let m=null;for(let p of h){let[S,R,k]=this._applyModelFallback(c,p.id,u,f);try{return await this._forward(t,e,p,s,R,r,S,k,l,i)}catch(v){if(v instanceof ft)m=v,this.health.recordError(p.id,v.status),S&&this.health.recordError(p.id,v.status,S),console.warn(`[gateway] ${p.id} \u2192 ${v.status}, trying next backend`);else throw v}}m?(e.writeHead(m.status,{"content-type":"application/json"}),e.end(m.body)):y(e,503,{error:{message:"All backends failed",type:"gateway_error"}})}_buildBackendList(t,e){let n=[],s=t.name;if(t.keys.length>0){let r=this._keyIdx[s]??0,o=t.keys.length;for(let i=0;i<o;i++){let a=(r+i)%o,c=`${s}:key:${a}`;this.health.isHealthy(c)&&n.push(G(c,t,t.keys[a]))}this._keyIdx[s]=(r+1)%o}if(t.keys.length===0||t.passthrough){let r=`${s}:passthrough`;if(this.health.isHealthy(r)){let o=Yt(e,t.auth_style);o&&n.push(G(r,t,o))}}for(let r of t.fallbacks){let o=`${s}:fb:${r.name}`;!this.health.isHealthy(o)||!r.api_key||n.push({id:o,base_url:r.base_url,api_key:r.api_key,auth_style:r.auth_style,model_prefix:r.model_prefix,model_map:r.model_map,translate:r.translate})}return n}_pickSoonestCooldownBackend(t,e){let n=t.name,s=[];for(let o=0;o<t.keys.length;o++){let i=`${n}:key:${o}`;s.push({id:i,backend:G(i,t,t.keys[o])})}if(t.keys.length===0||t.passthrough){let o=`${n}:passthrough`,i=Yt(e,t.auth_style);i&&s.push({id:o,backend:G(o,t,i)})}for(let o of t.fallbacks){if(!o.api_key)continue;let i=`${n}:fb:${o.name}`;s.push({id:i,backend:{id:i,base_url:o.base_url,api_key:o.api_key,auth_style:o.auth_style,model_prefix:o.model_prefix,model_map:o.model_map,translate:o.translate}})}if(s.length===0)return null;let r=this.health.soonestCooldown(s.map(o=>o.id));return r?s.find(o=>o.id===r.id)?.backend??null:s[0].backend}async _forward(t,e,n,s,r,o,i,a,c,l){let u=n.translate==="anthropic-to-openai",f=i;if(!f&&u&&r.length>0)try{f=JSON.parse(r.toString("utf-8")).model??""}catch{}let h=s;u&&s.includes("v1/messages")&&(h="v1/chat/completions");let p=`${n.base_url.replace(/\/+$/,"")}/${h}`,S=new C.URLSearchParams(o).toString();S&&(p+=`?${S}`);let R=Pn(t,n),k=r;u&&r.length>0&&(k=wn(r)),r.length>0&&(Object.keys(n.model_map).length>0||n.model_prefix)&&(k=jn(k,n)),c?.includes("deepseek")&&k.length>0&&qn(k)&&(k=Wn(k));let v=Date.now(),w;try{let P=k.length>0?new Uint8Array(k.buffer,k.byteOffset,k.byteLength):void 0;w=await fetch(p,{method:t.method??"POST",headers:R,body:P})}catch(P){throw new ft(502,Buffer.from(JSON.stringify({error:{message:`Upstream connection error: ${P}`,type:"gateway_error"}})))}let F=Date.now()-v;if(this._observeQuota(w,n,c),[429,500,502,503,529].includes(w.status)){let P=await w.arrayBuffer();throw new ft(w.status,Buffer.from(P))}if(this.health.recordSuccess(n.id),i&&this.health.recordSuccess(n.id,i),(w.headers.get("content-type")??"").includes("text/event-stream")){await this._stream(e,w,n,f,a,F,c,r,l);return}let Q=await cs(w);if(Q.kind==="event-stream"){await this._stream(e,w,n,f,a,F,c,r,l,Q.reader);return}await this._respond(e,w,Q.body,n,f,F,a,c,r,l)}_observeQuota(t,e,n){!e.id.startsWith("anthropic:")||!e.id.endsWith(":passthrough")||e.auth_style==="bearer"&&this.quota.observe(t.headers,{provider:"anthropic",mode:n??this.config.mode,status:t.status})}async _respond(t,e,n,s,r,o,i,a,c,l){let u=n,f,h;if(s.translate==="anthropic-to-openai")u=bn(u,r),f="application/json";else{let p=e.headers.get("content-type")??"application/json",[S,...R]=p.split(";");f=S.trim()||"application/json";for(let k of R){let[v,w]=k.split("=").map(F=>F.trim());v?.toLowerCase()==="charset"&&w&&(h=w.replace(/"/g,""))}}await this._recordUsageIfPossible(s,u,r,o,a,l),this._dumpApiCall(c,u,r,s.id,o);let m={};se(e,m),m["content-type"]=h?`${f}; charset=${h}`:f,m["x-gateway-backend"]=s.id,m["x-gateway-ms"]=String(o),i&&(m["x-gateway-model-fallback"]=i),t.writeHead(e.status,m),t.end(u)}async _stream(t,e,n,s,r,o=0,i,a,c,l){await fs({res:t,upstream:e,backend:n,originalModel:s,fallbackHeader:r,elapsedMs:o,billingMode:i,defaultBillingMode:this.config.mode,requestBody:a,metadata:c,bodyReader:l,pricing:this.pricing,tracker:this.usage,dumpApiCall:this._dumpApiCall.bind(this)})}_applyModelFallback(t,e,n,s){if(n.length===0||!s)return[s,n,""];if(this.health.isHealthy(e,s))return[s,n,""];let r=t.model_fallbacks[s]??[];for(let o of r){if(!this.health.isHealthy(e,o))continue;let i=Dn(n,o);if(!i.equals(n))return[o,i,`${s}->${o}`]}return[s,n,""]}_dumpApiCall(t,e,n,s,r){if(!(!this._dumpDir||!t||t.length===0))try{let o=new Date().toISOString().replace(/[:.]/g,"-"),i=K.join(this._dumpDir,`${o}.json`),a;try{a=JSON.parse(t.toString("utf-8"))}catch{a=t.toString("utf-8")}let c;if(e&&e.length>0){let u=e.toString("utf-8");try{c=JSON.parse(u)}catch{c=u}}let l={ts:new Date().toISOString(),model:n||void 0,backend:s,latency_ms:r,request:a};c!==void 0&&(l.response=c),O.writeFileSync(i,JSON.stringify(l)+`
36
- `,"utf-8")}catch{}}async _recordUsageIfPossible(t,e,n,s,r,o){let i=Bn(e,n);i&&await dt({backend:t,usage:i,elapsedMs:s,billingMode:r,metadata:o,defaultBillingMode:this.config.mode,pricing:this.pricing,tracker:this.usage})}async _handleModeSwitch(t,e){let n=await Kt(t,this.config.max_body_size_mb),s;try{s=n.length>0?JSON.parse(n.toString("utf-8")):{}}catch{return y(e,400,{error:{message:"Invalid JSON body",type:"gateway_error"}})}let r=typeof s.mode=="string"?s.mode:"";if(!r||!this.config.endpoint_modes[r])return y(e,400,{error:{message:`Unknown mode: ${r}`,type:"gateway_error"}});let o=this.config.mode;return this.config.mode=r,this.config.endpoints=this.config.endpoint_modes[r],console.log(`[gateway] Switched mode ${o} -> ${r}`),y(e,200,{ok:!0,mode:r,previous:o})}_writePidFile(){this._pidFile&&(O.mkdirSync(K.dirname(this._pidFile),{recursive:!0}),O.writeFileSync(this._pidFile,String(process.pid),"utf-8"),console.log(`[gateway] PID ${process.pid} written to ${this._pidFile}`))}_removePidFile(){if(this._pidFile)try{O.unlinkSync(this._pidFile),console.log(`[gateway] PID file removed: ${this._pidFile}`)}catch{}}_printBanner(){let t=`http://${this.config.host}:${this.config.port}`;if(console.log(),console.log(` aistatus gateway running on ${t}`),this.config.auth?.enabled){let e=this.config.auth.keys.length,n=(this.config.auth.public_paths??["/health"]).join(", ");console.log(` Auth: ${e} key${e!==1?"s":""} configured (public: ${n})`)}console.log();for(let[e,n]of Object.entries(this.config.endpoints)){let s=n.keys.length,r=n.fallbacks.length,o;s>0&&n.passthrough?o=`${s} key${s!==1?"s":""} + passthrough`:s>0?o=`${s} key${s!==1?"s":""}`:o="passthrough";let i=n.fallbacks.map(c=>c.name).join(", "),a=i?` \u2192 fallback: ${i}`:"";console.log(` /${e}/* (${o}${a})`)}console.log(),console.log(" Configure your CLI tools:"),"anthropic"in this.config.endpoints&&console.log(` export ANTHROPIC_BASE_URL=${t}/anthropic`),"openai"in this.config.endpoints&&console.log(` export OPENAI_BASE_URL=${t}/openai/v1`),console.log(),console.log(` Status: ${t}/status`),console.log(` Health: ${t}/health`),console.log(` Usage: ${t}/usage?period=today&group_by=model`),console.log()}},Rs=te.join(Zt.homedir(),".aistatus","gateway.yaml");function ue(t,e,n,s){let r=s.intervalMs??1e3,o=null,i=(a,c)=>{a.mtimeMs===0&&!s.reloadOnDelete||a.mtimeMs===c.mtimeMs&&a.size===c.size||(o&&clearTimeout(o),o=setTimeout(()=>{o=null;try{n(e())}catch(l){console.warn(`[gateway] Config reload failed for ${t}:`,l)}},200))};return J.watchFile(t,{interval:r,persistent:!1},i),console.log(`[gateway] Watching config file for changes: ${t}`),()=>{o&&(clearTimeout(o),o=null),J.unwatchFile(t,i)}}function Fs(t,e,n={}){return ue(t,()=>B(t),e,n)}function Ps(t,e={}){let n=e.filePath??at;return ue(n,()=>ct({filePath:n,env:e.env}),t,{intervalMs:e.intervalMs,reloadOnDelete:!0})}async function Xs(t={}){let e=t.host??"127.0.0.1",n=t.port??9880,s,r=null;t.auto?s=gt(e,n):t.configPath?(s=B(t.configPath),r=t.configPath):(s=B(),r=Rs),s.host=e,s.port=n;let o=new Cs(s,t.pidFile);return t.watchConfig!==!1&&(r&&Fs(r,i=>o.reloadConfig(i)),Ps(i=>o.reloadUploadConfig(i))),await o.run(),o}export{D as AUTH_STYLES,pe as DEFAULT_BASE_URLS,mt as DEFAULT_MAX_BODY_SIZE_MB,Cs as GatewayServer,Tt as HealthTracker,An as QuotaSnapshotStore,de as RESERVED_KEYS,wn as anthropicRequestToOpenai,gt as autoDiscover,Gt as checkGatewayAuth,me as fromDict,ge as generateConfig,Et as isServerError,B as loadConfig,bn as openaiResponseToAnthropic,Sn as openaiSseToAnthropicSse,Xs as startGateway,Fs as watchConfigFile,Ps as watchUploadConfigFile};