@cortex-agent/server 2026.10.28 → 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 +36 -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-BPXakv_3.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-WCm6wwmM.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-BHZpFXhc.js +0 -525
  256. package/web/dist/assets/index-DqWMdMkh.css +0 -1
  257. package/web/dist/assets/pdf-worker-Hp15W1QJ.js +0 -57
  258. package/web/dist/assets/pdf.worker.min-DnhTvCwe.js +0 -55
@@ -1,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{a as O}from"./chunk-JERCOLY3.js";import{b as p}from"./chunk-OE4KH3NJ.js";import{b as d}from"./chunk-5M4PFLRW.js";import{e as u}from"./chunk-NAA7GF6Q.js";import{d as l,l as f}from"./chunk-J5DVLUKY.js";import{e as S}from"./chunk-WHC7AYZD.js";var y=S(O(),1);import{copyFileSync as L,existsSync as C,mkdirSync as T,readdirSync as F,readFileSync as a,renameSync as P,constants as k}from"node:fs";import*as i from"node:path";var _={bash:"Bash",read:"Read",write:"Write",edit:"Edit",grep:"Grep",glob:"Glob",web_fetch:"WebFetch",web_search:"WebSearch",ask_user_question:"AskUserQuestion",enter_plan_mode:"EnterPlanMode",exit_plan_mode:"ExitPlanMode",todo_write:"TodoWrite",skill:"Skill",agent:"Agent"},h={bash:"bash",read:"read",write:"write",edit:"edit",grep:"grep",glob:"glob",web_fetch:"web_fetch",web_search:"web_search",todo_write:"todo_write",skill:"skill"},A={claude:_,pi:h},x={claude:m(_),pi:m(h)};function m(t){let e=new Map;for(let[n,o]of Object.entries(t))o&&e.set(o,n);return e}function U(t,e){return e.startsWith("mcp__")?e:x[t].get(e)??null}function g(t,e){return e.startsWith("mcp__")?e:A[t][e]??null}var b=u("agent-roles"),w=i.join(f,"agents"),R=i.join(l,"agents"),j="mcp__cortex-core__",B=new Set(Object.values(p).flat());function I(t){let n=(Array.isArray(t)?t.filter(o=>typeof o=="string"):typeof t=="string"?t.split(","):[]).map(o=>o.trim()).filter(Boolean);return n.length>0?n:void 0}function M(t){return t==="claude"||t==="pi"?t:void 0}function E(t){return typeof t=="string"&&t.trim()?t.trim():void 0}function W(t){let e=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)([\s\S]*)$/.exec(t);if(!e)return null;let n=(0,y.parse)(e[1]);return!n||typeof n.name!="string"||typeof n.description!="string"?null:{name:n.name,description:n.description,tools:I(n.tools),model:E(n.model),backend:M(n.backend),mode:E(n.mode),systemPrompt:e[2].trim()}}function D(t){try{return W(a(t,"utf8"))}catch{return null}}function Q(t=w,e=R){let n=new Map,o=d(e,t,".md"),r=[...o.filter(s=>s.origin==="builtin"),...o.filter(s=>s.origin!=="builtin")];for(let s of r){let c=D(s.path);c&&n.set(c.name,c)}return[...n.values()]}function H(t,e){let n=t.find(r=>r.name===e);if(n)return n;let o=t.map(r=>r.name).sort().join(", ")||"none";throw new Error(`Unknown subagent_type "${e}". Available roles: ${o}.`)}function J(t,e){if(!t.tools)return;let n=[];for(let o of t.tools){if(o.startsWith("mcp__")){n.push(o);continue}let r=g(e,o);if(r){n.push(r);continue}if(B.has(o)){n.push(e==="claude"?j+o:o);continue}e!=="claude"&&n.push(o)}return[...new Set(n)]}function Z(t={}){let e=t.rolesDir??w,n=t.defaultsDir??R;!t.legacyDir||C(e)||$(t.legacyDir,e,n)}function $(t,e,n){let o;try{o=F(t).filter(r=>r.endsWith(".md"))}catch{return}if(o.length){T(e,{recursive:!0});for(let r of o)N(i.join(t,r),i.join(n,r))||G(i.join(t,r),i.join(e,r));b.info(`Adopted ${o.length} role file(s) from ${t}`);try{P(t,`${t}.migrated`)}catch(r){b.warn(`Could not retire ${t}: ${r.message}`)}}}function N(t,e){try{return a(t,"utf8")===a(e,"utf8")}catch{return!1}}function G(t,e){try{L(t,e,k.COPYFILE_EXCL)}catch(n){let o=n.code;if(o==="EEXIST"||o==="ENOENT")return;throw n}}export{U as a,g as b,Q as c,H as d,J as e,Z as f};
@@ -1,6 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{c as A}from"./chunk-STUHNKQS.js";import{a as N}from"./chunk-Q4UGYGU5.js";import{c as g}from"./chunk-W5LGYSPZ.js";import{e as P}from"./chunk-NAA7GF6Q.js";import{l as C}from"./chunk-J5DVLUKY.js";import{readFileSync as ie}from"node:fs";import se from"node:path";var I=Math.floor(Number.MAX_SAFE_INTEGER/864e5);function L(e){return Number.isInteger(e)?e<1e3?"must be at least 1000 milliseconds":e>2147483647?"must be at most 2147483647 milliseconds":null:"must be an integer number of milliseconds"}var M=1024,$=131072;function te(e){return Number.isInteger(e)?e<M?`must be at least ${M} tokens`:e>$?`must be at most ${$} tokens`:null:"must be a whole number of tokens"}var j=1e5,x=1e6;function ne(e){return e===null?null:Number.isInteger(e)?e<j||e>x?`must be between ${j} and ${x} tokens`:null:"must be a whole number of tokens"}function re(e){return Number.isSafeInteger(e)?e<1?"must be at least 1 day":e>I?`must be at most ${I} days`:null:"must be a safe integer number of days"}var V=24;function oe(e){return Number.isFinite(e)?e<0||e>V?`must be between 0 and ${V} hours`:null:"must be a number of hours"}var d={turnNotify:{envVar:"CORTEX_TURN_NOTIFY",type:"boolean",default:!0,legacyParse:e=>!["0","false","off","no"].includes(e.trim().toLowerCase())},turnNotifyThresholdS:{envVar:"CORTEX_TURN_NOTIFY_THRESHOLD_S",type:"number",default:60,legacyParse:e=>{let t=Number(e.trim());return Number.isFinite(t)&&t>0?t:60}},notifyCompaction:{envVar:"CORTEX_NOTIFY_COMPACTION",type:"boolean",default:!0,legacyParse:e=>!["0","false","off","no"].includes(e.trim().toLowerCase())},showToolCalls:{envVar:"CORTEX_SHOW_TOOL_CALLS",type:"boolean",default:!1,legacyParse:e=>["1","true","yes","on"].includes(e.trim().toLowerCase())},statusNewqButton:{envVar:"CORTEX_STATUS_NEWQ_BUTTON",type:"boolean",default:!1,legacyParse:e=>["1","true","on","yes"].includes(e.trim().toLowerCase())},autoResume:{envVar:"CORTEX_AUTO_RESUME",type:"boolean",default:!0,legacyParse:e=>e!=="0"&&e!=="false"},showThinking:{envVar:"CORTEX_SHOW_THINKING",type:"boolean",default:!0,legacyParse:e=>!["0","false","off","no"].includes(e.trim().toLowerCase())},streamDeltas:{envVar:"CORTEX_STREAM_DELTAS",type:"boolean",default:!0,legacyParse:e=>e!=="0"},bgContinuation:{envVar:"CORTEX_BG_CONTINUATION",type:"boolean",default:!0,legacyParse:e=>!["0","false","off","no"].includes(e.trim().toLowerCase())},eventLog:{envVar:"CORTEX_EVENT_LOG",type:"boolean",default:!0,legacyParse:e=>e!=="off"},diskMonitor:{envVar:"CORTEX_DISK_MONITOR",type:"boolean",default:!0,legacyParse:e=>!["0","false","off","no"].includes(e.trim().toLowerCase())},disableUserContext:{envVar:"CORTEX_DISABLE_USER_CONTEXT",type:"boolean",default:!1,legacyParse:e=>e==="1"},serverUpdateDisable:{envVar:"CORTEX_SERVER_UPDATE_DISABLE",type:"boolean",default:!1,legacyParse:e=>e==="1"},serverAutoUpdate:{type:"boolean",default:!0},clientHotReloadEnabled:{type:"boolean",default:!0},feishuSkillsInWeb:{type:"boolean",default:!1},teamEnabled:{envVar:"CORTEX_TEAM_ENABLED",type:"boolean",default:!0,legacyParse:e=>e==="1"},telemetryEnabled:{type:"boolean",default:!0},waitpointSweepMs:{envVar:"CORTEX_WAITPOINT_SWEEP_MS",type:"number",default:3e4,legacyParse:e=>{let t=Number.parseInt(e||"",10);return Number.isFinite(t)?t:3e4}},waitpointTtlMs:{envVar:"CORTEX_WAITPOINT_TTL_MS",type:"number",default:10080*60*1e3,legacyParse:e=>{let t=Number.parseInt(e||"",10);return Number.isFinite(t)&&t>0?t:10080*60*1e3}},waitpointMaxWakesPerHour:{envVar:"CORTEX_WAITPOINT_MAX_WAKES_PER_HOUR",type:"number",default:12,legacyParse:e=>{let t=Number.parseInt(e||"",10);return Number.isFinite(t)&&t>0?t:12}},injectWaitMaxS:{envVar:"CORTEX_INJECT_WAIT_MAX_S",type:"number",default:600,legacyParse:e=>Number(e)},anthropicSubscriptionModes:{type:"string[]",default:["plan"]},subscriptionBillingModes:{type:"string[]",default:["plan","openai-codex","google-gemini-cli","google-antigravity"]},providerUsageCollectionEnabled:{type:"boolean",default:!0},providerUsageCollectionIntervalMs:{type:"number",default:300*1e3,validate:L},claudeWindowWarmupEnabled:{type:"boolean",default:!1},providerRateLimits:{type:"provider-rate-limits",default:{}},storeArchiveEnabled:{type:"boolean",default:!0},memoryIndexRegenEnabled:{type:"boolean",default:!0},memoryIndexRegenIntervalMs:{type:"number",default:1440*60*1e3,validate:L},sessionRetentionDays:{type:"number",default:90,validate:re},piCompactReserveTokens:{envVar:"CORTEX_PI_COMPACT_RESERVE_TOKENS",type:"number",default:16384,legacyParse:e=>{let t=Number.parseInt(e.trim(),10);return Number.isFinite(t)?t:16384},validate:te},maxContextTokens:{type:"number|null",default:null,validate:ne},cacheKeepWarmHours:{type:"number",default:6,validate:oe},coldResumeClearToolResults:{type:"boolean",default:!0},uiCorsOrigins:{envVar:"CORTEX_UI_CORS_ORIGINS",type:"string[]",default:[],legacyParse:e=>e.split(",").map(t=>t.trim()).filter(Boolean)},adminChannel:{envVar:["SLACK_ADMIN_CHANNEL","CORTEX_ADMIN_CHANNEL"],type:"string|null",default:null,legacyParse:e=>e||null},feishuAdminChannel:{envVar:"FEISHU_ADMIN_CHANNEL",type:"string|null",default:null,legacyParse:e=>e||null}};var l=P("settings"),p=se.join(C,"settings.json"),E=Object.keys(d),ae=new Set(["adminChannel","feishuAdminChannel"]),_=new Set,X=new Set,F=new N,le=new Set(["__proto__","prototype","constructor"]),W=120,k=!1,S={},w=null,U=null,ue=null,m=null,f=!1,de={boolean:e=>typeof e=="boolean",number:e=>typeof e=="number"&&Number.isFinite(e),"number|null":e=>e===null||typeof e=="number"&&Number.isFinite(e),"string[]":e=>Array.isArray(e)&&e.every(t=>typeof t=="string"),"string|null":e=>e===null||typeof e=="string","provider-rate-limits":u};function u(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function H(e){let t=e.trim();return t.length===0?"provider keys must not be empty":t!==e?"provider keys must not have leading or trailing whitespace":t.length>W?`provider keys must be at most ${W} characters`:le.has(t)?`provider key "${t}" is reserved`:null}function K(e){return typeof e!="number"||!Number.isFinite(e)?"threshold must be a finite number":e<=0?"threshold must be greater than 0":e>1?"threshold must be at most 1":null}function T(e,t){if(typeof e!="string")return`${t} must be a string`;let n=e.trim();return n.length===0?`${t} must not be empty`:n!==e?`${t} must not have leading or trailing whitespace`:null}function G(e,t){if(!Object.hasOwn(e,"threshold"))return null;if(typeof e.enabled!="boolean")return`${t}.enabled must be a boolean`;let n=K(e.threshold);return n?`${t}.${n}`:null}function fe(e,t){if(!u(e))return`${t} must be a plain object`;for(let r of Object.keys(e))if(!(r==="type"||r==="label"||r==="enabled"||r==="threshold"))return`${t} has unknown field "${r}"`;let n=T(e.type,"type");if(n)return`${t}.${n}`;if(Object.hasOwn(e,"label")){let r=T(e.label,"label");if(r)return`${t}.${r}`}return typeof e.enabled!="boolean"?`${t}.enabled must be a boolean`:G(e,t)}function ce(e,t){return`${e}\0${t??""}`}function be(e,t){if(!Array.isArray(e))return`providerRateLimits.${t}.windows must be an array`;let n=new Set;for(let[r,o]of e.entries()){let i=`providerRateLimits.${t}.windows.${r}`,s=fe(o,i);if(s)return s;let a=ce(o.type,o.label);if(n.has(a))return`${i} duplicates an existing window identity`;n.add(a)}return null}function me(e,t){if(!u(e))return`providerRateLimits.${t} must be a plain object`;for(let r of Object.keys(e))if(!(r==="enabled"||r==="threshold"||r==="windows"))return`providerRateLimits.${t} has unknown field "${r}"`;if(Object.hasOwn(e,"enabled")&&typeof e.enabled!="boolean")return`providerRateLimits.${t}.enabled must be a boolean`;let n=G(e,`providerRateLimits.${t}`);return n||(Object.hasOwn(e,"windows")?be(e.windows,t):typeof e.enabled=="boolean"?null:`providerRateLimits.${t} must declare enabled or windows`)}function Y(e){if(!u(e))return"must be a plain object";for(let[t,n]of Object.entries(e)){let r=H(t);if(r)return r;let o=me(n,t);if(o)return o}return null}function B(e,t){let n=T(e,t);if(n)throw new TypeError(n);return e.trim()}function ye(e){if(e!=null)return B(e,"label")}function pe(e){let t=e.provider.trim(),n=H(t);if(n)throw new TypeError(n);if(typeof e.enabled!="boolean")throw new TypeError("enabled must be a boolean");if(e.threshold!==null){let i=K(e.threshold);if(i)throw new TypeError(i)}let r=e.windowType===void 0?void 0:B(e.windowType,"type"),o=ye(e.windowLabel);if(o&&!r)throw new TypeError("windowLabel requires windowType");return{provider:t,enabled:e.enabled,threshold:e.threshold,...r?{windowType:r}:{},...o?{windowLabel:o}:{}}}function Ee(e){return{type:e.type,...e.label?{label:e.label}:{},enabled:e.enabled,...Object.hasOwn(e,"threshold")?{threshold:e.threshold}:{}}}function v(e){return{...typeof e.enabled=="boolean"?{enabled:e.enabled}:{},...Object.hasOwn(e,"threshold")?{threshold:e.threshold}:{},...e.windows?{windows:e.windows.map(Ee)}:{}}}function z(e){let t=Y(e);if(t)throw new TypeError(t);return Object.fromEntries(Object.entries(e).map(([n,r])=>[n,v(r)]))}function he(e){return Object.hasOwn(e,"providerRateLimits")?z(e.providerRateLimits):{}}function J(e){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("settings.json must contain a JSON object");for(let t of E){if(!Object.hasOwn(e,t))continue;let n=d[t];if(!de[n.type](e[t]))throw new TypeError(`settings.json key "${t}" must have type ${n.type}`);if(n.type==="provider-rate-limits"){let o=Y(e[t]);if(o)throw new TypeError(`settings.json key "${t}" ${o}`);continue}let r=n.validate?.(e[t]);if(r)throw new TypeError(`settings.json key "${t}" ${r}`)}}function h(){try{let e=JSON.parse(ie(p,"utf8"));return J(e),e}catch(e){if(e?.code==="ENOENT")return{};throw e}}function We(){h()}function ge(e,t){X.has(t)||(X.add(t),l.warn(`Deprecated env ${t} supplies settings.${e}; move it to settings.json`))}function _e(e,t){return e!=="providerRateLimits"?t[e]:z(t[e])}function q(e,t,n,r){let o=d[e];if(Object.hasOwn(t,e))return{key:e,value:_e(e,t),source:"file"};let i=o.envVar===void 0?[]:typeof o.envVar=="string"?[o.envVar]:o.envVar;for(let s of i){let a=n[s];if(!(a===void 0||ae.has(e)&&a.length===0))return r&&ge(e,s),{key:e,value:o.legacyParse(a),source:"env"}}return{key:e,value:o.default,source:"default"}}function R(e,t=process.env){return J(e),E.map(n=>q(n,e,t,!1))}function O(e){return Object.fromEntries(E.map(t=>{let n=q(t,e,process.env,!0);return[t,n.value]}))}function y(e,t){if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((n,r)=>y(n,t[r]));if(u(e)&&u(t)){let n=Object.keys(e).sort(),r=Object.keys(t).sort();return n.length===r.length&&n.every((o,i)=>o===r[i]&&y(e[o],t[o]))}return Object.is(e,t)}function we(e,t){return E.filter(n=>!y(e[n],t[n]))}function Te(e,t){let n=we(e,t);if(n.length!==0)for(let r of _)try{r(n)}catch(o){l.error("Settings change callback failed:",o)}}function Q(e){return Object.fromEntries(e.map(t=>[t.key,t.value]))}function Oe(e,t){return R(e).map(n=>({key:n.key,value:t[n.key],source:n.source}))}function c(e,t,n=Oe(e,t)){let r=w;S=e,w=t,U=n,r&&Te(r,t)}function Z(){m&&clearTimeout(m),m=setTimeout(()=>{m=null,Se()},300)}function Se(){if(f)return Z();try{let e=h();if(y(S,e))return;c(e,O(e)),l.info("Hot-reload: settings.json reloaded")}catch(e){l.error(`Hot-reload settings.json failed: ${e.message} \u2014 keeping previous settings`)}}function ve(){ue=A({label:"settings.json",filePath:p,onChange:Z,warn:e=>l.error(e),unref:!0})}function b(){if(!k){k=!0,ve();try{let e=h();c(e,O(e))}catch(e){l.error(`Load settings.json failed: ${e.message} \u2014 using env/default settings`),c({},O({}))}}}function ke(){return b(),w}function De(){return b(),U}function Fe(e){return b(),_.add(e),()=>_.delete(e)}function ee(){try{return h()}catch(e){return l.error(`Update settings.json read failed: ${e.message} \u2014 using previous settings`),S}}function Re(e,t){return e.type===t.windowType&&e.label===t.windowLabel}function Ne(e){return{type:e.windowType,...e.windowLabel?{label:e.windowLabel}:{},enabled:e.enabled,...e.threshold!==null?{threshold:e.threshold}:{}}}function D(e){let t=v(e);return t.windows?.length||delete t.windows,t.enabled===void 0&&t.threshold===void 0&&!t.windows?null:t}function Ce(e){return e.enabled===!1||e.threshold!==void 0}function Pe(e,t){let n=v(e??{});if(!t.windowType)return delete n.enabled,delete n.threshold,(!t.enabled||t.threshold!==null)&&(n.enabled=t.enabled),t.threshold!==null&&(n.threshold=t.threshold),D(n);let r=n.windows?.filter(i=>!Re(i,t))??[],o=t.enabled&&t.threshold===null&&Ce(n);return(!t.enabled||t.threshold!==null||o)&&r.push(Ne(t)),n.windows=r,D(n)}async function Ue(e){b();let t={...process.env};await F.run(async()=>{let n={...ee(),...e},r=R(n,t),o=Q(r);f=!0;try{await g(p,`${JSON.stringify(n,null,2)}
5
- `),c(n,o,r)}finally{f=!1}})}async function He(e){b();let t={...process.env},n=pe(e);return F.run(async()=>{let r={...ee()},o=he(r),i=Pe(o[n.provider],n);i?o[n.provider]=i:delete o[n.provider],r.providerRateLimits=o;let s=R(r,t),a=Q(s);f=!0;try{await g(p,`${JSON.stringify(r,null,2)}
6
- `),c(r,a,s)}finally{f=!1}return n})}export{d as a,J as b,We as c,ke as d,De as e,Fe as f,Ue as g,He as h};
@@ -1,28 +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 h}from"./chunk-NKXV32S6.js";import{g as Y}from"./chunk-O3JW2F7D.js";import{A as R,B as I,r as Z,y as O,z as x}from"./chunk-TZFLHVOQ.js";import{a as k}from"./chunk-YG7OEPR2.js";import{c as K,d as w,e as B,f as W,g as J,h as V}from"./chunk-YHIWOGVL.js";import{a as Q}from"./chunk-AAA3UBIS.js";import{e as u}from"./chunk-E7ZMYIY6.js";import{e as S}from"./chunk-NAA7GF6Q.js";import{e as X}from"./chunk-QWAQHHRS.js";import{c as G}from"./chunk-J5DVLUKY.js";import{copyFileSync as ke,existsSync as M,mkdirSync as Oe,readFileSync as Re,renameSync as Ie,unlinkSync as Me,writeFileSync as Ue}from"fs";import*as q from"path";var ee=S("pi-custom-providers");function te(e){if(!M(e))return{};try{let t=JSON.parse(Re(e,"utf8"));return!t||typeof t!="object"||Array.isArray(t)?{}:t}catch(t){return ee.warn(`Unreadable PI models.json at ${e}: ${t.message}`),{}}}function re(e){let t=e.providers;return!t||typeof t!="object"||Array.isArray(t)?{}:t}function ne(e,t){if(Oe(q.dirname(e),{recursive:!0}),M(e))try{ke(e,`${e}.bak`)}catch(n){ee.warn(`Failed to back up ${e}: ${n.message}`)}let r=`${e}.tmp.${process.pid}.${Date.now()}`;try{Ue(r,`${JSON.stringify(t,null,2)}
5
- `,"utf8"),Ie(r,e)}catch(n){try{M(r)&&Me(r)}catch{}throw n}}function oe(e,t,r){let n=te(e),o={...re(n)};o[t]=r,ne(e,{...n,providers:o})}function ie(e,t){let r=te(e),n={...re(r)};return t in n?(delete n[t],ne(e,{...r,providers:n}),!0):!1}var P=S("pi-custom-providers");function He(){return{modelsPath:k,gatewayPath:O,gatewayUrl:Y,onChanged:()=>Z.refresh()}}function U(e){let t=e?.keys;return Array.isArray(t)?t.filter(r=>typeof r=="string"&&r.length>0):[]}function H(e,t,r){let n={name:e,api:t.api,models:V(t),upstreamUrl:typeof r?.base_url=="string"?r.base_url:null,hasApiKey:U(r).length>0,routed:r!==null};return t.headers&&typeof t.headers=="object"&&(n.headers=t.headers),t.compat&&typeof t.compat=="object"&&(n.compat=t.compat),n}function se(e,t,r){let n=w(r.api,t);return x(e.gatewayPath,n,t)}function je(e){let t=h(e.modelsPath);return Object.entries(t).map(([r,n])=>H(r,n,se(e,r,n)))}function Fe(e,t){let r=h(e.modelsPath)[t];return r?H(t,r,se(e,t,r)):null}function Ne(e,t){let r=W(t),n=B(r);if(n.length>0)return{ok:!1,errors:n};let{name:o}=r,i=w(r.api,o),s=x(e.gatewayPath,i,o),l=t.apiKey===void 0?U(s):[t.apiKey].filter(Boolean);try{R(e.gatewayPath,{endpoint:i,mode:o,base_url:r.upstreamUrl,auth_style:K(r.api),keys:l,passthrough:l.length===0})}catch(b){return P.warn(`Failed to write the gateway route for '${o}': ${b.message}`),{ok:!1,errors:["write-failed"]}}let y=ze(e,r);try{oe(e.modelsPath,o,y)}catch(b){return P.warn(`Failed to write the PI catalog entry for '${o}': ${b.message}`),De(e,i,o,s),{ok:!1,errors:["write-failed"]}}return e.onChanged?.(),{ok:!0,provider:H(o,y,x(e.gatewayPath,i,o))}}function De(e,t,r,n){try{if(!n){I(e.gatewayPath,t,r);return}R(e.gatewayPath,{endpoint:t,mode:r,base_url:String(n.base_url??""),auth_style:String(n.auth_style??"bearer"),keys:U(n),passthrough:n.passthrough===!0})}catch(o){P.warn(`Failed to roll the gateway route for '${r}' back: ${o.message}`)}}function Le(e,t){let r=h(e.modelsPath)[t];if(!r)return{ok:!1,errors:["not-found"]};try{ie(e.modelsPath,t),I(e.gatewayPath,w(r.api,t),t)}catch(n){return P.warn(`Failed to remove custom provider '${t}': ${n.message}`),{ok:!1,errors:["write-failed"]}}return e.onChanged?.(),{ok:!0}}function ze(e,t){let r=h(e.modelsPath)[t.name]??{},n={...r,...J(t,e.gatewayUrl)},o=Array.isArray(r.models)?r.models:[],i=new Map(o.map(s=>[s.id,s]));return n.models=n.models.map(s=>({...i.get(s.id),...s})),t.headers!==void 0&&(n.headers=t.headers),t.compat!==void 0&&(n.compat=t.compat),n}import*as D from"fs";import*as Ee from"os";import*as A from"path";var p=e=>e.before!==e.after;import*as v from"fs";import*as $ from"path";var Ge="# >>> cortex >>>",Ke="# <<< cortex <<<",j=/# >>> cortex >>>\n[\s\S]*?\n# <<< cortex <<<\n?/,Be=e=>`'${e.replace(/'/g,"'\\''")}'`;function We(e){let t=Be(e);return`${Ge}
6
- case ":\${PATH}:" in *:${t}:*) ;; *) PATH=${t}:"$PATH"; export PATH ;; esac
7
- ${Ke}
8
- `}function Je(e,t,r){return j.test(e)?e.replace(j,()=>t):e?r==="top"?`${t}
9
- ${e}`:`${e}${e.endsWith(`
10
- `)?"":`
11
- `}
12
- ${t}`:t}function Ve(e){let t=j.exec(e);if(!t)return e;let r=e.slice(0,t.index),n=e.slice(t.index+t[0].length);return r===""?n.replace(/^\n/,""):(r.endsWith(`
13
-
14
- `)?r.slice(0,-1):r)+n}function Xe(e){let t=i=>$.join(e.home,i),r=[{file:t(".profile"),position:"bottom"}];e.exists(t(".bashrc"))&&r.push({file:t(".bashrc"),position:"top"}),e.exists(t(".bash_profile"))&&r.push({file:t(".bash_profile"),position:"bottom"});let n=e.zdotdir||e.home;return(e.platform==="darwin"||e.hasZsh||e.exists($.join(n,".zshrc")))&&r.push({file:$.join(n,".zshenv"),position:"bottom"}),r}function Ze(e){try{return v.readFileSync(e,"utf8")}catch{return null}}function Ye(e,t,r,n){let o=Ze(e);return n==="remove"?{target:e,before:o,after:o===null?null:Ve(o)}:{target:e,before:o,after:Je(o??"",We(r),t)}}function ae(e){return{plan:(t,r)=>Xe(e).map(({file:n,position:o})=>Ye(n,o,t,r)),apply:t=>{for(let r of t.filter(p))r.after!==null&&v.writeFileSync(r.target,r.after)}}}import{spawnSync as Qe}from"child_process";import*as ce from"path";var qe="HKCU\\Environment\\Path",ue=e=>ce.win32.normalize(e.trim()).replace(/\\+$/,"").toLowerCase(),le=(e,t)=>e.trim()!==""&&ue(e)===ue(t);function et(e,t){return e?e.split(";").some(r=>le(r,t))?e:`${t};${e}`:t}function tt(e,t){if(e===null)return null;let r=e.split(";"),n=r.filter(o=>!le(o,t));return n.length===r.length?e:n.join(";")}var rt=`
15
- [Console]::OutputEncoding = [Text.Encoding]::UTF8
16
- $k = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment')
17
- if ($k -and ($k.GetValueNames() -contains 'Path')) { [Console]::Out.Write('=' + $k.GetValue('Path', '', 'DoNotExpandEnvironmentNames')) }`,nt=`
18
- $k = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Environment')
19
- $kind = [Microsoft.Win32.RegistryValueKind]::ExpandString
20
- if ($k.GetValueNames() -contains 'Path') { $kind = $k.GetValueKind('Path') }
21
- if ($env:CORTEX_USER_PATH) { $k.SetValue('Path', $env:CORTEX_USER_PATH, $kind) } else { $k.DeleteValue('Path', $false) }
22
- Add-Type -Namespace CortexEnv -Name Native -MemberDefinition '[DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern IntPtr SendMessageTimeout(IntPtr h, uint m, UIntPtr w, string l, uint f, uint t, out UIntPtr r);'
23
- $r = [UIntPtr]::Zero
24
- [void][CortexEnv.Native]::SendMessageTimeout([IntPtr]0xffff, 0x1A, [UIntPtr]::Zero, 'Environment', 2, 5000, [ref]$r)`;function fe(e,t={}){let r=Qe("powershell.exe",["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",e],{encoding:"utf8",windowsHide:!0,env:{...process.env,...t}});if(r.status!==0)throw new Error(`powershell failed: ${(r.stderr||String(r.error??"")).trim()}`);return r.stdout}function ot(){let e=fe(rt);return e.startsWith("=")?e.slice(1):null}function it(e){fe(nt,{CORTEX_USER_PATH:e??""})}function me(e={read:ot,write:it}){return{plan:(t,r)=>{let n=e.read(),o=r==="add"?et(n,t):tt(n,t);return[{target:qe,before:n,after:o}]},apply:t=>{for(let r of t.filter(p))e.write(r.after)}}}import*as a from"fs";import*as c from"path";var de="cortex-managed-shim",he=`${de}: written by \`cortex path install\`, refreshed when the daemon starts.`;function g(e){return c.join(e,"runtime","bin")}function ge(e){let t=JSON.parse(a.readFileSync(c.join(e,"package.json"),"utf8"));return Object.entries(t.bin??{}).map(([r,n])=>({name:r,entry:c.join(e,n)}))}var C=e=>`'${e.replace(/'/g,"'\\''")}'`;function pe(e,t,r,n){return["#!/bin/sh",`# ${he}`,`if [ -z "\${CORTEX_HOME:-}" ]; then CORTEX_HOME=${C(r)}; fi`,"export CORTEX_HOME",`PATH=${C(n)}:"$PATH"; export PATH`,`exec ${C(e)} ${C(t)} "$@"`,""].join(`
25
- `)}function st(e,t,r){let n=o=>o.replace(/%/g,"%%");return["@echo off",`rem ${he}`,"setlocal",`if not defined CORTEX_HOME set "CORTEX_HOME=${n(r)}"`,`set "PATH=${n(c.win32.dirname(e))};%PATH%"`,`"${n(e)}" "${n(t)}" %*`,""].join(`\r
26
- `)}var E=e=>e.replace(/\\/g,"/"),at=e=>E(e).replace(/^([A-Za-z]):/,(t,r)=>`/${r.toLowerCase()}`);function ye(e,t=process.platform){if(t!=="win32"){let r=c.posix.dirname(e.node);return e.bins.map(({name:n,entry:o})=>({file:n,content:pe(e.node,o,e.home,r)}))}return e.bins.flatMap(({name:r,entry:n})=>[{file:`${r}.cmd`,content:st(e.node,n,e.home)},{file:r,content:pe(E(e.node),E(n),E(e.home),at(c.win32.dirname(e.node)))}])}function Se(e){try{return a.readFileSync(e,"utf8")}catch{return null}}function d(e){let t;try{t=a.readdirSync(e)}catch{return[]}return t.filter(r=>Se(c.join(e,r))?.includes(de)).sort()}function T(e,t){return t.filter(r=>Se(c.join(e,r.file))!==r.content).map(r=>r.file)}function F(e,t){a.mkdirSync(e,{recursive:!0});let r=T(e,t);for(let o of r){let i=t.find(s=>s.file===o);a.writeFileSync(c.join(e,o),i.content,{mode:493}),a.chmodSync(c.join(e,o),493)}let n=new Set(t.map(o=>o.file));for(let o of d(e))n.has(o)||a.unlinkSync(c.join(e,o));return r}function we(e){let t=d(e);for(let r of t)a.unlinkSync(c.join(e,r));try{a.readdirSync(e).length===0&&a.rmdirSync(e)}catch{}return t}function xe(e,t){return d(e).length===0?[]:F(e,t)}import*as m from"fs";import*as f from"path";var $e=e=>f.join(e,"runtime","terminal-cli.json");function ve(e){try{let t=JSON.parse(m.readFileSync($e(e),"utf8"))?.state;return t==="installed"||t==="removed"?t:null}catch{return null}}function N(e,t){let r=$e(e);m.mkdirSync(f.dirname(r),{recursive:!0}),m.writeFileSync(r,`${JSON.stringify({state:t,updated_at:new Date().toISOString()},null,2)}
27
- `)}function Pe(e,t){let r=e;try{r=m.realpathSync(e)}catch{}let o=(t==="win32"?f.win32:f.posix).normalize(r).replace(/[\\/]+$/,"");return t==="win32"?o.toLowerCase():o}function Ce(e,t,r){let n=X(t,"@cortex-agent/server",r);if(!n)return!1;let o=r==="win32"?f.win32:f.posix;return Pe(n,r)===Pe(o.join(e,"runtime","prefix"),r)}var L=e=>e==="win32"?A.win32:A.posix,_=(e,t)=>{let r=L(t).normalize(e).replace(/[\\/]+$/,"");return t==="win32"?r.toLowerCase():r};function Te(e,t,r,n=[]){let o=L(r),i=new Set(n.map(l=>_(l,r)));return t.split(o.delimiter).filter(l=>l&&!i.has(_(l,r))).flatMap(l=>e.map(y=>o.join(l,y))).filter(l=>D.existsSync(l))}function ut(e,t){return e==="win32"?me():ae({home:Ee.homedir(),platform:e,zdotdir:process.env.ZDOTDIR,exists:D.existsSync,hasZsh:Te(["zsh"],t,e).length>0})}function Qt(e){let t=process.platform,r=process.env.PATH??"";return{home:e,node:process.execPath,installRoot:G,platform:t,pathEnv:r,registrar:ut(t,r)}}function z(e){return ye({node:e.node,home:e.home,bins:ge(e.installRoot)},e.platform)}var _e=e=>e.map(t=>({target:t.target,changed:p(t)}));function ct(e,t){let r=e.platform==="win32"?["cortex.cmd","cortex.exe","cortex"]:["cortex"];return Te(r,e.pathEnv,e.platform,[t,...Q(e.node,e.installRoot,e.platform)])}function lt(e,t,r,n){e.registrar.apply(n);let o=F(t,r);return N(e.home,"installed"),o}function ft(e,t){let r=g(e.home),n=z(e),o=e.registrar.plan(r,"add"),i=t?T(r,n):lt(e,r,n,o);return{ok:!0,action:"install",dry_run:t,dir:r,shims:n.map(s=>s.file),written:i,path_targets:_e(o),shadowed:ct(e,r)}}function qt(e,t){let r=g(e.home),n=e.registrar.plan(r,"remove"),o=t?d(r):we(r);return t||(e.registrar.apply(n),N(e.home,"removed")),{ok:!0,action:"remove",dry_run:t,dir:r,removed:o,path_targets:_e(n)}}function er(e){let t=g(e.home),r=d(t),n=r.length>0?T(t,z(e)):[],o=e.registrar.plan(t,"add").map(s=>({target:s.target,registered:!p(s)})),i=e.pathEnv.split(L(e.platform).delimiter).some(s=>s&&_(s,e.platform)===_(t,e.platform));return{ok:!0,dir:t,installed:r.length>0,shims:r,stale:n,path_targets:o,on_current_path:i}}function tr(e){if(ve(e.home)==="removed")return{action:"skipped",files:[]};let t=g(e.home);return d(t).length===0&&Ce(e.home,e.installRoot,e.platform)?{action:"installed",files:ft(e,!1).written}:{action:"refreshed",files:xe(t,z(e))}}function Ae(e){return u(`cmd.auth.state.${e}`)}function be(e){return u(`cmd.auth.type.${e??"none"}`)}function mt(e){return e?u("cmd.auth.expires",{time:e}):""}function pt(e){return u("cmd.auth.credentialLine",{authType:be(e.authType),state:Ae(e.state),source:e.source??"\u2014",expires:mt(e.expiresAt)})}function dt(e){let t=u(`cmd.auth.backend.${e.backend}`),r=u("cmd.auth.accountLine",{backend:t,label:e.label,authType:be(e.authType),state:Ae(e.state),inUse:e.inUse?u("cmd.auth.inUse"):""});return e.credentials.length===0?[r]:[r,u("cmd.auth.credentials"),...e.credentials.map(pt)]}function ht(e){return e.backend==="claude"||e.inUse||e.state!=="logged-out"||e.credentials.length>0}function or(e){let t=e.piRuntime.available?u("cmd.auth.runtimeAvailable"):u("cmd.auth.runtimeUnavailable"),r=e.piRuntime.version?u("cmd.auth.runtimeVersion",{version:e.piRuntime.version}):"",n=e.accounts.filter(ht),o=e.accounts.length-n.length,i=[u("cmd.auth.heading"),u("cmd.auth.generatedAt",{time:e.generatedAt}),u("cmd.auth.runtimeLine",{status:t,version:r}),...n.flatMap(dt)];return o>0&&i.push(u("cmd.auth.hiddenLoggedOut",{n:o})),i.join(`
28
- `)}import{execFile as gt}from"node:child_process";var yt=["-o","BatchMode=yes","-o","ConnectTimeout=5","-o","StrictHostKeyChecking=no"];function St(e,t){return new Promise((r,n)=>{gt("ssh",[...e],{timeout:t},(o,i,s)=>{if(!o)return r(i.trim());n(new Error(s.trim()||(o.killed?`ssh timed out after ${t}ms`:o.message)))})})}function ar(e,t,r=15e3){return St([...yt,e,t],r)}export{or as a,He as b,je as c,Fe as d,Ne as e,Le as f,yt as g,St as h,ar as i,Qt as j,ft as k,qt as l,er as m,tr as n};
@@ -1,68 +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 Nt,g as Jt,h as P,i as Qt}from"./chunk-4U7XXM4W.js";import{a as Lt}from"./chunk-TCAEECDI.js";import{a as Rt,b as jt}from"./chunk-OZGBWAT2.js";import{a as Ht,b as Wt,c as Gt,d as K,e as Vt,f as qt,g as zt,i as Xt}from"./chunk-ZFPMIQA3.js";import{a as Yt}from"./chunk-YAEVYJAR.js";import{a as Zt,c as Kt}from"./chunk-D3NXKK2L.js";import{a as Pt,b as At}from"./chunk-YHIWOGVL.js";import{a as en}from"./chunk-QEOFEETJ.js";import{a as de}from"./chunk-DGMNI4AO.js";import{a as Dt,d as Ot,e as Mt}from"./chunk-SUFW24P4.js";import{a as X}from"./chunk-LCKVYFMD.js";import{a as He,d as Ge}from"./chunk-52T37Y47.js";import{d as $e,j as _t,t as Ut,u as Bt,v as We,x as ue}from"./chunk-3YHOCPQU.js";import{a as Tt,d as le}from"./chunk-MEPASGPP.js";import{c as Ct}from"./chunk-STUHNKQS.js";import{a as F}from"./chunk-PFMEUFJ7.js";import{J as n}from"./chunk-DPQPXBTP.js";import{d as xt}from"./chunk-W5LGYSPZ.js";import{e as I}from"./chunk-E7ZMYIY6.js";import{e as h}from"./chunk-NAA7GF6Q.js";import{f as Ft,g as Be}from"./chunk-QWAQHHRS.js";import{f as vt,l as Et,m as $t,t as kt}from"./chunk-J5DVLUKY.js";var _o=[["permission",/\b(EACCES|EPERM)\b|permission denied/i],["disk",/\bENOSPC\b|no space left/i],["timeout",/\bETIMEDOUT\b|timed? ?out|killed by SIG/i],["network",/\b(ENOTFOUND|ECONNRESET|ECONNREFUSED|EAI_AGAIN|ENETUNREACH)\b|network|fetch failed/i],["npm",/npm (ERR|error)|exited with code|could not start/i]];function Po(e){return _o.find(([,t])=>t.test(e))?.[0]??"other"}function tn(e,t){return Math.max(0,Math.round((t-e)/1e3))}function ke(e,t=new Date){return{type:"upgrade",at:t.toISOString(),...e}}function Ao(e,t){let o=tn(Date.parse(e.startedAt),Date.now()),{from:r,to:i,method:a}=e;if(t===null){We(l=>({...l,pendingUpgrade:e})),ue(ke({from:r,to:i,method:a,stage:"installed",durationS:o,failure:null}));return}let c={class:Po(t),message:He(t)};ue(ke({from:r,to:i,method:a,stage:"failed",durationS:o,failure:c}),{urgent:!0})}function nn(e){return(t,o)=>{let r={from:F,to:t,startedAt:new Date().toISOString(),method:le().serverAutoUpdate?"auto":"prompt"};e(t,i=>{try{Ao(r,i)}catch{}o(i)})}}function Do(e,t,o){if(e){let r=e.to===F?"confirmed":"unconfirmed",i=tn(Date.parse(e.startedAt),o);return ke({...e,stage:r,durationS:i,failure:null},new Date(o))}return!t||t===F?null:ke({from:t,to:F,method:"manual",stage:"version-changed",durationS:null,failure:null},new Date(o))}function Pi(e=Date.now()){let t=Bt(),o=Do(t.pendingUpgrade,t.lastVersion,e);We(r=>({...r,pendingUpgrade:null,lastVersion:F})),o&&ue(o)}function Oo(e){let t=e?.code;return t==="EACCES"||t==="EPERM"?"permission":e instanceof SyntaxError?"parse":typeof t=="string"&&t.startsWith("E")?"io":"other"}function Ai(e){let t=e.error instanceof Error?e.error.message:String(e.error);ue({type:"migration_failure",at:new Date().toISOString(),migration:e.migration.replace(/[^A-Za-z0-9._:/@[\]-]/g,"_").slice(0,80),errorClass:Oo(e.error),message:He(t)})}import*as _e from"node:fs";import*as Xe from"node:os";import{spawn as Go}from"node:child_process";var on={available:null,state:"idle"},v=on,N=null;function rn(){return v}function Oi(e,t){let o=N;N=null,o?.(null),N=t,v={available:e,state:"prompting"}}function sn(e){let t=N;return t?(N=null,t(e),!0):!1}function Mi(e){N=null,v=e==="apply"?{available:v.available,state:"waiting"}:on}function an(e){let t=N;N=null,t?.(null),v={available:e,state:"waiting",auto:!0}}function cn(){return v.auto?{auto:!0}:{}}function ln(){v={available:v.available,state:"installing",...cn()}}function un(){v={available:v.available,state:"restarting",...cn()}}function pe(e){v={available:v.available,state:"failed",error:e}}var Ce={status:"error",reason:"check_failed"},Mo=15e3;function Ve(e){return{status:"available",update:{version:e}}}async function Lo(e){let t,o=new Promise(r=>{t=setTimeout(()=>r(null),Mo),t.unref?.()});try{return await Promise.race([Promise.resolve().then(e),o])}finally{clearTimeout(t)}}var Te=class{deps;inFlight=null;pending=null;latestVersion=null;promptFailed=!1;decision=Promise.resolve(null);constructor(t){this.deps=t}check(){return this.inFlight?this.inFlight:(this.inFlight=this.discover().catch(()=>Ce).finally(()=>{this.inFlight=null}),this.inFlight)}async checkAndWait(){return await this.check(),{action:await this.decision,latestVersion:this.latestVersion}}skipReason(){if(le().serverUpdateDisable)return"disabled";if(this.deps.isDevMode())return"dev_mode";let{state:t}=rn();return t==="waiting"||t==="installing"||t==="restarting"?"update_in_progress":null}async discover(){let t=this.skipReason();return t?{status:"skipped",reason:t}:this.lookup()}async lookup(){let t=await Lo(this.deps.getLatest);if(!t||!/^\d+\.\d+\.\d+(?:-\d+)?$/.test(t))return Ce;let o=this.skipReason();return o?{status:"skipped",reason:o}:(this.latestVersion=t,this.resolveVersion(t))}resolveVersion(t){if(Lt(t,F)<=0)return this.current();let o=this.deps.loadState()??{};return o.skippedVersion===t?{status:"skipped",reason:"version_skipped"}:le().serverAutoUpdate?this.autoInstall(t,o):this.pending?.version===t?Ve(t):this.openPrompt(t,o)}autoInstall(t,o){this.deps.saveState({...o,lastCheckedAt:this.deps.now()}),this.pending=null,an(t);try{this.deps.installWhenIdle(t)}catch(r){return pe(r instanceof Error?r.message:String(r)),this.decision=Promise.resolve(null),Ce}return this.decision=Promise.resolve("apply"),{...Ve(t),reason:"auto_install"}}current(){return this.pending&&(this.pending=null,sn("cancel"),this.decision=Promise.resolve(null)),{status:"current"}}async openPrompt(t,o){let r={...o,lastCheckedAt:this.deps.now(),lastPromptedVersion:t};this.deps.saveState(r);let i=this.deps.prompt.ask({latestVersion:t});return this.pending={version:t,answer:i},this.promptFailed=!1,this.decision=this.handleDecision(this.pending,r),await Promise.resolve(),this.promptFailed?Ce:Ve(t)}async handleDecision(t,o){try{let r=await t.answer;return this.pending!==t?null:this.acceptChoice(r,t.version,o)}catch(r){return this.failDecision(t,r)}finally{this.pending===t&&(this.pending=null)}}failDecision(t,o){return this.pending!==t||(this.promptFailed=!0,pe(o instanceof Error?o.message:String(o))),null}acceptChoice(t,o,r){return t==="apply"&&(this.deps.saveState({...r,skippedVersion:void 0}),this.deps.installWhenIdle(o)),t==="skip"&&this.deps.saveState({...r,skippedVersion:o}),t}};import{execFile as Fo}from"node:child_process";var No=1024*1024;function Uo(e,t,o,r,i){let a=t&&typeof t.code=="number"?t.code:t?null:0,c=t?.signal??null,l=!!t&&(t?.killed===!0||c==="SIGTERM")&&i!==void 0;e({ok:a===0,code:a,signal:c,timedOut:l,stdout:o,stderr:r,...t&&typeof t.code=="string"?{error:t.message}:{}})}function J(e,t=[],o={}){return new Promise(r=>{let i=Fo(e,[...t],{cwd:o.cwd,shell:o.shell,env:o.env??process.env,timeout:o.timeoutMs,killSignal:"SIGTERM",maxBuffer:o.maxBuffer??No,encoding:"utf8",windowsHide:!0},(a,c,l)=>Uo(r,a,c,l,o.timeoutMs));o.stdin!==void 0?i.stdin?.end(o.stdin):i.stdin?.end()})}function Gi(e,t={}){let o=process.platform==="win32"?process.env.ComSpec??"cmd.exe":"/bin/sh",r=process.platform==="win32"?"/c":"-c";return J(o,[r,e],t)}import*as Q from"fs";import*as Re from"path";var qe=Re.join($t,"update-state.json");function dn(){try{return JSON.parse(Q.readFileSync(qe,"utf8"))}catch{return null}}function pn(e){let t=Re.dirname(qe);Q.mkdirSync(t,{recursive:!0}),Q.writeFileSync(qe,JSON.stringify(e,null,2))}var me="server-update",Bo=5*6e4,ee=null;function je(e){let t=e.now??Date.now();ee={phase:e.phase??null,expiresAt:t+Bo}}function ze(){ee=null}function fn(e=Date.now()){return ee?e>=ee.expiresAt?(ee=null,null):{phase:ee.phase}:null}function Ki(e=Date.now()){return fn(e)!==null}var mn=160;function Ho(e){let t=e.replace(/\s+/g," ").trim();return t?t.length>mn?`${t.slice(0,mn)}\u2026`:t:"(no text)"}async function Ji(e){let t=fn()?.phase??"restart",o=t===me;if(e.interactive){let i={type:"interactive-reply",conduit:e.channel,sessionId:""},a=o?I("startup.updateHold"):I("startup.rebuildHold",{phase:t});await e.adapter.postMessage(i,{text:`${X.warning} ${a}`}).catch(()=>{});return}let r={channel:e.channel,preview:Ho(e.text)};await Nt(e.adapter,{level:"warning",title:o?I("notice.serverUpdate.title"):I("notice.rebuild.title"),text:o?I("startup.updateHoldDropped",r):I("startup.rebuildHoldDropped",{phase:t,...r})}).catch(()=>{})}var Wo=6e4,hn={isIdle:()=>!0,onIdle:()=>()=>{}};function gn(e,t,o={}){let r=o.supervised??(()=>!!process.send),i=o.renewMs??Wo,a=null,c=!1,l=null,f=(w,g)=>{if(clearInterval(w),c=!1,g!==null){ze(),pe(g);return}un(),r()?je({phase:me}):ze()},m=()=>{if(c||a===null||!e.isIdle())return;let w=a;a=null,l?.(),l=null,c=!0,je({phase:me});let g=setInterval(()=>je({phase:me}),i);g.unref?.(),ln();let z=!1,ce=L=>{z||(z=!0,f(g,L))};try{t(w,ce)}catch(L){ce(L instanceof Error?L.message:String(L))}};return w=>{if(a=w,e.isIdle()){m();return}l??=e.onIdle(m)}}function Vo(){let e=process.env.CORTEX_REPO;if(!e)return!1;try{return _e.existsSync(e)&&_e.statSync(e).isDirectory()}catch{return!1}}async function qo(){let e=Be(["view","@cortex-agent/server","version"]),t=await J(e.command,e.args,{shell:e.shell,timeoutMs:15e3,cwd:Xe.tmpdir()});return t.ok&&t.stdout.trim()||null}var zo=2e3;function Xo(e,t,o){let r=t!==null?`killed by ${t}`:`exited with code ${e}`,i=o.trim().split(`
5
- `).slice(-6).join(`
6
- `).trim();return i?`npm install -g ${r}
7
- ${i}`:`npm install -g ${r}`}function Yo(e,t){let o=Be(Ft(["install","-g",`@cortex-agent/server@${e}`])),r=Go(o.command,o.args,{shell:o.shell,detached:!0,stdio:["ignore","ignore","pipe"],cwd:Xe.tmpdir()}),i="";r.stderr?.on("data",a=>{i.length<zo&&(i+=String(a))}),r.stderr?.unref?.(),r.on("error",a=>t(`npm install -g could not start: ${a.message}`)),r.on("exit",(a,c)=>t(a===0?null:Xo(a,c,i))),r.unref()}function Zo(){return new Date().toISOString()}function ua(e){return new Te({prompt:e.prompt,getLatest:e.getLatest??qo,installWhenIdle:e.installWhenIdle??gn(e.idle??hn,nn(Yo)),loadState:e.loadState??dn,saveState:e.saveState??pn,now:e.now??Zo,isDevMode:Vo})}import{readFileSync as wn,existsSync as Ko}from"fs";import*as Sn from"path";var U=h("machine-registry"),te=Sn.join(Et,"machines.json"),fe={},bn=!1,Pe=null,Y=null;function Jo(e,t){if(typeof t.cortexPath!="string"||typeof t.gpuCount!="number")throw new Error(`Invalid machine entry "${e}": requires cortexPath (string) and gpuCount (number)`);let o=t.clientConnection??"direct";if(o!=="direct"&&o!=="ssh-reverse")throw new Error(`Invalid machine entry "${e}": clientConnection must be direct or ssh-reverse`);if(o==="ssh-reverse"&&!t.ssh?.trim())throw new Error(`Invalid machine entry "${e}": ssh-reverse requires ssh`);if(t.clientReversePort!==void 0){if(o!=="ssh-reverse")throw new Error(`Invalid machine entry "${e}": clientReversePort requires ssh-reverse`);if(!Number.isInteger(t.clientReversePort)||t.clientReversePort<1024||t.clientReversePort>65535)throw new Error(`Invalid machine entry "${e}": clientReversePort must be an integer in 1024..65535`)}}var he=null;function wa(e){he=e}var In=null;function Sa(e){In=e}function Qo(e,t,o){e!==t?(U.info(`Hot-reload: machines changed [${e}] \u2192 [${t}]`),he?.(`${X.refresh} \`machines.json\` hot-reloaded: [${e}] \u2192 [${t}]`)):(U.info(`Hot-reload: ${o} machines reloaded`),he?.(`${X.refresh} \`machines.json\` hot-reloaded (${o} machines)`)),In?.()}function yn(e=!0){try{let t=wn(te,"utf-8"),o=JSON.parse(t);for(let[c,l]of Object.entries(o))Jo(c,l);let r=Object.keys(fe).sort().join(","),i=Object.keys(o).sort().join(","),a=bn;fe=o,bn=!0,a?Qo(r,i,Object.keys(o).length):U.info(`Loaded ${Object.keys(o).length} machines: ${Object.keys(o).join(", ")}`)}catch(t){let o=`[machine-registry] Failed to load ${te}: ${t.message}`;if(e)throw new Error(o);U.error(o+" \u2014 keeping previous config"),he?.(`${X.warning} \`machines.json\` hot-reload FAILED \u2014 keeping previous config`)}}function Ae(){return fe}var er=64;function tr(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=er}function nr(e,t){try{let o=JSON.parse(wn(te,"utf-8"));return o[e]?(o[e].gpuCount=t,xt(te,`${JSON.stringify(o,null,2)}
8
- `),!0):!1}catch(o){return U.error(`Failed to persist gpuCount for ${e}: ${o.message}`),!1}}function xn(e,t){let o=fe[e];if(!o||!tr(t))return"skipped";if(o.gpuCount===t)return"unchanged";if(!nr(e,t))return"skipped";let r=o.gpuCount;return o.gpuCount=t,U.info(`${e}: gpuCount ${r} \u2192 ${t} (client-reported)`),he?.(`${X.refresh} \`${e}\` gpuCount ${r} \u2192 ${t} (reported by its client)`),"updated"}function Ia(){return Object.keys(fe)[0]||"local"}function or(){Y&&clearTimeout(Y),Y=setTimeout(()=>{Y=null,yn(!1)},300)}function ya(){Pe?.close(),Pe=Ct({label:"machines.json",filePath:te,onChange:or,warn:e=>U.error(e)})}function xa(){Pe?.close(),Pe=null,Y&&clearTimeout(Y),Y=null}if(Ko(te))try{yn()}catch(e){U.error(`Auto-load failed: ${e.message}`)}var rr=3e4,sr=h("hook-bus"),vn=[],En=null;function ir(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ar(e,t){return e===void 0?!0:ir(e)?Object.entries(e).every(([o,r])=>Object.hasOwn(t,o)&&t[o]===r):!1}function cr(e,t){let o=e.run.script===void 0?void 0:Kt(e.run.script,En??Zt());return{id:e.id,command:o===void 0?e.run.command:"node",args:o,timeoutMs:e.run.timeout===void 0?t:e.run.timeout*1e3,result:e.result}}function lr(e,t,o){return vn.filter(r=>r.enabled!==!1).filter(r=>r.event===e).filter(r=>ar(r.matcher,t)).map(r=>cr(r,o))}function Ye(e,t){let o=t instanceof Error?t.message:String(t);return sr.error(`Hook ${e} failed: ${o}`),{id:e,error:o}}function ur(e,t){return e.result==="stdout-as-prompt"?{id:e.id,result:t.trim()}:{id:e.id}}function dr(e,t,o){let r=ur(e,t);return o?{...r,stderr:o}:r}async function pr(e,t,o){try{let r=await Yt({command:e.command,args:e.args,timeoutMs:e.timeoutMs,stdinPayload:t,env:o,label:e.id});return r.error?Ye(e.id,r.error):dr(e,r.stdout,r.stderr)}catch(r){return Ye(e.id,r)}}function Ca(e){vn=[...e.entries],En=e.scriptDirs??null}function mr(e){let t=JSON.stringify(e);if(t===void 0)throw new TypeError("Hook payload is not JSON-serializable");return t}async function Ze(e,t,o){let r=[...lr(e,t,o?.defaultTimeoutMs??rr),...o?.scopedHooks??[]];if(r.length===0)return[];let i;try{i=mr(t)}catch(c){return r.map(l=>Ye(l.id,c))}let a=[];for(let c of r)a.push(await pr(c,i,o?.env));return a}var Ke=null;function $n(e){Ke=e}function ja(e,t){if(!(!Ke||!Ut()))try{Ke(e,t)}catch{}}function ge(e,t=1){t<=0||P(o=>{o.features[e]=(o.features[e]??0)+t})}function fr(e){P(t=>{t.messagesByChannel[e]=(t.messagesByChannel[e]??0)+1})}function La(e){return e.startsWith("slack")?"slack":e.startsWith("feishu")?"feishu":e.startsWith("tui")?"tui":"other"}function hr(e){P(t=>{t.uiOps[e]=(t.uiOps[e]??0)+1})}var gr=new Set(["sessions.send","sessions.createAndSend"]),br=new Set(["sessions.create","sessions.createAndSend"]);function Fa(e,t,o){hr(e),t&&(gr.has(e)&&fr(o??"other"),br.has(e)&&(ge("session_created"),de("first_session")))}var wr={"/webhook/subagent":{start:"subagent_run"},"/webhook/team":{spawn:"worker_spawned"},"/webhook/board":{open:"board_opened"},"/webhook/waitpoint":{create:"waitpoint_created"}},De={day:"",ids:new Set};function Sr(e){let t=Jt(Date.now());De.day!==t&&Object.assign(De,{day:t,ids:new Set});let o=typeof e=="string"?e:"";De.ids.has(o)||(De.ids.add(o),ge("browser_session"))}function Na(e,t){let o=t??{};if(e==="/webhook/browser"&&o.action==="lease")return Sr(o.sessionId);let r=wr[e??""]?.[String(o.action)];r&&(ge(r),r==="worker_spawned"&&de("first_worker"))}function Ua(e=1){e<=0||(ge("schedule_created",e),de("first_schedule"))}function kn(){ge("remote_client_connected"),de("first_remote_client")}function Cn(){P(e=>{e.perf.remoteClientDisconnects+=1})}function Ba(e){P(t=>Qt(t,e))}var Tn=[];function Ha(e,t=performance.now()){Tn.push([e,t])}function Wa(e,t=performance.now()){let o={imports:Math.round(e)},r=e;for(let[i,a]of Tn)o[i]=Math.max(0,Math.round(a-r)),r=a;o.total=Math.round(t),P(i=>{i.perf.startups.push(o),i.perf.startups.length>10&&i.perf.startups.shift()})}var Ir=/^(?::[A-Za-z][A-Za-z0-9_]{0,30}|\*|[a-z][a-z-]{0,23})$/;function yr(e){return!e||e.length>80||!e.startsWith("/")?null:e.split("/").filter(o=>o!=="").every(o=>Ir.test(o))?e:null}function xr(e){P(({perf:{web:t}})=>{t.loads+=1,e.ttfbMs!==null&&(t.ttfbMs[$e("webLoadMs",e.ttfbMs)]+=1),e.firstRenderMs!==null&&(t.firstRenderMs[$e("webLoadMs",e.firstRenderMs)]+=1),e.interactiveMs!==null&&(t.interactiveMs[$e("webLoadMs",e.interactiveMs)]+=1)})}function vr(e,t){if(e.kind==="crash"){let{crashKind:r,errorName:i,message:a,stack:c,buildStamp:l,uptimeS:f}=e;return Ge({component:"web",kind:r,errorName:i,message:a,stack:c,buildStamp:l,uptimeS:f,client:t,route:yr(e.route)})}if(e.kind!=="native_crash")return;let o=new Date(e.at);Ge({component:e.component,kind:"panic",errorName:"panic",message:e.message,stack:e.stack,buildStamp:e.appVersion,client:t,at:Number.isNaN(o.getTime())?new Date:o})}function Er(e,t){if(e.kind==="load")return xr(e);if(e.kind==="sse_reconnect")return P(o=>{o.perf.sseReconnects+=e.count});vr(e,t)}function Ga(){$n(Er)}import*as Mn from"crypto";import*as jn from"crypto";var $r=h("reverse-stream"),kr="/reverse",Rn=1e4,Cr=64,B=new Map;function _n(e){if(!e)return null;let t=new URL(e,"http://placeholder");if(t.pathname!==kr)return null;let o=t.searchParams.get("stream");return o&&/^[0-9a-f]{32}$/.test(o)?o:null}function Pn(e,t){if(B.size>=Cr)throw new Error(`too many pending reverse streams (${B.size})`);let o=jn.randomBytes(16).toString("hex"),r,i,a=new Promise((l,f)=>{r=l,i=f}),c=setTimeout(()=>{B.delete(o),i(new Error(`device ${e} did not open a stream to ${t} within ${Rn}ms`))},Rn);return c.unref?.(),B.set(o,{device:e,target:t,resolve:r,reject:i,timer:c}),{id:o,socket:a}}function An(e,t,o){let{id:r,socket:i}=Pn(e,`${t}:${o}`);return{id:r,message:{type:"open-stream",streamId:r,host:t,port:o},socket:i}}function za(e,t){let{id:o,socket:r}=Pn(e,t);return{id:o,message:{type:"open-file-stream",streamId:o,path:t},socket:r}}function Dn(e,t){let o=B.get(e);return o?(clearTimeout(o.timer),B.delete(e),$r.info(`stream ${e.slice(0,8)} claimed by ${o.device} \u2192 ${o.target}`),o.resolve(t),!0):!1}function On(e){let t=0;for(let[o,r]of B)r.device===e&&(clearTimeout(r.timer),B.delete(o),r.reject(new Error(`device ${e} disconnected before opening the stream`)),t++);return t}var y=h("client-manager"),Je=null;function nc(e){Je=e}var be=null;function oc(e){be=e}var E=new Map,A=new Map,ne=null,Oe=null,Qe=null,Ln="Server shutting down",Tr=15e3,Rr=12e4,jr=3e4;function Fn(e,t){t!==Ln&&Cn(),Ze("cortex:client.disconnected",t?{device:e,reason:t}:{device:e}).catch(()=>{})}function _r(e,t){for(let[o,r]of A)r.device===e&&(clearTimeout(r.timer),r.reject(t),A.delete(o))}function et(e,t){E.delete(e),y.info(`Device disconnected: ${e}${t?` (${t})`:""}`),Fn(e,t);let o=On(e);o>0&&y.info(`cancelled ${o} pending reverse stream(s) for ${e}`),_r(e,new Error(`Device "${e}" disconnected${t?` (${t})`:""}`)),be?.onDeviceGone(e)}function Nn(e){let t=E.get(e);if(!t)throw new Error(`Device "${e}" is not online`);if(t.ws.readyState!==Rt.default.OPEN)throw et(e,"WebSocket is not open"),new Error(`Device "${e}" WebSocket is not open`);return t.ws}function Pr(e){return!!e&&(e==="::1"||/^(::ffff:)?127\./.test(e))}function Ar(e,t){if(!t)return e.close(4001,"Missing device name"),!1;if(!Object.hasOwn(Ae(),t))return e.close(4005,"Unknown device"),!1;let o=E.get(t);return o&&o.ws!==e?(y.info(`Device ${t} already connected, rejecting new connection`),e.close(4002,"Device already connected"),!1):!0}function Dr(e,t,o){let r=t.device;if(!Ar(e,r))return null;let i=typeof t.bundleHash=="string"&&t.bundleHash?t.bundleHash:null,a=t.platform||"unknown";E.set(r,{device:r,platform:a,capabilities:t.capabilities||[],connectedAt:new Date,lastHeartbeat:new Date,bundleHash:i,ws:e}),y.info(`Device connected: ${r} (${a})`),kn(),Ze("cortex:client.connected",{device:r}).catch(()=>{}),xn(r,typeof t.gpuCount=="number"?t.gpuCount:null);try{Je?.onHello(r,i)}catch(l){y.warn(`onHello hook failed for ${r}: ${l.message}`)}let c=typeof t.pid=="number"&&Number.isInteger(t.pid)&&t.pid>0?t.pid:null;try{be?.onHello?.(r,{pid:c,loopback:Pr(o)})}catch(l){y.warn(`lifecycle hello hook failed for ${r}: ${l.message}`)}return r}function Or(e){try{let t=JSON.parse(e);return t&&typeof t.type=="string"?t:null}catch{return null}}function Mr(e){let t=e.commandId?A.get(e.commandId):void 0;t&&(A.delete(e.commandId),clearTimeout(t.timer),e.success?t.resolve(e.data):t.reject(new Error(e.error||"Command failed")))}function Lr(e,t){try{Je?.onUpdateResult(e,{ok:!!t.ok,hash:typeof t.hash=="string"?t.hash:void 0,error:typeof t.error=="string"?t.error:void 0})}catch(o){y.warn(`onUpdateResult hook failed for ${e}: ${o.message}`)}}function Fr(e,t){if(e.type==="result")return Mr(e);if(t)if(e.type==="heartbeat"){let o=E.get(t);o&&(o.lastHeartbeat=new Date)}else e.type==="update-result"&&Lr(t,e)}function Nr(e,t){let o=e.req.headers[Dt],r=Array.isArray(o)?o[0]:o;if(Ot(Mt(),r))return t(!0);let i=e.req.socket?.remoteAddress||"unknown";y.warn(`WS auth rejected from ${i}: ${r?"invalid token":"missing token"}`),t(!1,401,"Unauthorized")}function Ur(e,t){let o=null;e.on("message",r=>{let i=Or(r.toString());i?.type==="hello"?o=Dr(e,i,t):i&&Fr(i,o)}),e.on("close",(r,i)=>{o&&E.get(o)?.ws===e&&et(o,i.toString().trim()||void 0)}),e.on("error",r=>{y.error(`WebSocket error for ${o||"unknown"}: ${r.message}`)})}function Br(e,t){let o=_n(t.url);if(!o)return Ur(e,t.socket?.remoteAddress);Dn(o,e)||(y.warn("reverse callback with an unknown stream id \u2014 closing"),e.close(4004,"Unknown stream"))}function Hr(){let e=Date.now(),t=[...E.values()].filter(o=>e-o.lastHeartbeat.getTime()>Tr);for(let o of t)if(E.get(o.device)===o){try{o.ws.close(4003,"Heartbeat timeout")}catch{}et(o.device,"Heartbeat timeout")}}function rc(e,t){if(ne){y.warn("Already running");return}Qe=e,be?.onStart(),ne=new jt.default({port:e,host:t,verifyClient:Nr}),y.info(`WebSocket server started on port ${e}`),ne.on("connection",Br),ne.on("error",o=>{y.error(`Server error: ${o.message}`)}),Oe=setInterval(Hr,5e3)}async function sc(){Oe&&clearInterval(Oe),Oe=null;for(let[t,o]of A)clearTimeout(o.timer),o.reject(new Error("Client manager shutting down")),A.delete(t);for(let[,t]of E){try{t.ws.close(1001,"Server shutting down")}catch{}Fn(t.device,Ln)}E.clear();let e=ne;ne=null,e&&e.close(),await be?.onStop(),Qe=null,e&&y.info("WebSocket server stopped")}function Me(){let e=[];for(let[,t]of E)e.push({device:t.device,platform:t.platform,connectedAt:t.connectedAt,lastHeartbeat:t.lastHeartbeat,capabilities:t.capabilities,bundleHash:t.bundleHash});return e}function Un(e){return E.has(e)}function ic(){return Qe}function Bn(e,t){Nn(e).send(JSON.stringify(t))}function Hn(e,t){let o;try{o=Nn(e)}catch(a){return Promise.reject(a)}let r=Mn.randomBytes(8).toString("hex"),i=t.timeout||(t.action==="bash"?Rr:jr);return new Promise((a,c)=>{let l=setTimeout(()=>{A.delete(r),c(new Error(`Command to "${e}" timed out after ${i/1e3}s`))},i);A.set(r,{resolve:a,reject:c,timer:l,device:e});try{let f={type:"command",commandId:r,action:t.action,params:t.params};o.send(JSON.stringify(f))}catch(f){A.delete(r),clearTimeout(l),c(new Error(`Failed to send command to "${e}": ${f.message}`))}})}import*as Gn from"net";var H=h("device-port"),Wn="127.0.0.1",Vn="127.0.0.1",Wr=32,Gr=64,W=new Map;function qn(e,t,o){return`${e}|${t}|${o}`}function Vr(e,t,o){let r=!1,i=a=>{if(!r){r=!0,H.debug(`${o} closed: ${a}`);try{t.close()}catch{}try{e.destroy()}catch{}}};t.on("message",a=>{let c=Array.isArray(a)?Buffer.concat(a):Buffer.from(a);e.write(c)||(t.pause?.(),e.once("drain",()=>t.resume?.()))}),t.on("error",a=>i(`ws error: ${a.message}`)),t.on("close",()=>i("ws closed")),e.on("data",a=>{e.pause(),t.send(a,c=>{c?i(`send failed: ${c.message}`):e.resume()})}),e.on("error",a=>i(`tcp error: ${a.message}`)),e.on("close",()=>i("tcp closed")),e.resume()}var qr=Bn;async function zr(e,t){let{device:o,remoteHost:r,remotePort:i}=e.info;if(t.pause(),t.setNoDelay(!0),e.connections.add(t),t.once("close",()=>e.connections.delete(t)),e.connections.size>Gr){H.warn(`${o}:${i} \u2014 connection cap reached, refusing`),t.destroy();return}let a;try{a=An(o,r,i)}catch(l){H.warn(`${o}:${i} \u2014 ${l.message}`),t.destroy();return}a.socket.catch(()=>{});try{qr(o,a.message)}catch(l){H.warn(`${o}:${i} \u2014 cannot ask device to open a stream: ${l.message}`),t.destroy();return}let c;try{c=await a.socket}catch(l){H.warn(`${o}:${i} \u2014 ${l.message}`),t.destroy();return}if(t.destroyed){try{c.close()}catch{}return}Vr(t,c,`${o}:${i} stream ${a.id.slice(0,8)}`)}async function zn(e,t){let o=Vn,r=qn(e,o,t),i=W.get(r);if(i)return i.info;if(W.size>=Wr)throw new Error(`too many device ports open (${W.size})`);let a=Gn.createServer(),c={info:{device:e,remoteHost:o,remotePort:t,localPort:0,openedAt:new Date},server:a,connections:new Set};await new Promise((f,m)=>{a.once("error",m),a.listen(0,Wn,()=>{a.removeListener("error",m),f()})});let l=a.address();if(!l||typeof l=="string")throw a.close(),new Error("failed to bind a local port");return c.info.localPort=l.port,a.on("connection",f=>{zr(c,f)}),a.on("error",f=>H.warn(`listener for ${e}:${t} failed: ${f.message}`)),W.set(r,c),H.info(`device port ${Wn}:${l.port} \u2192 ${e} ${o}:${t}`),c.info}function oe(e,t){let o=Vn,r=qn(e,o,t),i=W.get(r);if(!i)return!1;W.delete(r);for(let a of i.connections)a.destroy();return i.connections.clear(),i.server.close(),H.info(`closed device port ${i.info.localPort} \u2192 ${e} ${o}:${t}`),!0}function dc(){return[...W.values()].map(e=>({...e.info}))}function pc(){for(let e of[...W.values()])oe(e.info.device,e.info.remotePort)}import*as Ie from"fs";import*as no from"net";import*as oo from"path";import{spawn as ro}from"child_process";import*as re from"fs";import*as tt from"path";import{execFile as Xr,spawn as Yr}from"child_process";import{promisify as Zr}from"util";var Kr=Zr(Xr),Xn=h("browser-display");function Jr(e){if(e.override)return{mode:"attached",display:e.override,takeover:"remote-desktop",reason:`display pinned by configuration (${e.override})`};if(e.platform==="linux"){if(e.envDisplay&&e.usableDisplays.includes(e.envDisplay))return{mode:"attached",display:e.envDisplay,takeover:"remote-desktop",reason:`$DISPLAY ${e.envDisplay} is reachable`};if(e.usableDisplays.length>0){let t=e.usableDisplays[0];return{mode:"attached",display:t,takeover:"remote-desktop",reason:`graphical session ${t} belongs to this user and is reachable`}}return e.hasXvfb?{mode:"virtual",display:null,takeover:"vnc-required",reason:"no reachable session; a virtual display will be created (a VNC bridge is needed to watch it)"}:{mode:"headless",display:null,takeover:"none",reason:"no graphical session and no Xvfb \u2014 the agent can browse, but nobody can take over"}}return e.platform==="darwin"||e.platform==="win32"?e.interactiveSession?{mode:"attached",display:null,takeover:"remote-desktop",reason:"running inside an interactive desktop session"}:{mode:"headless",display:null,takeover:"none",reason:e.platform==="win32"?"service session (Session 0) cannot show a window \u2014 CDP still works, takeover cannot":"no Aqua session (daemon context) \u2014 CDP still works, takeover cannot"}:{mode:"headless",display:null,takeover:"none",reason:`unsupported platform ${e.platform}`}}async function Qr(){let e;try{e=await re.promises.readdir("/tmp/.X11-unix")}catch{return[]}let t=typeof process.getuid=="function"?process.getuid():-1;return(await Promise.all(e.filter(r=>/^X\d+$/.test(r)).map(async r=>{try{let a=await re.promises.stat(`/tmp/.X11-unix/${r}`);if(t>=0&&a.uid!==t)return null}catch{return null}let i=`:${r.slice(1)}`;return await es(i)?i:null}))).filter(r=>r!==null).sort((r,i)=>Number(r.slice(1))-Number(i.slice(1)))}async function es(e){let t=[["xdpyinfo",["-display",e]],["xset",["-display",e,"q"]]];for(let[o,r]of t){let i=await Yn(o,r,3e3);if(i!=="missing")return i===0}return Xn.warn("neither xdpyinfo nor xset is installed \u2014 trusting X socket ownership"),!0}function Yn(e,t,o){return new Promise(r=>{let i=Yr(e,t,{stdio:"ignore",timeout:o});i.once("error",a=>r(a.code==="ENOENT"?"missing":-1)),i.once("exit",a=>r(a??-1))})}async function nt(e){return await Yn("which",[e],2e3)===0}async function ts(e,t=process.env){if(e==="darwin")try{let{stdout:o}=await Kr("launchctl",["managername"],{encoding:"utf8",timeout:2e3});return o.trim()==="Aqua"}catch{return!1}if(e==="win32"){let o=t.SESSIONNAME;return!!o&&o.toLowerCase()!=="services"}return!1}function Zn(e,t="/tmp"){for(let o=e;o<e+100;o++)if(!(re.existsSync(tt.join(t,`.X${o}-lock`))||re.existsSync(tt.join(t,".X11-unix",`X${o}`))))return o;return null}async function Kn(e=process.env){let t=process.platform,o=e.CORTEX_BROWSER_DISPLAY,r=t==="linux"&&!o,[i,a,c]=await Promise.all([r?Qr():[],r?nt("Xvfb"):!1,o?!1:ts(t,e)]),l=Jr({platform:t,override:o,envDisplay:e.DISPLAY,usableDisplays:i,hasXvfb:a,interactiveSession:c});return Xn.info(`display \u2192 ${l.mode}${l.display?` (${l.display})`:""}: ${l.reason}`),l}var D=h("managed-browser"),Jn=oo.join(vt,"browser","profile"),ns=9222,os=600*1e3,Qn=3e4,eo=1e4,rs=99,ss=3,ot="browser stopped while starting",is=6e4,as=3,b=null,we=null,se=null,R=0,T=null,Se=[],j="server";async function rt(){R++,T&&(clearTimeout(T),T=null);try{return await ao()}catch(e){throw R>0&&R--,e}}function st(){R!==0&&(R--,R===0&&cs())}function so(){return{running:!!b,refs:R,browser:b?{cdpEndpoint:b.cdpEndpoint,port:b.port,display:b.display,pid:b.pid}:null}}function xc(){T&&(clearTimeout(T),T=null),R=0,se&&(se.cancelled=!0,Le(se.procs,"SIGTERM")),io()}function cs(){T&&clearTimeout(T),T=setTimeout(()=>{T=null,R===0&&(D.info("no browser sessions left \u2014 reclaiming Chrome"),io())},os),T.unref?.()}function io(){let e=b;b=null,e&&Le([e.proc,...e.xvfb?[e.xvfb]:[]],"SIGTERM")}function Le(e,t){for(let o of e)try{o.kill(t)}catch{}}async function ao(){return b||we||(we=ls().finally(()=>{we=null}),we)}async function ls(){let e={cancelled:!1,procs:[]};se=e;try{return await us(e)}catch(t){throw Le(e.procs,"SIGKILL"),t}finally{se===e&&(se=null)}}async function us(e){let t=()=>{if(e.cancelled)throw new Error(ot)},o=await fs();if(!o)throw new Error("no Chrome/Chromium found \u2014 install Google Chrome, or set CORTEX_BROWSER_BINARY to its path");let r=await Kn();t(),Ie.mkdirSync(Jn,{recursive:!0});let i=await hs(ns);t();let a,c=r.display;if(r.mode==="virtual"){let g=await ps(e);a=g.proc,c=g.display}let l=[`--remote-debugging-port=${i}`,`--user-data-dir=${Jn}`,"--no-first-run","--no-default-browser-check","--disable-features=Translate","--remote-debugging-address=127.0.0.1"];r.mode==="headless"&&l.push("--headless=new"),process.platform==="linux"&&l.push("--password-store=basic");let f={...process.env};c?f.DISPLAY=c:delete f.DISPLAY,D.info(`launching ${o} on port ${i} (${r.mode}${c?` ${c}`:""})`);let m=ro(o,l,{env:f,stdio:"ignore",detached:!1});e.procs.push(m);let w=null;return m.on("exit",(g,z)=>ds(m,g,z)),m.on("error",g=>{w=g.message,D.error(`Chrome failed to spawn: ${g.message}`)}),await gs(i,()=>e.cancelled?ot:w?`Chrome failed to spawn: ${w}`:m.exitCode!==null||m.signalCode!==null?`Chrome exited during startup (code=${m.exitCode} signal=${m.signalCode})`:null),t(),b={cdpEndpoint:`http://127.0.0.1:${i}`,port:i,display:{...r,display:c},pid:m.pid??-1,proc:m,xvfb:a},D.info(`Chrome ready at ${b.cdpEndpoint} (pid ${b.pid})`),b}function ds(e,t,o){if(!b||b.proc!==e||(D.warn(`Chrome exited (code=${t} signal=${o})`),b.xvfb?.kill("SIGTERM"),b=null,R===0))return;let r=Date.now();if(Se=Se.filter(i=>r-i<is),Se.length>=as){D.error("Chrome crashed repeatedly \u2014 giving up until the next acquire"),Se=[];return}Se.push(r),D.info(`${R} session(s) still need a browser \u2014 restarting`),ao().catch(i=>D.error(`restart failed: ${String(i)}`))}async function ps(e){let t=rs,o="no free display number";for(let r=0;r<ss;r++){let i=Zn(t);if(i===null)break;let a=`:${i}`,c=ro("Xvfb",[a,"-screen","0","1920x1080x24","-nolisten","tcp","-displayfd","3"],{stdio:["ignore","ignore","ignore","pipe"]});e.procs.push(c);let l=await ms(c);if(e.cancelled)throw new Error(ot);if(!l)return{proc:c,display:a};o=`${a}: ${l}`,D.warn(`Xvfb ${o}`),Le([c],"SIGKILL"),t=i+1}throw new Error(`Xvfb could not start a virtual display (${o})`)}function ms(e){return new Promise(t=>{let o=!1,r="",i=l=>{o||(o=!0,clearTimeout(a),t(l))},a=setTimeout(()=>i(`not ready within ${eo}ms`),eo),c=e.stdio[3];c?.on("data",l=>{r+=String(l),r.includes(`
9
- `)&&i(null)}),c?.on("error",()=>{}),e.once("exit",(l,f)=>i(`exited (code=${l} signal=${f})`)),e.once("error",l=>i(l.message))})}async function fs(e=process.env){if(e.CORTEX_BROWSER_BINARY)return Ie.existsSync(e.CORTEX_BROWSER_BINARY)?e.CORTEX_BROWSER_BINARY:null;let t=process.platform==="darwin"?["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Chromium.app/Contents/MacOS/Chromium"]:process.platform==="win32"?[`${e.ProgramFiles??"C:\\Program Files"}\\Google\\Chrome\\Application\\chrome.exe`,`${e["ProgramFiles(x86)"]??"C:\\Program Files (x86)"}\\Google\\Chrome\\Application\\chrome.exe`,`${e.LOCALAPPDATA??""}\\Google\\Chrome\\Application\\chrome.exe`]:[];for(let o of t)try{if(Ie.existsSync(o))return o}catch{}for(let o of["google-chrome","google-chrome-stable","chromium","chromium-browser","chrome"])if(await nt(o))return o;return null}async function hs(e){if(await to(e))return e;for(let t=e+1;t<e+20;t++)if(await to(t))return t;throw new Error(`no free CDP port near ${e}`)}function to(e){return new Promise(t=>{let o=no.createServer();o.once("error",()=>t(!1)),o.once("listening",()=>o.close(()=>t(!0))),o.listen(e,"127.0.0.1")})}async function gs(e,t){let o=Date.now()+Qn,r="";for(;Date.now()<o;){let i=t();if(i)throw new Error(i);try{let a=await fetch(`http://127.0.0.1:${e}/json/version`,{signal:AbortSignal.timeout(2e3)});if(a.ok)return;r=`HTTP ${a.status}`}catch(a){r=a instanceof Error?a.message:String(a)}await new Promise(a=>setTimeout(a,250))}throw new Error(`Chrome did not expose CDP on ${e} within ${Qn}ms (${r})`)}var co=".cortex/browser/profile",Fe="DevToolsActivePort";function bs(e){return e==="darwin"?["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Chromium.app/Contents/MacOS/Chromium"]:[]}var ws=["google-chrome","google-chrome-stable","chromium","chromium-browser","chrome"],it="Cortex Managed Browser",Ss=`
10
- $ErrorActionPreference = "Stop"
11
- $profile = Join-Path $env:USERPROFILE ".cortex\\browser\\profile"
12
- $portFile = Join-Path $profile "${Fe}"
13
- New-Item -ItemType Directory -Force -Path $profile | Out-Null
14
- if ((Test-Path -LiteralPath $portFile) -and (Get-Item -LiteralPath $portFile).Length -gt 0) {
15
- Get-Content -LiteralPath $portFile -TotalCount 1
16
- exit 0
17
- }
18
- $candidates = @(
19
- (Join-Path $env:ProgramFiles "Google\\Chrome\\Application\\chrome.exe"),
20
- (Join-Path ([Environment]::GetEnvironmentVariable("ProgramFiles(x86)")) "Google\\Chrome\\Application\\chrome.exe"),
21
- (Join-Path $env:LOCALAPPDATA "Google\\Chrome\\Application\\chrome.exe")
22
- )
23
- $chrome = $candidates | Where-Object { $_ -and (Test-Path -LiteralPath $_) } | Select-Object -First 1
24
- if (-not $chrome) {
25
- foreach ($name in @("google-chrome", "google-chrome-stable", "chromium", "chromium-browser", "chrome")) {
26
- $found = Get-Command $name -ErrorAction SilentlyContinue
27
- if ($found) { $chrome = $found.Source; break }
28
- }
29
- }
30
- if (-not $chrome) { [Console]::Error.WriteLine("chrome-not-found"); exit 3 }
31
- $user = (Get-CimInstance Win32_ComputerSystem).UserName
32
- if (-not $user) { [Console]::Error.WriteLine("no-interactive-user"); exit 5 }
33
- $current = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
34
- if ($user -ine $current) { [Console]::Error.WriteLine("interactive-user-mismatch"); exit 6 }
35
- $quote = [char]34
36
- $arguments = "--remote-debugging-port=0 --remote-debugging-address=127.0.0.1 --user-data-dir=$quote$profile$quote --no-first-run --no-default-browser-check about:blank"
37
- $action = New-ScheduledTaskAction -Execute $chrome -Argument $arguments
38
- $principal = New-ScheduledTaskPrincipal -UserId $user -LogonType Interactive -RunLevel Limited
39
- $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero) -MultipleInstances IgnoreNew
40
- Register-ScheduledTask -TaskName "${it}" -Action $action -Principal $principal -Settings $settings -Force | Out-Null
41
- Start-ScheduledTask -TaskName "${it}"
42
- for ($i = 0; $i -lt 60; $i++) {
43
- if ((Test-Path -LiteralPath $portFile) -and (Get-Item -LiteralPath $portFile).Length -gt 0) { break }
44
- Start-Sleep -Milliseconds 500
45
- }
46
- if (-not ((Test-Path -LiteralPath $portFile) -and (Get-Item -LiteralPath $portFile).Length -gt 0)) {
47
- [Console]::Error.WriteLine("chrome-did-not-listen")
48
- exit 4
49
- }
50
- Get-Content -LiteralPath $portFile -TotalCount 1
51
- `.trim();function Is(e){let t=bs(e).map(o=>` [ -f "${o}" ] && { CHROME="${o}"; }`).join(`
52
- `);return[`PROFILE="$HOME/${co}"`,`PORTFILE="$PROFILE/${Fe}"`,'mkdir -p "$PROFILE"','if [ -s "$PORTFILE" ]; then head -1 "$PORTFILE"; exit 0; fi','CHROME=""',...t?[`if [ -z "$CHROME" ]; then :
53
- ${t}
54
- fi`]:[],`for b in ${ws.join(" ")}; do`,' [ -n "$CHROME" ] && break',' p=$(command -v "$b" 2>/dev/null) && CHROME="$p"',"done",'[ -n "$CHROME" ] || { echo "chrome-not-found" >&2; exit 3; }','nohup "$CHROME" --remote-debugging-port=0 --remote-debugging-address=127.0.0.1 --user-data-dir="$PROFILE" --no-first-run --no-default-browser-check --password-store=basic about:blank >/dev/null 2>&1 &','for _ in $(seq 1 60); do [ -s "$PORTFILE" ] && break; sleep 0.5; done','[ -s "$PORTFILE" ] || { echo "chrome-did-not-listen" >&2; exit 4; }','head -1 "$PORTFILE"'].join(`
55
- `)}function lo(e){return e==="win32"?`powershell.exe -NoProfile -Command '${Ss}' </dev/null`:Is(e)}function at(e){let t=`"$HOME/${co}"`;return e==="win32"?[`powershell.exe -NoProfile -Command '${['$ErrorActionPreference = "SilentlyContinue"',`Stop-ScheduledTask -TaskName "${it}" -ErrorAction SilentlyContinue`,"Get-CimInstance Win32_Process | Where-Object {",' $_.Name -eq "chrome.exe" -and $_.CommandLine -like "*.cortex*browser*profile*"',"} | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }"].join(`
56
- `)}' </dev/null >/dev/null 2>&1 || true`,`rm -f ${t}/${Fe}`].join(`
57
- `):[`pkill -f -- ${t} >/dev/null 2>&1 || true`,`rm -f ${t}/${Fe}`].join(`
58
- `)}var ye=h("device-browser"),ys=9e4,xs=5e3,vs=10*6e4,G=new Map;async function lt(e,t,o){let r=await Hn(e,{action:"bash",params:{command:t},timeout:o});if(r?.exitCode!==void 0&&r.exitCode!==0){let i=String(r.stderr??"").trim()||`exit ${r.exitCode}`;throw new Error(i)}return typeof r?.stdout=="string"?r.stdout:""}function Es(e){let t=e.split(`
59
- `).map(r=>r.trim()).filter(r=>/^\d+$/.test(r));if(t.length===0)return null;let o=Number(t[t.length-1]);return o>0&&o<=65535?o:null}function po(e){return Me().find(t=>t.device===e)?.platform??""}async function ct(e){try{return(await fetch(`${e}/json/version`,{signal:AbortSignal.timeout(xs)})).ok}catch{return!1}}async function uo(e,t){let o=await lt(e,lo(t),ys),r=Es(o);if(r===null)throw new Error(`device ${e} reported no debugging port`);let i=await zn(e,r);return{device:e,remotePort:r,cdpEndpoint:`http://127.0.0.1:${i.localPort}`,refs:0,idleTimer:null}}async function ut(e){let t=po(e),o=G.get(e);if(o){if(o.idleTimer&&(clearTimeout(o.idleTimer),o.idleTimer=null),await ct(o.cdpEndpoint))return o.refs++,{device:e,remotePort:o.remotePort,cdpEndpoint:o.cdpEndpoint};ye.info(`${e}: mapped browser no longer answers \u2014 relaunching`),oe(e,o.remotePort),G.delete(e)}let r=await uo(e,t);if(!await ct(r.cdpEndpoint)&&(ye.info(`${e}: adopted debugging port ${r.remotePort} is dead \u2014 stopping and relaunching`),oe(e,r.remotePort),await lt(e,at(t),3e4),r=await uo(e,t),!await ct(r.cdpEndpoint)))throw oe(e,r.remotePort),new Error(`device ${e} launched Chrome but its debugging port is unreachable`);return r.refs=1,G.set(e,r),ye.info(`${e}: browser on device port ${r.remotePort} \u2192 ${r.cdpEndpoint}`),{device:e,remotePort:r.remotePort,cdpEndpoint:r.cdpEndpoint}}function $s(e){e.idleTimer=setTimeout(()=>{e.refs>0||(ye.info(`${e.device}: no browser sessions left \u2014 reclaiming Chrome`),ks(e.device).catch(t=>ye.warn(`${e.device}: could not stop Chrome: ${t.message}`)))},vs),e.idleTimer.unref?.()}function mo(e){let t=G.get(e);t&&(t.refs=Math.max(0,t.refs-1),t.refs===0&&!t.idleTimer&&$s(t))}async function ks(e){let t=G.get(e);t?.idleTimer&&clearTimeout(t.idleTimer),G.delete(e),t&&oe(e,t.remotePort),await lt(e,at(po(e)),3e4)}function Rc(){for(let e of G.values())e.idleTimer&&clearTimeout(e.idleTimer);G.clear()}var V=h("browser-broker"),Cs=10*6e4,Ts=15e3,Rs=5e3,$=class extends Error{code;hint;constructor(t,o,r){super(o),this.name="BrowserLeaseError",this.code=t,this.hint=r}};function Ne(e){return typeof e=="string"?e.trim():""}function js(e,t){let o=t.trim(),r="or run without --device to use the server's browser";return o.includes("chrome-not-found")?{message:`Chrome is not installed on ${e}`,hint:`install Google Chrome on ${e}, ${r}`}:o.includes("no-interactive-user")?{message:`nobody is logged in to the desktop on ${e}`,hint:`log in on ${e}, ${r}`}:o.includes("interactive-user-mismatch")?{message:`the Cortex client on ${e} runs as a different user than the desktop session`,hint:`run the Cortex client as the logged-in user on ${e}`}:o.includes("chrome-did-not-listen")?{message:`Chrome on ${e} did not open its debugging port in time`,hint:`close any Chrome window still using the Cortex profile on ${e} and retry`}:/timed out/i.test(o)?{message:`${e} did not answer while starting Chrome (${o})`,hint:`check that ${e} is awake and its Cortex client is connected`}:{message:`could not start Chrome on ${e}: ${o||"unknown error"}`}}function _s(e){let t=new Map,o=new Map,r=new Map,i=new Map,a=new Set,c=null;function l(){for(let s of a)try{s()}catch(u){V.warn(`listener failed: ${u.message}`)}}function f(s,u,d){let S=(s.get(u)??Promise.resolve()).catch(()=>{}).then(d),x=S.catch(()=>{});return s.set(u,x),x.then(()=>{s.get(u)===x&&s.delete(u)}),S}function m(){if(c)return c;try{c={bin:e.resolveBin(),env:e.baseEnv()}}catch(s){throw s instanceof Ht?new $("engine-missing",s.message,s.hint):s}return c}function w(s){s.idleTimer&&clearTimeout(s.idleTimer),s.idleTimer=setTimeout(()=>{if(s.idleTimer=null,s.takenOver){w(s);return}t.get(s.sessionId)===s&&(V.info(`${s.sessionId}: browser idle for ${Math.round(e.idleMs/6e4)} min \u2014 releasing`),f(o,s.sessionId,async()=>{t.get(s.sessionId)===s&&!s.takenOver&&await z(s)}))},e.idleMs),s.idleTimer.unref?.()}function g(s){s.lastUsedAt=e.now(),w(s)}async function z(s){if(s.idleTimer&&clearTimeout(s.idleTimer),s.idleTimer=null,t.get(s.sessionId)===s&&t.delete(s.sessionId),i.delete(s),s.holdsRef&&(s.holdsRef=!1,e.release(s.device)),l(),!(!s.cdpEndpoint||!c))for(let u of[["tab","close"],["close"]])await e.run(c.bin,K(s.cdpEndpoint,s.abSession,u),c.env).catch(()=>{})}function ce(s,u){return s.holdsRef&&(s.holdsRef=!1,e.release(s.device)),i.delete(s),s.state="error",s.error=u.hint?`${u.message} \u2014 ${u.hint}`:u.message,s.cdpEndpoint=null,l(),u}function L(s){if(s===j)return;let{state:u,online:d}=e.availability(s);if(u==="online")return;let p=d.length?`online devices: ${["server",...d].join(", ")}`:"no devices are online";throw u==="offline"?new $("device-offline",`device "${s}" is offline`,`start its Cortex client, or pick another device (${p})`):new $("unknown-device",`unknown device "${s}"`,`use one of: server${d.length?`, ${d.join(", ")}`:""}`)}function gt(s,u){if(u instanceof $)return u;let d=u?.message??String(u);if(s===j)return new $("chrome-failed",`could not start Chrome on the server: ${d}`);let{message:p,hint:S}=js(s,d);return new $("chrome-failed",p,S)}function ko(s){return s===j?e.acquire(s):f(r,s,()=>e.acquire(s))}async function Co(s){try{L(s.device),m(),s.cdpEndpoint=await ko(s.device),s.holdsRef=!0,await St(s),s.state="ready",s.error=void 0,i.set(s,e.now()),V.info(`${s.sessionId}: browser ready on ${s.device} (${s.abSession})`)}catch(u){throw ce(s,gt(s.device,u))}l()}async function To(s){if(!(!(s.device===j||e.now()-(i.get(s)??0)>=Ts)||!s.cdpEndpoint))try{L(s.device);let d=await(s.device===j?e.refresh(s.device,s.cdpEndpoint):f(r,s.device,()=>e.refresh(s.device,s.cdpEndpoint)));i.set(s,e.now()),d!==s.cdpEndpoint&&(V.info(`${s.sessionId}: ${s.device} browser moved to ${d}`),s.cdpEndpoint=d,l())}catch(d){throw ce(s,gt(s.device,d))}}function bt(s,u,d){return f(o,s,async()=>{let p=t.get(s);if(d&&p?.takenOver)throw new $("taken-over","the user is controlling this browser right now","wait for them to hand it back, or ask them; do not retry in a loop");let S=u||p?.device||j;if(p&&(p.device!==S||p.state==="error")){let jo=p.takenOver;await z(p),p=void 0,jo&&V.info(`${s}: switching device ends the takeover`)}if(p?.state==="ready")return await To(p),g(p),p;let x={sessionId:s,device:S,abSession:Gt(s,S),state:"starting",cdpEndpoint:null,holdsRef:!1,takenOver:!1,lastUsedAt:e.now(),idleTimer:null,refreshing:!1,refreshAgain:!1};return t.set(s,x),g(x),l(),await Co(x),x})}function wt(s){let u=t.get(s);if(!u)throw new $("no-lease",`session ${s} has no browser`);return u}function Ro(s){let u=wt(s);if(u.state!=="ready"||!u.cdpEndpoint)throw new $("no-lease",`the browser for session ${s} is ${u.state}`);return u}async function Ee(s,u){let d=m(),p=()=>e.run(d.bin,K(s.cdpEndpoint,s.abSession,u),d.env),S=await p();return S.code===0||!qt(S.stderr)||(V.info(`${s.sessionId}: bound tab is gone \u2014 opening a new one`),(await e.run(d.bin,K(s.cdpEndpoint,s.abSession,["tab","new"]),d.env)).code!==0)?S:(await St(s),p())}async function St(s){let u=m(),d=await e.run(u.bin,K(s.cdpEndpoint,s.abSession,Vt),u.env).catch(p=>({code:-1,stdout:"",stderr:String(p)}));d.code!==0&&V.warn(`${s.sessionId}: could not set the viewport: ${d.stderr.trim().slice(0,200)}`)}async function It(s){if(s.refreshing){s.refreshAgain=!0;return}s.refreshing=!0;try{do{if(s.refreshAgain=!1,t.get(s.sessionId)!==s||s.state!=="ready"||!c)return;let u=async S=>{let x=await e.run(c.bin,K(s.cdpEndpoint,s.abSession,["--json","get",S]),c.env);if(x.code===0)try{return Ne(JSON.parse(x.stdout)?.data?.[S])||void 0}catch{return}},[d,p]=[await u("url"),await u("title")];(d!==s.url||p!==s.title)&&(s.url=d,s.title=p,l())}while(s.refreshAgain)}finally{s.refreshing=!1}}function yt(s){try{return JSON.parse(s)}catch{return null}}return{async leaseBrowser({sessionId:s,device:u}){let d=Ne(s);if(!d)throw new $("bad-request","no session id","cortex-browser must run inside a Cortex session (CORTEX_SESSION_ID is unset)");let p=await bt(d,Ne(u)||null,!0);return{device:p.device,cdpEndpoint:p.cdpEndpoint,abSession:p.abSession}},listBrowserSessions(){return[...t.values()].sort((s,u)=>u.lastUsedAt-s.lastUsedAt).map(s=>({sessionId:s.sessionId,device:s.device,abSession:s.abSession,state:s.state,...s.error?{error:s.error}:{},...s.url?{url:s.url}:{},...s.title?{title:s.title}:{},takenOver:s.takenOver,lastUsedAt:s.lastUsedAt}))},async runAgentBrowser(s,u){let d=await bt(s,null,!1),p=await Ee(d,u);return It(d),p},async streamPort(s){let u=t.get(s);if(!u||u.state!=="ready")return null;let d=yt((await Ee(u,["--json","stream","status"])).stdout);if(d?.data?.enabled&&typeof d.data.port=="number")return d.data.port;let p=yt((await Ee(u,["--json","stream","enable"])).stdout);return typeof p?.data?.port=="number"?p.data.port:null},setTakeover(s,u){let d=wt(s);d.takenOver!==u&&(d.takenOver=u,g(d),V.info(`${s}: browser ${u?"taken over by the user":"handed back to the agent"}`),l())},isTakenOver(s){return t.get(s)?.takenOver??!1},async insertText(s,u){let d=Ro(s),p=await Ee(d,["keyboard","inserttext",u]);if(p.code!==0)throw new Error(p.stderr.trim()||`agent-browser exited ${p.code}`)},noteBrowserCommand(s){let u=t.get(Ne(s));u&&(g(u),It(u))},agentBrowserRuntime(){return m()},onBrowserSessionsChanged(s){return a.add(s),()=>{a.delete(s)}},shutdown(){for(let s of t.values())s.idleTimer&&clearTimeout(s.idleTimer);t.clear(),a.clear()}}}async function Ps(e){try{return(await fetch(`${e}/json/version`,{signal:AbortSignal.timeout(Rs)})).ok}catch{return!1}}function As(){return{async acquire(e){return e===j?(await rt()).cdpEndpoint:(await ut(e)).cdpEndpoint},release(e){e===j?st():mo(e)},async refresh(e,t){if(e===j){let o=so().browser?.cdpEndpoint;if(o)return o;let r=(await rt()).cdpEndpoint;return st(),r}return await Ps(t)?t:(await ut(e)).cdpEndpoint},availability(e){let t=Me().map(o=>o.device).sort();return Un(e)?{state:"online",online:t}:{state:Object.hasOwn(Ae(),e)?"offline":"unknown",online:t}},resolveBin:()=>Wt(),baseEnv:()=>zt(),run:(e,t,o)=>Xt(e,t,{env:o}),now:()=>Date.now(),idleMs:Cs}}var dt=null;function q(){return dt??=_s(As()),dt}var Lc=e=>q().leaseBrowser(e),Fc=()=>q().listBrowserSessions();var Nc=e=>q().streamPort(e),Uc=(e,t)=>q().setTakeover(e,t),Bc=e=>q().isTakenOver(e),Hc=(e,t)=>q().insertText(e,t),Wc=e=>q().noteBrowserCommand(e),Gc=()=>q().agentBrowserRuntime();function Vc(){dt?.shutdown()}import*as k from"node:fs";import*as O from"node:path";var ie=h("project-store"),Ds=1e3;function fo(e,t,o){return[`# ${e} Status`,"","Updated: \u2014","","## Current Situation",t,"","## In Flight & New Variables","none","","## Blockers & Pending Decisions","none","","## Next Step",o,""].join(`
60
- `)}var Os=fo("general","Synthetic umbrella project \u2014 collects work not scoped to a specific project.","none"),Ms=`# general
61
-
62
- Synthetic umbrella project \u2014 always present. Created automatically by the system.
63
- `,Ls=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,pt=class{projectsDir;watchEnabled;projects=[];initialized=!1;watcher=null;debounceTimer=null;constructor(t={}){this.projectsDir=t.projectsDir??kt,this.watchEnabled=t.watchEnabled??!0}async initialize(){this.initialized||(this.scaffoldGeneral(),this.scan(),this.initialized=!0,this.watchEnabled&&this.startWatcher(),ie.info(`ProjectStore initialized: ${this.projects.length} projects (${this.projectsDir})`))}list(){return[...this.projects]}get(t){return this.projects.find(o=>o.id===t)}exists(t){return this.projects.some(o=>o.id===t)}getDefault(){return this.projects.find(t=>t.kind==="general")}resolveFromMessage(t){if(!t)return this.getDefault();let o=t.match(/\[project:([^\]]+)\]/);if(o)return this.get(o[1])??this.getDefault();let r=t.toLowerCase(),i=null,a=0;for(let c of this.projects){if(c.kind==="general")continue;let l=c.id.toLowerCase();r.includes(l)&&c.id.length>a&&(i=c,a=c.id.length)}return i??this.getDefault()}refresh(){this.scan()}createProject(t){let o=typeof t=="string"?t.trim():"";if(!o||o==="general"||!Ls.test(o)||O.basename(o)!==o)return{ok:!1,code:"invalid-name",message:`Invalid project name: ${JSON.stringify(t)}`};let r=O.join(this.projectsDir,o);if(this.exists(o)||k.existsSync(r))return{ok:!1,code:"already-exists",message:`Project already exists: ${o}`};this.scaffoldProject(r,fo(o,"New project \u2014 not yet oriented.","Define mission.md and roadmap.md."),`# ${o}
64
-
65
- ${o} project.
66
- `),ie.info(`Created project at ${r}`),this.scan();let i=this.get(o);return i?{ok:!0,project:i}:{ok:!1,code:"invalid-name",message:`Project not registered after creation: ${o}`}}destroy(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.watcher&&(this.watcher.close(),this.watcher=null),this.initialized=!1}scaffoldGeneral(){let t=O.join(this.projectsDir,"general");k.existsSync(t)||(this.scaffoldProject(t,Os,Ms),ie.info(`Scaffolded general project at ${t}`))}scaffoldProject(t,o,r){k.mkdirSync(t,{recursive:!0}),k.writeFileSync(O.join(t,"STATUS.md"),o,"utf8"),k.writeFileSync(O.join(t,"AGENTS.md"),r,"utf8")}scan(){let t=[];t.push(this.makeGeneralProject());try{let o=k.readdirSync(this.projectsDir,{withFileTypes:!0});for(let r of o)r.isDirectory()&&(r.name.startsWith(".")||r.name!=="general"&&t.push({id:r.name,name:r.name,kind:"user",contextDir:O.join(this.projectsDir,r.name)}))}catch{}this.projects=t}makeGeneralProject(){return{id:"general",name:"general",kind:"general",contextDir:O.join(this.projectsDir,"general")}}startWatcher(){try{this.watcher=k.watch(this.projectsDir,(t,o)=>{o&&(o.startsWith(".")||this.debouncedRescan())}),this.watcher.on("error",t=>{ie.error(`Watcher error for ${this.projectsDir}:`,t.message)})}catch(t){ie.error(`Failed to start watcher for ${this.projectsDir}:`,t)}}debouncedRescan(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.scan(),ie.debug("Rescanned projects after directory change")},Ds)}},Yc=new pt;import*as C from"node:fs";import*as _ from"node:path";var Fs=["mission.md","roadmap.md","STATUS.md"],Ns=["experiments","knowledge","patterns","decisions"];function mt(e){return Object.assign(new Error(e),{code:"not-found"})}function Ue(e){return Object.assign(new Error(e),{code:"invalid-args"})}function go(e,t){let o=e.projectStore.get(t);if(!o)throw mt(`project not found: ${t}`);try{return C.realpathSync(o.contextDir)}catch{throw mt(`project directory not found: ${t}`)}}function ho(e,t){return t===e||t.startsWith(e+_.sep)}function Us(e,t){if(_.isAbsolute(t))throw Ue(`absolute path not allowed: ${t}`);let o=_.resolve(e,t);if(!ho(e,o))throw Ue(`path escapes project root: ${t}`);let r;try{r=C.realpathSync(o)}catch{throw mt(`file not found: ${t}`)}if(!ho(e,r))throw Ue(`path escapes project root: ${t}`);if(!C.statSync(r).isFile())throw Ue(`not a file: ${t}`);return r}async function Qc(e,t){let o=go(e,t.projectId),r=Fs.flatMap(a=>{let c=_.join(o,a),l;try{l=C.statSync(c)}catch{return[]}return l.isFile()?[{name:a,sizeBytes:l.size,modifiedAt:l.mtime.toISOString()}]:[]}),i=Ns.flatMap(a=>{let c=_.join(o,a),l;try{l=C.readdirSync(c,{withFileTypes:!0})}catch{return[]}let f=l.filter(m=>m.isFile()&&m.name.endsWith(".md")&&m.name!=="index.md"&&m.name!=="AGENTS.md").map(m=>{let w=C.statSync(_.join(c,m.name));return{name:m.name,sizeBytes:w.size,modifiedAt:w.mtime.toISOString()}}).sort((m,w)=>m.name.localeCompare(w.name));return[{name:a,entryCount:f.length,entries:f}]});return{projectId:t.projectId,files:r,dirs:i}}async function Bs(e,t){let o=await J("git",["diff","--numstat","HEAD","--",t],{cwd:e,timeoutMs:5e3,maxBuffer:1048576,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}});if(!o.ok)return null;let i=o.stdout.split(`
67
- `).find(m=>m.trim().length>0);if(!i)return{added:0,removed:0};let[a,c]=i.split(" "),l=Number(a),f=Number(c);return!Number.isFinite(l)||!Number.isFinite(f)?null:{added:l,removed:f}}var Hs=/\b(?:task|manager|gate)\s+([0-9a-f]{4})\b/i;function Ws(e){let t=Hs.exec(e);return t?t[1].toLowerCase():null}function Gs(e){let t=[],o=new Map,r=null,i=0;for(let a of e.split(`
68
- `)){if(a.startsWith(" ")){r&&t.push({line:i,commit:r.slice(0,8),taskRef:o.get(r)??null}),r=null;continue}let c=/^([0-9a-f]{40}) \d+ (\d+)(?: \d+)?$/.exec(a);if(c){r=c[1],i=Number(c[2]);continue}r&&a.startsWith("summary ")&&o.set(r,Ws(a.slice(8)))}return t}async function Vs(e,t){let o=await J("git",["blame","--line-porcelain","HEAD","--",t],{cwd:e,timeoutMs:5e3,maxBuffer:8388608,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}});return o.ok?Gs(o.stdout):null}async function el(e,t){let o=go(e,t.projectId),r=Us(o,t.path),i=C.statSync(r),a=C.readFileSync(r,"utf8"),[c,l]=en()?await Promise.all([Bs(o,t.path),Vs(o,t.path)]):[null,null];return{projectId:t.projectId,path:t.path,content:a,sizeBytes:i.size,modifiedAt:i.mtime.toISOString(),lineDiff:c,blame:l}}var bo={feishu:["FEISHU_APP_ID","FEISHU_APP_SECRET","FEISHU_DOMAIN","FEISHU_ENCRYPT_KEY","FEISHU_VERIFICATION_TOKEN"],slack:["SLACK_BOT_TOKEN","SLACK_SIGNING_SECRET","SLACK_APP_TOKEN"]},ol={feishu:["FEISHU_APP_ID","FEISHU_APP_SECRET"],slack:bo.slack},rl=["FEISHU_APP_ID","FEISHU_DOMAIN"],Z=n.string().min(1).max(4096).regex(/^[^\s'\\\u0000-\u001f\u007f]+$/,"Invalid credential characters"),qs=n.object({FEISHU_APP_ID:Z.nullable().optional(),FEISHU_APP_SECRET:Z.nullable().optional(),FEISHU_DOMAIN:n.enum(["feishu","lark"]).nullable().optional(),FEISHU_ENCRYPT_KEY:Z.nullable().optional(),FEISHU_VERIFICATION_TOKEN:Z.nullable().optional(),SLACK_BOT_TOKEN:Z.nullable().optional(),SLACK_SIGNING_SECRET:Z.nullable().optional(),SLACK_APP_TOKEN:Z.nullable().optional()}).strict(),wo=n.object({platform:n.enum(["feishu","slack"]),enabled:n.boolean().optional(),fields:qs}).strict().refine(e=>Object.keys(e.fields).every(t=>bo[e.platform].includes(t)),"Fields must belong to the selected platform");var ft=["openai-codex","anthropic"];function il(e){return ft.includes(e)}var So=n.object({sessionId:n.string().min(1),starred:n.boolean()}),Io=n.object({sessionId:n.string().min(1),label:n.string().trim().min(1).max(60)});var zs=n.object({projectId:n.string().optional(),resumable:n.boolean().optional(),origin:n.enum(["direct","thread","scheduled"]).optional()}),Xs=n.object({sessionId:n.string(),compactSubagents:n.boolean().optional(),since:n.string().max(64).optional()}),Ys=n.object({sessionId:n.string(),subagentId:n.string().min(1).max(512)}),Zs=n.object({sessionId:n.string(),ref:n.string().min(1).max(512)}),Ks=n.object({sessionId:n.string().min(1)}),Js=n.object({projectId:n.string().optional(),paused:n.boolean().optional()}),Qs=n.object({projectId:n.string().optional()}),ei=n.object({boardId:n.string()}),ti=n.object({boardId:n.string()}),ni=n.object({}),oi=n.object({sessionId:n.string().min(1)}),ri=n.object({status:n.array(n.string()).optional(),limit:n.number().optional()}),si=n.object({executionId:n.string()}),ii=n.object({projectId:n.string()}),ai=n.object({projectId:n.string(),path:n.string()}),ci=n.object({status:n.enum(["pending","approved","rejected","failed"]).optional()}),li=n.object({projectId:n.string()}),ui=n.object({projectId:n.string()});var yl=n.object({}),xl=n.object({projectId:n.string().nullish()}),vl=n.object({}),El=n.object({}),$l=n.object({flowId:n.string().min(1)}),kl=n.object({}),Cl=n.object({}),Tl=n.object({enabled:n.boolean(),name:n.string().trim().optional(),org:n.string().trim().optional(),email:n.string().trim().optional()}),Rl=n.object({}),jl=_t,_l=n.object({}),Pl=n.object({}),Al=n.object({machine:n.string().min(1)}),Dl=n.object({}),Ol=n.object({sessionId:n.string().min(1).optional(),agentName:n.string().min(1).nullable().optional()}),Ml=n.object({}),Ll=n.object({}),Fl=n.object({}),Nl=n.object({}),Ul=n.object({}),Bl=n.object({limit:n.number().int().positive().max(50).optional()}),Hl=n.object({}),Wl=n.object({}),Gl=n.object({backend:n.enum(["claude","pi"]),provider:n.string().min(1),authType:n.enum(["api_key","oauth"]),noticeId:n.string().min(1).optional()}),Vl=n.object({flowId:n.string().min(1),value:n.string(),promptId:n.number().int().nonnegative().optional()}),ql=n.object({flowId:n.string().min(1)}),zl=n.object({backend:n.enum(["claude","pi"]).optional()}),Xl=n.object({backend:n.enum(["claude","pi"]),provider:n.string().min(1),authType:n.enum(["api_key","oauth"])}),xo=n.string().min(1).regex(At),Yl=n.object({name:xo,api:n.enum(Pt),upstreamUrl:n.string().min(1),apiKey:n.string().optional(),models:n.array(n.object({id:n.string().min(1),contextWindow:n.number().int().positive().optional(),maxTokens:n.number().int().positive().optional(),reasoning:n.boolean().optional()})).min(1),headers:n.record(n.string(),n.string()).optional(),compat:n.record(n.string(),n.unknown()).optional()}),Zl=n.object({name:xo}),Kl=n.object({name:n.string()}),Jl=n.object({projectId:n.string().optional()}),Ql=n.object({sessionId:n.string(),text:n.string(),attachments:n.array(n.object({name:n.string(),path:n.string(),size:n.number(),mimeType:n.string(),type:n.enum(["image","video","file","view"])})).optional()}),eu=n.object({sessionId:n.string()}),tu=n.object({sessionId:n.string()}),nu=n.object({sessionId:n.string()}),ou=n.object({sessionIds:n.array(n.string()).min(1).max(500)}),ru=n.object({sessionId:n.string(),agentName:n.string().min(1).nullable().optional()}),vo=n.object({backend:n.enum(["claude","pi"]),provider:n.string().min(1).nullable(),model:n.string().min(1),thinking:n.string().min(1).nullable(),mode:n.string().min(1)}).strict(),xe=vo,su=n.object({sessionId:n.string(),selection:xe}).strict(),iu=n.object({requestId:n.string().min(1),answers:n.record(n.string(),n.string())}),au=n.object({requestId:n.string().min(1),approved:n.boolean(),feedback:n.string().optional()}),cu=n.object({sessionId:n.string().min(1),decisionId:n.string().min(1),action:n.enum(["approve","explain","revise"]),message:n.string().optional()}),lu=n.object({sessionId:n.string().regex(/^[\w-]+$/),ts:n.string().min(1),src:n.string().min(1)}),uu=n.object({sessionId:n.string()}),du=n.object({sessionId:n.string(),turnIndex:n.number().int().min(0),text:n.string().min(1)}),pu=n.object({projectId:n.string(),agentName:n.string().min(1).optional(),selection:xe.optional(),clean:n.boolean().optional(),text:n.string(),draftUploadId:n.string().uuid().optional(),attachments:n.array(n.object({name:n.string(),path:n.string(),size:n.number(),mimeType:n.string(),type:n.enum(["image","video","file"])})).optional()}),mu=n.object({waitpointId:n.string().min(1)}),fu=n.object({executionId:n.string()}),hu=n.object({scheduleId:n.string()}),gu=n.object({type:n.enum(["interval","daily","weekly","once"]),message:n.string().min(1),projectId:n.string().optional(),selection:xe.optional(),intervalMs:n.number().int().positive().optional(),time:n.string().regex(/^\d{2}:\d{2}$/).optional(),dayOfWeek:n.number().int().min(0).max(6).optional(),delay:n.number().int().positive().optional()}).superRefine((e,t)=>{e.type==="interval"&&e.intervalMs===void 0&&t.addIssue({code:n.ZodIssueCode.custom,path:["intervalMs"],message:I("ui.schedule.intervalRequired")}),(e.type==="daily"||e.type==="weekly")&&e.time===void 0&&t.addIssue({code:n.ZodIssueCode.custom,path:["time"],message:I("ui.schedule.timeRequired",{type:e.type})}),e.type==="weekly"&&e.dayOfWeek===void 0&&t.addIssue({code:n.ZodIssueCode.custom,path:["dayOfWeek"],message:I("ui.schedule.dayOfWeekRequired")}),e.type==="once"&&e.delay===void 0&&t.addIssue({code:n.ZodIssueCode.custom,path:["delay"],message:I("ui.schedule.delayRequired")})}),bu=n.object({scheduleId:n.string(),message:n.string().min(1).optional(),projectId:n.string().optional(),selection:xe.optional(),intervalMs:n.number().int().positive().optional(),time:n.string().regex(/^\d{2}:\d{2}$/).optional(),dayOfWeek:n.number().int().min(0).max(6).optional()}),di=new Set(["__proto__","prototype","constructor"]),pi=120,mi={boolean:n.boolean(),number:n.number().finite(),"number|null":n.number().finite().nullable(),"string[]":n.array(n.string()),"string|null":n.string().nullable()};function fi(e){let t=mi[e.type];return!("validate"in e)||typeof e.validate!="function"?t:t.superRefine((o,r)=>{let i=e.validate(o);i&&r.addIssue({code:n.ZodIssueCode.custom,message:i})})}var hi=Object.fromEntries(Object.entries(Tt).filter(([e])=>e!=="providerRateLimits").map(([e,t])=>[e,fi(t)]));function gi(e,t){for(let[o,r]of Object.entries(e))r===void 0&&t.addIssue({code:n.ZodIssueCode.custom,path:[o],message:"setting must not be undefined"})}var bi=n.object(hi).partial().strict().superRefine(gi),wu=n.discriminatedUnion("section",[n.object({section:n.literal("budget"),project:n.string().min(1).nullish(),value:n.object({daily_usd:n.number().finite().positive(),monthly_usd:n.number().finite().positive()}).nullish()}).superRefine((e,t)=>{e.value==null&&!e.project&&t.addIssue({code:n.ZodIssueCode.custom,path:["value"],message:"a budget write without a value clears a per-project override and requires `project`"})}),n.object({section:n.literal("settings"),value:bi}),n.object({section:n.literal("preferences"),value:n.object({lang:n.enum(["en","zh"])})})]),Su=n.object({provider:n.string().trim().min(1).max(pi).refine(e=>!di.has(e),"provider key is reserved"),windowType:n.string().trim().min(1).nullish(),windowLabel:n.string().trim().min(1).nullish(),enabled:n.boolean(),threshold:n.union([n.number().finite().gt(0).lte(1),n.null()]).optional()}).superRefine((e,t)=>{e.windowLabel&&!e.windowType&&t.addIssue({code:n.ZodIssueCode.custom,path:["windowType"],message:"windowType is required when windowLabel is set"})}),Iu=n.object({}),wi=n.union([n.string(),n.number(),n.boolean(),n.null()]),Eo={event:n.string().min(1),matcher:n.string().optional(),matcherFilters:n.record(n.string(),wi).optional(),script:n.string().min(1).optional(),command:n.string().min(1).optional(),timeoutSec:n.number().finite().positive().optional(),backends:n.array(n.enum(["claude","pi"])).optional(),requiresTool:n.string().min(1).optional(),result:n.enum(["stdout-as-prompt","none"]).optional(),enabled:n.boolean().optional()};function $o(e,t){let o=e.script!==void 0,r=e.command!==void 0;o===r&&t.addIssue({code:n.ZodIssueCode.custom,path:["script"],message:I("ui.hook.exactlyOneRun")})}var yu=n.object({id:n.string().min(1),...Eo}).superRefine($o),xu=n.object({id:n.string().min(1),...Eo}).superRefine($o),vu=n.object({id:n.string().min(1),enabled:n.boolean()}),Eu=n.object({id:n.string().min(1)}),$u=n.object({id:n.string().min(1),payload:n.string()}),Si=vo.pick({backend:!0,provider:!0,model:!0}),ku=n.object({backend:n.enum(["claude","pi"]),provider:n.string().min(1).nullable().optional(),model:n.string().min(1)}).strict(),Cu=n.object({ref:Si,thinking:n.string().nullable()}).strict(),Tu=n.object({selection:xe}).strict(),Ii=e=>new TextEncoder().encode(e).byteLength<=255,yi=e=>e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")&&!e.includes("\0"),xi=n.string().max(240).regex(/^[A-Za-z0-9][A-Za-z0-9_-]*$/),vi=n.string().min(1).refine(Ii).refine(yi),ht=n.string().regex(/^[a-f0-9]{64}$/),Ei=n.object({kind:n.literal("agent"),name:xi,baseHash:ht}),Ru=n.object({target:Ei,pluginIds:n.array(vi),acknowledgeMcp:n.boolean().optional()}),M=n.string().min(1).max(64).regex(/^(?!.*--)[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/),ae={pluginId:M,skill:M},ju=n.object(ae),_u=n.object({...ae,content:n.string().max(512*1024),baseHash:ht}),Pu=n.object({...ae,description:n.string().min(1).max(1024)}),Au=n.object({...ae,toPluginId:M,toSkill:M}),Du=n.object(ae),Ou=n.object(ae),Mu=n.object({id:M,description:n.string().max(1024).optional()}),Lu=n.object({id:M}),Fu=n.object({id:M}),Nu=n.object({pluginId:M}),yo=n.record(n.string().min(1).max(200),n.string().max(4096).nullable()),Uu=n.object({pluginId:M,servers:n.array(n.object({name:n.string().min(1).max(64).regex(/^[A-Za-z0-9][A-Za-z0-9_-]*$/),type:n.enum(["stdio","streamable-http","sse"]),command:n.string().max(1024).optional(),args:n.array(n.string().max(1024)).max(64).optional(),cwd:n.string().max(1024).optional(),url:n.string().max(2048).optional(),env:yo.optional(),headers:yo.optional()})).max(32),baseHash:ht}),ve=n.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]*$/),Bu=n.object({name:ve}),Hu=n.object({name:ve,body:n.record(n.string(),n.unknown())}),Wu=n.object({name:ve,body:n.record(n.string(),n.unknown()),baseHash:n.string().optional()}),Gu=n.object({name:ve}),Vu=n.object({name:ve,text:n.string().max(65536)}),qu=n.object({id:n.string()}),zu=n.object({projectId:n.string(),id:n.string()}),$i=n.string().trim().min(1).max(1e3).refine(e=>!/[\r\n]/.test(e),{error:()=>I("ui.note.oneLine")}),ki=n.object({projectId:n.string(),text:$i}),Xu=ki.extend({id:n.string()}),Yu=n.object({projectId:n.string(),id:n.string(),completed:n.boolean()}),Zu=n.object({projectId:n.string(),id:n.string()}),Ku=n.object({projectId:n.string()}),Ju=n.object({id:n.string(),feedback:n.string().optional()}),Qu=n.object({kind:n.enum(["soft","hard","force"])}),ed=n.object({provider:n.string().optional()}),td=n.object({}),nd=n.object({provider:n.enum(ft),creditId:n.string().min(1).optional()}),od=n.object({}),rd=n.object({}),sd=n.object({}),id=n.object({kind:n.enum(["reconnect-platform","add-machine"]),platform:n.enum(["slack","feishu"]).optional(),machineName:n.string().min(1).optional()}).superRefine((e,t)=>{e.kind==="reconnect-platform"&&e.platform===void 0&&t.addIssue({code:n.ZodIssueCode.custom,path:["platform"],message:"platform is required for kind=reconnect-platform"}),e.kind==="add-machine"&&(e.machineName===void 0||e.machineName.trim()==="")&&t.addIssue({code:n.ZodIssueCode.custom,path:["machineName"],message:I("ui.approval.machineNameRequired")})});export{bo as a,ol as b,rl as c,wo as d,ft as e,il as f,So as g,Io as h,zs as i,Xs as j,Ys as k,Zs as l,Ks as m,Js as n,Qs as o,ei as p,ti as q,ni as r,oi as s,ri as t,si as u,ii as v,ai as w,ci as x,li as y,ui as z,yl as A,xl as B,vl as C,El as D,$l as E,kl as F,Cl as G,Tl as H,Rl as I,jl as J,_l as K,Pl as L,Al as M,Dl as N,Ol as O,Ml as P,Ll as Q,Fl as R,Nl as S,Ul as T,Bl as U,Hl as V,Wl as W,Gl as X,Vl as Y,ql as Z,zl as _,Xl as $,Yl as aa,Zl as ba,Kl as ca,Jl as da,Ql as ea,eu as fa,tu as ga,nu as ha,ou as ia,ru as ja,xe as ka,su as la,iu as ma,au as na,cu as oa,lu as pa,uu as qa,du as ra,pu as sa,mu as ta,fu as ua,hu as va,gu as wa,bu as xa,wu as ya,Su as za,Iu as Aa,yu as Ba,xu as Ca,vu as Da,Eu as Ea,$u as Fa,Si as Ga,ku as Ha,Cu as Ia,Tu as Ja,Ru as Ka,ju as La,_u as Ma,Pu as Na,Au as Oa,Du as Pa,Ou as Qa,Mu as Ra,Lu as Sa,Fu as Ta,Nu as Ua,Uu as Va,Bu as Wa,Hu as Xa,Wu as Ya,Gu as Za,Vu as _a,qu as $a,zu as ab,ki as bb,Xu as cb,Yu as db,Zu as eb,Ku as fb,Ju as gb,Qu as hb,ed as ib,td as jb,nd as kb,od as lb,rd as mb,sd as nb,id as ob,rn as pb,Oi as qb,sn as rb,Mi as sb,J as tb,Gi as ub,je as vb,ze as wb,Ki as xb,Ji as yb,Pi as zb,Ai as Ab,Vo as Bb,ua as Cb,xc as Db,wa as Eb,Sa as Fb,yn as Gb,Ae as Hb,Ia as Ib,ya as Jb,xa as Kb,za as Lb,Ca as Mb,Ze as Nb,ja as Ob,ge as Pb,fr as Qb,La as Rb,Fa as Sb,Na as Tb,Ua as Ub,Ba as Vb,Ha as Wb,Wa as Xb,Ga as Yb,nc as Zb,oc as _b,rc as $b,sc as ac,Me as bc,Un as cc,ic as dc,Bn as ec,Hn as fc,zn as gc,oe as hc,dc as ic,pc as jc,Rc as kc,$ as lc,Lc as mc,Fc as nc,Nc as oc,Uc as pc,Bc as qc,Hc as rc,Wc as sc,Gc as tc,Vc as uc,Yc as vc,go as wc,Us as xc,Qc as yc,Ws as zc,el as Ac};
@@ -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{existsSync as i,readFileSync as n}from"fs";function s(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let r=e;return typeof r.api=="string"&&Array.isArray(r.models)}function c(e){if(!i(e))return{};try{let r=JSON.parse(n(e,"utf8"));if(!r||typeof r!="object"||Array.isArray(r))return{};let t=r.providers;return!t||typeof t!="object"||Array.isArray(t)?{}:t}catch{return{}}}function a(e){let r={};for(let[t,o]of Object.entries(c(e)))s(o)&&(r[t]=o);return r}export{a};
@@ -1,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{c as I}from"./chunk-TAWLERZA.js";import{m as B}from"./chunk-CQLH4UVX.js";import{a as J,b as Y}from"./chunk-Z4H3VDHI.js";import{$ as H,A as k,D as E,F as C,I as P,L,V as x,W as Z,X as D,_ as p,b as f,d as T,e as R,f as g,g as b,h as G,i as W,j as F,o as u,w as _,y as v}from"./chunk-FOQ7VLIL.js";import{a as U,b as z,d as X}from"./chunk-5T7IX5KN.js";import{i as V}from"./chunk-OE4KH3NJ.js";import{a as N}from"./chunk-PFMEUFJ7.js";import{D as j}from"./chunk-DPQPXBTP.js";import{e as O}from"./chunk-NAA7GF6Q.js";import{b as q}from"./chunk-QWAQHHRS.js";var Q=Symbol.for("mcp.completable");function A(o){return!!o&&typeof o=="object"&&Q in o}function ee(o){return o[Q]?.complete}var K;(function(o){o.Completable="McpCompletable"})(K||(K={}));var ce=/^[A-Za-z0-9._-]{1,128}$/;function de(o){let e=[];if(o.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(o.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${o.length})`]};if(o.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),o.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(o.startsWith("-")||o.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(o.startsWith(".")||o.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!ce.test(o)){let t=o.split("").filter(r=>!/[A-Za-z0-9._-]/.test(r)).filter((r,n,a)=>a.indexOf(r)===n);return e.push(`Tool name contains invalid characters: ${t.map(r=>`"${r}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function ue(o,e){if(e.length>0){console.warn(`Tool name validation warning for "${o}":`);for(let t of e)console.warn(` - ${t}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function M(o){let e=de(o);return ue(o,e.warnings),e.isValid}var S=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,r){let n={taskSupport:"required",...t.execution};if(n.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,n,t._meta,r)}};var y=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new J(e,t)}get experimental(){return this._experimental||(this._experimental={tasks:new S(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(h(P)),this.server.assertCanSetRequestHandler(h(L)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(P,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let r={name:e,title:t.title,description:t.description,inputSchema:(()=>{let n=g(t.inputSchema);return n?H(n,{strictUnions:!0,pipeStrategy:"input"}):pe})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let n=g(t.outputSchema);n&&(r.outputSchema=H(n,{strictUnions:!0,pipeStrategy:"output"}))}return r})})),this.server.setRequestHandler(L,async(e,t)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new p(u.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new p(u.InvalidParams,`Tool ${e.params.name} disabled`);let n=!!e.params.task,a=r.execution?.taskSupport,s="createTask"in r.handler;if((a==="required"||a==="optional")&&!s)throw new p(u.InternalError,`Tool ${e.params.name} has taskSupport '${a}' but was not registered with registerToolTask`);if(a==="required"&&!n)throw new p(u.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(a==="optional"&&!n&&s)return await this.handleAutomaticTaskPolling(r,e,t);let i=await this.validateToolInput(r,e.params.arguments,e.params.name),c=await this.executeToolHandler(r,i,t);return n||await this.validateToolOutput(r,c,e.params.name),c}catch(r){if(r instanceof p&&r.code===u.UrlElicitationRequired)throw r;return this.createToolError(r instanceof Error?r.message:String(r))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,t,r){if(!e.inputSchema)return;let a=g(e.inputSchema)??e.inputSchema,s=await T(a,t);if(!s.success){let i="error"in s?s.error:"Unknown error",c=b(i);throw new p(u.InvalidParams,`Input validation error: Invalid arguments for tool ${r}: ${c}`)}return s.data}async validateToolOutput(e,t,r){if(!e.outputSchema||!("content"in t)||t.isError)return;if(!t.structuredContent)throw new p(u.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let n=g(e.outputSchema),a=await T(n,t.structuredContent);if(!a.success){let s="error"in a?a.error:"Unknown error",i=b(s);throw new p(u.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${i}`)}}async executeToolHandler(e,t,r){let n=e.handler;if("createTask"in n){if(!r.taskStore)throw new Error("No task store provided.");let s={...r,taskStore:r.taskStore};if(e.inputSchema){let i=n;return await Promise.resolve(i.createTask(t,s))}else{let i=n;return await Promise.resolve(i.createTask(s))}}if(e.inputSchema){let s=n;return await Promise.resolve(s(t,r))}else{let s=n;return await Promise.resolve(s(r))}}async handleAutomaticTaskPolling(e,t,r){if(!r.taskStore)throw new Error("No task store provided for task-capable tool.");let n=await this.validateToolInput(e,t.params.arguments,t.params.name),a=e.handler,s={...r,taskStore:r.taskStore},i=n?await Promise.resolve(a.createTask(n,s)):await Promise.resolve(a.createTask(s)),c=i.task.taskId,l=i.task,m=l.pollInterval??5e3;for(;l.status!=="completed"&&l.status!=="failed"&&l.status!=="cancelled";){await new Promise(le=>setTimeout(le,m));let d=await r.taskStore.getTask(c);if(!d)throw new p(u.InternalError,`Task ${c} not found during polling`);l=d}return await r.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(h(x)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(x,async e=>{switch(e.params.ref.type){case"ref/prompt":return Z(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return D(e),this.handleResourceCompletion(e,e.params.ref);default:throw new p(u.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,t){let r=this._registeredPrompts[t.name];if(!r)throw new p(u.InvalidParams,`Prompt ${t.name} not found`);if(!r.enabled)throw new p(u.InvalidParams,`Prompt ${t.name} disabled`);if(!r.argsSchema)return w;let a=R(r.argsSchema)?.[e.params.argument.name];if(!A(a))return w;let s=ee(a);if(!s)return w;let i=await s(e.params.argument.value,e.params.context);return re(i)}async handleResourceCompletion(e,t){let r=Object.values(this._registeredResourceTemplates).find(s=>s.resourceTemplate.uriTemplate.toString()===t.uri);if(!r){if(this._registeredResources[t.uri])return w;throw new p(u.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let n=r.resourceTemplate.completeCallback(e.params.argument.name);if(!n)return w;let a=await n(e.params.argument.value,e.params.context);return re(a)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(h(_)),this.server.assertCanSetRequestHandler(h(v)),this.server.assertCanSetRequestHandler(h(k)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(_,async(e,t)=>{let r=Object.entries(this._registeredResources).filter(([a,s])=>s.enabled).map(([a,s])=>({uri:a,name:s.name,...s.metadata})),n=[];for(let a of Object.values(this._registeredResourceTemplates)){if(!a.resourceTemplate.listCallback)continue;let s=await a.resourceTemplate.listCallback(t);for(let i of s.resources)n.push({...a.metadata,...i})}return{resources:[...r,...n]}}),this.server.setRequestHandler(v,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([t,r])=>({name:t,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(k,async(e,t)=>{let r=new URL(e.params.uri),n=this._registeredResources[r.toString()];if(n){if(!n.enabled)throw new p(u.InvalidParams,`Resource ${r} disabled`);return n.readCallback(r,t)}for(let a of Object.values(this._registeredResourceTemplates)){let s=a.resourceTemplate.uriTemplate.match(r.toString());if(s)return a.readCallback(r,s,t)}throw new p(u.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(h(E)),this.server.assertCanSetRequestHandler(h(C)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(E,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?me(t.argsSchema):void 0}))})),this.server.setRequestHandler(C,async(e,t)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new p(u.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new p(u.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let n=g(r.argsSchema),a=await T(n,e.params.arguments);if(!a.success){let c="error"in a?a.error:"Unknown error",l=b(c);throw new p(u.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${l}`)}let s=a.data,i=r.callback;return await Promise.resolve(i(s,t))}else{let n=r.callback;return await Promise.resolve(n(t))}}),this._promptHandlersInitialized=!0)}resource(e,t,...r){let n;typeof r[0]=="object"&&(n=r.shift());let a=r[0];if(typeof t=="string"){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);let s=this._createRegisteredResource(e,void 0,t,n,a);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,void 0,t,n,a);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}registerResource(e,t,r,n){if(typeof t=="string"){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);let a=this._createRegisteredResource(e,r.title,t,r,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let a=this._createRegisteredResourceTemplate(e,r.title,t,r,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}_createRegisteredResource(e,t,r,n,a){let s={name:e,title:t,metadata:n,readCallback:a,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({uri:null}),update:i=>{typeof i.uri<"u"&&i.uri!==r&&(delete this._registeredResources[r],i.uri&&(this._registeredResources[i.uri]=s)),typeof i.name<"u"&&(s.name=i.name),typeof i.title<"u"&&(s.title=i.title),typeof i.metadata<"u"&&(s.metadata=i.metadata),typeof i.callback<"u"&&(s.readCallback=i.callback),typeof i.enabled<"u"&&(s.enabled=i.enabled),this.sendResourceListChanged()}};return this._registeredResources[r]=s,s}_createRegisteredResourceTemplate(e,t,r,n,a){let s={resourceTemplate:r,title:t,metadata:n,readCallback:a,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==e&&(delete this._registeredResourceTemplates[e],l.name&&(this._registeredResourceTemplates[l.name]=s)),typeof l.title<"u"&&(s.title=l.title),typeof l.template<"u"&&(s.resourceTemplate=l.template),typeof l.metadata<"u"&&(s.metadata=l.metadata),typeof l.callback<"u"&&(s.readCallback=l.callback),typeof l.enabled<"u"&&(s.enabled=l.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=s;let i=r.uriTemplate.variableNames;return Array.isArray(i)&&i.some(l=>!!r.completeCallback(l))&&this.setCompletionRequestHandler(),s}_createRegisteredPrompt(e,t,r,n,a){let s={title:t,description:r,argsSchema:n===void 0?void 0:f(n),callback:a,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredPrompts[e],i.name&&(this._registeredPrompts[i.name]=s)),typeof i.title<"u"&&(s.title=i.title),typeof i.description<"u"&&(s.description=i.description),typeof i.argsSchema<"u"&&(s.argsSchema=f(i.argsSchema)),typeof i.callback<"u"&&(s.callback=i.callback),typeof i.enabled<"u"&&(s.enabled=i.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=s,n&&Object.values(n).some(c=>{let l=c instanceof j?c._def?.innerType:c;return A(l)})&&this.setCompletionRequestHandler(),s}_createRegisteredTool(e,t,r,n,a,s,i,c,l){M(e);let m={title:t,description:r,inputSchema:te(n),outputSchema:te(a),annotations:s,execution:i,_meta:c,handler:l,enabled:!0,disable:()=>m.update({enabled:!1}),enable:()=>m.update({enabled:!0}),remove:()=>m.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==e&&(typeof d.name=="string"&&M(d.name),delete this._registeredTools[e],d.name&&(this._registeredTools[d.name]=m)),typeof d.title<"u"&&(m.title=d.title),typeof d.description<"u"&&(m.description=d.description),typeof d.paramsSchema<"u"&&(m.inputSchema=f(d.paramsSchema)),typeof d.outputSchema<"u"&&(m.outputSchema=f(d.outputSchema)),typeof d.callback<"u"&&(m.handler=d.callback),typeof d.annotations<"u"&&(m.annotations=d.annotations),typeof d._meta<"u"&&(m._meta=d._meta),typeof d.enabled<"u"&&(m.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=m,this.setToolRequestHandlers(),this.sendToolListChanged(),m}tool(e,...t){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let r,n,a,s;if(typeof t[0]=="string"&&(r=t.shift()),t.length>1){let c=t[0];if($(c))n=t.shift(),t.length>1&&typeof t[0]=="object"&&t[0]!==null&&!$(t[0])&&(s=t.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(l=>typeof l=="object"&&l!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);s=t.shift()}}let i=t[0];return this._createRegisteredTool(e,void 0,r,n,a,s,{taskSupport:"forbidden"},void 0,i)}registerTool(e,t,r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:n,description:a,inputSchema:s,outputSchema:i,annotations:c,_meta:l}=t;return this._createRegisteredTool(e,n,a,s,i,c,{taskSupport:"forbidden"},l,r)}prompt(e,...t){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let r;typeof t[0]=="string"&&(r=t.shift());let n;t.length>1&&(n=t.shift());let a=t[0],s=this._createRegisteredPrompt(e,void 0,r,n,a);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}registerPrompt(e,t,r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:n,description:a,argsSchema:s}=t,i=this._createRegisteredPrompt(e,n,a,s,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var pe={type:"object",properties:{}};function se(o){return o!==null&&typeof o=="object"&&"parse"in o&&typeof o.parse=="function"&&"safeParse"in o&&typeof o.safeParse=="function"}function oe(o){return"_def"in o||"_zod"in o||se(o)}function $(o){return typeof o!="object"||o===null||oe(o)?!1:Object.keys(o).length===0?!0:Object.values(o).some(se)}function te(o){if(o){if($(o))return f(o);if(!oe(o))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return o}}function me(o){let e=R(o);return e?Object.entries(e).map(([t,r])=>{let n=G(r),a=W(r);return{name:t,description:n,required:!a}}):[]}function h(o){let t=R(o)?.method;if(!t)throw new Error("Schema is missing a method literal");let r=F(t);if(typeof r=="string")return r;throw new Error("Schema method literal must be a string")}function re(o){return{completion:{values:o.slice(0,100),total:o.length,hasMore:o.length>100}}}var w={completion:{values:[],hasMore:!1}};function ne(o,e){let t=o.tool,r=new Map;o.tool=((...s)=>{let i=t.apply(o,s);return i&&(s[0]==="agent"||s[0]==="worker_spawn")&&r.set(s[0],i),i});try{e()}finally{o.tool=t}let n=r.get("worker_spawn");r.get("agent")&&n&&n.update({description:B(n.description??"")})}var ae=O("mcp-bundled"),he=async o=>{let[{registerRemoteOpsTools:e},{registerTimeTools:t},{registerSubagentTools:r}]=await Promise.all([import("./remote-ops-BALZYKH6.js"),import("./time-KEHDQT6K.js"),import("./subagent-E3UC7ZHC.js")]);return n=>{e(n,o),t(n),r(n,o)}},fe=async o=>{let[{registerCostTools:e},{registerExecutionTools:t},{registerContextTools:r},{registerWaitpointTools:n}]=await Promise.all([import("./cost-PGGFI7QJ.js"),import("./executions-6ARGR3IO.js"),import("./context-VCQH5OB6.js"),import("./waitpoint-2FGQBIAC.js")]);return a=>{e(a),t(a),r(a,o),n(a,o)}},ge=async o=>{let[{registerInteractionPlanTools:e,interactionDepsFor:t},{registerInteractionAskTools:r}]=await Promise.all([import("./interaction-plan-E5V42MUP.js"),import("./interaction-ask-G5T3H3CG.js")]),n=t(o);return a=>{e(a,n),r(a,n)}},we=async o=>{let{registerSlackTools:e,slackDepsFor:t}=await import("./slack-WAGSPZUX.js"),r=t(o);return n=>e(n,r)},Te=async o=>{let[{registerFileTools:e},{buildFeishuClientFromEnv:t}]=await Promise.all([import("./file-7BN7RCAY.js"),import("./client-XOGYH5UR.js")]),r=t();return n=>e(n,{client:r,fallbackChannel:o.channel,ctx:o})},Re=async o=>{let[{registerUiFileTools:e},{registerUiViewTools:t},{registerUiDecisionTools:r},{registerUiBoardTools:n}]=await Promise.all([import("./ui-file-GVH53O3X.js"),import("./ui-view-O7PLANT7.js"),import("./ui-decision-U2FXSEC2.js"),import("./ui-board-4GYW6KKW.js")]);return a=>{e(a,o),t(a,o),r(a,o),n(a,o)}},be=async o=>{let{registerWorkerTools:e}=await import("./workers-XN4PSTH6.js");return t=>e(t,o)},Se=async o=>{let{registerWorkerReportTools:e}=await import("./workers-XN4PSTH6.js");return t=>e(t,o)},ye={"cortex-core":he,"cortex-ext":fe,"cortex-interaction-bridge":ge,"cortex-slack":we,"cortex-feishu":Te,"cortex-web":Re,"cortex-workers":be,"cortex-worker-report":Se};function _e(o,e){let t=e instanceof Error?e.message:String(e);ae.error(`Skipping MCP bundle ${o}: ${t}`)}async function ve(o,e,t=(n,a)=>ye[n](a),r=_e){return(await Promise.all(o.map(async a=>{try{let s=await t(a,e);return i=>{try{s(i)}catch(c){r(a,c)}}}catch(s){return r(a,s),null}}))).filter(a=>a!==null)}async function ie(o,e){let t=await ve(o,e),r=new y({name:z,version:N});return V(r,n=>ne(n,()=>t.forEach(a=>a(n))),e.toolAllowlist),r}async function ke(){let o=process.env[U]??process.argv[2],e=X(o);if(e.includes("cortex-ext")){let{executionRepo:r}=await import("./execution-repo-ZLJTBWFC.js");r.follow()}await(await ie(e,I())).connect(new Y)}q(new URL("dist/domain/mcp/bundled-server.js",__cortexPackageRoot).href)&&ke().catch(o=>{ae.error(o),process.exit(1)});async function Ke(o,e){return ie(o,I(e))}export{ve as a,ie as b,ke as c,Ke as d};
@@ -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{I as re,V as K,a as U,b as k,c as ee,g as te,v as ne}from"./chunk-TZFLHVOQ.js";import{a as Z,b as S,c as D,d as L}from"./chunk-5T7IX5KN.js";import{a as q,b as z,f as J,g as Q}from"./chunk-OE4KH3NJ.js";import{a as N}from"./chunk-5M4PFLRW.js";import{b as x}from"./chunk-W5LGYSPZ.js";import{e as E}from"./chunk-NAA7GF6Q.js";import{h as X}from"./chunk-QWAQHHRS.js";import{d as V,e as A,f as T,j as d,l}from"./chunk-J5DVLUKY.js";import{createHash as Re}from"node:crypto";import{chmodSync as oe,mkdirSync as we,readFileSync as He,writeFileSync as ie}from"fs";import*as s from"path";var be=E("config-generator"),xe=s.join(l,"mcp-config.json"),Ne=s.join(l,"mcp-config-core.json"),De=s.join(l,"mcp-config-empty.json"),Le=s.join(l,"mcp-config-interaction.json"),Ue=s.join(l,"mcp-config-slack.json"),ke=s.join(l,"mcp-config-feishu.json"),Ke=s.join(l,"mcp-config-web.json");function Ge(e,t,n){return{command:"node",args:[s.join(t,e)],cwd:t,...n?{env:n}:{}}}function m(e,t){let n=Ge("dist/domain/mcp/bundled-server.js",t);return{...n,args:[...n.args,D(e)]}}function Me(e){return JSON.parse(He(e,"utf8"))}function je(e){let t=e.env?.[Z];if(t!==void 0)return L(t);let n=Array.isArray(e.args)?e.args:[],r=typeof n[0]=="string"?n[0].replaceAll("\\","/"):"";return s.basename(r)==="bundled-server.js"&&typeof n[1]=="string"?L(n[1]):null}function $e(e){let t={external:{},template:null};for(let n of e)for(let[r,o]of Object.entries(n.mcpServers)){if(je(o)===null){t.external[r]=o;continue}t.template??=o}return t}function Fe(e,t,n){let{external:r,template:o}=$e(e);if(!o)return{mcpServers:r};if(r[S])throw new Error(`User MCP server name conflicts with reserved ${S}`);let c=Array.isArray(o.args)?[...o.args]:[];c[1]=D(n);let p={...o.env??{},...t?{[q]:t}:{}};return{mcpServers:{[S]:{...o,args:c,env:p},...r}}}function Ye(e,t,n,r,o){let c=Re("sha256").update(JSON.stringify({configPaths:t,documents:n,encodedAllowlist:r,selectedBundles:o})).digest("hex").slice(0,16);return s.join(e,`mcp-composition-${c}.json`)}function Be(e,t){return Q(e),e.filter(n=>t.has(n))}function Vt(e,t,n=s.join(l,"mcp-tool-gates"),r){if(t===void 0)return[...e];let o=e.map(Me),c=new Set(r.flatMap(Se=>z[Se]??[])),p=Be(J(t),c),W=JSON.stringify(p),ve=Fe(o,W,r);we(n,{recursive:!0,mode:448}),oe(n,448);let b=Ye(n,e,o,W,r);return ie(b,JSON.stringify(ve,null,2),{mode:384}),oe(b,384),[b]}function We(e){return{mcpServers:{"cortex-core":m(["cortex-core","cortex-ext"],e)}}}function Ve(e){return{mcpServers:{"cortex-core":m(["cortex-core"],e)}}}function Xe(){return{mcpServers:{}}}function qe(e){return{mcpServers:{"cortex-interaction-bridge":m(["cortex-interaction-bridge"],e)}}}function ze(e){return{mcpServers:{"cortex-slack":m(["cortex-slack"],e)}}}function Je(e){return{mcpServers:{"cortex-feishu":m(["cortex-feishu"],e)}}}function Qe(e){return{mcpServers:{"cortex-web":m(["cortex-web"],e)}}}function Xt(){let e=[["full",xe,We(A)],["core",Ne,Ve(A)],["empty",De,Xe()],["interaction",Le,qe(A)],["Slack",Ue,ze(A)],["Feishu",ke,Je(A)],["Web",Ke,Qe(A)]];for(let[t,n,r]of e)ie(n,JSON.stringify(r,null,2)),be.info(`Generated ${t} MCP config at ${n}`)}import{fileURLToPath as Ze}from"node:url";import{spawn as et}from"child_process";import{createWriteStream as tt,mkdirSync as ce,existsSync as nt}from"fs";import*as w from"path";import*as ue from"http";import{createRequire as rt}from"module";var ot=E("gateway-mgr"),O=d.url,nn=rt(new URL("dist/domain/costs/gateway-manager.js",__cortexPackageRoot).href),it=Ze(new URL("vendor/aistatus/",__cortexPackageRoot)),G=w.join(it,"gateway-cli.js"),le=w.join(T,"logs"),at=w.join(le,"gateway.log"),M=1e3,st=3e4,ct=1e4,ae=3e4,ut=5e3,u=null,fe=0,h=M,C=null,R=null,y=!1,f=!1,g=null;function i(e){ot.info(e);try{let t=new Date().toLocaleTimeString("en-GB",{hour12:!1});pe().write(`[gateway-mgr ${t}] ${e}
5
- `)}catch{}}function pe(){return g||(ce(le,{recursive:!0}),g=tt(at,{flags:"a"})),g}var lt=globalThis.__mockHttpGet||ue.get,ft=globalThis.__mockChildProcessSpawn||et;function j(){return new Promise(e=>{let t=lt(`${O}/status`,{timeout:ut},n=>{let r="";n.on("data",o=>{r+=o}),n.on("end",()=>{e(n.statusCode===200)})});t.on("error",()=>e(!1)),t.on("timeout",()=>{t.destroy(),e(!1)})})}async function pt(){if(y||!u&&!f)return;let e=f;f=await j(),e&&!f?i("Health check failed \u2014 gateway may be unresponsive"):!e&&f&&i("Health check passed \u2014 gateway is responsive")}function _e(){return se!==null?se:f}async function _t(){return await j()?(f=!0,h=M,i(`Gateway already healthy on ${O} \u2014 reusing existing process`),!0):!1}async function de(){if(!y){if(u){i("spawnGateway called but child already running \u2014 skipping");return}if(!nt(G)){i(`Gateway CLI not found at ${G} \u2014 cannot start gateway`);return}await _t()||At()}}function dt(){return d.home?(ce(d.home,{recursive:!0}),{...process.env,HOME:d.home,USERPROFILE:d.home}):{...process.env}}function At(){i("Starting aistatus gateway (TS)..."),fe=Date.now(),f=!1;let e=pe();u=ft(process.execPath,[G,"start","-c",d.configPath,"-p",String(d.port)],{cwd:T,stdio:["ignore","pipe","pipe"],detached:!1,env:dt()}),u.stdout?.on("data",t=>{e.write(t)}),u.stderr?.on("data",t=>{e.write(t)}),i(`Gateway started \u2014 PID ${u.pid}`),u.on("exit",Et),setTimeout(mt,2e3)}function Et(e,t){let n=u?.pid;if(u=null,f=!1,y){i(`Gateway exited (shutdown) \u2014 PID ${n}`);return}Date.now()-fe>ct&&(h=M),i(t?`Gateway killed by signal ${t} \u2014 PID ${n}`:`Gateway exited with code ${e} \u2014 PID ${n}`),i(`Restarting gateway in ${h}ms...`),C=setTimeout(()=>{C=null,de()},h),h=Math.min(h*2,st)}async function mt(){u&&(f=await j(),i(f?"Gateway is healthy after startup":"Gateway not yet healthy after startup (will retry via periodic check)"))}function ht(){return new Promise(e=>{if(!u)return e();let t=u;i(`Stopping gateway (PID ${t.pid})...`);let n=setTimeout(()=>{i("Force killing gateway...");try{t.kill("SIGKILL")}catch{}},5e3);t.once("exit",()=>{clearTimeout(n),e()}),t.kill("SIGTERM")})}function rn(){y=!1,de(),R=setInterval(pt,ae),i(`Gateway manager started (health check interval: ${ae/1e3}s)`)}async function on(){y=!0,C&&(clearTimeout(C),C=null),R&&(clearInterval(R),R=null),await ht(),g&&(g.end(),g=null),i("Gateway manager stopped")}var se=null;var gt=[[/(?:\blogin_required\b|please\s+run\s+\/login\b)/i,"login_required"],[/(?:\boauth_expired\b|oauth\s+(?:token|session)\s+(?:has\s+)?expired\b)/i,"oauth_expired"],[/(?:\bauthentication_error\b|\bauthentication\b|\binvalid[_ -]api[_ -]key\b|\binvalid\s+x-api-key\b)/i,"invalid_api_key"],[/(?:\bunauthorized\b|\b401\b)/i,"unauthorized"],[/\binvalid_grant\b/i,"invalid_grant"]],I=null,$=new Set;function Ae(e,t){return`${e}:${t}`}function sn(e){for(let[t,n]of gt)if(t.test(e))return n;return null}function cn(e){I=e,$.clear()}function un(e){I&&($.add(Ae(e.backend,e.provider)),I.publish({type:"auth.required",...e}))}function ln(e){!I||!$.delete(Ae(e.backend,e.provider))||I.publish({type:"auth.recovered",...e})}import*as Ee from"node:path";var me=Ee.join(l,".env");function he(){let e=ee(),n=U(process.env.CLAUDE_CODE_OAUTH_TOKEN)||e.CLAUDE_CODE_OAUTH_TOKEN,r=n!==void 0&&n===e.CLAUDE_CODE_OAUTH_TOKEN;return{ANTHROPIC_API_KEY:k(process.env.ANTHROPIC_API_KEY)||e.ANTHROPIC_API_KEY,ANTHROPIC_BASE_URL:U(process.env.ANTHROPIC_BASE_URL)||e.ANTHROPIC_BASE_URL,CLAUDE_CODE_OAUTH_TOKEN:n,CLAUDE_CODE_OAUTH_TOKEN_EXPIRES_AT:r?e.CLAUDE_CODE_OAUTH_TOKEN_EXPIRES_AT:void 0}}var _=he();function H(){let e=he();return e.ANTHROPIC_API_KEY&&(_.ANTHROPIC_API_KEY=e.ANTHROPIC_API_KEY),e.ANTHROPIC_BASE_URL&&(_.ANTHROPIC_BASE_URL=e.ANTHROPIC_BASE_URL),_.CLAUDE_CODE_OAUTH_TOKEN=e.CLAUDE_CODE_OAUTH_TOKEN,_.CLAUDE_CODE_OAUTH_TOKEN_EXPIRES_AT=e.CLAUDE_CODE_OAUTH_TOKEN?e.CLAUDE_CODE_OAUTH_TOKEN_EXPIRES_AT:void 0,{..._}}function Tt(e){let t=k(e);if(!t||/[\s"\\]/.test(t))throw new Error("Enter a valid Anthropic API key.");return t}function Y(e,t){return new RegExp(`^[ \\t]*(?:export[ \\t]+)?${e}[ \\t]*=.*$`,t)}function Ct(e,t,n){let r=`${t}=${JSON.stringify(n)}`;if(Y(t,"m").test(e))return e.replace(Y(t,"gm"),r);let c=e.length===0||e.endsWith(`
6
- `)?"":`
7
- `;return`${e}${c}${r}
8
- `}function Ot(e,t){let n=Y(t,"gm");return e.replace(new RegExp(`${n.source}(?:\\r?\\n|$)`,"gm"),"")}async function yt(e,t){await x(me,n=>Ct(n,e,t),{mode:384})}async function ge(e){await x(me,t=>e.reduce(Ot,t),{mode:384})}async function An(e){let t=Tt(e);await yt("ANTHROPIC_API_KEY",t),_.ANTHROPIC_API_KEY=t,process.env.ANTHROPIC_API_KEY=t}async function En(){await ge(["ANTHROPIC_API_KEY"]),_.ANTHROPIC_API_KEY=void 0,delete process.env.ANTHROPIC_API_KEY}async function mn(){await ge(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN_EXPIRES_AT"]),_.CLAUDE_CODE_OAUTH_TOKEN=void 0,_.CLAUDE_CODE_OAUTH_TOKEN_EXPIRES_AT=void 0,delete process.env.CLAUDE_CODE_OAUTH_TOKEN}function It(e){return te()?null:e.CLAUDE_CODE_OAUTH_TOKEN??null}function F(e,t){t!==void 0&&(t===null?delete process.env[e]:process.env[e]=t)}function hn(){let e=H(),t=It(e);F("ANTHROPIC_API_KEY",e.ANTHROPIC_API_KEY??null),F("CLAUDE_CODE_OAUTH_TOKEN",t),t===null&&F("CLAUDE_CODE_OAUTH_TOKEN_EXPIRES_AT",null)}var Pt=E("mode-env");function vt(e,t){if(t&&Object.keys(t).length>0){let n=Object.entries(t).map(([r,o])=>`${encodeURIComponent(r)}=${encodeURIComponent(o)}`).join(",");return`${O}/m/${e}/${n}/anthropic`}return`${O}/m/${e}/anthropic`}function St(e,t){let n=vt(e,t);if(e==="plan")return{ANTHROPIC_BASE_URL:n,ANTHROPIC_API_KEY:null};let r=H();return{ANTHROPIC_BASE_URL:n,ANTHROPIC_API_KEY:r.ANTHROPIC_API_KEY||X}}function Rt(e){if(e==="plan")return{ANTHROPIC_API_KEY:null};let t=H();return{ANTHROPIC_BASE_URL:t.ANTHROPIC_BASE_URL,ANTHROPIC_API_KEY:t.ANTHROPIC_API_KEY||null,CLAUDE_CODE_OAUTH_TOKEN:t.CLAUDE_CODE_OAUTH_TOKEN||null}}function Te(e,t){return _e()?St(e,t):(Pt.debug(`Gateway unhealthy \u2014 using direct Anthropic connection (mode=${e})`),Rt(e))}function wn(e={}){let t=e.selection??e.session?.selection??re(e.channel??void 0)??K(),n=e.session;if((n?.backendSessionId===void 0?n?.sessionId:n.backendSessionId)&&n?.backend&&t.backend!==n.backend)throw new Error(`Cannot resume ${n.backend} session on ${t.backend} backend`);return t}function Hn(){return ne.readIfPresent()?.default?K():null}function wt(e,t={}){let n={};return t.project&&(n.project=t.project),t.trigger&&(n.trigger=t.trigger),Te(e.mode||"api",Object.keys(n).length?n:void 0)}function bn(e,t){let{project:n,trigger:r,routeTrigger:o}=e.context;return wt(t,{project:n,trigger:o??r})}import v from"node:path";import P from"node:fs";import a from"node:path";function Ln(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ce(e,t){let n=a.resolve(e),r=a.resolve(t);return r===n||r.startsWith(n+a.sep)}function B(e){try{return P.lstatSync(e),!0}catch{return!1}}function Ht(e){let t=[],n=a.resolve(e);for(;!B(n);){let r=a.dirname(n);if(r===n)return null;t.unshift(a.basename(n)),n=r}return{base:n,tail:t}}function bt(e,t){return t.reduce((n,r)=>a.join(n,r),e)}function Oe(e){try{return P.realpathSync(e)}catch{return null}}function xt(e){let t=Ht(e),n=t?Oe(t.base):null;return n&&t?bt(n,t.tail):null}function Nt(e,t){let n=a.relative(a.resolve(e),a.resolve(t));return n===""?[]:n===".."||n.startsWith(`..${a.sep}`)||a.isAbsolute(n)?null:n.split(a.sep).filter(Boolean)}function Dt(e,t,n){let r=a.join(t,n);if(!B(r))return r;let o=Oe(r);return o&&Ce(e,o)?o:null}function Lt(e,t){return Ce(e,t)?t:null}function Ut(e,t){let n=xt(e),r=Nt(e,t);if(!n||!r)return null;let o=n;for(let c of r)if(o=Dt(n,o,c),!o)return null;return Lt(n,o)}function Un(e,t){return Ut(e,a.resolve(e,t))}function kn(e){try{return P.statSync(e).isFile()}catch{return!1}}function Kn(e){try{return P.statSync(e).isDirectory()}catch{return!1}}function ye(e){return B(e)?P.readdirSync(e,{withFileTypes:!0}).filter(n=>n.isDirectory()||n.isSymbolicLink()).map(n=>n.name).sort():[]}var Pe=v.join(V,"plugins");function kt(){return N()?Pe:null}function Kt(e=kt()){return e?ye(e):[]}function Gt(e){return v.posix.join("plugins",e)}function Mt(e){return e.skills!==!1&&N()}function Ie(e,t){return v.isAbsolute(e)?v.resolve(e):v.resolve(t,e)}function Yn(e,t={}){let n=t.dataDir??T,r=(e.pluginDirs??[]).map(p=>Ie(p,n));if(!Mt(e))return e.pluginDirs?r:void 0;let o=new Set(e.disabledPlugins??[]),c=(t.builtinIds??Kt(Pe)).filter(p=>!o.has(p)).map(p=>Ie(Gt(p),n));return[...new Set([...r,...c])]}export{Vt as a,We as b,Ve as c,Xe as d,qe as e,Xt as f,O as g,rn as h,on as i,Ln as j,Ce as k,B as l,Oe as m,Ut as n,Un as o,kn as p,Kn as q,ye as r,kt as s,Kt as t,Mt as u,Yn as v,sn as w,cn as x,un as y,ln as z,H as A,An as B,En as C,mn as D,hn as E,wn as F,Hn as G,wt as H,bn as I};
@@ -1,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- var s=(e=>(e.OPERATIONAL="operational",e.DEGRADED="degraded",e.DOWN="down",e.UNKNOWN="unknown",e))(s||{}),t=class{provider;status;statusDetail;model;alternatives;constructor(e){this.provider=e.provider,this.status=e.status,this.statusDetail=e.statusDetail??null,this.model=e.model??null,this.alternatives=e.alternatives??[]}get isAvailable(){return this.status==="operational"}},a=class{content;modelUsed;providerUsed;wasFallback;fallbackReason;inputTokens;outputTokens;cacheCreationInputTokens;cacheReadInputTokens;costUsd;raw;constructor(e){this.content=e.content,this.modelUsed=e.modelUsed,this.providerUsed=e.providerUsed,this.wasFallback=e.wasFallback,this.fallbackReason=e.fallbackReason??null,this.inputTokens=e.inputTokens??0,this.outputTokens=e.outputTokens??0,this.cacheCreationInputTokens=e.cacheCreationInputTokens??0,this.cacheReadInputTokens=e.cacheReadInputTokens??0,this.costUsd=e.costUsd??0,this.raw=e.raw??null}toString(){return this.content}};export{s as a,t as b,a 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
- var f=[161,161,164,164,167,168,170,170,173,174,176,180,182,186,188,191,198,198,208,208,215,216,222,225,230,230,232,234,236,237,240,240,242,243,247,250,252,252,254,254,257,257,273,273,275,275,283,283,294,295,299,299,305,307,312,312,319,322,324,324,328,331,333,333,338,339,358,359,363,363,462,462,464,464,466,466,468,468,470,470,472,472,474,474,476,476,593,593,609,609,708,708,711,711,713,715,717,717,720,720,728,731,733,733,735,735,768,879,913,929,931,937,945,961,963,969,1025,1025,1040,1103,1105,1105,8208,8208,8211,8214,8216,8217,8220,8221,8224,8226,8228,8231,8240,8240,8242,8243,8245,8245,8251,8251,8254,8254,8308,8308,8319,8319,8321,8324,8364,8364,8451,8451,8453,8453,8457,8457,8467,8467,8470,8470,8481,8482,8486,8486,8491,8491,8531,8532,8539,8542,8544,8555,8560,8569,8585,8585,8592,8601,8632,8633,8658,8658,8660,8660,8679,8679,8704,8704,8706,8707,8711,8712,8715,8715,8719,8719,8721,8721,8725,8725,8730,8730,8733,8736,8739,8739,8741,8741,8743,8748,8750,8750,8756,8759,8764,8765,8776,8776,8780,8780,8786,8786,8800,8801,8804,8807,8810,8811,8814,8815,8834,8835,8838,8839,8853,8853,8857,8857,8869,8869,8895,8895,8978,8978,9312,9449,9451,9547,9552,9587,9600,9615,9618,9621,9632,9633,9635,9641,9650,9651,9654,9655,9660,9661,9664,9665,9670,9672,9675,9675,9678,9681,9698,9701,9711,9711,9733,9734,9737,9737,9742,9743,9756,9756,9758,9758,9792,9792,9794,9794,9824,9825,9827,9829,9831,9834,9836,9837,9839,9839,9886,9887,9919,9919,9926,9933,9935,9939,9941,9953,9955,9955,9960,9961,9963,9969,9972,9972,9974,9977,9979,9980,9982,9983,10045,10045,10102,10111,11094,11097,12872,12879,57344,63743,65024,65039,65533,65533,127232,127242,127248,127277,127280,127337,127344,127373,127375,127376,127387,127404,917760,917999,983040,1048573,1048576,1114109],m=12288,d=65510,h=[12288,12288,65281,65376,65504,65510];var x=4352,w=262141,s=[4352,4447,8986,8987,9001,9002,9193,9196,9200,9200,9203,9203,9725,9726,9748,9749,9776,9783,9800,9811,9855,9855,9866,9871,9875,9875,9889,9889,9898,9899,9917,9918,9924,9925,9934,9934,9940,9940,9962,9962,9970,9971,9973,9973,9978,9978,9981,9981,9989,9989,9994,9995,10024,10024,10060,10060,10062,10062,10067,10069,10071,10071,10133,10135,10160,10160,10175,10175,11035,11036,11088,11088,11093,11093,11904,11929,11931,12019,12032,12245,12272,12287,12289,12350,12353,12438,12441,12543,12549,12591,12593,12686,12688,12773,12783,12830,12832,12871,12880,42124,42128,42182,43360,43388,44032,55203,63744,64255,65040,65049,65072,65106,65108,65126,65128,65131,94176,94180,94192,94198,94208,101589,101631,101662,101760,101874,110576,110579,110581,110587,110589,110590,110592,110882,110898,110898,110928,110930,110933,110933,110948,110951,110960,111355,119552,119638,119648,119670,126980,126980,127183,127183,127374,127374,127377,127386,127488,127490,127504,127547,127552,127560,127568,127569,127584,127589,127744,127776,127789,127797,127799,127868,127870,127891,127904,127946,127951,127955,127968,127984,127988,127988,127992,128062,128064,128064,128066,128252,128255,128317,128331,128334,128336,128359,128378,128378,128405,128406,128420,128420,128507,128591,128640,128709,128716,128716,128720,128722,128725,128728,128732,128735,128747,128748,128756,128764,128992,129003,129008,129008,129292,129338,129340,129349,129351,129535,129648,129660,129664,129674,129678,129734,129736,129736,129741,129756,129759,129770,129775,129784,131072,196605,196608,262141];var a=(t,i)=>{let n=0,e=Math.floor(t.length/2)-1;for(;n<=e;){let r=Math.floor((n+e)/2),o=r*2;if(i<t[o])e=r-1;else if(i>t[o+1])n=r+1;else return!0}return!1};var p=19968,[c,R]=W(s);function W(t){let i=t[0],n=t[1];for(let e=0;e<t.length;e+=2){let r=t[e],o=t[e+1];if(p>=r&&p<=o)return[r,o];o-r>n-i&&(i=r,n=o)}return[i,n]}var g=t=>t<161||t>1114109?!1:a(f,t),u=t=>t<m||t>d?!1:a(h,t);var l=t=>t>=c&&t<=R?!0:t<x||t>w?!1:a(s,t);function b(t){if(!Number.isSafeInteger(t))throw new TypeError(`Expected a code point, got \`${typeof t}\`.`)}function H(t,{ambiguousAsWide:i=!1}={}){return b(t),u(t)||l(t)||i&&g(t)?2:1}export{u as a,l as b,H as c};
@@ -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 t}from"./chunk-PMG4YGDU.js";import{e}from"./chunk-E7ZMYIY6.js";function r(){return["Initialize Cortex data directory","","Usage: cortex init [--home <path>] [--gateway-config-dir <path>] [--force] [--answers <file>] [--json]","","Creates the CORTEX_HOME directory structure and asks for the language, interaction","platform (Slack / Feishu), machine name, usage reporting and system service.","Writes .env, copies default configs and generates mcp-config*.json, machines.json","and agent-state.json. It then detects provider logins, offers to log in, and sets","up gateway routes, the default model and favorites.","","Options:"," --home <path> Set CORTEX_HOME (default: $CORTEX_HOME or ~/.cortex/)"," --gateway-config-dir <path> Gateway config output directory (default: gateway home/.aistatus/)"," --force Overwrite existing configs (.env, budget.json, agent-state.json, etc.)"," --answers <file> Read answers from a JSON file instead of prompting; omitted fields use defaults"," --json Print NDJSON progress events on stdout and send human output to stderr"," --help, -h Show this help","","With --answers or --json, init does not prompt or start provider login; it reports","credential status and can finish before any provider is set up.","","Examples:"," cortex init"," cortex init --home /data/cortex"," cortex init --answers answers.json --json"].join(`
5
- `)}function s(){return["Auto-detect Claude Code / PI configurations and generate gateway.yaml + models.json","","Usage: cortex setup-gateway [--dry-run] [--output-dir <path>]","","Discovers backend endpoints from local Claude Code and PI configs, then","writes gateway.yaml (with backup) and $CORTEX_HOME/config/models.json.","Gateway settings: CORTEX_GATEWAY_PORT (9880) and CORTEX_GATEWAY_HOME (OS home).","Both read config/.env; gateway.yaml lives in <gateway home>/.aistatus/.","Without flags, this command writes files in place.","","Options:"," --dry-run Print the generated gateway.yaml to stdout without writing anything"," --output-dir <path> Write gateway.yaml and models.json under <path> instead of the defaults"," --help, -h Show this help"].join(`
6
- `)}function c(){return["Start the Cortex TUI (terminal UI) client","","Usage: cortex tui [options]","","Connects to a running Cortex daemon via WebSocket and opens","a terminal-based chat interface.","","Options:"," --resume Open the resume-session picker on connect"," --project <id> Start a fresh session in the named project"," --port <n> Override TUI port (default: 3003, or CORTEX_TUI_PORT)"," --help, -h Show this help"].join(`
7
- `)}function d(){return t({name:"cortex ui",description:"Manage the Web UI endpoint used by the Cortex apps and browsers",usage:"cortex ui <enable|pair> [--port <port>] [--home <path>] [--json]",commands:[{name:"enable",description:"Turn on the loopback Web UI endpoint and print how to reach it"},{name:"pair",description:"Print a one-time pairing code (10 minutes) for a new app or browser"}],options:[{flag:"--port <port>",description:"enable: TCP port to serve the Web UI on",default:"the configured CORTEX_UI_PORT, else 3004"},{flag:"--home <path>",description:"CORTEX_HOME to use",default:"$CORTEX_HOME or ~/.cortex"},{flag:"--json",description:"Print the result as JSON (enable: endpoint, token, change state; pair: code, expiry)"},{flag:"--help, -h",description:"Show this help"}],examples:[{description:"Enable the endpoint, keeping the configured port",command:"cortex ui enable"},{description:"Serve on another port",command:"cortex ui enable --port 4000"},{description:"Machine-readable output for the desktop setup flow",command:"cortex ui enable --json"},{description:"Get a code to connect a phone or another computer",command:"cortex ui pair"}]})}function m(){return t({name:"cortex path",description:"Make this install's commands (cortex, cortex-signal, \u2026) available in new terminals",usage:"cortex path <install|remove|status> [--home <path>] [--dry-run] [--json]",commands:[{name:"install",description:"Write launchers that use this install's Node into <home>/runtime/bin and put that directory on PATH (shell profiles on Linux/macOS, the user Path on Windows)"},{name:"remove",description:"Delete the launchers and undo the PATH change"},{name:"status",description:"Show whether the launchers exist, are current, and are on PATH"}],options:[{flag:"--home <path>",description:"CORTEX_HOME the launchers belong to",default:"$CORTEX_HOME or ~/.cortex"},{flag:"--dry-run",description:"Report what install or remove would change and change nothing"},{flag:"--json",description:"Print the result as JSON"},{flag:"--help, -h",description:"Show this help"}],examples:[{description:"Add cortex to new terminals",command:"cortex path install"},{description:"Preview the change",command:"cortex path install --dry-run --json"},{description:"Check the current state",command:"cortex path status"},{description:"Undo it",command:"cortex path remove"}]})}function p(){return t({name:"cortex client",description:"Manage the cortex-client installs on remote machines",usage:"cortex client remove --device <name> [--keep-remote] [--dry-run] [--home <path>]",commands:[{name:"remove",description:"Unregister a machine from machines.json, stop and uninstall its client over SSH, and drop its runtime state"}],options:[{flag:"--device <name>",description:"Machine name as registered in machines.json (required)"},{flag:"--keep-remote",description:"Only unregister locally; leave the remote process and files alone"},{flag:"--dry-run",description:"Print what would be removed as JSON and change nothing"},{flag:"--home <path>",description:"CORTEX_HOME of the server",default:"$CORTEX_HOME or ~/.cortex"},{flag:"--help, -h",description:"Show this help"}],examples:[{description:"Preview the removal",command:"cortex client remove --device trainer --dry-run"},{description:"Remove a machine and uninstall its client",command:"cortex client remove --device trainer"},{description:"Unregister a machine that no longer exists",command:"cortex client remove --device trainer --keep-remote"}]})}function l(){return t({name:"cortex memory",description:`Project memory under $CORTEX_HOME/context/projects (experiments/, knowledge/, patterns/).
8
- regen rewrites only the generated index.md files; the EXP/K/PAT files are never modified. Output is JSON.`,usage:"cortex memory <command> [--project <name>]... [options]",commands:[{name:"regen",description:"Rebuild experiments/knowledge/patterns index.md from frontmatter and the access log"},{name:"consolidate",description:"Report contradictions, stale entries, anti-pattern signals and consolidation candidates"}],options:[{flag:"--project <name>",description:"Limit to one project; repeat for several",default:"every project with memory directories"},{flag:"--text",description:"consolidate: print a human-readable summary instead of JSON"},{flag:"--help, -h",description:"Show this help"}],examples:[{description:"Rebuild every index",command:"cortex memory regen"},{description:"Rebuild one project's indexes",command:"cortex memory regen --project wm-align"},{description:"Lifecycle report for all projects",command:"cortex memory consolidate --text"},{description:"Lifecycle report as JSON for one project",command:"cortex memory consolidate --project wm-align"}]})}function h(){return t({name:"cortex schedule",description:`Manage scheduled tasks. Each fire opens a new session in the schedule's project and sends it the message.
9
- Changes land in schedules.json; a running daemon picks them up within a second. Output is JSON.`,usage:"cortex schedule <command> [<id>] [options]",commands:[{name:"list",description:"List schedules (--project to filter)"},{name:"get <id>",description:"Show one schedule"},{name:"add --type <type>",description:"Create a schedule"},{name:"edit <id>",description:"Change message, project, model, thinking, pre-check or timing (the type is fixed)"},{name:"pause <id>",description:"Pause a recurring schedule"},{name:"resume <id>",description:"Resume a paused schedule"},{name:"remove <id>",description:"Delete a schedule (--dry-run to preview)"}],options:[{flag:"--type <type>",description:"add: interval | daily | weekly | once"},{flag:"--interval <duration>",description:"interval: repeat period, e.g. 30m, 2h, 1d"},{flag:"--time <HH:MM>",description:"daily/weekly: time of day, 24-hour, server local time"},{flag:"--day <day>",description:"weekly: sun..sat or 0-6"},{flag:"--delay <duration>",description:"once: fire this long from now, e.g. 90m, 2h"},{flag:"--message <text|->",description:'Prompt for the fired session; "-" reads stdin'},{flag:"--project <id>",description:"Project the fired session belongs to",default:"general"},{flag:"--model [provider/]model",description:"Model to run",default:"the default model"},{flag:"--thinking <level>",description:"Thinking level for the selected model"},{flag:"--pre-check <cmd>",description:"Shell gate run before each fire; non-zero exit skips it"},{flag:"--idempotency-key <key>",description:"add: return the schedule already created with this key"},{flag:"--dry-run",description:"remove: show what would be removed"},{flag:"--help, -h",description:"Show this help"}],examples:[{description:"Every 30 minutes in a project",command:'cortex schedule add --type interval --interval 30m --project nimbus --message "Check GPU usage on lab2 and report a one-line summary"'},{description:"Every day at 09:00",command:`cortex schedule add --type daily --time 09:00 --message "Summarize yesterday's sessions"`},{description:"Every Monday at 21:00",command:'cortex schedule add --type weekly --day mon --time 21:00 --message "Weekly review"'},{description:"Once, two hours from now, prompt from stdin",command:'echo "Check training run r42 on lab2" | cortex schedule add --type once --delay 2h --message -'},{description:"List one project's schedules",command:"cortex schedule list --project nimbus"},{description:"Move a daily schedule to 10:30",command:"cortex schedule edit a1b2c3d4 --time 10:30"},{description:"Preview a removal",command:"cortex schedule remove a1b2c3d4 --dry-run"}]})}function n(){return[{name:"init",description:"Initialize CORTEX_HOME directory with configs and API keys"},{name:"start",description:"Start the Cortex server (node dist/entry/app.js)"},{name:"daemon",description:"Start daemon mode with file watching and auto-restart"},{name:"daemon stop",description:"Stop the running daemon (SIGTERM) and the local client it launched"},{name:"daemon status",description:"Check daemon + child status (PID, uptime)"},{name:"daemon restart",description:"Graceful restart \u2014 signal daemon to drain and respawn app.js"},{name:"daemon restart --hard",description:"Hard restart \u2014 send SIGTERM directly to app.js (daemon auto-recovers)"},{name:"daemon restart --force",description:"Force restart \u2014 send SIGKILL immediately to app.js"},{name:"daemon restart-self",description:"Stop and restart the daemon process itself"},{name:"restart",description:"Legacy alias for daemon restart (touches $STORE_DIR/.restart)"},{name:"install latest",description:"Install the latest version of Cortex from npm"},{name:"config",description:"Show resolved paths and initialization status"},{name:"doctor",description:"Health-check the install (runtime, login, platform, gateway); --fix to repair"},{name:"auth status",description:e("cmd.auth.cli.statusDescription")},{name:"feishu",description:"Manage Feishu user-identity login (login / status / logout)"},{name:"setup-gateway",description:"Auto-detect Claude/PI configs and generate gateway.yaml + models.json"},{name:"ui enable",description:"Enable the local Web UI endpoint the desktop app connects to"},{name:"client remove",description:"Unregister a remote machine and uninstall its cortex-client"},{name:"path install",description:"Make cortex available in new terminals (remove / status to undo or check)"},{name:"schedule",description:"List, add, edit, pause, resume and remove scheduled tasks"},{name:"memory",description:"Rebuild project memory indexes; report knowledge lifecycle findings"},{name:"tui",description:"Start the Terminal UI (TUI) client for local interaction"}]}function o(){return[{description:"Interactive init",command:"cortex init"},{description:"Init to custom directory",command:"cortex init --home /tmp/my-cortex"},{description:"Show resolved paths",command:"cortex config"},{description:"Health-check the install",command:"cortex doctor"},{description:e("cmd.auth.cli.exampleSummary"),command:"cortex auth status"},{description:e("cmd.auth.cli.exampleJson"),command:"cortex auth status --json"},{description:"Diagnose and auto-repair",command:"cortex doctor --fix"},{description:"Re-generate gateway config",command:"cortex setup-gateway"},{description:"Enable the local Web UI endpoint",command:"cortex ui enable"},{description:"Remove a remote machine and its client",command:"cortex client remove --device trainer"},{description:"Add cortex to new terminals",command:"cortex path install"},{description:"List scheduled tasks",command:"cortex schedule list"},{description:"Rebuild every project memory index",command:"cortex memory regen"},{description:"Start the server",command:"cortex start"},{description:"Stop the daemon",command:"cortex daemon stop"},{description:"Check daemon status",command:"cortex daemon status"},{description:"Graceful restart",command:"cortex daemon restart"},{description:"Hard restart app.js",command:"cortex daemon restart --hard"},{description:"Restart daemon itself",command:"cortex daemon restart-self"}]}function u(){return t({name:"cortex",description:"Cortex CLI \u2014 server management and initialization",usage:"cortex <command> [options]",commands:n(),options:[{flag:"--help, -h",description:"Show this help"}],examples:o()})}function g(){return t({name:"cortex auth",description:e("cmd.auth.cli.description"),usage:"cortex auth <status|login|provider> [options]",commands:[{name:"status",description:e("cmd.auth.cli.statusDescription")},{name:"login",description:e("init.auth.loginDescription")},{name:"provider",description:e("provider.cli.description")}],options:[{flag:"--json",description:e("cmd.auth.cli.jsonDescription")},{flag:"--help, -h",description:e("cmd.auth.cli.helpDescription")}],examples:[{description:e("cmd.auth.cli.exampleSummary"),command:"cortex auth status"},{description:e("cmd.auth.cli.exampleJson"),command:"cortex auth status --json"},{description:e("provider.cli.exampleList"),command:"cortex auth provider list"}],labels:{usage:e("cmd.auth.cli.helpUsage"),commands:e("cmd.auth.cli.helpCommands"),options:e("cmd.auth.cli.helpOptions"),examples:e("cmd.auth.cli.helpExamples")}})}export{r as a,s as b,c,d,m as e,p as f,l as g,h,u as i,g 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
- function a(t){let e=(t.CORTEX_UI_HTTP||"").trim().toLowerCase();return e==="1"||e==="true"||e==="on"||e==="yes"}async function m(t){if(!a(process.env))return null;let{startUiHttpServer:e}=await import("./start-ui-http-QALT7C3P.js");return e({uiService:t})}import{accessSync as c,constants as p,realpathSync as u,statSync as l}from"node:fs";import{execFileSync as r}from"node:child_process";import*as n from"node:path";function i(t){try{return c(t,p.X_OK),l(t).isFile()}catch{return!1}}function f(){let t=process.platform==="win32"?(process.env.PATHEXT||".EXE;.CMD;.BAT").split(";"):[""];return(process.env.PATH||"").split(n.delimiter).flatMap(s=>t.map(o=>n.resolve(s,`git${o}`))).find(i)??null}function d(t){if(process.platform!=="darwin"||u(t)!=="/usr/bin/git")return!0;let e=r("/usr/bin/xcode-select",["-p"],{encoding:"utf8",stdio:"pipe",timeout:5e3}).trim();return!!e&&i(n.join(e,"usr/bin/git"))}function b(){try{let t=f();return!t||!d(t)?!1:r(t,["--version"],{encoding:"utf8",stdio:"pipe",timeout:5e3}).startsWith("git version ")}catch{return!1}}export{b as a,a as b,m 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{d as c}from"./chunk-52T37Y47.js";import{d as a}from"./chunk-W5LGYSPZ.js";import{a as S,m as l}from"./chunk-J5DVLUKY.js";import{e as g}from"./chunk-WHC7AYZD.js";var u=g(S(),1),E=new Set(["CLAUDE_CODE_OAUTH_TOKEN_EXPIRES_AT"]);function O(n,t=process.env){let e={};u.config({path:n,processEnv:e});for(let r of E)delete e[r];u.populate(t,e)}var x="CORTEX_CHILD_EXIT";function I(n){return JSON.stringify(n)}function y(n){if(!n)return null;try{let t=JSON.parse(n);if(typeof t.uptimeMs!="number"||typeof t.backoffMs!="number")return null;let e=Number.isInteger(t.code)?t.code:null,r=typeof t.signal=="string"?t.signal.slice(0,20):null;return{code:e,signal:r,uptimeMs:Math.max(0,t.uptimeMs),backoffMs:Math.max(0,Math.round(t.backoffMs))}}catch{return null}}function M(n=process.env){let t=y(n[x]);t&&c({component:"server",kind:"childExit",errorName:"ChildExit",message:t.signal?`signal ${t.signal}`:`exit code ${t.code??"unknown"}`,stack:"",uptimeS:Math.round(t.uptimeMs/1e3),exit:{code:t.code,signal:t.signal,backoffMs:t.backoffMs}})}import{existsSync as b,readFileSync as h}from"node:fs";import*as d from"node:path";var p=d.join(l,"daemon-rebuild.json");function C(n){let t=(n.now??(()=>new Date))().toISOString();return{status:"running",reason:n.reason,current:null,steps:n.names.map(e=>({name:e,status:"pending",detail:null,startedAt:null,endedAt:null})),startedAt:t,updatedAt:t,endedAt:null,detail:null,daemonPid:n.daemonPid}}function f(n,t,e,r){return{...n,updatedAt:r,steps:n.steps.map(o=>o.name===t?{...o,...e}:o)}}function P(n,t,e=()=>new Date){let r=e().toISOString();return{...f(n,t,{status:"running",startedAt:r,endedAt:null},r),current:t}}function w(n,t,e,r=null,o=()=>new Date){let s=o().toISOString(),i=f(n,t,{status:e,detail:r,endedAt:s},s);return i.current!==t?i:{...i,current:i.steps.filter(m=>m.status==="running").at(-1)?.name??null}}function L(n,t,e=null,r=()=>new Date){let o=r().toISOString();return{...n,status:t,current:null,detail:e,updatedAt:o,endedAt:o,steps:n.steps.map(s=>s.status==="pending"?{...s,status:"skipped"}:s)}}function A(n){if(!n||typeof n!="object")return!1;let t=n;return typeof t.status=="string"&&typeof t.reason=="string"&&typeof t.startedAt=="string"&&Array.isArray(t.steps)}function T(n=p){try{if(!b(n))return null;let t=JSON.parse(h(n,"utf8"));return A(t)?t:null}catch{return null}}function F(n,t=p){try{return a(t,JSON.stringify(n,null,2)),!0}catch{return!1}}export{O as a,x as b,I as c,M as d,C as e,P as f,w as g,L as h,T as i,F 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{k as l}from"./chunk-CQLH4UVX.js";import{a as d,h as p}from"./chunk-OE4KH3NJ.js";import*as E from"node:http";function O(e,o,t,n={},s=183e4){let a=t===void 0?null:JSON.stringify(t),T=new URL(o);return new Promise((_,h)=>{let i=E.request(b(e,T,a,n,s),c=>{let u=[];c.on("data",f=>u.push(Buffer.from(f))),c.on("end",()=>_({status:c.statusCode??0,body:k(Buffer.concat(u).toString("utf8"))}))});i.on("error",h),i.on("timeout",()=>i.destroy(new Error(`Loopback request timed out after ${s}ms`))),a!==null&&i.write(a),i.end()})}function b(e,o,t,n,s){return{hostname:o.hostname,port:o.port,path:`${o.pathname}${o.search}`,method:e,headers:t===null?n:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(t),...n},timeout:s}}function k(e){if(!e)return null;try{return JSON.parse(e)}catch{return{_raw:e}}}var m=3001;function r(e){return e===void 0||e===""?null:e}function S(e,o){let t=parseInt(e??"",10);return Number.isFinite(t)&&t>0?t:o}function R(e){let o=e.CORTEX_BACKEND,t=r(e.CORTEX_MODEL);return o!=="claude"&&o!=="pi"||!t?null:{backend:o,model:t,provider:o==="pi"?r(e.CORTEX_PROVIDER):null,thinking:r(e.CORTEX_THINKING),mode:e.CORTEX_MODE??""}}function U(e=process.env){return{channel:r(e.SLACK_CHANNEL)??r(e.FEISHU_CHANNEL),sessionId:r(e.CORTEX_SESSION_ID),selection:R(e),project:r(e.CORTEX_PROJECT),backend:r(e.CORTEX_BACKEND),claudeModel:r(e.CORTEX_CLAUDE_MODEL),subagentPiModels:l(e.CORTEX_SUBAGENT_PI_MODELS),subagentClaudeModels:l(e.CORTEX_SUBAGENT_CLAUDE_MODELS),scheduleTaskId:r(e.CORTEX_SCHEDULE_TASK_ID),callbackSource:r(e.CORTEX_CALLBACK_SOURCE),webhookBaseUrl:`http://127.0.0.1:${S(e.WEBHOOK_PORT,m)}`,webhookToken:e.CORTEX_WEBHOOK_TOKEN||"",slackBotToken:r(e.SLACK_BOT_TOKEN),toolAllowlist:p(e[d])}}function L(e){return{"x-cortex-token":e.webhookToken}}function I(e){return e.sessionId?e.sessionId:e.channel?.startsWith("web:")?e.channel.slice(4):null}var w=async(e,o)=>{let{body:t}=await O("POST",`${e.webhookBaseUrl}/webhook/board`,{sessionId:o,action:"status"},L(e));if(!t?.success)throw new Error(t?.error||"board status failed");let n=t.data;return n?{id:n.id,title:n.title,dir:n.dir??null}:null};async function A(e,o=w){let t={channel:e.channel,sessionId:e.sessionId,model:e.selection?.model??null,thinking:e.selection?.thinking??null,mode:e.selection?.mode??null,project:e.project,backend:e.backend,scheduleTaskId:e.scheduleTaskId,callbackSource:e.callbackSource},n=I(e);if(n)try{t.board=await o(e,n)}catch{}return t}function X(e,o){e.tool("cortex_context","Get current session identity, backend, model, thinking, mode, project, bound board and trigger context.",{},{readOnlyHint:!0},async()=>{try{let t=await A(o),{channel:n,...s}=t;return{content:[{type:"text",text:JSON.stringify(s,null,2)}]}}catch(t){return{content:[{type:"text",text:`Failed to resolve context: ${t.message}`}],isError:!0}}})}export{O as a,m as b,U as c,L as d,I as e,A as f,X as g};