@cortex-agent/server 2026.10.27 → 2026.11.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (258) hide show
  1. package/LICENSE +255 -21
  2. package/README.md +54 -7
  3. package/THIRD_PARTY_NOTICES.txt +1109 -278
  4. package/defaults/hooks/cortex-hook-api.mjs +2 -1
  5. package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +23 -15
  6. package/dist/agent-adapter/claude/remote-mcp-proxy.js +1 -1
  7. package/dist/chunks/{anthropic-messages-M3SMXACA.js → anthropic-messages-M732OMEE.js} +1 -1
  8. package/dist/chunks/{azure-openai-responses-76YWXHSB.js → azure-openai-responses-RAKTV6JY.js} +1 -1
  9. package/dist/chunks/bedrock-converse-stream-WNUGNZ27.js +62 -0
  10. package/dist/chunks/bowser-MLGGLXTZ.js +20 -0
  11. package/dist/chunks/child-runner-MO5RT6FH.js +4 -0
  12. package/dist/chunks/chunk-2ATTYCRJ.js +4 -0
  13. package/dist/chunks/{chunk-PXS5SHOV.js → chunk-2ROGTDM2.js} +1 -1
  14. package/dist/chunks/chunk-2VVRTJQN.js +4 -0
  15. package/dist/chunks/{chunk-OZGBWAT2.js → chunk-2YTYYG4K.js} +1 -1
  16. package/dist/chunks/chunk-3CPIMAYX.js +30 -0
  17. package/dist/chunks/{chunk-FXDIR3SQ.js → chunk-3CZPBLB3.js} +1 -1
  18. package/dist/chunks/chunk-3ORG56I5.js +8 -0
  19. package/dist/chunks/{chunk-LEUENXI2.js → chunk-4YLAGSDM.js} +1 -1
  20. package/dist/chunks/{chunk-HU6UIDEJ.js → chunk-53TQNK7Z.js} +1 -1
  21. package/dist/chunks/{chunk-4U7XXM4W.js → chunk-5A6CA5TM.js} +1 -1
  22. package/dist/chunks/{chunk-PBJ5MPPX.js → chunk-5DF5WJNM.js} +1 -1
  23. package/dist/chunks/chunk-5PAW3DEU.js +50 -0
  24. package/dist/chunks/{chunk-DXBSQXJL.js → chunk-7GAYFN52.js} +1 -1
  25. package/dist/chunks/chunk-7GEBDPTT.js +4 -0
  26. package/dist/chunks/{chunk-NR6U3WIZ.js → chunk-AFTBQRPN.js} +1 -1
  27. package/dist/chunks/chunk-AVXDF7AG.js +4 -0
  28. package/dist/chunks/chunk-BDLKI2NT.js +4 -0
  29. package/dist/chunks/{chunk-P52RMIYX.js → chunk-BJGYGEZO.js} +1 -1
  30. package/dist/chunks/chunk-BUZQBTV2.js +10 -0
  31. package/dist/chunks/chunk-BZDIAI5M.js +125 -0
  32. package/dist/chunks/{chunk-A34TDMIC.js → chunk-CEGSDGYQ.js} +1 -1
  33. package/dist/chunks/{chunk-Q7CE3UIE.js → chunk-CK3P345X.js} +69 -69
  34. package/dist/chunks/{chunk-YAEVYJAR.js → chunk-EE3WT25T.js} +1 -1
  35. package/dist/chunks/chunk-ETIBCA2S.js +4 -0
  36. package/dist/chunks/{chunk-REBNWCKI.js → chunk-FP7ML72L.js} +1 -1
  37. package/dist/chunks/{chunk-H2FP6DG4.js → chunk-H4QZ2P3Z.js} +1 -1
  38. package/dist/chunks/chunk-IA6IODY3.js +4 -0
  39. package/dist/chunks/{chunk-D3NXKK2L.js → chunk-IKLTEWA3.js} +1 -1
  40. package/dist/chunks/chunk-IYVZHGUQ.js +5 -0
  41. package/dist/chunks/chunk-JJDEQ6N2.js +4 -0
  42. package/dist/chunks/chunk-JKL3AK5D.js +106 -0
  43. package/dist/chunks/chunk-KDPY2YA3.js +129 -0
  44. package/dist/chunks/{chunk-SUFW24P4.js → chunk-KUDK7GPS.js} +1 -1
  45. package/dist/chunks/chunk-LAWOWPZX.js +363 -0
  46. package/dist/chunks/chunk-LEAV3FFG.js +4 -0
  47. package/dist/chunks/chunk-LP72AF56.js +45 -0
  48. package/dist/chunks/{chunk-KENCMLRE.js → chunk-LP7T32PW.js} +1 -1
  49. package/dist/chunks/chunk-LQTFDC67.js +4 -0
  50. package/dist/chunks/{chunk-HALUQ7ZF.js → chunk-MGYYSX7Y.js} +1 -1
  51. package/dist/chunks/chunk-NNBSSISP.js +4 -0
  52. package/dist/chunks/chunk-NNTQUHLO.js +877 -0
  53. package/dist/chunks/{chunk-PFMEUFJ7.js → chunk-NRD57ICT.js} +1 -1
  54. package/dist/chunks/{chunk-QWAQHHRS.js → chunk-NXZS5PEW.js} +1 -1
  55. package/dist/chunks/chunk-OFEPDNRB.js +4 -0
  56. package/dist/chunks/{chunk-6LZK4DDH.js → chunk-P7TVR4GY.js} +1 -1
  57. package/dist/chunks/chunk-QEL6CMLE.js +4 -0
  58. package/dist/chunks/chunk-QMSSIDRQ.js +70 -0
  59. package/dist/chunks/chunk-QUXPMNFQ.js +4 -0
  60. package/dist/chunks/chunk-R52AVUQB.js +5 -0
  61. package/dist/chunks/chunk-R6CGBSTC.js +22 -0
  62. package/dist/chunks/chunk-RA2BUYI3.js +6 -0
  63. package/dist/chunks/chunk-RDW6FRF5.js +4 -0
  64. package/dist/chunks/chunk-RF4JLYBX.js +6 -0
  65. package/dist/chunks/{chunk-YPK2CAIZ.js → chunk-ROVKOIHF.js} +1 -1
  66. package/dist/chunks/chunk-RYLSRII6.js +7 -0
  67. package/dist/chunks/{chunk-XNSSUVT6.js → chunk-S3MR37DL.js} +1 -1
  68. package/dist/chunks/chunk-SAJD4EKE.js +10 -0
  69. package/dist/chunks/chunk-SFX7V5O2.js +10 -0
  70. package/dist/chunks/chunk-STCNHXPJ.js +6 -0
  71. package/dist/chunks/{chunk-FOJQXLL2.js → chunk-SY2HV3V5.js} +1 -1
  72. package/dist/chunks/chunk-T73GHMFB.js +4 -0
  73. package/dist/chunks/chunk-TKFFQNAP.js +19 -0
  74. package/dist/chunks/chunk-TMV2ZDOI.js +18 -0
  75. package/dist/chunks/chunk-TX46YMGI.js +5 -0
  76. package/dist/chunks/chunk-U23S37TT.js +6 -0
  77. package/dist/chunks/chunk-UT6DGZDO.js +4 -0
  78. package/dist/chunks/{chunk-JERCOLY3.js → chunk-V35MFAUQ.js} +4 -6
  79. package/dist/chunks/chunk-V6X7Y62J.js +7 -0
  80. package/dist/chunks/chunk-V7K3KNDM.js +4 -0
  81. package/dist/chunks/{chunk-NAA7GF6Q.js → chunk-VBN2JSER.js} +1 -1
  82. package/dist/chunks/chunk-VIMHSW6J.js +4 -0
  83. package/dist/chunks/chunk-VK5J556O.js +4 -0
  84. package/dist/chunks/chunk-VPVSKJGX.js +6 -0
  85. package/dist/chunks/chunk-VTL3Z2OP.js +23 -0
  86. package/dist/chunks/{chunk-X2GYYRVM.js → chunk-VW7TLY3P.js} +1 -1
  87. package/dist/chunks/chunk-W34AK4SK.js +65 -0
  88. package/dist/chunks/chunk-W6AKCEYF.js +8 -0
  89. package/dist/chunks/chunk-WBSE3EF3.js +27 -0
  90. package/dist/chunks/chunk-WZYS2HAK.js +4 -0
  91. package/dist/chunks/{chunk-UNVEZI57.js → chunk-XEBEWR6Y.js} +1 -1
  92. package/dist/chunks/chunk-XPPZ6Y3X.js +8 -0
  93. package/dist/chunks/chunk-XYSXL3KX.js +4 -0
  94. package/dist/chunks/chunk-YAAKL3QS.js +80 -0
  95. package/dist/chunks/chunk-YB5LUJHS.js +65 -0
  96. package/dist/chunks/chunk-Z24SBRJK.js +4 -0
  97. package/dist/chunks/cloudflare-workers-ai-system-one-32JCFHI3.js +1 -1
  98. package/dist/chunks/context-GQKWKFRM.js +4 -0
  99. package/dist/chunks/cost-OOO32GLC.js +5 -0
  100. package/dist/chunks/dist-V5FRMUFH.js +4 -0
  101. package/dist/chunks/easter-egg-3d-CZH7AYZ7.js +4 -0
  102. package/dist/chunks/{event-streams-3JSFPOTZ.js → event-streams-AVE4MSS6.js} +1 -1
  103. package/dist/chunks/execution-repo-XXL4FXC6.js +4 -0
  104. package/dist/chunks/{executions-6ARGR3IO.js → executions-BN6OLLVM.js} +1 -1
  105. package/dist/chunks/file-H572PL2Z.js +4 -0
  106. package/dist/chunks/google-generative-ai-2G4ITOZL.js +4 -0
  107. package/dist/chunks/google-vertex-PACHCMRZ.js +4 -0
  108. package/dist/chunks/init-75F4V7SK.js +4 -0
  109. package/dist/chunks/{install-cli-4IZCSDFZ.js → install-cli-ABBD7DO5.js} +1 -1
  110. package/dist/chunks/{interaction-ask-G5T3H3CG.js → interaction-ask-EE2UPR3Q.js} +1 -1
  111. package/dist/chunks/{interaction-plan-E5V42MUP.js → interaction-plan-C446T2GZ.js} +1 -1
  112. package/dist/chunks/{llama-cpp-classify-OTXZWCMW.js → llama-cpp-classify-IA2F2H7A.js} +1 -1
  113. package/dist/chunks/local-client-stop-5YOLXGYT.js +4 -0
  114. package/dist/chunks/memory-cli-5SSF6YJM.js +11 -0
  115. package/dist/chunks/{mistral-conversations-34F66L3O.js → mistral-conversations-VHP63CDS.js} +1 -1
  116. package/dist/chunks/{model-resolver-N3DTAQ2S.js → model-resolver-FVJNZ6NA.js} +1 -1
  117. package/dist/chunks/{node-PTK2HCDV.js → node-DAO3SX7O.js} +1 -1
  118. package/dist/chunks/{openai-codex-2REL6UQU.js → openai-codex-JULCKICT.js} +1 -1
  119. package/dist/chunks/{openai-codex-responses-ZBVHREB3.js → openai-codex-responses-EHJ4AZBE.js} +1 -1
  120. package/dist/chunks/{openai-completions-VVIB26SH.js → openai-completions-CRAGQFCE.js} +1 -1
  121. package/dist/chunks/{openai-decisions-2N6ZRPZC.js → openai-decisions-P5UX7BWY.js} +1 -1
  122. package/dist/chunks/{openai-responses-735XA2ZX.js → openai-responses-IZ22NVQ7.js} +1 -1
  123. package/dist/chunks/{openrouter-images-3IKETHAC.js → openrouter-images-W2JAMSRH.js} +1 -1
  124. package/dist/chunks/{pi-messages-I3E4ZFHA.js → pi-messages-MJEEQU2R.js} +1 -1
  125. package/dist/chunks/{radius-HXRZVBDB.js → radius-ZM7ZRMXF.js} +1 -1
  126. package/dist/chunks/{remote-ops-BALZYKH6.js → remote-ops-O5CR4RGA.js} +1 -1
  127. package/dist/chunks/runner-S6R3US24.js +4 -0
  128. package/dist/chunks/schedule-cli-4T4YC5V5.js +4 -0
  129. package/dist/chunks/slack-2CGM4SMY.js +4 -0
  130. package/dist/chunks/start-ui-http-3D7QNHGB.js +43 -0
  131. package/dist/chunks/subagent-OZGUOV3J.js +4 -0
  132. package/dist/chunks/{time-KEHDQT6K.js → time-P6PE52WL.js} +1 -1
  133. package/dist/chunks/tool-shims-IA2WELXJ.js +4 -0
  134. package/dist/chunks/typesafe-system-one-6ULACYD4.js +1 -1
  135. package/dist/chunks/ui-board-H4INJD6C.js +5 -0
  136. package/dist/chunks/ui-decision-6HHNROIT.js +4 -0
  137. package/dist/chunks/{ui-file-GVH53O3X.js → ui-file-6PLXHSTB.js} +1 -1
  138. package/dist/chunks/ui-view-6MDU4GXY.js +4 -0
  139. package/dist/chunks/virtual-modules-OFI7QKYH.js +4 -0
  140. package/dist/chunks/waitpoint-W5M3BE55.js +5 -0
  141. package/dist/chunks/workers-GTFP75MS.js +4 -0
  142. package/dist/client-bundle/client.mjs +44 -31
  143. package/dist/client-bundle/manifest.json +2 -2
  144. package/dist/core/pi-sdk.js +1 -1
  145. package/dist/domain/auth/cc-auth-cli.js +1 -1
  146. package/dist/domain/mcp/bundled-server.js +1 -1
  147. package/dist/domain/mcp/feishu/client.js +4 -0
  148. package/dist/entry/app.js +201 -191
  149. package/dist/entry/browser-cli.js +10 -10
  150. package/dist/entry/cli.js +1 -1
  151. package/dist/entry/cortex-cli.js +1 -1
  152. package/dist/entry/daemon.js +4 -4
  153. package/dist/entry/hook-cli.js +2 -2
  154. package/dist/entry/production-app-bootstrap.js +1 -1
  155. package/dist/entry/production-evidence-export-cli.js +1 -1
  156. package/dist/entry/signal-cli.js +2 -2
  157. package/dist/tui/index.js +41 -41
  158. package/package.json +3 -3
  159. package/vendor/pi/dist/core/extensions/loader.js +1 -1
  160. package/vendor/pi/dist/extensions/codemode/execute.js +1 -1
  161. package/vendor/pi-ai/bedrock.js +1 -1
  162. package/vendor/pi-ai/oauth-load.js +1 -1
  163. package/web/dist/assets/{board-math-css-BmiXB1z5.js → board-math-css-BgIyUG-C.js} +1 -1
  164. package/web/dist/assets/index-9lyu2S6W.css +1 -0
  165. package/web/dist/assets/index-C-hpzey7.js +532 -0
  166. package/web/dist/assets/{index-XBRXpnC5.js → index-C2eMpcuI.js} +1 -1
  167. package/web/dist/assets/pdf-worker-DdZgk2mV.js +57 -0
  168. package/web/dist/assets/pdf.worker.min-Bz_KHX45.js +55 -0
  169. package/web/dist/index.html +2 -2
  170. package/web/dist/theme.css +22 -0
  171. package/dist/chunks/api-GM53PHIL-GFHEXXE6.js +0 -4
  172. package/dist/chunks/bedrock-converse-stream-5UPX4NTQ.js +0 -58
  173. package/dist/chunks/child-runner-3GHOWGZP.js +0 -4
  174. package/dist/chunks/chunk-2ZNLUY2U.js +0 -128
  175. package/dist/chunks/chunk-3F6WW7HR.js +0 -13
  176. package/dist/chunks/chunk-3OKHUVEM.js +0 -7
  177. package/dist/chunks/chunk-3THJYAEF.js +0 -4
  178. package/dist/chunks/chunk-3YHOCPQU.js +0 -10
  179. package/dist/chunks/chunk-4LLH5OWM.js +0 -10
  180. package/dist/chunks/chunk-52T37Y47.js +0 -8
  181. package/dist/chunks/chunk-7MU2AKNM.js +0 -4
  182. package/dist/chunks/chunk-AAA3UBIS.js +0 -4
  183. package/dist/chunks/chunk-ASYQHJVQ.js +0 -9
  184. package/dist/chunks/chunk-BGVHA2D4.js +0 -4
  185. package/dist/chunks/chunk-BKHDWCRT.js +0 -79
  186. package/dist/chunks/chunk-CQLH4UVX.js +0 -4
  187. package/dist/chunks/chunk-D6UA4BZC.js +0 -19
  188. package/dist/chunks/chunk-DGMNI4AO.js +0 -4
  189. package/dist/chunks/chunk-DHSA5ACV.js +0 -125
  190. package/dist/chunks/chunk-DPQPXBTP.js +0 -68
  191. package/dist/chunks/chunk-E7ZMYIY6.js +0 -30
  192. package/dist/chunks/chunk-EQITBTJC.js +0 -10
  193. package/dist/chunks/chunk-EXJA5RIX.js +0 -357
  194. package/dist/chunks/chunk-FH74NME3.js +0 -115
  195. package/dist/chunks/chunk-FOQ7VLIL.js +0 -17
  196. package/dist/chunks/chunk-J5DVLUKY.js +0 -6
  197. package/dist/chunks/chunk-JW2HFMTF.js +0 -4
  198. package/dist/chunks/chunk-KIGMAATV.js +0 -23
  199. package/dist/chunks/chunk-KIU5FAPY.js +0 -5
  200. package/dist/chunks/chunk-KIWMQPH7.js +0 -739
  201. package/dist/chunks/chunk-LMSQZ6TQ.js +0 -4
  202. package/dist/chunks/chunk-MEPASGPP.js +0 -6
  203. package/dist/chunks/chunk-MFAEUHMV.js +0 -28
  204. package/dist/chunks/chunk-NKDMKRSB.js +0 -68
  205. package/dist/chunks/chunk-NKXV32S6.js +0 -4
  206. package/dist/chunks/chunk-NVX5IPRN.js +0 -4
  207. package/dist/chunks/chunk-O3JW2F7D.js +0 -8
  208. package/dist/chunks/chunk-OISO5JXB.js +0 -4
  209. package/dist/chunks/chunk-OPYXNSMY.js +0 -4
  210. package/dist/chunks/chunk-PZMXHA6X.js +0 -9
  211. package/dist/chunks/chunk-QEOFEETJ.js +0 -4
  212. package/dist/chunks/chunk-REPYBMQS.js +0 -4
  213. package/dist/chunks/chunk-TAWLERZA.js +0 -4
  214. package/dist/chunks/chunk-TWAEABGG.js +0 -52
  215. package/dist/chunks/chunk-TZFLHVOQ.js +0 -7
  216. package/dist/chunks/chunk-UD3NMUHR.js +0 -12
  217. package/dist/chunks/chunk-W25TB3PU.js +0 -4
  218. package/dist/chunks/chunk-W5LGYSPZ.js +0 -4
  219. package/dist/chunks/chunk-XAJLZR7C.js +0 -28
  220. package/dist/chunks/chunk-XH6FMP3N.js +0 -71
  221. package/dist/chunks/chunk-XSRZHN63.js +0 -4
  222. package/dist/chunks/chunk-YG7OEPR2.js +0 -6
  223. package/dist/chunks/chunk-YHIWOGVL.js +0 -4
  224. package/dist/chunks/chunk-YZSHTWNM.js +0 -92
  225. package/dist/chunks/chunk-Z4H3VDHI.js +0 -4
  226. package/dist/chunks/client-XOGYH5UR.js +0 -4
  227. package/dist/chunks/config-DJSQI77S-335IXHSM.js +0 -4
  228. package/dist/chunks/context-VCQH5OB6.js +0 -4
  229. package/dist/chunks/cost-PGGFI7QJ.js +0 -5
  230. package/dist/chunks/dist-PUKMZ7GW.js +0 -4
  231. package/dist/chunks/easter-egg-3d-MO4MOEVF.js +0 -4
  232. package/dist/chunks/es5-VNTQPCKX.js +0 -4
  233. package/dist/chunks/execution-repo-ZLJTBWFC.js +0 -4
  234. package/dist/chunks/file-7BN7RCAY.js +0 -4
  235. package/dist/chunks/gateway-UCRPMR75.js +0 -36
  236. package/dist/chunks/google-generative-ai-2VXWLHWI.js +0 -4
  237. package/dist/chunks/google-vertex-UA36QP2U.js +0 -4
  238. package/dist/chunks/init-HA7FAQ73.js +0 -4
  239. package/dist/chunks/local-client-stop-SQRU7ZZM.js +0 -4
  240. package/dist/chunks/memory-cli-PYOILNN5.js +0 -11
  241. package/dist/chunks/models-L5VF4I5O-XXNJYQMQ.js +0 -4
  242. package/dist/chunks/runner-PLVZDGHB.js +0 -4
  243. package/dist/chunks/schedule-cli-OLASBBYJ.js +0 -4
  244. package/dist/chunks/slack-WAGSPZUX.js +0 -4
  245. package/dist/chunks/start-ui-http-QALT7C3P.js +0 -43
  246. package/dist/chunks/subagent-E3UC7ZHC.js +0 -4
  247. package/dist/chunks/tool-shims-Q6P6UXVC.js +0 -4
  248. package/dist/chunks/ui-board-4GYW6KKW.js +0 -5
  249. package/dist/chunks/ui-decision-U2FXSEC2.js +0 -4
  250. package/dist/chunks/ui-view-O7PLANT7.js +0 -4
  251. package/dist/chunks/virtual-modules-IDC5YKZJ.js +0 -4
  252. package/dist/chunks/waitpoint-2FGQBIAC.js +0 -5
  253. package/dist/chunks/workers-XN4PSTH6.js +0 -4
  254. package/vendor/aistatus/gateway-cli.js +0 -21
  255. package/web/dist/assets/index-DqWMdMkh.css +0 -1
  256. package/web/dist/assets/index-btKNdkvc.js +0 -525
  257. package/web/dist/assets/pdf-worker-Hp15W1QJ.js +0 -57
  258. package/web/dist/assets/pdf.worker.min-DnhTvCwe.js +0 -55
@@ -1,6 +1,6 @@
1
1
  import { createRequire as __cortexCreateRequire } from 'node:module';
2
2
  const require = __cortexCreateRequire(import.meta.url);
3
3
  const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{a as P,c as m}from"./chunk-HALUQ7ZF.js";import{a as T}from"./chunk-Q4UGYGU5.js";import{e as v}from"./chunk-NAA7GF6Q.js";import{m as h}from"./chunk-J5DVLUKY.js";import*as l from"path";import{readFileSync as O,statSync as N}from"fs";import{appendFile as L,mkdir as U}from"fs/promises";import*as _ from"path";function b(){return{runs:0,turns:0,activeMs:0,cost:0,costSamples:0,subCost:0,subSamples:0}}function E(e,t){return e.runs+=t.runs,e.turns+=t.turns,e.activeMs+=t.activeMs,e.cost+=t.cost,e.costSamples+=t.costSamples,e.subCost+=t.subCost,e.subSamples+=t.subSamples,e}function S(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function R(e){if(e?.thread?.threadId||!e?.runtime?.endedAt)return null;let t=e?.session?.sessionId;if(typeof t=="string"&&t)return{sessionId:t,role:"own"};let s=e?.session?.ownerSessionId;return typeof s=="string"&&s?{sessionId:s,role:"subagent"}:null}function I(e,t,s){let n=R(t);if(!n||s&&(t.runtime?.endedAt??"")<s)return;let r=e.get(n.sessionId);r||e.set(n.sessionId,r=b());let i=S(t.metrics?.costUsd);if(n.role==="subagent"){i!==null&&(r.subCost+=i,r.subSamples++);return}r.runs++;let u=S(t.metrics?.numTurns);u!==null&&(r.turns+=u);let o=S(t.metrics?.durationS);o!==null&&(r.activeMs+=Math.round(o*1e3)),i!==null&&(r.cost+=i,r.costSamples++)}function k(e){if(!e||e.runs===0&&e.subSamples===0)return null;let t=e.costSamples>0||e.subSamples>0;return{runs:e.runs,turns:e.turns,activeMs:e.activeMs,costUsd:t?e.cost+e.subCost:null,subagentCostUsd:e.subSamples>0?e.subCost:null}}function $(){return process.env.CORTEX_SESSION_TOTALS_FILE||_.join(h,"session-totals.json")}function c(e,t){let s=e[t];return typeof s=="number"&&Number.isFinite(s)?s:0}function F(e){let t={carriedThrough:null,sessions:{}};if(!e||typeof e!="object"||Array.isArray(e))return t;let s=e,n=typeof s.carriedThrough=="string"&&s.carriedThrough?s.carriedThrough:null,r=s.sessions;if(!r||typeof r!="object"||Array.isArray(r))return{carriedThrough:n,sessions:{}};let i={};for(let[u,o]of Object.entries(r)){if(!u||!o||typeof o!="object"||Array.isArray(o))continue;let a=o;i[u]={runs:c(a,"runs"),turns:c(a,"turns"),activeMs:c(a,"activeMs"),cost:c(a,"cost"),costSamples:c(a,"costSamples"),subCost:c(a,"subCost"),subSamples:c(a,"subSamples")}}return{carriedThrough:n,sessions:i}}var w=class{repo;constructor(t){this.repo=new m({filePath:t||$(),defaultValue:()=>({carriedThrough:null,sessions:{}}),migrate:F})}async read(){return this.repo.read()}async fold(t,s){if(t.length===0)return;let n=new Map;for(let r of t)I(n,r);await this.repo.mutate(r=>{let i={...r.sessions};for(let[o,a]of n)i[o]=E({...i[o]??b()},a);return{next:{carriedThrough:!r.carriedThrough||r.carriedThrough<s?s:r.carriedThrough,sessions:i},result:void 0}})}async forget(t){if(t.length===0)return;let s=await this.repo.read();t.some(n=>n in s.sessions)&&await this.repo.mutate(n=>{let r={...n.sessions};for(let i of t)delete r[i];return{next:{...n,sessions:r},result:void 0}})}async flush(){await this.repo.flush()}invalidate(){this.repo.invalidate()}},M=new w;var p=v("execution-repo"),j=new Set(["completed","failed","stale","cancelled"]);function C(e){if(!e.session)return e;let t={...e.session};return delete t.sessionName,{...e,session:t}}function D(e){return e||process.env.CORTEX_EXECUTIONS_FILE||l.join(h,"executions.json")}function d(){return new Date().toISOString()}function J(e){let t=Date.now().toString(36),s=Math.random().toString(36).slice(2,6);return`exec_${e}_${t}_${s}`}function q({kind:e,channel:t,project:s,trigger:n,backend:r,billingMode:i,sessionId:u,ownerSessionId:o,label:a,scheduleTaskId:g}){let f=d();return{id:J(e),kind:e,status:"running",channel:t||null,project:s||"general",source:{trigger:n||e},backend:r||"claude",billingMode:i||"api",session:{sessionId:u||null,...o?{ownerSessionId:o}:{}},scheduleTaskId:g||null,runtime:{startedAt:f,updatedAt:f,endedAt:null},metrics:{costUsd:null,numTurns:null,durationS:null},text:{label:a||null,finalOutput:null,error:null}}}function y(e,t,{costUsd:s,numTurns:n,durationS:r,finalOutput:i,error:u}={}){let o=d();return{...e,status:t,runtime:{...e.runtime,updatedAt:o,endedAt:o},metrics:{costUsd:s??e.metrics.costUsd,numTurns:n??e.metrics.numTurns,durationS:r??e.metrics.durationS},text:{...e.text,finalOutput:i??e.text.finalOutput,error:u??e.text.error}}}var A=class{map=new Map;repo;filePath;sessionTotals;mutex=new T;_pendingPersist=Promise.resolve();_persistQueued=!1;followed=null;constructor(t){this.filePath=D(t?.filePath),this.sessionTotals=t?.sessionTotals??M,this.repo=new m({filePath:this.filePath,defaultValue:()=>({}),compact:!0})}load(){try{let t=JSON.parse(O(this.filePath,"utf8"));this.map.clear();for(let[s,n]of Object.entries(t))this.map.set(s,C(n));p.info(`Loaded ${this.map.size} executions`)}catch{this.map.clear()}}follow(){this.followed="",this.refresh()}refresh(){if(this.followed===null)return;let t;try{let s=N(this.filePath);t=`${s.ino}:${s.mtimeMs}:${s.size}`}catch{this.map.clear(),this.followed="missing";return}if(t!==this.followed)try{let s=JSON.parse(O(this.filePath,"utf8"));this.map=new Map(Object.entries(s).map(([n,r])=>[n,C(r)])),this.followed=t}catch(s){p.warn(`Could not re-read ${this.filePath}: ${s.message}`)}}getExecution(t){return this.refresh(),this.map.get(t)||null}getRunningExecutions(){this.refresh();let t=[];for(let s of this.map.values())s.status==="running"&&t.push(s);return t}getAllExecutions(){return this.refresh(),Array.from(this.map.values())}getAll(){return this.refresh(),Array.from(this.map.values()).sort((t,s)=>s.runtime.startedAt.localeCompare(t.runtime.startedAt))}updateRecordInternal(t,s){let n=this.map.get(t);if(!n)return null;if(j.has(n.status))return n;let r=s({...n});return r.runtime={...n.runtime,...r.runtime,updatedAt:d()},this.map.set(t,r),this.queuePersist(),r}startLocalExecution({kind:t="local",channel:s,project:n,trigger:r,backend:i,billingMode:u,sessionId:o,ownerSessionId:a=null,label:g,scheduleTaskId:f}){let x=q({kind:t,channel:s,project:n,trigger:r,backend:i,billingMode:u,sessionId:o,ownerSessionId:a,label:g,scheduleTaskId:f});return this.map.set(x.id,x),this.queuePersist(),x}touchExecution(t,s={}){return this.updateRecordInternal(t,n=>({...n,...s,metrics:{...n.metrics,...s.metrics||{}},text:{...n.text,...s.text||{}},session:s.session?{...n.session,...s.session}:n.session}))}completeExecution(t,s={}){return this.updateRecordInternal(t,n=>y(n,"completed",s))}failExecution(t,s={}){return this.updateRecordInternal(t,n=>y(n,"failed",s))}cancelExecution(t,s={}){return this.updateRecordInternal(t,n=>y(n,"cancelled",s))}set(t,s){this.map.set(t,s),this.queuePersist()}async markMissingRunningExecutionsStale(t){await this._pendingPersist;let s=[];return await this.mutex.run(async()=>{let n=d();for(let r of this.map.values())r.status==="running"&&(t&&t(r)||(r.status="stale",r.runtime.updatedAt=n,r.runtime.endedAt=n,s.push(r.id)));s.length>0&&await this.persist()}),s}defaultArchivePath(){let t=l.basename(this.filePath).replace(/\.json$/,"");return l.join(l.dirname(this.filePath),"archive",`${t}-archive.jsonl`)}selectArchivable(t){let s=[];for(let n of this.map.values()){if(!j.has(n.status))continue;let r=n.runtime?.endedAt||n.runtime?.updatedAt||n.runtime?.startedAt;r&&r<t&&s.push(n)}return s}async archiveTerminal({olderThanMs:t=10080*60*1e3,archivePath:s}={}){return await this._pendingPersist,this.mutex.run(async()=>{let n=new Date(Date.now()-t).toISOString(),r=this.selectArchivable(n);if(r.length===0)return 0;await this.sessionTotals.fold(r,n);let i=s||this.defaultArchivePath();await U(l.dirname(i),{recursive:!0}),await L(i,r.map(u=>JSON.stringify(u)).join(`
4
+ import{a as P,c as m}from"./chunk-MGYYSX7Y.js";import{a as T}from"./chunk-Q4UGYGU5.js";import{e as v}from"./chunk-VBN2JSER.js";import{j as h}from"./chunk-Z24SBRJK.js";import*as l from"path";import{readFileSync as O,statSync as N}from"fs";import{appendFile as L,mkdir as U}from"fs/promises";import*as _ from"path";function b(){return{runs:0,turns:0,activeMs:0,cost:0,costSamples:0,subCost:0,subSamples:0}}function E(e,t){return e.runs+=t.runs,e.turns+=t.turns,e.activeMs+=t.activeMs,e.cost+=t.cost,e.costSamples+=t.costSamples,e.subCost+=t.subCost,e.subSamples+=t.subSamples,e}function S(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function R(e){if(e?.thread?.threadId||!e?.runtime?.endedAt)return null;let t=e?.session?.sessionId;if(typeof t=="string"&&t)return{sessionId:t,role:"own"};let s=e?.session?.ownerSessionId;return typeof s=="string"&&s?{sessionId:s,role:"subagent"}:null}function I(e,t,s){let n=R(t);if(!n||s&&(t.runtime?.endedAt??"")<s)return;let r=e.get(n.sessionId);r||e.set(n.sessionId,r=b());let i=S(t.metrics?.costUsd);if(n.role==="subagent"){i!==null&&(r.subCost+=i,r.subSamples++);return}r.runs++;let u=S(t.metrics?.numTurns);u!==null&&(r.turns+=u);let o=S(t.metrics?.durationS);o!==null&&(r.activeMs+=Math.round(o*1e3)),i!==null&&(r.cost+=i,r.costSamples++)}function k(e){if(!e||e.runs===0&&e.subSamples===0)return null;let t=e.costSamples>0||e.subSamples>0;return{runs:e.runs,turns:e.turns,activeMs:e.activeMs,costUsd:t?e.cost+e.subCost:null,subagentCostUsd:e.subSamples>0?e.subCost:null}}function $(){return process.env.CORTEX_SESSION_TOTALS_FILE||_.join(h,"session-totals.json")}function c(e,t){let s=e[t];return typeof s=="number"&&Number.isFinite(s)?s:0}function F(e){let t={carriedThrough:null,sessions:{}};if(!e||typeof e!="object"||Array.isArray(e))return t;let s=e,n=typeof s.carriedThrough=="string"&&s.carriedThrough?s.carriedThrough:null,r=s.sessions;if(!r||typeof r!="object"||Array.isArray(r))return{carriedThrough:n,sessions:{}};let i={};for(let[u,o]of Object.entries(r)){if(!u||!o||typeof o!="object"||Array.isArray(o))continue;let a=o;i[u]={runs:c(a,"runs"),turns:c(a,"turns"),activeMs:c(a,"activeMs"),cost:c(a,"cost"),costSamples:c(a,"costSamples"),subCost:c(a,"subCost"),subSamples:c(a,"subSamples")}}return{carriedThrough:n,sessions:i}}var w=class{repo;constructor(t){this.repo=new m({filePath:t||$(),defaultValue:()=>({carriedThrough:null,sessions:{}}),migrate:F})}async read(){return this.repo.read()}async fold(t,s){if(t.length===0)return;let n=new Map;for(let r of t)I(n,r);await this.repo.mutate(r=>{let i={...r.sessions};for(let[o,a]of n)i[o]=E({...i[o]??b()},a);return{next:{carriedThrough:!r.carriedThrough||r.carriedThrough<s?s:r.carriedThrough,sessions:i},result:void 0}})}async forget(t){if(t.length===0)return;let s=await this.repo.read();t.some(n=>n in s.sessions)&&await this.repo.mutate(n=>{let r={...n.sessions};for(let i of t)delete r[i];return{next:{...n,sessions:r},result:void 0}})}async flush(){await this.repo.flush()}invalidate(){this.repo.invalidate()}},M=new w;var p=v("execution-repo"),j=new Set(["completed","failed","stale","cancelled"]);function C(e){if(!e.session)return e;let t={...e.session};return delete t.sessionName,{...e,session:t}}function D(e){return e||process.env.CORTEX_EXECUTIONS_FILE||l.join(h,"executions.json")}function d(){return new Date().toISOString()}function J(e){let t=Date.now().toString(36),s=Math.random().toString(36).slice(2,6);return`exec_${e}_${t}_${s}`}function q({kind:e,channel:t,project:s,trigger:n,backend:r,billingMode:i,sessionId:u,ownerSessionId:o,label:a,scheduleTaskId:g}){let f=d();return{id:J(e),kind:e,status:"running",channel:t||null,project:s||"general",source:{trigger:n||e},backend:r||"claude",billingMode:i||"api",session:{sessionId:u||null,...o?{ownerSessionId:o}:{}},scheduleTaskId:g||null,runtime:{startedAt:f,updatedAt:f,endedAt:null},metrics:{costUsd:null,numTurns:null,durationS:null},text:{label:a||null,finalOutput:null,error:null}}}function y(e,t,{costUsd:s,numTurns:n,durationS:r,finalOutput:i,error:u}={}){let o=d();return{...e,status:t,runtime:{...e.runtime,updatedAt:o,endedAt:o},metrics:{costUsd:s??e.metrics.costUsd,numTurns:n??e.metrics.numTurns,durationS:r??e.metrics.durationS},text:{...e.text,finalOutput:i??e.text.finalOutput,error:u??e.text.error}}}var A=class{map=new Map;repo;filePath;sessionTotals;mutex=new T;_pendingPersist=Promise.resolve();_persistQueued=!1;followed=null;constructor(t){this.filePath=D(t?.filePath),this.sessionTotals=t?.sessionTotals??M,this.repo=new m({filePath:this.filePath,defaultValue:()=>({}),compact:!0})}load(){try{let t=JSON.parse(O(this.filePath,"utf8"));this.map.clear();for(let[s,n]of Object.entries(t))this.map.set(s,C(n));p.info(`Loaded ${this.map.size} executions`)}catch{this.map.clear()}}follow(){this.followed="",this.refresh()}refresh(){if(this.followed===null)return;let t;try{let s=N(this.filePath);t=`${s.ino}:${s.mtimeMs}:${s.size}`}catch{this.map.clear(),this.followed="missing";return}if(t!==this.followed)try{let s=JSON.parse(O(this.filePath,"utf8"));this.map=new Map(Object.entries(s).map(([n,r])=>[n,C(r)])),this.followed=t}catch(s){p.warn(`Could not re-read ${this.filePath}: ${s.message}`)}}getExecution(t){return this.refresh(),this.map.get(t)||null}getRunningExecutions(){this.refresh();let t=[];for(let s of this.map.values())s.status==="running"&&t.push(s);return t}getAllExecutions(){return this.refresh(),Array.from(this.map.values())}getAll(){return this.refresh(),Array.from(this.map.values()).sort((t,s)=>s.runtime.startedAt.localeCompare(t.runtime.startedAt))}updateRecordInternal(t,s){let n=this.map.get(t);if(!n)return null;if(j.has(n.status))return n;let r=s({...n});return r.runtime={...n.runtime,...r.runtime,updatedAt:d()},this.map.set(t,r),this.queuePersist(),r}startLocalExecution({kind:t="local",channel:s,project:n,trigger:r,backend:i,billingMode:u,sessionId:o,ownerSessionId:a=null,label:g,scheduleTaskId:f}){let x=q({kind:t,channel:s,project:n,trigger:r,backend:i,billingMode:u,sessionId:o,ownerSessionId:a,label:g,scheduleTaskId:f});return this.map.set(x.id,x),this.queuePersist(),x}touchExecution(t,s={}){return this.updateRecordInternal(t,n=>({...n,...s,metrics:{...n.metrics,...s.metrics||{}},text:{...n.text,...s.text||{}},session:s.session?{...n.session,...s.session}:n.session}))}completeExecution(t,s={}){return this.updateRecordInternal(t,n=>y(n,"completed",s))}failExecution(t,s={}){return this.updateRecordInternal(t,n=>y(n,"failed",s))}cancelExecution(t,s={}){return this.updateRecordInternal(t,n=>y(n,"cancelled",s))}set(t,s){this.map.set(t,s),this.queuePersist()}async markMissingRunningExecutionsStale(t){await this._pendingPersist;let s=[];return await this.mutex.run(async()=>{let n=d();for(let r of this.map.values())r.status==="running"&&(t&&t(r)||(r.status="stale",r.runtime.updatedAt=n,r.runtime.endedAt=n,s.push(r.id)));s.length>0&&await this.persist()}),s}defaultArchivePath(){let t=l.basename(this.filePath).replace(/\.json$/,"");return l.join(l.dirname(this.filePath),"archive",`${t}-archive.jsonl`)}selectArchivable(t){let s=[];for(let n of this.map.values()){if(!j.has(n.status))continue;let r=n.runtime?.endedAt||n.runtime?.updatedAt||n.runtime?.startedAt;r&&r<t&&s.push(n)}return s}async archiveTerminal({olderThanMs:t=10080*60*1e3,archivePath:s}={}){return await this._pendingPersist,this.mutex.run(async()=>{let n=new Date(Date.now()-t).toISOString(),r=this.selectArchivable(n);if(r.length===0)return 0;await this.sessionTotals.fold(r,n);let i=s||this.defaultArchivePath();await U(l.dirname(i),{recursive:!0}),await L(i,r.map(u=>JSON.stringify(u)).join(`
5
5
  `)+`
6
6
  `,"utf8");for(let u of r)this.map.delete(u.id);return await this.persist(),p.info(`Archived ${r.length} terminal execution(s) to ${i}`),r.length})}async flush(){await this._pendingPersist,await this.mutex.run(async()=>{})}queuePersist(){return this._persistQueued?this._pendingPersist:(this._persistQueued=!0,this._pendingPersist=this._pendingPersist.catch(()=>{}).then(()=>this.mutex.run(()=>(this._persistQueued=!1,this.persist()))).catch(t=>{p.error("persist failed:",t)}),this._pendingPersist)}async persist(){let t={};for(let[s,n]of this.map)t[s]=n;await this.repo.write(t)}},Q=new A;P(Q);export{b as a,E as b,I as c,k as d,M as e,j as f,A as g,Q as h};
@@ -1,6 +1,6 @@
1
1
  import { createRequire as __cortexCreateRequire } from 'node:module';
2
2
  const require = __cortexCreateRequire(import.meta.url);
3
3
  const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{a as d,d as p}from"./chunk-W5LGYSPZ.js";import{c as E}from"./chunk-J5DVLUKY.js";import*as o from"node:fs";import*as r from"node:path";import{createHash as C}from"node:crypto";import*as g from"node:fs";import*as u from"node:path";import{createHash as L}from"node:crypto";var b=["client.mjs","cortex-run-watcher.mjs"];function v(n){let t=L("sha256");for(let e of b)t.update(g.readFileSync(u.join(n,e)));return t.digest("hex")}function A(n){let t=JSON.parse(g.readFileSync(u.join(n,"manifest.json"),"utf8"));if(!(typeof t?.version=="string"&&t.version.trim()&&typeof t.hash=="string"&&/^[a-f0-9]{64}$/.test(t.hash)&&typeof t.source=="string"&&/^(unknown|[a-f0-9]{40})$/.test(t.source)))throw new Error("Invalid package-local client manifest; reinstall the server package");return{version:t.version,hash:t.hash,source:t.source}}function x(n=E){let t=u.join(n,"dist","client-bundle"),e=A(t),i=L("sha256"),s=b.map(l=>{let S=g.readFileSync(u.join(t,l));if(!S.length)throw new Error(`Empty package-local client file: ${l}`);return i.update(S),{name:l,data:S.toString("base64")}});if(i.digest("hex")!==e.hash)throw new Error("Package-local client hash mismatch; reinstall the server package");return{...e,files:s}}var F=".local-install-stage",I=n=>C("sha256").update(n).digest("hex"),a=n=>r.join(n.DATA_DIR,"client"),h=n=>r.join(a(n),"local-install.json"),f=n=>r.join(n.CONFIG_DIR,"cortex-client.json");function j(n){return JSON.stringify({deviceName:n,serverHost:"127.0.0.1",serverPort:3002},null,2)+`
4
+ import{a as d,e as p}from"./chunk-AVXDF7AG.js";import{a as E}from"./chunk-Z24SBRJK.js";import*as o from"node:fs";import*as r from"node:path";import{createHash as C}from"node:crypto";import*as g from"node:fs";import*as u from"node:path";import{createHash as L}from"node:crypto";var b=["client.mjs","cortex-run-watcher.mjs"];function v(n){let t=L("sha256");for(let e of b)t.update(g.readFileSync(u.join(n,e)));return t.digest("hex")}function A(n){let t=JSON.parse(g.readFileSync(u.join(n,"manifest.json"),"utf8"));if(!(typeof t?.version=="string"&&t.version.trim()&&typeof t.hash=="string"&&/^[a-f0-9]{64}$/.test(t.hash)&&typeof t.source=="string"&&/^(unknown|[a-f0-9]{40})$/.test(t.source)))throw new Error("Invalid package-local client manifest; reinstall the server package");return{version:t.version,hash:t.hash,source:t.source}}function x(n=E){let t=u.join(n,"dist","client-bundle"),e=A(t),i=L("sha256"),s=b.map(l=>{let S=g.readFileSync(u.join(t,l));if(!S.length)throw new Error(`Empty package-local client file: ${l}`);return i.update(S),{name:l,data:S.toString("base64")}});if(i.digest("hex")!==e.hash)throw new Error("Package-local client hash mismatch; reinstall the server package");return{...e,files:s}}var F=".local-install-stage",I=n=>C("sha256").update(n).digest("hex"),a=n=>r.join(n.DATA_DIR,"client"),h=n=>r.join(a(n),"local-install.json"),f=n=>r.join(n.CONFIG_DIR,"cortex-client.json");function j(n){return JSON.stringify({deviceName:n,serverHost:"127.0.0.1",serverPort:3002},null,2)+`
5
5
  `}function c(n){if(o.lstatSync(n,{throwIfNoEntry:!1})?.isSymbolicLink())throw new Error(`Local client ownership cannot cover a symlink: ${n}`)}function m(n){c(a(n));let t=h(n);if(c(t),!o.existsSync(t))return null;let e;try{e=JSON.parse(o.readFileSync(t,"utf8"))}catch{throw new Error("Invalid local client ownership intent; inspect client/local-install.json")}if(!(e?.schema===1&&["pending","ready"].includes(e.state)&&typeof e.device=="string"&&!!e.device.trim()&&e.configHash===I(j(e.device))&&typeof e.bundleHash=="string"&&/^[a-f0-9]{64}$/.test(e.bundleHash)&&(e.launchAttempted===void 0||typeof e.launchAttempted=="boolean")))throw new Error("Invalid local client ownership intent; inspect client/local-install.json");return e}function H(n,t){if(!(t&&!t.ssh&&!t.clientCommand&&t.clientConnection!=="ssh-reverse"&&typeof t.cortexPath=="string"&&r.resolve(t.cortexPath)===r.resolve(n.DATA_DIR)))throw new Error("Local client machine conflicts with ownership; keep SSH/custom-command machines externally managed")}function k(n,t){let e=r.join(n.CONFIG_DIR,"machines.json");if(!o.existsSync(e))return;let i=JSON.parse(o.readFileSync(e,"utf8"));H(n,i[t])}function N(n,t){if(c(n.CONFIG_DIR),c(f(n)),!!o.existsSync(f(n))&&I(o.readFileSync(f(n),"utf8"))!==t.configHash)throw new Error("Owned local client config was modified; refusing to overwrite config/cortex-client.json")}function O(n){let t=/^local-install\.json\.tmp\.[1-9]\d*\.\d+\.[a-z0-9]{0,6}$/;if(o.readdirSync(a(n),{withFileTypes:!0}).filter(i=>!i.name.startsWith("local-install.json.mutation-lock")&&!(i.isFile()&&t.test(i.name))).length||o.lstatSync(f(n),{throwIfNoEntry:!1}))throw new Error("Unowned local client files/config exist; refusing to adopt or overwrite them")}function w(n,t){p(h(n),JSON.stringify(t,null,2)+`
6
6
  `)}function y(n,t,e){if(t.device!==e)throw new Error("Local client ownership belongs to a different device");k(n,e),N(n,t)}async function G(n,t,e){let i=x(e);c(a(n)),o.mkdirSync(a(n),{recursive:!0}),await d(h(n),async()=>{let s=m(n);if(s)return y(n,s,t);if(k(n,t),O(n),!t.trim())throw new Error("Local client device must not be empty");w(n,{schema:1,state:"pending",device:t,launchAttempted:!1,configHash:I(j(t)),bundleHash:i.hash})})}function D(n,t){let e=r.join(a(n),F);c(e),o.mkdirSync(e,{recursive:!0});for(let i of t.files){let s=r.join(e,i.name);c(s),p(s,Buffer.from(i.data,"base64").toString("utf8"))}if(v(e)!==t.hash)throw new Error("Staged local client hash mismatch");o.renameSync(e,r.join(a(n),"current"))}function T(n,t,e){let i=r.join(a(n),"current");if(c(i),o.existsSync(i)){if(t.state==="ready")return;if(v(i)!==t.bundleHash)throw new Error("Pending local client publication hash mismatch")}else w(n,{...t,state:"pending",bundleHash:e.hash}),D(n,e),t={...t,bundleHash:e.hash};w(n,{...t,state:"ready"})}async function U(n,t,e){await d(h(n),async()=>{e.throwIfAborted();let i=m(n);if(!i)throw new Error("Missing local client ownership intent");y(n,i,t),w(n,{...i,launchAttempted:!0})},{signal:e})}async function W(n,t){await d(h(n),async()=>{let e=m(n);!e||e.device!==t||e.launchAttempted===!1||(y(n,e,t),w(n,{...e,launchAttempted:!1}))})}async function z(n,t,e,i){if(i?.throwIfAborted(),!m(n))throw new Error("Missing local client ownership intent");let s=x(e);await d(h(n),async()=>{i?.throwIfAborted();let l=m(n);if(!l)throw new Error("Missing local client ownership intent");y(n,l,t),o.existsSync(f(n))||p(f(n),j(t)),T(n,l,s)},{signal:i})}export{x as a,m as b,H as c,y as d,G as e,U as f,W as g,z as h};
@@ -1,4 +1,4 @@
1
1
  import { createRequire as __cortexCreateRequire } from 'node:module';
2
2
  const require = __cortexCreateRequire(import.meta.url);
3
3
  const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{e as s,m,n as p,o as l,t as x}from"./chunk-3YHOCPQU.js";var d={adapter:null,bus:null,notify:null,deliverScheduledTurn:null};function A(t){let e=d[t];if(!e)throw new Error(`job ctx: ${t} not injected`);return e}var u=[],L=1;function h(t){u.unshift({id:`sn-${L++}`,ts:new Date().toISOString(),level:t.level??"info",text:t.text,...t.title!==void 0?{title:t.title}:{}}),u.length>50&&(u.length=50)}function j(t){return t===void 0?u.slice():u.slice(0,t)}function M(t){h({level:t.level??"info",text:t.text,...t.title!==void 0?{title:t.title}:{}}),d.bus?.publish({type:"system.notice",level:t.level??"info",text:t.text,...t.title!==void 0?{title:t.title}:{}})}async function F(t,e){M(e);try{let r={type:"system-notice"},i={text:e.text,...e.richBlocks?{richBlocks:e.richBlocks}:{}};return(e.actions?.length?await t.postInteractive(r,{...i,actions:e.actions}):await t.postMessage(r,i)).conduit.length>0}catch{return!1}}import{mkdirSync as O,readdirSync as P,readFileSync as I,rmSync as _,writeFileSync as D}from"node:fs";function X(t,e,r,i){return{backend:t,provider:e,model:r,billing:i,outcomes:{completed:0,failed:0,cancelled:0,rateLimited:0},failures:{},retries:0,fallbacks:0,ttftMs:s("ttftMs"),durationS:s("turnDurationS"),contextPctAtEnd:s("contextPct"),compactions:{auto:0,manual:0},tokens:{input:0,output:0,cacheRead:0,cacheWrite:0}}}var S=()=>({completed:0,failed:0,cancelled:0});function a(t){return{day:t,turns:{},features:{},messagesByChannel:{},uiOps:{},tools:{},agent:{userInterrupts:0,superseded:0,sessionTurns:{},workers:S(),subagents:S()},perf:{startups:[],eventLoopP99s:[],web:{loads:0,ttfbMs:s("webLoadMs"),firstRenderMs:s("webLoadMs"),interactiveMs:s("webLoadMs")},sseReconnects:0,remoteClientDisconnects:0},errors:{byModule:{},samples:[]}}}var T=1440,C=7,o=null,c=m,R=Date.now;function y(t){return new Date(t).toISOString().slice(0,10)}function v(t){try{return JSON.parse(I(t,"utf8"))}catch{return null}}function w(t){try{O(c,{recursive:!0}),D(l(t.day,c),JSON.stringify(t),"utf8")}catch{}}function E(){let t=y(R());if(o?.day===t)return o;o&&w(o);let e=v(l(t,c));return o=e?.day===t?{...a(t),...e}:a(t),o}function z(t){if(x())try{t(E())}catch{}}function Q(t,e){t.perf.eventLoopP99s.push(e),t.perf.eventLoopP99s.length>T&&t.perf.eventLoopP99s.shift()}function N(){o&&w(o)}function g(){try{return P(c).filter(t=>t.startsWith(p)&&t.endsWith(".json")).map(t=>t.slice(p.length,-5))}catch{return[]}}function V(t=R()){let e=y(t);o&&o.day!==e&&N(),o?.day!==e&&(o=null);let r=y(t-C*24*60*60*1e3),i=g().filter(n=>n<e).sort();for(let n of i.filter(f=>f<r))b(n);return i.filter(n=>n>=r).flatMap(n=>{let f=v(l(n,c));return f?.day===n?[{...a(n),...f}]:[]})}function b(t){_(l(t,c),{force:!0})}function Z(){o=null;for(let t of g())b(t)}export{d as a,A as b,j as c,M as d,F as e,X as f,y as g,z as h,Q as i,N as j,V as k,b as l,Z as m};
4
+ import{e as s,n as m,p,q as l,v as x}from"./chunk-BUZQBTV2.js";var d={adapter:null,bus:null,notify:null,deliverScheduledTurn:null};function A(t){let e=d[t];if(!e)throw new Error(`job ctx: ${t} not injected`);return e}var u=[],L=1;function h(t){u.unshift({id:`sn-${L++}`,ts:new Date().toISOString(),level:t.level??"info",text:t.text,...t.title!==void 0?{title:t.title}:{}}),u.length>50&&(u.length=50)}function j(t){return t===void 0?u.slice():u.slice(0,t)}function M(t){h({level:t.level??"info",text:t.text,...t.title!==void 0?{title:t.title}:{}}),d.bus?.publish({type:"system.notice",level:t.level??"info",text:t.text,...t.title!==void 0?{title:t.title}:{}})}async function F(t,e){M(e);try{let r={type:"system-notice"},i={text:e.text,...e.richBlocks?{richBlocks:e.richBlocks}:{}};return(e.actions?.length?await t.postInteractive(r,{...i,actions:e.actions}):await t.postMessage(r,i)).conduit.length>0}catch{return!1}}import{mkdirSync as O,readdirSync as P,readFileSync as I,rmSync as _,writeFileSync as D}from"node:fs";function X(t,e,r,i){return{backend:t,provider:e,model:r,billing:i,outcomes:{completed:0,failed:0,cancelled:0,rateLimited:0},failures:{},retries:0,fallbacks:0,ttftMs:s("ttftMs"),durationS:s("turnDurationS"),contextPctAtEnd:s("contextPct"),compactions:{auto:0,manual:0},tokens:{input:0,output:0,cacheRead:0,cacheWrite:0}}}var S=()=>({completed:0,failed:0,cancelled:0});function a(t){return{day:t,turns:{},features:{},messagesByChannel:{},uiOps:{},tools:{},agent:{userInterrupts:0,superseded:0,sessionTurns:{},workers:S(),subagents:S()},perf:{startups:[],eventLoopP99s:[],web:{loads:0,ttfbMs:s("webLoadMs"),firstRenderMs:s("webLoadMs"),interactiveMs:s("webLoadMs")},sseReconnects:0,remoteClientDisconnects:0},errors:{byModule:{},samples:[]}}}var T=1440,C=7,o=null,c=m,R=Date.now;function y(t){return new Date(t).toISOString().slice(0,10)}function v(t){try{return JSON.parse(I(t,"utf8"))}catch{return null}}function w(t){try{O(c,{recursive:!0}),D(l(t.day,c),JSON.stringify(t),"utf8")}catch{}}function E(){let t=y(R());if(o?.day===t)return o;o&&w(o);let e=v(l(t,c));return o=e?.day===t?{...a(t),...e}:a(t),o}function z(t){if(x())try{t(E())}catch{}}function Q(t,e){t.perf.eventLoopP99s.push(e),t.perf.eventLoopP99s.length>T&&t.perf.eventLoopP99s.shift()}function N(){o&&w(o)}function g(){try{return P(c).filter(t=>t.startsWith(p)&&t.endsWith(".json")).map(t=>t.slice(p.length,-5))}catch{return[]}}function V(t=R()){let e=y(t);o&&o.day!==e&&N(),o?.day!==e&&(o=null);let r=y(t-C*24*60*60*1e3),i=g().filter(n=>n<e).sort();for(let n of i.filter(f=>f<r))b(n);return i.filter(n=>n>=r).flatMap(n=>{let f=v(l(n,c));return f?.day===n?[{...a(n),...f}]:[]})}function b(t){_(l(t,c),{force:!0})}function Z(){o=null;for(let t of g())b(t)}export{d as a,A as b,j as c,M as d,F as e,X as f,y as g,z as h,Q as i,N as j,V as k,b as l,Z as m};
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __cortexCreateRequire } from 'node:module';
2
2
  const require = __cortexCreateRequire(import.meta.url);
3
3
  const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{e as k,na as x}from"./chunk-LACGULCN.js";import{d as X}from"./chunk-FX6MOGLR.js";import{F as h,Ia as R,R as w,f as W,s as I,v as F,w as G,x as H,y as N,za as J}from"./chunk-Q7CE3UIE.js";import{h as P,w as U}from"./chunk-QUUEQRIT.js";import{randomBytes as be}from"node:crypto";import{createWriteStream as Le}from"node:fs";import{writeFile as Ce}from"node:fs/promises";import{tmpdir as Me}from"node:os";import{join as ke}from"node:path";var q=384;function z(e,t){return ke(Me(),`${e}-${be(8).toString("hex")}${t}`)}async function Pt(e,t,n){let r=z(e,t);return await Ce(r,n,{mode:q,flag:"wx"}),r}function Ut(e,t){let n=z(e,t);return{path:n,stream:Le(n,{mode:q,flags:"wx"})}}var Ft=2e3,Gt=51200;function B(e){if(e.length===0)return[];let t=e.split(`
4
+ import{d as X}from"./chunk-FX6MOGLR.js";import{F as h,Ia as R,R as w,f as W,s as I,v as F,w as G,x as H,y as N,za as J}from"./chunk-CK3P345X.js";import{e as k,na as x}from"./chunk-LACGULCN.js";import{h as P,w as U}from"./chunk-QUUEQRIT.js";import{randomBytes as be}from"node:crypto";import{createWriteStream as Le}from"node:fs";import{writeFile as Ce}from"node:fs/promises";import{tmpdir as Me}from"node:os";import{join as ke}from"node:path";var q=384;function z(e,t){return ke(Me(),`${e}-${be(8).toString("hex")}${t}`)}async function Pt(e,t,n){let r=z(e,t);return await Ce(r,n,{mode:q,flag:"wx"}),r}function Ut(e,t){let n=z(e,t);return{path:n,stream:Le(n,{mode:q,flags:"wx"})}}var Ft=2e3,Gt=51200;function B(e){if(e.length===0)return[];let t=e.split(`
5
5
  `);return e.endsWith(`
6
6
  `)&&t.pop(),t}function Ht(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/(1024*1024)).toFixed(1)}MB`}function Jt(e,t={}){let n=t.maxLines??2e3,r=t.maxBytes??51200,o=Buffer.byteLength(e,"utf-8"),i=B(e),s=i.length;if(s<=n&&o<=r)return{content:e,truncated:!1,truncatedBy:null,totalLines:s,totalBytes:o,outputLines:s,outputBytes:o,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:n,maxBytes:r};if(Buffer.byteLength(i[0],"utf-8")>r)return{content:"",truncated:!0,truncatedBy:"bytes",totalLines:s,totalBytes:o,outputLines:0,outputBytes:0,lastLinePartial:!1,firstLineExceedsLimit:!0,maxLines:n,maxBytes:r};let l=[],c=0,p="lines";for(let d=0;d<i.length&&d<n;d++){let m=i[d],y=Buffer.byteLength(m,"utf-8")+(d>0?1:0);if(c+y>r){p="bytes";break}l.push(m),c+=y}l.length>=n&&c<=r&&(p="lines");let u=l.join(`
7
7
  `),f=Buffer.byteLength(u,"utf-8");return{content:u,truncated:!0,truncatedBy:p,totalLines:s,totalBytes:o,outputLines:l.length,outputBytes:f,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:n,maxBytes:r}}function Xt(e,t={}){let n=t.maxLines??2e3,r=t.maxBytes??51200,o=Buffer.byteLength(e,"utf-8"),i=B(e),s=i.length;if(s<=n&&o<=r)return{content:e,truncated:!1,truncatedBy:null,totalLines:s,totalBytes:o,outputLines:s,outputBytes:o,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:n,maxBytes:r};let a=[],l=0,c="lines",p=!1;for(let d=i.length-1;d>=0&&a.length<n;d--){let m=i[d],y=Buffer.byteLength(m,"utf-8")+(a.length>0?1:0);if(l+y>r){if(c="bytes",a.length===0){let A=Ie(m,r);a.unshift(A),l=Buffer.byteLength(A,"utf-8"),p=!0}break}a.unshift(m),l+=y}a.length>=n&&l<=r&&(c="lines");let u=a.join(`
@@ -0,0 +1,50 @@
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 Le,e as Me,f as Ue,g as He,h,i as Ge,l as Ke,w as Ve}from"./chunk-KDPY2YA3.js";import{a as Je,b as Be,c as We,d as qe,e as Xe,h as S,i as L}from"./chunk-W6AKCEYF.js";import{a as ue,b as de,d as me}from"./chunk-FP7ML72L.js";import{a as De,b as we,c as Ee,d as Pe,e as _e,f as je,i as Ae,j as Re,k as Oe,l as Te,m as Ne}from"./chunk-WBSE3EF3.js";import{C as P,u as k,v as $e}from"./chunk-3ORG56I5.js";import{f as ve,m as Ie}from"./chunk-2VVRTJQN.js";import{a as Se}from"./chunk-5NRGVROY.js";import{a as E}from"./chunk-LEAV3FFG.js";import{a as he}from"./chunk-2ATTYCRJ.js";import{b as ae,c as ce,h as le}from"./chunk-KUDK7GPS.js";import{f as ke}from"./chunk-BDLKI2NT.js";import{L as be,n as Ce,o as ye}from"./chunk-JJDEQ6N2.js";import{h as pe}from"./chunk-QUXPMNFQ.js";import{a as _,b as m,c as Fe}from"./chunk-PMG4YGDU.js";import{d as xe}from"./chunk-R52AVUQB.js";import{a as b,b as ge,c as w,e as F}from"./chunk-LP7T32PW.js";import{a as N}from"./chunk-NRD57ICT.js";import{b as oe,q as se}from"./chunk-TX46YMGI.js";import{e as Z}from"./chunk-AVXDF7AG.js";import{e as c}from"./chunk-3CPIMAYX.js";import{e as ie}from"./chunk-VBN2JSER.js";import{b as fe}from"./chunk-NXZS5PEW.js";import{a as ee,d as y,i as te,j as ne,o as p,p as T,q as re}from"./chunk-Z24SBRJK.js";import{a as jt}from"./chunk-VPVSKJGX.js";import{e as _t}from"./chunk-WHC7AYZD.js";import{fork as A}from"child_process";import*as d from"path";import*as wt from"net";import{fileURLToPath as On}from"url";import{existsSync as f,readdirSync as Tn,readFileSync as X,unlinkSync as z}from"fs";var Ye=_t(jt(),1);import*as u from"node:fs";import*as l from"node:path";import{fileURLToPath as At}from"node:url";function Rt(e){if(typeof e!="string")return;let t=e.trim();if(!(!t||t==="null"||t==="undefined"))return t}function Ot(e){let t=e.match(/^v?(\d+)/);return t?Number(t[1]):0}function Tt(e){let t=l.join(e.paths.CONFIG_DIR,".env"),n={},r=e.readText(t);if(r!=null)try{n=e.parseDotenv(r)}catch{n={}}return i=>Rt(e.env[i]??n[i])}function Nt(e){let t=e.defaultSelection()?.backend??"claude";return t==="pi"?{id:"backend-runtime",label:"Backend runtime",status:"pass",detail:"backend: pi runs in-process from the bundled SDK (no CLI needed)"}:e.commandExists("claude")?{id:"backend-runtime",label:"Backend runtime",status:"pass",detail:`claude found on PATH (backend: ${t})`}:{id:"backend-runtime",label:"Backend runtime",status:"warn",detail:`claude not on PATH (backend: ${t})`,hint:"Install/login the claude CLI"}}function Ft(e){return e.commandExists("git")?{id:"git",label:"git",status:"pass",detail:"usable on PATH"}:(e.platform??process.platform)==="win32"?{id:"git",label:"git",status:"fail",detail:"unavailable",hint:"Install Git for Windows \u2014 shell tools require Git Bash"}:{id:"git",label:"git",status:"warn",detail:"unavailable (optional)",hint:"Install Git to enable version history and Git-sourced extensions"}}function Lt(e){let t=[],n=Ot(e.nodeVersion);t.push(n>=e.requiredNodeMajor?{id:"node-version",label:"Node version",status:"pass",detail:`${e.nodeVersion} (>=${e.requiredNodeMajor})`}:{id:"node-version",label:"Node version",status:"warn",detail:`${e.nodeVersion} \u2014 Cortex requires Node >=${e.requiredNodeMajor}`,hint:"Upgrade Node.js"}),t.push(Ft(e)),t.push(Nt(e));let r=l.join(e.paths.STORE_DIR,l.basename(p)),i=e.fileExists(r)?e.readText(r):null,o=i?Number(i.trim()):NaN;return Number.isFinite(o)&&e.pidAlive(o)?t.push({id:"daemon",label:"Daemon",status:"pass",detail:`running (pid ${o})`}):t.push({id:"daemon",label:"Daemon",status:"skip",detail:"not running",hint:"Start with `cortex daemon`"}),{title:"Runtime & Process",checks:t}}function Mt(e,t){let n=[];for(let[r,i]of Object.entries(t.paths))t.fileExists(i)?t.isWritable(i)||n.push(`${r} not writable (${i})`):n.push(`${r} missing (${i})`);e.push(n.length===0?{id:"dirs",label:"Data directories",status:"pass",detail:"present and writable"}:{id:"dirs",label:"Data directories",status:"fail",detail:n.join("; "),hint:"run `cortex doctor --fix` or `cortex init`",fixable:!0})}function Ut(e,t,n){let r=l.join(t.paths.CONFIG_DIR,".env");e.push(t.fileExists(r)?{id:"env-file",label:".env file",status:"pass",detail:r}:{id:"env-file",label:".env file",status:"fail",detail:`missing (${r})`,hint:"run `cortex init`"});let i=[ae,ce].filter(o=>!n(o));e.push(i.length===0?{id:"auth-tokens",label:"Auth tokens",status:"pass",detail:"client + webhook tokens set"}:{id:"auth-tokens",label:"Auth tokens",status:"fail",detail:`missing: ${i.join(", ")}`,hint:"run `cortex doctor --fix` to generate",fixable:!0})}function Qe(e){let t=e.defaultSelection();return t?.backend!=="claude"||!t.connection||t.connection===oe?null:t.connection}function Ht(e){let t=Qe(e);return t!==null&&e.claudeConnections().includes(t)}function Gt(e,t){let n=Qe(t);n===null?e.push({id:"claude-connection",label:"Claude connection",status:"skip",detail:"default does not use a key connection"}):t.claudeConnections().includes(n)?e.push({id:"claude-connection",label:"Claude connection",status:"pass",detail:`${n} configured`}):e.push({id:"claude-connection",label:"Claude connection",status:"warn",detail:`${n} is not configured`,hint:"add the connection in Settings or pick another model"})}function Kt(e,t){let{CONFIG_DIR:n,STORE_DIR:r}=t.paths,i=l.join(r,"agent-state.json"),o=t.fileExists(i)?"agent-state.json":"mode.json";zt(e,t,t.fileExists(i)?i:l.join(r,"mode.json"),"mode-json",o,"warn"),e.push(Yt(t,l.join(n,"models.json")));let s=l.join(n,"mcp-config.json");t.fileExists(s)?Ze(t.readText(s))?e.push({id:"mcp-config",label:"mcp-config.json",status:"pass",detail:"valid"}):e.push({id:"mcp-config",label:"mcp-config.json",status:"warn",detail:"invalid JSON",hint:"run `cortex doctor --fix` to regenerate",fixable:!0}):e.push({id:"mcp-config",label:"mcp-config.json",status:"warn",detail:`missing (${s})`,hint:"run `cortex doctor --fix` to regenerate",fixable:!0})}var M="See docs/backends.md#remote-login",Vt=new Set(["expired","logged-out"]),Jt="Reinstall the Cortex server package \u2014 the PI SDK ships with it";async function Bt(e){let t=e.resolvePiSdk();if(!t)return{id:"pi-runtime",label:"PI runtime",status:"warn",detail:`bundled PI SDK not resolvable (${k})`,hint:Jt};try{let n=await e.loadPiRuntime();if(n.available&&typeof n.runtime.login=="function"){let r=n.version??t.version,i=r?` ${r}`:"";return{id:"pi-runtime",label:"PI runtime",status:"pass",detail:`in-process SDK ${t.package}${i}; login export found`}}}catch{}return{id:"pi-runtime",label:"PI runtime",status:"warn",detail:"bundled PI runtime or login export unavailable",hint:M}}function ze(e,t){return t&&(e.connection??null)===null&&e.backend==="claude"&&e.provider==="anthropic"&&e.state==="logged-out"}function Wt(e,t){let n=e.accounts.filter(a=>a.inUse),r=n.filter(a=>ze(a,t)),i=n.filter(a=>Vt.has(a.state)&&!ze(a,t)),o=[...new Set(i.map(a=>a.provider))].sort();if(i.length>0)return{id:"backend-auth",label:"Backend authentication",status:"warn",detail:`${n.length} in use; ${i.length} expired or logged out: ${o.join(", ")}`,hint:M};let s=r.length>0?"; on a key connection: anthropic":"";return{id:"backend-auth",label:"Backend authentication",status:"pass",detail:`${n.length} in use; 0 expired or logged out${s}`}}async function qt(e,t){try{return Wt(await e.getAuthStatus(),t)}catch{return{id:"backend-auth",label:"Backend authentication",status:"warn",detail:"authentication summary unavailable",hint:M}}}async function Xt(e,t){let n=[];return Mt(n,e),Ut(n,e,t),Gt(n,e),Kt(n,e),n.push(...await Promise.all([Bt(e),qt(e,Ht(e))])),{title:"Backend Install / Login",checks:n}}function Ze(e){if(e==null)return!1;try{return JSON.parse(e),!0}catch{return!1}}function zt(e,t,n,r,i,o){if(!t.fileExists(n)){e.push({id:r,label:i,status:o,detail:`missing (${n})`});return}e.push(Ze(t.readText(n))?{id:r,label:i,status:"pass",detail:"valid"}:{id:r,label:i,status:o,detail:"invalid JSON"})}function Yt(e,t){let n={id:"models",label:"models.json"};if(!e.fileExists(t))return{...n,status:"warn",detail:`missing (${t})`,hint:"run `cortex init`"};try{let r=JSON.parse(e.readText(t)??"");if(r?.default&&(r.default=se(r.default)),ye(r?.default),!Array.isArray(r?.favorites))throw new Error("missing `favorites` array");return r.favorites.forEach(Ce),{...n,status:"pass",detail:`default: ${r.default.model}; favorites: ${r.favorites.length}`}}catch(r){return{...n,status:"fail",detail:r.message,hint:"re-run `cortex init`"}}}function Qt(e,t){let n=[],i=(t("CORTEX_PLATFORM")??"slack").split(",").map(o=>o.trim().toLowerCase()).filter(Boolean);n.push({id:"platform",label:"Platform",status:"pass",detail:`configured: ${i.join(", ")||"(none)"}`});for(let o of i)if(o==="slack"){let s=[],a=t("SLACK_BOT_TOKEN"),g=t("SLACK_SIGNING_SECRET"),O=t("SLACK_APP_TOKEN");a?a.startsWith("xoxb-")||s.push("SLACK_BOT_TOKEN should start with xoxb-"):s.push("SLACK_BOT_TOKEN missing"),g||s.push("SLACK_SIGNING_SECRET missing"),O?O.startsWith("xapp-")||s.push("SLACK_APP_TOKEN should start with xapp-"):s.push("SLACK_APP_TOKEN missing"),n.push(s.length===0?{id:"slack-creds",label:"Slack credentials",status:"pass",detail:"bot / signing / app tokens present"}:{id:"slack-creds",label:"Slack credentials",status:"fail",detail:s.join("; "),hint:"set Slack tokens in .env (see `cortex init`)"})}else if(o==="feishu"){let s=[];t("FEISHU_APP_ID")||s.push("FEISHU_APP_ID missing"),t("FEISHU_APP_SECRET")||s.push("FEISHU_APP_SECRET missing"),n.push(s.length===0?{id:"feishu-creds",label:"Feishu credentials",status:"pass",detail:"app id / secret present"}:{id:"feishu-creds",label:"Feishu credentials",status:"fail",detail:s.join("; "),hint:"set FEISHU_APP_ID / FEISHU_APP_SECRET in .env"})}else o==="test"?n.push({id:"test-platform",label:"Test platform",status:"skip",detail:"mock adapter (test only)"}):n.push({id:`platform-${o}`,label:`Platform: ${o}`,status:"warn",detail:"unknown platform name"});return{title:"Messaging Platform",checks:n}}async function U(e){let t=Tt(e),n=[Lt(e),await Xt(e,t),Qt(e,t)],r={pass:0,warn:0,fail:0,skip:0};for(let i of n)for(let o of i.checks)r[o.status]++;return{sections:n,counts:r,ok:r.fail===0}}async function et(e,t,n){let r=new Map;for(let s of e.sections)for(let a of s.checks)a.fixable&&(a.status==="fail"||a.status==="warn")&&r.set(a.id,a);let i=[],o=l.join(t.paths.CONFIG_DIR,".env");if(r.has("dirs")){for(let s of[t.paths.DATA_DIR,t.paths.CONFIG_DIR,t.paths.STORE_DIR])n.mkdirp(s);i.push({id:"dirs",label:"Data directories",applied:!0,detail:"created missing directories"})}if(r.has("auth-tokens")){n.ensureEnvFile(o);let s=n.ensureAuthTokens(o);i.push({id:"auth-tokens",label:"Auth tokens",applied:s.length>0,detail:s.length>0?`generated: ${s.join(", ")}`:"already present"})}return r.has("mcp-config")&&(n.regenerateMcpConfig(),i.push({id:"mcp-config",label:"mcp-config.json",applied:!0,detail:"regenerated"})),i}function Zt(e){if(e==="git")return he();let t=process.env.PATH||"",n=process.platform==="win32"?(process.env.PATHEXT||".EXE;.CMD;.BAT").split(";"):[""];for(let r of t.split(l.delimiter))if(r)for(let i of n){let o=l.join(r,e+i);try{if(u.existsSync(o))return!0}catch{}}return!1}function en(){let e;try{e=l.dirname(At(import.meta.resolve(k)))}catch{return null}for(;;){try{let n=JSON.parse(u.readFileSync(l.join(e,"package.json"),"utf8"));if(n?.name===k)return{package:k,version:typeof n.version=="string"?n.version:null}}catch{}let t=l.dirname(e);if(t===e)return{package:k,version:null};e=t}}function tt(){return{env:process.env,paths:{DATA_DIR:y,CONFIG_DIR:te,STORE_DIR:ne},nodeVersion:process.version,requiredNodeMajor:20,fileExists:e=>{try{return u.existsSync(e)}catch{return!1}},isWritable:e=>{try{return u.accessSync(e,u.constants.W_OK),!0}catch{return!1}},readText:e=>{try{return u.readFileSync(e,"utf8")}catch{return null}},parseDotenv:e=>(0,Ye.parse)(e),commandExists:Zt,pidAlive:b,resolvePiSdk:en,loadPiRuntime:()=>$e(),getAuthStatus:()=>P(),defaultSelection:tn,claudeConnections:()=>be.claudeConnections().filter(e=>e.kind==="key"||e.kind==="account").map(e=>e.id)}}function tn(){try{let e=Ie();return e?{backend:e.backend,connection:e.backend==="claude"?ke(e):null}:null}catch{return null}}function nt(){return{mkdirp:e=>{u.mkdirSync(e,{recursive:!0})},ensureEnvFile:e=>{u.existsSync(e)||(u.mkdirSync(l.dirname(e),{recursive:!0}),u.writeFileSync(e,""))},ensureAuthTokens:e=>le({envPath:e}).generated,regenerateMcpConfig:()=>ve()}}function nn(){return _({name:"cortex doctor",description:"Health-check the Cortex installation \u2014 runtime, backend/login, messaging platform.",usage:"cortex doctor [options]",options:[{flag:"--fix",description:"Apply safe, idempotent repairs (generate missing tokens, create dirs, rebuild mcp-config)"},{flag:"--json",description:"Emit the report as JSON"},{flag:"--help, -h",description:"Show this help"}],examples:[{description:"Run a read-only diagnosis",command:"cortex doctor"},{description:"Diagnose and auto-repair fixable issues",command:"cortex doctor --fix"},{description:"Machine-readable output",command:"cortex doctor --json"}]})}var rn={pass:"[OK] ",warn:"[WARN]",fail:"[FAIL]",skip:"[--] "};function on(e,t){let n=["Cortex Doctor",""];for(let s of e.sections){n.push(s.title);for(let a of s.checks)n.push(` ${rn[a.status]} ${a.label} \u2014 ${a.detail}`),a.hint&&(a.status==="fail"||a.status==="warn")&&n.push(` \u21B3 ${a.hint}`);n.push("")}if(t.length>0){n.push("Fixes applied:");for(let s of t)n.push(` ${s.applied?"[OK] ":"[--] "} ${s.label} \u2014 ${s.detail}`);n.push("")}let{pass:r,warn:i,fail:o}=e.counts;return n.push(`Summary: ${r} passed, ${i} warning${i===1?"":"s"}, ${o} failed`),(o>0||i>0)&&e.sections.some(a=>a.checks.some(g=>g.fixable&&(g.status==="fail"||g.status==="warn")))&&n.push("Run `cortex doctor --fix` to auto-repair fixable issues."),n.join(`
5
+ `).trimEnd()+`
6
+ `}async function rt(e,t){if(e.includes("--help")||e.includes("-h"))return{exitCode:0,stdout:nn(),stderr:""};let n=e.includes("--json"),r=e.includes("--fix"),i=t?.diag??tt(),o=t?.fix??nt(),s=await U(i),a=[];r&&(a=await et(s,i,o),s=await U(i));let g=n?JSON.stringify({...s,fixes:r?a:void 0},null,2)+`
7
+ `:on(s,a);return{exitCode:s.ok?0:1,stdout:g,stderr:""}}var it=["list","add","remove"];function sn(){return{validValues:c("provider.cli.validValues"),hint:c("provider.cli.hint")}}function x(e,t){return{exitCode:1,stdout:"",stderr:m(e,{...t,labels:sn()})}}function ot(){return _({name:"cortex auth provider",description:c("provider.cli.description"),usage:"cortex auth provider <list|add|remove> [options]",commands:[{name:"list",description:c("provider.cli.listDescription")},{name:"add",description:c("provider.cli.addDescription")},{name:"remove",description:c("provider.cli.removeDescription")}],options:[{flag:"--name <name>",description:c("provider.cli.nameDescription")},{flag:"--api <api>",description:`${c("provider.cli.apiDescription")} (${E.join(" | ")})`},{flag:"--url <url>",description:c("provider.cli.urlDescription")},{flag:"--key <key|->",description:c("provider.cli.keyDescription")},{flag:"--model <id>",description:c("provider.cli.modelDescription")},{flag:"--dry-run",description:c("provider.cli.dryRunDescription")},{flag:"--json",description:c("provider.cli.jsonDescription")},{flag:"--help, -h",description:c("provider.cli.helpDescription")}],examples:[{description:c("provider.cli.exampleAdd"),command:"cortex auth provider add --name my-vllm --api anthropic-messages --url http://127.0.0.1:8100 --model Model-27B"},{description:c("provider.cli.exampleAddPiped"),command:"pass show my-endpoint | cortex auth provider add --name my-proxy --api openai-completions --url https://proxy.example.com/v1 --model small --key -"},{description:c("provider.cli.exampleList"),command:"cortex auth provider list --json"},{description:c("provider.cli.exampleRemove"),command:"cortex auth provider remove --name my-vllm --dry-run"}],labels:{usage:c("cmd.auth.cli.helpUsage"),commands:c("cmd.auth.cli.helpCommands"),options:c("cmd.auth.cli.helpOptions"),examples:c("cmd.auth.cli.helpExamples")}})}var an=new Set(["--name","--api","--url","--key"]);function cn(e){let t=new Map,n=[],r=!1,i=!1;for(let o=0;o<e.length;o+=1){let s=e[o];if(s==="--json"){r=!0;continue}if(s==="--dry-run"){i=!0;continue}if(s==="--model"||an.has(s)){let a=e[o+1];if(a===void 0||a.startsWith("--"))return x(c("provider.cli.flagNeedsValue",{flag:s}),{hint:"cortex auth provider --help"});o+=1,s==="--model"?n.push(a):t.set(s,a);continue}return x(c("provider.cli.unknownFlag",{flag:s}),{validValues:["--name","--api","--url","--key","--model","--dry-run","--json"],hint:"cortex auth provider --help"})}return{values:t,models:n,json:r,dryRun:i}}function H(e){return c(`provider.issue.${e}`)}function ln(e){return e.routed?c("provider.cli.listItem",{name:e.name,api:e.api,upstream:e.upstreamUrl??""}):c("provider.cli.listItemUnrouted",{name:e.name,api:e.api})}function un(e,t){let n=Ee(t);return e.json?{exitCode:0,stdout:JSON.stringify({ok:!0,providers:n},null,2),stderr:""}:{exitCode:0,stdout:n.length===0?c("provider.cli.listEmpty"):n.map(ln).join(`
8
+ `),stderr:""}}function dn(e,t){let n=e.values.get("--key");return n===void 0?void 0:n!=="-"?n:(t.readSecret??Fe)().trim()}function mn(e,t,n){for(let s of["--name","--api","--url"])if(!e.values.has(s))return x(c("provider.cli.missingFlag",{flag:s}),{hint:"cortex auth provider add --help"});let r=e.values.get("--api");if(!E.includes(r))return x(H("api-invalid"),{validValues:[...E],hint:"cortex auth provider add --help"});let i=_e(t,{name:e.values.get("--name"),api:r,upstreamUrl:e.values.get("--url"),apiKey:dn(e,n),models:e.models.map(s=>({id:s}))});return i.ok===!1?x(i.errors.map(H).join(`
9
+ `),{hint:"cortex auth provider add --help"}):{exitCode:0,stdout:e.json?JSON.stringify({ok:!0,provider:i.provider},null,2):c("provider.cli.added",{name:i.provider.name,upstream:i.provider.upstreamUrl??""}),stderr:""}}function fn(e,t){let n=e.values.get("--name");if(!n)return x(c("provider.cli.missingFlag",{flag:"--name"}),{hint:"cortex auth provider remove --help"});let r=Pe(t,n);if(!r)return x(c("provider.cli.notFound",{name:n}),{hint:"cortex auth provider list"});if(e.dryRun)return{exitCode:0,stdout:JSON.stringify({dry_run:!0,would_remove:r},null,2),stderr:""};let i=je(t,n);return i.ok===!1?x(i.errors.map(H).join(`
10
+ `),{hint:"cortex auth provider list"}):{exitCode:0,stdout:e.json?JSON.stringify({ok:!0,name:n},null,2):c("provider.cli.removed",{name:n}),stderr:""}}function st(e,t,n={}){if(e.length===0||e[0]==="--help"||e[0]==="-h")return{exitCode:0,stdout:ot(),stderr:""};let r=e[0];if(!it.includes(r))return x(c("provider.cli.unknownSubcommand",{command:r}),{validValues:[...it],hint:"cortex auth provider --help"});let i=e.slice(1);if(i.includes("--help")||i.includes("-h"))return{exitCode:0,stdout:ot(),stderr:""};let o=cn(i);return"values"in o?r==="list"?un(o,t):r==="add"?mn(o,t,n):fn(o,t):o}function at(){return{validValues:c("cmd.auth.cli.validValues"),hint:c("cmd.auth.cli.hint")}}function pn(e){if(e.length===0||e[0]==="--help"||e[0]==="-h")return{exitCode:0,stdout:L(),stderr:""};if(e[0]==="status")return e.slice(1);let t=c("cmd.auth.cli.unknownSubcommand",{command:e[0]});return{exitCode:1,stdout:"",stderr:m(t,{validValues:["status","login","provider"],hint:"cortex auth --help",labels:at()})}}function hn(e){if(e.includes("--help")||e.includes("-h"))return{exitCode:0,stdout:L(),stderr:""};let t=e.find(i=>i!=="--json");if(!t)return null;let n=c("cmd.auth.cli.unknownFlag",{flag:t});return{exitCode:1,stdout:"",stderr:m(n,{validValues:["--json"],hint:"cortex auth status --help",labels:at()})}}async function ct(e,t,n){if(e[0]==="login")return Me(e.slice(1));if(e[0]==="provider")return st(e.slice(1),n);let r=pn(e);if(!Array.isArray(r))return r;let i=hn(r);if(i)return i;let o=await t();return{exitCode:0,stdout:r.includes("--json")?JSON.stringify(o,null,2):De(o),stderr:""}}import*as dt from"node:path";var lt=["enable","pair"];function G(e,t){let n=e.indexOf(t);return n!==-1&&e[n+1]?e[n+1]:void 0}function K(e,t){return{exitCode:1,stdout:"",stderr:m(e,t)}}async function xn(e){let t=e.includes("--json"),n=G(e,"--port"),r=n===void 0?void 0:Number(n);if(r!==void 0&&(!Number.isInteger(r)||r<1||r>65535))return K(`Invalid --port: '${n}'.`,{validValues:["an integer in 1-65535"],hint:"cortex ui enable --port 26790"});let i=h(G(e,"--home"));try{let o=await He({configDir:i.CONFIG_DIR,port:r});if(t){let a={ok:!0,home:i.DATA_DIR,...o};return{exitCode:0,stdout:`${JSON.stringify(a,null,2)}
11
+ `,stderr:""}}return{exitCode:0,stdout:`${[`Web UI endpoint enabled: ${o.url}`,`Home: ${i.DATA_DIR}`,o.changed?"Configuration changed \u2014 restart the daemon to apply (cortex daemon restart).":"Already configured \u2014 no restart needed.","Connect another app or browser with a one-time code from `cortex ui pair`."].join(`
12
+ `)}
13
+ `,stderr:""}}catch(o){return{exitCode:1,stdout:"",stderr:o.message||String(o)}}}async function gn(e){let t=h(G(e,"--home")),n=me({file:dt.join(t.STORE_DIR,ue)}),{code:r,expiresAt:i}=n.create();return e.includes("--json")?{exitCode:0,stdout:`${JSON.stringify({ok:!0,code:r,expiresAt:i},null,2)}
14
+ `,stderr:""}:{exitCode:0,stdout:`${[`Pairing code: ${r}`,`Valid for ${de/6e4} minutes, once.`,"Enter it with this server's address in the Cortex app, or on the browser sign-in page."].join(`
15
+ `)}
16
+ `,stderr:""}}var ut={enable:xn,pair:gn};async function mt(e){if(e.length===0)return K("Missing subcommand for 'ui'.",{validValues:lt,hint:"cortex ui --help"});if(e.includes("--help")||e.includes("-h"))return{exitCode:0,stdout:We(),stderr:""};let t=Object.hasOwn(ut,e[0])?ut[e[0]]:void 0;return t?t(e):K(`Unknown subcommand: '${e[0]}'.`,{validValues:lt,hint:"cortex ui --help"})}import*as pt from"node:fs";import*as C from"node:path";var I=class extends Error{validValues;hint;constructor(t,n,r){super(t),this.validValues=n,this.hint=r}},ht="client-pids.json",xt="client-routes.json";function j(e){try{return JSON.parse(pt.readFileSync(e,"utf8"))}catch{return{}}}function V(e,t,n=!1){let r=j(e);t in r&&(delete r[t],Z(e,`${JSON.stringify(r,null,2)}${n?`
17
+ `:""}`))}function vn(e,t){return Ae(e,t,3e4)}var Cn=/"([^"]+?)[\\/]client[\\/]current[\\/]client\.mjs"|(\S+?)[\\/]client[\\/]current[\\/]client\.mjs/;function gt(e){let t=e.clientCommand?.match(Cn),n=t?.[1]??t?.[2];return n||(e.win?"%USERPROFILE%\\.cortex":"$HOME/.cortex")}function yn(e){return[`h="${e}"`,'k=$(pgrep -f "$h/client/current/client[.]mjs" | xargs); [ -n "$k" ] && kill $k; echo "killed=${k:-none}"','if [ -f "$h/config/machines.json" ]; then echo files=kept-server-home; else',' rm -rf "$h/client"; rm -f "$h/config/cortex-client.json" "$h"/logs/client-*.log',' rmdir "$h/logs" "$h/config" "$h" 2>/dev/null; echo files=removed',"fi"].join(`
18
+ `)}function bn(e){let t=`powershell -NoProfile -Command "$k = @(Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -like '*${e}\\client\\current\\client[.]mjs*' }); $k | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }; 'killed=' + (@($k | ForEach-Object { $_.ProcessId }) -join ' ')"`,n=`rmdir /s /q "${e}\\client" 2>nul & del /q "${e}\\config\\cortex-client.json" 2>nul & del /q "${e}\\logs\\client-*.log" 2>nul & echo files=removed`;return`${t} & if exist "${e}\\config\\machines.json" (echo files=kept-server-home) else (${n})`}function kn(e){return(e.win?bn:yn)(gt(e))}function ft(e,t){return e.match(new RegExp(`^${t}=(.*)$`,"m"))?.[1]?.trim()||"none"}async function Sn(e,t){try{let n=await t(e.ssh,kn(e));return{status:"cleaned",killed:ft(n,"killed"),files:ft(n,"files")}}catch(n){return{status:"unreachable",error:n.message}}}function In(e,t){let n=e[t];if(!n){let r=Object.keys(e).filter(i=>e[i].ssh);throw new I(`Unknown device: '${t}'.`,r,"cortex client remove --device <name>")}if(!n.ssh)throw new I(`'${t}' is the server's local machine and has no remote client to remove.`,void 0,"edit config/machines.json by hand if this machine really should go");return n}function $n(e,t){let n=j(C.join(t.configDir,"machines.json")),r=In(n,e.device),i=j(C.join(t.storeDir,ht))[e.device],o=j(C.join(t.storeDir,xt))[e.device];return{machine_entry:r,runtime:{pid:typeof i=="number"?i:null,route:typeof o=="string"?o:null},remote:e.keepRemote?null:{host:r.ssh,home:gt(r)}}}async function vt(e,t){let n=$n(e,t),{device:r}=e;if(e.dryRun)return{ok:!0,device:r,dry_run:!0,would_remove:n};V(C.join(t.configDir,"machines.json"),r,!0);let i=n.remote?await Sn(n.machine_entry,t.remoteExec??vn):{status:"skipped"};return V(C.join(t.storeDir,ht),r),V(C.join(t.storeDir,xt),r),{ok:!0,device:r,dry_run:!1,removed_at:new Date().toISOString(),machine_entry:n.machine_entry,runtime:n.runtime,remote:i}}var Ct=["--device","--home"],yt=["--keep-remote","--dry-run"];function $(e,t,n="cortex client remove --help"){return{exitCode:1,stdout:"",stderr:m(e,{validValues:t,hint:n})}}function Dn(e){let t={};for(let n=0;n<e.length;n+=1){let r=e[n];if(yt.includes(r)){t[r]=!0;continue}if(!Ct.includes(r))return $(`Unknown option: '${r}'.`,[...Ct,...yt]);let i=e[n+1];if(!i||i.startsWith("--"))return $(`Missing value for ${r}.`);t[r]=i,n+=1}return t}async function wn(e,t){let n=Dn(e);if("exitCode"in n)return n;if(typeof n["--device"]!="string")return $("Missing --device.",void 0,"cortex client remove --device <name>");let r=h(n["--home"]);try{let i=await vt({device:n["--device"],keepRemote:n["--keep-remote"]===!0,dryRun:n["--dry-run"]===!0},{configDir:r.CONFIG_DIR,storeDir:r.STORE_DIR,remoteExec:t}),o=i.remote?.status==="unreachable"?`Warning: '${i.device}' was removed locally, but its machine could not be reached; the remote client was not uninstalled.`:"";return{exitCode:0,stdout:`${JSON.stringify(i,null,2)}
19
+ `,stderr:o}}catch(i){return i instanceof I?$(i.message,i.validValues,i.hint):{exitCode:1,stdout:"",stderr:i.message}}}async function bt(e,t){return e.includes("--help")||e.includes("-h")?{exitCode:0,stdout:Xe(),stderr:""}:e.length===0?$("Missing subcommand for 'client'.",["remove"],"cortex client --help"):e[0]!=="remove"?$(`Unknown subcommand: '${e[0]}'.`,["remove"],"cortex client --help"):wn(e.slice(1),t)}var En=["install","remove","status"];function Pn(e,t){let n=e.indexOf(t);return n!==-1&&e[n+1]?e[n+1]:void 0}var kt=e=>({exitCode:1,stdout:"",stderr:m(e,{validValues:En,hint:"cortex path --help"})});function J(e,t,n){let r=e.path_targets.filter(i=>i[t]).map(i=>i.target);return`${n}: ${r.length?r.join(", "):"none"}`}function _n(e){let t=[`${e.dry_run?"Would install":"Installed"} terminal commands in ${e.dir}`,J(e,"changed",e.dry_run?"PATH would change in":"PATH updated in"),"Open a new terminal to use `cortex`."];return e.shadowed.length&&t.push(`New terminals will use this install instead of: ${e.shadowed.join(", ")}`),process.env.SHELL?.endsWith("fish")&&t.push(`fish is not configured automatically; run: fish_add_path ${e.dir}`),t}function jn(e){return[`${e.dry_run?"Would remove":"Removed"} ${e.removed.length} command file(s) from ${e.dir}`,J(e,"changed",e.dry_run?"PATH would change in":"PATH restored in")]}function An(e){return[`Terminal commands: ${e.installed?"installed":"not installed"} (${e.dir})`,...e.stale.length?[`Out of date: ${e.stale.join(", ")} \u2014 rerun cortex path install`]:[],J(e,"registered","On PATH via")]}var Rn={install:(e,t)=>{let n=Oe(e,t);return{report:n,text:_n(n)}},remove:(e,t)=>{let n=Te(e,t);return{report:n,text:jn(n)}},status:e=>{let t=Ne(e);return{report:t,text:An(t)}}};function St(e,t=Re){if(e.includes("--help")||e.includes("-h"))return{exitCode:0,stdout:qe(),stderr:""};if(e.length===0)return kt("Missing subcommand for 'path'.");let n=Rn[e[0]];if(!n)return kt(`Unknown subcommand: '${e[0]}'.`);try{let r=t(h(Pn(e,"--home")).DATA_DIR),{report:i,text:o}=n(r,e.includes("--dry-run"));return{exitCode:0,stdout:e.includes("--json")?`${JSON.stringify(i,null,2)}
20
+ `:`${o.join(`
21
+ `)}
22
+ `,stderr:""}}catch(r){return{exitCode:1,stdout:"",stderr:`cortex path ${e[0]} failed: ${r?.message??String(r)}
23
+ `}}}var v=ie("cli"),Y=d.dirname(On(new URL("dist/entry/cli.js",__cortexPackageRoot).href)),B=d.join(Y,"app.js"),D=d.join(Y,"daemon.js"),W=d.join(Y,"..","tui","index.js");function Nn(e){let t={resume:!1};for(let n=0;n<e.length;n++)switch(e[n]){case"--resume":t.resume=!0;break;case"--project":t.project=e[++n];break;case"--port":t.port=Number(e[++n]);break}return t}function Fn(e){return new Promise(t=>{let n=wt.connect({host:"127.0.0.1",port:e},()=>{n.end(),t(!0)});n.setTimeout(500),n.on("timeout",()=>{n.destroy(),t(!1)}),n.on("error",()=>t(!1))})}async function Ln(e){let t=Nn(e),n=t.port??pe();await Fn(n)||(process.stderr.write(`Cortex daemon is not running on port ${n}.
24
+ Start it with: cortex daemon
25
+ `),process.exit(1)),f(W)||(v.error(`TUI entry not found: ${W}`),v.error("Run `npm run build` first."),process.exit(1));let r=["--port",String(n)];t.resume&&r.push("--resume"),t.project&&r.push("--project",t.project),A(W,r,{stdio:"inherit"}).on("exit",o=>process.exit(o??0)),await new Promise(()=>{})}function R(){if(!f(p))return{result:{exitCode:0,stdout:`Cortex daemon is not running.
26
+ `,stderr:""}};let e=w(p);if(e===null){try{z(p)}catch{}return{result:{exitCode:0,stdout:`Cortex daemon is not running (removed corrupted PID file).
27
+ `,stderr:""}}}if(!ge(p,e)){try{z(p)}catch{}return{result:{exitCode:0,stdout:`Cortex daemon is not running (removed stale PID file for PID ${e}).
28
+ `,stderr:""}}}return{pid:e}}async function Mn(){let e=R();if("result"in e)return It(e.result);let t=await Un(e.pid);return t.daemonGone?It(t.result):t.result}async function It(e){let{exitCode:t,stdout:n,stderr:r}=e;try{let{stopLaunchedLocalClients:i}=await import("./local-client-stop-5YOLXGYT.js");for(let{device:o,pid:s,outcome:a}of await i())a==="stopped"&&(n+=`Stopped local client ${o} (PID ${s}).
29
+ `),a==="unverified"&&(r+=`Left local client ${o} (PID ${s}) running: could not confirm the process is its client.
30
+ `),a==="survived"&&(t=1,r+=`Local client ${o} (PID ${s}) did not exit.
31
+ `)}catch(i){r+=`Could not stop the local client: ${i.message||String(i)}
32
+ `}return{exitCode:t,stdout:n,stderr:r}}async function Un(e){try{process.kill(e,"SIGTERM")}catch(i){return{daemonGone:!1,result:{exitCode:1,stdout:"",stderr:`Failed to send signal to daemon (PID ${e}): ${i.message}
33
+ `}}}let t=1e4,n=200,r=Date.now()+t;for(;Date.now()<r;){await new Promise(i=>setTimeout(i,n));try{process.kill(e,0)}catch{break}}try{process.kill(e,0);try{process.kill(e,"SIGKILL")}catch{}return{daemonGone:!b(e),result:{exitCode:1,stdout:"",stderr:`Daemon (PID ${e}) did not stop within ${t/1e3}s. Forcibly killed (SIGKILL).
34
+ `}}}catch{}try{w(p)===e&&z(p)}catch{}return{daemonGone:!0,result:{exitCode:0,stdout:`Cortex daemon stopped (PID ${e}).
35
+ `,stderr:""}}}function Et(e){try{let t=`/proc/${e}/stat`;if(!f(t))return"unknown";let n=X(t,"utf8"),r=n.lastIndexOf(")"),i=n.substring(r+2).split(" "),o=parseInt(i[19],10);if(!Number.isFinite(o))return"unknown";let s=X("/proc/uptime","utf8"),a=parseFloat(s.split(" ")[0]),Pt=Date.now()-a*1e3+o/100*1e3,Q=Date.now()-Pt;return Q<0?"unknown":Se(Q)}catch{return"unknown"}}function Hn(){let e=R();if("result"in e)return e.result;let{pid:t}=e,n=Et(t),r=["Cortex daemon is running.",` PID: ${t}`,` Uptime: ${n}`];return r.push(` Child: ${Gn(w(T))}`),{exitCode:0,stdout:r.join(`
36
+ `)+`
37
+ `,stderr:""}}function Gn(e){if(e!==null&&b(e))return`app.js (PID ${e}, uptime ${Et(e)})`;let t=xe();return t?`stopped \u2014 ${t.message}`:e===null?"starting...":`none (stale PID ${e} \u2014 daemon will restart)`}function Kn(){let e=R();if("result"in e)return{exitCode:1,stdout:"",stderr:`Cortex daemon is not running. Nothing to restart.
38
+ `};try{return F(),{exitCode:0,stdout:`Restart signal sent to daemon (PID ${e.pid}).
39
+ `,stderr:""}}catch(t){return{exitCode:1,stdout:"",stderr:`Failed to signal daemon restart: ${t.message||String(t)}
40
+ `}}}function $t(e){if("result"in R())return{exitCode:1,stdout:"",stderr:`Cortex daemon is not running.
41
+ `};let t=w(T);if(t===null)return{exitCode:1,stdout:"",stderr:`No child PID file found. Is app.js running?
42
+ `};if(!b(t))return{exitCode:1,stdout:"",stderr:`Child process (PID ${t}) is not running.
43
+ `};let n=e?"SIGKILL":"SIGTERM";try{process.kill(t,n)}catch(r){return{exitCode:1,stdout:"",stderr:`Failed to send ${n} to app.js (PID ${t}): ${r.message}
44
+ `}}return{exitCode:0,stdout:`Sent ${n} to app.js (PID ${t}). Daemon will restart it automatically.
45
+ `,stderr:""}}function Vn(){let e={INSTALL_ROOT:ee,...h()},t=d.join(e.CONFIG_DIR,".env"),n=d.join(e.CONFIG_DIR,"mcp-config.json"),r=d.join(e.STORE_DIR,"agent-state.json"),i=d.join(e.STORE_DIR,"mode.json"),o=0;try{o=Tn(e.STORE_DIR).length}catch{}let s={dataDirExists:f(e.DATA_DIR)&&o>0,dotEnvExists:f(t),mcpConfigExists:f(n),modeJsonExists:f(r)||f(i)};return Ke(e,s)}function Dt(e,t){let n=e.indexOf(t);return n!==-1&&e[n+1]?e[n+1]:void 0}async function Jn(e){if(e.includes("--help")||e.includes("-h"))return{exitCode:0,stdout:Je(),stderr:""};let t=Dt(e,"--home"),n=Dt(e,"--answers");try{let r=n?Ge(X(d.resolve(n),"utf-8")):void 0;return await Ve({homeDir:t,force:e.includes("--force"),answers:r,jsonEvents:e.includes("--json")}),{exitCode:0,stdout:"",stderr:""}}catch(r){return r instanceof Le&&r.exitCode===130?{exitCode:130,stdout:"",stderr:c("init.cancel")}:{exitCode:1,stdout:"",stderr:r.message||String(r)}}}function Bn(){let e=re;try{return F(e),{exitCode:0,stdout:`Restart trigger touched: ${e}
46
+ If a daemon is running it will drain and respawn app.js.
47
+ `,stderr:""}}catch(t){return{exitCode:1,stdout:"",stderr:`Could not write ${e}: ${t.message||String(t)}`}}}async function Wn(e){let{runCli:t,getInstallHelp:n}=await import("./install-cli-ABBD7DO5.js");return e.includes("--help")||e.includes("-h")?{exitCode:0,stdout:n(),stderr:""}:t(e)}function qn(e){return e[1]==="--hard"?$t(!1):e[1]==="--force"?$t(!0):Kn()}function Xn(e){return e[0]==="stop"?Mn():e[0]==="status"?Hn():e[0]==="restart"?qn(e):null}async function zn(e){let t=Xn(e);return t||(e.includes("--help")||e.includes("-h")?{exitCode:0,stdout:S(),stderr:""}:e.includes("--version")||e.includes("-V")?{exitCode:0,stdout:`${N}
48
+ `,stderr:""}:{exitCode:0,stdout:"",stderr:`'daemon' must be run from the main entry point, not imported.
49
+ Use: node dist/entry/cli.js daemon`})}var Yn={init:e=>Jn(e),config:()=>({exitCode:0,stdout:Vn(),stderr:""}),auth:(e,t)=>ct(e,t.getAuthStatus??P,t.customProviderStores??we()),doctor:e=>rt(e),feishu:e=>Ue(e),restart:()=>Bn(),ui:e=>mt(e),client:e=>bt(e),path:e=>St(e),install:e=>Wn(e),schedule:async e=>(await import("./schedule-cli-4T4YC5V5.js")).runScheduleCli(e),memory:async e=>(await import("./memory-cli-5SSF6YJM.js")).runMemoryCli(e),start:()=>({exitCode:0,stdout:"",stderr:`'start' must be run from the main entry point, not imported.
50
+ Use: node dist/entry/cli.js start`}),daemon:e=>zn(e)};async function q(e,t={}){if(e.length===0||e[0]==="--help"||e[0]==="-h")return{exitCode:0,stdout:S(),stderr:""};let n=Yn[e[0]];return n?n(e.slice(1),t):{exitCode:1,stdout:"",stderr:`Unknown command: '${e[0]}'. Use --help to see available commands.`}}function Qn(){let e=process.argv.slice(2);(e.length===0||e[0]==="--help"||e[0]==="-h")&&(console.log(S()),process.exit(0));let t=e[0],n=e.slice(1);if((n.includes("--help")||n.includes("-h"))&&(t==="daemon"&&(console.log(S()),process.exit(0)),t==="start"&&(console.log(S()),process.exit(0)),t==="tui"&&(console.log(Be()),process.exit(0))),(n.includes("--version")||n.includes("-V"))&&t==="daemon"&&(console.log(N),process.exit(0)),t==="start"){f(B)||(v.error(`Entry not found: ${B}`),v.error("Run `npm run build` first."),process.exit(1)),A(B,[],{cwd:y,stdio:"inherit",env:{...process.env}}).on("exit",i=>process.exit(i??0));return}if(t==="daemon"){if(n[0]==="restart-self"){q(["daemon","stop"]).then(async i=>{i.stdout&&console.log(i.stdout),i.stderr&&console.error(i.stderr),f(D)||(v.error(`Entry not found: ${D}`),v.error("Run `npm run build` first."),process.exit(1)),console.log("Starting daemon..."),A(D,[],{cwd:y,detached:!0,stdio:"ignore",env:{...process.env}}),process.exit(0)});return}if(n[0]==="stop"||n[0]==="status"||n[0]==="restart"){q(e).then(i=>{i.stdout&&console.log(i.stdout),i.stderr&&console.error(i.stderr),process.exit(i.exitCode)});return}f(D)||(v.error(`Entry not found: ${D}`),v.error("Run `npm run build` first."),process.exit(1));let r={cwd:y,windowsHide:!0,detached:!0,stdio:"ignore",env:{...process.env}};A(D,[],r),process.exit(0)}if(t==="tui"){Ln(n);return}q(e).then(r=>{r.stdout&&console.log(r.stdout),r.stderr&&console.error(r.stderr),process.exit(r.exitCode)})}fe(new URL("dist/entry/cli.js",__cortexPackageRoot).href)&&Qn();export{Nn as a,Fn as b,Ln as c,Vn as d,q as e,Qn as f};
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __cortexCreateRequire } from 'node:module';
2
2
  const require = __cortexCreateRequire(import.meta.url);
3
3
  const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{a as z}from"./chunk-V3AQJSWR.js";import{a as q,b as H,c as V,d as Z,e as K,o as Q}from"./chunk-QBKCAIJG.js";import{F as G,J as F,o as D,p as W,y as B}from"./chunk-PZMGBKUR.js";import{c as L,d as N}from"./chunk-SKHLZ6XY.js";import{a as T}from"./chunk-USBJFDJ6.js";function te(s,n){let r={v:1,id:s};return n&&(r.phase=n),JSON.stringify(r)}function ne(s){if(s){if(s.startsWith("{"))try{let n=JSON.parse(s);if(n.v===1&&typeof n.id=="string")return n.phase==="commentary"||n.phase==="final_answer"?{id:n.id,phase:n.phase}:{id:n.id}}catch{}return{id:s}}}function oe(s,n){let r=n.filter(l=>l.type==="text").map(l=>l.text).join(`
4
+ import{a as z}from"./chunk-V3AQJSWR.js";import{c as L,d as N}from"./chunk-SKHLZ6XY.js";import{a as q,b as H,c as V,d as Z,e as K,o as Q}from"./chunk-QBKCAIJG.js";import{F as G,J as F,o as D,p as W,y as B}from"./chunk-PZMGBKUR.js";import{a as T}from"./chunk-USBJFDJ6.js";function te(s,n){let r={v:1,id:s};return n&&(r.phase=n),JSON.stringify(r)}function ne(s){if(s){if(s.startsWith("{"))try{let n=JSON.parse(s);if(n.v===1&&typeof n.id=="string")return n.phase==="commentary"||n.phase==="final_answer"?{id:n.id,phase:n.phase}:{id:n.id}}catch{}return{id:s}}}function oe(s,n){let r=n.filter(l=>l.type==="text").map(l=>l.text).join(`
5
5
  `),p=n.filter(l=>l.type==="image"),f=r.trim().length>0;if(p.length===0||!s.input.includes("image"))return T(f?r:p.length>0?"(see attached image)":"(no tool output)");let c=[];f&&c.push({type:"input_text",text:T(r)});for(let l of p)c.push({type:"input_image",detail:"auto",image_url:`data:${l.mimeType};base64,${l.data}`});return c}function se(s){return s.supportsMidConvoSystemMessages&&s.supportsAdditionalTools?"changes":s.supportsToolSearch?"additions":"none"}function ae(s){let n="This is an incremental tools update. Previously declared tools remain available unless explicitly marked unavailable. A tool declared again here is available again, and its latest definition replaces the earlier one.";return s.size>0?`${n}
6
6
  Still unavailable: ${[...s].join(", ")}.`:n}function ie(s){return`The following tools are no longer available. Do not call them:
7
7
  ${s.map(n=>`- ${n}`).join(`
@@ -0,0 +1,4 @@
1
+ import { createRequire as __cortexCreateRequire } from 'node:module';
2
+ const require = __cortexCreateRequire(import.meta.url);
3
+ const __cortexPackageRoot = new URL("../../", import.meta.url);
4
+ import{a as _}from"./chunk-RA2BUYI3.js";import{c as P}from"./chunk-T73GHMFB.js";import{a as w}from"./chunk-OKRK6JPY.js";import{a as g}from"./chunk-VK5J556O.js";import{a as i,b as l,c as S,v as T,w as b,x as v,z as E}from"./chunk-BUZQBTV2.js";import{e as m,h as f,j as h}from"./chunk-TX46YMGI.js";import{mkdtempSync as x,rmSync as R,writeFileSync as A}from"node:fs";import C from"node:os";import u from"node:path";var O=new Set(["Bash","Read","Write","Edit","MultiEdit","Grep","Glob","LS","WebFetch","WebSearch","AskUserQuestion","EnterPlanMode","ExitPlanMode","TodoWrite","Skill","Agent","Task","TaskOutput","TaskStop","NotebookEdit","NotebookRead","BashOutput","KillShell","KillBash","SlashCommand","ToolSearch","ListMcpResourcesTool","ReadMcpResourceTool","bash","read","write","edit","grep","glob","find","ls","powershell","web_fetch","web_search","todo_write","skill","agent","agent_stop"]),I=/[^A-Za-z0-9._:/@[\]-]/g;function a(e){return e.replace(I,"_").slice(0,80)||i}function V(e){return O.has(e)?e:e.startsWith("mcp__cortex-")?a(e):e.startsWith("mcp__")?S:i}function L(e,r,t){return e==="claude"?{provider:"anthropic",customApi:null}:t.customProviders.has(r)?{provider:l,customApi:a(t.customProviders.get(r))}:{provider:t.piProviders.has(r)?r:i,customApi:null}}function X(e,r,t,n){return e==="claude"?w.includes(t)||n.modelIds.has(t.replace(/\[1m\]$/,""))?a(t):i:n.customProviders.has(r)?l:n.piModels.has(`${r}/${t}`)?a(t):i}function k(e,r){return[...new Set(e.map(t=>L("pi",t,r).provider))]}function N(e){let r=P(e),t=new Map(Object.entries(r).map(([n,o])=>[n,String(o.api)]));for(let n of f(h()))m(n)&&t.set(n.provider,n.api);return t}async function j(){let e=x(u.join(C.tmpdir(),"cortex-telemetry-catalog-"));try{let r=u.join(e,"auth.json");return A(r,""),(await(await g()).ModelRuntime.create({authPath:r,modelsPath:u.join(e,"absent","models.json"),allowModelNetwork:!1})).getAllModels().map(o=>({provider:String(o.provider),id:String(o.id)}))}finally{R(e,{recursive:!0,force:!0})}}function H(e,r){return{piProviders:new Set(e.map(t=>t.provider)),piModels:new Set(e.map(t=>`${t.provider}/${t.id}`)),modelIds:new Set(e.map(t=>t.id)),customProviders:r}}var d=null;function ee(e,r=_){if(d?.day===e)return d.catalog;let t=j().catch(()=>[]).then(n=>H(n,N(r)));return d={day:e,catalog:t},t}var W=["teamEnabled","serverAutoUpdate","serverUpdateDisable","autoResume","bgContinuation","streamDeltas","clientHotReloadEnabled","storeArchiveEnabled","providerUsageCollectionEnabled","claudeWindowWarmupEnabled","feishuSkillsInWeb","memoryIndexRegenEnabled"];function c(e){return e.state==="logged-in"||e.state==="expiring"}function D(e){let r=e.find(t=>t.backend==="claude"&&c(t));return r?r.authType==="api_key"?"api":"plan":"none"}function B(e){let r={};for(let{platform:t}of e){let n=["linux","darwin","win32"].includes(t)?t:"other";r[n]=(r[n]??0)+1}return r}function U(e){return Object.fromEntries(W.filter(r=>typeof e[r]=="boolean").map(r=>[a(r),e[r]]))}async function ne(e,r=new Date){let n=(await e.authStatus().catch(()=>null))?.accounts.filter(c)??[],o=e.onlineDevices(),y=n.filter(s=>s.backend==="pi").map(s=>s.provider);return{type:"heartbeat",at:r.toISOString(),backends:[...new Set(n.map(s=>s.backend))],claudeBilling:D(n),piProviders:k(y,await e.catalog()).slice(0,60),projects:e.projects(),onlineClients:o.length,clientPlatforms:B(o),activeSessions24h:await e.activeSessions24h().catch(()=>0),uptimeH:Math.round(e.uptimeS()/3600*100)/100,settings:U(e.settings())}}var p=new Set;function M(e){return p.has(e)?!0:b().funnelSent.includes(e)?(p.add(e),!0):!1}function z(e,r=null){M(e)||!E({type:"funnel",at:new Date().toISOString(),source:"server",step:e,detail:r})||(p.add(e),v(n=>({...n,funnelSent:[...new Set([...n.funnelSent,e])]})))}async function le(e){if(!T()||M("provider_authed"))return;let t=(await e().catch(()=>null))?.accounts.find(c);t&&z("provider_authed",t.backend)}export{a,V as b,L as c,X as d,ee as e,ne as f,z as g,le as h};
@@ -1,4 +1,4 @@
1
1
  import { createRequire as __cortexCreateRequire } from 'node:module';
2
2
  const require = __cortexCreateRequire(import.meta.url);
3
3
  const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- var t;function e(r){t=r}var o=async()=>t?t.anthropic():(await import("./anthropic-SUZWKBRW.js")).anthropicOAuth,i=async()=>t?t.openaiCodex():(await import("./openai-codex-2REL6UQU.js")).openaiCodexOAuth,n=async()=>t?t.openaiChatGPT():(await import("./openai-chatgpt-PETGIJOZ.js")).openaiChatGPTOAuth,a=async()=>t?t.githubCopilot():(await import("./github-copilot-HAI2DA62.js")).githubCopilotOAuth,u=async()=>t?t.openrouter():(await import("./openrouter-GDY3BLT2.js")).openRouterOAuth,s=async()=>t?t.kimiCoding():(await import("./kimi-coding-HMJRKCPA.js")).kimiCodingOAuth,p=async()=>t?t.meta():(await import("./meta-KY3LNFV2.js")).metaOAuth,c=async()=>t?t.xai():(await import("./xai-KEVUJTFV.js")).xaiOAuth,h=async r=>t?t.radius(r):(await import("./radius-HXRZVBDB.js")).createRadiusOAuth(r);export{e as a,o as b,i as c,n as d,a as e,u as f,s as g,p as h,c as i,h as j};
4
+ var t;function e(r){t=r}var o=async()=>t?t.anthropic():(await import("./anthropic-SUZWKBRW.js")).anthropicOAuth,i=async()=>t?t.openaiCodex():(await import("./openai-codex-JULCKICT.js")).openaiCodexOAuth,n=async()=>t?t.openaiChatGPT():(await import("./openai-chatgpt-PETGIJOZ.js")).openaiChatGPTOAuth,a=async()=>t?t.githubCopilot():(await import("./github-copilot-HAI2DA62.js")).githubCopilotOAuth,u=async()=>t?t.openrouter():(await import("./openrouter-GDY3BLT2.js")).openRouterOAuth,s=async()=>t?t.kimiCoding():(await import("./kimi-coding-HMJRKCPA.js")).kimiCodingOAuth,p=async()=>t?t.meta():(await import("./meta-KY3LNFV2.js")).metaOAuth,c=async()=>t?t.xai():(await import("./xai-KEVUJTFV.js")).xaiOAuth,h=async r=>t?t.radius(r):(await import("./radius-ZM7ZRMXF.js")).createRadiusOAuth(r);export{e as a,o as b,i as c,n as d,a as e,u as f,s as g,p as h,c as i,h as j};
@@ -0,0 +1,4 @@
1
+ import { createRequire as __cortexCreateRequire } from 'node:module';
2
+ const require = __cortexCreateRequire(import.meta.url);
3
+ const __cortexPackageRoot = new URL("../../", import.meta.url);
4
+ import a from"node:fs/promises";import m from"node:path";var g=10,M=3e4,O=2e4,A=1e3;function p(t){return`${t}.mutation-lock`}var w=class extends Error{filePath;timeoutMs;holderPid;constructor(e,r,n){let i=n===null?"":` held by pid ${n}`;super(`Timed out after ${r} ms waiting for the lock on ${e} (${p(e)}${i}).`),this.filePath=e,this.timeoutMs=r,this.holderPid=n,this.name="FileLockTimeoutError"}};function v(t){try{return process.kill(t,0),!0}catch(e){return e?.code!=="ESRCH"}}async function y(t){try{let e=await a.readFile(`/proc/${t}/stat`,"utf8");return e.slice(e.lastIndexOf(")")+2).split(" ")[19]??null}catch{return null}}async function u(t){try{let e=JSON.parse(await a.readFile(m.join(t,"owner.json"),"utf8"));return typeof e.pid!="number"||typeof e.token!="string"?null:{pid:e.pid,token:e.token,processStart:typeof e.processStart=="string"?e.processStart:null,acquiredAt:typeof e.acquiredAt=="number"?e.acquiredAt:null}}catch{return null}}async function I(t){if(!v(t.pid))return!0;let e=await y(t.pid);return t.processStart!==null&&e!==null&&t.processStart!==e}async function f(t){let e;try{e=Date.now()-(await a.stat(t)).mtimeMs}catch{return!1}let r=await u(t);return r?r.acquiredAt!==null&&Date.now()-r.acquiredAt>O?!0:I(r):e>A}async function _(t,e){if((await u(t))?.token!==e)return;let r=`${t}.released.${encodeURIComponent(e)}`;try{await a.rename(t,r),(await u(r))?.token===e&&await a.rm(r,{recursive:!0,force:!0})}catch{}}async function L(t){if(await f(t))try{let e=await a.stat(t);await a.writeFile(m.join(t,".reclaimed"),"");let r=await a.stat(t);if(r.dev!==e.dev||r.ino!==e.ino||await u(t)&&!await f(t))return;let n=`${r.dev}.${r.ino}.${String(r.ctimeMs).replace(".","-")}`,i=`${t}.reclaimed.${n}`;await a.rename(t,i),await a.rm(i,{recursive:!0,force:!0})}catch{}}async function F(t){let e=`${process.pid}:${Date.now()}:${Math.random()}`,r=`${t}.candidate.${encodeURIComponent(e)}`;try{await a.mkdir(r);let n={pid:process.pid,token:e,processStart:await y(process.pid),acquiredAt:Date.now()};return await a.writeFile(m.join(r,"owner.json"),JSON.stringify(n),{mode:384}),await a.rename(r,t),()=>_(t,e)}catch(n){if(await a.rm(r,{recursive:!0,force:!0}),n?.code==="EEXIST"||n?.code==="ENOTEMPTY"||n?.code==="EPERM"&&await a.stat(t).then(()=>!0,()=>!1))return null;throw n}}async function x(t,e){e.signal?.throwIfAborted(),await a.mkdir(m.dirname(t),{recursive:!0});let r=p(t),n=e.timeoutMs??M,i=Date.now()+n;for(;Date.now()<i;){e.signal?.throwIfAborted();let c=await F(r);if(c)return c;await f(r)?await L(r):await new Promise(T=>setTimeout(T,g))}throw new w(t,n,(await u(r))?.pid??null)}async function S(t,e,r={}){let n=await x(t,r);try{return await e()}finally{await n()}}import s from"node:fs/promises";import{writeFileSync as D,renameSync as $,mkdirSync as N,chmodSync as R}from"node:fs";import d from"node:path";import*as h from"node:os";function E(){return!!process.env.NODE_TEST_CONTEXT}var b=[".cortex",".pi",".aistatus"].map(t=>d.join(h.homedir(),t));function l(t){if(!E())return;let e=d.resolve(t),r=b.find(n=>e===n||e.startsWith(n+d.sep));if(r)throw new Error(`atomicWrite blocked: test process attempted to write under the real ${r} (${e}). Isolate state first: run the test through vitest \u2014 \`npm test\` / \`npm run test:file <file>\` \u2014 whose setup file points CORTEX_HOME at an isolated temp home; repoint HOME too for files under it.`)}function o(t){if(t?.aborted)throw t.reason instanceof Error?t.reason:new Error("Atomic write aborted.")}async function k(t){try{return await s.readFile(t,"utf8")}catch(e){if(e.code==="ENOENT")return"";throw e}}async function q(t,e){try{await s.chmod(t,e)}catch(r){if(r.code!=="ENOENT")throw r}}async function z(t,e,r={}){l(t),await S(t,async()=>{o(r.signal);let n=await k(t);o(r.signal);let i=await e(n);o(r.signal),i!==n?await C(t,i,r):r.mode!==void 0&&await q(t,r.mode)},{signal:r.signal})}async function C(t,e,r={}){l(t),o(r.signal),await s.mkdir(d.dirname(t),{recursive:!0}),o(r.signal);let n=Math.random().toString(36).slice(2,8),i=`${t}.tmp.${process.pid}.${Date.now()}.${n}`,c=!1;try{await s.writeFile(i,e,{encoding:"utf8",mode:r.mode}),o(r.signal),r.mode!==void 0&&await s.chmod(i,r.mode),o(r.signal),$(i,t),c=!0}finally{c||await s.rm(i,{force:!0})}}function B(t,e,r={}){l(t),N(d.dirname(t),{recursive:!0});let n=Math.random().toString(36).slice(2,8),i=`${t}.tmp.${process.pid}.${Date.now()}.${n}`;D(i,e,{encoding:"utf8",mode:r.mode}),r.mode!==void 0&&R(i,r.mode),$(i,t)}export{S as a,E as b,z as c,C as d,B as e};
@@ -0,0 +1,4 @@
1
+ import { createRequire as __cortexCreateRequire } from 'node:module';
2
+ const require = __cortexCreateRequire(import.meta.url);
3
+ const __cortexPackageRoot = new URL("../../", import.meta.url);
4
+ import{A as l,K as d,R as N,e as I,r as m}from"./chunk-JJDEQ6N2.js";import{a as _}from"./chunk-RA2BUYI3.js";import{b as O}from"./chunk-T73GHMFB.js";import{a as v}from"./chunk-V35MFAUQ.js";import{a as c,b as i,e as A,g as C,h as E,j as u}from"./chunk-TX46YMGI.js";import{h as f}from"./chunk-Z24SBRJK.js";import{e as h}from"./chunk-WHC7AYZD.js";var a=h(v(),1);import{existsSync as S,mkdirSync as D,readFileSync as U,writeFileSync as k}from"fs";import*as T from"path";var x=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function b(e){return T.join(e,"config.yaml")}function P(e){if(!S(e))return{};try{let r=a.parse(U(e,"utf-8"));return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}catch{return{}}}function p(e){return typeof e=="string"?e:""}function J(e=f){let r=P(b(e));return{enabled:r.uploadEnabled===!0,name:p(r.name),org:p(r.org),email:p(r.email)}}function Q(e){if(!e.enabled)return[];let r=[];return e.name?.trim()||r.push("name-required"),x.test(e.email?.trim()??"")||r.push("email-invalid"),r}function X(e,r=f){let t=b(r);D(r,{recursive:!0});let n=P(t),o=e.enabled?{name:e.name||"",org:e.org||"",email:e.email||""}:{name:n.name??"",org:n.org??"",email:n.email??""};k(t,a.stringify({...n,...o,uploadEnabled:e.enabled}))}var K="cortex-gateway",w=/^http:\/\/(?:127\.0\.0\.1|localhost):\d+\/m\//;function g(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let{apiKey:r,baseUrl:t}=e;return r===K||typeof t=="string"&&w.test(t)}function L(e){if(!e)return{};let r={};for(let[t,n]of Object.entries(O(e)))!n||typeof n!="object"||Array.isArray(n)||g(n)||(r[t]=n);return r}function H(e){let r={baseUrl:e.baseUrl};return e.key&&(r.apiKey=e.key),A(e)&&(r.api=e.api,r.models=e.models.map(t=>({...t})),e.headers&&(r.headers={...e.headers}),e.compat&&(r.compat={...e.compat})),r}function B(e={}){let r=L(e.userModelsPath===void 0?_:e.userModelsPath),t={};for(let n of E(u(e.file??c)))r[n.provider]=H(n),n.key&&(t[n.provider]=n.key);return e.accountProvider?j({providers:r,runtimeKeys:t},e.accountProvider):{providers:r,runtimeKeys:t}}function j(e,r){let{[r]:t,...n}=e.runtimeKeys,o=e.providers[r];if(!o||!("apiKey"in o))return{providers:e.providers,runtimeKeys:n};let{apiKey:s,...R}=o;return{providers:{...e.providers,[r]:R},runtimeKeys:n}}var F=["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN"];function y(e){let r=F.filter(t=>e.sets[t]===void 0);return{...e,unsets:r}}function Y(e){let r=I(e)?.token;return y({connection:i,sets:r?{CLAUDE_CODE_OAUTH_TOKEN:r}:{}})}function G(e){let r=e.authStyle==="bearer"?"ANTHROPIC_AUTH_TOKEN":"ANTHROPIC_API_KEY";return y({connection:e.id,...e.baseUrl?{baseUrl:e.baseUrl}:{},sets:{[r]:e.key}})}function M(e,r){return y({connection:e,sets:{},configDir:m(e,r.accountDir)})}function W(e,r){return C(u(r)).find(t=>t.id===e)??null}function $(e,r={}){let t=r.file??c,n=r.claude??{},o=e??d({file:t,claude:n,claudeAccountsDir:r.accountDir?.accountsDir}).defaultClaudeConnection()??i;if(o===i)return Y(n);let s=W(o,t);if(s)return G(s);if(l({backend:"claude",id:o},t))return M(o,r);throw new Error(`Claude connection '${o}' is not configured`)}function q(e,r={}){return e.backend==="pi"?e.connection||e.provider||"pi":e.connection??N(e,r)??i}function ge(e,r){return e.backend==="claude"&&r?r.connection:q(e)}export{B as a,J as b,Q as c,X as d,$ as e,q as f,ge as g};
@@ -3,4 +3,4 @@ const require = __cortexCreateRequire(import.meta.url);
3
3
  const __cortexPackageRoot = new URL("../../", import.meta.url);
4
4
  import{f as k,h as U,i as F}from"./chunk-RA6HKFBV.js";import{G as D,M as _,c as $,h as w,m as N,n as b,o as V}from"./chunk-QUUEQRIT.js";import*as v from"node:fs";import{createRequire as le}from"node:module";import*as p from"node:path";import{fileURLToPath as A}from"node:url";import{EventEmitter as ne}from"node:events";function z(){let e=new ne;return{emit:(r,l)=>{e.emit(r,l)},on:(r,l)=>{let n=async c=>{try{await l(c)}catch(a){console.error(`Event handler error (${r}):`,a)}};return e.on(r,n),()=>e.off(r,n)},clear:()=>{e.removeAllListeners()}}}import{spawn as se}from"node:child_process";async function B(e,r,l,n){return new Promise(c=>{let a=se(e,r,{cwd:l,shell:!1,stdio:["ignore","pipe","pipe"]}),i="",d="",o=!1,u,g=()=>{o||(o=!0,a.kill("SIGTERM"),setTimeout(()=>{a.killed||a.kill("SIGKILL")},5e3))};n?.signal&&(n.signal.aborted?g():n.signal.addEventListener("abort",g,{once:!0})),n?.timeout&&n.timeout>0&&(u=setTimeout(()=>{g()},n.timeout)),a.stdout?.on("data",h=>{i+=h.toString()}),a.stderr?.on("data",h=>{d+=h.toString()}),$(a).then(h=>{u&&clearTimeout(u),n?.signal&&n.signal.removeEventListener("abort",g),c({stdout:i,stderr:d,code:h??0,killed:o})}).catch(h=>{u&&clearTimeout(u),n?.signal&&n.signal.removeEventListener("abort",g),c({stdout:i,stderr:d,code:1,killed:o})})})}import{readFileSync as ie}from"node:fs";var oe=["extensions","skills","prompts","themes"];function O(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function W(e){try{let r=JSON.parse(N(ie(e,"utf-8")));if(!O(r)||!O(r.pi))return null;let l={};for(let n of oe){let c=r.pi[n];Array.isArray(c)&&c.every(a=>typeof a=="string")&&(l[n]=c)}return l}catch{return null}}var J="builtin:";function G(e){if(e.startsWith(J))return"builtin";if(e.startsWith("<")&&e.endsWith(">"))return e.slice(1,-1).split(":")[0]||"temporary"}function q(e){return e.startsWith(J)||e.startsWith("<")}function Ie(e,r){return{path:e,source:r.source,scope:r.scope,origin:r.origin,baseDir:r.baseDir}}function H(e,r){return{path:e,source:r.source,scope:r.scope??"temporary",origin:r.origin??"top-level",baseDir:r.baseDir}}var P=process.env.PI_TIMING==="1",S=new Map;function ae(e="main"){P&&S.set(e,{timings:[],lastTime:Date.now()})}function T(e,r="main"){if(!P)return;let l=Date.now();S.has(r)||ae(r);let n=S.get(r);n.timings.push({label:e,ms:l-n.lastTime}),n.lastTime=l}function ce(e,r){let l=r.filter(n=>n.ms>=0);if(l.length!==0){console.error(`
5
5
  --- ${e} ---`);for(let n of l)console.error(` ${n.label}: ${n.ms}ms`);console.error(` TOTAL: ${l.reduce((n,c)=>n+c.ms,0)}ms`),console.error(`${"-".repeat(e.length+8)}
6
- `)}}function je(){if(P)for(let[e,r]of S)ce(`Startup Timings: ${e}`,r.timings)}var R=le(new URL("vendor/pi/dist/core/extensions/loader.js",__cortexPackageRoot).href),de="sea"in process.features&&process.features.sea===!0||process.getBuiltinModule("node:sea")?.isSea()===!0,ue=!b&&p.extname(A(new URL("vendor/pi/dist/core/extensions/loader.js",__cortexPackageRoot).href))===".ts",Z=b||de||V,K;function fe(){return K??=(Z?import("./jiti-static-loader-W3QZ4GDS.js"):import("./jiti-loader-WANUXUDO.js")).then(e=>e.createJiti),K}var X;function Q(){return X??=import("./virtual-modules-IDC5YKZJ.js").then(e=>e.VIRTUAL_MODULES),X}var M=null;function pe(){if(M)return M;let e=p.dirname(A(new URL("vendor/pi/dist/core/extensions/loader.js",__cortexPackageRoot).href)),r=p.resolve(e,"../..","index.js"),l=R.resolve("typebox"),n=R.resolve("typebox/compile"),c=R.resolve("typebox/value"),a=p.resolve(e,"../../../../"),i=(f,y)=>{let m=p.join(a,f);return v.existsSync(m)?m:A(import.meta.resolve(y))},d=r,o=i("agent/dist/index.js","@earendil-works/pi-agent-core"),u=i("tui/dist/index.js","@earendil-works/pi-tui"),g=i("ai/dist/compat.js","@earendil-works/pi-ai/compat"),h=i("ai/dist/models.js","@earendil-works/pi-ai/models"),t=i("ai/dist/oauth.js","@earendil-works/pi-ai/oauth"),s=i("ai/dist/providers/all.js","@earendil-works/pi-ai/providers/all");return M={"@earendil-works/pi-coding-agent":d,"@earendil-works/pi-agent-core":o,"@earendil-works/pi-tui":u,"@earendil-works/pi-ai/providers/all":s,"@earendil-works/pi-ai/compat":g,"@earendil-works/pi-ai/models":h,"@earendil-works/pi-ai/oauth":t,"@earendil-works/pi-ai":g,"@mariozechner/pi-coding-agent":d,"@mariozechner/pi-agent-core":o,"@mariozechner/pi-tui":u,"@mariozechner/pi-ai/providers/all":s,"@mariozechner/pi-ai/compat":g,"@mariozechner/pi-ai/models":h,"@mariozechner/pi-ai/oauth":t,"@mariozechner/pi-ai":g,typebox:l,"typebox/compile":n,"typebox/value":c,"@sinclair/typebox":l,"@sinclair/typebox/compile":n,"@sinclair/typebox/value":c},M}var x,L=0,I=new Map;function ge(){I.clear(),x=void 0,L++}function he(e){let r=w(e);return x!==void 0&&x!==r&&ge(),x=r,{cwd:r,generation:L}}function me(){let e=()=>{throw new Error("Extension runtime not initialized. Action methods cannot be called during extension loading.")},r={},l=new Set,n=()=>{if(r.staleMessage)throw new Error(r.staleMessage)},c={sendMessage:e,sendUserMessage:e,appendEntry:e,setSessionName:e,getSessionName:e,setLabel:e,getActiveTools:e,getAllTools:e,getSettings:e,setActiveTools:e,refreshTools:()=>{},getCommands:e,setModel:()=>Promise.reject(new Error("Extension runtime not initialized")),getThinkingLevel:e,setThinkingLevel:e,flagValues:new Map,pendingProviderRegistrations:[],pendingNativeProviderRegistrations:[],mcpServers:new F,pendingVirtualModelRegistrations:[],createContext:e,assertActive:n,invalidate:a=>{if(!r.staleMessage){r.staleMessage=a??"This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().";for(let i of l)i();l.clear()}},trackEventBusSubscription:a=>{let i=!0,d=()=>{i&&(i=!1,l.delete(d),a())};return l.add(d),d},registerProvider:(a,i,d="<unknown>")=>{c.pendingProviderRegistrations.push({name:a,config:i,extensionPath:d})},registerNativeProvider:(a,i="<unknown>")=>{c.pendingNativeProviderRegistrations.push({provider:a,extensionPath:i})},unregisterProvider:a=>{c.pendingProviderRegistrations=c.pendingProviderRegistrations.filter(i=>i.name!==a),c.pendingNativeProviderRegistrations=c.pendingNativeProviderRegistrations.filter(i=>i.provider.id!==a)},registerVirtualModel:(a,i="<unknown>")=>{c.pendingVirtualModelRegistrations.push({definition:a,extensionPath:i})},unregisterVirtualModel:(a,i)=>{c.pendingVirtualModelRegistrations=c.pendingVirtualModelRegistrations.filter(({definition:d})=>d.provider!==a||d.id!==i)}};return c}function ve(e,r,l,n){let c=new Map,a=[],i=[],d="loading",o=()=>{if(d==="failed")throw new Error(`Extension "${e.path}" failed to load and its API is no longer active.`);r.assertActive()},u=t=>{d==="loading"?a.push(t):t()},g=()=>{c.clear(),a.length=0,i.length=0};return{api:{on(t,s){o();let f=(...m)=>s(...m),y=e.handlers.get(t)??[];return y.push(f),e.handlers.set(t,y),()=>{let m=e.handlers.get(t);if(!m)return;let E=m.indexOf(f);E!==-1&&(m.splice(E,1),m.length===0&&e.handlers.delete(t))}},registerTool(t){if(o(),typeof t.parameters!="object"||t.parameters===null||Array.isArray(t.parameters))throw new Error(`Tool "${t.name}" registered by extension "${e.path}" must define an object parameter schema.`);e.tools.set(t.name,{definition:t,sourceInfo:e.sourceInfo}),r.refreshTools()},registerCommand(t,s){if(o(),typeof t!="string"||t.length===0)throw new Error(`Command registered by extension "${e.path}" must have a non-empty string name. Use pi.registerCommand("name", { description, handler }).`);if(typeof s?.handler!="function")throw new Error(`Command "/${t}" registered by extension "${e.path}" must define handler().`);e.commands.set(t,{name:t,sourceInfo:e.sourceInfo,...s})},registerShortcut(t,s){o(),e.shortcuts.set(t,{shortcut:t,extensionPath:e.path,...s})},registerFlag(t,s){if(o(),s.default!==void 0&&typeof s.default!==s.type)throw new Error(`Invalid default for flag "${t}": expected ${s.type}, got ${typeof s.default}`);e.flags.set(t,{name:t,extensionPath:e.path,...s}),s.default!==void 0&&!r.flagValues.has(t)&&(d==="loading"?c.has(t)||c.set(t,s.default):r.flagValues.set(t,s.default))},registerMessageRenderer(t,s){o(),e.messageRenderers.set(t,s)},registerMarkdownTransformer(t){o(),e.markdownTransformer=t},registerEntryRenderer(t,s){o(),e.entryRenderers??=new Map,e.entryRenderers.set(t,s)},registerToolRenderer(t){o(),e.toolRenderers??=[],e.toolRenderers.push(t)},getFlag(t){if(o(),!!e.flags.has(t))return r.flagValues.has(t)?r.flagValues.get(t):c.get(t)},sendMessage(t,s){o(),r.sendMessage(t,s)},sendUserMessage(t,s){o(),r.sendUserMessage(t,s)},appendEntry(t,s){o(),r.appendEntry(t,s)},setSessionName(t){o(),r.setSessionName(t)},getSessionName(){return o(),r.getSessionName()},setLabel(t,s){o(),r.setLabel(t,s)},exec(t,s,f){return o(),B(t,s,f?.cwd??l,f)},getActiveTools(){return o(),r.getActiveTools()},getAllTools(){return o(),r.getAllTools()},getSettings(){return o(),r.getSettings()},setActiveTools(t){o(),r.setActiveTools(t)},getCommands(){return o(),r.getCommands()},setModel(t){return o(),r.setModel(t)},getThinkingLevel(){return o(),r.getThinkingLevel()},setThinkingLevel(t){o(),r.setThinkingLevel(t)},registerProvider(t,s){if(o(),typeof t=="string"){if(!s)throw new Error("Provider config is required when registering by name");u(()=>r.registerProvider(t,s,e.path));return}u(()=>r.registerNativeProvider(t,e.path))},unregisterProvider(t){o(),u(()=>r.unregisterProvider(t,e.path))},registerMcpServer(t,s){o();let f=U(t,s);if(typeof f=="string")throw new Error(`Invalid MCP server registered by extension "${e.path}": ${f}`);let y=r.mcpServers.get(t)?.extensionPath;if(y!==void 0&&y!==e.path)throw new Error(`MCP server "${t}" is already registered by extension "${y}"`);let m=r.mcpServers.list().find(j=>j.name!==t&&k(j.name)===k(t));if(m)throw new Error(`MCP server "${t}" conflicts with registered server "${m.name}"`);let E={name:t,config:structuredClone(f),extensionPath:e.path};u(()=>r.mcpServers.register(E))},unregisterMcpServer(t){o(),u(()=>r.mcpServers.unregister(t,e.path))},getMcpServers(){return o(),r.mcpServers.list()},registerVirtualModel(t){o();let s={...t,route:f=>t.route(f,r.createContext())};u(()=>r.registerVirtualModel(s,e.path))},unregisterVirtualModel(t,s){o(),u(()=>r.unregisterVirtualModel(t,s))},events:{emit(t,s){o(),n.emit(t,s)},on(t,s){o();let f=r.trackEventBusSubscription(n.on(t,s));return d==="loading"&&i.push(f),f}}},commit:()=>{if(d==="loading"){r.assertActive();for(let[t,s]of c)r.flagValues.has(t)||r.flagValues.set(t,s);for(let t of a)t();d="active",g()}},discard:()=>{if(d==="loading"){d="failed";for(let t of i)t();g()}}}}function Y(e){return e!==void 0&&x===e.cwd&&L===e.generation}async function ye(e,r){if(Y(r)){let d=I.get(e);if(d)return d}let l=await fe(),n=Z?{virtualModules:await Q(),tryNative:!1}:ue?{virtualModules:await Q(),tsconfigPaths:!0}:{alias:pe()},i=await l(new URL("vendor/pi/dist/core/extensions/loader.js",__cortexPackageRoot).href,{moduleCache:!1,...n}).import(e,{default:!0});if(typeof i=="function")return Y(r)&&I.set(e,i),i}function we(e,r){let l=G(e)??"local",n=q(e)?void 0:p.dirname(r);return{path:e,resolvedPath:r,sourceInfo:H(e,{source:l,baseDir:n}),handlers:new Map,tools:new Map,messageRenderers:new Map,entryRenderers:new Map,commands:new Map,flags:new Map,shortcuts:new Map}}async function ee(e,r,l,n,c,a){let i=we(r,l),d=ve(i,a,n,c);try{await e(d.api),d.commit()}catch(o){throw d.discard(),o}return T(`${r} factory`,"extensions"),i}async function xe(e,r,l,n,c){let a=w(e,r,{normalizeUnicodeSpaces:!0});try{let i=await ye(a,c);return T(`${e} module import`,"extensions"),i?{extension:await ee(i,e,a,r,l,n),error:null}:{extension:null,error:`Extension does not export a valid factory function: ${e}`}}catch(i){return{extension:null,error:`Failed to load extension: ${i instanceof Error?i.message:String(i)}`}}}async function Je(e,r,l,n,c="<inline>"){let a=w(r);return ee(e,c,c,a,l,n)}async function te(e,r,l,n,c=!1){let a=[],i=[],d=[],o=c?he(r):void 0,u=o?.cwd??w(r),g=l??z(),h=n??me();for(let t of e){let{extension:s,error:f}=await xe(t,u,g,h,o);if(f){i.push({path:t,error:f});continue}s&&a.push(s)}return{extensions:a,errors:i,warnings:d,runtime:h}}async function Ee(e,r,l,n){return te(e,r,l,n)}async function Ge(e,r,l,n){return te(e,r,l,n,!0)}function Se(e){return e.endsWith(".ts")||e.endsWith(".js")}function re(e){let r=p.join(e,"package.json");if(v.existsSync(r)){let c=W(r);if(c?.extensions?.length){let a=[];for(let i of c.extensions){let d=p.resolve(e,i);v.existsSync(d)&&a.push(d)}if(a.length>0)return a}}let l=p.join(e,"index.ts"),n=p.join(e,"index.js");return v.existsSync(l)?[l]:v.existsSync(n)?[n]:null}function C(e){if(!v.existsSync(e))return[];let r=[];try{let l=v.readdirSync(e,{withFileTypes:!0});for(let n of l){let c=p.join(e,n.name);if((n.isFile()||n.isSymbolicLink())&&Se(n.name)){r.push(c);continue}if(n.isDirectory()||n.isSymbolicLink()){let a=re(c);a&&r.push(...a)}}}catch{return[]}return r}async function qe(e,r,l=_(),n){let c=w(r),a=w(l),i=[],d=new Set,o=h=>{for(let t of h){let s=p.resolve(t);d.has(s)||(d.add(s),i.push(t))}},u=p.join(c,D,"extensions");o(C(u));let g=p.join(a,"extensions");o(C(g));for(let h of e){let t=w(h,c,{normalizeUnicodeSpaces:!0});if(v.existsSync(t)&&v.statSync(t).isDirectory()){let s=re(t);if(s){o(s);continue}o(C(t));continue}o([t])}return Ee(i,c,n)}export{z as a,W as b,J as c,G as d,q as e,Ie as f,H as g,ae as h,T as i,je as j,ge as k,me as l,Je as m,Ee as n,Ge as o,qe as p};
6
+ `)}}function je(){if(P)for(let[e,r]of S)ce(`Startup Timings: ${e}`,r.timings)}var R=le(new URL("vendor/pi/dist/core/extensions/loader.js",__cortexPackageRoot).href),de="sea"in process.features&&process.features.sea===!0||process.getBuiltinModule("node:sea")?.isSea()===!0,ue=!b&&p.extname(A(new URL("vendor/pi/dist/core/extensions/loader.js",__cortexPackageRoot).href))===".ts",Z=b||de||V,K;function fe(){return K??=(Z?import("./jiti-static-loader-W3QZ4GDS.js"):import("./jiti-loader-WANUXUDO.js")).then(e=>e.createJiti),K}var X;function Q(){return X??=import("./virtual-modules-OFI7QKYH.js").then(e=>e.VIRTUAL_MODULES),X}var M=null;function pe(){if(M)return M;let e=p.dirname(A(new URL("vendor/pi/dist/core/extensions/loader.js",__cortexPackageRoot).href)),r=p.resolve(e,"../..","index.js"),l=R.resolve("typebox"),n=R.resolve("typebox/compile"),c=R.resolve("typebox/value"),a=p.resolve(e,"../../../../"),i=(f,y)=>{let m=p.join(a,f);return v.existsSync(m)?m:A(import.meta.resolve(y))},d=r,o=i("agent/dist/index.js","@earendil-works/pi-agent-core"),u=i("tui/dist/index.js","@earendil-works/pi-tui"),g=i("ai/dist/compat.js","@earendil-works/pi-ai/compat"),h=i("ai/dist/models.js","@earendil-works/pi-ai/models"),t=i("ai/dist/oauth.js","@earendil-works/pi-ai/oauth"),s=i("ai/dist/providers/all.js","@earendil-works/pi-ai/providers/all");return M={"@earendil-works/pi-coding-agent":d,"@earendil-works/pi-agent-core":o,"@earendil-works/pi-tui":u,"@earendil-works/pi-ai/providers/all":s,"@earendil-works/pi-ai/compat":g,"@earendil-works/pi-ai/models":h,"@earendil-works/pi-ai/oauth":t,"@earendil-works/pi-ai":g,"@mariozechner/pi-coding-agent":d,"@mariozechner/pi-agent-core":o,"@mariozechner/pi-tui":u,"@mariozechner/pi-ai/providers/all":s,"@mariozechner/pi-ai/compat":g,"@mariozechner/pi-ai/models":h,"@mariozechner/pi-ai/oauth":t,"@mariozechner/pi-ai":g,typebox:l,"typebox/compile":n,"typebox/value":c,"@sinclair/typebox":l,"@sinclair/typebox/compile":n,"@sinclair/typebox/value":c},M}var x,L=0,I=new Map;function ge(){I.clear(),x=void 0,L++}function he(e){let r=w(e);return x!==void 0&&x!==r&&ge(),x=r,{cwd:r,generation:L}}function me(){let e=()=>{throw new Error("Extension runtime not initialized. Action methods cannot be called during extension loading.")},r={},l=new Set,n=()=>{if(r.staleMessage)throw new Error(r.staleMessage)},c={sendMessage:e,sendUserMessage:e,appendEntry:e,setSessionName:e,getSessionName:e,setLabel:e,getActiveTools:e,getAllTools:e,getSettings:e,setActiveTools:e,refreshTools:()=>{},getCommands:e,setModel:()=>Promise.reject(new Error("Extension runtime not initialized")),getThinkingLevel:e,setThinkingLevel:e,flagValues:new Map,pendingProviderRegistrations:[],pendingNativeProviderRegistrations:[],mcpServers:new F,pendingVirtualModelRegistrations:[],createContext:e,assertActive:n,invalidate:a=>{if(!r.staleMessage){r.staleMessage=a??"This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().";for(let i of l)i();l.clear()}},trackEventBusSubscription:a=>{let i=!0,d=()=>{i&&(i=!1,l.delete(d),a())};return l.add(d),d},registerProvider:(a,i,d="<unknown>")=>{c.pendingProviderRegistrations.push({name:a,config:i,extensionPath:d})},registerNativeProvider:(a,i="<unknown>")=>{c.pendingNativeProviderRegistrations.push({provider:a,extensionPath:i})},unregisterProvider:a=>{c.pendingProviderRegistrations=c.pendingProviderRegistrations.filter(i=>i.name!==a),c.pendingNativeProviderRegistrations=c.pendingNativeProviderRegistrations.filter(i=>i.provider.id!==a)},registerVirtualModel:(a,i="<unknown>")=>{c.pendingVirtualModelRegistrations.push({definition:a,extensionPath:i})},unregisterVirtualModel:(a,i)=>{c.pendingVirtualModelRegistrations=c.pendingVirtualModelRegistrations.filter(({definition:d})=>d.provider!==a||d.id!==i)}};return c}function ve(e,r,l,n){let c=new Map,a=[],i=[],d="loading",o=()=>{if(d==="failed")throw new Error(`Extension "${e.path}" failed to load and its API is no longer active.`);r.assertActive()},u=t=>{d==="loading"?a.push(t):t()},g=()=>{c.clear(),a.length=0,i.length=0};return{api:{on(t,s){o();let f=(...m)=>s(...m),y=e.handlers.get(t)??[];return y.push(f),e.handlers.set(t,y),()=>{let m=e.handlers.get(t);if(!m)return;let E=m.indexOf(f);E!==-1&&(m.splice(E,1),m.length===0&&e.handlers.delete(t))}},registerTool(t){if(o(),typeof t.parameters!="object"||t.parameters===null||Array.isArray(t.parameters))throw new Error(`Tool "${t.name}" registered by extension "${e.path}" must define an object parameter schema.`);e.tools.set(t.name,{definition:t,sourceInfo:e.sourceInfo}),r.refreshTools()},registerCommand(t,s){if(o(),typeof t!="string"||t.length===0)throw new Error(`Command registered by extension "${e.path}" must have a non-empty string name. Use pi.registerCommand("name", { description, handler }).`);if(typeof s?.handler!="function")throw new Error(`Command "/${t}" registered by extension "${e.path}" must define handler().`);e.commands.set(t,{name:t,sourceInfo:e.sourceInfo,...s})},registerShortcut(t,s){o(),e.shortcuts.set(t,{shortcut:t,extensionPath:e.path,...s})},registerFlag(t,s){if(o(),s.default!==void 0&&typeof s.default!==s.type)throw new Error(`Invalid default for flag "${t}": expected ${s.type}, got ${typeof s.default}`);e.flags.set(t,{name:t,extensionPath:e.path,...s}),s.default!==void 0&&!r.flagValues.has(t)&&(d==="loading"?c.has(t)||c.set(t,s.default):r.flagValues.set(t,s.default))},registerMessageRenderer(t,s){o(),e.messageRenderers.set(t,s)},registerMarkdownTransformer(t){o(),e.markdownTransformer=t},registerEntryRenderer(t,s){o(),e.entryRenderers??=new Map,e.entryRenderers.set(t,s)},registerToolRenderer(t){o(),e.toolRenderers??=[],e.toolRenderers.push(t)},getFlag(t){if(o(),!!e.flags.has(t))return r.flagValues.has(t)?r.flagValues.get(t):c.get(t)},sendMessage(t,s){o(),r.sendMessage(t,s)},sendUserMessage(t,s){o(),r.sendUserMessage(t,s)},appendEntry(t,s){o(),r.appendEntry(t,s)},setSessionName(t){o(),r.setSessionName(t)},getSessionName(){return o(),r.getSessionName()},setLabel(t,s){o(),r.setLabel(t,s)},exec(t,s,f){return o(),B(t,s,f?.cwd??l,f)},getActiveTools(){return o(),r.getActiveTools()},getAllTools(){return o(),r.getAllTools()},getSettings(){return o(),r.getSettings()},setActiveTools(t){o(),r.setActiveTools(t)},getCommands(){return o(),r.getCommands()},setModel(t){return o(),r.setModel(t)},getThinkingLevel(){return o(),r.getThinkingLevel()},setThinkingLevel(t){o(),r.setThinkingLevel(t)},registerProvider(t,s){if(o(),typeof t=="string"){if(!s)throw new Error("Provider config is required when registering by name");u(()=>r.registerProvider(t,s,e.path));return}u(()=>r.registerNativeProvider(t,e.path))},unregisterProvider(t){o(),u(()=>r.unregisterProvider(t,e.path))},registerMcpServer(t,s){o();let f=U(t,s);if(typeof f=="string")throw new Error(`Invalid MCP server registered by extension "${e.path}": ${f}`);let y=r.mcpServers.get(t)?.extensionPath;if(y!==void 0&&y!==e.path)throw new Error(`MCP server "${t}" is already registered by extension "${y}"`);let m=r.mcpServers.list().find(j=>j.name!==t&&k(j.name)===k(t));if(m)throw new Error(`MCP server "${t}" conflicts with registered server "${m.name}"`);let E={name:t,config:structuredClone(f),extensionPath:e.path};u(()=>r.mcpServers.register(E))},unregisterMcpServer(t){o(),u(()=>r.mcpServers.unregister(t,e.path))},getMcpServers(){return o(),r.mcpServers.list()},registerVirtualModel(t){o();let s={...t,route:f=>t.route(f,r.createContext())};u(()=>r.registerVirtualModel(s,e.path))},unregisterVirtualModel(t,s){o(),u(()=>r.unregisterVirtualModel(t,s))},events:{emit(t,s){o(),n.emit(t,s)},on(t,s){o();let f=r.trackEventBusSubscription(n.on(t,s));return d==="loading"&&i.push(f),f}}},commit:()=>{if(d==="loading"){r.assertActive();for(let[t,s]of c)r.flagValues.has(t)||r.flagValues.set(t,s);for(let t of a)t();d="active",g()}},discard:()=>{if(d==="loading"){d="failed";for(let t of i)t();g()}}}}function Y(e){return e!==void 0&&x===e.cwd&&L===e.generation}async function ye(e,r){if(Y(r)){let d=I.get(e);if(d)return d}let l=await fe(),n=Z?{virtualModules:await Q(),tryNative:!1}:ue?{virtualModules:await Q(),tsconfigPaths:!0}:{alias:pe()},i=await l(new URL("vendor/pi/dist/core/extensions/loader.js",__cortexPackageRoot).href,{moduleCache:!1,...n}).import(e,{default:!0});if(typeof i=="function")return Y(r)&&I.set(e,i),i}function we(e,r){let l=G(e)??"local",n=q(e)?void 0:p.dirname(r);return{path:e,resolvedPath:r,sourceInfo:H(e,{source:l,baseDir:n}),handlers:new Map,tools:new Map,messageRenderers:new Map,entryRenderers:new Map,commands:new Map,flags:new Map,shortcuts:new Map}}async function ee(e,r,l,n,c,a){let i=we(r,l),d=ve(i,a,n,c);try{await e(d.api),d.commit()}catch(o){throw d.discard(),o}return T(`${r} factory`,"extensions"),i}async function xe(e,r,l,n,c){let a=w(e,r,{normalizeUnicodeSpaces:!0});try{let i=await ye(a,c);return T(`${e} module import`,"extensions"),i?{extension:await ee(i,e,a,r,l,n),error:null}:{extension:null,error:`Extension does not export a valid factory function: ${e}`}}catch(i){return{extension:null,error:`Failed to load extension: ${i instanceof Error?i.message:String(i)}`}}}async function Je(e,r,l,n,c="<inline>"){let a=w(r);return ee(e,c,c,a,l,n)}async function te(e,r,l,n,c=!1){let a=[],i=[],d=[],o=c?he(r):void 0,u=o?.cwd??w(r),g=l??z(),h=n??me();for(let t of e){let{extension:s,error:f}=await xe(t,u,g,h,o);if(f){i.push({path:t,error:f});continue}s&&a.push(s)}return{extensions:a,errors:i,warnings:d,runtime:h}}async function Ee(e,r,l,n){return te(e,r,l,n)}async function Ge(e,r,l,n){return te(e,r,l,n,!0)}function Se(e){return e.endsWith(".ts")||e.endsWith(".js")}function re(e){let r=p.join(e,"package.json");if(v.existsSync(r)){let c=W(r);if(c?.extensions?.length){let a=[];for(let i of c.extensions){let d=p.resolve(e,i);v.existsSync(d)&&a.push(d)}if(a.length>0)return a}}let l=p.join(e,"index.ts"),n=p.join(e,"index.js");return v.existsSync(l)?[l]:v.existsSync(n)?[n]:null}function C(e){if(!v.existsSync(e))return[];let r=[];try{let l=v.readdirSync(e,{withFileTypes:!0});for(let n of l){let c=p.join(e,n.name);if((n.isFile()||n.isSymbolicLink())&&Se(n.name)){r.push(c);continue}if(n.isDirectory()||n.isSymbolicLink()){let a=re(c);a&&r.push(...a)}}}catch{return[]}return r}async function qe(e,r,l=_(),n){let c=w(r),a=w(l),i=[],d=new Set,o=h=>{for(let t of h){let s=p.resolve(t);d.has(s)||(d.add(s),i.push(t))}},u=p.join(c,D,"extensions");o(C(u));let g=p.join(a,"extensions");o(C(g));for(let h of e){let t=w(h,c,{normalizeUnicodeSpaces:!0});if(v.existsSync(t)&&v.statSync(t).isDirectory()){let s=re(t);if(s){o(s);continue}o(C(t));continue}o([t])}return Ee(i,c,n)}export{z as a,W as b,J as c,G as d,q as e,Ie as f,H as g,ae as h,T as i,je as j,ge as k,me as l,Je as m,Ee as n,Ge as o,qe as p};
@@ -0,0 +1,10 @@
1
+ import { createRequire as __cortexCreateRequire } from 'node:module';
2
+ const require = __cortexCreateRequire(import.meta.url);
3
+ const __cortexPackageRoot = new URL("../../", import.meta.url);
4
+ import{e as K,g as V}from"./chunk-STCNHXPJ.js";import{a as J}from"./chunk-NRD57ICT.js";import{K as t}from"./chunk-W34AK4SK.js";import{d as G}from"./chunk-3CPIMAYX.js";import{e as $}from"./chunk-VBN2JSER.js";import{e as z}from"./chunk-NXZS5PEW.js";import{a as _,j as X}from"./chunk-Z24SBRJK.js";var A=1,q=64*1024,O=200,Yt="other",Ht="custom",Xt="mcp_other",l=t.string().regex(/^[A-Za-z0-9._:/@[\]-]{1,80}$/),o=t.number().int().nonnegative(),u=t.number().nonnegative(),f=t.iso.datetime(),ye=t.string().regex(/^\d{4}-\d{2}-\d{2}$/),x=t.string().max(40),y=t.string().max(300),I={ttftMs:[500,1e3,2e3,5e3,1e4,3e4,6e4],turnDurationS:[5,15,30,60,120,300,600,1800,3600],contextPct:[10,25,50,75,90,100],turnsPerSession:[1,2,5,10,20,50,100],webLoadMs:[200,500,1e3,2e3,5e3,1e4]};function d(e){return t.array(o).length(I[e].length+1)}function $t(e,n){let r=I[e],s=r.findIndex(i=>n<=i);return s===-1?r.length:s}function Kt(e){return new Array(I[e].length+1).fill(0)}var ge=t.object({schema:t.literal(A),installId:t.uuid(),sentAt:f,version:x,channel:t.enum(["release","dev"]),installForm:t.enum(["desktop","npm","other"]),os:t.enum(["linux","darwin","win32","android","other"]),osRelease:t.string().max(20),arch:t.string().max(20),nodeMajor:t.number().int().nullable(),uiLang:t.enum(["en","zh","other"])}),Re=["server","daemon","web","desktop","android"],Le=["uncaughtException","unhandledRejection","childExit","renderError","windowError","panic"],ve=["desktop","android","browser"],we=t.object({type:t.literal("crash"),at:f,component:t.enum(Re),kind:t.enum(Le),errorName:t.string().max(80),message:y,stack:t.string().max(8e3),groupKey:t.string().max(200),uptimeS:u.nullable(),route:t.string().max(80).nullable(),buildStamp:t.string().max(60).nullable(),client:t.enum(ve).nullable(),exit:t.object({code:t.number().int().nullable(),signal:t.string().max(20).nullable(),backoffMs:o}).nullable(),suppressed:o,version:x.optional()}),Ae=t.object({type:t.literal("heartbeat"),at:f,backends:t.array(t.enum(["claude","pi"])).max(2),claudeBilling:t.enum(["plan","api","none"]),piProviders:t.array(l).max(60),projects:o,onlineClients:o,clientPlatforms:t.partialRecord(t.enum(["linux","darwin","win32","other"]),o),activeSessions24h:o,uptimeH:u,settings:t.record(l,t.boolean())}),Oe=["network","permission","npm","disk","timeout","other"],Ie=t.object({type:t.literal("upgrade"),at:f,from:x,to:x,method:t.enum(["auto","prompt","manual"]),stage:t.enum(["installed","failed","confirmed","unconfirmed","version-changed"]),durationS:u.nullable(),failure:t.object({class:t.enum(Oe),message:y}).nullable()}),Me=t.object({type:t.literal("migration_failure"),at:f,migration:l,errorClass:t.enum(["io","parse","permission","other"]),message:y}),ke=["setup_started","server_installed","server_install_failed","init_completed","init_failed","daemon_started","daemon_start_failed"],Ne=["server_init_completed","provider_authed","first_session","first_turn_completed","first_remote_client","first_worker","first_schedule"],je=["existing_install"];var Ce=t.object({type:t.literal("funnel"),at:f,source:t.enum(["desktop-setup","server"]),step:t.enum([...ke,...Ne,...je]),detail:l.nullable()}),De=["auth","rate_limit","network","adapter_crash","timeout","other"],Fe=t.object({backend:t.enum(["claude","pi"]),provider:l,model:l,billing:t.enum(["plan","api"]).nullable(),customApi:l.nullable(),outcomes:t.object({completed:o,failed:o,cancelled:o,rateLimited:o}),failures:t.partialRecord(t.enum(De),o),retries:o,fallbacks:o,ttftMs:d("ttftMs"),durationS:d("turnDurationS"),contextPctAtEnd:d("contextPct"),compactions:t.object({auto:o,manual:o}),tokens:t.object({input:o,output:o,cacheRead:o,cacheWrite:o})}),Ue=["session_created","worker_spawned","subagent_run","board_opened","schedule_created","schedule_fired","waitpoint_created","waitpoint_signaled","browser_session","plan_submitted","plan_approved","plan_rejected","ask_user_asked","ask_user_answered","remote_client_connected"],Pe=["desktop","android","browser","feishu","slack","tui","other"],W=t.object({completed:o,failed:o,cancelled:o}),Be=t.object({type:t.literal("daily"),day:ye,turns:t.array(Fe).max(100),features:t.partialRecord(t.enum(Ue),o),messagesByChannel:t.partialRecord(t.enum(Pe),o),uiOps:t.record(l,o),tools:t.array(t.object({name:l,calls:o,errors:o})).max(200),agent:t.object({userInterrupts:o,superseded:o,turnsPerSession:d("turnsPerSession"),workers:W,subagents:W}),perf:t.object({startups:t.array(t.record(l,u)).max(10),eventLoop:t.object({windows:o,p99MedianMs:u,p99MaxMs:u}),web:t.object({loads:o,ttfbMs:d("webLoadMs"),firstRenderMs:d("webLoadMs"),interactiveMs:d("webLoadMs")}),sseReconnects:o,remoteClientDisconnects:o}),errors:t.object({byModule:t.record(l,o),samples:t.array(t.object({module:l,groupKey:t.string().max(200),message:y,count:o})).max(5)})}),g=t.discriminatedUnion("type",[we,Ae,Ie,Me,Ce,Be]),Z=t.object({envelope:ge,events:t.array(g).min(1).max(O)}),Vt=t.discriminatedUnion("kind",[t.object({kind:t.literal("crash"),crashKind:t.enum(["renderError","windowError","unhandledRejection"]),errorName:t.string().max(200),message:t.string().max(2e3),stack:t.string().max(2e4),route:t.string().max(80).nullable(),buildStamp:t.string().max(60).nullable(),uptimeS:u.nullable()}),t.object({kind:t.literal("native_crash"),component:t.enum(["desktop","android"]),at:f,message:t.string().max(2e3),stack:t.string().max(2e4),appVersion:x}),t.object({kind:t.literal("load"),ttfbMs:u.nullable(),firstRenderMs:u.nullable(),interactiveMs:u.nullable()}),t.object({kind:t.literal("sse_reconnect"),count:t.number().int().min(1).max(1e3)})]),Gt="x-cortex-client",Jt=t.object({enabled:t.boolean(),installId:t.uuid().optional()});import T from"node:path";var R=T.join(X,"telemetry"),M=T.join(R,"install-id"),S=T.join(R,"outbox.jsonl"),k=T.join(R,"state.json"),Ye="rollup-";function Zt(e,n=R){return T.join(n,`${Ye}${e}.json`)}import{randomUUID as He}from"node:crypto";import{mkdirSync as Xe,readFileSync as $e,writeFileSync as Ke}from"node:fs";import Ve from"node:path";var N=new Map,Ge=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Q(e){return typeof e=="string"&&Ge.test(e)}function Je(e){try{let n=$e(e,"utf8").trim();return Q(n)?n.toLowerCase():null}catch{return null}}function ee(e,n){Xe(Ve.dirname(e),{recursive:!0}),Ke(e,`${n}
5
+ `,{encoding:"utf8",mode:384})}function te(e=M){let n=Je(e),r=n??N.get(e)??He();if(!n)try{ee(e,r)}catch{}return N.set(e,r),r}function on(e,n=M){if(!Q(e))throw new Error("install id must be a UUID");ee(n,e.toLowerCase()),N.set(n,e.toLowerCase())}import{existsSync as qe,statSync as Ze}from"node:fs";import Qe from"node:path";import{readFileSync as ze}from"node:fs";import We from"node:path";var ne=We.join(_,"dist","build-info.json"),j;function oe(e){if(typeof e!="string"||e.trim()==="")return null;try{let n=new URL(e.trim());return n.protocol==="https:"||n.protocol==="http:"?n.toString():null}catch{return null}}function re(e){try{let n=JSON.parse(ze(e,"utf8"));return oe(n.telemetryEndpoint)}catch{return null}}function se(e=process.env,n=ne){let r=oe(e.CORTEX_TELEMETRY_ENDPOINT);return r||(n!==ne?re(n):(j===void 0&&(j=re(n)),j))}function et(e){if(e===void 0)return!1;let n=e.trim().toLowerCase();return n!==""&&n!=="0"&&n!=="false"&&n!=="no"&&n!=="off"}function tt(e){return e.CORTEX_TELEMETRY?.trim()==="0"?"env":et(e.DO_NOT_TRACK)?"do-not-track":e.CORTEX_CONFIG_IMMUTABLE==="1"?"sealed":null}function nt(e){let n=e.env.CORTEX_TELEMETRY?.trim()==="1",r=e.devCheckout?"dev":"release",s=c=>({active:!1,reason:c,channel:r,endpoint:e.endpoint}),i=tt(e.env);return i?s(i):e.settingEnabled?e.devCheckout&&!n?s("dev"):e.endpoint?{active:!0,reason:null,channel:r,endpoint:e.endpoint}:s("no-endpoint"):s("setting")}var ie;function rt(){let e=process.env.CORTEX_REPO;try{return!!e&&Ze(e).isDirectory()}catch{return!1}}function ot(){return ie??=qe(Qe.join(_,"src","entry"))||rt(),ie}function C(e=process.env){return nt({settingEnabled:K().telemetryEnabled,env:e,devCheckout:ot(),endpoint:se(e)})}function h(){return C().active}import{mkdirSync as st,readFileSync as it,writeFileSync as at}from"node:fs";import ct from"node:path";var ae={lastHeartbeatAt:null,lastVersion:null,funnelSent:[],pendingUpgrade:null,funnelBaseline:null};function lt(e){return e==="fresh"||e==="existing"?e:null}function D(e=k){try{let n=JSON.parse(it(e,"utf8"));return{...ae,...n,funnelSent:Array.isArray(n.funnelSent)?n.funnelSent.filter(r=>typeof r=="string"):[],funnelBaseline:lt(n.funnelBaseline)}}catch{return{...ae}}}function ce(e,n=k){let r=e(D(n));try{st(ct.dirname(n),{recursive:!0}),at(n,`${JSON.stringify(r,null,2)}
6
+ `,"utf8")}catch{}return r}import ut from"node:os";var pt=["linux","darwin","win32","android"];function mt(e=process.env,n=_){return e.CORTEX_NPM_PREFIX?.trim()?"desktop":z(n,"@cortex-agent/server")?"npm":"other"}function dt(e){return pt.includes(e)?e:"other"}function ft(e){return(e.split(".")[0]??"").slice(0,20)}function le(e,n=new Date){return{schema:A,installId:te(),sentAt:n.toISOString(),version:J.slice(0,40),channel:e,installForm:mt(),os:dt(process.platform),osRelease:ft(ut.release()),arch:process.arch.slice(0,20),nodeMajor:Number.parseInt(process.versions.node,10),uiLang:G()}}import{appendFileSync as Et,existsSync as _t,mkdirSync as ht,readFileSync as xt,renameSync as Tt,rmSync as v,statSync as St,writeFileSync as bt}from"node:fs";import yt from"node:path";var ue=2*1024*1024,gt=Math.floor(ue*.75);function F(e){return`${e.slice(0,-6)}.sending.jsonl`}function L(e){try{return xt(e,"utf8").split(`
7
+ `).filter(n=>n.trim()!=="")}catch{return[]}}function pe(e,n){let r=0,s=e.length;for(;s>0&&r+Buffer.byteLength(e[s-1])+1<=n;)s-=1,r+=Buffer.byteLength(e[s])+1;return e.slice(s)}function U(e,n){if(n.length===0)return void v(e,{force:!0});bt(e,`${n.join(`
8
+ `)}
9
+ `,"utf8")}function Rt(e,n){St(e).size<=n||U(e,pe(L(e),Math.floor(n*.75)))}function me(e,n=S,r=ue){let s=g.safeParse(e);if(!s.success)return!1;try{return ht(yt.dirname(n),{recursive:!0}),Et(n,`${JSON.stringify(s.data)}
10
+ `,"utf8"),Rt(n,r),!0}catch{return!1}}function de(e=S){let n=F(e);if(_t(e)){let r=`${e}.${process.pid}.tmp`;try{Tt(e,r),U(n,pe([...L(n),...L(r)],gt)),v(r,{force:!0})}catch{}}return L(n).flatMap(r=>Lt(r))}function Lt(e){try{let n=g.safeParse(JSON.parse(e));return n.success?[n.data]:[]}catch{return[]}}function fe(e,n=S){try{U(F(n),e.map(r=>JSON.stringify(r)))}catch{}}function Ee(e=S){v(e,{force:!0}),v(F(e),{force:!0})}var _e=$("telemetry"),vt=1e4,wt=2048;function he(e){let n=q-wt,r=[],s=[],i=0;for(let c of e){let m=Buffer.byteLength(JSON.stringify(c))+1;m>n||((s.length>=O||i+m>n)&&(r.push(s),s=[],i=0),s.push(c),i+=m)}return s.length>0&&r.push(s),r}function At(e,n){return n?"sent":e>=400&&e<500?"rejected":"retry"}async function xe(e,n,r,s=fetch){let i=Z.safeParse({envelope:n,events:r});if(!i.success)return"rejected";try{let c=await s(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(i.data),signal:AbortSignal.timeout(vt)});c.body?.cancel?.().catch(()=>{});let m=At(c.status,c.ok);return m!=="sent"&&_e.debug(`telemetry upload ${m}: HTTP ${c.status}`),m}catch(c){return _e.debug(`telemetry upload failed: ${c.message}`),"retry"}}var b=class{now;failures=0;nextAt=0;constructor(n=Date.now){this.now=n}ready(){return this.now()>=this.nextAt}succeeded(){this.failures=0,this.nextAt=0}failed(){this.failures+=1;let n=Math.min(6e4*2**(this.failures-1),360*6e4);this.nextAt=this.now()+n}};var Ot=1440*60*1e3,It=600*1e3,Mt=3e4,kt=2e3,B=[],w=new b,a=null,P=null,p=null,Te=0;function Xn(e){B.push(e)}function E(){return a?.options.now?.()??Date.now()}function Y(e){for(let n of B)try{e(n)?.()}catch{}}function H(){try{Ee()}catch{}Y(e=>e.wipe)}function Nt(e,n={}){if(!h())return!1;let r=me(e);return r&&n.urgent&&Se(kt),r}function Se(e){let n=E()+e;!a||p&&Te<=n||(p&&clearTimeout(p),Te=n,p=setTimeout(()=>{p=null,be()},e),p.unref?.())}async function jt(e,n){let r=he(n);for(let s=0;s<r.length;s+=1){let i=le(e.channel,new Date(E()));if(await xe(e.endpoint,i,r[s],a?.options.fetchImpl)==="retry")return w.failed(),r.slice(s).flat()}return w.succeeded(),[]}async function Ct(){let e=C();if(!e.active||!e.endpoint||!w.ready())return;let n=de();fe(n.length===0?[]:await jt(e,n))}function be(){return P??=Ct().catch(()=>{}).finally(()=>{P=null}),P}async function Dt(){let e=Date.parse(D().lastHeartbeatAt??"")||0;if(!a||E()-e<Ot)return;let n=await a.options.collectHeartbeat().catch(()=>null);!n||!Nt(n)||ce(r=>({...r,lastHeartbeatAt:new Date(E()).toISOString()}))}async function Ft(e){for(let n of B)try{await n.finalize?.(e)}catch{}}async function $n(){if(!h())return H();Y(e=>e.persist),await a?.options.collectFunnel?.().catch(()=>{}),!(!a||E()-a.bootAt<Ut(a.options))&&(await Ft(E()),await Dt(),await be())}function Ut(e){if(e.firstDelayMs!==void 0)return e.firstDelayMs;let n=Number.parseInt(process.env.CORTEX_TELEMETRY_FIRST_DELAY_S??"",10);return Number.isFinite(n)&&n>=0?n*1e3:It}function Pt(e){e.includes("telemetryEnabled")&&!h()&&H()}function Kn(e){if(!a){if(a={options:e,bootAt:e.now?.()??Date.now(),unsubscribe:V(Pt)},w=new b(()=>E()),!h())return H();Se(Mt),e.collectFunnel?.().catch(()=>{})}}function Vn(){p&&clearTimeout(p),p=null,a?.unsubscribe(),a=null,h()&&Y(e=>e.persist)}export{Yt as a,Ht as b,Xt as c,$t as d,Kt as e,ve as f,Ne as g,Ue as h,Pe as i,Be as j,Vt as k,Gt as l,Jt as m,R as n,k as o,Ye as p,Zt as q,Q as r,te as s,on as t,C as u,h as v,D as w,ce as x,Xn as y,Nt as z,$n as A,Kn as B,Vn as C};