@cortex-agent/server 2026.10.28 → 2026.12.5

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 (401) hide show
  1. package/LICENSE +255 -21
  2. package/README.md +36 -7
  3. package/THIRD_PARTY_NOTICES.txt +1990 -593
  4. package/defaults/hooks/cortex-hook-api.mjs +2 -1
  5. package/defaults/hooks/quota-stop.mjs +37 -0
  6. package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +23 -15
  7. package/defaults/prompts/clean-workspace.md +5 -0
  8. package/dist/agent-adapter/claude/remote-mcp-proxy.js +1 -1
  9. package/dist/chunks/agent-runner-LVZVKBZX.js +4 -0
  10. package/dist/chunks/anthropic-messages-TT6454AA.js +8 -0
  11. package/dist/chunks/azure-openai-responses-52LR2XZD.js +4 -0
  12. package/dist/chunks/bedrock-converse-stream-EOZGYUNY.js +60 -0
  13. package/dist/chunks/bowser-MLGGLXTZ.js +20 -0
  14. package/dist/chunks/child-runner-SMG2VOU5.js +4 -0
  15. package/dist/chunks/chunk-24DH4IR5.js +4 -0
  16. package/dist/chunks/chunk-25XKBRDT.js +70 -0
  17. package/dist/chunks/chunk-2ABET62E.js +23 -0
  18. package/dist/chunks/chunk-2BVUA256.js +4 -0
  19. package/dist/chunks/{chunk-LEUENXI2.js → chunk-2WFL62UO.js} +1 -1
  20. package/dist/chunks/{chunk-OZGBWAT2.js → chunk-2YTYYG4K.js} +1 -1
  21. package/dist/chunks/chunk-335SSANX.js +4 -0
  22. package/dist/chunks/chunk-377OPTXX.js +17 -0
  23. package/dist/chunks/chunk-3EZNVLBF.js +129 -0
  24. package/dist/chunks/chunk-3O6ZG5HA.js +7 -0
  25. package/dist/chunks/{chunk-6AKUD3CF.js → chunk-3XLHL5YT.js} +1 -1
  26. package/dist/chunks/chunk-4HRI75GU.js +4 -0
  27. package/dist/chunks/chunk-4JBYLRPM.js +57 -0
  28. package/dist/chunks/chunk-4KKV7VKE.js +4 -0
  29. package/dist/chunks/chunk-4KQHDDC5.js +4 -0
  30. package/dist/chunks/chunk-4SWD4JMP.js +33 -0
  31. package/dist/chunks/chunk-52VCLZS5.js +4 -0
  32. package/dist/chunks/chunk-54P7TSY3.js +10 -0
  33. package/dist/chunks/chunk-5DVSAXOI.js +7 -0
  34. package/dist/chunks/chunk-5F3A62YS.js +4 -0
  35. package/dist/chunks/{chunk-XNSSUVT6.js → chunk-5FHETFZM.js} +1 -1
  36. package/dist/chunks/{chunk-A34TDMIC.js → chunk-5LBLRAHS.js} +1 -1
  37. package/dist/chunks/chunk-5UYVNA3W.js +4 -0
  38. package/dist/chunks/chunk-6G3OYMCV.js +21 -0
  39. package/dist/chunks/chunk-7GGPYU5E.js +30 -0
  40. package/dist/chunks/chunk-7TYSMLUV.js +4 -0
  41. package/dist/chunks/chunk-7W7VYUTK.js +5 -0
  42. package/dist/chunks/chunk-AXYAZTTN.js +6 -0
  43. package/dist/chunks/{chunk-BGVHA2D4.js → chunk-B3NB243Z.js} +1 -1
  44. package/dist/chunks/chunk-BKYP6AGM.js +8 -0
  45. package/dist/chunks/chunk-BVEDNESB.js +4 -0
  46. package/dist/chunks/chunk-BWDJS6A4.js +12 -0
  47. package/dist/chunks/chunk-C6YVF7EI.js +4 -0
  48. package/dist/chunks/chunk-CEJIYYVE.js +15 -0
  49. package/dist/chunks/chunk-CI2RHH74.js +50 -0
  50. package/dist/chunks/chunk-CMSOOLJB.js +4 -0
  51. package/dist/chunks/chunk-CSVTYYLP.js +4 -0
  52. package/dist/chunks/chunk-DE5EGVKG.js +6 -0
  53. package/dist/chunks/{chunk-E6BYRULL.js → chunk-DK3RPZOQ.js} +1 -1
  54. package/dist/chunks/{chunk-YPK2CAIZ.js → chunk-DK4UCK7L.js} +1 -1
  55. package/dist/chunks/chunk-DYLBVUAU.js +4 -0
  56. package/dist/chunks/chunk-FDC2GRBK.js +27 -0
  57. package/dist/chunks/chunk-FE7HH5JS.js +18 -0
  58. package/dist/chunks/chunk-FYD57YRO.js +436 -0
  59. package/dist/chunks/chunk-G264APQN.js +5 -0
  60. package/dist/chunks/chunk-G4JYZFEO.js +11 -0
  61. package/dist/chunks/chunk-GFFM56U2.js +4 -0
  62. package/dist/chunks/chunk-GOS3P7KS.js +132 -0
  63. package/dist/chunks/chunk-HVN37UXD.js +4 -0
  64. package/dist/chunks/chunk-IA6IODY3.js +4 -0
  65. package/dist/chunks/{chunk-HU6UIDEJ.js → chunk-IGZWZP7Z.js} +1 -1
  66. package/dist/chunks/{chunk-NR6U3WIZ.js → chunk-IJ7XFQMI.js} +1 -1
  67. package/dist/chunks/chunk-IMMGYDAB.js +6 -0
  68. package/dist/chunks/chunk-IOWBF7UK.js +10 -0
  69. package/dist/chunks/{chunk-HALUQ7ZF.js → chunk-ITGCWQFK.js} +1 -1
  70. package/dist/chunks/chunk-IVZ7QUEG.js +4 -0
  71. package/dist/chunks/{chunk-YAEVYJAR.js → chunk-IWY2HIFK.js} +1 -1
  72. package/dist/chunks/{chunk-KGJZAYQD.js → chunk-J7OBATRN.js} +1 -1
  73. package/dist/chunks/{chunk-QWAQHHRS.js → chunk-JGUEIW2W.js} +1 -1
  74. package/dist/chunks/chunk-JKL3AK5D.js +106 -0
  75. package/dist/chunks/chunk-JZ7U7RUK.js +351 -0
  76. package/dist/chunks/chunk-KJUQCCB5.js +4 -0
  77. package/dist/chunks/chunk-KST6OY76.js +10 -0
  78. package/dist/chunks/chunk-KZSAFVSY.js +129 -0
  79. package/dist/chunks/chunk-LD2ZSH3M.js +903 -0
  80. package/dist/chunks/chunk-LE6QPXN6.js +7 -0
  81. package/dist/chunks/chunk-LEAV3FFG.js +4 -0
  82. package/dist/chunks/chunk-LIIZI3HY.js +5 -0
  83. package/dist/chunks/chunk-LP72AF56.js +45 -0
  84. package/dist/chunks/{chunk-FXDIR3SQ.js → chunk-MJQ2D2OP.js} +1 -1
  85. package/dist/chunks/{chunk-6LZK4DDH.js → chunk-NHHR4DCF.js} +1 -1
  86. package/dist/chunks/chunk-NW4GW47L.js +4 -0
  87. package/dist/chunks/chunk-OALEJ6FG.js +60 -0
  88. package/dist/chunks/chunk-OIV4DIMB.js +4 -0
  89. package/dist/chunks/chunk-OJ37ZWBG.js +4 -0
  90. package/dist/chunks/chunk-OZXMPBUX.js +4 -0
  91. package/dist/chunks/{chunk-3THJYAEF.js → chunk-PG7452XE.js} +1 -1
  92. package/dist/chunks/chunk-PJCUB7YJ.js +4 -0
  93. package/dist/chunks/chunk-PTS3J4DQ.js +6 -0
  94. package/dist/chunks/{chunk-PXS5SHOV.js → chunk-PVVEEBUU.js} +1 -1
  95. package/dist/chunks/chunk-Q7BZLPBU.js +8 -0
  96. package/dist/chunks/{chunk-FOJQXLL2.js → chunk-QC66ZXPP.js} +1 -1
  97. package/dist/chunks/chunk-QXFWIL4C.js +4 -0
  98. package/dist/chunks/{chunk-PFMEUFJ7.js → chunk-R2CCD4OF.js} +1 -1
  99. package/dist/chunks/chunk-R6CGBSTC.js +22 -0
  100. package/dist/chunks/chunk-RG5GP4RB.js +5 -0
  101. package/dist/chunks/{chunk-D3NXKK2L.js → chunk-RW2F2QNP.js} +1 -1
  102. package/dist/chunks/{models-L5VF4I5O-XXNJYQMQ.js → chunk-RWPO3NZ3.js} +1 -1
  103. package/dist/chunks/chunk-SAJD4EKE.js +10 -0
  104. package/dist/chunks/chunk-SDUS2H3E.js +4 -0
  105. package/dist/chunks/chunk-SIHGKM4E.js +4 -0
  106. package/dist/chunks/chunk-SKHFU5DI.js +4 -0
  107. package/dist/chunks/{chunk-STUHNKQS.js → chunk-SM45TH22.js} +1 -1
  108. package/dist/chunks/chunk-T54CZKNJ.js +6 -0
  109. package/dist/chunks/chunk-TKFFQNAP.js +19 -0
  110. package/dist/chunks/chunk-TMV2ZDOI.js +18 -0
  111. package/dist/chunks/chunk-TRXLIL7V.js +4 -0
  112. package/dist/chunks/{chunk-SUFW24P4.js → chunk-UEEW2R4E.js} +1 -1
  113. package/dist/chunks/chunk-UHXPRU6G.js +10 -0
  114. package/dist/chunks/chunk-UPQVWHZ3.js +4 -0
  115. package/dist/chunks/{chunk-JERCOLY3.js → chunk-V35MFAUQ.js} +4 -6
  116. package/dist/chunks/chunk-V7K3KNDM.js +4 -0
  117. package/dist/chunks/chunk-VHX2GHBF.js +4 -0
  118. package/dist/chunks/chunk-VOAKRJ4R.js +4 -0
  119. package/dist/chunks/{chunk-X2GYYRVM.js → chunk-VW7TLY3P.js} +1 -1
  120. package/dist/chunks/chunk-W34AK4SK.js +65 -0
  121. package/dist/chunks/{chunk-REBNWCKI.js → chunk-WU7RNAZD.js} +1 -1
  122. package/dist/chunks/chunk-WZC4TDDM.js +6 -0
  123. package/dist/chunks/chunk-WZYS2HAK.js +4 -0
  124. package/dist/chunks/chunk-X2TKJ7KR.js +11 -0
  125. package/dist/chunks/{chunk-H2FP6DG4.js → chunk-X5ND4H4P.js} +1 -1
  126. package/dist/chunks/{chunk-4U7XXM4W.js → chunk-Y3AOGNDT.js} +1 -1
  127. package/dist/chunks/chunk-Y6DGVTKM.js +6 -0
  128. package/dist/chunks/{chunk-KENCMLRE.js → chunk-YAEHSSR4.js} +1 -1
  129. package/dist/chunks/chunk-YWPBE5LP.js +4 -0
  130. package/dist/chunks/chunk-ZAVX7G2M.js +15 -0
  131. package/dist/chunks/chunk-ZD2M73XA.js +19 -0
  132. package/dist/chunks/chunk-ZD4O6NPV.js +4 -0
  133. package/dist/chunks/chunk-ZNAMETPQ.js +4 -0
  134. package/dist/chunks/chunk-ZY6N5LVQ.js +4 -0
  135. package/dist/chunks/chunk-ZYQ4TDTT.js +81 -0
  136. package/dist/chunks/cli-VB2N7HEK.js +55 -0
  137. package/dist/chunks/cloudflare-workers-ai-system-one-YKU742EC.js +4 -0
  138. package/dist/chunks/context-CI2FKEQE.js +4 -0
  139. package/dist/chunks/cost-CZRRSIUF.js +5 -0
  140. package/dist/chunks/dist-QCNQN6DY.js +4 -0
  141. package/dist/chunks/easter-egg-3d-XR5S2O3T.js +4 -0
  142. package/dist/chunks/{event-streams-3JSFPOTZ.js → event-streams-AVE4MSS6.js} +1 -1
  143. package/dist/chunks/{execution-repo-ZLJTBWFC.js → execution-repo-5TLV2NM4.js} +1 -1
  144. package/dist/chunks/{executions-6ARGR3IO.js → executions-I3UUIGSL.js} +1 -1
  145. package/dist/chunks/file-Y5G56IUT.js +4 -0
  146. package/dist/chunks/github-copilot-BRU2SRRZ.js +4 -0
  147. package/dist/chunks/google-generative-ai-ZF5QEUZV.js +4 -0
  148. package/dist/chunks/google-vertex-4PJZZI3Y.js +4 -0
  149. package/dist/chunks/init-A6GY656J.js +4 -0
  150. package/dist/chunks/{install-cli-4IZCSDFZ.js → install-cli-FALWKQYO.js} +1 -1
  151. package/dist/chunks/{interaction-ask-G5T3H3CG.js → interaction-ask-O5HGF6CH.js} +1 -1
  152. package/dist/chunks/{interaction-plan-E5V42MUP.js → interaction-plan-JTVDN3BC.js} +1 -1
  153. package/dist/chunks/kimi-coding-ZCIBMDZ6.js +4 -0
  154. package/dist/chunks/{llama-cpp-classify-OTXZWCMW.js → llama-cpp-classify-NRUXAIGQ.js} +3 -3
  155. package/dist/chunks/local-client-stop-RS4AHNF4.js +4 -0
  156. package/dist/chunks/{memory-cli-PYOILNN5.js → memory-cli-DIT4DQF3.js} +1 -1
  157. package/dist/chunks/meta-JQH66YU7.js +4 -0
  158. package/dist/chunks/mistral-conversations-CXHOECUV.js +7 -0
  159. package/dist/chunks/model-resolver-GIBPYRKP.js +4 -0
  160. package/dist/chunks/monitor-Z2HKNY5E.js +4 -0
  161. package/dist/chunks/{node-PTK2HCDV.js → node-DAO3SX7O.js} +1 -1
  162. package/dist/chunks/{openai-codex-2REL6UQU.js → openai-codex-JULCKICT.js} +1 -1
  163. package/dist/chunks/openai-codex-responses-U6DGMGDK.js +12 -0
  164. package/dist/chunks/openai-completions-PP4XLLOM.js +9 -0
  165. package/dist/chunks/{openai-decisions-2N6ZRPZC.js → openai-decisions-JU6QQKEM.js} +1 -1
  166. package/dist/chunks/openai-responses-2SG757TL.js +6 -0
  167. package/dist/chunks/openrouter-images-32M7YZWC.js +4 -0
  168. package/dist/chunks/pi-messages-VSINMXN4.js +10 -0
  169. package/dist/chunks/radius-THYKWV4E.js +4 -0
  170. package/dist/chunks/remote-ops-2WBEFQ3E.js +14 -0
  171. package/dist/chunks/runner-5MKMRTIN.js +4 -0
  172. package/dist/chunks/runtime-DST3H5JP.js +4 -0
  173. package/dist/chunks/schedule-cli-V7Y2BBVY.js +4 -0
  174. package/dist/chunks/slack-R7SEJYMY.js +4 -0
  175. package/dist/chunks/start-ui-http-7K5JOLPU.js +43 -0
  176. package/dist/chunks/subagent-Z5IQ4L54.js +4 -0
  177. package/dist/chunks/{time-KEHDQT6K.js → time-P6PE52WL.js} +1 -1
  178. package/dist/chunks/tool-shims-YCXZWTST.js +4 -0
  179. package/dist/chunks/typesafe-system-one-M2DABJSZ.js +4 -0
  180. package/dist/chunks/ui-board-HQIE4RZG.js +5 -0
  181. package/dist/chunks/ui-decision-YBZDS4YW.js +4 -0
  182. package/dist/chunks/{ui-file-GVH53O3X.js → ui-file-SRD4ILBS.js} +1 -1
  183. package/dist/chunks/ui-view-Z25MTZT7.js +4 -0
  184. package/dist/chunks/virtual-modules-H4DXPJZB.js +4 -0
  185. package/dist/chunks/waitpoint-M6JZBSLT.js +5 -0
  186. package/dist/chunks/workers-SQ2R32TK.js +4 -0
  187. package/dist/client-bundle/client.mjs +273 -93
  188. package/dist/client-bundle/manifest.json +2 -2
  189. package/dist/core/pi-sdk.js +1 -1
  190. package/dist/domain/auth/cc-auth-cli.js +1 -1
  191. package/dist/domain/mcp/bundled-server.js +1 -1
  192. package/dist/domain/mcp/feishu/client.js +4 -0
  193. package/dist/entry/app.js +151 -559
  194. package/dist/entry/browser-cli.js +10 -10
  195. package/dist/entry/cli.js +1 -1
  196. package/dist/entry/cortex-cli.js +1 -1
  197. package/dist/entry/daemon.js +4 -4
  198. package/dist/entry/hook-cli.js +2 -2
  199. package/dist/entry/production-app-bootstrap.js +1 -1
  200. package/dist/entry/production-evidence-export-cli.js +1 -1
  201. package/dist/entry/signal-cli.js +2 -2
  202. package/dist/tui/index.js +41 -41
  203. package/package.json +3 -3
  204. package/vendor/pi/CHANGELOG.md +330 -0
  205. package/vendor/pi/dist/codemode-worker.js +2 -0
  206. package/vendor/pi/dist/core/export-html/ansi-to-html.js +57 -20
  207. package/vendor/pi/dist/core/export-html/template.css +9 -0
  208. package/vendor/pi/dist/core/export-html/template.js +166 -46
  209. package/vendor/pi/dist/core/export-html/tool-renderer.js +5 -3
  210. package/vendor/pi/dist/core/extensions/loader.js +1 -1
  211. package/vendor/pi/dist/extensions/codemode/execute.js +15 -13
  212. package/vendor/pi/dist/modes/interactive/theme/theme.js +36 -23
  213. package/vendor/pi/dist/utils/image-resize-worker.js +1 -1
  214. package/vendor/pi/dist/utils/image-resize.js +1 -1
  215. package/vendor/pi/docs/cli.md +35 -12
  216. package/vendor/pi/docs/custom-provider.md +2 -0
  217. package/vendor/pi/docs/environment-variables.md +2 -0
  218. package/vendor/pi/docs/extensions.md +3192 -225
  219. package/vendor/pi/docs/keybindings.md +2 -2
  220. package/vendor/pi/docs/llama-cpp.md +27 -19
  221. package/vendor/pi/docs/mcp.md +6 -4
  222. package/vendor/pi/docs/message-types.md +1 -1
  223. package/vendor/pi/docs/models-configuration.md +9 -3
  224. package/vendor/pi/docs/models.md +2 -1
  225. package/vendor/pi/docs/nvidia-rtx-llama-cpp.md +5 -5
  226. package/vendor/pi/docs/packages.md +24 -0
  227. package/vendor/pi/docs/prompt-templates.md +1 -1
  228. package/vendor/pi/docs/providers.md +4 -2
  229. package/vendor/pi/docs/quickstart.md +7 -3
  230. package/vendor/pi/docs/rpc-commands.md +1 -1
  231. package/vendor/pi/docs/rpc.md +4 -2
  232. package/vendor/pi/docs/sessions.md +17 -3
  233. package/vendor/pi/docs/settings.md +6 -5
  234. package/vendor/pi/docs/slash-commands.md +3 -2
  235. package/vendor/pi/docs/terminal-setup.md +3 -1
  236. package/vendor/pi/docs/tmux.md +6 -0
  237. package/vendor/pi/docs/tui.md +4 -0
  238. package/vendor/pi/docs/windows.md +27 -0
  239. package/vendor/pi/examples/extensions/README.md +2 -1
  240. package/vendor/pi/examples/extensions/custom-provider-anthropic/index.ts +27 -31
  241. package/vendor/pi/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  242. package/vendor/pi/examples/extensions/custom-provider-anthropic/package.json +1 -1
  243. package/vendor/pi/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  244. package/vendor/pi/examples/extensions/debug-provider.ts +2 -2
  245. package/vendor/pi/examples/extensions/gondolin/index.ts +4 -7
  246. package/vendor/pi/examples/extensions/gondolin/package-lock.json +19 -29
  247. package/vendor/pi/examples/extensions/gondolin/package.json +2 -2
  248. package/vendor/pi/examples/extensions/plan-mode/index.ts +23 -13
  249. package/vendor/pi/examples/extensions/plan-mode/utils.ts +42 -16
  250. package/vendor/pi/examples/extensions/preset.ts +2 -0
  251. package/vendor/pi/examples/extensions/reload-runtime.ts +17 -5
  252. package/vendor/pi/examples/extensions/subagent/README.md +14 -11
  253. package/vendor/pi/examples/extensions/subagent/index.ts +392 -171
  254. package/vendor/pi/examples/extensions/todo.ts +7 -0
  255. package/vendor/pi/examples/extensions/tools.ts +2 -0
  256. package/vendor/pi/examples/extensions/with-deps/package-lock.json +2 -2
  257. package/vendor/pi/examples/extensions/with-deps/package.json +1 -1
  258. package/vendor/pi/examples/tsconfig.json +208 -0
  259. package/vendor/pi/package.json +15 -16
  260. package/vendor/pi/schemas/models.schema.json +66 -37
  261. package/vendor/pi/schemas/settings.schema.json +18 -1
  262. package/vendor/pi-ai/bedrock.js +1 -1
  263. package/vendor/pi-ai/oauth-load.js +1 -1
  264. package/web/dist/assets/{board-math-css-BPXakv_3.js → board-math-css-DKX6FcUS.js} +1 -1
  265. package/web/dist/assets/index-D11wi0uG.js +540 -0
  266. package/web/dist/assets/index-JedYumhY.css +1 -0
  267. package/web/dist/assets/{index-WCm6wwmM.js → index-jl30Gy8P.js} +1 -1
  268. package/web/dist/assets/pdf-worker-DdZgk2mV.js +57 -0
  269. package/web/dist/assets/pdf.worker.min-Bz_KHX45.js +55 -0
  270. package/web/dist/index.html +2 -2
  271. package/web/dist/theme.css +22 -0
  272. package/dist/chunks/anthropic-messages-M3SMXACA.js +0 -8
  273. package/dist/chunks/api-GM53PHIL-GFHEXXE6.js +0 -4
  274. package/dist/chunks/azure-openai-responses-76YWXHSB.js +0 -4
  275. package/dist/chunks/bedrock-converse-stream-5UPX4NTQ.js +0 -58
  276. package/dist/chunks/child-runner-3GHOWGZP.js +0 -4
  277. package/dist/chunks/chunk-2ZNLUY2U.js +0 -128
  278. package/dist/chunks/chunk-3F6WW7HR.js +0 -13
  279. package/dist/chunks/chunk-3OKHUVEM.js +0 -7
  280. package/dist/chunks/chunk-3YHOCPQU.js +0 -10
  281. package/dist/chunks/chunk-4EX2JJWB.js +0 -4
  282. package/dist/chunks/chunk-4LLH5OWM.js +0 -10
  283. package/dist/chunks/chunk-52T37Y47.js +0 -8
  284. package/dist/chunks/chunk-7MU2AKNM.js +0 -4
  285. package/dist/chunks/chunk-AAA3UBIS.js +0 -4
  286. package/dist/chunks/chunk-ASYQHJVQ.js +0 -9
  287. package/dist/chunks/chunk-BKHDWCRT.js +0 -79
  288. package/dist/chunks/chunk-CQLH4UVX.js +0 -4
  289. package/dist/chunks/chunk-CVC66CFV.js +0 -33
  290. package/dist/chunks/chunk-D6UA4BZC.js +0 -19
  291. package/dist/chunks/chunk-DGMNI4AO.js +0 -4
  292. package/dist/chunks/chunk-DHSA5ACV.js +0 -125
  293. package/dist/chunks/chunk-DPQPXBTP.js +0 -68
  294. package/dist/chunks/chunk-DXBSQXJL.js +0 -18
  295. package/dist/chunks/chunk-E7ZMYIY6.js +0 -30
  296. package/dist/chunks/chunk-EQITBTJC.js +0 -10
  297. package/dist/chunks/chunk-EXJA5RIX.js +0 -357
  298. package/dist/chunks/chunk-FF7UELTU.js +0 -4
  299. package/dist/chunks/chunk-FH74NME3.js +0 -115
  300. package/dist/chunks/chunk-FOQ7VLIL.js +0 -17
  301. package/dist/chunks/chunk-FX6MOGLR.js +0 -11
  302. package/dist/chunks/chunk-G2V65UBA.js +0 -4
  303. package/dist/chunks/chunk-HGPBHTVD.js +0 -6
  304. package/dist/chunks/chunk-J5DVLUKY.js +0 -6
  305. package/dist/chunks/chunk-JW2HFMTF.js +0 -4
  306. package/dist/chunks/chunk-KDYEGGMW.js +0 -4
  307. package/dist/chunks/chunk-KIGMAATV.js +0 -23
  308. package/dist/chunks/chunk-KIU5FAPY.js +0 -5
  309. package/dist/chunks/chunk-KIWMQPH7.js +0 -739
  310. package/dist/chunks/chunk-L6VCIGWS.js +0 -11
  311. package/dist/chunks/chunk-LACGULCN.js +0 -10
  312. package/dist/chunks/chunk-LMSQZ6TQ.js +0 -4
  313. package/dist/chunks/chunk-MEPASGPP.js +0 -6
  314. package/dist/chunks/chunk-MFAEUHMV.js +0 -28
  315. package/dist/chunks/chunk-NAA7GF6Q.js +0 -5
  316. package/dist/chunks/chunk-NKDMKRSB.js +0 -68
  317. package/dist/chunks/chunk-NKXV32S6.js +0 -4
  318. package/dist/chunks/chunk-NVX5IPRN.js +0 -4
  319. package/dist/chunks/chunk-O3JW2F7D.js +0 -8
  320. package/dist/chunks/chunk-OE4KH3NJ.js +0 -4
  321. package/dist/chunks/chunk-OISO5JXB.js +0 -4
  322. package/dist/chunks/chunk-OPYXNSMY.js +0 -4
  323. package/dist/chunks/chunk-OSEIQ7SS.js +0 -4
  324. package/dist/chunks/chunk-P52RMIYX.js +0 -6
  325. package/dist/chunks/chunk-PBJ5MPPX.js +0 -60
  326. package/dist/chunks/chunk-PZMGBKUR.js +0 -13
  327. package/dist/chunks/chunk-PZMXHA6X.js +0 -9
  328. package/dist/chunks/chunk-Q7CE3UIE.js +0 -133
  329. package/dist/chunks/chunk-QBKCAIJG.js +0 -4
  330. package/dist/chunks/chunk-QEOFEETJ.js +0 -4
  331. package/dist/chunks/chunk-QUUEQRIT.js +0 -4
  332. package/dist/chunks/chunk-RA6HKFBV.js +0 -4
  333. package/dist/chunks/chunk-REPYBMQS.js +0 -4
  334. package/dist/chunks/chunk-SKHLZ6XY.js +0 -9
  335. package/dist/chunks/chunk-TAWLERZA.js +0 -4
  336. package/dist/chunks/chunk-TWAEABGG.js +0 -52
  337. package/dist/chunks/chunk-TZFLHVOQ.js +0 -7
  338. package/dist/chunks/chunk-UD3NMUHR.js +0 -12
  339. package/dist/chunks/chunk-UNVEZI57.js +0 -4
  340. package/dist/chunks/chunk-VQUPKMDR.js +0 -4
  341. package/dist/chunks/chunk-W25TB3PU.js +0 -4
  342. package/dist/chunks/chunk-W5LGYSPZ.js +0 -4
  343. package/dist/chunks/chunk-WEZWKMYU.js +0 -4
  344. package/dist/chunks/chunk-XAJLZR7C.js +0 -28
  345. package/dist/chunks/chunk-XH6FMP3N.js +0 -71
  346. package/dist/chunks/chunk-XSRZHN63.js +0 -4
  347. package/dist/chunks/chunk-Y3GFB5XM.js +0 -8
  348. package/dist/chunks/chunk-YG7OEPR2.js +0 -6
  349. package/dist/chunks/chunk-YHIWOGVL.js +0 -4
  350. package/dist/chunks/chunk-YKKEI5GI.js +0 -4
  351. package/dist/chunks/chunk-YZSHTWNM.js +0 -92
  352. package/dist/chunks/chunk-Z4H3VDHI.js +0 -4
  353. package/dist/chunks/cli-5DBTRMHU.js +0 -53
  354. package/dist/chunks/client-XOGYH5UR.js +0 -4
  355. package/dist/chunks/cloudflare-workers-ai-system-one-32JCFHI3.js +0 -4
  356. package/dist/chunks/config-DJSQI77S-335IXHSM.js +0 -4
  357. package/dist/chunks/context-VCQH5OB6.js +0 -4
  358. package/dist/chunks/cost-PGGFI7QJ.js +0 -5
  359. package/dist/chunks/dist-PUKMZ7GW.js +0 -4
  360. package/dist/chunks/easter-egg-3d-MO4MOEVF.js +0 -4
  361. package/dist/chunks/es5-VNTQPCKX.js +0 -4
  362. package/dist/chunks/file-7BN7RCAY.js +0 -4
  363. package/dist/chunks/gateway-UCRPMR75.js +0 -36
  364. package/dist/chunks/github-copilot-HAI2DA62.js +0 -4
  365. package/dist/chunks/google-generative-ai-2VXWLHWI.js +0 -4
  366. package/dist/chunks/google-vertex-UA36QP2U.js +0 -4
  367. package/dist/chunks/init-HA7FAQ73.js +0 -4
  368. package/dist/chunks/kimi-coding-HMJRKCPA.js +0 -4
  369. package/dist/chunks/local-client-stop-SQRU7ZZM.js +0 -4
  370. package/dist/chunks/meta-KY3LNFV2.js +0 -4
  371. package/dist/chunks/mistral-conversations-34F66L3O.js +0 -7
  372. package/dist/chunks/model-resolver-N3DTAQ2S.js +0 -4
  373. package/dist/chunks/openai-codex-responses-ZBVHREB3.js +0 -12
  374. package/dist/chunks/openai-completions-VVIB26SH.js +0 -9
  375. package/dist/chunks/openai-responses-735XA2ZX.js +0 -6
  376. package/dist/chunks/openrouter-images-3IKETHAC.js +0 -4
  377. package/dist/chunks/pi-messages-I3E4ZFHA.js +0 -10
  378. package/dist/chunks/radius-HXRZVBDB.js +0 -4
  379. package/dist/chunks/remote-ops-BALZYKH6.js +0 -14
  380. package/dist/chunks/runner-PLVZDGHB.js +0 -4
  381. package/dist/chunks/runtime-6YLTA2ZD.js +0 -4
  382. package/dist/chunks/schedule-cli-OLASBBYJ.js +0 -4
  383. package/dist/chunks/slack-WAGSPZUX.js +0 -4
  384. package/dist/chunks/start-ui-http-QALT7C3P.js +0 -43
  385. package/dist/chunks/subagent-E3UC7ZHC.js +0 -4
  386. package/dist/chunks/tool-shims-Q6P6UXVC.js +0 -4
  387. package/dist/chunks/typesafe-system-one-6ULACYD4.js +0 -4
  388. package/dist/chunks/ui-board-4GYW6KKW.js +0 -5
  389. package/dist/chunks/ui-decision-U2FXSEC2.js +0 -4
  390. package/dist/chunks/ui-view-O7PLANT7.js +0 -4
  391. package/dist/chunks/virtual-modules-IDC5YKZJ.js +0 -4
  392. package/dist/chunks/waitpoint-2FGQBIAC.js +0 -5
  393. package/dist/chunks/workers-XN4PSTH6.js +0 -4
  394. package/vendor/aistatus/gateway-cli.js +0 -21
  395. package/vendor/pi/examples/extensions/sandbox/index.ts +0 -321
  396. package/vendor/pi/examples/extensions/sandbox/package-lock.json +0 -92
  397. package/vendor/pi/examples/extensions/sandbox/package.json +0 -19
  398. package/web/dist/assets/index-BHZpFXhc.js +0 -525
  399. package/web/dist/assets/index-DqWMdMkh.css +0 -1
  400. package/web/dist/assets/pdf-worker-Hp15W1QJ.js +0 -57
  401. package/web/dist/assets/pdf.worker.min-DnhTvCwe.js +0 -55
@@ -0,0 +1,4 @@
1
+ import { createRequire as __cortexCreateRequire } from 'node:module';
2
+ const require = __cortexCreateRequire(import.meta.url);
3
+ const __cortexPackageRoot = new URL("../../", import.meta.url);
4
+ import{b as _}from"./chunk-IVZ7QUEG.js";import{a as x}from"./chunk-IA6IODY3.js";import{A as D,g as T,j as S}from"./chunk-Y6DGVTKM.js";import{c as w}from"./chunk-ITGCWQFK.js";import{q as g}from"./chunk-LIIZI3HY.js";import{k as d}from"./chunk-T54CZKNJ.js";function b(e){if(!e||typeof e=="object")return!1;let t=typeof e=="string"?e:String(e);return!(!t.trim()||t==="null"||t==="undefined")}function Q(e,t){return e.some(n=>n.status==="running"&&n.kind==="scheduled"&&n.scheduleTaskId===t)}var E=["interval","daily","weekly","once"],A={sun:0,mon:1,tue:2,wed:3,thu:4,fri:5,sat:6},a=class extends Error{field;value;constructor(t,n,r){super(n),this.field=t,this.value=r,this.name="ScheduleSpecError"}},N={s:1e3,m:6e4,h:36e5,d:864e5};function $(e){let t=e?.trim().match(/^(\d+(?:\.\d+)?)(s|m|h|d)$/i);return t?Math.round(parseFloat(t[1])*N[t[2].toLowerCase()]):null}function l(e,t){if(e===void 0||e==="")throw new a(t,`${t} is required (e.g. 30m, 2h, 1d)`);let n=typeof e=="number"?Math.round(e):$(e);if(n===null||!Number.isFinite(n)||n<=0)throw new a(t,`invalid ${t}: '${e}' (use 30s, 5m, 2h, 1d)`,e);return n}function f(e){if(!e)throw new a("time","time is required (HH:MM, 24-hour)");let t=e.trim().match(/^(\d{2}):(\d{2})$/);if(!t||Number(t[1])>23||Number(t[2])>59)throw new a("time",`invalid time: '${e}' (use HH:MM, 24-hour)`,e);return t[0]}function I(e){if(e===void 0||e==="")throw new a("dayOfWeek","dayOfWeek is required (sun..sat or 0-6)");let t=typeof e=="string"?e.trim().toLowerCase():e,n=typeof t=="number"||/^\d+$/.test(t)?Number(t):A[t];if(!Number.isInteger(n)||n<0||n>6)throw new a("dayOfWeek",`invalid dayOfWeek: '${e}' (use sun..sat or 0-6)`,e);return n}function O(e){let t=typeof e=="string"?e.trim():"";if(!b(t))throw new a("message","message must be a non-empty prompt",e);return t}function L(e){return E.includes(e)}var H={interval:e=>({type:"interval",intervalMs:l(e.interval,"interval")}),daily:e=>({type:"daily",time:f(e.time)}),weekly:e=>({type:"weekly",dayOfWeek:I(e.dayOfWeek),time:f(e.time)}),once:e=>({type:"once",delayMs:l(e.delay,"delay")})};function te(e){if(!L(e.type))throw new a("type",`invalid type: '${e.type}' (valid: ${E.join(", ")})`,e.type);let t=H[e.type](e),n=e.preCheck?.trim();return{...t,message:O(e.message),projectId:e.projectId?.trim()||"general",selection:e.selection?{...e.selection}:void 0,...n?{preCheck:n}:{}}}var v=new Set(["memory-index-regen"]),F=["message","projectId","selection","dispatchType","preCheck"],W={interval:["intervalMs"],daily:["time"],weekly:["dayOfWeek","time"],once:["runAt"]};function U(e,t){let n=Object.keys(t);if(n.length===0)throw new a("patch","nothing to update \u2014 provide at least one field");let r=new Set([...F,...W[e]]),s=n.filter(i=>!r.has(i));if(s.length)throw new a("patch",`invalid fields for ${e}: ${s.join(", ")}`,s)}function B(e){if(e.dispatchType&&v.has(e.dispatchType))throw new a("dispatchType",`built-in job dispatch type cannot be scheduled: ${e.dispatchType}`);if("intervalMs"in e&&l(e.intervalMs,"intervalMs"),"dayOfWeek"in e&&I(e.dayOfWeek),"runAt"in e&&!(Number.isFinite(e.runAt)&&e.runAt>0))throw new a("runAt","runAt must be a positive epoch ms",e.runAt)}function M(e,t){U(e,t),B(t);let n={...t};return"message"in t&&(n.message=O(t.message)),"time"in t&&(n.time=f(t.time)),n}function V(e,t){let[n,r]=e.split(":").map(Number),s=new Date(t);return s.setHours(n,r,0,0),s.getTime()<=t&&s.setDate(s.getDate()+1),s.getTime()-t}function z(e,t,n){let[r,s]=t.split(":").map(Number),i=new Date(n);i.setHours(r,s,0,0);let o=(e-i.getDay()+7)%7;return o===0&&i.getTime()<=n&&(o=7),i.setDate(i.getDate()+o),i.getTime()-n}function X(e,t=Date.now()){return e.type==="daily"?V(e.time,t):e.type==="weekly"?z(e.dayOfWeek,e.time,t):e.intervalMs||6e4}function u(e,t=Date.now()){e.type!=="once"&&(e.nextRun=e.isPaused?null:t+X(e,t))}function j(e,t,n,r){let{message:s,projectId:i,preCheck:o,selection:h,...c}=e,y={id:t,message:s,projectId:i,selection:{...r},preCheck:o,createdAt:n};if(c.type==="once")return{...y,type:"once",runAt:n+c.delayMs};let k={...y,...c,lastRun:null,nextRun:null};return u(k,n),k}function ue(e,t,n){if(e===void 0&&t===void 0)return;let r={...e!==void 0?S(e):{},...t!==void 0?{thinking:t}:{}},s=D({request:n},r);if(s.ok===!0)return s.selection;if(s.reason==="invalid-thinking"){let i=r.backend??n?.backend??s.base?.backend,o=(s.allowed??[]).join(", ");throw new a("thinking",`Invalid thinking '${t}' for ${i}. Valid values: ${o}`,t)}throw new a("model",`Cannot use model '${e??""}': ${s.reason}`,e)}function Y(e){let t=e.CORTEX_BACKEND;return t!=="claude"&&t!=="pi"||!e.CORTEX_MODEL?null:{backend:t,provider:e.CORTEX_PROVIDER||null,model:e.CORTEX_MODEL}}function ce(e,t,n=process.env){if(!(!e||!t||!n.CORTEX_SESSION_ID))try{_({backend:t.backend,model:x(t),parent:Y(n)})}catch(r){throw new a("model",r.message,e)}}import*as p from"path";import*as R from"fs";var q=p.join(d,"schedules.json"),K=p.join(d,"channel-registry.json");function C(){return{tasks:[]}}function P(e){try{let t=R.readFileSync(e??K,"utf8"),n=JSON.parse(t),r={};for(let[s,i]of Object.entries(n))r[i]=s;return r}catch{return{}}}function pe(e){return P()[e]??null}function G(e){return function(n){if(typeof n!="object"||n===null||!("tasks"in n))return C();let r=n,s=P(e);for(let i of r.tasks){let o=i;"channel"in o&&!("projectId"in o)?(o.projectId=s[String(o.channel)]??"general",delete o.channel):"projectId"in o&&"channel"in o&&delete o.channel}for(let i of r.tasks){let o=i;delete o.target,delete o.fallback,o.selection&&(o.selection=g(o.selection))}return r}}var m=class{_repo;constructor(t=q,n){this._repo=new w({filePath:t,defaultValue:C,migrate:G(n),sharedFile:!0})}async read(){return this._repo.read()}async addTask(t){await this._repo.mutate(n=>(n.tasks.push(t),{next:n,result:void 0}))}async removeTask(t){return this._repo.mutate(n=>{let r=n.tasks.findIndex(s=>s.id===t);return r===-1?{next:n,result:!1}:(n.tasks.splice(r,1),{next:n,result:!0})})}async updateTask(t,n){return this._repo.mutate(r=>{let s=r.tasks.find(i=>i.id===t);return s?(n(s),{next:r,result:s}):{next:r,result:null}})}async findTask(t){return(await this._repo.read()).tasks.find(r=>r.id===t)||null}async mutate(t){return this._repo.mutate(t)}invalidate(){this._repo.invalidate()}flush(){return this._repo.flush()}},he=new m,ye=new Set(["task-dispatch","task-archive"]);import{randomBytes as J}from"crypto";async function Te(e,t,n={}){let r=j(t,J(4).toString("hex"),Date.now(),t.selection??T()),s=n.idempotencyKey;return s&&(r.idempotencyKey=s),e.mutate(i=>{let o=s?i.tasks.find(h=>h.idempotencyKey===s):void 0;return o?{next:i,result:{task:o,created:!1}}:(i.tasks.push(r),{next:i,result:{task:r,created:!0}})})}function Se(e,t,n){return e.updateTask(t,r=>{Object.assign(r,M(r.type,n)),u(r)})}function _e(e,t){return e.updateTask(t,n=>{if(n.type==="once")throw new Error(`cannot pause once schedule ${t}`);n.isPaused||Object.assign(n,{isPaused:!0,pausedAt:Date.now(),pausedBy:"user",nextRun:null})})}function De(e,t){return e.updateTask(t,n=>{if(n.type==="once")throw new Error(`cannot resume once schedule ${t}`);n.isPaused&&(Object.assign(n,{isPaused:!1,pausedAt:null,pausedBy:null}),u(n))})}export{b as a,Q as b,E as c,a as d,l as e,I as f,L as g,te as h,M as i,X as j,ue as k,ce as l,q as m,pe as n,m as o,he as p,ye as q,Te as r,Se as s,_e as t,De as u};
@@ -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{f as K,h as V}from"./chunk-AXYAZTTN.js";import{a as J}from"./chunk-R2CCD4OF.js";import{K as t}from"./chunk-W34AK4SK.js";import{d as G}from"./chunk-7GGPYU5E.js";import{e as $}from"./chunk-7W7VYUTK.js";import{e as z}from"./chunk-JGUEIW2W.js";import{b as _,k as X}from"./chunk-T54CZKNJ.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};
@@ -0,0 +1,129 @@
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 Ke,b as Je,c as Xe,d as qe,e as ze,f as Ye,g as Ze,h as Ht,i as Qe,j as ti}from"./chunk-NHHR4DCF.js";import{f as ii,i as si,j as ni,l as ri,m as oi,n as Bt,o as ai,p as ci,q as ui}from"./chunk-G264APQN.js";import{a as Wt,k as ei}from"./chunk-5DVSAXOI.js";import{b as je,c as Le,d as Ue,e as Ve}from"./chunk-HVN37UXD.js";import{e as li,h as hi}from"./chunk-IGZWZP7Z.js";import{a as Fe,b as Pe}from"./chunk-4HRI75GU.js";import{g as xe}from"./chunk-OZXMPBUX.js";import{b as _e,h as Ce}from"./chunk-UEEW2R4E.js";import{g as Be}from"./chunk-VHX2GHBF.js";import{M as Ge,N as He,P as We}from"./chunk-C6YVF7EI.js";import{a as Vt,b as Ae,c as Re,d as Oe,g as Gt,l as De,m as Ne}from"./chunk-BVEDNESB.js";import{a as di}from"./chunk-PMG4YGDU.js";import{d as Me}from"./chunk-YAEHSSR4.js";import{m as Se,r as Te,t as Ee}from"./chunk-KST6OY76.js";import{a as ke}from"./chunk-R2CCD4OF.js";import{c as It}from"./chunk-TRXLIL7V.js";import{a as Ut,b as bt,c as be,e as c}from"./chunk-7GGPYU5E.js";import{c as we,e as Ie}from"./chunk-7W7VYUTK.js";import{a as jt,b as ht,c as U,e as ve,j as Lt}from"./chunk-T54CZKNJ.js";import{c as Os,e as lt}from"./chunk-WHC7AYZD.js";var zt=Os((Hr,Ti)=>{"use strict";var qt={to(t,e){return e?`\x1B[${e+1};${t+1}H`:`\x1B[${t+1}G`},move(t,e){let i="";return t<0?i+=`\x1B[${-t}D`:t>0&&(i+=`\x1B[${t}C`),e<0?i+=`\x1B[${-e}A`:e>0&&(i+=`\x1B[${e}B`),i},up:(t=1)=>`\x1B[${t}A`,down:(t=1)=>`\x1B[${t}B`,forward:(t=1)=>`\x1B[${t}C`,backward:(t=1)=>`\x1B[${t}D`,nextLine:(t=1)=>"\x1B[E".repeat(t),prevLine:(t=1)=>"\x1B[F".repeat(t),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},Ks={up:(t=1)=>"\x1B[S".repeat(t),down:(t=1)=>"\x1B[T".repeat(t)},Js={screen:"\x1B[2J",up:(t=1)=>"\x1B[1J".repeat(t),down:(t=1)=>"\x1B[J".repeat(t),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(t){let e="";for(let i=0;i<t;i++)e+=this.line+(i<t-1?qt.up():"");return t&&(e+=qt.left),e}};Ti.exports={cursor:qt,scroll:Ks,erase:Js,beep:"\x07"}});var Ts=lt(jt(),1);import{mkdirSync as yt,writeFileSync as B,copyFileSync as ks,existsSync as L,readFileSync as ge,readdirSync as zn}from"fs";import{randomBytes as Is}from"crypto";import{execSync as ct}from"child_process";import*as d from"path";import*as W from"os";import{createInterface as Yn}from"readline/promises";import{stdin as Mt}from"process";import{existsSync as vn}from"node:fs";import{execSync as wn}from"node:child_process";import*as Ji from"node:path";import{styleText as Yt}from"node:util";import{stdout as Zt,stdin as xi}from"node:process";import*as Y from"node:readline";import Xs from"node:readline";var pi=(()=>{let t=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return e=>{let i=0;for(t.lastIndex=0;t.test(e);)i+=1;return e.length-i}})(),mi=t=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,fi=t=>t===8987||t===9001||t>=12272&&t<=12287||t>=12289&&t<=12350||t>=12441&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12783&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t>=131072&&t<=196605||t>=196608&&t<=262141;var Ds=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,Ns=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,gi=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,Fs=/\t{1,1000}/y,$i=new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*","yu"),Ps=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Ms=new RegExp("\\p{M}+","gu"),js={limit:1/0,ellipsis:""},yi=(t,e={},i={})=>{let s=e.limit??1/0,n=e.ellipsis??"",r=e?.ellipsisWidth??(n?yi(n,js,i).width:0),o=0,a=i.controlWidth??0,l=i.tabWidth??8,h=i.emojiWidth??2,f=2,p=i.regularWidth??1,g=i.wideWidth??f,$=[[Ps,p],[Ds,o],[Ns,a],[Fs,l],[$i,h],[gi,g]],m=0,w=0,C=t.length,O=0,M=!1,A=C,j=Math.max(0,s-r),S=0,R=0,k=0,x=0;t:for(;;){if(R>S||w>=C&&w>m){let D=t.slice(S,R)||t.slice(m,w);O=0;for(let K of D.replaceAll(Ms,"")){let F=K.codePointAt(0)||0;if(mi(F)?x=f:fi(F)?x=g:x=p,k+x>j&&(A=Math.min(A,Math.max(S,m)+O)),k+x>s){M=!0;break t}O+=K.length,k+=x}S=R=0}if(w>=C)break t;for(let D=0,K=$.length;D<K;D++){let[F,vt]=$[D];if(F.lastIndex=w,F.test(t)){if(O=F===gi?pi(t.slice(w,F.lastIndex)):F===$i?1:F.lastIndex-w,x=O*vt,k+x>j&&(A=Math.min(A,w+Math.floor((j-k)/vt))),k+x>s){M=!0;break t}k+=x,S=m,R=w,w=m=F.lastIndex;continue t}}w+=1}return{width:M?j:k,index:M?A:C,truncated:M,ellipsed:M&&s>=r}},vi=yi;var Ls={limit:1/0,ellipsis:"",ellipsisWidth:0},Us=(t,e={})=>vi(t,Ls,e).width,P=Us;var St="\x1B",_i="\x9B",Vs=39,Jt="\x07",Ci="[",Gs="]",ki="m",Xt=`${Gs}8;;`,wi=new RegExp(`(?:\\${Ci}(?<code>\\d+)m|\\${Xt}(?<uri>.*)${Jt})`,"y"),Ii=t=>{if(t>=30&&t<=37||t>=90&&t<=97)return 39;if(t>=40&&t<=47||t>=100&&t<=107)return 49;if(t===1||t===2)return 22;if(t===3)return 23;if(t===4)return 24;if(t===7)return 27;if(t===8)return 28;if(t===9)return 29;if(t===0)return 0},bi=t=>`${St}${Ci}${t}${ki}`,Si=t=>`${St}${Xt}${t}${Jt}`,Kt=(t,e,i)=>{let s=e[Symbol.iterator](),n=!1,r=!1,o=t.at(-1),a=o===void 0?0:P(o),l=s.next(),h=s.next(),f=0;for(;!l.done;){let p=l.value,g=P(p);a+g<=i?t[t.length-1]+=p:(t.push(p),a=0),(p===St||p===_i)&&(n=!0,r=e.startsWith(Xt,f+1)),n?r?p===Jt&&(n=!1,r=!1):p===ki&&(n=!1):(a+=g,a===i&&!h.done&&(t.push(""),a=0)),l=h,h=s.next(),f+=p.length}o=t.at(-1),!a&&o!==void 0&&o.length&&t.length>1&&(t[t.length-2]+=t.pop())},Hs=t=>{let e=t.split(" "),i=e.length;for(;i&&!P(e[i-1]);)i--;return i===e.length?t:e.slice(0,i).join(" ")+e.slice(i).join("")},Ws=(t,e,i={})=>{if(i.trim!==!1&&t.trim()==="")return"";let s="",n,r,o=t.split(" "),a=[""],l=0;for(let p=0;p<o.length;p++){let g=o[p];if(i.trim!==!1){let m=a.at(-1)??"",w=m.trimStart();m.length!==w.length&&(a[a.length-1]=w,l=P(w))}p!==0&&(l>=e&&(i.wordWrap===!1||i.trim===!1)&&(a.push(""),l=0),(l||i.trim===!1)&&(a[a.length-1]+=" ",l++));let $=P(g);if(i.hard&&$>e){let m=e-l,w=1+Math.floor(($-m-1)/e);Math.floor(($-1)/e)<w&&a.push(""),Kt(a,g,e),l=P(a.at(-1)??"");continue}if(l+$>e&&l&&$){if(i.wordWrap===!1&&l<e){Kt(a,g,e),l=P(a.at(-1)??"");continue}a.push(""),l=0}if(l+$>e&&i.wordWrap===!1){Kt(a,g,e),l=P(a.at(-1)??"");continue}a[a.length-1]+=g,l+=$}i.trim!==!1&&(a=a.map(p=>Hs(p)));let h=a.join(`
5
+ `),f=!1;for(let p=0;p<h.length;p++){let g=h[p];if(s+=g,f)f=!1;else if(f=g>="\uD800"&&g<="\uDBFF",f)continue;if(g===St||g===_i){wi.lastIndex=p+1;let m=wi.exec(h)?.groups;if(m?.code!==void 0){let w=Number.parseFloat(m.code);n=w===Vs?void 0:w}else m?.uri!==void 0&&(r=m.uri.length===0?void 0:m.uri)}if(h[p+1]===`
6
+ `){r&&(s+=Si(""));let $=n?Ii(n):void 0;n&&$&&(s+=bi($))}else g===`
7
+ `&&(n&&Ii(n)&&(s+=bi(n)),r&&(s+=Si(r)))}return s},Bs=/\r?\n/;function J(t,e,i){return String(t).normalize().split(Bs).map(s=>Ws(s,e,i)).join(`
8
+ `)}var N=lt(zt(),1);import{ReadStream as Ei}from"node:tty";function tt(t,e,i){if(!i.some(o=>!o.disabled))return t;let s=t+e,n=Math.max(i.length-1,0),r=s<0?n:s>n?0:s;return i[r]?.disabled?tt(r,e<0?-1:1,i):r}var qs=["up","down","left","right","space","enter","cancel"],zs=["January","February","March","April","May","June","July","August","September","October","November","December"],T={actions:new Set(qs),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,accessible:void 0,date:{monthNames:[...zs],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(t,e)=>`There are only ${t} days in ${e}`,afterMin:t=>`Date must be on or after ${t.toISOString().slice(0,10)}`,beforeMax:t=>`Date must be on or before ${t.toISOString().slice(0,10)}`}}};function Ys(t){if(t!==void 0)return t;if(T.accessible!==void 0)return T.accessible;let e=process.env.ACCESSIBLE;return e!==void 0&&e!==""&&e!=="0"&&e!=="false"}function Qt(t,e){if(typeof t=="string")return T.aliases.get(t)===e;for(let i of t)if(i!==void 0&&Qt(i,e))return!0;return!1}function Zs(t,e){if(t===e)return;let i=t.split(`
9
+ `),s=e.split(`
10
+ `),n=Math.max(i.length,s.length),r=[];for(let o=0;o<n;o++)i[o]!==s[o]&&r.push(o);return{lines:r,numLinesBefore:i.length,numLinesAfter:s.length,numLines:n}}var Qs=globalThis.process.platform.startsWith("win"),Ct=Symbol("clack:cancel");function rt(t){return t===Ct}function _t(t,e){let i=t;i.isTTY&&i.setRawMode(e)}function Ai({input:t=xi,output:e=Zt,overwrite:i=!0,hideCursor:s=!0}={}){let n=Y.createInterface({input:t,output:e,prompt:"",tabSize:1});Y.emitKeypressEvents(t,n),t instanceof Ei&&t.isTTY&&t.setRawMode(!0);let r=(o,{name:a,sequence:l})=>{let h=String(o);if(Qt([h,a,l],"cancel")){s&&e.write(N.cursor.show),process.exit(0);return}if(!i)return;Y.moveCursor(e,a==="return"?0:-1,a==="return"?-1:0,()=>{Y.clearLine(e,1,()=>{t.once("keypress",r)})})};return s&&e.write(N.cursor.hide),t.once("keypress",r),()=>{t.off("keypress",r),s&&e.write(N.cursor.show),t instanceof Ei&&t.isTTY&&!Qs&&t.setRawMode(!1),n.terminal=!1,n.close()}}var dt=t=>"columns"in t&&typeof t.columns=="number"?t.columns:80,te=t=>"rows"in t&&typeof t.rows=="number"?t.rows:20;function Z(t,e,i,s=i,n=i,r){let o=dt(t??Zt);return J(e,o-i.length,{hard:!0,trim:!1}).split(`
11
+ `).map((a,l,h)=>{let f=r?r(a,l):a;return l===0?`${s}${f}`:l===h.length-1?`${n}${f}`:`${i}${f}`}).join(`
12
+ `)}function Ri(t,e){if("~standard"in t){let i=t["~standard"].validate(e);return i instanceof Promise?i.then(s=>s.issues?.at(0)?.message):i.issues?.at(0)?.message}return t(e)}var et=class{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";get accessible(){return Ys(this.opts.accessible)}constructor(e,i=!0){let{input:s=xi,output:n=Zt,render:r,signal:o,...a}=e;this.opts=a,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=r.bind(this),this._track=i,this._abortSignal=o,this.input=s,this.output=n}unsubscribe(){this._subscribers.clear()}setSubscriber(e,i){let s=this._subscribers.get(e)??[];s.push(i),this._subscribers.set(e,s)}on(e,i){this.setSubscriber(e,{cb:i})}once(e,i){this.setSubscriber(e,{cb:i,once:!0})}emit(e,...i){let s=this._subscribers.get(e)??[],n=[];for(let r of s)r.cb(...i),r.once&&n.push(()=>s.splice(s.indexOf(r),1));for(let r of n)r()}prompt(){return new Promise(e=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),e(Ct);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=Xs.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on("keypress",this.onKeypress),_t(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(N.cursor.show),this.output.off("resize",this.render),_t(this.input,!1),e(this.value)}),this.once("cancel",()=>{this.output.write(N.cursor.show),this.output.off("resize",this.render),_t(this.input,!1),e(Ct)})})}_isActionKey(e,i){return e===" "}_shouldSubmit(e,i){return!0}_setValue(e){this.value=e,this.emit("value",this.value)}_setUserInput(e,i){this.userInput=e??"",this.emit("userInput",this.userInput),i&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}async onKeypress(e,i){if(this.state!=="validating"){if(this._track&&i.name!=="return"&&(i.name&&this._isActionKey(e,i)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),i?.name&&(!this._track&&T.aliases.has(i.name)&&this.emit("cursor",T.aliases.get(i.name)),T.actions.has(i.name)&&this.emit("cursor",i.name)),e&&(e.toLowerCase()==="y"||e.toLowerCase()==="n")&&this.emit("confirm",e.toLowerCase()==="y"),this.emit("key",e,i),i?.name==="return"&&this._shouldSubmit(e,i)){if(this.opts.validate){let s=Ri(this.opts.validate,this.value),n;s instanceof Promise?(this.state="validating",this.render(),n=await s):n=s,n&&(this.error=n instanceof Error?n.message:n,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}Qt([e,i?.name,i?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
13
+ `),_t(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=J(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
14
+ `).length-1;this.output.write(N.cursor.move(-999,e*-1))}render(){let e=J(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(N.cursor.hide);else{let i=Zs(this._prevFrame,e),s=te(this.output);if(this.restoreCursor(),i){let n=Math.max(0,i.numLinesAfter-s),r=Math.max(0,i.numLinesBefore-s),o=i.lines.find(a=>a>=n);if(o===void 0){this._prevFrame=e;return}if(i.lines.length===1){this.output.write(N.cursor.move(0,o-r)),this.output.write(N.erase.lines(1));let a=e.split(`
15
+ `);this.output.write(a[o]),this._prevFrame=e,this.output.write(N.cursor.move(0,a.length-o-1));return}else if(i.lines.length>1){if(n<r)o=n;else{let l=o-r;l>0&&this.output.write(N.cursor.move(0,l))}this.output.write(N.erase.down());let a=e.split(`
16
+ `).slice(o);this.output.write(a.join(`
17
+ `)),this._prevFrame=e;return}}this.output.write(N.erase.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}};var kt=class extends et{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(e){super(e,!1),this.value=!!e.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",i=>{this.output.write(N.cursor.move(0,-1)),this.value=i,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}};var Tt=class extends et{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter(e=>e.disabled!==!0)}toggleAll(){let e=this._enabledOptions,i=this.value!==void 0&&this.value.length===e.length;this.value=i?[]:e.map(s=>s.value)}toggleInvert(){let e=this.value;if(!e)return;let i=this._enabledOptions.filter(s=>!e.includes(s.value));this.value=i.map(s=>s.value)}toggleValue(){this.value===void 0&&(this.value=[]);let e=this.value.includes(this._value);this.value=e?this.value.filter(i=>i!==this._value):[...this.value,this._value]}constructor(e){super(e,!1),this.options=e.options,this.value=[...e.initialValues??[]];let i=Math.max(this.options.findIndex(({value:s})=>s===e.cursorAt),0);this.cursor=this.options[i]?.disabled?tt(i,1,this.options):i,this.on("key",(s,n)=>{n.name==="a"&&this.toggleAll(),n.name==="i"&&this.toggleInvert()}),this.on("cursor",s=>{switch(s){case"left":case"up":this.cursor=tt(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=tt(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}},Oi=class extends et{_mask="\u2022";get cursor(){return this._cursor}get masked(){return this.userInput.replaceAll(/./g,this._mask)}get userInputWithCursor(){if(this.state==="submit"||this.state==="cancel")return this.masked;let e=this.userInput;if(this.cursor>=e.length)return`${this.masked}${Yt(["inverse","hidden"],"_")}`;let i=this.masked,s=i.slice(0,this.cursor),n=i.slice(this.cursor,this.cursor+1),r=i.slice(this.cursor+1);return`${s}${Yt("inverse",n)}${r}`}clear(){this._clearUserInput()}constructor({mask:e,...i}){super(i),this._mask=e??"\u2022",this.on("userInput",s=>{this._setValue(s)}),this.on("finalize",()=>{this.value===void 0&&(this.value="")})}},Di=class extends et{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){let e=this._selectedValue;this.value=e===void 0?void 0:e.value}constructor(e){super(e,!1),this.options=e.options;let i=this.options.findIndex(({value:n})=>n===e.initialValue),s=i===-1?0:i;this.cursor=this.options[s]?.disabled?tt(s,1,this.options):s,this.changeValue(),this.on("cursor",n=>{switch(n){case"left":case"up":this.cursor=tt(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=tt(this.cursor,1,this.options);break}this.changeValue()})}};var Et=class extends et{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${this.userInput}\u2588`;let i=e.slice(0,this.cursor),s=e.slice(this.cursor,this.cursor+1),n=e.slice(this.cursor+1);return`${i}${Yt("inverse",s)}${n}`}get cursor(){return this._cursor}constructor(e){super({...e,initialUserInput:e.initialUserInput??e.initialValue}),this.on("userInput",i=>{this._setValue(i)}),this.on("finalize",()=>{this.value||(this.value=e.defaultValue),this.value===void 0&&(this.value="")})}};import{styleText as u,stripVTControlCharacters as oo}from"node:util";import G from"node:process";var mt=lt(zt(),1);function tn(){return G.platform!=="win32"?G.env.TERM!=="linux":!!G.env.CI||!!G.env.WT_SESSION||!!G.env.TERMINUS_SUBLIME||G.env.ConEmuTask==="{cmd::Cmder}"||G.env.TERM_PROGRAM==="Terminus-Sublime"||G.env.TERM_PROGRAM==="vscode"||G.env.TERM==="xterm-256color"||G.env.TERM==="alacritty"||G.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var ee=tn(),en=()=>process.env.CI==="true";var I=(t,e)=>ee?t:e,Ni=I("\u25C6","*"),Li=I("\u25A0","x"),Ui=I("\u25B2","x"),Rt=I("\u25C7","o"),sn=I("\u250C","T"),y=I("\u2502","|"),H=I("\u2514","\u2014"),lo=I("\u2510","T"),ho=I("\u2518","\u2014"),ie=I("\u25CF",">"),At=I("\u25CB"," "),nn=I("\u25FB","[\u2022]"),Fi=I("\u25FC","[+]"),Pi=I("\u25FB","[ ]"),rn=I("\u25AA","\u2022"),Mi=I("\u2500","-"),on=I("\u256E","+"),an=I("\u251C","+"),cn=I("\u256F","+"),un=I("\u2570","+"),po=I("\u256D","+"),ln=I("\u25CF","\u2022"),hn=I("\u25C6","*"),dn=I("\u25B2","!"),pn=I("\u25A0","x"),ft=t=>{switch(t){case"initial":case"active":return u("cyan",Ni);case"cancel":return u("red",Li);case"error":return u("yellow",Ui);case"submit":return u("green",Rt);case"validating":return u("dim",Ni)}},Vi=t=>{switch(t){case"initial":case"active":return u("cyan",y);case"cancel":return u("red",y);case"error":return u("yellow",y);case"submit":return u("green",y)}};function Gi(t,e){let i=[`${e?`${u("cyan",y)} `:""}${t.join(" \u2022 ")}`];return e&&i.push(u("cyan",H)),i}var ji=(t,e,i,s,n,r=!1)=>{let o=e,a=0;if(r)for(let l=s-1;l>=i;l--){let h=t[l];if(h&&(o-=h.length),a++,o<=n)break}else for(let l=i;l<s;l++){let h=t[l];if(h&&(o-=h.length),a++,o<=n)break}return{lineCount:o,removals:a}},se=({cursor:t,options:e,style:i,output:s=process.stdout,maxItems:n=Number.POSITIVE_INFINITY,columnPadding:r=0,rowPadding:o=4})=>{let a=dt(s)-r,l=te(s),h=u("dim","..."),f=Math.max(l-o,0),p=Math.max(Math.min(n,f),5),g=0;t>=p-3&&(g=Math.max(Math.min(t-p+3,e.length-p),0));let $=p<e.length&&g>0,m=p<e.length&&g+p<e.length,w=Math.min(g+p,e.length),C=[],O=0;$&&O++,m&&O++;let M=g+($?1:0),A=w-(m?1:0);for(let S=M;S<A;S++){let R=e[S],k=R?i(R,S===t):"",x=J(k,a,{hard:!0,trim:!1}).split(`
18
+ `);C.push(x),O+=x.length}if(O>f){let S=0,R=0,k=O,x=t-M,D=f,K=()=>ji(C,k,0,x,D),F=()=>ji(C,k,x+1,C.length,D,!0);$?({lineCount:k,removals:S}=K(),k>D&&(m||(D-=1),{lineCount:k,removals:R}=F())):(m||(D-=1),{lineCount:k,removals:R}=F(),k>D&&(D-=1,{lineCount:k,removals:S}=K())),S>0&&($=!0,C.splice(0,S)),R>0&&(m=!0,C.splice(C.length-R,R))}let j=[];$&&j.push(h);for(let S of C)for(let R of S)j.push(R);return m&&j.push(h),j};var Q=t=>{let e=t.active??"Yes",i=t.inactive??"No";return new kt({active:e,inactive:i,signal:t.signal,input:t.input,output:t.output,initialValue:t.initialValue??!0,render(){let s=t.withGuide??T.withGuide,n=`${ft(this.state)} `,r=s?`${u("gray",y)} `:"",o=Z(t.output,t.message,r,n),a=`${s?`${u("gray",y)}
19
+ `:""}${o}
20
+ `,l=this.value?e:i;switch(this.state){case"submit":{let h=s?`${u("gray",y)} `:"";return`${a}${h}${u("dim",l)}`}case"cancel":{let h=s?`${u("gray",y)} `:"";return`${a}${h}${u(["strikethrough","dim"],l)}${s?`
21
+ ${u("gray",y)}`:""}`}default:{let h=s?`${u("cyan",y)} `:"",f=s?u("cyan",H):"";return`${a}${h}${this.value?`${u("green",ie)} ${e}`:`${u("dim",At)} ${u("dim",e)}`}${t.vertical?s?`
22
+ ${u("cyan",y)} `:`
23
+ `:` ${u("dim","/")} `}${this.value?`${u("dim",At)} ${u("dim",i)}`:`${u("green",ie)} ${i}`}
24
+ ${f}
25
+ `}}}}).prompt()};var mn=[`${u("dim","\u2191/\u2193")} to navigate`,`${u("dim","Space:")} select`,`${u("dim","Enter:")} confirm`],pt=(t,e)=>t.split(`
26
+ `).map(i=>e(i)).join(`
27
+ `),Ot=t=>{let e=(n,r)=>{let o=n.label??String(n.value);return r==="disabled"?`${u("gray",Pi)} ${pt(o,a=>u(["strikethrough","gray"],a))}${n.hint?` ${u("dim",`(${n.hint??"disabled"})`)}`:""}`:r==="active"?`${u("cyan",nn)} ${o}${n.hint?` ${u("dim",`(${n.hint})`)}`:""}`:r==="selected"?`${u("green",Fi)} ${pt(o,a=>u("dim",a))}${n.hint?` ${u("dim",`(${n.hint})`)}`:""}`:r==="cancelled"?`${pt(o,a=>u(["strikethrough","dim"],a))}`:r==="active-selected"?`${u("green",Fi)} ${o}${n.hint?` ${u("dim",`(${n.hint})`)}`:""}`:r==="submitted"?`${pt(o,a=>u("dim",a))}`:`${u("dim",Pi)} ${pt(o,a=>u("dim",a))}`},i=t.required??!0,s=t.showInstructions??!0;return new Tt({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValues:t.initialValues,required:i,cursorAt:t.cursorAt,validate(n){if(i&&(n===void 0||n.length===0))return`Please select at least one option.
28
+ ${u("reset",u("dim",`Press ${u(["gray","bgWhite","inverse"]," space ")} to select, ${u("gray",u("bgWhite",u("inverse"," enter ")))} to submit`))}`},render(){let n=t.withGuide??T.withGuide,r=Z(t.output,t.message,n?`${Vi(this.state)} `:"",`${ft(this.state)} `),o=`${n?`${u("gray",y)}
29
+ `:""}${r}
30
+ `,a=this.value??[],l=(h,f)=>{if(h.disabled)return e(h,"disabled");let p=a.includes(h.value);return f&&p?e(h,"active-selected"):p?e(h,"selected"):e(h,f?"active":"inactive")};switch(this.state){case"submit":{let h=this.options.filter(({value:p})=>a.includes(p)).map(p=>e(p,"submitted")).join(u("dim",", "))||u("dim","none"),f=Z(t.output,h,n?`${u("gray",y)} `:"");return`${o}${f}`}case"cancel":{let h=this.options.filter(({value:p})=>a.includes(p)).map(p=>e(p,"cancelled")).join(u("dim",", "));if(h.trim()==="")return`${o}${u("gray",y)}`;let f=Z(t.output,h,n?`${u("gray",y)} `:"");return`${o}${f}${n?`
31
+ ${u("gray",y)}`:""}`}case"error":{let h=n?`${u("yellow",y)} `:"",f=this.error.split(`
32
+ `).map(($,m)=>m===0?`${n?`${u("yellow",H)} `:""}${u("yellow",$)}`:` ${$}`).join(`
33
+ `),p=o.split(`
34
+ `).length,g=f.split(`
35
+ `).length+1;return`${o}${h}${se({output:t.output,options:this.options,cursor:this.cursor,maxItems:t.maxItems,columnPadding:h.length,rowPadding:p+g,style:l}).join(`
36
+ ${h}`)}
37
+ ${f}
38
+ `}default:{let h=n?`${u("cyan",y)} `:"",f=o.split(`
39
+ `).length,p=s?Gi(mn,n):n?[u("cyan",H)]:[],g=p.join(`
40
+ `),$=p.length+1;return`${o}${h}${se({output:t.output,options:this.options,cursor:this.cursor,maxItems:t.maxItems,columnPadding:h.length,rowPadding:f+$,style:l}).join(`
41
+ ${h}`)}
42
+ ${g}
43
+ `}}}}).prompt()};var v={message:(t=[],{symbol:e=u("gray",y),secondarySymbol:i=u("gray",y),output:s=process.stdout,spacing:n=1,withGuide:r}={})=>{let o=[],a=r??T.withGuide,l=a?i:"",h=a?`${e} `:"",f=a?`${i} `:"";for(let g=0;g<n;g++)o.push(l);let p=Array.isArray(t)?t:t.split(`
44
+ `);if(p.length>0){let[g,...$]=p;g.length>0?o.push(`${h}${g}`):o.push(a?e:"");for(let m of $)m.length>0?o.push(`${f}${m}`):o.push(a?i:"")}s.write(`${o.join(`
45
+ `)}
46
+ `)},info:(t,e)=>{v.message(t,{...e,symbol:u("blue",ln)})},success:(t,e)=>{v.message(t,{...e,symbol:u("green",hn)})},step:(t,e)=>{v.message(t,{...e,symbol:u("green",Rt)})},warn:(t,e)=>{v.message(t,{...e,symbol:u("yellow",dn)})},warning:(t,e)=>{v.warn(t,e)},error:(t,e)=>{v.message(t,{...e,symbol:u("red",pn)})}},Hi=(t="",e)=>{let i=e?.output??process.stdout,s=e?.withGuide??T.withGuide?`${u("gray",H)} `:"";i.write(`${s}${u("red",t)}
47
+
48
+ `)},Wi=(t="",e)=>{let i=e?.output??process.stdout,s=e?.withGuide??T.withGuide?`${u("gray",sn)} `:"";i.write(`${s}${t}
49
+ `)},Bi=(t="",e)=>{let i=e?.output??process.stdout,s=e?.withGuide??T.withGuide?`${u("gray",y)}
50
+ ${u("gray",H)} `:"";i.write(`${s}${t}
51
+
52
+ `)};var fn=t=>t,gn=(t,e,i)=>{let s={hard:!0,trim:!1},n=J(t,e,s).split(`
53
+ `),r=n.reduce((l,h)=>Math.max(P(h),l),0),o=n.map(i).reduce((l,h)=>Math.max(P(h),l),0),a=e-(o-r);return J(t,a,s)},gt=(t="",e="",i)=>{let s=i?.output??G.stdout,n=i?.withGuide??T.withGuide,r=i?.format??fn,o=["",...gn(t,dt(s)-6,r).split(`
54
+ `).map(r),""],a=P(e),l=Math.max(o.reduce((g,$)=>{let m=P($);return m>g?m:g},0),a)+2,h=o.map(g=>`${u("gray",y)} ${g}${" ".repeat(l-P(g))}${u("gray",y)}`).join(`
55
+ `),f=n?`${u("gray",y)}
56
+ `:"",p=n?an:un;s.write(`${f}${u("green",Rt)} ${u("reset",e)} ${u("gray",Mi.repeat(Math.max(l-a-1,1))+on)}
57
+ ${h}
58
+ ${u("gray",p+Mi.repeat(l+2)+cn)}
59
+ `)},it=t=>new Oi({validate:t.validate,mask:t.mask??rn,signal:t.signal,input:t.input,output:t.output,render(){let e=t.withGuide??T.withGuide,i=`${e?`${u("gray",y)}
60
+ `:""}${ft(this.state)} ${t.message}
61
+ `,s=this.userInputWithCursor,n=this.masked;switch(this.state){case"error":{let r=e?`${u("yellow",y)} `:"",o=e?`${u("yellow",H)} `:"",a=n??"";return t.clearOnError&&this.clear(),`${i.trim()}
62
+ ${r}${a}
63
+ ${o}${u("yellow",this.error)}
64
+ `}case"submit":{let r=e?`${u("gray",y)} `:"",o=n?u("dim",n):"";return`${i}${r}${o}`}case"cancel":{let r=e?`${u("gray",y)} `:"",o=n?u(["strikethrough","dim"],n):"";return`${i}${r}${o}${n&&e?`
65
+ ${u("gray",y)}`:""}`}default:{let r=e?`${u("cyan",y)} `:"",o=e?u("cyan",H):"";return`${i}${r}${s}
66
+ ${o}
67
+ `}}}}).prompt();var $n=t=>u("magenta",t),Ki=({indicator:t="dots",onCancel:e,output:i=process.stdout,cancelMessage:s,errorMessage:n,frames:r=ee?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:o=ee?80:120,signal:a,...l}={})=>{let h=en(),f,p,g=!1,$=!1,m="",w,C=performance.now(),O=dt(i),M=l?.styleFrame??$n,A=_=>{let V=_>1?n??T.messages.error:s??T.messages.cancel;$=_===1,g&&(ut(V,_),$&&typeof e=="function"&&e())},j=()=>A(2),S=()=>A(1),R=()=>{process.on("uncaughtExceptionMonitor",j),process.on("unhandledRejection",j),process.on("SIGINT",S),process.on("SIGTERM",S),process.on("exit",A),a&&a.addEventListener("abort",S)},k=()=>{process.removeListener("uncaughtExceptionMonitor",j),process.removeListener("unhandledRejection",j),process.removeListener("SIGINT",S),process.removeListener("SIGTERM",S),process.removeListener("exit",A),a&&a.removeEventListener("abort",S)},x=()=>{if(w===void 0)return;h&&i.write(`
68
+ `);let _=J(w,O,{hard:!0,trim:!1}).split(`
69
+ `);_.length>1&&i.write(mt.cursor.up(_.length-1)),i.write(mt.cursor.to(0)),i.write(mt.erase.down())},D=_=>_.replace(/\.+$/,""),K=_=>{let V=(performance.now()-_)/1e3,X=Math.floor(V/60),q=Math.floor(V%60);return X>0?`[${X}m ${q}s]`:`[${q}s]`},F=l.withGuide??T.withGuide,vt=(_="")=>{g=!0,f=Ai({output:i}),m=D(_),C=performance.now(),F&&i.write(`${u("gray",y)}
70
+ `);let V=0,X=0;R(),p=setInterval(()=>{if(h&&m===w)return;x(),w=m;let q=M(r[V]),wt;if(h)wt=`${q} ${m}...`;else if(t==="timer")wt=`${q} ${m} ${K(C)}`;else{let Rs=".".repeat(Math.floor(X)).slice(0,3);wt=`${q} ${m}${Rs}`}let As=J(wt,O,{hard:!0,trim:!1});i.write(As),V=V+1<r.length?V+1:0,X=X<4?X+.125:0},o)},ut=(_="",V=0,X=!1)=>{if(!g)return;g=!1,clearInterval(p),x();let q=V===0?u("green",Rt):V===1?u("red",Li):u("red",Ui);m=_??m,X||(t==="timer"?i.write(`${q} ${m} ${K(C)}
71
+ `):i.write(`${q} ${m}
72
+ `)),k(),f()};return{start:vt,stop:(_="")=>ut(_,0),message:(_="")=>{m=D(_??m)},cancel:(_="")=>ut(_,1),error:(_="")=>ut(_,2),clear:()=>ut("",0,!0),get isCancelled(){return $}}},mo={light:I("\u2500","-"),heavy:I("\u2501","="),block:I("\u2588","#")};var yn=[`${u("dim","\u2191/\u2193")} to navigate`,`${u("dim","Enter:")} confirm`],xt=(t,e)=>t.includes(`
73
+ `)?t.split(`
74
+ `).map(i=>e(i)).join(`
75
+ `):e(t),st=t=>{let e=(s,n)=>{if(s===void 0)return"";let r=s.label??String(s.value);switch(n){case"disabled":return`${u("gray",At)} ${xt(r,o=>u("gray",o))}${s.hint?` ${u("dim",`(${s.hint??"disabled"})`)}`:""}`;case"selected":return`${xt(r,o=>u("dim",o))}`;case"active":return`${u("green",ie)} ${r}${s.hint?` ${u("dim",`(${s.hint})`)}`:""}`;case"cancelled":return`${xt(r,o=>u(["strikethrough","dim"],o))}`;default:return`${u("dim",At)} ${xt(r,o=>u("dim",o))}`}},i=t.showInstructions??!0;return new Di({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValue:t.initialValue,render(){let s=t.withGuide??T.withGuide,n=`${ft(this.state)} `,r=`${Vi(this.state)} `,o=Z(t.output,t.message,r,n),a=`${s?`${u("gray",y)}
76
+ `:""}${o}
77
+ `;switch(this.state){case"submit":{let l=s?`${u("gray",y)} `:"",h=Z(t.output,e(this.options[this.cursor],"selected"),l);return`${a}${h}`}case"cancel":{let l=s?`${u("gray",y)} `:"",h=Z(t.output,e(this.options[this.cursor],"cancelled"),l);return`${a}${h}${s?`
78
+ ${u("gray",y)}`:""}`}default:{let l=s?`${u("cyan",y)} `:"",h=a.split(`
79
+ `).length,f=i?Gi(yn,s):s?[u("cyan",H)]:[],p=f.join(`
80
+ `),g=f.length+1;return`${a}${l}${se({output:t.output,cursor:this.cursor,options:this.options,maxItems:t.maxItems,columnPadding:l.length,rowPadding:h+g,style:($,m)=>e($,$.disabled?"disabled":m?"active":"inactive")}).join(`
81
+ ${l}`)}
82
+ ${p}
83
+ `}}}}).prompt()};var fo=`${u("gray",y)} `;var ot=t=>new Et({validate:t.validate,placeholder:t.placeholder,defaultValue:t.defaultValue,initialValue:t.initialValue,output:t.output,signal:t.signal,input:t.input,render(){let e=t?.withGuide??T.withGuide,i=`${`${e?`${u("gray",y)}
84
+ `:""}${ft(this.state)} `}${t.message}
85
+ `,s=t.placeholder&&t.placeholder.length>0?u("inverse",t.placeholder[0])+u("dim",t.placeholder.slice(1)):u(["inverse","hidden"],"_"),n=this.userInput?this.userInputWithCursor:s,r=this.value??"";switch(this.state){case"validating":{let o=e?`${u("cyan",y)} `:"",a=e?u("cyan",H):"",l=u("dim",n),h=u("dim","Validating...");return`${i}${o}${l}
86
+ ${a} ${h}
87
+ `}case"error":{let o=this.error?` ${u("yellow",this.error)}`:"",a=e?`${u("yellow",y)} `:"",l=e?u("yellow",H):"";return`${i.trim()}
88
+ ${a}${n}
89
+ ${l}${o}
90
+ `}case"submit":{let o=r?`${e?" ":""}${u("dim",r)}`:"",a=e?u("gray",y):"";return`${i}${a}${o}`}case"cancel":{let o=r?` ${u(["strikethrough","dim"],r)}`:"",a=e?u("gray",y):"";return`${i}${a}${o}${r.trim()?`
91
+ ${a}`:""}`}default:{let o=e?`${u("cyan",y)} `:"",a=e?u("cyan",H):"";return`${i}${o}${n}
92
+ ${a}
93
+ `}}}}).prompt();var Xi=Fe;function qi(){return process.platform==="win32"?"https://git-scm.com/download/win (Git for Windows, including Git Bash)":process.platform==="darwin"?"xcode-select --install (or brew install git if you use Homebrew)":"Install Git via your package manager or https://git-scm.com/downloads"}function ne(){return Xi()?!0:process.platform!=="win32"?(v.info(c("init.git.optional")),!1):(v.warn(c("init.git.required")),v.info(c("init.git.manualHint",{hint:qi()})),!1)}function zi(t){if(!vn(Ji.join(t,".git")))try{wn("git init",{cwd:t,stdio:"pipe"})}catch(e){v.warn(c("init.git.initFailed",{message:e instanceof Error?e.message:String(e)}))}}import{randomUUID as Sn}from"node:crypto";import{execSync as In}from"node:child_process";function re(t){if(rt(t))throw new b(c("init.auth.cancelled"),130);return t}function bn(t){let e=i=>process.stderr.write(`${i}
94
+ `);if(t.kind==="auth_url"){e(c("init.auth.openBrowser",{url:t.url}));return}if(t.kind==="device_code"){e(c("init.auth.deviceCode",{url:t.verificationUri,code:t.userCode}));return}if(e(t.message),t.kind==="info")for(let i of t.links??[])e(i.url)}function Yi(){let t=process.stderr;return{async select(e,i,s){if(!i.length)throw new b(c("init.auth.noCapabilities"));return re(await st({message:e,options:i,output:t,signal:s}))},async secret(e,i){return re(await it({message:e,output:t,signal:i}))},async confirm(e){return re(await Q({message:e,initialValue:!1,output:t}))},notify:bn}}async function Zi(t,e){let i=e?null:await import("./init-A6GY656J.js"),s=e??{installed:()=>i.isBackendInstalled("claude"),install:()=>In(i.getInstallCommand("claude"),{stdio:"pipe",timeout:12e4})};if(s.installed())return!0;if(!await t.confirm(c("init.auth.installPrompt")))return!1;try{s.install()}catch{throw new b(c("init.auth.installFailed"))}if(!s.installed())throw new b(c("init.auth.pathMissing"));return!0}var b=class extends Error{exitCode;constructor(e,i=1){super(e),this.exitCode=i}};function _n(){return di({name:"cortex auth login",description:c("init.auth.help"),usage:"cortex auth login [--backend pi|claude] [--provider ID] [--auth-type oauth|api_key]",options:[{flag:"--backend pi|claude",description:c("init.auth.backendOption")},{flag:"--provider ID",description:c("init.auth.providerOption")},{flag:"--auth-type oauth|api_key",description:c("init.auth.typeOption")},{flag:"--help, -h",description:c("cmd.auth.cli.helpDescription")}],examples:[{description:c("init.auth.exampleProvider"),command:"cortex auth login"},{description:c("init.auth.exampleClaude"),command:"cortex auth login --backend claude --provider anthropic --auth-type oauth"}],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")}})}function Cn(t){let e={},i={"--backend":"backend","--provider":"provider","--auth-type":"authType"};for(let s=0;s<t.length;s+=2){let n=i[t[s]];if(!n||!t[s+1]||t[s+1].startsWith("--")||e[n])throw new b(c("init.auth.invalidOptions"));e[n]=t[s+1]}if(e.backend&&!["pi","claude"].includes(e.backend))throw new b(c("init.auth.invalidBackend"));if(e.authType&&!["oauth","api_key"].includes(e.authType))throw new b(c("init.auth.invalidType"));return e}async function kn(t,e){let i=t.backend??await e.ui.select(c("init.auth.backend"),[{value:"pi",label:c("init.auth.bundled")},{value:"claude",label:"Claude Code"}]),n=(await e.readStatus()).accounts.filter(l=>l.backend===i&&l.capabilities.length),r=t.provider??await e.ui.select(c("init.auth.provider"),n.map(l=>({value:l.provider,label:`${l.label} (${c(`cmd.auth.state.${l.state}`)})`}))),o=n.find(l=>l.provider===r);if(!o)throw new b(c("init.auth.unavailable"));let a=t.authType??await e.ui.select(c("init.auth.type"),o.capabilities.map(l=>({value:l,label:c(`init.auth.${l}`)})));if(!o.capabilities.includes(a))throw new b(c("init.auth.unsupported",{values:o.capabilities.join(", ")}));if(i==="claude"&&!await e.ensureClaude())throw new b(c("init.auth.installDeclined"),130);return{backend:i,provider:r,authType:a,channel:"cli",sessionId:Sn()}}async function Tn(t,e,i){let s=t.pendingPrompt,n=AbortSignal.any([i,AbortSignal.timeout(Math.max(1,Date.parse(t.expiresAt)-Date.now()))]),r;try{r=s.kind==="select"?await e.ui.select(s.message,(s.options??[]).map(o=>({value:o.id,label:o.label})),n):await e.ui.secret(s.message,n),n.throwIfAborted()}catch(o){throw i.aborted?new b(c("init.auth.cancelled"),130):n.aborted?new b(c("init.auth.expired")):o}return e.service.respond(t.flowId,r)}async function En(t,e,i){let s=t,n="";for(;!["done","failed","cancelled"].includes(s.step);){if(i.aborted)throw new b(c("init.auth.cancelled"),130);if(Date.now()>=Date.parse(s.expiresAt))throw new b(c("init.auth.expired"));let r=JSON.stringify(s.notice);if(s.notice&&n!==r&&e.ui.notify(s.notice),n=r,s.pendingPrompt){s=await Tn(s,e,i);continue}await new Promise(a=>setTimeout(a,150));let o=e.service.getState(s.flowId);if(!o)throw new b(c("init.auth.expired"));s=o}return s}async function xn(t,e){let i=await kn(t,e),s=await e.service.start(i),n,r=new AbortController,o=()=>r.abort();process.once("SIGINT",o);try{n=await En(s,e,r.signal)}catch(l){throw await e.service.cancel(s.flowId).catch(()=>{}),r.signal.aborted?new b(c("init.auth.cancelled"),130):l}finally{process.removeListener("SIGINT",o)}if(n.step!=="done")throw new b(c(n.step==="cancelled"?"init.auth.cancelled":"init.auth.failed"),n.step==="cancelled"?130:1);let a=await e.sync(i.backend);return{exitCode:0,stderr:"",stdout:JSON.stringify({ok:!0,backend:i.backend,provider:i.provider,authType:i.authType,state:"done",sync:a,inferenceVerified:!1})}}function oe(){let t=Yi();return{tty:!!process.stdin.isTTY&&!!process.stderr.isTTY,readStatus:si,ui:t,service:ii,ensureClaude:()=>Zi(t),sync:async e=>{let i=await ui({backends:[e]});return{...i,reason:i.reason&&i.reason!=="no-routes"?"sync-failed":i.reason}}}}async function Qi(t,e=oe()){if(t.includes("--help")||t.includes("-h"))return{exitCode:0,stdout:_n(),stderr:""};let i=we({consoleToStderr:!0,files:!1,console:!1});try{let s=Cn(t);if(!e.tty)throw new b(c("init.auth.ttyRequired"));return await xn(s,e)}catch(s){let n=s instanceof b?s:new b(c("init.auth.failed"));return{exitCode:n.exitCode,stdout:JSON.stringify({ok:!1,state:n.exitCode===130?"cancelled":"failed"}),stderr:n.message}}finally{i()}}function ae(t){return[...new Set(t.accounts.filter(e=>[e,...e.credentials??[]].some(i=>i.state==="logged-in"||i.state==="expiring")).map(e=>e.backend))]}async function ts(t,e){try{let i=await t.readStatus();return e({step:"auth",state:ae(i).length?"configured":!i.piRuntime.available||i.accounts.some(s=>s.state==="unknown")?"unknown":"needs-login",inferenceVerified:!1,accounts:i.accounts.map(s=>({backend:s.backend,provider:s.provider,state:s.state})),runtimeAvailable:i.piRuntime.available}),i}catch{return e({step:"auth",state:"unknown",reason:"detection-failed",inferenceVerified:!1}),null}}async function es(t,e,i=oe()){let s=await ts(i,e);if(!t)return s?ae(s):[];for(;;){let n=s?ae(s):[];i.ui.notify({kind:"info",message:s?s.accounts.map(o=>`${o.backend} / ${o.label}: ${c(`cmd.auth.state.${o.state}`)}`).join(`
95
+ `):c("init.auth.detectionFailed")});let r=await i.ui.select(c("init.auth.setup"),[...n.length?[{value:"continue",label:c("init.auth.continue")}]:[],{value:"login",label:c("init.auth.login")},{value:"rescan",label:c("init.auth.rescan")},{value:"skip",label:c("init.auth.skip")}]);if(r==="skip")return[];if(r==="continue")return n;if(r==="login"){let o=await Qi([],{...i,sync:async()=>({configured:!1,routes:0,defaultSet:!1,favorites:[],reason:"deferred-to-init"})});if(o.exitCode===130)throw new b(c("init.cancel"),130);i.ui.notify({kind:"info",message:o.stderr||c("init.auth.saved")})}s=await ts(i,e)}}function E(t){rt(t)&&(Hi(c("init.cancel")),process.exit(0))}var An=new Set(["claude","plan","api","subscription"]),Rn={"pi-anthropic":"anthropic"};function Dt(t){return typeof t=="string"&&t.trim()?t.trim():void 0}function On(t){return t.backend==="claude"?"claude":t.backend==="pi"?Dt(t.provider):Dt(t.mode)}function ce(t){if(!t||typeof t!="object")return;let e=t,i=On(e),s=Dt(e.model);if(!i||!s)return;let n=e.backend==="claude"?Dt(e.connection):void 0;return n?{route:i,model:s,connection:n}:{route:i,model:s}}function ue(t){let e=t?.trim(),i=e?e.indexOf(":"):-1;if(!(!e||i<=0||i===e.length-1))return{route:e.substring(0,i).trim(),model:e.substring(i+1).trim()}}function ns(t){let e=(t?.trim()?t.split(","):[]).map(i=>ue(i.trim())).filter(i=>!!i);return e.length>0?e:void 0}function Dn(t,e){let i=He(t,{backend:"claude",provider:null})?.connections??[];return e.connection!==void 0?i.includes(e.connection)?e.connection:void 0:An.has(e.route)?null:i.includes(e.route)?e.route:void 0}function is(t,e){let i=We(t,e.model),s=Dn(t,e),n=Rn[e.route]??e.route,r=s!==void 0?i.find(o=>o.backend==="claude"):i.find(o=>o.backend==="pi"&&o.provider===n);if(!r)throw new Error(`(${e.route}, ${e.model}) is not among the models this host can run`);return{...r,thinking:null,connection:s??null}}function Nn(t,e){let i=e?.defaultChoice?is(t,e.defaultChoice):void 0,s=(e?.favorites??[]).map(n=>is(t,n));return{default:i,favorites:s}}function rs(t){return t.backend==="claude"?"claude":t.provider??"pi"}function Fn(t){return t.flatMap(e=>e.models.map(i=>({value:JSON.stringify([e.backend,e.provider,i]),label:`${rs(e)} / ${i}`})))}function ss(t){let[e,i,s]=JSON.parse(t);return{backend:e,provider:i,model:s}}async function Pn(t){if(!Bt(t)?.default)return!0;let e=await Q({message:c("init.modelSetup.overwritePrompt"),initialValue:!1});return E(e),e}async function Mn(t,e,i){if(!await Pn(i))return{};let s=Fn(t),n=e[0]?JSON.stringify([e[0].backend,e[0].provider,e[0].model]):s[0].value,r=await st({message:c("init.modelSetup.defaultPrompt"),options:s,initialValue:n});E(r);let o=await Ot({message:c("init.modelSetup.favoritesPrompt"),options:s,required:!1,initialValues:[r]});return E(o),{default:{...ss(r),thinking:null,connection:null},favorites:o.map(ss)}}function jn(t){let e=t.map(i=>{let s=i.models.slice(0,3).join(", ");return` ${rs(i)}: ${s}${i.models.length>3?", ...":""}`}).join(`
96
+ `);v.success(c("init.modelSetup.discovered",{count:t.length,summary:e}))}function Ln(t,e){v.success(c("init.modelSetup.modelsWritten",{path:e})),v.info(c("init.modelSetup.generatedModels",{names:t.favorites.map(i=>i.model).join(", "),default:t.default.model}))}async function le(t){let e=await Ge.reload(),i=e.routes.filter(o=>t.backends.includes(o.backend)&&o.models.length>0);if(i.length===0)return v.warn(c("init.modelSetup.noModels")),v.info(c("init.modelSetup.rerunHint")),!1;jn(i);let s=await ci(e,{backends:t.backends}),n=t.interactive?await Mn(i,s,t.configDir):Nn(e,t.answers),r=ri(oi(Bt(t.configDir),s).file,n);return Ln(r,ai(t.configDir,r)),!0}import{existsSync as Un,mkdirSync as Vn,readFileSync as as,writeFileSync as Gn}from"node:fs";import os from"node:path";function cs(t){if(t===void 0)return;let e=Se.safeParse(t);return e.success?e.data:void 0}function Hn(t){if(!Un(t))return{};let e=JSON.parse(as(t,"utf8"));if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must contain a JSON object`);return e}function us(t,e){let i=os.join(e.configDir,"settings.json"),s=Hn(i);Vn(e.configDir,{recursive:!0}),Gn(i,`${JSON.stringify({...s,telemetryEnabled:t.enabled},null,2)}
97
+ `,"utf8");let n=os.join(e.storeDir,"telemetry","install-id");t.installId&&!Wn(n)&&Ee(t.installId,n)}function Wn(t){try{return Te(as(t,"utf8").trim())}catch{return!1}}var ps=lt(jt(),1);import*as ds from"readline";import*as he from"path";function Nt(t,e,i){let s=`${e}=${i}`,n=t===""?[]:t.replace(/\n+$/,"").split(`
98
+ `),r=new RegExp(`^\\s*(?:export\\s+)?${e}\\s*=`),o=n.map(a=>r.test(a)).lastIndexOf(!0);if(o>=0){if(n[o]===s)return t;n[o]=s}else n.push(s);return n.join(`
99
+ `)+`
100
+ `}function at(t,e,i){return It(t,s=>Nt(s,e,i),{mode:384})}function ls(){return["Manage Feishu user-identity login (FEISHU_AUTH_MODE=user)","","Usage: cortex feishu <login|status|logout> [options]",""," login Authorize a Feishu user account via the OAuth device flow"," (prints a URL to open in any browser \u2014 no redirect URI needed)"," status Show the current auth mode and stored user-token state"," logout Delete the stored user token","","Options:"," --scope <scopes> Override the requested scopes (default: docx/sheets/bitable/wiki +"," space:document:delete \u2014 an all-\u514D\u5BA1 set; offline_access is always"," added). The review-gated drive:drive / drive:drive:readonly are"," avoided; add the latter via --scope for docx canonical URLs."," --manual Use the legacy authorize-URL + paste-the-code flow instead"," --redirect-uri <url> Redirect URI for --manual only (default: $FEISHU_REDIRECT_URI)"," --help, -h Show this help"].join(`
101
+ `)}function Bn(t){let e=ds.createInterface({input:process.stdin,output:process.stdout});return new Promise(i=>e.question(t,s=>{e.close(),i(s)}))}function hs(t,e){let i=t.indexOf(e);return i!==-1&&t[i+1]?t[i+1]:void 0}function Ft(t){return t?new Date(t).toISOString():"unknown"}async function ms(t,e={}){let i=t[0];if(!i||i==="--help"||i==="-h")return{exitCode:i?0:1,stdout:ls(),stderr:""};let s=e.env??process.env;e.loadDotenv!==!1&&!e.env&&ps.config({path:he.join(Lt,".env")});let n=e.tokenFile??Je(),r=s.FEISHU_DOMAIN||void 0;switch(i){case"login":{let o=s.FEISHU_APP_ID,a=s.FEISHU_APP_SECRET;if(!o||!a)return{exitCode:1,stdout:"",stderr:"Missing FEISHU_APP_ID / FEISHU_APP_SECRET. Run `cortex init` or set them in the .env first.\n"};let l=hs(t,"--scope")??s.FEISHU_USER_SCOPE??Ke,h=r==="lark"?"lark (larksuite.com)":"feishu (feishu.cn)",f=e.envFile??he.join(Lt,".env"),p=async()=>{if(e.loadDotenv===!1)return!1;try{return await at(f,"FEISHU_AUTH_MODE","user"),!0}catch{return!1}},g=(m,w)=>({exitCode:0,stderr:"",stdout:["","Logged in as Feishu user.",` region: ${h}`,` scope: ${m.scope??"(default)"}`,` access expires: ${Ft(m.access_expires_at)}`,` refresh expires:${Ft(m.refresh_expires_at)}`,` token file: ${n}`,"",w?`FEISHU_AUTH_MODE=user written to ${f} \u2014 restart Cortex for doc tools to use this identity.`:"Set FEISHU_AUTH_MODE=user in your .env and restart Cortex for doc tools to use this identity.",""].join(`
102
+ `)});if(t.includes("--manual")){let m=hs(t,"--redirect-uri")??s.FEISHU_REDIRECT_URI;if(!m)return{exitCode:1,stdout:"",stderr:`--manual needs a redirect URI. Set FEISHU_REDIRECT_URI (registered in the Feishu app console) or pass --redirect-uri.
103
+ `};let w=Xe({appId:o,redirectUri:m,scope:l,state:"cortex",domain:r});process.stdout.write(["1) Open this URL in a browser and authorize:","",` ${w}`,"","2) After authorizing you will be redirected to your redirect URI."," Copy the authorization code (the `code` query param) \u2014 or the whole redirected URL.",""].join(`
104
+ `));let O=await(e.prompt??Bn)("Paste the code or callback URL: "),M=qe(O);if(!M)return{exitCode:1,stdout:"",stderr:`Could not read an authorization code from the input.
105
+ `};try{let A=await ze({appId:o,appSecret:a,code:M,redirectUri:m,domain:r,fetchImpl:e.fetchImpl,now:e.now});return Ht(A,n),g(A,await p())}catch(A){return{exitCode:1,stdout:"",stderr:`Login failed: ${A.message}
106
+ `}}}let $;try{$=await Ye({appId:o,appSecret:a,scope:l,domain:r,fetchImpl:e.fetchImpl})}catch(m){return{exitCode:1,stdout:"",stderr:`${m.message}
107
+ `}}process.stdout.write([`Authorizing a Feishu user account (region: ${h}).`,"","1) Open this URL in a browser and confirm:","",` ${$.verification_uri_complete}`,...$.user_code?["",` verification code: ${$.user_code}`]:[],"","2) Waiting for authorization"].join(`
108
+ `));try{let m=await Ze({appId:o,appSecret:a,deviceCode:$.device_code,interval:$.interval,expiresIn:$.expires_in,domain:r,fetchImpl:e.fetchImpl,now:e.now,sleep:e.sleep,onPending:()=>process.stdout.write(".")});return Ht(m,n),g(m,await p())}catch(m){return{exitCode:1,stdout:"",stderr:`
109
+ Login failed: ${m.message}
110
+ `}}}case"status":{let o=s.FEISHU_AUTH_MODE==="user"?"user":"bot",a=Qe(n),l=[`Feishu auth mode: ${o}`,`Token file: ${n}`];if(!a)l.push("User token: not logged in (no token stored)."),o==="user"&&l.push("Doc tools will fail until you run `cortex feishu login`.");else{let h=(e.now??Date.now)(),f=h<a.access_expires_at,p=h<a.refresh_expires_at,g=f?"valid":p?"expired (refreshable)":"expired (re-login needed)";l.push(`User token: logged in \u2014 ${g}`,` scope: ${a.scope??"(default)"}`,` access expires: ${Ft(a.access_expires_at)}`,` refresh expires:${Ft(a.refresh_expires_at)}`)}return{exitCode:0,stdout:l.join(`
111
+ `)+`
112
+ `,stderr:""}}case"logout":return{exitCode:0,stderr:"",stdout:ti(n)?`Removed stored Feishu user token (${n}).
113
+ `:`No stored Feishu user token to remove.
114
+ `};default:return{exitCode:1,stdout:"",stderr:`Unknown subcommand '${i}'.
115
+
116
+ ${ls()}
117
+ `}}}var de=lt(jt(),1);import{existsSync as gs,readFileSync as $s}from"fs";import*as nt from"path";var Kn=["cortexui://localhost","http://cortexui.localhost","tauri://localhost","http://tauri.localhost"];function Pt(t,e){if(gs(t))try{return de.parse($s(t,"utf-8"))[e]?.trim()||void 0}catch{return}}async function Jn(t){let e=nt.join(t,"settings.json"),i=!1;return await It(e,s=>{let n={};if(s.trim()){let a=JSON.parse(s);if(!a||typeof a!="object"||Array.isArray(a))throw new TypeError("settings.json must contain a JSON object");n=a}let r=Array.isArray(n.uiCorsOrigins)?n.uiCorsOrigins.filter(a=>typeof a=="string"):[],o=Kn.filter(a=>!r.includes(a));return o.length===0?s:(i=!0,`${JSON.stringify({...n,uiCorsOrigins:[...r,...o]},null,2)}
118
+ `)}),i}async function ys(t){let e=nt.join(t.configDir,".env"),i=gs(e)?de.parse($s(e,"utf-8")):{},{port:s,changed:n}=await pe(t),r={...i},{clientToken:o,generated:a}=Ce({envPath:e,env:r}),l=a.length>0||n;return Pe(i)||(await at(e,"CORTEX_UI_HTTP","1"),l=!0),await Jn(t.configDir)&&(l=!0),{url:`http://127.0.0.1:${s}`,token:o,port:s,changed:l}}async function pe(t){let e=nt.join(t.configDir,".env"),i=Pt(e,Vt),s=await Xn(t,i,Pt(e,Re)??Oe);return i===String(s)?{port:s,changed:!1}:(await at(e,Vt,String(s)),{port:s,changed:!0})}var fs="Invalid main port (CORTEX_UI_PORT); choose a port between 1 and 65535 and retry.";async function Xn(t,e,i){let s=e===void 0?qn(t.configDir):Gt(e);if(t.port===void 0){if(e!==void 0&&s===null)throw new Error(fs);return s??Ne(i)}if(Gt(String(t.port))===null)throw new Error(fs);if(t.port===s||await De(t.port,i))return t.port;throw new Error(`Port ${t.port} is already in use by another process; choose another port, or leave the port out to pick a free one.`)}function qn(t){let e=nt.join(nt.dirname(t),"data","app.pid");return Me(e)===null?null:Ae}function me(t){if(t!==void 0){if(t==="127.0.0.1")return"127.0.0.1";throw new Error("--answers clientListenHost must be the literal 127.0.0.1")}}function vs(t){if(t===void 0)return;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("--answers localClient must be an object with enabled: true or false");let{enabled:e}=t;if(typeof e!="boolean")throw new Error("--answers localClient.enabled must be true or false");return{enabled:e}}async function ws(t,e,i,s){if(!e.localClient?.enabled)return i();try{await li(t,e.machineName),i(),await hi(t,e.machineName),s({step:"local-client",state:"ok",device:e.machineName})}catch(n){throw s({step:"local-client",state:"error",reason:n.message}),n}}var Es=Ie("init");function Zn(t){let e=t?d.resolve(t):process.env.CORTEX_HOME?d.resolve(process.env.CORTEX_HOME):d.join(W.homedir(),".cortex"),i=d.join(e,"context");return{DATA_DIR:e,CONFIG_DIR:d.join(e,"config"),STORE_DIR:d.join(e,"data"),CONTEXT_DIR:i,PROJECTS_DIR:process.env.CORTEX_PROJECTS_DIR?d.resolve(process.env.CORTEX_PROJECTS_DIR):d.join(i,"projects"),WORKSPACE_DIR:d.join(e,"tmp")}}function bs(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}function Qn(t){if(!t||typeof t!="object")return;let{enabled:e,port:i}=t;return e!==!0?void 0:{enabled:!0,port:typeof i=="number"&&Number.isInteger(i)&&i>0&&i<65536?i:void 0}}function tr(t){let e=t??{},i=s=>typeof e[s]=="string"?e[s]:"";return e.enabled===!0?{enabled:!0,name:i("name"),org:i("org"),email:i("email")}:e.enabled===!1?{enabled:!1}:void 0}function er(t){let e;try{e=JSON.parse(t)}catch(r){throw new Error(`--answers file is not valid JSON: ${r.message}`)}if(!e||typeof e!="object"||Array.isArray(e))throw new Error("--answers file must contain a JSON object");let i=e,s=bs(i.backends).filter(r=>r==="claude"||r==="pi"),n=[];for(let r of bs(i.platforms)){let o=r.trim().toLowerCase();(o==="slack"||o==="feishu")&&!n.includes(o)&&n.push(o)}return{lang:typeof i.lang=="string"?Ut(i.lang):bt(),backends:s.length>0?s:i.backends===void 0?["pi"]:["claude"],machineName:typeof i.machineName=="string"&&i.machineName.trim()?i.machineName.trim():W.hostname(),gpuCount:typeof i.gpuCount=="number"?i.gpuCount:ye(),platforms:n,slackConfig:i.slackConfig,feishuConfig:i.feishuConfig,usageSharing:tr(i.usageSharing??i.gatewayUsage),telemetry:cs(i.telemetry),installService:i.installService===!0,defaultChoice:ce(i.defaultChoice),favorites:Array.isArray(i.favorites)?i.favorites.map(ce).filter(r=>!!r):void 0,localUi:Qn(i.localUi),localClient:vs(i.localClient),clientListenHost:me(i.clientListenHost)}}function ir(t){let e=["# Cortex Configuration","# Generated by `cortex init`","",`CORTEX_MACHINE=${t.machineName}`,"","# Auth tokens \u2014 WS client (cortex-client \u2194 server) + webhook bearer. Required (fail-closed).","# Remote cortex-client machines must share CORTEX_CLIENT_TOKEN. Rotate by editing here + restart.",`CORTEX_CLIENT_TOKEN=${Is(32).toString("hex")}`,`CORTEX_WEBHOOK_TOKEN=${Is(32).toString("hex")}`],i=me(t.clientListenHost);return i!==void 0&&e.push(`CORTEX_CLIENT_HOST=${i}`),t.platforms.length>0&&(e.push(`CORTEX_PLATFORM=${t.platforms.join(",")}`),e.push(""),t.slackConfig&&(e.push("# Slack configuration"),e.push(`SLACK_BOT_TOKEN=${t.slackConfig.botToken}`),e.push(`SLACK_SIGNING_SECRET=${t.slackConfig.signingSecret}`),e.push(`SLACK_APP_TOKEN=${t.slackConfig.appToken}`),e.push("")),t.feishuConfig&&(e.push("# Feishu configuration"),e.push(`FEISHU_APP_ID=${t.feishuConfig.appId}`),e.push(`FEISHU_APP_SECRET=${t.feishuConfig.appSecret}`),t.feishuConfig.domain&&e.push(`FEISHU_DOMAIN=${t.feishuConfig.domain}`),e.push(`FEISHU_AUTH_MODE=${t.feishuConfig.authMode??"bot"}`))),e.push(""),e.join(`
119
+ `)}function sr(){return JSON.stringify({defaultAgent:"main"})}function Pa(t,e){let i=c("init.config.found"),s=c("init.config.missing");return[c("init.config.title"),` INSTALL_ROOT: ${t.INSTALL_ROOT}`,` DATA_DIR: ${t.DATA_DIR}`,` CONFIG_DIR: ${t.CONFIG_DIR}`,` STORE_DIR: ${t.STORE_DIR}`,` CONTEXT_DIR: ${t.CONTEXT_DIR}`,` PROJECTS_DIR: ${t.PROJECTS_DIR}`,` WORKSPACE_DIR: ${t.WORKSPACE_DIR}`,"",c("init.config.statusTitle"),` DATA_DIR: ${e.dataDirExists?c("init.config.initialized"):c("init.config.notInitialized")}`,` .env: ${e.dotEnvExists?i:s}`,` mcp-config.json: ${e.mcpConfigExists?i:s}`,` agent-state: ${e.modeJsonExists?i:s}`].join(`
120
+ `)}var $e={claude:{bin:"claude",npmPackage:"@anthropic-ai/claude-code",labelKey:"init.backend.label.claude",loginHintKey:"init.backend.loginHint.claude"},pi:{bin:null,npmPackage:null,labelKey:"init.backend.label.pi",loginHintKey:"init.backend.loginHint.pi"}},Ss=JSON.stringify({display_information:{name:"Cortex",description:"Autonomous research agent",background_color:"#2c2d30"},features:{bot_user:{display_name:"Cortex",always_online:!0}},oauth_config:{scopes:{bot:["chat:write","im:history","im:write","reactions:read","reactions:write","users:read","commands","app_mentions:read","channels:history","channels:read","groups:history","files:read","files:write","emoji:read","pins:read","pins:write"]}},settings:{event_subscriptions:{bot_events:["message.im","message.channels","message.groups","app_mention"]},interactivity:{is_enabled:!1},org_deploy_enabled:!1,socket_mode_enabled:!0,token_rotation_enabled:!1}},null,2);function nr(t){if(process.stdout.isTTY){let i=Buffer.from(t,"utf-8").toString("base64");return process.stdout.write(`\x1B]52;c;${i}\x07`),!0}let e=process.platform==="darwin"?[["pbcopy",[]]]:process.platform==="win32"?[["clip",[]]]:[["xclip",["-selection","clipboard"]],["wl-copy",[]],["xsel",["--clipboard","--input"]]];for(let[i,s]of e)try{let n=[i,...s].join(" ");return ct(n,{input:t,stdio:"pipe",timeout:3e3}),!0}catch{continue}return!1}async function rr(t){if(process.stdin.isTTY)return process.stdout.write(c("init.clipboard.prompt")),new Promise(e=>{let i=process.stdin.isRaw??!1;try{process.stdin.setRawMode(!0),process.stdin.resume()}catch{process.stdout.write("\r\x1B[K"),e();return}let s=n=>{let r=n.toString();process.stdout.write("\b \b");try{process.stdin.setRawMode(i),process.stdin.pause()}catch{}process.stdin.removeListener("data",s),process.stdout.write("\r\x1B[K"),r.toLowerCase()==="c"&&(nr(t)?v.success(c("init.clipboard.copied")):(v.warn(c("init.clipboard.failed")),v.info(c("init.clipboard.manual")))),e()};process.stdin.on("data",s)})}function or(t){if(!L(t))return null;try{let e=ge(t,"utf-8"),i={};for(let s of e.split(`
121
+ `)){let n=s.trim();if(!n||n.startsWith("#"))continue;let r=n.indexOf("=");if(r===-1)continue;let o=n.substring(0,r).trim(),a=n.substring(r+1).trim();o==="SLACK_SIGNING_SECRET"?i.signingSecret=a:o==="SLACK_APP_TOKEN"?i.appToken=a:o==="SLACK_BOT_TOKEN"&&(i.botToken=a)}return!i.signingSecret&&!i.appToken&&!i.botToken?null:i}catch{return null}}function ar(t){let{bin:e}=$e[t];if(!e)return!0;let i=process.platform==="win32"?"where":"which";try{return ct(`${i} ${e}`,{stdio:"pipe"}),!0}catch{return!1}}function cr(t){let{npmPackage:e}=$e[t];return e?`npm install -g ${e}`:null}function ye(){try{let t=ct("nvidia-smi --query-gpu=count --format=csv,noheader",{stdio:"pipe",encoding:"utf-8",timeout:5e3}),e=parseInt(t.trim(),10);return Number.isFinite(e)?e:0}catch{return 0}}async function ur(t){for(let e of t){let i=$e[e],s=c(i.labelKey),n=cr(e);if(!n)v.success(c("init.backend.bundled",{label:s}));else if(ar(e))v.success(c("init.backend.alreadyInstalled",{label:s}));else{let r=Ki();r.start(c("init.backend.installing",{label:s}));try{ct(n,{stdio:"pipe",timeout:12e4}),r.stop(c("init.backend.installed",{label:s}))}catch{r.stop(c("init.backend.installFailed",{label:s})),v.error(c("init.backend.installFailedHint",{command:n}))}}}}function _s(t,e,i,s="system"){let n=s==="user";return["[Unit]","Description=Cortex Agent Server","After=network.target","","[Service]","Type=simple",...n?[]:[`User=${t}`],`ExecStart=${JSON.stringify(e.node)} ${JSON.stringify(e.daemon)}`,`Environment=CORTEX_HOME=${i}`,"Restart=on-failure","RestartSec=5","","[Install]",n?"WantedBy=default.target":"WantedBy=multi-user.target",""].join(`
122
+ `)}function lr(t,e){return['<?xml version="1.0" encoding="UTF-8"?>','<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">','<plist version="1.0">',"<dict>"," <key>Label</key>"," <string>cc.cortex.agent-server</string>"," <key>ProgramArguments</key>"," <array>",` <string>${Cs(t.node)}</string>`,` <string>${Cs(t.daemon)}</string>`," </array>"," <key>EnvironmentVariables</key>"," <dict>"," <key>CORTEX_HOME</key>",` <string>${e}</string>`," </dict>"," <key>RunAtLoad</key>"," <true/>"," <key>KeepAlive</key>"," <true/>"," <key>StandardOutPath</key>",` <string>${e}/logs/cortex-stdout.log</string>`," <key>StandardErrorPath</key>",` <string>${e}/logs/cortex-stderr.log</string>`,"</dict>","</plist>",""].join(`
123
+ `)}function Cs(t){return t.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function hr(){return{node:process.execPath,daemon:d.join(ht,"dist","entry","daemon.js")}}function dr(){if(process.platform==="win32")return!1;try{return ct("sudo -n true",{stdio:"pipe"}),!0}catch{return!1}}function pr(t){let e=W.userInfo().username,i=hr(),s=process.platform;if(s==="darwin"){let n="cc.cortex.agent-server.plist",r=lr(i,t),o=d.join(W.homedir(),"Library","LaunchAgents",n);B(o,r),v.success(c("init.service.launchdWritten",{path:o})),v.info(c("init.service.launchdStartHint",{path:o}))}else if(s==="linux"){let n=_s(e,i,t,"system"),r="cortex.service",o=`/etc/systemd/system/${r}`,a=d.join(W.homedir(),".config","systemd","user");try{yt(a,{recursive:!0});let l=d.join(a,r);B(l,_s(e,i,t,"user")),v.success(c("init.service.systemdUserWritten",{path:l})),v.info(c("init.service.systemdUserEnableHint"));return}catch{}if(dr())try{let l=d.join(W.tmpdir(),r);B(l,n),ct(`sudo cp ${l} ${o} && sudo systemctl daemon-reload`,{stdio:"pipe"}),v.success(c("init.service.systemdInstalled",{path:o})),v.info(c("init.service.systemdEnableHint"))}catch(l){v.warn(c("init.service.systemInstallFailed",{message:l.message}))}else{let l=d.join(t,"config",r);B(l,n),v.warn(c("init.service.noSudo")),v.info(c("init.service.manualInstallHint",{localPath:l,systemPath:o}))}}else v.warn(c("init.service.unsupported",{platform:s}))}async function mr(t){gt(Ss,c("init.slack.manifestTitle")),gt(c("init.slack.guide"),c("init.slack.guideTitle")),await rr(Ss);let e=t&&(t.signingSecret||t.appToken||t.botToken),i,s,n;if(e){v.info(c("init.slack.prefillFound"));let r=await ot({message:c("init.slack.skipPrompt"),placeholder:c("init.slack.skipPlaceholder"),defaultValue:""});E(r),r.trim()===""&&(i=t.signingSecret,s=t.appToken,n=t.botToken)}return i||(i=await it({message:c("init.slack.signingSecretPrompt"),validate(r){if(!r)return c("init.slack.signingSecretRequired")}}),E(i),s=await it({message:c("init.slack.appTokenPrompt"),validate(r){if(!r)return c("init.slack.appTokenRequired");if(!r.startsWith("xapp-"))return c("init.slack.appTokenPrefix")}}),E(s),n=await it({message:c("init.slack.botTokenPrompt"),validate(r){if(!r)return c("init.slack.botTokenRequired");if(!r.startsWith("xoxb-"))return c("init.slack.botTokenPrefix")}}),E(n)),{signingSecret:i,appToken:s,botToken:n}}async function fr(){gt(c("init.feishu.guide"),c("init.feishu.guideTitle"));let t=await ot({message:c("init.feishu.appIdPrompt"),validate(o){if(!o)return c("init.feishu.appIdRequired")}});E(t);let e=await it({message:c("init.feishu.appSecretPrompt"),validate(o){if(!o)return c("init.feishu.appSecretRequired")}});E(e);let i=await ot({message:c("init.feishu.domainPrompt"),placeholder:c("init.feishu.domainPlaceholder")});E(i);let s=i.trim().toLowerCase(),n=s==="feishu"||s==="lark"?s:void 0,r=await st({message:c("init.feishu.authModePrompt"),options:[{value:"bot",label:c("init.feishu.authModeBotLabel"),hint:c("init.feishu.authModeBotHint")},{value:"user",label:c("init.feishu.authModeUserLabel"),hint:c("init.feishu.authModeUserHint")}],initialValue:"user"});return E(r),{appId:t,appSecret:e,domain:n,authMode:r}}async function gr(t,e,i={}){let s=i.cmdFeishuImpl??ms,n=i.stdout??(l=>process.stdout.write(l)),r={...process.env,FEISHU_APP_ID:t.appId,FEISHU_APP_SECRET:t.appSecret};t.domain&&(r.FEISHU_DOMAIN=t.domain);let o=d.join(e,"feishu-user-token.json"),a=await s(["login"],{env:r,tokenFile:o,loadDotenv:!1});return a.stdout&&n(a.stdout),a.exitCode!==0&&a.stderr&&n(a.stderr),a}async function $r(t){let e=bt(),i=await st({message:"Select language / \u9009\u62E9\u8BED\u8A00",options:[{value:"en",label:"English"},{value:"zh",label:"\u4E2D\u6587 (Simplified Chinese)"}],initialValue:e});E(i);let s=i;be(s),Wi(c("init.intro"));let n=["pi"];v.info(c("init.auth.piFirst"));let r=await Ot({message:c("init.platform.prompt"),options:[{value:"slack",label:c("init.platform.slackLabel"),hint:c("init.platform.slackHint")},{value:"feishu",label:c("init.platform.feishuLabel")}],required:!1});E(r);let o=r,a,l;if(o.includes("slack")){let w=d.join(t.CONFIG_DIR,".env"),C=or(w);a=await mr(C??void 0)}o.includes("feishu")&&(l=await fr(),l.authMode==="user"&&(v.info(c("init.feishu.loginStarting")),(await gr(l,t.CONFIG_DIR)).exitCode===0?v.success(c("init.feishu.loginComplete")):v.warn(c("init.feishu.loginIncomplete"))));let h=W.hostname(),f=await ot({message:c("init.machine.prompt"),placeholder:h,defaultValue:h,validate(w){if(!w)return c("init.machine.required")}});E(f);let p=ye();p>0?v.success(c("init.machine.gpuDetected",{count:p})):v.info(c("init.machine.gpuNone"));let g=await yr(),$=await vr(),m=await Q({message:c("init.serviceRegister.prompt"),initialValue:!0});return E(m),{lang:s,backends:n,machineName:f,gpuCount:p,platforms:o,slackConfig:a,feishuConfig:l,usageSharing:g,telemetry:$,installService:m}}async function fe(t){let e=await ot({message:c(`init.usageSharing.${t}Prompt`),placeholder:c(`init.usageSharing.${t}Placeholder`)});return E(e),e}async function yr(){gt(c("init.usageSharing.note"),c("init.usageSharing.noteTitle"));let t=await Q({message:c("init.usageSharing.enablePrompt"),initialValue:!0});if(E(t),!t)return{enabled:!1};let e=await fe("name"),i=await fe("org");return{enabled:!0,name:e,org:i,email:await fe("email")}}async function vr(){let t=await Q({message:c("init.telemetry.prompt"),initialValue:!0});return E(t),{enabled:t}}async function wr(){let t=[],e=Yn({input:Mt});for await(let i of e)t.push(i);return Es.info("Cortex Initialization (non-interactive)"),Sr(t)}function Ir(t=""){let e=t.split(",").map(i=>i.trim().toLowerCase());return[...new Set(e.filter(i=>i==="slack"||i==="feishu"))]}function br(t,e){let i,s,n=7;if(e.includes("slack")&&t.length>=n+3&&(i={signingSecret:t[n]||"",appToken:t[n+1]||"",botToken:t[n+2]||""},n+=3),e.includes("feishu")&&t.length>=n+3){let r=(t[n+2]||"").trim().toLowerCase();s={appId:t[n]||"",appSecret:t[n+1]||"",domain:r==="feishu"||r==="lark"?r:void 0},n+=3}return{slackConfig:i,feishuConfig:s,cursor:n}}function Sr(t){let[e,i,s,n,r,o,a]=t,l=(e||"pi").split(",").map(m=>m.trim()).filter(m=>m==="claude"||m==="pi"),h=Ir(i),{slackConfig:f,feishuConfig:p,cursor:g}=br(t,h),$=s?.trim().toLowerCase();return{lang:process.env.CORTEX_LANG?Ut(process.env.CORTEX_LANG):bt(),backends:l.length>0?l:["claude"],machineName:W.hostname(),gpuCount:ye(),platforms:h,slackConfig:f,feishuConfig:p,usageSharing:$==="y"?{enabled:!0,name:n||"",org:r||"",email:o||""}:$==="n"?{enabled:!1}:void 0,installService:a?.toLowerCase()==="y",defaultChoice:ue(t[g]),favorites:ns(t[g+1])}}function _r(t){let e=[t.DATA_DIR,t.CONFIG_DIR,t.STORE_DIR,d.join(t.DATA_DIR,"logs","sessions"),t.WORKSPACE_DIR,t.PROJECTS_DIR,d.join(t.CONTEXT_DIR,"user"),d.join(t.CONTEXT_DIR,"decisions"),d.join(t.CONTEXT_DIR,"scans"),d.join(t.CONTEXT_DIR,"ideas"),d.join(t.CONTEXT_DIR,"retrospectives"),d.join(t.DATA_DIR,".claude","hooks"),d.join(t.DATA_DIR,".claude","rules"),d.join(t.DATA_DIR,"plugins"),d.join(t.DATA_DIR,"prompts","directives"),d.join(t.DATA_DIR,"prompts","systemPrompts"),d.join(t.DATA_DIR,"prompts","promptTemplates"),d.join(t.DATA_DIR,"hooks"),d.join(t.DATA_DIR,"plan"),d.join(t.DATA_DIR,"logs","sessions-pi")];for(let i of e)yt(i,{recursive:!0})}function z(t,e,i){if(!L(t)||L(e)&&!i)return!1;let s=d.dirname(e);return L(s)||yt(s,{recursive:!0}),ks(t,e),!0}function xs(t,e,i){if(L(t)){yt(e,{recursive:!0});for(let s of zn(t,{withFileTypes:!0})){let n=d.join(t,s.name),r=d.join(e,s.name);if(s.isDirectory())xs(n,r,i);else if(s.isFile()){if(L(r)&&!i)continue;ks(n,r)}}}}function Cr(t,e){z(d.join(U,"AGENTS.md"),d.join(t.DATA_DIR,"AGENTS.md"),!1),z(d.join(U,"gitignore"),d.join(t.DATA_DIR,".gitignore"),!1),z(d.join(U,".claude","settings.json"),d.join(t.DATA_DIR,".claude","settings.json"),!1),z(d.join(U,"context","AGENTS.md"),d.join(t.CONTEXT_DIR,"AGENTS.md"),!1),z(d.join(U,"context","projects","AGENTS.md"),d.join(t.PROJECTS_DIR,"AGENTS.md"),!1),z(d.join(U,"context","scans","AGENTS.md"),d.join(t.CONTEXT_DIR,"scans","AGENTS.md"),!1),z(d.join(U,"context","ideas","AGENTS.md"),d.join(t.CONTEXT_DIR,"ideas","AGENTS.md"),!1),z(d.join(U,"context","user","AGENTS.md"),d.join(t.CONTEXT_DIR,"user","AGENTS.md"),!1),z(d.join(U,"config","budget.json"),d.join(t.CONFIG_DIR,"budget.json"),e),ei(d.join(U,"config",Wt),d.join(t.CONFIG_DIR,Wt)),xs(d.join(U,"context","decisions"),d.join(t.CONTEXT_DIR,"decisions"),e)}function kr(t){let e=[["mcp-config.json",je(ht)],["mcp-config-core.json",Le(ht)],["mcp-config-empty.json",Ue()],["mcp-config-interaction.json",Ve(ht)]];for(let[i,s]of e)B(d.join(t,i),JSON.stringify(s,null,2))}function Tr(t,e,i){kr(t.CONFIG_DIR);let s=d.join(t.STORE_DIR,"agent-state.json");(!L(s)&&!L(d.join(t.STORE_DIR,"mode.json"))||i)&&B(s,sr());let n=d.join(t.CONFIG_DIR,"preferences.json");(!L(n)||i)&&B(n,JSON.stringify({lang:e.lang},null,2)+`
124
+ `);let r=d.join(t.CONFIG_DIR,"machines.json");if(!L(r)||i){let o={cortexPath:t.DATA_DIR,gpuCount:e.gpuCount},a={[e.machineName]:o};B(r,JSON.stringify(a,null,2)+`
125
+ `)}}function Er(t,e){let i=d.join(t.STORE_DIR,"schedules.json");if(L(i)&&!e)return;let s=d.join(U,"data","schedules.json");if(!L(s))return;let n="",r=Date.now(),o=ge(s,"utf-8");o=o.replace(/__ADMIN_CHANNEL__/g,n);let a=JSON.parse(o);for(let l of a.tasks)l.createdAt===0&&(l.createdAt=r);yt(d.dirname(i),{recursive:!0}),B(i,JSON.stringify(a,null,2)+`
126
+ `)}function xr(t,e,i){let s=d.join(t.CONFIG_DIR,".env"),n=L(s);if(n&&!i)return;let r=ir(e);if(!n){B(s,r);return}let o=ge(s,"utf8"),a=(0,Ts.parse)(o);for(let l of r.split(`
127
+ `)){let h=l.match(/^([A-Z_]+)=(.*)$/);if(!h)continue;let[,f,p]=h;(f==="CORTEX_CLIENT_TOKEN"||f==="CORTEX_WEBHOOK_TOKEN")&&a[f]?.trim()||(o=Nt(o,f,p))}B(s,o)}function Ar(){let t=process.stdout,e=t.write.bind(t);return t.write=((i,s,n)=>process.stderr.write(i,s,n)),{emit(i){e(`${JSON.stringify(i)}
128
+ `)},restore(){t.write=e}}}async function Ma(t={}){let e=Zn(t.homeDir),i=t.force??!1,s=t.jsonEvents?Ar():null;try{await Fr(e,i,t,s)}finally{s?.restore()}}function Rr(t,e){e.usageSharing&&Be(e.usageSharing),e.telemetry&&us(e.telemetry,{configDir:t.CONFIG_DIR,storeDir:t.STORE_DIR})}async function Or(t,e,i,s,n){let r=a=>n?.emit(a),o=await es(s,a=>{r(a),!n&&!s&&process.stdout.write(`${JSON.stringify(a)}
129
+ `)});if(s){let a=o.length>0&&await le({backends:o,configDir:t.CONFIG_DIR,answers:e,interactive:!0});r({step:"models",state:a?"ok":"skip"});return}try{let a=await le({backends:e.backends,configDir:t.CONFIG_DIR,answers:e});r({step:"models",state:a?"ok":"skip",reason:a?void 0:"no-backend-login"})}catch(a){Es.warn(`Model setup failed (non-interactive): ${a.message}`),r({step:"models",state:"skip",reason:a.message})}}function Dr(t,e,i){let s=e.localClient?.enabled?!1:i;xr(t,e,s),Cr(t,s),Tr(t,e,s),Er(t,s)}function Nr(t){let e=!L(d.join(t.CONFIG_DIR,"machines.json")),i=ne();_r(t),i&&zi(t.DATA_DIR),ni({freshHome:e,file:d.join(t.STORE_DIR,"telemetry","state.json")})}async function Fr(t,e,i,s){let n=l=>s?.emit(l),r=i.answers??(Mt.isTTY&&!i.jsonEvents?await $r(t):i.jsonEvents&&Mt.isTTY?er("{}"):await wr()),o=!i.answers&&!i.jsonEvents&&Mt.isTTY;n({step:"answers",state:"ok",machine:r.machineName,backends:r.backends}),await ur(r.backends),n({step:"backends",state:"ok"}),Nr(t),n({step:"home",state:"ok",home:t.DATA_DIR}),await ws(t,r,()=>Dr(t,r,e),n),n({step:"config",state:"ok"}),Rr(t,r),await pe({configDir:t.CONFIG_DIR,port:r.localUi?.port});let a=null;r.localUi?.enabled&&(a=await ys({configDir:t.CONFIG_DIR,port:r.localUi.port}),v.success(c("init.localUi.enabled",{url:a.url})),n({step:"local-ui",state:"ok",url:a.url,port:a.port})),r.installService&&(pr(t.DATA_DIR),n({step:"service",state:"ok"})),await Or(t,r,i,!!o,s),Bi(c("init.outro",{dataDir:t.DATA_DIR})),r.telemetry?.enabled!==!1&&d.resolve(t.DATA_DIR)===d.resolve(ve)&&xe("server_init_completed"),n({step:"result",state:"ok",home:t.DATA_DIR,version:ke,clientToken:Pt(d.join(t.CONFIG_DIR,".env"),_e)??null,uiUrl:a?.url??null})}export{Xi as a,qi as b,ne as c,b as d,Qi as e,ms as f,ys as g,Zn as h,er as i,ir as j,sr as k,Pa as l,Ss as m,ar as n,cr as o,_s as p,lr as q,gr as r,Sr as s,z as t,Tr as u,xr as v,Ma as w,Dr as x};