@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,10 +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 p,c as S}from"./chunk-WHC7AYZD.js";var T=S((ur,qe)=>{"use strict";var Ae=["nodebuffer","arraybuffer","fragments"],We=typeof Blob<"u";We&&Ae.push("blob");qe.exports={BINARY_TYPES:Ae,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:We,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Y=S((dr,se)=>{"use strict";var{EMPTY_BUFFER:jt}=T(),pe=Buffer[Symbol.species];function Vt(t,e){if(t.length===0)return jt;if(t.length===1)return t[0];let s=Buffer.allocUnsafe(e),r=0;for(let i=0;i<t.length;i++){let n=t[i];s.set(n,r),r+=n.length}return r<e?new pe(s.buffer,s.byteOffset,r):s}function Ge(t,e,s,r,i){for(let n=0;n<i;n++)s[r+n]=t[n]^e[n&3]}function $e(t,e){for(let s=0;s<t.length;s++)t[s]^=e[s&3]}function zt(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function ge(t){if(ge.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new pe(t):ArrayBuffer.isView(t)?e=new pe(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),ge.readOnly=!1),e}se.exports={concat:Vt,mask:Ge,toArrayBuffer:zt,toBuffer:ge,unmask:$e};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=p("bufferutil");se.exports.mask=function(e,s,r,i,n){n<48?Ge(e,s,r,i,n):t.mask(e,s,r,i,n)},se.exports.unmask=function(e,s){e.length<32?$e(e,s):t.unmask(e,s)}}catch{}});var ze=S((_r,Ve)=>{"use strict";var je=Symbol("kDone"),ye=Symbol("kRun"),xe=class{constructor(e){this[je]=()=>{this.pending--,this[ye]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[ye]()}[ye](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[je])}}};Ve.exports=xe});var X=S((mr,Xe)=>{"use strict";var K=p("zlib"),He=Y(),Ht=ze(),{kStatusCode:Ye}=T(),Yt=Buffer[Symbol.species],Kt=Buffer.from([0,0,255,255]),ie=Symbol("permessage-deflate"),k=Symbol("total-length"),A=Symbol("callback"),N=Symbol("buffers"),W=Symbol("error"),re,Se=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!re){let s=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;re=new Ht(s)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[A];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let s=this._options,r=e.find(i=>!(s.serverNoContextTakeover===!1&&i.server_no_context_takeover||i.server_max_window_bits&&(s.serverMaxWindowBits===!1||typeof s.serverMaxWindowBits=="number"&&s.serverMaxWindowBits>i.server_max_window_bits)||typeof s.clientMaxWindowBits=="number"&&!i.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return s.serverNoContextTakeover&&(r.server_no_context_takeover=!0),s.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof s.serverMaxWindowBits=="number"&&(r.server_max_window_bits=s.serverMaxWindowBits),typeof s.clientMaxWindowBits=="number"?r.client_max_window_bits=s.clientMaxWindowBits:(r.client_max_window_bits===!0||s.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let s=e[0];if(this._options.clientNoContextTakeover===!1&&s.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!s.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(s.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&s.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return s}normalizeParams(e){return e.forEach(s=>{Object.keys(s).forEach(r=>{let i=s[r];if(i.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(i=i[0],r==="client_max_window_bits"){if(i!==!0){let n=+i;if(!Number.isInteger(n)||n<8||n>15)throw new TypeError(`Invalid value for parameter "${r}": ${i}`);i=n}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${i}`)}else if(r==="server_max_window_bits"){let n=+i;if(!Number.isInteger(n)||n<8||n>15)throw new TypeError(`Invalid value for parameter "${r}": ${i}`);i=n}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(i!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${i}`)}else throw new Error(`Unknown parameter "${r}"`);s[r]=i})}),e}decompress(e,s,r){re.add(i=>{this._decompress(e,s,(n,o)=>{i(),r(n,o)})})}compress(e,s,r){re.add(i=>{this._compress(e,s,(n,o)=>{i(),r(n,o)})})}_decompress(e,s,r){let i=this._isServer?"client":"server";if(!this._inflate){let n=`${i}_max_window_bits`,o=typeof this.params[n]!="number"?K.Z_DEFAULT_WINDOWBITS:this.params[n];this._inflate=K.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[ie]=this,this._inflate[k]=0,this._inflate[N]=[],this._inflate.on("error",Zt),this._inflate.on("data",Ke)}this._inflate[A]=r,this._inflate.write(e),s&&this._inflate.write(Kt),this._inflate.flush(()=>{let n=this._inflate[W];if(n){this._inflate.close(),this._inflate=null,r(n);return}let o=He.concat(this._inflate[N],this._inflate[k]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[k]=0,this._inflate[N]=[],s&&this.params[`${i}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,s,r){let i=this._isServer?"server":"client";if(!this._deflate){let n=`${i}_max_window_bits`,o=typeof this.params[n]!="number"?K.Z_DEFAULT_WINDOWBITS:this.params[n];this._deflate=K.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[k]=0,this._deflate[N]=[],this._deflate.on("data",Xt)}this._deflate[A]=r,this._deflate.write(e),this._deflate.flush(K.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let n=He.concat(this._deflate[N],this._deflate[k]);s&&(n=new Yt(n.buffer,n.byteOffset,n.length-4)),this._deflate[A]=null,this._deflate[k]=0,this._deflate[N]=[],s&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),r(null,n)})}};Xe.exports=Se;function Xt(t){this[N].push(t),this[k]+=t.length}function Ke(t){if(this[k]+=t.length,this[ie]._maxPayload<1||this[k]<=this[ie]._maxPayload){this[N].push(t);return}this[W]=new RangeError("Max payload size exceeded"),this[W].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[W][Ye]=1009,this.removeListener("data",Ke),this.reset()}function Zt(t){if(this[ie]._inflate=null,this[W]){this[A](this[W]);return}t[Ye]=1007,this[A](t)}});var q=S((pr,ne)=>{"use strict";var{isUtf8:Ze}=p("buffer"),{hasBlob:Qt}=T(),Jt=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function es(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Ee(t){let e=t.length,s=0;for(;s<e;)if((t[s]&128)===0)s++;else if((t[s]&224)===192){if(s+1===e||(t[s+1]&192)!==128||(t[s]&254)===192)return!1;s+=2}else if((t[s]&240)===224){if(s+2>=e||(t[s+1]&192)!==128||(t[s+2]&192)!==128||t[s]===224&&(t[s+1]&224)===128||t[s]===237&&(t[s+1]&224)===160)return!1;s+=3}else if((t[s]&248)===240){if(s+3>=e||(t[s+1]&192)!==128||(t[s+2]&192)!==128||(t[s+3]&192)!==128||t[s]===240&&(t[s+1]&240)===128||t[s]===244&&t[s+1]>143||t[s]>244)return!1;s+=4}else return!1;return!0}function ts(t){return Qt&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}ne.exports={isBlob:ts,isValidStatusCode:es,isValidUTF8:Ee,tokenChars:Jt};if(Ze)ne.exports.isValidUTF8=function(t){return t.length<24?Ee(t):Ze(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=p("utf-8-validate");ne.exports.isValidUTF8=function(e){return e.length<32?Ee(e):t(e)}}catch{}});var nt=S((gr,it)=>{"use strict";var{Writable:ss}=p("stream"),Qe=X(),{BINARY_TYPES:rs,EMPTY_BUFFER:Je,kStatusCode:is,kWebSocket:ns}=T(),{concat:ve,toArrayBuffer:os,unmask:as}=Y(),{isValidStatusCode:fs,isValidUTF8:et}=q(),oe=Buffer[Symbol.species],v=0,tt=1,st=2,rt=3,be=4,we=5,ae=6,Oe=class extends ss{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||rs[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[ns]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=v}_write(e,s,r){if(this._opcode===8&&this._state==v)return r();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){r(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new oe(r.buffer,r.byteOffset+e,r.length-e),new oe(r.buffer,r.byteOffset,e)}let s=Buffer.allocUnsafe(e);do{let r=this._buffers[0],i=s.length-e;e>=r.length?s.set(this._buffers.shift(),i):(s.set(new Uint8Array(r.buffer,r.byteOffset,e),i),this._buffers[0]=new oe(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return s}startLoop(e){this._loop=!0;do switch(this._state){case v:this.getInfo(e);break;case tt:this.getPayloadLength16(e);break;case st:this.getPayloadLength64(e);break;case rt:this.getMask();break;case be:this.getData(e);break;case we:case ae:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let s=this.consume(2);if((s[0]&48)!==0){let i=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(i);return}let r=(s[0]&64)===64;if(r&&!this._extensions[Qe.extensionName]){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._fin=(s[0]&128)===128,this._opcode=s[0]&15,this._payloadLength=s[1]&127,this._opcode===0){if(r){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(!this._fragmented){let i=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let i=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(i);return}if(r){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let i=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(i);return}}else{let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(s[1]&128)===128,this._isServer){if(!this._masked){let i=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(i);return}}else if(this._masked){let i=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(i);return}this._payloadLength===126?this._state=tt:this._payloadLength===127?this._state=st:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let s=this.consume(8),r=s.readUInt32BE(0);if(r>Math.pow(2,21)-1){let i=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(i);return}this._payloadLength=r*Math.pow(2,32)+s.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let s=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(s);return}this._masked?this._state=rt:this._state=be}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=be}getData(e){let s=Je;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}s=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&as(s,this._mask)}if(this._opcode>7){this.controlMessage(s,e);return}if(this._compressed){this._state=we,this.decompress(s,e);return}if(s.length){if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let r=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(r);return}this._messageLength=this._totalPayloadLength,this._fragments.push(s)}this.dataMessage(e)}decompress(e,s){this._extensions[Qe.extensionName].decompress(e,this._fin,(i,n)=>{if(i)return s(i);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");s(o);return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let o=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");s(o);return}this._fragments.push(n)}this.dataMessage(s),this._state===v&&this.startLoop(s)})}dataMessage(e){if(!this._fin){this._state=v;return}let s=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let i;this._binaryType==="nodebuffer"?i=ve(r,s):this._binaryType==="arraybuffer"?i=os(ve(r,s)):this._binaryType==="blob"?i=new Blob(r):i=r,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=v):(this._state=ae,setImmediate(()=>{this.emit("message",i,!0),this._state=v,this.startLoop(e)}))}else{let i=ve(r,s);if(!this._skipUTF8Validation&&!et(i)){let n=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(n);return}this._state===we||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=v):(this._state=ae,setImmediate(()=>{this.emit("message",i,!1),this._state=v,this.startLoop(e)}))}}controlMessage(e,s){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Je),this.end();else{let r=e.readUInt16BE(0);if(!fs(r)){let n=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");s(n);return}let i=new oe(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!et(i)){let n=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");s(n);return}this._loop=!1,this.emit("conclude",r,i),this.end()}this._state=v;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=v):(this._state=ae,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=v,this.startLoop(s)}))}createError(e,s,r,i,n){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${s}`:s);return Error.captureStackTrace(o,this.createError),o.code=n,o[is]=i,o}};it.exports=Oe});var lt=S((xr,ft)=>{"use strict";var{Duplex:yr}=p("stream"),{randomFillSync:ls}=p("crypto"),{types:{isUint8Array:hs}}=p("util"),ot=X(),{EMPTY_BUFFER:cs,kWebSocket:us,NOOP:ds}=T(),{isBlob:G,isValidStatusCode:_s}=q(),{mask:at,toBuffer:B}=Y(),b=Symbol("kByteLength"),ms=Buffer.alloc(4),fe=8*1024,R,$=fe,w=0,ps=1,gs=2,Te=class t{constructor(e,s,r){this._extensions=s||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=w,this.onerror=ds,this[us]=void 0}static frame(e,s){let r,i=!1,n=2,o=!1;s.mask&&(r=s.maskBuffer||ms,s.generateMask?s.generateMask(r):($===fe&&(R===void 0&&(R=Buffer.alloc(fe)),ls(R,0,fe),$=0),r[0]=R[$++],r[1]=R[$++],r[2]=R[$++],r[3]=R[$++]),o=(r[0]|r[1]|r[2]|r[3])===0,n=6);let f;typeof e=="string"?(!s.mask||o)&&s[b]!==void 0?f=s[b]:(e=Buffer.from(e),f=e.length):(f=e.length,i=s.mask&&s.readOnly&&!o);let l=f;f>=65536?(n+=8,l=127):f>125&&(n+=2,l=126);let a=Buffer.allocUnsafe(i?f+n:n);return a[0]=s.fin?s.opcode|128:s.opcode,s.rsv1&&(a[0]|=64),a[1]=l,l===126?a.writeUInt16BE(f,2):l===127&&(a[2]=a[3]=0,a.writeUIntBE(f,4,6)),s.mask?(a[1]|=128,a[n-4]=r[0],a[n-3]=r[1],a[n-2]=r[2],a[n-1]=r[3],o?[a,e]:i?(at(e,r,a,n,f),[a]):(at(e,r,e,0,f),[a,e])):[a,e]}close(e,s,r,i){let n;if(e===void 0)n=cs;else{if(typeof e!="number"||!_s(e))throw new TypeError("First argument must be a valid error code number");if(s===void 0||!s.length)n=Buffer.allocUnsafe(2),n.writeUInt16BE(e,0);else{let f=Buffer.byteLength(s);if(f>123)throw new RangeError("The message must not be greater than 123 bytes");if(n=Buffer.allocUnsafe(2+f),n.writeUInt16BE(e,0),typeof s=="string")n.write(s,2);else if(hs(s))n.set(s,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[b]:n.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==w?this.enqueue([this.dispatch,n,!1,o,i]):this.sendFrame(t.frame(n,o),i)}ping(e,s,r){let i,n;if(typeof e=="string"?(i=Buffer.byteLength(e),n=!1):G(e)?(i=e.size,n=!1):(e=B(e),i=e.length,n=B.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[b]:i,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:9,readOnly:n,rsv1:!1};G(e)?this._state!==w?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==w?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}pong(e,s,r){let i,n;if(typeof e=="string"?(i=Buffer.byteLength(e),n=!1):G(e)?(i=e.size,n=!1):(e=B(e),i=e.length,n=B.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[b]:i,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:10,readOnly:n,rsv1:!1};G(e)?this._state!==w?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==w?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,s,r){let i=this._extensions[ot.extensionName],n=s.binary?2:1,o=s.compress,f,l;typeof e=="string"?(f=Buffer.byteLength(e),l=!1):G(e)?(f=e.size,l=!1):(e=B(e),f=e.length,l=B.readOnly),this._firstFragment?(this._firstFragment=!1,o&&i&&i.params[i._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=f>=i._threshold),this._compress=o):(o=!1,n=0),s.fin&&(this._firstFragment=!0);let a={[b]:f,fin:s.fin,generateMask:this._generateMask,mask:s.mask,maskBuffer:this._maskBuffer,opcode:n,readOnly:l,rsv1:o};G(e)?this._state!==w?this.enqueue([this.getBlobData,e,this._compress,a,r]):this.getBlobData(e,this._compress,a,r):this._state!==w?this.enqueue([this.dispatch,e,this._compress,a,r]):this.dispatch(e,this._compress,a,r)}getBlobData(e,s,r,i){this._bufferedBytes+=r[b],this._state=gs,e.arrayBuffer().then(n=>{if(this._socket.destroyed){let f=new Error("The socket was closed while the blob was being read");process.nextTick(ke,this,f,i);return}this._bufferedBytes-=r[b];let o=B(n);s?this.dispatch(o,s,r,i):(this._state=w,this.sendFrame(t.frame(o,r),i),this.dequeue())}).catch(n=>{process.nextTick(ys,this,n,i)})}dispatch(e,s,r,i){if(!s){this.sendFrame(t.frame(e,r),i);return}let n=this._extensions[ot.extensionName];this._bufferedBytes+=r[b],this._state=ps,n.compress(e,r.fin,(o,f)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");ke(this,l,i);return}this._bufferedBytes-=r[b],this._state=w,r.readOnly=!1,this.sendFrame(t.frame(f,r),i),this.dequeue()})}dequeue(){for(;this._state===w&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][b],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][b],this._queue.push(e)}sendFrame(e,s){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],s),this._socket.uncork()):this._socket.write(e[0],s)}};ft.exports=Te;function ke(t,e,s){typeof s=="function"&&s(e);for(let r=0;r<t._queue.length;r++){let i=t._queue[r],n=i[i.length-1];typeof n=="function"&&n(e)}}function ys(t,e,s){ke(t,e,s),t.onerror(e)}});var Ce=S((Sr,ht)=>{"use strict";var{tokenChars:Z}=q();function O(t,e,s){t[e]===void 0?t[e]=[s]:t[e].push(s)}function xs(t){let e=Object.create(null),s=Object.create(null),r=!1,i=!1,n=!1,o,f,l=-1,a=-1,h=-1,c=0;for(;c<t.length;c++)if(a=t.charCodeAt(c),o===void 0)if(h===-1&&Z[a]===1)l===-1&&(l=c);else if(c!==0&&(a===32||a===9))h===-1&&l!==-1&&(h=c);else if(a===59||a===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${c}`);h===-1&&(h=c);let g=t.slice(l,h);a===44?(O(e,g,s),s=Object.create(null)):o=g,l=h=-1}else throw new SyntaxError(`Unexpected character at index ${c}`);else if(f===void 0)if(h===-1&&Z[a]===1)l===-1&&(l=c);else if(a===32||a===9)h===-1&&l!==-1&&(h=c);else if(a===59||a===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${c}`);h===-1&&(h=c),O(s,t.slice(l,h),!0),a===44&&(O(e,o,s),s=Object.create(null),o=void 0),l=h=-1}else if(a===61&&l!==-1&&h===-1)f=t.slice(l,c),l=h=-1;else throw new SyntaxError(`Unexpected character at index ${c}`);else if(i){if(Z[a]!==1)throw new SyntaxError(`Unexpected character at index ${c}`);l===-1?l=c:r||(r=!0),i=!1}else if(n)if(Z[a]===1)l===-1&&(l=c);else if(a===34&&l!==-1)n=!1,h=c;else if(a===92)i=!0;else throw new SyntaxError(`Unexpected character at index ${c}`);else if(a===34&&t.charCodeAt(c-1)===61)n=!0;else if(h===-1&&Z[a]===1)l===-1&&(l=c);else if(l!==-1&&(a===32||a===9))h===-1&&(h=c);else if(a===59||a===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${c}`);h===-1&&(h=c);let g=t.slice(l,h);r&&(g=g.replace(/\\/g,""),r=!1),O(s,f,g),a===44&&(O(e,o,s),s=Object.create(null),o=void 0),f=void 0,l=h=-1}else throw new SyntaxError(`Unexpected character at index ${c}`);if(l===-1||n||a===32||a===9)throw new SyntaxError("Unexpected end of input");h===-1&&(h=c);let _=t.slice(l,h);return o===void 0?O(e,_,s):(f===void 0?O(s,_,!0):r?O(s,f,_.replace(/\\/g,"")):O(s,f,_),O(e,o,s)),e}function Ss(t){return Object.keys(t).map(e=>{let s=t[e];return Array.isArray(s)||(s=[s]),s.map(r=>[e].concat(Object.keys(r).map(i=>{let n=r[i];return Array.isArray(n)||(n=[n]),n.map(o=>o===!0?i:`${i}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}ht.exports={format:Ss,parse:xs}});var xt=S((Er,yt)=>{"use strict";var{kForOnEventAttribute:Q,kListener:Le}=T(),ct=Symbol("kCode"),ut=Symbol("kData"),dt=Symbol("kError"),_t=Symbol("kMessage"),mt=Symbol("kReason"),j=Symbol("kTarget"),pt=Symbol("kType"),gt=Symbol("kWasClean"),C=class{constructor(e){this[j]=null,this[pt]=e}get target(){return this[j]}get type(){return this[pt]}};Object.defineProperty(C.prototype,"target",{enumerable:!0});Object.defineProperty(C.prototype,"type",{enumerable:!0});var U=class extends C{constructor(e,s={}){super(e),this[ct]=s.code===void 0?0:s.code,this[mt]=s.reason===void 0?"":s.reason,this[gt]=s.wasClean===void 0?!1:s.wasClean}get code(){return this[ct]}get reason(){return this[mt]}get wasClean(){return this[gt]}};Object.defineProperty(U.prototype,"code",{enumerable:!0});Object.defineProperty(U.prototype,"reason",{enumerable:!0});Object.defineProperty(U.prototype,"wasClean",{enumerable:!0});var V=class extends C{constructor(e,s={}){super(e),this[dt]=s.error===void 0?null:s.error,this[_t]=s.message===void 0?"":s.message}get error(){return this[dt]}get message(){return this[_t]}};Object.defineProperty(V.prototype,"error",{enumerable:!0});Object.defineProperty(V.prototype,"message",{enumerable:!0});var J=class extends C{constructor(e,s={}){super(e),this[ut]=s.data===void 0?null:s.data}get data(){return this[ut]}};Object.defineProperty(J.prototype,"data",{enumerable:!0});var Es={addEventListener(t,e,s={}){for(let i of this.listeners(t))if(!s[Q]&&i[Le]===e&&!i[Q])return;let r;if(t==="message")r=function(n,o){let f=new J("message",{data:o?n:n.toString()});f[j]=this,le(e,this,f)};else if(t==="close")r=function(n,o){let f=new U("close",{code:n,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});f[j]=this,le(e,this,f)};else if(t==="error")r=function(n){let o=new V("error",{error:n,message:n.message});o[j]=this,le(e,this,o)};else if(t==="open")r=function(){let n=new C("open");n[j]=this,le(e,this,n)};else return;r[Q]=!!s[Q],r[Le]=e,s.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let s of this.listeners(t))if(s[Le]===e&&!s[Q]){this.removeListener(t,s);break}}};yt.exports={CloseEvent:U,ErrorEvent:V,Event:C,EventTarget:Es,MessageEvent:J};function le(t,e,s){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,s):t.call(e,s)}});var Ue=S((wr,Pt)=>{"use strict";var vs=p("events"),bs=p("https"),ws=p("http"),vt=p("net"),Os=p("tls"),{randomBytes:Ts,createHash:ks}=p("crypto"),{Duplex:vr,Readable:br}=p("stream"),{URL:Ne}=p("url"),P=X(),Cs=nt(),Ls=lt(),{isBlob:Ns}=q(),{BINARY_TYPES:St,CLOSE_TIMEOUT:Ps,EMPTY_BUFFER:he,GUID:Bs,kForOnEventAttribute:Pe,kListener:Rs,kStatusCode:Us,kWebSocket:y,NOOP:bt}=T(),{EventTarget:{addEventListener:Is,removeEventListener:Ds}}=xt(),{format:Fs,parse:Ms}=Ce(),{toBuffer:As}=Y(),wt=Symbol("kAborted"),Be=[8,13],L=["CONNECTING","OPEN","CLOSING","CLOSED"],Ws=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,d=class t extends vs{constructor(e,s,r){super(),this._binaryType=St[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=he,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,s===void 0?s=[]:Array.isArray(s)||(typeof s=="object"&&s!==null?(r=s,s=[]):s=[s]),Ot(this,e,s,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){St.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,s,r){let i=new Cs({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),n=new Ls(e,this._extensions,r.generateMask);this._receiver=i,this._sender=n,this._socket=e,i[y]=this,n[y]=this,e[y]=this,i.on("conclude",$s),i.on("drain",js),i.on("error",Vs),i.on("message",zs),i.on("ping",Hs),i.on("pong",Ys),n.onerror=Ks,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),s.length>0&&e.unshift(s),e.on("close",Ct),e.on("data",ue),e.on("end",Lt),e.on("error",Nt),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[P.extensionName]&&this._extensions[P.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,s){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){E(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,s,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),kt(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,s,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=s=void 0):typeof s=="function"&&(r=s,s=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Re(this,e,r);return}s===void 0&&(s=!this._isServer),this._sender.ping(e||he,s,r)}pong(e,s,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=s=void 0):typeof s=="function"&&(r=s,s=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Re(this,e,r);return}s===void 0&&(s=!this._isServer),this._sender.pong(e||he,s,r)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,s,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof s=="function"&&(r=s,s={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Re(this,e,r);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...s};this._extensions[P.extensionName]||(i.compress=!1),this._sender.send(e||he,i,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){E(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(d,"CONNECTING",{enumerable:!0,value:L.indexOf("CONNECTING")});Object.defineProperty(d.prototype,"CONNECTING",{enumerable:!0,value:L.indexOf("CONNECTING")});Object.defineProperty(d,"OPEN",{enumerable:!0,value:L.indexOf("OPEN")});Object.defineProperty(d.prototype,"OPEN",{enumerable:!0,value:L.indexOf("OPEN")});Object.defineProperty(d,"CLOSING",{enumerable:!0,value:L.indexOf("CLOSING")});Object.defineProperty(d.prototype,"CLOSING",{enumerable:!0,value:L.indexOf("CLOSING")});Object.defineProperty(d,"CLOSED",{enumerable:!0,value:L.indexOf("CLOSED")});Object.defineProperty(d.prototype,"CLOSED",{enumerable:!0,value:L.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(d.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(d.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Pe])return e[Rs];return null},set(e){for(let s of this.listeners(t))if(s[Pe]){this.removeListener(t,s);break}typeof e=="function"&&this.addEventListener(t,e,{[Pe]:!0})}})});d.prototype.addEventListener=Is;d.prototype.removeEventListener=Ds;Pt.exports=d;function Ot(t,e,s,r){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Ps,protocolVersion:Be[1],maxBufferedChunks:1048576,maxFragments:131072,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=i.autoPong,t._closeTimeout=i.closeTimeout,!Be.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${Be.join(", ")})`);let n;if(e instanceof Ne)n=e;else try{n=new Ne(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}n.protocol==="http:"?n.protocol="ws:":n.protocol==="https:"&&(n.protocol="wss:"),t._url=n.href;let o=n.protocol==="wss:",f=n.protocol==="ws+unix:",l;if(n.protocol!=="ws:"&&!o&&!f?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:f&&!n.pathname?l="The URL's pathname is empty":n.hash&&(l="The URL contains a fragment identifier"),l){let u=new SyntaxError(l);if(t._redirects===0)throw u;ce(t,u);return}let a=o?443:80,h=Ts(16).toString("base64"),c=o?bs.request:ws.request,_=new Set,g;if(i.createConnection=i.createConnection||(o?Gs:qs),i.defaultPort=i.defaultPort||a,i.port=n.port||a,i.host=n.hostname.startsWith("[")?n.hostname.slice(1,-1):n.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":h,Connection:"Upgrade",Upgrade:"websocket"},i.path=n.pathname+n.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(g=new P({...i.perMessageDeflate,isServer:!1,maxPayload:i.maxPayload}),i.headers["Sec-WebSocket-Extensions"]=Fs({[P.extensionName]:g.offer()})),s.length){for(let u of s){if(typeof u!="string"||!Ws.test(u)||_.has(u))throw new SyntaxError("An invalid or duplicated subprotocol was specified");_.add(u)}i.headers["Sec-WebSocket-Protocol"]=s.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(n.username||n.password)&&(i.auth=`${n.username}:${n.password}`),f){let u=i.path.split(":");i.socketPath=u[0],i.path=u[1]}let m;if(i.followRedirects){if(t._redirects===0){t._originalIpc=f,t._originalSecure=o,t._originalHostOrSocketPath=f?i.socketPath:n.host;let u=r&&r.headers;if(r={...r,headers:{}},u)for(let[x,F]of Object.entries(u))r.headers[x.toLowerCase()]=F}else if(t.listenerCount("redirect")===0){let u=f?t._originalIpc?i.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:n.host===t._originalHostOrSocketPath;(!u||t._originalSecure&&!o)&&(delete i.headers.authorization,delete i.headers.cookie,u||delete i.headers.host,i.auth=void 0)}i.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),m=t._req=c(i),t._redirects&&t.emit("redirect",t.url,m)}else m=t._req=c(i);i.timeout&&m.on("timeout",()=>{E(t,m,"Opening handshake has timed out")}),m.on("error",u=>{m===null||m[wt]||(m=t._req=null,ce(t,u))}),m.on("response",u=>{let x=u.headers.location,F=u.statusCode;if(x&&i.followRedirects&&F>=300&&F<400){if(++t._redirects>i.maxRedirects){E(t,m,"Maximum redirects exceeded");return}m.abort();let z;try{z=new Ne(x,e)}catch{let M=new SyntaxError(`Invalid URL: ${x}`);ce(t,M);return}Ot(t,z,s,r)}else t.emit("unexpected-response",m,u)||E(t,m,`Unexpected server response: ${u.statusCode}`)}),m.on("upgrade",(u,x,F)=>{if(t.emit("upgrade",u),t.readyState!==d.CONNECTING)return;m=t._req=null;let z=u.headers.upgrade;if(z===void 0||z.toLowerCase()!=="websocket"){E(t,x,"Invalid Upgrade header");return}let De=ks("sha1").update(h+Bs).digest("base64");if(u.headers["sec-websocket-accept"]!==De){E(t,x,"Invalid Sec-WebSocket-Accept header");return}let M=u.headers["sec-websocket-protocol"],H;if(M!==void 0?_.size?_.has(M)||(H="Server sent an invalid subprotocol"):H="Server sent a subprotocol but none was requested":_.size&&(H="Server sent no subprotocol"),H){E(t,x,H);return}M&&(t._protocol=M);let Fe=u.headers["sec-websocket-extensions"];if(Fe!==void 0){if(!g){E(t,x,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let _e;try{_e=Ms(Fe)}catch{E(t,x,"Invalid Sec-WebSocket-Extensions header");return}let Me=Object.keys(_e);if(Me.length!==1||Me[0]!==P.extensionName){E(t,x,"Server indicated an extension that was not requested");return}try{g.accept(_e[P.extensionName])}catch{E(t,x,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[P.extensionName]=g}t.setSocket(x,F,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxBufferedChunks:i.maxBufferedChunks,maxFragments:i.maxFragments,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}),i.finishRequest?i.finishRequest(m,t):m.end()}function ce(t,e){t._readyState=d.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function qs(t){return t.path=t.socketPath,vt.connect(t)}function Gs(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=vt.isIP(t.host)?"":t.host),Os.connect(t)}function E(t,e,s){t._readyState=d.CLOSING;let r=new Error(s);Error.captureStackTrace(r,E),e.setHeader?(e[wt]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(ce,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Re(t,e,s){if(e){let r=Ns(e)?e.size:As(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(s){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${L[t.readyState]})`);process.nextTick(s,r)}}function $s(t,e){let s=this[y];s._closeFrameReceived=!0,s._closeMessage=e,s._closeCode=t,s._socket[y]!==void 0&&(s._socket.removeListener("data",ue),process.nextTick(Tt,s._socket),t===1005?s.close():s.close(t,e))}function js(){let t=this[y];t.isPaused||t._socket.resume()}function Vs(t){let e=this[y];e._socket[y]!==void 0&&(e._socket.removeListener("data",ue),process.nextTick(Tt,e._socket),e.close(t[Us])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Et(){this[y].emitClose()}function zs(t,e){this[y].emit("message",t,e)}function Hs(t){let e=this[y];e._autoPong&&e.pong(t,!this._isServer,bt),e.emit("ping",t)}function Ys(t){this[y].emit("pong",t)}function Tt(t){t.resume()}function Ks(t){let e=this[y];e.readyState!==d.CLOSED&&(e.readyState===d.OPEN&&(e._readyState=d.CLOSING,kt(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function kt(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Ct(){let t=this[y];if(this.removeListener("close",Ct),this.removeListener("data",ue),this.removeListener("end",Lt),t._readyState=d.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[y]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Et),t._receiver.on("finish",Et))}function ue(t){this[y]._receiver.write(t)||this.pause()}function Lt(){let t=this[y];t._readyState=d.CLOSING,t._receiver.end(),this.end()}function Nt(){let t=this[y];this.removeListener("error",Nt),this.on("error",bt),t&&(t._readyState=d.CLOSING,this.destroy())}});var Js=S((Tr,Ut)=>{"use strict";var Or=Ue(),{Duplex:Xs}=p("stream");function Bt(t){t.emit("close")}function Zs(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Rt(t){this.removeListener("error",Rt),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Qs(t,e){let s=!0,r=new Xs({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(n,o){let f=!o&&r._readableState.objectMode?n.toString():n;r.push(f)||t.pause()}),t.once("error",function(n){r.destroyed||(s=!1,r.destroy(n))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(i,n){if(t.readyState===t.CLOSED){n(i),process.nextTick(Bt,r);return}let o=!1;t.once("error",function(l){o=!0,n(l)}),t.once("close",function(){o||n(i),process.nextTick(Bt,r)}),s&&t.terminate()},r._final=function(i){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(i)});return}t._socket!==null&&(t._socket._writableState.finished?(i(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){i()}),t.close()))},r._read=function(){t.isPaused&&t.resume()},r._write=function(i,n,o){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(i,n,o)});return}t.send(i,o)},r.on("end",Zs),r.on("error",Rt),r}Ut.exports=Qs});var Dt=S((kr,It)=>{"use strict";var{tokenChars:er}=q();function tr(t){let e=new Set,s=-1,r=-1,i=0;for(i;i<t.length;i++){let o=t.charCodeAt(i);if(r===-1&&er[o]===1)s===-1&&(s=i);else if(i!==0&&(o===32||o===9))r===-1&&s!==-1&&(r=i);else if(o===44){if(s===-1)throw new SyntaxError(`Unexpected character at index ${i}`);r===-1&&(r=i);let f=t.slice(s,r);if(e.has(f))throw new SyntaxError(`The "${f}" subprotocol is duplicated`);e.add(f),s=r=-1}else throw new SyntaxError(`Unexpected character at index ${i}`)}if(s===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let n=t.slice(s,i);if(e.has(n))throw new SyntaxError(`The "${n}" subprotocol is duplicated`);return e.add(n),e}It.exports={parse:tr}});var cr=S((Lr,Gt)=>{"use strict";var sr=p("events"),de=p("http"),{Duplex:Cr}=p("stream"),{createHash:rr}=p("crypto"),Ft=Ce(),I=X(),ir=Dt(),nr=Ue(),{CLOSE_TIMEOUT:or,GUID:ar,kWebSocket:fr}=T(),lr=/^[+/0-9A-Za-z]{22}==$/,Mt=0,At=1,qt=2,Ie=class extends sr{constructor(e,s){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:1024*1024,maxFragments:128*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:or,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:nr,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=de.createServer((r,i)=>{let n=de.STATUS_CODES[426];i.writeHead(426,{"Content-Length":n.length,"Content-Type":"text/plain"}),i.end(n)}),this._server.listen(e.port,e.host,e.backlog,s)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=hr(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(i,n,o)=>{this.handleUpgrade(i,n,o,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Mt}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===qt){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(ee,this);return}if(e&&this.once("close",e),this._state!==At)if(this._state=At,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(ee,this):process.nextTick(ee,this);else{let s=this._server;this._removeListeners(),this._removeListeners=this._server=null,s.close(()=>{ee(this)})}}shouldHandle(e){if(this.options.path){let s=e.url.indexOf("?");if((s!==-1?e.url.slice(0,s):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,s,r,i){s.on("error",Wt);let n=e.headers["sec-websocket-key"],o=e.headers.upgrade,f=+e.headers["sec-websocket-version"];if(e.method!=="GET"){D(this,e,s,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){D(this,e,s,400,"Invalid Upgrade header");return}if(n===void 0||!lr.test(n)){D(this,e,s,400,"Missing or invalid Sec-WebSocket-Key header");return}if(f!==13&&f!==8){D(this,e,s,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){te(s,400);return}let l=e.headers["sec-websocket-protocol"],a=new Set;if(l!==void 0)try{a=ir.parse(l)}catch{D(this,e,s,400,"Invalid Sec-WebSocket-Protocol header");return}let h=e.headers["sec-websocket-extensions"],c={};if(this.options.perMessageDeflate&&h!==void 0){let _=new I({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let g=Ft.parse(h);g[I.extensionName]&&(_.accept(g[I.extensionName]),c[I.extensionName]=_)}catch{D(this,e,s,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let _={origin:e.headers[`${f===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(_,(g,m,u,x)=>{if(!g)return te(s,m||401,u,x);this.completeUpgrade(c,n,a,e,s,r,i)});return}if(!this.options.verifyClient(_))return te(s,401)}this.completeUpgrade(c,n,a,e,s,r,i)}completeUpgrade(e,s,r,i,n,o,f){if(!n.readable||!n.writable)return n.destroy();if(n[fr])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Mt)return te(n,503);let a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${rr("sha1").update(s+ar).digest("base64")}`],h=new this.options.WebSocket(null,void 0,this.options);if(r.size){let c=this.options.handleProtocols?this.options.handleProtocols(r,i):r.values().next().value;c&&(a.push(`Sec-WebSocket-Protocol: ${c}`),h._protocol=c)}if(e[I.extensionName]){let c=e[I.extensionName].params,_=Ft.format({[I.extensionName]:[c]});a.push(`Sec-WebSocket-Extensions: ${_}`),h._extensions=e}this.emit("headers",a,i),n.write(a.concat(`\r
5
- `).join(`\r
6
- `)),n.removeListener("error",Wt),h.setSocket(n,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(h),h.on("close",()=>{this.clients.delete(h),this._shouldEmitClose&&!this.clients.size&&process.nextTick(ee,this)})),f(h,i)}};Gt.exports=Ie;function hr(t,e){for(let s of Object.keys(e))t.on(s,e[s]);return function(){for(let r of Object.keys(e))t.removeListener(r,e[r])}}function ee(t){t._state=qt,t.emit("close")}function Wt(){this.destroy()}function te(t,e,s,r){s=s||de.STATUS_CODES[e],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(s),...r},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${de.STATUS_CODES[e]}\r
7
- `+Object.keys(r).map(i=>`${i}: ${r[i]}`).join(`\r
8
- `)+`\r
9
- \r
10
- `+s)}function D(t,e,s,r,i,n){if(t.listenerCount("wsClientError")){let o=new Error(i);Error.captureStackTrace(o,D),t.emit("wsClientError",o,s,e)}else te(s,r,i,n)}});export{X as a,nt as b,lt as c,Ce as d,Ue as e,Js as f,Dt as g,cr as h};
@@ -1,8 +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{m as l,t as f,w as d,x as m}from"./chunk-3YHOCPQU.js";import{c as p}from"./chunk-J5DVLUKY.js";import{mkdirSync as O,readFileSync as w,rmSync as M,writeFileSync as z}from"node:fs";import E from"node:path";var _=3600*1e3,N=20,A=E.join(l,"crash-limits.json");function F(e,t){try{let r=JSON.parse(w(e,"utf8"));return r.day===t&&r.groups&&typeof r.sentToday=="number"?r:{day:t,sentToday:0,groups:r.groups??{}}}catch{return{day:t,sentToday:0,groups:{}}}}function g(e,t,r){for(let[s,n]of Object.entries(t.groups))r-n.lastSentAt>24*_&&n.suppressed===0&&delete t.groups[s];try{O(E.dirname(e),{recursive:!0}),z(e,JSON.stringify(t),"utf8")}catch{}}function S(e,t=Date.now(),r=A){let s=F(r,new Date(t).toISOString().slice(0,10)),n=s.groups[e]??{lastSentAt:0,suppressed:0};return t-n.lastSentAt<_||s.sentToday>=N?(s.groups[e]={...n,suppressed:n.suppressed+1},g(r,s,t),{send:!1,suppressed:n.suppressed+1}):(s.groups[e]={lastSentAt:t,suppressed:0},s.sentToday+=1,g(r,s,t),{send:!0,suppressed:n.suppressed})}function h(e=A){M(e,{force:!0})}var H=/ at (\S+):(\d+):\d+\s*$/,Z=/^\s*at (\S+):(\d+):\d+\s*$/,K=/^[A-Za-z0-9._-]+$/,D=/^[A-Za-z0-9_-]+-\d+\.\d+\.\d+[A-Za-z0-9.+-]*$/,P=/^(?:core|std|alloc|proc_macro|test)$/;function R(e){return!/^(?:[A-Za-z]:\/|\/|~)/.test(e)}function v(e){return e.split("/").every(s=>K.test(s)&&s!=="..")&&e.length<=120?e:null}function G(e){let t=e.lastIndexOf("/src/");if(t<0)return null;let r=e.slice(0,t).split("/").pop()??"";return D.test(r)||e.includes("/library/")&&P.test(r)?`${r}/${e.slice(t+1)}`:e.slice(t+1)}function X(e){let t=e.replace(/\\/g,"/").replace(/^\.\//,"");return v(R(t)?t:G(t)??"")}function x(e){let t=e?X(e[1]):null;return t?`panic@${t}:${e[2]}`:null}function j(e){for(let t of e.split(`
5
- `)){let r=Z.exec(t);if(r&&R(r[1].replace(/\\/g,"/")))return x(r)}return null}function y(e,t){return x(H.exec(e))??j(t)??"panic@unknown"}import i from"node:os";var U=300,T=30,W=8e3;function Y(){try{return i.userInfo().username}catch{return""}}function B(){return{installRoot:p,homeDir:i.homedir(),username:Y(),hostname:i.hostname()}}function I(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function $(e){let t=e.replace(/\\/g,"/").replace(/\/+$/,""),r=t.replace(/\//g,"\\");return[...new Set([t,r])].filter(s=>s.length>1)}function J(e,t){let r=e;for(let s of $(t)){let n=new RegExp(`(?:file:\\/\\/\\/?)?${I(s)}([\\\\/][^\\s:'"()<>]*)`,"g");r=r.replace(n,(o,c)=>c.slice(1).replace(/\\/g,"/"))}return r}var V=/\b([a-z][a-z0-9+.-]*):\/\/([^\s/?#'"()<>]*)([^\s?#'"()<>]*)(?:[?#][^\s'"()<>]*)?/gi,q=new Set(["localhost","127.0.0.1","[::1]"]);function Q(e){return e.replace(V,(t,r,s,n)=>{let o=s.replace(/^[^@]*@/,""),c=o.replace(/:\d+$/,"").toLowerCase(),a=r.toLowerCase()==="cortexui"||q.has(c);return r.toLowerCase()==="file"?"<path>":`${r}://${a?o:"<host>"}${n}`})}var ee=/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g,te=/\b(?:sk|pk|rk|ghp|gho|ghs|ghu|github_pat|xox[abposr]|glpat|AKIA|AIza)[-_A-Za-z0-9]{8,}/g,re=/\b[0-9a-fA-F]{32,}\b/g,se=/[A-Za-z0-9+_=-]{32,}/g,ne=/\b(?!127\.0\.0\.1\b)(?!0\.0\.0\.0\b)(?:\d{1,3}\.){3}\d{1,3}\b/g;function oe(e){return e.replace(ee,"<email>").replace(te,"<secret>").replace(re,"<secret>").replace(se,t=>/\d/.test(t)&&/[A-Za-z]/.test(t)?"<secret>":t).replace(ne,"<ip>")}var ce=/(?<![\w.:/\\<>-])\/(?:[^\s:'"()<>,;]+)/g,ae=/\b[A-Za-z]:[\\/][^\s:'"()<>,;]*/g,ie=/\\\\[^\s\\:'"()<>]+\\[^\s:'"()<>,;]*/g;function ue(e){return e.replace(ie,"<path>").replace(ae,"<path>").replace(ce,"<path>")}function pe(e,t){let r=e;for(let n of $(t.homeDir))r=r.split(n).join("<home>");let s=[[t.hostname,"<host>"],[t.username,"<user>"]];for(let[n,o]of[...s].sort((c,a)=>a[0].length-c[0].length))n.length<3||(r=r.replace(new RegExp(`(?<![A-Za-z0-9])${I(n)}(?![A-Za-z0-9])`,"gi"),o));return r}function b(e,t=B()){let r=J(e,t.installRoot);return pe(ue(oe(Q(r))),t)}function u(e,t){return b(e,t).slice(0,U)}function C(e,t){let r=b(e,t).split(`
6
- `),s=r.findIndex(o=>/^\s*at\s/.test(o));return(s===-1?r.slice(0,T+1):r.slice(0,s+T)).join(`
7
- `).slice(0,W)}var le=/^\s*at\s+(?:(\S+)\s+)?\(?((?:dist|src)\/[^\s:()]+)/,fe=/(?:^|[\s@(])((?:[a-z]+:\/\/[^\s/]+)?\/assets\/[^\s:()]+)/;function k(e,t){for(let r of t.split(`
8
- `)){let s=le.exec(r);if(s)return`${e}@${s[2]}${s[1]?`#${s[1]}`:""}`.slice(0,200);let n=fe.exec(r);if(n)return`${e}@${n[1].replace(/^[a-z]+:\/\/[^/]+/,"")}`.slice(0,200)}return`${e}@unknown`.slice(0,200)}d({wipe:()=>h()});function L(e){return e instanceof Error?e.name||e.constructor?.name||"Error":typeof e=="object"&&e!==null?"NonErrorObject":`Non${typeof e}`}function de(e){return e instanceof Error?{errorName:L(e),message:e.message??"",stack:e.stack??""}:{errorName:L(e),message:"",stack:""}}function me(e,t=0){let r=u(e.errorName).slice(0,80)||"Error",s=C(e.stack);return{type:"crash",at:(e.at??new Date).toISOString(),component:e.component,kind:e.kind,errorName:r,message:u(e.message),stack:s,groupKey:Ee(e,r,s),uptimeS:e.uptimeS??null,route:e.route?.slice(0,80)??null,buildStamp:e.buildStamp?.slice(0,60)??null,client:e.client??null,exit:e.exit??null,suppressed:t}}function ge(e){return e?.signal?`ChildExit@${e.signal}`:`ChildExit@code:${e?.code??"unknown"}`}function Ee(e,t,r){return e.kind==="childExit"?ge(e.exit):e.kind==="panic"?y(e.message,e.stack):k(t,r)}function _e(e){try{if(!f())return;let t=me(e),r=S(t.groupKey);if(!r.send)return;m({...t,suppressed:r.suppressed},{urgent:!0})}catch{}}function Oe(e,t,r){_e({component:e,kind:t,...de(r),uptimeS:Math.round(process.uptime())})}export{u as a,C as b,k as c,_e as d,Oe 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
- import{f as t}from"./chunk-J5DVLUKY.js";import*as o from"path";var i=o.join(t,"data","pi"),n=o.join(t,"logs","sessions-pi");function r(p){return o.join(p,"models.json")}export{i as a,n as b,r as c};
@@ -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{e as m}from"./chunk-QWAQHHRS.js";import{c as a}from"./chunk-J5DVLUKY.js";import*as i from"path";var w="@cortex-agent/server";function f(r=process.execPath,s=a,n=process.platform){let e=n==="win32"?i.win32:i.posix,o=[e.dirname(r)],t=m(s,w,n);return t&&o.push(n==="win32"?t:e.join(t,"bin")),o}function l(r,s,n=process.platform){let e=n==="win32"?i.win32:i.posix,o=p=>{let c=e.normalize(p).replace(/[\\/]+$/,"");return n==="win32"?c.toLowerCase():c},t=r.split(e.delimiter).filter(Boolean),h=new Set(t.map(o));return[...s.filter(p=>!h.has(o(p))),...t].join(e.delimiter)}function d(){process.env.PATH=l(process.env.PATH??"",f())}export{f as a,d as b};
@@ -1,9 +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 Tt,B as Rt,D as Ct,E as j,G as Dt,v as St,z as w}from"./chunk-O3JW2F7D.js";import{R as Pt,W as kt,d as vt,m as wt,o as bt,r as N,t as _t,v as I}from"./chunk-TZFLHVOQ.js";import{a as Et}from"./chunk-7MU2AKNM.js";import{a as Ne}from"./chunk-JERCOLY3.js";import{a as At,e as F}from"./chunk-BGVHA2D4.js";import{b as f,d as h,h as Ft,i as Nt,j as It,k as jt,l as Ot,n as Mt,o as $t}from"./chunk-3OKHUVEM.js";import{f as xt}from"./chunk-OE4KH3NJ.js";import{q as yt}from"./chunk-3YHOCPQU.js";import{b as gt}from"./chunk-STUHNKQS.js";import{J as c}from"./chunk-DPQPXBTP.js";import{d as A}from"./chunk-W5LGYSPZ.js";import{e as u}from"./chunk-E7ZMYIY6.js";import{e as m}from"./chunk-NAA7GF6Q.js";import{d as b,f as ht,k as Y,l as E,y as S}from"./chunk-J5DVLUKY.js";import{e as Fe}from"./chunk-WHC7AYZD.js";import*as X from"node:path";var Lt="environments",R=X.join(E,Lt),yn=X.join(b,"config",Lt),Wt="main";import{existsSync as Q,mkdirSync as Ze,readdirSync as tt,readFileSync as zt,statSync as Qe,watch as tr,writeFileSync as er}from"node:fs";import*as D from"node:path";import{existsSync as q,readFileSync as Ke}from"node:fs";import*as x from"node:path";import{readFileSync as Ie}from"fs";import*as Kt from"path";var je=m("prompt-includes");function Oe(t){let e=t.trimStart();if(!e.startsWith("---"))return{frontmatter:null,body:t};let r=e.indexOf(`
5
- ---`,3);if(r===-1)return{frontmatter:null,body:t};let n=e.slice(3,r).trim(),o=e.slice(r+4).replace(/^\n/,""),i={},a;for(let s of n.split(`
6
- `)){let l=s.match(/^(\w[\w-]*)\s*:\s*(.*)$/);if(!l)continue;let[,p,P]=l,k=P.trim().replace(/^["'](.*)["']$/,"$1");p==="extends"?a=k:i[p]=k}return{frontmatter:{extends:a,vars:i},body:o}}function Me(t){let e=[],r=/^@fill\((\w[\w-]*)\)\s*\n([\s\S]*?)^@endfill\s*$/gm,n;for(;(n=r.exec(t))!==null;)e.push({name:n[1],content:n[2].replace(/\n$/,"")});return e}function $e(t,e){let r=new Map(e.map(n=>[n.name,n.content]));return t.replace(/^@block\((\w[\w-]*)\)\s*\n([\s\S]*?)^@endblock\s*$/gm,(n,o,i)=>{let a=r.get(o);return a!==void 0?a:i.replace(/\n$/,"")})}function Le(t,e){return t.replace(/\$\{(\w[\w-]*)(?::-([^}]*))?\}/g,(r,n,o)=>n in e?e[n]:o!==void 0?o:"")}function We(t,e){return t=t.replace(/^@if\(!(\w[\w-]*)\)\s*\n([\s\S]*?)^@endif\s*\n?/gm,(r,n,o)=>n in e&&e[n]!==""?"":o),t=t.replace(/^@if\((\w[\w-]*)\)\s*\n([\s\S]*?)^@endif\s*\n?/gm,(r,n,o)=>n in e&&e[n]!==""?o:""),t}function Vt(t,e){let{frontmatter:r,body:n}=Oe(t);if(!r||!r.extends)return r?n:t;let o=Kt.join(e,r.extends),i;try{i=Ie(o,"utf8")}catch(l){return je.error(`Failed to read template "${r.extends}": ${l.message}`),n}let a=Me(n),s=$e(i,a);return s=We(s,r.vars),s=Le(s,r.vars),s}var Ve=m("environments"),y="file:",C={directive:"directives",promptTemplate:"promptTemplates",systemPrompt:"systemPrompts"},Bt=x.join(b,"prompts");function Be(t,e){return q(x.join(S,t,e))?S:q(x.join(Bt,t,e))?Bt:S}function O(t,e){if(!e||!e.startsWith(y))return e;let r=e.slice(y.length),n=C[t];if(!n)return e;let o=Be(n,r);try{let i=Ke(x.join(o,n,r),"utf8");return Vt(i,x.join(o,n,"templates"))}catch(i){return Ve.error(`Failed to read ${t} file ref "${e}": ${i.message}`),e}}function Ut(){return{promptsDir:S,pluginBaseDir:ht,builtinDir:b,join:x.join,exists:q,isAbsolute:x.isAbsolute}}var Ue={loadRules:c.boolean().optional(),disableHooks:c.boolean().optional(),skills:c.boolean().optional(),settingSources:c.array(c.enum(["user","project","local"])).optional(),projectContext:c.boolean().optional()},Jt=c.object({name:c.string().min(1),description:c.string().optional(),directive:c.string().optional(),systemPrompt:c.string().optional(),promptTemplate:c.string().optional(),claudeAgent:c.string().optional(),outputStyle:c.string().optional(),tools:c.string().optional(),pluginDirs:c.array(c.string()).optional(),disabledPlugins:c.array(c.string()).optional(),mcpComposition:c.enum(["direct","none"]).optional(),mcpToolAllowlist:c.array(c.string()).optional(),...Ue}),Z=["persistSession","delegable"],Je=new Set([...Object.keys(Jt.shape),...Z]);function Ge(t){let e="";for(let r of t)typeof r=="number"?e+=`[${r}]`:e+=e===""?String(r):`.${String(r)}`;return e}function ze(t){return t.success?[]:t.error.issues.map(e=>({path:Ge(e.path)||"(root)",message:e.message}))}function He(t,e){return Object.keys(t).filter(r=>!e.has(r)).map(r=>({path:r,message:u("ux.tpl.unknownField",{key:r})}))}function Ye(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Xe(t,e,r,n,o){if(!n||typeof e!="string"||!e.startsWith(y))return;let i=C[t];if(!i)return;let a=e.slice(y.length);n.exists(n.join(n.promptsDir,i,a))||n.exists(n.join(n.builtinDir,"prompts",i,a))||o.push({path:r,message:u("ux.tpl.promptFileMissing",{subdir:i,filename:a,value:e})})}function qe(t,e,r){!e||!Array.isArray(t)||t.forEach((n,o)=>{if(typeof n!="string")return;let i=e.isAbsolute(n)?n:e.join(e.pluginBaseDir,n),a=!e.isAbsolute(n)&&e.exists(e.join(e.builtinDir,n));!e.exists(i)&&!a&&r.push({path:`pluginDirs[${o}]`,message:u("ux.tpl.pluginDirMissing",{dir:n})})})}function M(t,e,r){if(!Ye(e))return{errors:[{path:"(root)",message:u("ux.tpl.bodyNotObject")}],warnings:[]};let n={errors:ze(Jt.safeParse(e)),warnings:He(e,Je)};typeof e.name=="string"&&e.name!==t&&n.errors.push({path:"name",message:u("ux.tpl.nameMismatch",{name:e.name,file:t})});for(let o of["directive","systemPrompt","promptTemplate"])Xe(o,e[o],o,r,n.warnings);return qe(e.pluginDirs,r,n.warnings),n}var g=m("environments"),_={},Ht=!1,Yt=0;function $n(){return Yt}function rr(t){if(!Q(t))return{};let e={};for(let r of tt(t).sort()){if(!r.endsWith(".json"))continue;let n=r.slice(0,-5),o;try{o=JSON.parse(zt(D.join(t,r),"utf8"))}catch(l){g.warn(`Skipping malformed environment ${r}: ${l.message}`);continue}let{errors:i,warnings:a}=M(n,o,Ut());for(let l of i)g.error(`environment ${n} \u2014 ${l.path}: ${l.message}`);for(let l of a)g.warn(`environment ${n} \u2014 ${l.path}: ${l.message}`);let s=o;if(!s||typeof s!="object"||s.name!==n){g.warn(`Skipping environment ${r}: name field "${s?.name}" \u2260 filename`);continue}for(let l of["profile",...Z])delete s[l];e[n]=s}return e}function Xt(t=R){try{_=rr(t)}catch(e){g.error(`Failed to load environments from ${t}: ${e.message}`),_={}}return Ht=!0,Yt+=1,g.info(`Loaded ${Object.keys(_).length} environments`),_}function qt(){Ht||Xt()}function Zt(t){qt();let e=_[t];if(!e)return null;let r=structuredClone(e);r.directive=O("directive",r.directive),r.systemPrompt=O("systemPrompt",r.systemPrompt),r.promptTemplate=O("promptTemplate",r.promptTemplate);let n=St(r);return n&&(r.pluginDirs=n),r}function Ln(){return qt(),Object.keys(_).sort().map(t=>_[t])}function Wn(t,e){if(!Q(t))return g.warn(`Cannot read default environments from ${t}`),!1;let r=!1;for(let n of tt(t)){if(!n.endsWith(".json"))continue;let o=D.join(e,n);if(!Q(o))try{Ze(e,{recursive:!0}),er(o,zt(D.join(t,n),"utf8"),"utf8"),g.info(`Added environment from defaults: ${n}`),r=!0}catch(i){g.error(`Failed to copy default environment ${n}: ${i.message}`)}}return r}var Gt=null,$=null;function nr(t){try{return tt(t).filter(e=>e.endsWith(".json")).sort().map(e=>{let r=Qe(D.join(t,e));return`${e}:${r.size}:${r.mtimeMs}:${r.ctimeMs}:${r.ino}`}).join("|")}catch{return"missing"}}function or(t){$&&clearTimeout($),$=setTimeout(()=>{$=null,g.info("Detected change in environments, reloading..."),Xt(t)},300)}function Kn(t=R){Gt?.close(),Gt=gt({label:"environments",snapshot:()=>nr(t),onChange:()=>or(t),startWatching:e=>[tr(t,()=>e())],warn:e=>g.error(e)})}var ir="__active__";function ar(t,e){return t===ir?Pt(e)||Wt:t}function sr(t){return{directive:t.directive,systemPrompt:t.systemPrompt,promptTemplate:t.promptTemplate,claudeAgent:t.claudeAgent,outputStyle:t.outputStyle,tools:t.tools,pluginDirs:t.pluginDirs,mcpComposition:t.mcpComposition,mcpToolAllowlist:t.mcpToolAllowlist?xt(t.mcpToolAllowlist):void 0,loadRules:t.loadRules,disableHooks:t.disableHooks,skills:t.skills,settingSources:t.settingSources,projectContext:t.projectContext}}function zn(t,e){let r=Zt(ar(t,e));return r?sr(r):null}import{createHash as ur}from"node:crypto";import{existsSync as L,mkdirSync as lr,readdirSync as cr,readFileSync as Qt,rmSync as pr}from"node:fs";import*as W from"node:path";var mr=/^[A-Za-z0-9][A-Za-z0-9_-]*$/;function d(t,e,r){return Object.assign(new Error(e),{code:t,...r?{issues:r}:{}})}function et(t){return ur("sha256").update(t,"utf8").digest("hex")}function rt(t){if(typeof t!="string"||!mr.test(t))throw d("invalid-args",u("ux.tpl.invalidName",{name:String(t)}))}function nt(t,e){return W.join(t,`${e}.json`)}function te(t){return L(t)?cr(t).filter(e=>e.endsWith(".json")).map(e=>e.slice(0,-5)).sort():[]}function ot(t,e){rt(e);let r=nt(t,e);if(!L(r))throw d("not-found",u("ux.tpl.unknownEntity",{name:e}));let n=Qt(r,"utf8"),o=null;try{let i=JSON.parse(n);i&&typeof i=="object"&&!Array.isArray(i)&&(o=i)}catch{o=null}return{name:e,filePath:r,body:o,content:n,sha256:et(n)}}function it(t,e,r){let{name:n,body:o,baseHash:i}=e;if(rt(n),!o||typeof o!="object"||Array.isArray(o))throw d("invalid-args",u("ux.tpl.bodyNotObject"));let a=nt(t,n),s=L(a),l=s?Qt(a,"utf8"):null;if(i===null&&s)throw d("invalid-args",u("ux.tpl.alreadyExists",{name:n}));if(i!==null&&!s)throw d("not-found",u("ux.tpl.unknownEntity",{name:n}));if(i!==null&&l!==null&&et(l)!==i)throw d("conflict",u("ux.tpl.changedOnDisk",{name:n}));let{errors:p,warnings:P}=M(n,o,r);if(p.length>0)throw d("invalid-args",u("ux.tpl.notValid",{name:n,issues:p.map(dt=>`${dt.path}: ${dt.message}`).join("; ")}),p);let k=`${JSON.stringify(o,null,2)}
7
- `,ft=l!==k;return ft&&(lr(W.dirname(a),{recursive:!0}),A(a,k)),{changed:ft,filePath:a,warnings:P,sha256:et(k)}}function to(t,e){rt(e);let r=nt(t,e);if(!L(r))throw d("not-found",u("ux.tpl.unknownEntity",{name:e}));return pr(r,{force:!0}),{removed:!0,filePath:r}}import{existsSync as ne,readFileSync as fr,rmSync as dr}from"node:fs";import*as v from"node:path";var ee=C.systemPrompt;function oe(t=R){return{envDir:t,promptDir:v.join(S,ee),defaultPromptDir:v.join(b,"prompts",ee)}}function ie(t){return typeof t!="string"||!t.startsWith(y)?null:t.slice(y.length)||null}function K(t){return ne(t)?fr(t,"utf8"):null}function V(t,e){let r=v.resolve(t,e),n=v.relative(t,r);return n&&!n.startsWith("..")&&!v.isAbsolute(n)?r:null}function ae(t,e,r){let n=`${y}${e}`;return te(t).filter(o=>{if(o===r)return!1;try{return ot(t,o).body?.systemPrompt===n}catch{return!1}})}function lo(t,e,r=oe()){let n=e?.systemPrompt,o=ie(n);if(o){let a=V(r.promptDir,o),s=V(r.defaultPromptDir,o),l=s?K(s):null;return{kind:"file",file:o,text:(a&&K(a))??l??"",sharedWith:ae(r.envDir,o,t),defaultText:l}}let i=typeof n=="string"&&n.length>0;return{kind:i?"inline":"none",file:null,text:i?n:"",sharedWith:[],defaultText:null}}function re(t,e,r){let n=V(t.promptDir,e);if(!n)throw d("invalid-args",u("ux.env.promptFileOutside",{file:e}));let o=V(t.defaultPromptDir,e);return o&&K(o)===r?ne(n)?(dr(n),!0):!1:K(n)===r?!1:(A(n,r),!0)}function co(t,e,r=oe(),n){let o=ot(r.envDir,t);if(!o.body)throw d("invalid-args",u("ux.tpl.bodyNotObject"));let i=ie(o.body.systemPrompt);if(i)return{changed:re(r,i,e),file:i};if(e.trim()===""){let p={...o.body};return delete p.systemPrompt,{changed:it(r.envDir,{name:t,body:p,baseHash:o.sha256},n).changed,file:null}}let a=`${t}.md`,s=ae(r.envDir,a,t);if(s.length>0)throw d("conflict",u("ux.env.promptFileInUse",{file:a,envs:s.join(", ")}));re(r,a,e);let l={...o.body,systemPrompt:`${y}${a}`};return it(r.envDir,{name:t,body:l,baseHash:o.sha256},n),{changed:!0,file:a}}import{existsSync as hr,readFileSync as gr}from"node:fs";import*as at from"node:path";var ue=m("models-generator");function yr(t,e){return t==="anthropic"&&(e==="plan"||e==="api")?"claude":"pi"}function le(t){return t.flatMap(e=>e.models.map(r=>({model:r,backend:yr(e.endpoint,e.mode),mode:e.mode,endpoint:e.endpoint})))}function _o(t){return le(t).sort((e,r)=>e.mode.localeCompare(r.mode)||e.model.localeCompare(r.model)).map(({mode:e,model:r})=>({mode:e,model:r}))}function st(t){let e=t.find(n=>n.models.length>0);if(!e)return;let r=e.defaultModel&&e.models.includes(e.defaultModel)?e.defaultModel:e.models[0];return{mode:e.mode,model:r}}function se(t,e){let r=t.find(n=>n.mode===e.mode&&n.model===e.model);if(!r)throw new Error(`(mode="${e.mode}", model="${e.model}") not found among discovered models`);return{backend:r.backend,provider:r.backend==="pi"?r.endpoint:null,model:r.model,thinking:null,mode:r.backend==="pi"?r.endpoint:r.mode}}function ce(t){let e=t.map(({backend:r,provider:n,model:o})=>{let i={backend:r,provider:n,model:o};return[JSON.stringify([r,n,o]),i]});return[...new Map(e).values()]}function B(t,e={}){let r=e.defaultChoice??st(t);if(!r)throw new Error("No discovered model is available for the default selection");let n=le(t),o=se(n,r),i=(e.favorites??[]).map(a=>se(n,a));return{default:o,favorites:ce([o,...i])}}function ut(t){let e=at.join(t,"models.json");if(!hr(e))return null;try{return JSON.parse(gr(e,"utf8"))}catch(r){return ue.warn(`Failed to read models.json: ${r.message}`),null}}function lt(t,e=E,r=!1){let n=ut(e);return{default:!r&&n?.default?n.default:t.default,favorites:ce([...n?.favorites??[],...t.favorites])}}function Po(t,e={}){let r=e.outputDir??E,n=lt(B(t,e),r,e.overwrite),o=at.join(r,"models.json");return A(o,JSON.stringify(n,null,2)+`
8
- `),ue.info(`Written models.json to ${o}`),o}import*as me from"node:path";var pe=m("gateway-sync");function xr(t,e){let r=ut(e),n=new Set((r?.favorites??[]).map(a=>JSON.stringify([a.backend,a.provider]))),o=B(t);o.favorites=[];for(let a of t){if(!st([a]))continue;let s=B([a]).favorites[0],l=JSON.stringify([s.backend,s.provider]);n.has(l)||(o.favorites.push(s),n.add(l))}let i=lt(o,e);return A(me.join(e,"models.json"),JSON.stringify(i,null,2)+`
9
- `),I.invalidate(),{defaultSet:!r?.default,favorites:i.favorites}}async function Io(t={}){try{let e=await(t.discover??wt)(t.backends);if(!e.some(n=>n.models.length>0))return{configured:!1,endpoints:0,defaultSet:!1,favorites:[],reason:"no-endpoints"};bt(e,t.gatewayConfigDir);let r=await _t.run(()=>xr(e,t.configDir??E));return pe.info(`Synced ${e.length} endpoint(s) \u2192 ${r.favorites.length} favorite model(s)`),{configured:!0,endpoints:e.length,...r}}catch(e){let r=e instanceof Error?e.message:String(e);return pe.warn(`Gateway sync skipped: ${r}`),{configured:!1,endpoints:0,defaultSet:!1,favorites:[],reason:r}}}import*as U from"node:path";var vr="@earendil-works/pi-coding-agent";function ct(t,e=null){return{available:!1,version:e,entry:null,error:t,runtime:null,readStoredCredential:null}}function Ar(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.ModelRuntime?.create=="function"&&typeof e.readStoredCredential=="function"}async function T(t={}){let e;try{e=await(t.importModule??At)()}catch{return ct("pi runtime import failed")}if(!Ar(e))return ct("pi runtime exports unavailable");let r=typeof e.VERSION=="string"?e.VERSION:null;try{let n=t.authPath??F(),o=U.join(U.dirname(n),"models.json"),i=await e.ModelRuntime.create({authPath:n,modelsPath:o,allowModelNetwork:!1});return{available:!0,version:r,entry:vr,error:null,runtime:i,readStoredCredential:e.readStoredCredential}}catch{return ct("pi runtime initialization failed",r)}}function Go(t,e,r){let n=t.accounts.find(o=>o.backend===e&&o.provider===r);return n?.capabilities.includes("oauth")?"oauth":n?.capabilities.includes("api_key")?"api_key":null}var wr=10080*60*1e3,br=new Set(["runtime","environment","fallback","models_json_key","models_json_command"]);function Er(t){return typeof t!="number"||!Number.isFinite(t)||Number.isNaN(new Date(t).getTime())?null:t}function Sr(t){let e=vt({claudeConfigDir:t});return e?{expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt}:null}function ye(t,e){let r=e.filter(n=>n!==null);return r.some(n=>n<=t)?"expired":r.some(n=>n-t<wr)?"expiring":"logged-in"}function xe(t){return t===null?null:new Date(t).toISOString()}function _r(t,e){let r=t.refreshExpiresAt??t.expiresAt;return{authType:"oauth",state:ye(e,[r]),source:"credentials.json",expiresAt:xe(r),refreshExpiresAt:null,manageable:!0}}function Pr(){return{authType:"oauth",state:"logged-in",source:"claude-cli",expiresAt:null,refreshExpiresAt:null,manageable:!0}}function kr(){return{authType:"oauth",state:"unknown",source:"legacy-env",expiresAt:null,refreshExpiresAt:null,manageable:!0,detail:"legacy_runtime_token"}}function Tr(){return{authType:"api_key",state:"logged-in",source:"env",expiresAt:null,refreshExpiresAt:null,manageable:!0}}function Rr(t,e,r,n,o){let i=[];return e&&i.push(Tr()),r?i.push(t?_r(t,o):Pr()):n&&i.push(kr()),i}function fe(t,e,r){return{backend:"claude",provider:"anthropic",label:"Anthropic",capabilities:["api_key","oauth"],authType:t.authType,state:t.state,source:t.source,expiresAt:t.expiresAt,refreshExpiresAt:t.refreshExpiresAt,inUse:r,credentials:e,...t.detail?{detail:t.detail}:{}}}function de(t,e,r){return{backend:"claude",provider:"anthropic",label:"Anthropic",capabilities:["api_key","oauth"],authType:null,state:t,source:null,expiresAt:null,refreshExpiresAt:null,inUse:r,credentials:e}}function Cr(t,e,r,n,o,i,a){let s=Rr(t,e,r===!0,n,i);if(o==="api"){let p=s.find(P=>P.authType==="api_key");return p?fe(p,s,a):de("logged-out",s,a)}let l=r===!0?s.find(p=>p.authType==="oauth"):void 0;return l?fe(l,s,a):de(r===null?"unknown":"logged-out",s,a)}function ve(t){let e=[];return typeof t.auth.apiKey?.login=="function"&&e.push("api_key"),typeof t.auth.oauth?.login=="function"&&e.push("oauth"),e}function he(t,e,r,n){return{backend:"pi",provider:t.id,label:t.name,capabilities:ve(t),authType:e.authType,state:e.state,source:e.source,expiresAt:e.expiresAt,refreshExpiresAt:null,inUse:n,credentials:r,...e.detail?{detail:e.detail}:{}}}function J(t,e,r,n=[]){return{backend:"pi",provider:t.id,label:t.name,capabilities:ve(t),authType:null,state:"unknown",source:e,expiresAt:null,refreshExpiresAt:null,inUse:r,credentials:n}}function Dr(t,e){let r=t.type==="oauth"?Er(t.expires):null;return{authType:t.type,state:t.type==="oauth"?ye(e,[r]):"logged-in",source:"stored",expiresAt:xe(r),refreshExpiresAt:null,manageable:!0}}function Fr(t){let e=t.source==="models_json_key";return{authType:"api_key",state:"logged-in",source:t.source??null,expiresAt:null,refreshExpiresAt:null,manageable:!1,...e?{detail:"models_json_key"}:{}}}function Nr(t,e){let r=[t];return e&&(e.authType!==t.authType||e.source!==t.source)&&r.push(e),r}function Ir(t,e,r,n){if(e.configured&&br.has(e.source)){let i=Fr(e);return he(t,i,Nr(i,r),n)}if(e.configured&&e.source==="stored"&&r)return he(t,r,[r],n);let o=r?[r]:[];return e.configured?J(t,e.source??null,n,o):{...J(t,e.source??null,n,o),state:"logged-out"}}function jr(t,e,r,n,o,i){let a;try{a=t.getProviderAuthStatus(r.id)}catch{return J(r,null,i)}try{let s=e(r.id,n),l=s?Dr(s,o):null;return Ir(r,a,l,i)}catch{return J(r,a.source??null,i)}}function ge(t,e){e.backend==="claude"&&(t.claude=!0),e.backend==="pi"&&e.provider&&t.pi.add(e.provider)}function pt(){return I.readIfPresent()?.default?Dt():null}function Or(){return pt()?.backend??null}function Mr(){return pt()?.mode??"plan"}function $r(t){let e={claude:!1,pi:new Set};try{for(let n of(t.listFavorites??kt)())ge(e,n)}catch{}let r=(t.getActiveBackend??Or)();if(r==="claude"&&(e.claude=!0),r!=="pi")return e;try{let n=(t.getDefaultSelection??pt)();n&&ge(e,n)}catch{}return e}function Lr(t){return{available:t.available,version:t.version,entry:t.entry,error:t.error}}function Wr(t,e,r,n,o){for(let i of e.runtime.getProviders())t.push(jr(e.runtime,e.readStoredCredential,i,r,n,o.has(i.id)))}async function Kr(t){try{return(await(t.readClaudeAuthStatus??Mt)()).loggedIn}catch{return null}}async function zo(t={}){let e=(t.now??(()=>new Date))(),r=t.piAuthPath??F(),n=$r(t),o={...(t.getSavedApiEnv??Tt)()},i=t.loadPiRuntime??T,[a,s]=await Promise.all([Kr(t),i({authPath:r})]),p=[Cr(Sr(t.claudeConfigDir),o.ANTHROPIC_API_KEY,a,o.CLAUDE_CODE_OAUTH_TOKEN,(t.getClaudeMode??Mr)(),e.getTime(),n.claude)];return s.available&&Wr(p,s,r,e.getTime(),n.pi),{generatedAt:e.toISOString(),accounts:p,piRuntime:Lr(s)}}var G=Fe(Ne(),1);import{existsSync as Vr,mkdirSync as Br,readFileSync as Ur,writeFileSync as Jr}from"fs";import*as Ae from"path";var Gr=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function we(t){return Ae.join(t,"config.yaml")}function be(t){if(!Vr(t))return{};try{let e=G.parse(Ur(t,"utf-8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function mt(t){return typeof t=="string"?t:""}function qo(t=Y){let e=be(we(t));return{enabled:e.uploadEnabled===!0,name:mt(e.name),org:mt(e.org),email:mt(e.email)}}function Zo(t){if(!t.enabled)return[];let e=[];return t.name?.trim()||e.push("name-required"),Gr.test(t.email?.trim()??"")||e.push("email-invalid"),e}function Qo(t,e=Y){let r=we(e);Br(e,{recursive:!0});let n=be(r),o=t.enabled?{name:t.name||"",org:t.org||"",email:t.email||""}:{name:n.name??"",org:n.org??"",email:n.email??""};Jr(r,G.stringify({...n,...o,uploadEnabled:t.enabled}))}async function Ee(t){let e=await t.prompt({type:"secret",message:u("ux.auth.apiKeyPrompt")});try{await Rt(e)}catch(r){let n=h(u("ux.auth.apiKeySaveFailed"),r);throw new f("claude_api_key_save_failed",n,r)}return j(),w({backend:"claude",provider:"anthropic"}),{provider:"anthropic",authType:"api_key",expiresAt:null}}var zr="Credential managed by Claude Code.";function Hr(t){if(t instanceof Ot){if(t.code==="claude_auth_cancelled")return new f("claude_subscription_cancelled",u("ux.auth.ccCancelled"));if(t.code==="claude_auth_timeout")return new f("claude_subscription_timeout",u("ux.auth.ccTimeout"))}let e=h(u("ux.auth.ccFailed"),t);return new f("claude_subscription_failed",e,t)}function Yr(t){return{signal:t.signal,async onAuthorization(e){return t.notify({type:"auth_url",url:e}),t.prompt({type:"manual_code",message:u("ux.auth.ccPasteCode")})},onCodeSubmitted(){t.notify({type:"progress",message:u("ux.auth.ccCompleting")})}}}async function Xr(t){try{await(t.removeLegacyToken??Ct)(),(t.reloadAuth??j)()}catch(e){throw new f("claude_subscription_cleanup_failed",h(u("ux.auth.ccCleanupFailed"),e),e)}}async function Se(t,e={}){try{await(e.login??$t)(Yr(t))}catch(r){throw Hr(r)}return await Xr(e),(e.publishRecovered??w)({backend:"claude",provider:"anthropic"}),{provider:"anthropic",authType:"oauth",expiresAt:null,detail:zr}}var qr=m("pi-login");function z(t,e,r,n){return{ok:!1,provider:t,authType:"api_key",error:n===void 0?{code:e,message:r}:{code:e,message:r,cause:n}}}async function Zr(t){try{return await(t.loadRuntime??T)()}catch(e){return qr.warn("PI runtime failed to load:",e),null}}function Qr(t){return typeof t.auth.apiKey?.login=="function"}function tn(t,e){return(e.refreshProviders??(()=>N.refresh()))(),w({backend:"pi",provider:t}),{ok:!0,provider:t,authType:"api_key",expiresAt:null}}function en(t,e){if(!t?.available){let o=h(u("ux.auth.piRuntimeUnavailable"),t?.error);return{failure:z(e,"runtime_unavailable",o)}}let r=t.runtime.getProviders().find(o=>o.id===e);if(!r)return{failure:z(e,"provider_not_found",u("ux.auth.piProviderNotFound"))};let n=r.name||e;if(!Qr(r)){let o=u("ux.auth.piApiKeyUnsupported",{provider:n});return{failure:z(e,"api_key_login_unsupported",o)}}return{runtime:t.runtime,label:n}}async function rn(t,e,r={}){let n=en(await Zr(r),t);if("failure"in n)return n.failure;try{await n.runtime.login(t,"api_key",e)}catch(o){let i=h(u("ux.auth.piApiKeyFailed",{provider:n.label}),o);return z(t,"login_failed",i,o)}return tn(t,r)}function _e(t,e={}){return async r=>{let n=await rn(t,r,e);if(n.ok===!1)throw new f(n.error.code,n.error.message,n.error.cause);return{provider:n.provider,authType:n.authType,expiresAt:n.expiresAt}}}import*as Pe from"node:path";var nn=Pe.join(Et,"device-id");function ke(t=nn){return yt(t)}var on=m("pi-oauth");function H(t,e,r,n){return{ok:!1,provider:t,authType:"oauth",error:n===void 0?{code:e,message:r}:{code:e,message:r,cause:n}}}function Te(t,e,r){let n=h(u("ux.auth.piOAuthFailed",{provider:e}),r);return H(t,"login_failed",n,r)}async function an(t){try{return await(t.loadRuntime??T)()}catch(e){return on.warn("PI runtime failed to load:",e),null}}function sn(t){return typeof t.auth?.oauth?.login=="function"}function un(t){if(t.type!=="oauth"||!Number.isFinite(t.expires))return null;let e=new Date(t.expires);return Number.isNaN(e.getTime())?null:e.toISOString()}function ln(t,e,r){return(r.refreshProviders??(()=>N.refresh()))(),w({backend:"pi",provider:t}),{ok:!0,provider:t,authType:"oauth",expiresAt:e}}function cn(t,e){if(!t?.available){let o=h(u("ux.auth.piRuntimeUnavailable"),t?.error);return{failure:H(e,"runtime_unavailable",o)}}let r=t.runtime.getProviders().find(o=>o.id===e);if(!r)return{failure:H(e,"provider_not_found",u("ux.auth.piProviderNotFound"))};let n=r.name||e;if(!sn(r)){let o=u("ux.auth.piOAuthUnsupported",{provider:n});return{failure:H(e,"oauth_unsupported",o)}}return{runtime:t.runtime,label:n}}async function pn(t,e,r={}){let n;try{n=cn(await an(r),t)}catch(o){return Te(t,t,o)}if("failure"in n)return n.failure;try{let o=r.getDeviceId??(()=>ke()),i=await n.runtime.login(t,"oauth",e,{getDeviceId:o});return ln(t,un(i),r)}catch(o){return Te(t,n.label,o)}}function Re(t,e={}){return async r=>{let n=await pn(t,r,e);if(n.ok===!1)throw new f(n.error.code,n.error.message,n.error.cause);return{provider:n.provider,authType:n.authType,expiresAt:n.expiresAt}}}var Ce=new WeakMap;function De(t){let e=Ce.get(t);if(e)return e;let r=new Map;return Ce.set(t,r),r}function ji(t,e,r){De(t).set(e,r)}function Oi(t,e,r){let n=r??De(t).get(e);if(!n)return{kind:"unbound"};let o=t.getState(n);return o?{kind:"state",state:o}:{kind:"expired"}}function Mi(t){if(t.kind!=="state")return null;let{step:e}=t.state;return e==="failed"||e==="cancelled"?null:t.state}function mn(t,e){if(t.provider!=="anthropic")throw new f("provider_not_found","Claude provider must be anthropic.");return t.authType==="oauth"?e.claudeOAuthConsumer??Se:e.claudeConsumer??Ee}function fn(t,e){if(!t.provider.trim())throw new f("provider_not_found","A provider is required.");return(t.authType==="oauth"?e.piOAuthConsumerFactory??Re:e.piConsumerFactory??_e)(t.provider)}function dn(t,e){return t.backend==="claude"?mn(t,e):fn(t,e)}function hn(t={}){return{async start(e){return(t.startFlow??Ft)(e,dn(e,t))},getState:e=>(t.getFlowState??jt)(e),respond:(e,r,n)=>(t.respondPrompt??Nt)(e,r,n),cancel:e=>(t.cancelFlow??It)(e)}}var $i=hn();export{Lt as a,R as b,yn as c,Wt as d,Ut as e,M as f,$n as g,Xt as h,Zt as i,Ln as j,Wn as k,Kn as l,zn as m,te as n,ot as o,it as p,to as q,oe as r,lo as s,co as t,_o as u,st as v,ut as w,Po as x,Io as y,vr as z,T as A,Go as B,zo as C,ji as D,Oi as E,Mi as F,$i as G,qo as H,Zo as I,Qo as J};
@@ -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{e as i}from"./chunk-NAA7GF6Q.js";import*as s from"node:os";import*as o from"node:path";var t=i("pi-sdk");var l="./core/model-resolver.js",a;function p(){return a??=import("./dist-PUKMZ7GW.js"),a}function u(e){return typeof e=="object"&&e!==null&&Object.values(e).every(r=>typeof r=="string")}async function f(e){try{let r=e??"file:///unused-bundled-entry.js",n=e?await import(new URL(l,r).href):await import("./model-resolver-N3DTAQ2S.js");if(u(n.defaultModelPerProvider))return n.defaultModelPerProvider;t.warn("PI default model table has an unexpected shape; using PI model order")}catch(r){t.warn(`PI default model table unavailable; using PI model order: ${r.message}`)}return{}}function m(){let e=Date.now();p().then(()=>t.info(`PI SDK preloaded in ${Date.now()-e}ms`)).catch(r=>t.warn(`PI SDK preload failed; the first PI session will surface the error: ${r.message}`))}function d(){return o.join(s.homedir(),".pi","agent")}function P(){return o.join(d(),"auth.json")}function h(){return o.join(d(),"models.json")}export{p as a,f as b,m as c,d,P as e,h as f};