@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
@@ -1,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{L as M,o as O}from"./chunk-PZMGBKUR.js";var f=class extends Error{},D=["$ref","$defs","definitions","allOf","oneOf","patternProperties","dependentSchemas","dependencies","unevaluatedProperties","propertyNames","contains","prefixItems","not","if","then","else"];function y(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function L(e){if(!y(e))return!1;let r=typeof e.type=="string"?[e.type]:Array.isArray(e.type)?e.type:[];return r.includes("object")||r.includes("array")||e.properties!==void 0||e.items!==void 0}function R(e){return y(e)?e.type==="null"||Array.isArray(e.type)&&e.type.includes("null")||e.const===null||Array.isArray(e.enum)&&e.enum.includes(null)?!0:Array.isArray(e.anyOf)&&e.anyOf.some(r=>R(r)):!1}function w(e,r){if(!y(e))throw new f("boolean schemas are unsupported");for(let a of D)if(e[a]!==void 0)throw new f(`${a} schemas are unsupported`);if(r){for(let[a,l]of Object.entries(e))if(r(a,l))throw new f(`${a}: ${JSON.stringify(l)} is unsupported`)}if(e.anyOf!==void 0){if(!Array.isArray(e.anyOf)||e.anyOf.length===0)throw new f("anyOf must contain at least one schema");for(let a of e.anyOf){if(L(a))throw new f("object and array unions are unsupported");w(a,r)}}if(e.items!==void 0){if(Array.isArray(e.items))throw new f("tuple schemas are unsupported");w(e.items,r)}let t=e.type==="object";if(e.properties!==void 0&&!t)throw new f("properties require type object");if(!t)return;if(e.additionalProperties!==void 0&&e.additionalProperties!==!1)throw new f("schema-valued or true additionalProperties is unsupported");if(e.properties!==void 0&&!y(e.properties))throw new f("object properties must be a schema map");if(e.required!==void 0&&(!Array.isArray(e.required)||e.required.some(a=>typeof a!="string")))throw new f("object required must be a string array");let n=e.properties??{},o=Object.keys(n),i=new Set(Array.isArray(e.required)?e.required:[]);if([...i].some(a=>!o.includes(a)))throw new f("required contains an unknown property");for(let[a,l]of Object.entries(n))w(l,r),!i.has(a)&&!R(l)&&(n[a]={anyOf:[l,{type:"null"}]});e.required=o,e.additionalProperties=!1}function k(e,r){let t=structuredClone(e);if(!y(t))throw new f("root schema must have type object");if(w(t,r),t.type!=="object")throw new f("root schema must have type object");return t}function re(e,r){return r===!0?k(e.parameters):e.parameters}function ne(e,r,t){let n=r[t];if(typeof n!="string")throw new Error(`Grammar tool call "${e}" requires argument "${t}" to be a string.`);return n}function oe(e,r,t,n){if(e.closed){if(n&&t===e.input)return;throw new Error(`grammar tool input for property "${r}" changed after it was closed`)}if(!t.startsWith(e.input))throw new Error(`grammar tool input for property "${r}" changed non-monotonically`);let o=t.slice(e.input.length);if(!n&&o.length===0)return;let i="";return e.started||(i+=`{${JSON.stringify(r)}:"`,e.started=!0),i+=JSON.stringify(o).slice(1,-1),e.input=t,n&&(i+='"}',e.closed=!0),i}function b(e){let r=e.parameters;if(r.type!=="object")throw new Error("grammar constrained sampling requires an object parameter schema");if(!Array.isArray(r.required)||r.required.length!==1||typeof r.required[0]!="string")throw new Error("grammar constrained sampling requires exactly one required string property");let t=r.required[0];if(!r.properties?.[t])throw new Error(`grammar constrained sampling requires a properties entry for ${t}`);if(r.properties[t]?.type!=="string")throw new Error(`grammar constrained sampling property ${t} must have type string`);return t}function ie(e,r,t){let n=e.constrainedSampling;if(!(!n||n.type!=="json_schema")){if(r)try{return k(e.parameters,t),!0}catch(o){if(!(o instanceof f))throw o;if(n.strict!=="require")return;throw new Error(`Tool "${e.name}" requires JSON-schema constrained sampling, but ${o.message}.`)}if(n.strict==="require")throw new Error(`Tool "${e.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`)}}function G(e,r){let t=e.constrainedSampling;if(!t||t.type!=="grammar"||!r)return;let n=t.variants.openai_lark,o=t.variants.openai_regex,i=typeof n=="string"&&n.trim().length>0,a=typeof o=="string"&&o.trim().length>0;if(!i&&!a)throw new Error(`Tool "${e.name}" cannot use grammar constrained sampling: no supported grammar variant was provided.`);try{return{format:i?"lark":"regex",definition:i?n:o,inputProperty:b(e)}}catch(l){let d=l instanceof Error?l.message:String(l);throw new Error(`Tool "${e.name}" cannot use grammar constrained sampling: ${d}.`)}}function ae(e,r){let t=new Map;for(let n of e??[]){let o=G(n,r);o&&t.set(n.name,o.inputProperty)}return t}var E=3.5,J=4800;function P(e){return e.totalTokens||e.input+e.output+e.cacheRead+e.cacheWrite}function _(e){try{return JSON.stringify(e)??"undefined"}catch{return"[unserializable]"}}function H(e){if(typeof e=="string")return e.length;let r=0;for(let t of e)r+=t.type==="text"?t.text.length:J;return r}function q(e){return Math.ceil(e.length/E)}function N(e){return Math.ceil(H(e)/E)}function C(e){let r=0;if(e.role==="system")return q(O(e))+v(e.toolsAdded)+v(e.toolsRemoved);if(e.role==="user"||e.role==="toolResult")return N(e.content);for(let t of e.content)t.type==="text"?r+=t.text.length:t.type==="thinking"?r+=t.thinking.length:r+=t.name.length+_(t.arguments).length;return Math.ceil(r/E)}function W(e){let r=Number.NEGATIVE_INFINITY,t;for(let n=0;n<e.length;n++){let o=e[n];if(o.role==="assistant"){let i=o;i.timestamp>=r&&i.stopReason!=="aborted"&&i.stopReason!=="error"&&P(i.usage)>0&&(t={usage:i.usage,index:n})}r=Math.max(r,o.timestamp)}return t}function $(e){let r="messages"in e?e.messages:e,t=W(r);if(t){let o=P(t.usage),i=0;for(let a=t.index+1;a<r.length;a++)i+=C(r[a]);return{tokens:o+i,usageTokens:o,trailingTokens:i,lastUsageIndex:t.index}}let n=0;for(let o of r)n+=C(o);return{tokens:n,usageTokens:0,trailingTokens:n,lastUsageIndex:null}}function v(e){return!e||e.length===0?0:q(_(e))}var B=4096,j=1;function F(e,r,t){if(e.contextWindow<=0)return Math.max(j,t);let n=e.contextWindow-$(r).tokens-B;return Math.min(t,Math.max(j,n))}function z(e,r,t){let n=M(e,r),o=e.samplingParamsByThinkingLevel?.[n];return e.samplingParams||o||t?{...e.samplingParams,...o,...t}:void 0}function ce(e,r,t,n){let o=z(e,t?.reasoning??"off",t?.samplingParams);return{temperature:t?.temperature,samplingParams:o,maxTokens:F(e,r,t?.maxTokens??e.maxTokens),signal:t?.signal,telemetry:t?.telemetry,apiKey:n||t?.apiKey,fetch:t?.fetch,transport:t?.transport,cacheRetention:t?.cacheRetention,sessionId:t?.sessionId,headers:t?.headers,identity:t?.identity,onPayload:t?.onPayload,onResponse:t?.onResponse,onProviderStreamEvent:t?.onProviderStreamEvent,timeoutMs:t?.timeoutMs,websocketConnectTimeoutMs:t?.websocketConnectTimeoutMs,maxRetries:t?.maxRetries,maxRetryDelayMs:t?.maxRetryDelayMs,metadata:t?.metadata,env:t?.env}}var K=1024,U={minimal:1024,low:2048,medium:8192,high:16384};function V(e){return e==="xhigh"||e==="max"?"high":e}function Y(e,r){let t={...U,...r},n=V(e);return t[n]}function X(e,r){return Math.min(e,Math.max(0,r-K))}function de(e,r,t,n){let o=Y(t,n),i=e===void 0?r:Math.min(e+o,r);return i<=o&&(o=X(o,i)),{maxTokens:i,thinkingBudget:o}}var Q="(image omitted: model does not support images)",Z="(tool image omitted: model does not support images)",ee="(image attached after the tool results)";function ge(e){if(!e.isError)return;let r=e.content.filter(t=>t.type==="image");if(r.length!==0)return{content:I(e.content,ee),caption:`Images from the error result of tool call ${e.toolCallId} (${e.toolName}):`,images:r}}function I(e,r){let t=[],n=!1;for(let o of e){if(o.type==="image"){n||t.push({type:"text",text:r}),n=!0;continue}t.push(o),n=o.text===r}return t}function te(e,r){return r.input.includes("image")?e:e.map(t=>t.role==="user"&&Array.isArray(t.content)?{...t,content:I(t.content,Q)}:t.role==="toolResult"?{...t,content:I(t.content,Z)}:t)}function ye(e,r,t){let n=new Map,o=e.map(s=>s.content==null?{...s,content:[]}:s),a=te(o,r).map(s=>{if(s.role==="system"||s.role==="user")return s;if(s.role==="toolResult"){let u=n.get(s.toolCallId);return u&&u!==s.toolCallId?{...s,toolCallId:u}:s}if(s.role==="assistant"){let u=s,c=u.provider===r.provider&&u.api===r.api&&u.model===r.id,x=u.content.flatMap(p=>{if(p.type==="thinking")return c?p.redacted||p.thinkingSignature?p:!p.thinking||p.thinking.trim()===""?[]:p:[];if(p.type==="text")return c?p:{type:"text",text:p.text};if(p.type==="toolCall"){let m=p,g=m;if(!c&&m.thoughtSignature&&(g={...m},delete g.thoughtSignature),!c&&t){let A=t(m.id,r,u);A!==m.id&&(n.set(m.id,A),g={...g,id:A})}return g}return p});return{...u,content:x}}return s}),l=[],d=[],h=new Set,T=[],S=()=>{if(d.length>0){for(let s of d)h.has(s.id)||l.push({role:"toolResult",toolCallId:s.id,toolName:s.name,content:[{type:"text",text:"No result provided"}],isError:!0,timestamp:Date.now()});d=[],h=new Set}l.push(...T),T.length=0};for(let s=0;s<a.length;s++){let u=a[s];if(u.role==="assistant"){S();let c=u;if(c.stopReason==="error"||c.stopReason==="aborted")continue;let x=c.content.filter(p=>p.type==="toolCall");x.length>0&&(d=x,h=new Set),l.push(u)}else u.role==="toolResult"?(h.add(u.toolCallId),l.push(u)):u.role==="system"?d.length>0?T.push(u):l.push(u):(u.role==="user"&&S(),l.push(u))}return S(),l}export{re as a,ne as b,oe as c,ie as d,G as e,ae as f,F as g,z as h,ce as i,V as j,Y as k,X as l,de as m,ge as n,ye as o};
@@ -1,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- function a(t){let e=(t.CORTEX_UI_HTTP||"").trim().toLowerCase();return e==="1"||e==="true"||e==="on"||e==="yes"}async function m(t){if(!a(process.env))return null;let{startUiHttpServer:e}=await import("./start-ui-http-QALT7C3P.js");return e({uiService:t})}import{accessSync as c,constants as p,realpathSync as u,statSync as l}from"node:fs";import{execFileSync as r}from"node:child_process";import*as n from"node:path";function i(t){try{return c(t,p.X_OK),l(t).isFile()}catch{return!1}}function f(){let t=process.platform==="win32"?(process.env.PATHEXT||".EXE;.CMD;.BAT").split(";"):[""];return(process.env.PATH||"").split(n.delimiter).flatMap(s=>t.map(o=>n.resolve(s,`git${o}`))).find(i)??null}function d(t){if(process.platform!=="darwin"||u(t)!=="/usr/bin/git")return!0;let e=r("/usr/bin/xcode-select",["-p"],{encoding:"utf8",stdio:"pipe",timeout:5e3}).trim();return!!e&&i(n.join(e,"usr/bin/git"))}function b(){try{let t=f();return!t||!d(t)?!1:r(t,["--version"],{encoding:"utf8",stdio:"pipe",timeout:5e3}).startsWith("git version ")}catch{return!1}}export{b as a,a as b,m as c};
@@ -1,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{a as ae}from"./chunk-B3XBQEFM.js";import{e as ie}from"./chunk-WHC7AYZD.js";import{realpathSync as pe,statSync as fe}from"node:fs";import{homedir as le}from"node:os";import{isAbsolute as B,join as me,resolve as j,relative as ge,sep as F}from"node:path";import{fileURLToPath as he}from"node:url";var R=ie(ae(),1);import{spawn as ce,spawnSync as ue}from"node:child_process";var de=100;function Oe(e,t,n){return process.platform==="win32"?(0,R.default)(e,t,n):ce(e,t,n)}function w(e,t,n){return process.platform==="win32"?R.default.sync(e,t,n):ue(e,t,n)}function je(e){return new Promise((t,n)=>{let r=!1,o=!1,i=null,a,p=e.stdout===null,d=e.stderr===null,l=()=>{a&&(clearTimeout(a),a=void 0),e.removeListener("error",W),e.removeListener("exit",T),e.removeListener("close",O),e.stdout?.removeListener("end",N),e.stderr?.removeListener("end",L),e.stdout?.removeListener("data",y),e.stderr?.removeListener("data",y)},P=m=>{r||(r=!0,l(),e.stdout?.destroy(),e.stderr?.destroy(),t(m))},k=()=>{!o||r||p&&d&&P(i)},$=()=>{a&&clearTimeout(a),a=setTimeout(()=>P(i),de)},y=()=>{o&&!r&&$()},N=()=>{p=!0,k()},L=()=>{d=!0,k()},W=m=>{r||(r=!0,l(),n(m))},T=m=>{o=!0,i=m,k(),r||$()},O=m=>{P(m)};e.stdout?.once("end",N),e.stderr?.once("end",L),e.stdout?.on("data",y),e.stderr?.on("data",y),e.once("error",W),e.once("exit",T),e.once("close",O)})}var xe=/[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g;function qe(e){try{return pe(e)}catch{return e}}function Ve(e){try{let t=fe(e,{bigint:!0});return`${t.dev}:${t.ino}:${t.size}:${t.mtimeNs}:${t.ctimeNs}`}catch{return}}function He(e){let t=e.trim();return!(t.startsWith("npm:")||t.startsWith("git:")||t.startsWith("github:")||t.startsWith("http:")||t.startsWith("https:")||t.startsWith("ssh:")||t.startsWith("builtin:"))}function be(e){if(!e.startsWith("/")||e.startsWith("//")||e.includes("\\"))return e;let t=e.match(/^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/i);if(!t)return e;let n=t[2]?.replaceAll("/","\\");return`${t[1].toUpperCase()}:\\${n??""}`}function _(e,t={}){let n=t.trim?e.trim():e;if(t.normalizeUnicodeSpaces&&(n=n.replace(xe," ")),t.stripAtPrefix&&n.startsWith("@")&&(n=n.slice(1)),process.platform==="win32"&&(n=be(n)),t.expandTilde??!0){let r=t.homeDir??le();if(n==="~")return r;if(n.startsWith("~/")||process.platform==="win32"&&n.startsWith("~\\"))return me(r,n.slice(2))}return/^file:\/\//.test(n)?he(n):n}function U(e,t=process.cwd(),n={}){let r=_(e,n),o=_(t);return B(r)?j(r):j(o,r)}function Pe(e,t){let n=U(t),r=U(e,n),o=ge(n,r);return o===""||o!==".."&&!o.startsWith(`..${F}`)&&!B(o)?o||".":void 0}function Ke(e,t){let n=U(e,t);return(Pe(n,t)??n).split(F).join("/")}function Qe(e){let t=process.platform==="darwin"?["com.dropbox.ignored","com.apple.fileprovider.ignore#P"]:process.platform==="linux"?["user.com.dropbox.ignored"]:[];for(let n of t)process.platform==="darwin"?w("xattr",["-w",n,"1",e],{encoding:"utf-8",stdio:"ignore"}):w("setfattr",["-n",n,"-v","1",e],{encoding:"utf-8",stdio:"ignore"})}import{accessSync as z,constants as G,existsSync as g,readFileSync as I,realpathSync as _e}from"fs";import{homedir as C}from"os";import{basename as K,dirname as u,join as s,resolve as S,sep as M,win32 as Se}from"path";import{fileURLToPath as Q}from"url";function we(e){return e.startsWith("\uFEFF")?{bom:"\uFEFF",text:e.slice(1)}:{bom:"",text:e}}function A(e){return we(e).text}var ve=Q(new URL("vendor/pi/dist/config.js",__cortexPackageRoot).href),X=u(ve),h=new URL("vendor/pi/dist/config.js",__cortexPackageRoot).href.includes("$bunfs")||new URL("vendor/pi/dist/config.js",__cortexPackageRoot).href.includes("~BUN")||new URL("vendor/pi/dist/config.js",__cortexPackageRoot).href.includes("%7EBUN"),ye=!!process.versions.bun,Ee=!0;function Y(e){return typeof e=="string"?{packageName:e,installSpec:e}:{packageName:e.packageName,installSpec:e.installSpec??e.packageName}}function E(e,t){return t?{...e,display:`${t.display} && ${e.display}`,steps:[t,e]}:e}function f(e,t){return{command:e,args:t,display:[e,...t].map(n=>/\s/.test(n)?`"${n}"`:n).join(" ")}}function Z(){if(h)return"bun-binary";let e=`${X}\0${process.execPath||""}`.toLowerCase().replace(/\\/g,"/");return e.includes("/pnpm/")||e.includes("/.pnpm/")?"pnpm":e.includes("/yarn/")||e.includes("/.yarn/")?"yarn":ye||e.includes("/install/global/node_modules/")?"bun":e.includes("/npm/")||e.includes("/node_modules/")?"npm":"unknown"}function ee(){let e=c(),t=process.platform==="win32"||e.includes("\\")?Se:{basename:K,dirname:u},n=t.dirname(e),r;if(t.basename(n).startsWith("@")&&t.basename(t.dirname(n))==="node_modules"?r=t.dirname(n):t.basename(n)==="node_modules"&&(r=n),!r)return;let o=t.dirname(r);if(t.basename(o)==="lib")return{root:r,prefix:t.dirname(o)}}function te(e,t,n=t,r){let o=Y(n);switch(e){case"bun-binary":return;case"pnpm":{let i=x("pnpm",["root","-g"])?void 0:/^(.*[\\/]global[\\/][^\\/]+)[\\/]\.pnpm[\\/]/.exec(c()),a=i?[`--config.global-bin-dir=${process.env.PNPM_HOME||u(u(i[1]))}`]:[];return E(f("pnpm",["install","-g","--ignore-scripts","--config.minimumReleaseAge=0",...a,o.installSpec]),o.packageName===t?void 0:f("pnpm",["remove","-g",...a,t]))}case"yarn":return E(f("yarn",["global","add","--ignore-scripts",o.installSpec]),o.packageName===t?void 0:f("yarn",["global","remove",t]));case"bun":return E(f("bun",["install","-g","--ignore-scripts","--minimum-release-age=0",o.installSpec]),o.packageName===t?void 0:f("bun",["uninstall","-g",t]));case"npm":{let[i="npm",...a]=r??[],p=r?.length?void 0:ee(),d=[...a,...p?["--prefix",p.prefix]:[]],l=f(i,[...d,"install","-g","--ignore-scripts","--min-release-age=0",o.installSpec]),P=o.packageName===t?void 0:f(i,[...d,"uninstall","-g",t]);return E(l,P)}case"unknown":return}}function x(e,t,n={}){let r=w(e,t,{encoding:"utf-8",stdio:["ignore","pipe","pipe"]});if(r.status===0)return r.stdout.trim()||void 0;if(n.requireSuccess){let o=r.error?.message||r.stderr.trim()||`exit code ${r.status??"unknown"}`;throw new Error(`Failed to run ${[e,...t].join(" ")}: ${o}`)}}function De(e,t,n){switch(e){case"npm":{let r=!!n?.length,[o="npm",...i]=n??[];if(r&&o==="bun"){let d=x(o,[...i,"pm","bin","-g"],{requireSuccess:!0}),l=[s(C(),".bun","install","global","node_modules")];return d&&l.push(s(u(d),"install","global","node_modules")),l}let a=x(o,[...i,"root","-g"],{requireSuccess:r}),p=r?void 0:ee();return[a,p?.root].filter(d=>!!d)}case"pnpm":{let r=x("pnpm",["root","-g"]);if(r)return[r,u(r)];let o=/^(.*[\\/]global[\\/][^\\/]+)[\\/]\.pnpm[\\/]/.exec(c());return o?[o[1]]:[]}case"yarn":{let r=x("yarn",["global","dir"]);return r?[r,s(r,"node_modules")]:[]}case"bun":{let r=x("bun",["pm","bin","-g"]),o=[s(C(),".bun","install","global","node_modules")];return r&&o.push(s(u(r),"install","global","node_modules")),o}case"bun-binary":case"unknown":return[]}}function J(e,t){let n=S(e);if(!g(n))return;let r=n;if(t)try{r=_e(n)}catch{return}return process.platform==="win32"&&(r=r.toLowerCase()),r}function q(e){return Array.from(new Set([J(e,!1),J(e,!0)].filter(t=>!!t)))}function ke(){let e=process.argv[1];if(!e)return;let t=u(e);for(;t!==u(t);){if(g(s(t,"package.json")))return t;t=u(t)}}function ne(){let e=c();try{return z(e,G.W_OK),z(u(e),G.W_OK),!0}catch{return!1}}function re(e,t,n){let o=[c(),ke()].filter(i=>!!i).flatMap(i=>q(i));return De(e,t,n).some(i=>q(i).some(a=>{let p=a.endsWith(M)?a:`${a}${M}`;return o.some(d=>d.startsWith(p))}))}function it(e,t,n=e){let r=Z(),o=te(r,e,n,t);if(!(!o||!re(r,e,t)||!ne()))return o}function at(e,t,n=e){let r=Z(),o=Y(n);if(r==="bun-binary")return"Download from: https://github.com/earendil-works/pi/releases/latest";let i=te(r,e,o,t);return i?re(r,e,t)&&!ne()?`This installation is managed by a global ${r} install, but the install path is not writable. Update it yourself with: ${i.display}`:`This installation is not managed by a global ${r} install. Update it with the package manager, wrapper, or source checkout that provides it.`:`Update ${o.installSpec} using the package manager, wrapper, or source checkout that provides this installation.`}function Re(e){let t=e;for(;t!==u(t);){if(g(s(t,"package.json"))){let n=u(t);return K(t)==="dist"&&g(s(n,"package.json"))?n:t}t=u(t)}return e}function c(){let e=process.env.PI_PACKAGE_DIR;return e?_(e):h?u(process.execPath):Re(X)}function ct(){if(h)return s(c(),"theme");let e=c(),t=g(s(e,"src"))?"src":"dist";return s(e,t,"modes","interactive","theme")}function ut(){if(h)return s(c(),"export-html");let e=c(),t=g(s(e,"src"))?"src":"dist";return s(e,t,"core","export-html")}function Ue(){return s(c(),"package.json")}function dt(){return S(s(c(),"README.md"))}function pt(){return S(s(c(),"docs"))}function ft(){return S(s(c(),"examples"))}function lt(){return S(s(c(),"CHANGELOG.md"))}function Ae(){if(h)return s(c(),"assets");let e=c(),t=g(s(e,"src"))?"src":"dist";return s(e,t,"modes","interactive","assets")}function mt(e){return s(Ae(),e)}var V;function gt(){return V??=Q(new URL("vendor/quickjs.wasm",__cortexPackageRoot)),V}function Ce(e,t){if(e==="bun-binary")return"./src/extensions/codemode/worker.ts";if(e==="bundled-node")return new URL("./codemode-worker.js",t)}var H;function ht(){let e=h?"bun-binary":Ee?"bundled-node":"unbundled",t=Ce(e,new URL("vendor/pi/dist/config.js",__cortexPackageRoot).href);return e!=="bundled-node"||!(t instanceof URL)?t:(H??=new URL(`data:text/javascript;base64,${I(t).toString("base64")}`),H)}function xt(e=oe){if(h||!e)return;let t;try{t=JSON.parse(A(I(e,"utf-8")))}catch(n){return n.code==="ENOENT"?{kind:"removed"}:void 0}return t.version&&t.version!==$e?{kind:"updated",version:t.version}:void 0}var v={},oe;try{let e=Ue();v=JSON.parse(A(I(e,"utf-8"))),oe=e}catch(e){if(e.code!=="ENOENT")throw e}var se=v.piConfig?.name,bt=v.name||"@earendil-works/pi-coding-agent",D=se||"pi",Pt=se?D:"\u03C0",Ie=v.piConfig?.configDir||".pi",$e=v.version||"0.0.0",Ne=`${D.toUpperCase()}_CODING_AGENT_DIR`,wt=`${D.toUpperCase()}_CODING_AGENT_SESSION_DIR`;function Le(e){return _(e)}var We="https://pi.dev/session/";function _t(e){return`${process.env.PI_SHARE_VIEWER_URL||We}#${e}`}function b(){let e=process.env[Ne];return e?Le(e):s(C(),Ie,"agent")}function St(){return s(b(),"themes")}function vt(){return s(b(),"auth.json")}function yt(){return s(b(),"settings.json")}function Et(){return s(b(),"bin")}function Dt(){return s(b(),"sessions")}function kt(){return s(b(),`${D}-debug.log`)}export{Oe as a,w as b,je as c,qe as d,Ve as e,He as f,_ as g,U as h,Pe as i,Ke as j,Qe as k,we as l,A as m,h as n,Ee as o,Z as p,it as q,at as r,c as s,ct as t,ut as u,dt as v,pt as w,ft as x,lt as y,mt as z,gt as A,ht as B,xt as C,bt as D,D as E,Pt as F,Ie as G,$e as H,Ne as I,wt as J,Le as K,_t as L,b as M,St as N,vt as O,yt as P,Et as Q,Dt as R,kt as S};
@@ -1,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- function R(e){let t=e.split("*").map(r=>r.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${t}$`)}function k(e){let t=new Set(e.filter(n=>!n.includes("*"))),r=e.filter(n=>n.includes("*")).map(R);return n=>t.has(n)||r.some(o=>o.test(n))}var U="list_mcp_resources",x="list_mcp_resource_templates",_="read_mcp_resource",y=new Set([U,x,_]);function T(e){return e.startsWith("mcp__")||y.has(e)}var E=["codemode","deferred","direct","hidden"],$={"codemode-deferred":"codemode"},f=["localhost","127.0.0.1","[::1]"];function L(e){if(!URL.canParse(e))return!1;let t=new URL(e);return t.protocol==="http:"&&f.includes(t.hostname)&&t.search===""&&t.hash===""}var S=/^[A-Za-z0-9_-]+$/;function w(e){return`mcp__${e.replace(/-/g,"_")}`}function c(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function h(e){return c(e)&&Object.values(e).every(t=>typeof t=="string")}function O(e){if(e===void 0)return;if(!c(e))return"oauth must be an object";if(e.clientId!==void 0&&typeof e.clientId!="string")return"oauth.clientId must be a string";if(e.clientSecret!==void 0&&typeof e.clientSecret!="string")return"oauth.clientSecret must be a string";let t=e.callbackPort;if(t!==void 0&&(typeof t!="number"||!Number.isInteger(t)||t<1||t>65535))return"oauth.callbackPort must be a port number";if(e.callbackUrl!==void 0){if(typeof e.callbackUrl!="string"||!L(e.callbackUrl))return"oauth.callbackUrl must be an http URI on localhost, 127.0.0.1, or [::1] without query or fragment";let n=new URL(e.callbackUrl).port;if(n&&t!==void 0&&Number(n)!==t)return"oauth.callbackUrl and oauth.callbackPort name different ports"}if(e.scope!==void 0&&typeof e.scope!="string")return"oauth.scope must be a string";if(e.clientName!==void 0&&(typeof e.clientName!="string"||!e.clientName.trim()))return"oauth.clientName must be a non-empty string";if(e.clientRegistration!==void 0&&e.clientRegistration!=="dcr"){if(e.clientRegistration!=="cimd")return'oauth.clientRegistration must be "dcr" or "cimd"';if(e.clientId!==void 0||e.clientName!==void 0)return'oauth.clientRegistration "cimd" cannot be combined with oauth.clientId or oauth.clientName';let n=typeof e.callbackUrl=="string"?new URL(e.callbackUrl):void 0;if(n&&(n.hostname==="[::1]"||n.pathname!=="/callback"))return'oauth.clientRegistration "cimd" requires oauth.callbackUrl on localhost or 127.0.0.1 with path /callback'}let r=e.authServerMetadataUrl;if(r!==void 0){let n=typeof r=="string"&&URL.canParse(r)?new URL(r):void 0;if(!n||!(n.protocol==="https:"||n.protocol==="http:"&&f.includes(n.hostname)))return"oauth.authServerMetadataUrl must be an https URL, or http on localhost, 127.0.0.1, or [::1]"}}function m(e){return typeof e=="string"&&E.includes(e)}function b(e){return typeof e=="string"?$[e]??e:e}function P(e){let{exposure:t,toolExposure:r}=e,n={...e};return t!==void 0&&(n.exposure=b(t)),c(r)&&(n.toolExposure=Object.fromEntries(Object.entries(r).map(([o,i])=>[o,b(i)]))),n}function A(e,t){let r=e.toolExposure??{},n=r[t];if(n!==void 0)return n;for(let[o,i]of Object.entries(r))if(o.includes("*")&&R(o).test(t))return i;return e.exposure??"codemode"}function C(e,t){if(!S.test(e))return`invalid server name "${e}" (use letters, digits, "_" and "-")`;if(!c(t))return`server "${e}" must be an object`;let r=P(t),{type:n,exposure:o,enabled:i,timeout:a,toolExposure:d,description:p}=r,l=E.map(s=>`"${s}"`).join(", ");if(o!==void 0&&!m(o))return`server "${e}": exposure must be one of ${l}`;if(d!==void 0){if(!c(d))return`server "${e}": toolExposure must map tool names to exposures`;for(let[s,u]of Object.entries(d))if(!m(u))return`server "${e}": toolExposure "${s}" must be one of ${l}`}if(i!==void 0&&typeof i!="boolean")return`server "${e}": enabled must be a boolean`;if(p!==void 0&&typeof p!="string")return`server "${e}": description must be a string`;if(a!==void 0&&(typeof a!="number"||!(a>0)))return`server "${e}": timeout must be a positive number of seconds`;if(n==="sse")return`server "${e}": legacy SSE transport is not supported; use the streamable HTTP URL`;if(typeof r.url=="string"&&(n===void 0||n==="http"||n==="streamable-http")){if(!URL.canParse(r.url)||!/^https?:$/.test(new URL(r.url).protocol))return`server "${e}": url must be an http or https URL`;if(r.headers!==void 0&&!h(r.headers))return`server "${e}": headers must map names to strings`;let s=O(r.oauth);if(s)return`server "${e}": ${s}`;if(r.auth!==void 0){if(!c(r.auth)||typeof r.auth.provider!="string"||!r.auth.provider)return`server "${e}": auth.provider must be a provider name`;let u=new URL(r.url);if(u.protocol!=="https:"&&!f.includes(u.hostname))return`server "${e}": auth requires an https URL, or http on localhost, 127.0.0.1, or [::1]`}return r}return typeof r.command=="string"&&(n===void 0||n==="stdio")?r.args!==void 0&&!(Array.isArray(r.args)&&r.args.every(s=>typeof s=="string"))?`server "${e}": args must be an array of strings`:r.env!==void 0&&!h(r.env)?`server "${e}": env must map names to strings`:r.cwd!==void 0&&typeof r.cwd!="string"?`server "${e}": cwd must be a string`:r:`server "${e}" needs either "command" (stdio) or "url" (streamable HTTP)`}var g=class{servers=new Map;changeListener;register(t){this.servers.set(t.name,t),this.changeListener?.()}unregister(t,r){this.servers.get(t)?.extensionPath===r&&(this.servers.delete(t),this.changeListener?.())}get(t){return this.servers.get(t)}list(){return[...this.servers.values()].map(t=>({...t,config:structuredClone(t.config)}))}setChangeListener(t){this.changeListener=t}};export{k as a,U as b,x as c,_ as d,T as e,w as f,A as g,C as h,g as i};
@@ -1,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{d as c}from"./chunk-52T37Y47.js";import{d as a}from"./chunk-W5LGYSPZ.js";import{a as S,m as l}from"./chunk-J5DVLUKY.js";import{e as g}from"./chunk-WHC7AYZD.js";var u=g(S(),1),E=new Set(["CLAUDE_CODE_OAUTH_TOKEN_EXPIRES_AT"]);function O(n,t=process.env){let e={};u.config({path:n,processEnv:e});for(let r of E)delete e[r];u.populate(t,e)}var x="CORTEX_CHILD_EXIT";function I(n){return JSON.stringify(n)}function y(n){if(!n)return null;try{let t=JSON.parse(n);if(typeof t.uptimeMs!="number"||typeof t.backoffMs!="number")return null;let e=Number.isInteger(t.code)?t.code:null,r=typeof t.signal=="string"?t.signal.slice(0,20):null;return{code:e,signal:r,uptimeMs:Math.max(0,t.uptimeMs),backoffMs:Math.max(0,Math.round(t.backoffMs))}}catch{return null}}function M(n=process.env){let t=y(n[x]);t&&c({component:"server",kind:"childExit",errorName:"ChildExit",message:t.signal?`signal ${t.signal}`:`exit code ${t.code??"unknown"}`,stack:"",uptimeS:Math.round(t.uptimeMs/1e3),exit:{code:t.code,signal:t.signal,backoffMs:t.backoffMs}})}import{existsSync as b,readFileSync as h}from"node:fs";import*as d from"node:path";var p=d.join(l,"daemon-rebuild.json");function C(n){let t=(n.now??(()=>new Date))().toISOString();return{status:"running",reason:n.reason,current:null,steps:n.names.map(e=>({name:e,status:"pending",detail:null,startedAt:null,endedAt:null})),startedAt:t,updatedAt:t,endedAt:null,detail:null,daemonPid:n.daemonPid}}function f(n,t,e,r){return{...n,updatedAt:r,steps:n.steps.map(o=>o.name===t?{...o,...e}:o)}}function P(n,t,e=()=>new Date){let r=e().toISOString();return{...f(n,t,{status:"running",startedAt:r,endedAt:null},r),current:t}}function w(n,t,e,r=null,o=()=>new Date){let s=o().toISOString(),i=f(n,t,{status:e,detail:r,endedAt:s},s);return i.current!==t?i:{...i,current:i.steps.filter(m=>m.status==="running").at(-1)?.name??null}}function L(n,t,e=null,r=()=>new Date){let o=r().toISOString();return{...n,status:t,current:null,detail:e,updatedAt:o,endedAt:o,steps:n.steps.map(s=>s.status==="pending"?{...s,status:"skipped"}:s)}}function A(n){if(!n||typeof n!="object")return!1;let t=n;return typeof t.status=="string"&&typeof t.reason=="string"&&typeof t.startedAt=="string"&&Array.isArray(t.steps)}function T(n=p){try{if(!b(n))return null;let t=JSON.parse(h(n,"utf8"));return A(t)?t:null}catch{return null}}function F(n,t=p){try{return a(t,JSON.stringify(n,null,2)),!0}catch{return!1}}export{O as a,x as b,I as c,M as d,C as e,P as f,w as g,L as h,T as i,F as j};
@@ -1,9 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{c as h,e as C}from"./chunk-WHC7AYZD.js";var p=h(r=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0});r.Allow=r.ALL=r.COLLECTION=r.ATOM=r.SPECIAL=r.INF=r._INFINITY=r.INFINITY=r.NAN=r.BOOL=r.NULL=r.OBJ=r.ARR=r.NUM=r.STR=void 0;r.STR=1;r.NUM=2;r.ARR=4;r.OBJ=8;r.NULL=16;r.BOOL=32;r.NAN=64;r.INFINITY=128;r._INFINITY=256;r.INF=r.INFINITY|r._INFINITY;r.SPECIAL=r.NULL|r.BOOL|r.INF|r.NAN;r.ATOM=r.STR|r.NUM|r.SPECIAL;r.COLLECTION=r.ARR|r.OBJ;r.ALL=r.ATOM|r.COLLECTION;r.Allow={STR:r.STR,NUM:r.NUM,ARR:r.ARR,OBJ:r.OBJ,NULL:r.NULL,BOOL:r.BOOL,NAN:r.NAN,INFINITY:r.INFINITY,_INFINITY:r._INFINITY,INF:r.INF,SPECIAL:r.SPECIAL,ATOM:r.ATOM,COLLECTION:r.COLLECTION,ALL:r.ALL};r.default=r.Allow});var y=h(a=>{"use strict";var E=a&&a.__createBinding||(Object.create?(function(t,n,u,e){e===void 0&&(e=u);var i=Object.getOwnPropertyDescriptor(n,u);(!i||("get"in i?!n.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return n[u]}}),Object.defineProperty(t,e,i)}):(function(t,n,u,e){e===void 0&&(e=u),t[e]=n[u]})),R=a&&a.__exportStar||function(t,n){for(var u in t)u!=="default"&&!Object.prototype.hasOwnProperty.call(n,u)&&E(n,t,u)};Object.defineProperty(a,"__esModule",{value:!0});a.Allow=a.MalformedJSON=a.PartialJSON=a.parseJSON=a.parse=void 0;var c=p();Object.defineProperty(a,"Allow",{enumerable:!0,get:function(){return c.Allow}});R(p(),a);var I=class extends Error{};a.PartialJSON=I;var A=class extends Error{};a.MalformedJSON=A;function L(t,n=c.Allow.ALL){if(typeof t!="string")throw new TypeError(`expecting str, got ${typeof t}`);if(!t.trim())throw new Error(`${t} is empty`);return B(t.trim(),n)}a.parseJSON=L;var B=(t,n)=>{let u=t.length,e=0,i=s=>{throw new I(`${s} at position ${e}`)},N=s=>{throw new A(`${s} at position ${e}`)},o=()=>(O(),e>=u&&i("Unexpected end of input"),t[e]==='"'?d():t[e]==="{"?J():t[e]==="["?m():t.substring(e,e+4)==="null"||c.Allow.NULL&n&&u-e<4&&"null".startsWith(t.substring(e))?(e+=4,null):t.substring(e,e+4)==="true"||c.Allow.BOOL&n&&u-e<4&&"true".startsWith(t.substring(e))?(e+=4,!0):t.substring(e,e+5)==="false"||c.Allow.BOOL&n&&u-e<5&&"false".startsWith(t.substring(e))?(e+=5,!1):t.substring(e,e+8)==="Infinity"||c.Allow.INFINITY&n&&u-e<8&&"Infinity".startsWith(t.substring(e))?(e+=8,1/0):t.substring(e,e+9)==="-Infinity"||c.Allow._INFINITY&n&&1<u-e&&u-e<9&&"-Infinity".startsWith(t.substring(e))?(e+=9,-1/0):t.substring(e,e+3)==="NaN"||c.Allow.NAN&n&&u-e<3&&"NaN".startsWith(t.substring(e))?(e+=3,NaN):_()),d=()=>{let s=e,f=!1;for(e++;e<u&&(t[e]!=='"'||f&&t[e-1]==="\\");)f=t[e]==="\\"?!f:!1,e++;if(t.charAt(e)=='"')try{return JSON.parse(t.substring(s,++e-Number(f)))}catch(l){N(String(l))}else if(c.Allow.STR&n)try{return JSON.parse(t.substring(s,e-Number(f))+'"')}catch{return JSON.parse(t.substring(s,t.lastIndexOf("\\"))+'"')}i("Unterminated string literal")},J=()=>{e++,O();let s={};try{for(;t[e]!=="}";){if(O(),e>=u&&c.Allow.OBJ&n)return s;let f=d();O(),e++;try{let l=o();s[f]=l}catch(l){if(c.Allow.OBJ&n)return s;throw l}O(),t[e]===","&&e++}}catch{if(c.Allow.OBJ&n)return s;i("Expected '}' at end of object")}return e++,s},m=()=>{e++;let s=[];try{for(;t[e]!=="]";)s.push(o()),O(),t[e]===","&&e++}catch{if(c.Allow.ARR&n)return s;i("Expected ']' at end of array")}return e++,s},_=()=>{if(e===0){t==="-"&&N("Not sure what '-' is");try{return JSON.parse(t)}catch(f){if(c.Allow.NUM&n)try{return JSON.parse(t.substring(0,t.lastIndexOf("e")))}catch{}N(String(f))}}let s=e;for(t[e]==="-"&&e++;t[e]&&",]}".indexOf(t[e])===-1;)e++;e==u&&!(c.Allow.NUM&n)&&i("Unterminated number literal");try{return JSON.parse(t.substring(s,e))}catch{t.substring(s,e)==="-"&&i("Not sure what '-' is");try{return JSON.parse(t.substring(s,t.lastIndexOf("e")))}catch(l){N(String(l))}}},O=()=>{for(;e<u&&`
5
- \r `.includes(t[e]);)e++};return o()},F=L;a.parse=F});var b=C(y(),1),P=new Set(['"',"\\","/","b","f","n","r","t"]);function M(t){let n=t.codePointAt(0);return n!==void 0&&n>=0&&n<=31}function x(t){switch(t){case"\b":return"\\b";case"\f":return"\\f";case`
6
- `:return"\\n";case"\r":return"\\r";case" ":return"\\t";default:return`\\u${t.codePointAt(0)?.toString(16).padStart(4,"0")??"0000"}`}}function w(t){let n="",u=!1;for(let e=0;e<t.length;e++){let i=t[e];if(!u){n+=i,i==='"'&&(u=!0);continue}if(i==='"'){n+=i,u=!1;continue}if(i==="\\"){let N=t[e+1];if(N===void 0){n+="\\\\";continue}if(N==="u"){let o=t.slice(e+2,e+6);if(/^[0-9a-fA-F]{4}$/.test(o)){n+=`\\u${o}`,e+=5;continue}}if(P.has(N)){n+=`\\${N}`,e+=1;continue}n+="\\\\";continue}n+=M(i)?x(i):i}return n}function T(t){try{return JSON.parse(t)}catch(n){let u=w(t);if(u!==t)return JSON.parse(u);throw n}}function $(t){if(!t?.trim())return{arguments:{}};try{let n=T(t);if(typeof n!="object"||n===null||Array.isArray(n))throw new Error("Tool arguments must be a JSON object");return{arguments:n}}catch(n){return{arguments:{},argumentsError:`${n instanceof Error?n.message:String(n)}
7
-
8
- Received arguments:
9
- ${t}`}}}function v(t){if(!t||t.trim()==="")return{};try{return T(t)}catch{try{return(0,b.parse)(t)??{}}catch{try{return(0,b.parse)(w(t))??{}}catch{return{}}}}}export{w as a,T as b,$ as c,v as d};
@@ -1,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{k as l}from"./chunk-CQLH4UVX.js";import{a as d,h as p}from"./chunk-OE4KH3NJ.js";import*as E from"node:http";function O(e,o,t,n={},s=183e4){let a=t===void 0?null:JSON.stringify(t),T=new URL(o);return new Promise((_,h)=>{let i=E.request(b(e,T,a,n,s),c=>{let u=[];c.on("data",f=>u.push(Buffer.from(f))),c.on("end",()=>_({status:c.statusCode??0,body:k(Buffer.concat(u).toString("utf8"))}))});i.on("error",h),i.on("timeout",()=>i.destroy(new Error(`Loopback request timed out after ${s}ms`))),a!==null&&i.write(a),i.end()})}function b(e,o,t,n,s){return{hostname:o.hostname,port:o.port,path:`${o.pathname}${o.search}`,method:e,headers:t===null?n:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(t),...n},timeout:s}}function k(e){if(!e)return null;try{return JSON.parse(e)}catch{return{_raw:e}}}var m=3001;function r(e){return e===void 0||e===""?null:e}function S(e,o){let t=parseInt(e??"",10);return Number.isFinite(t)&&t>0?t:o}function R(e){let o=e.CORTEX_BACKEND,t=r(e.CORTEX_MODEL);return o!=="claude"&&o!=="pi"||!t?null:{backend:o,model:t,provider:o==="pi"?r(e.CORTEX_PROVIDER):null,thinking:r(e.CORTEX_THINKING),mode:e.CORTEX_MODE??""}}function U(e=process.env){return{channel:r(e.SLACK_CHANNEL)??r(e.FEISHU_CHANNEL),sessionId:r(e.CORTEX_SESSION_ID),selection:R(e),project:r(e.CORTEX_PROJECT),backend:r(e.CORTEX_BACKEND),claudeModel:r(e.CORTEX_CLAUDE_MODEL),subagentPiModels:l(e.CORTEX_SUBAGENT_PI_MODELS),subagentClaudeModels:l(e.CORTEX_SUBAGENT_CLAUDE_MODELS),scheduleTaskId:r(e.CORTEX_SCHEDULE_TASK_ID),callbackSource:r(e.CORTEX_CALLBACK_SOURCE),webhookBaseUrl:`http://127.0.0.1:${S(e.WEBHOOK_PORT,m)}`,webhookToken:e.CORTEX_WEBHOOK_TOKEN||"",slackBotToken:r(e.SLACK_BOT_TOKEN),toolAllowlist:p(e[d])}}function L(e){return{"x-cortex-token":e.webhookToken}}function I(e){return e.sessionId?e.sessionId:e.channel?.startsWith("web:")?e.channel.slice(4):null}var w=async(e,o)=>{let{body:t}=await O("POST",`${e.webhookBaseUrl}/webhook/board`,{sessionId:o,action:"status"},L(e));if(!t?.success)throw new Error(t?.error||"board status failed");let n=t.data;return n?{id:n.id,title:n.title,dir:n.dir??null}:null};async function A(e,o=w){let t={channel:e.channel,sessionId:e.sessionId,model:e.selection?.model??null,thinking:e.selection?.thinking??null,mode:e.selection?.mode??null,project:e.project,backend:e.backend,scheduleTaskId:e.scheduleTaskId,callbackSource:e.callbackSource},n=I(e);if(n)try{t.board=await o(e,n)}catch{}return t}function X(e,o){e.tool("cortex_context","Get current session identity, backend, model, thinking, mode, project, bound board and trigger context.",{},{readOnlyHint:!0},async()=>{try{let t=await A(o),{channel:n,...s}=t;return{content:[{type:"text",text:JSON.stringify(s,null,2)}]}}catch(t){return{content:[{type:"text",text:`Failed to resolve context: ${t.message}`}],isError:!0}}})}export{O as a,m as b,U as c,L as d,I as e,A as f,X as g};
@@ -1,52 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{d as He,e as Ke,f as Ve,g as Je,h as g,i as Be,l as We,w as Ye}from"./chunk-2ZNLUY2U.js";import{a as qe,b as Xe,c as ze,d as Qe,e as Ze,f as et,i as I,j as U}from"./chunk-PZMXHA6X.js";import{a as pe,b as fe,d as me}from"./chunk-REBNWCKI.js";import{a as De,b as _e,c as Re,d as je,e as Te,f as Oe,i as Ne,j as Fe,k as Le,l as Me,m as Ge}from"./chunk-MFAEUHMV.js";import{A as Ee,C as _,w as Ae,x as Pe,z as b}from"./chunk-ASYQHJVQ.js";import{G as $e,f as ye}from"./chunk-O3JW2F7D.js";import{F as ke,G as Se,m as ve,o as Ce,p as we,q as be}from"./chunk-TZFLHVOQ.js";import{a as Ie}from"./chunk-5NRGVROY.js";import{a as P}from"./chunk-YHIWOGVL.js";import{a as ge}from"./chunk-QEOFEETJ.js";import{b as ue,c as ce,h as de}from"./chunk-SUFW24P4.js";import{a as R,b as f,c as Ue}from"./chunk-PMG4YGDU.js";import{a as w,b as xe,c as A,e as G}from"./chunk-KENCMLRE.js";import{a as M}from"./chunk-PFMEUFJ7.js";import{d as ne}from"./chunk-W5LGYSPZ.js";import{e as l}from"./chunk-E7ZMYIY6.js";import{e as le}from"./chunk-NAA7GF6Q.js";import{b as he,h as E}from"./chunk-QWAQHHRS.js";import{a as Ot,c as re,f as C,j as D,k as ie,l as oe,m as se,p as h,q as L,r as ae}from"./chunk-J5DVLUKY.js";import{e as Tt}from"./chunk-WHC7AYZD.js";import{fork as T}from"child_process";import*as d from"path";import*as Rt from"net";import{fileURLToPath as Un}from"url";import{existsSync as m,readdirSync as Hn,readFileSync as Q,unlinkSync as Z}from"fs";var rt=Tt(Ot(),1);import*as c from"node:fs";import*as u from"node:path";import*as nt from"node:http";import{fileURLToPath as Nt}from"node:url";function Ft(e){if(typeof e!="string")return;let t=e.trim();if(!(!t||t==="null"||t==="undefined"))return t}function Lt(e){let t=e.match(/^v?(\d+)/);return t?Number(t[1]):0}function Mt(e){let t=u.join(e.paths.CONFIG_DIR,".env"),n={},r=e.readText(t);if(r!=null)try{n=e.parseDotenv(r)}catch{n={}}return i=>Ft(e.env[i]??n[i])}function Gt(e){let t=e.defaultSelection()?.backend??"claude";return t==="pi"?{id:"backend-runtime",label:"Backend runtime",status:"pass",detail:"backend: pi runs in-process from the bundled SDK (no CLI needed)"}:e.commandExists("claude")?{id:"backend-runtime",label:"Backend runtime",status:"pass",detail:`claude found on PATH (backend: ${t})`}:{id:"backend-runtime",label:"Backend runtime",status:"warn",detail:`claude not on PATH (backend: ${t})`,hint:"Install/login the claude CLI"}}function Ut(e){return e.commandExists("git")?{id:"git",label:"git",status:"pass",detail:"usable on PATH"}:(e.platform??process.platform)==="win32"?{id:"git",label:"git",status:"fail",detail:"unavailable",hint:"Install Git for Windows \u2014 shell tools require Git Bash"}:{id:"git",label:"git",status:"warn",detail:"unavailable (optional)",hint:"Install Git to enable version history and Git-sourced extensions"}}function Ht(e){let t=[],n=Lt(e.nodeVersion);t.push(n>=e.requiredNodeMajor?{id:"node-version",label:"Node version",status:"pass",detail:`${e.nodeVersion} (>=${e.requiredNodeMajor})`}:{id:"node-version",label:"Node version",status:"warn",detail:`${e.nodeVersion} \u2014 Cortex requires Node >=${e.requiredNodeMajor}`,hint:"Upgrade Node.js"}),t.push(Ut(e)),t.push(Gt(e));let r=u.join(e.paths.STORE_DIR,u.basename(h)),i=e.fileExists(r)?e.readText(r):null,o=i?Number(i.trim()):NaN;return Number.isFinite(o)&&e.pidAlive(o)?t.push({id:"daemon",label:"Daemon",status:"pass",detail:`running (pid ${o})`}):t.push({id:"daemon",label:"Daemon",status:"skip",detail:"not running",hint:"Start with `cortex daemon`"}),{title:"Runtime & Process",checks:t}}function Kt(e,t){let n=[];for(let[r,i]of Object.entries(t.paths))t.fileExists(i)?t.isWritable(i)||n.push(`${r} not writable (${i})`):n.push(`${r} missing (${i})`);e.push(n.length===0?{id:"dirs",label:"Data directories",status:"pass",detail:"present and writable"}:{id:"dirs",label:"Data directories",status:"fail",detail:n.join("; "),hint:"run `cortex doctor --fix` or `cortex init`",fixable:!0})}function Vt(e,t,n){let r=u.join(t.paths.CONFIG_DIR,".env");e.push(t.fileExists(r)?{id:"env-file",label:".env file",status:"pass",detail:r}:{id:"env-file",label:".env file",status:"fail",detail:`missing (${r})`,hint:"run `cortex init`"});let i=[ue,ce].filter(o=>!n(o));e.push(i.length===0?{id:"auth-tokens",label:"Auth tokens",status:"pass",detail:"client + webhook tokens set"}:{id:"auth-tokens",label:"Auth tokens",status:"fail",detail:`missing: ${i.join(", ")}`,hint:"run `cortex doctor --fix` to generate",fixable:!0})}function Jt(e){let t=e.defaultSelection();return t?.backend==="claude"&&(t.mode||"api")!=="plan"}function Bt(e,t,n){let r=t("ANTHROPIC_API_KEY");return n&&(!r||r===E)&&Jt(e)}function Wt(e,t,n){let r=t("ANTHROPIC_API_KEY");if(n)e.push({id:"anthropic-key",label:"Anthropic API key",status:"pass",detail:"managed by healthy gateway"});else if(r){let i=r===E?"managed by gateway":"set";e.push({id:"anthropic-key",label:"Anthropic API key",status:"pass",detail:i})}else e.push({id:"anthropic-key",label:"Anthropic API key",status:"warn",detail:"not set \u2014 required for API mode (plan/subscription mode can ignore)",hint:"set ANTHROPIC_API_KEY in .env or run `cortex init`"})}function Yt(e,t){let{CONFIG_DIR:n,STORE_DIR:r}=t.paths,i=u.join(r,"agent-state.json"),o=t.fileExists(i)?"agent-state.json":"mode.json";tn(e,t,t.fileExists(i)?i:u.join(r,"mode.json"),"mode-json",o,"warn"),e.push(nn(t,u.join(n,"models.json")));let s=u.join(n,"mcp-config.json");t.fileExists(s)?it(t.readText(s))?e.push({id:"mcp-config",label:"mcp-config.json",status:"pass",detail:"valid"}):e.push({id:"mcp-config",label:"mcp-config.json",status:"warn",detail:"invalid JSON",hint:"run `cortex doctor --fix` to regenerate",fixable:!0}):e.push({id:"mcp-config",label:"mcp-config.json",status:"warn",detail:`missing (${s})`,hint:"run `cortex doctor --fix` to regenerate",fixable:!0})}var H="See docs/backends.md#remote-login",qt=new Set(["expired","logged-out"]),Xt="Reinstall the Cortex server package \u2014 the PI SDK ships with it";async function zt(e){let t=e.resolvePiSdk();if(!t)return{id:"pi-runtime",label:"PI runtime",status:"warn",detail:`bundled PI SDK not resolvable (${b})`,hint:Xt};try{let n=await e.loadPiRuntime();if(n.available&&typeof n.runtime.login=="function"){let r=n.version??t.version,i=r?` ${r}`:"";return{id:"pi-runtime",label:"PI runtime",status:"pass",detail:`in-process SDK ${t.package}${i}; login export found`}}}catch{}return{id:"pi-runtime",label:"PI runtime",status:"warn",detail:"bundled PI runtime or login export unavailable",hint:H}}function tt(e,t){return t&&e.backend==="claude"&&e.provider==="anthropic"&&e.state==="logged-out"}function Qt(e,t){let n=e.accounts.filter(a=>a.inUse),r=n.filter(a=>tt(a,t)),i=n.filter(a=>qt.has(a.state)&&!tt(a,t)),o=[...new Set(i.map(a=>a.provider))].sort();if(i.length>0)return{id:"backend-auth",label:"Backend authentication",status:"warn",detail:`${n.length} in use; ${i.length} expired or logged out: ${o.join(", ")}`,hint:H};let s=r.length>0?"; gateway-backed: anthropic":"";return{id:"backend-auth",label:"Backend authentication",status:"pass",detail:`${n.length} in use; 0 expired or logged out${s}`}}async function Zt(e,t){try{return Qt(await e.getAuthStatus(),t)}catch{return{id:"backend-auth",label:"Backend authentication",status:"warn",detail:"authentication summary unavailable",hint:H}}}async function en(e,t,n){let r=[],i=Bt(e,t,n);return Kt(r,e),Vt(r,e,t),Wt(r,t,i),Yt(r,e),r.push(...await Promise.all([zt(e),Zt(e,i)])),{title:"Backend Install / Login",checks:r}}function it(e){if(e==null)return!1;try{return JSON.parse(e),!0}catch{return!1}}function tn(e,t,n,r,i,o){if(!t.fileExists(n)){e.push({id:r,label:i,status:o,detail:`missing (${n})`});return}e.push(it(t.readText(n))?{id:r,label:i,status:"pass",detail:"valid"}:{id:r,label:i,status:o,detail:"invalid JSON"})}function nn(e,t){let n={id:"models",label:"models.json"};if(!e.fileExists(t))return{...n,status:"warn",detail:`missing (${t})`,hint:"run `cortex setup-gateway`"};try{let r=JSON.parse(e.readText(t)??"");if(Se(r?.default),!Array.isArray(r?.favorites))throw new Error("missing `favorites` array");return r.favorites.forEach(ke),{...n,status:"pass",detail:`default: ${r.default.model}; favorites: ${r.favorites.length}`}}catch(r){return{...n,status:"fail",detail:r.message,hint:"re-run `cortex setup-gateway`"}}}function rn(e,t){let n=[],i=(t("CORTEX_PLATFORM")??"slack").split(",").map(o=>o.trim().toLowerCase()).filter(Boolean);n.push({id:"platform",label:"Platform",status:"pass",detail:`configured: ${i.join(", ")||"(none)"}`});for(let o of i)if(o==="slack"){let s=[],a=t("SLACK_BOT_TOKEN"),p=t("SLACK_SIGNING_SECRET"),F=t("SLACK_APP_TOKEN");a?a.startsWith("xoxb-")||s.push("SLACK_BOT_TOKEN should start with xoxb-"):s.push("SLACK_BOT_TOKEN missing"),p||s.push("SLACK_SIGNING_SECRET missing"),F?F.startsWith("xapp-")||s.push("SLACK_APP_TOKEN should start with xapp-"):s.push("SLACK_APP_TOKEN missing"),n.push(s.length===0?{id:"slack-creds",label:"Slack credentials",status:"pass",detail:"bot / signing / app tokens present"}:{id:"slack-creds",label:"Slack credentials",status:"fail",detail:s.join("; "),hint:"set Slack tokens in .env (see `cortex init`)"})}else if(o==="feishu"){let s=[];t("FEISHU_APP_ID")||s.push("FEISHU_APP_ID missing"),t("FEISHU_APP_SECRET")||s.push("FEISHU_APP_SECRET missing"),n.push(s.length===0?{id:"feishu-creds",label:"Feishu credentials",status:"pass",detail:"app id / secret present"}:{id:"feishu-creds",label:"Feishu credentials",status:"fail",detail:s.join("; "),hint:"set FEISHU_APP_ID / FEISHU_APP_SECRET in .env"})}else o==="test"?n.push({id:"test-platform",label:"Test platform",status:"skip",detail:"mock adapter (test only)"}):n.push({id:`platform-${o}`,label:`Platform: ${o}`,status:"warn",detail:"unknown platform name"});return{title:"Messaging Platform",checks:n}}function on(e,t,n){let r=[],i=u.join(e.aistatusDir,"gateway.yaml"),o=e.fileExists(i),s=new URL(e.gatewayUrl??D.url).host,a=D.home?i:"~/.aistatus/gateway.yaml";r.push(o?{id:"gateway-config",label:"Gateway config",status:"pass",detail:i}:{id:"gateway-config",label:"Gateway config",status:"skip",detail:`not configured (no ${a})`,hint:"run `cortex setup-gateway` if you use the gateway"});let p=t("ANTHROPIC_API_KEY")===E||o;return n?r.push({id:"gateway-health",label:"Gateway health",status:"pass",detail:`responding at ${s}`}):p?r.push({id:"gateway-health",label:"Gateway health",status:"fail",detail:`no response at ${s}/status`,hint:"check gateway.log or restart Cortex (the server auto-starts the gateway)"}):r.push({id:"gateway-health",label:"Gateway health",status:"skip",detail:"not running (not required for current backend)"}),{title:"Gateway",checks:r}}async function K(e){let t=Mt(e),n=await e.probeGateway(),r=[Ht(e),await en(e,t,n),rn(e,t),on(e,t,n)],i={pass:0,warn:0,fail:0,skip:0};for(let o of r)for(let s of o.checks)i[s.status]++;return{sections:r,counts:i,ok:i.fail===0}}async function ot(e,t,n){let r=new Map;for(let s of e.sections)for(let a of s.checks)a.fixable&&(a.status==="fail"||a.status==="warn")&&r.set(a.id,a);let i=[],o=u.join(t.paths.CONFIG_DIR,".env");if(r.has("dirs")){for(let s of[t.paths.DATA_DIR,t.paths.CONFIG_DIR,t.paths.STORE_DIR])n.mkdirp(s);i.push({id:"dirs",label:"Data directories",applied:!0,detail:"created missing directories"})}if(r.has("auth-tokens")){n.ensureEnvFile(o);let s=n.ensureAuthTokens(o);i.push({id:"auth-tokens",label:"Auth tokens",applied:s.length>0,detail:s.length>0?`generated: ${s.join(", ")}`:"already present"})}return r.has("mcp-config")&&(n.regenerateMcpConfig(),i.push({id:"mcp-config",label:"mcp-config.json",applied:!0,detail:"regenerated"})),i}function sn(e){if(e==="git")return ge();let t=process.env.PATH||"",n=process.platform==="win32"?(process.env.PATHEXT||".EXE;.CMD;.BAT").split(";"):[""];for(let r of t.split(u.delimiter))if(r)for(let i of n){let o=u.join(r,e+i);try{if(c.existsSync(o))return!0}catch{}}return!1}function an(){let e;try{e=u.dirname(Nt(import.meta.resolve(b)))}catch{return null}for(;;){try{let n=JSON.parse(c.readFileSync(u.join(e,"package.json"),"utf8"));if(n?.name===b)return{package:b,version:typeof n.version=="string"?n.version:null}}catch{}let t=u.dirname(e);if(t===e)return{package:b,version:null};e=t}}function ln(){return new Promise(e=>{let t=nt.get(`${D.url}/status`,{timeout:5e3},n=>{n.resume(),e(n.statusCode===200)});t.on("error",()=>e(!1)),t.on("timeout",()=>{t.destroy(),e(!1)})})}function st(){return{env:process.env,paths:{DATA_DIR:C,CONFIG_DIR:oe,STORE_DIR:se},aistatusDir:ie,gatewayUrl:D.url,nodeVersion:process.version,requiredNodeMajor:20,fileExists:e=>{try{return c.existsSync(e)}catch{return!1}},isWritable:e=>{try{return c.accessSync(e,c.constants.W_OK),!0}catch{return!1}},readText:e=>{try{return c.readFileSync(e,"utf8")}catch{return null}},parseDotenv:e=>(0,rt.parse)(e),commandExists:sn,pidAlive:w,probeGateway:ln,resolvePiSdk:an,loadPiRuntime:()=>Ee(),getAuthStatus:()=>_(),defaultSelection:un}}function un(){try{return $e()}catch{return null}}function at(){return{mkdirp:e=>{c.mkdirSync(e,{recursive:!0})},ensureEnvFile:e=>{c.existsSync(e)||(c.mkdirSync(u.dirname(e),{recursive:!0}),c.writeFileSync(e,""))},ensureAuthTokens:e=>de({envPath:e}).generated,regenerateMcpConfig:()=>ye()}}function cn(){return R({name:"cortex doctor",description:"Health-check the Cortex installation \u2014 runtime, backend/login, messaging platform, gateway.",usage:"cortex doctor [options]",options:[{flag:"--fix",description:"Apply safe, idempotent repairs (generate missing tokens, create dirs, rebuild mcp-config)"},{flag:"--json",description:"Emit the report as JSON"},{flag:"--help, -h",description:"Show this help"}],examples:[{description:"Run a read-only diagnosis",command:"cortex doctor"},{description:"Diagnose and auto-repair fixable issues",command:"cortex doctor --fix"},{description:"Machine-readable output",command:"cortex doctor --json"}]})}var dn={pass:"[OK] ",warn:"[WARN]",fail:"[FAIL]",skip:"[--] "};function pn(e,t){let n=["Cortex Doctor",""];for(let s of e.sections){n.push(s.title);for(let a of s.checks)n.push(` ${dn[a.status]} ${a.label} \u2014 ${a.detail}`),a.hint&&(a.status==="fail"||a.status==="warn")&&n.push(` \u21B3 ${a.hint}`);n.push("")}if(t.length>0){n.push("Fixes applied:");for(let s of t)n.push(` ${s.applied?"[OK] ":"[--] "} ${s.label} \u2014 ${s.detail}`);n.push("")}let{pass:r,warn:i,fail:o}=e.counts;return n.push(`Summary: ${r} passed, ${i} warning${i===1?"":"s"}, ${o} failed`),(o>0||i>0)&&e.sections.some(a=>a.checks.some(p=>p.fixable&&(p.status==="fail"||p.status==="warn")))&&n.push("Run `cortex doctor --fix` to auto-repair fixable issues."),n.join(`
5
- `).trimEnd()+`
6
- `}async function lt(e,t){if(e.includes("--help")||e.includes("-h"))return{exitCode:0,stdout:cn(),stderr:""};let n=e.includes("--json"),r=e.includes("--fix"),i=t?.diag??st(),o=t?.fix??at(),s=await K(i),a=[];r&&(a=await ot(s,i,o),s=await K(i));let p=n?JSON.stringify({...s,fixes:r?a:void 0},null,2)+`
7
- `:pn(s,a);return{exitCode:s.ok?0:1,stdout:p,stderr:""}}var ut=["list","add","remove"];function fn(){return{validValues:l("provider.cli.validValues"),hint:l("provider.cli.hint")}}function x(e,t){return{exitCode:1,stdout:"",stderr:f(e,{...t,labels:fn()})}}function ct(){return R({name:"cortex auth provider",description:l("provider.cli.description"),usage:"cortex auth provider <list|add|remove> [options]",commands:[{name:"list",description:l("provider.cli.listDescription")},{name:"add",description:l("provider.cli.addDescription")},{name:"remove",description:l("provider.cli.removeDescription")}],options:[{flag:"--name <name>",description:l("provider.cli.nameDescription")},{flag:"--api <api>",description:`${l("provider.cli.apiDescription")} (${P.join(" | ")})`},{flag:"--url <url>",description:l("provider.cli.urlDescription")},{flag:"--key <key|->",description:l("provider.cli.keyDescription")},{flag:"--model <id>",description:l("provider.cli.modelDescription")},{flag:"--dry-run",description:l("provider.cli.dryRunDescription")},{flag:"--json",description:l("provider.cli.jsonDescription")},{flag:"--help, -h",description:l("provider.cli.helpDescription")}],examples:[{description:l("provider.cli.exampleAdd"),command:"cortex auth provider add --name my-vllm --api anthropic-messages --url http://127.0.0.1:8100 --model Model-27B"},{description:l("provider.cli.exampleAddPiped"),command:"pass show my-endpoint | cortex auth provider add --name my-proxy --api openai-completions --url https://proxy.example.com/v1 --model small --key -"},{description:l("provider.cli.exampleList"),command:"cortex auth provider list --json"},{description:l("provider.cli.exampleRemove"),command:"cortex auth provider remove --name my-vllm --dry-run"}],labels:{usage:l("cmd.auth.cli.helpUsage"),commands:l("cmd.auth.cli.helpCommands"),options:l("cmd.auth.cli.helpOptions"),examples:l("cmd.auth.cli.helpExamples")}})}var mn=new Set(["--name","--api","--url","--key"]);function hn(e){let t=new Map,n=[],r=!1,i=!1;for(let o=0;o<e.length;o+=1){let s=e[o];if(s==="--json"){r=!0;continue}if(s==="--dry-run"){i=!0;continue}if(s==="--model"||mn.has(s)){let a=e[o+1];if(a===void 0||a.startsWith("--"))return x(l("provider.cli.flagNeedsValue",{flag:s}),{hint:"cortex auth provider --help"});o+=1,s==="--model"?n.push(a):t.set(s,a);continue}return x(l("provider.cli.unknownFlag",{flag:s}),{validValues:["--name","--api","--url","--key","--model","--dry-run","--json"],hint:"cortex auth provider --help"})}return{values:t,models:n,json:r,dryRun:i}}function V(e){return l(`provider.issue.${e}`)}function gn(e){return e.routed?l("provider.cli.listItem",{name:e.name,api:e.api,upstream:e.upstreamUrl??""}):l("provider.cli.listItemUnrouted",{name:e.name,api:e.api})}function xn(e,t){let n=Re(t);return e.json?{exitCode:0,stdout:JSON.stringify({ok:!0,providers:n},null,2),stderr:""}:{exitCode:0,stdout:n.length===0?l("provider.cli.listEmpty"):n.map(gn).join(`
8
- `),stderr:""}}function yn(e,t){let n=e.values.get("--key");return n===void 0?void 0:n!=="-"?n:(t.readSecret??Ue)().trim()}function vn(e,t,n){for(let s of["--name","--api","--url"])if(!e.values.has(s))return x(l("provider.cli.missingFlag",{flag:s}),{hint:"cortex auth provider add --help"});let r=e.values.get("--api");if(!P.includes(r))return x(V("api-invalid"),{validValues:[...P],hint:"cortex auth provider add --help"});let i=Te(t,{name:e.values.get("--name"),api:r,upstreamUrl:e.values.get("--url"),apiKey:yn(e,n),models:e.models.map(s=>({id:s}))});return i.ok===!1?x(i.errors.map(V).join(`
9
- `),{hint:"cortex auth provider add --help"}):{exitCode:0,stdout:e.json?JSON.stringify({ok:!0,provider:i.provider},null,2):l("provider.cli.added",{name:i.provider.name,upstream:i.provider.upstreamUrl??""}),stderr:""}}function Cn(e,t){let n=e.values.get("--name");if(!n)return x(l("provider.cli.missingFlag",{flag:"--name"}),{hint:"cortex auth provider remove --help"});let r=je(t,n);if(!r)return x(l("provider.cli.notFound",{name:n}),{hint:"cortex auth provider list"});if(e.dryRun)return{exitCode:0,stdout:JSON.stringify({dry_run:!0,would_remove:r},null,2),stderr:""};let i=Oe(t,n);return i.ok===!1?x(i.errors.map(V).join(`
10
- `),{hint:"cortex auth provider list"}):{exitCode:0,stdout:e.json?JSON.stringify({ok:!0,name:n},null,2):l("provider.cli.removed",{name:n}),stderr:""}}function dt(e,t,n={}){if(e.length===0||e[0]==="--help"||e[0]==="-h")return{exitCode:0,stdout:ct(),stderr:""};let r=e[0];if(!ut.includes(r))return x(l("provider.cli.unknownSubcommand",{command:r}),{validValues:[...ut],hint:"cortex auth provider --help"});let i=e.slice(1);if(i.includes("--help")||i.includes("-h"))return{exitCode:0,stdout:ct(),stderr:""};let o=hn(i);return"values"in o?r==="list"?xn(o,t):r==="add"?vn(o,t,n):Cn(o,t):o}function pt(){return{validValues:l("cmd.auth.cli.validValues"),hint:l("cmd.auth.cli.hint")}}function wn(e){if(e.length===0||e[0]==="--help"||e[0]==="-h")return{exitCode:0,stdout:U(),stderr:""};if(e[0]==="status")return e.slice(1);let t=l("cmd.auth.cli.unknownSubcommand",{command:e[0]});return{exitCode:1,stdout:"",stderr:f(t,{validValues:["status","login","provider"],hint:"cortex auth --help",labels:pt()})}}function bn(e){if(e.includes("--help")||e.includes("-h"))return{exitCode:0,stdout:U(),stderr:""};let t=e.find(i=>i!=="--json");if(!t)return null;let n=l("cmd.auth.cli.unknownFlag",{flag:t});return{exitCode:1,stdout:"",stderr:f(n,{validValues:["--json"],hint:"cortex auth status --help",labels:pt()})}}async function ft(e,t,n){if(e[0]==="login")return Ke(e.slice(1));if(e[0]==="provider")return dt(e.slice(1),n);let r=wn(e);if(!Array.isArray(r))return r;let i=bn(r);if(i)return i;let o=await t();return{exitCode:0,stdout:r.includes("--json")?JSON.stringify(o,null,2):De(o),stderr:""}}import*as gt from"node:path";var mt=["enable","pair"];function J(e,t){let n=e.indexOf(t);return n!==-1&&e[n+1]?e[n+1]:void 0}function B(e,t){return{exitCode:1,stdout:"",stderr:f(e,t)}}async function In(e){let t=e.includes("--json"),n=J(e,"--port"),r=n===void 0?void 0:Number(n);if(r!==void 0&&(!Number.isInteger(r)||r<1||r>65535))return B(`Invalid --port: '${n}'.`,{validValues:["an integer in 1-65535"],hint:"cortex ui enable --port 3004"});let i=g(J(e,"--home"));try{let o=await Je({configDir:i.CONFIG_DIR,port:r});if(t){let a={ok:!0,home:i.DATA_DIR,...o};return{exitCode:0,stdout:`${JSON.stringify(a,null,2)}
11
- `,stderr:""}}return{exitCode:0,stdout:`${[`Web UI endpoint enabled: ${o.url}`,`Home: ${i.DATA_DIR}`,o.changed?"Configuration changed \u2014 restart the daemon to apply (cortex daemon restart).":"Already configured \u2014 no restart needed.","Connect another app or browser with a one-time code from `cortex ui pair`."].join(`
12
- `)}
13
- `,stderr:""}}catch(o){return{exitCode:1,stdout:"",stderr:o.message||String(o)}}}async function kn(e){let t=g(J(e,"--home")),n=me({file:gt.join(t.STORE_DIR,pe)}),{code:r,expiresAt:i}=n.create();return e.includes("--json")?{exitCode:0,stdout:`${JSON.stringify({ok:!0,code:r,expiresAt:i},null,2)}
14
- `,stderr:""}:{exitCode:0,stdout:`${[`Pairing code: ${r}`,`Valid for ${fe/6e4} minutes, once.`,"Enter it with this server's address in the Cortex app, or on the browser sign-in page."].join(`
15
- `)}
16
- `,stderr:""}}var ht={enable:In,pair:kn};async function xt(e){if(e.length===0)return B("Missing subcommand for 'ui'.",{validValues:mt,hint:"cortex ui --help"});if(e.includes("--help")||e.includes("-h"))return{exitCode:0,stdout:Qe(),stderr:""};let t=Object.hasOwn(ht,e[0])?ht[e[0]]:void 0;return t?t(e):B(`Unknown subcommand: '${e[0]}'.`,{validValues:mt,hint:"cortex ui --help"})}import*as vt from"node:fs";import*as v from"node:path";var k=class extends Error{validValues;hint;constructor(t,n,r){super(t),this.validValues=n,this.hint=r}},Ct="client-pids.json",wt="client-routes.json";function j(e){try{return JSON.parse(vt.readFileSync(e,"utf8"))}catch{return{}}}function W(e,t,n=!1){let r=j(e);t in r&&(delete r[t],ne(e,`${JSON.stringify(r,null,2)}${n?`
17
- `:""}`))}function Sn(e,t){return Ne(e,t,3e4)}var $n=/"([^"]+?)[\\/]client[\\/]current[\\/]client\.mjs"|(\S+?)[\\/]client[\\/]current[\\/]client\.mjs/;function bt(e){let t=e.clientCommand?.match($n),n=t?.[1]??t?.[2];return n||(e.win?"%USERPROFILE%\\.cortex":"$HOME/.cortex")}function Dn(e){return[`h="${e}"`,'k=$(pgrep -f "$h/client/current/client[.]mjs" | xargs); [ -n "$k" ] && kill $k; echo "killed=${k:-none}"','if [ -f "$h/config/machines.json" ]; then echo files=kept-server-home; else',' rm -rf "$h/client"; rm -f "$h/config/cortex-client.json" "$h"/logs/client-*.log',' rmdir "$h/logs" "$h/config" "$h" 2>/dev/null; echo files=removed',"fi"].join(`
18
- `)}function An(e){let t=`powershell -NoProfile -Command "$k = @(Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -like '*${e}\\client\\current\\client[.]mjs*' }); $k | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }; 'killed=' + (@($k | ForEach-Object { $_.ProcessId }) -join ' ')"`,n=`rmdir /s /q "${e}\\client" 2>nul & del /q "${e}\\config\\cortex-client.json" 2>nul & del /q "${e}\\logs\\client-*.log" 2>nul & echo files=removed`;return`${t} & if exist "${e}\\config\\machines.json" (echo files=kept-server-home) else (${n})`}function Pn(e){return(e.win?An:Dn)(bt(e))}function yt(e,t){return e.match(new RegExp(`^${t}=(.*)$`,"m"))?.[1]?.trim()||"none"}async function En(e,t){try{let n=await t(e.ssh,Pn(e));return{status:"cleaned",killed:yt(n,"killed"),files:yt(n,"files")}}catch(n){return{status:"unreachable",error:n.message}}}function _n(e,t){let n=e[t];if(!n){let r=Object.keys(e).filter(i=>e[i].ssh);throw new k(`Unknown device: '${t}'.`,r,"cortex client remove --device <name>")}if(!n.ssh)throw new k(`'${t}' is the server's local machine and has no remote client to remove.`,void 0,"edit config/machines.json by hand if this machine really should go");return n}function Rn(e,t){let n=j(v.join(t.configDir,"machines.json")),r=_n(n,e.device),i=j(v.join(t.storeDir,Ct))[e.device],o=j(v.join(t.storeDir,wt))[e.device];return{machine_entry:r,runtime:{pid:typeof i=="number"?i:null,route:typeof o=="string"?o:null},remote:e.keepRemote?null:{host:r.ssh,home:bt(r)}}}async function It(e,t){let n=Rn(e,t),{device:r}=e;if(e.dryRun)return{ok:!0,device:r,dry_run:!0,would_remove:n};W(v.join(t.configDir,"machines.json"),r,!0);let i=n.remote?await En(n.machine_entry,t.remoteExec??Sn):{status:"skipped"};return W(v.join(t.storeDir,Ct),r),W(v.join(t.storeDir,wt),r),{ok:!0,device:r,dry_run:!1,removed_at:new Date().toISOString(),machine_entry:n.machine_entry,runtime:n.runtime,remote:i}}var kt=["--device","--home"],St=["--keep-remote","--dry-run"];function S(e,t,n="cortex client remove --help"){return{exitCode:1,stdout:"",stderr:f(e,{validValues:t,hint:n})}}function jn(e){let t={};for(let n=0;n<e.length;n+=1){let r=e[n];if(St.includes(r)){t[r]=!0;continue}if(!kt.includes(r))return S(`Unknown option: '${r}'.`,[...kt,...St]);let i=e[n+1];if(!i||i.startsWith("--"))return S(`Missing value for ${r}.`);t[r]=i,n+=1}return t}async function Tn(e,t){let n=jn(e);if("exitCode"in n)return n;if(typeof n["--device"]!="string")return S("Missing --device.",void 0,"cortex client remove --device <name>");let r=g(n["--home"]);try{let i=await It({device:n["--device"],keepRemote:n["--keep-remote"]===!0,dryRun:n["--dry-run"]===!0},{configDir:r.CONFIG_DIR,storeDir:r.STORE_DIR,remoteExec:t}),o=i.remote?.status==="unreachable"?`Warning: '${i.device}' was removed locally, but its machine could not be reached; the remote client was not uninstalled.`:"";return{exitCode:0,stdout:`${JSON.stringify(i,null,2)}
19
- `,stderr:o}}catch(i){return i instanceof k?S(i.message,i.validValues,i.hint):{exitCode:1,stdout:"",stderr:i.message}}}async function $t(e,t){return e.includes("--help")||e.includes("-h")?{exitCode:0,stdout:et(),stderr:""}:e.length===0?S("Missing subcommand for 'client'.",["remove"],"cortex client --help"):e[0]!=="remove"?S(`Unknown subcommand: '${e[0]}'.`,["remove"],"cortex client --help"):Tn(e.slice(1),t)}var On=["install","remove","status"];function Nn(e,t){let n=e.indexOf(t);return n!==-1&&e[n+1]?e[n+1]:void 0}var Dt=e=>({exitCode:1,stdout:"",stderr:f(e,{validValues:On,hint:"cortex path --help"})});function Y(e,t,n){let r=e.path_targets.filter(i=>i[t]).map(i=>i.target);return`${n}: ${r.length?r.join(", "):"none"}`}function Fn(e){let t=[`${e.dry_run?"Would install":"Installed"} terminal commands in ${e.dir}`,Y(e,"changed",e.dry_run?"PATH would change in":"PATH updated in"),"Open a new terminal to use `cortex`."];return e.shadowed.length&&t.push(`New terminals will use this install instead of: ${e.shadowed.join(", ")}`),process.env.SHELL?.endsWith("fish")&&t.push(`fish is not configured automatically; run: fish_add_path ${e.dir}`),t}function Ln(e){return[`${e.dry_run?"Would remove":"Removed"} ${e.removed.length} command file(s) from ${e.dir}`,Y(e,"changed",e.dry_run?"PATH would change in":"PATH restored in")]}function Mn(e){return[`Terminal commands: ${e.installed?"installed":"not installed"} (${e.dir})`,...e.stale.length?[`Out of date: ${e.stale.join(", ")} \u2014 rerun cortex path install`]:[],Y(e,"registered","On PATH via")]}var Gn={install:(e,t)=>{let n=Le(e,t);return{report:n,text:Fn(n)}},remove:(e,t)=>{let n=Me(e,t);return{report:n,text:Ln(n)}},status:e=>{let t=Ge(e);return{report:t,text:Mn(t)}}};function At(e,t=Fe){if(e.includes("--help")||e.includes("-h"))return{exitCode:0,stdout:Ze(),stderr:""};if(e.length===0)return Dt("Missing subcommand for 'path'.");let n=Gn[e[0]];if(!n)return Dt(`Unknown subcommand: '${e[0]}'.`);try{let r=t(g(Nn(e,"--home")).DATA_DIR),{report:i,text:o}=n(r,e.includes("--dry-run"));return{exitCode:0,stdout:e.includes("--json")?`${JSON.stringify(i,null,2)}
20
- `:`${o.join(`
21
- `)}
22
- `,stderr:""}}catch(r){return{exitCode:1,stdout:"",stderr:`cortex path ${e[0]} failed: ${r?.message??String(r)}
23
- `}}}var y=le("cli"),ee=d.dirname(Un(new URL("dist/entry/cli.js",__cortexPackageRoot).href)),q=d.join(ee,"app.js"),$=d.join(ee,"daemon.js"),X=d.join(ee,"..","tui","index.js");function Kn(e){let t={resume:!1};for(let n=0;n<e.length;n++)switch(e[n]){case"--resume":t.resume=!0;break;case"--project":t.project=e[++n];break;case"--port":t.port=Number(e[++n]);break}return t}function Vn(e){return new Promise(t=>{let n=Rt.connect({host:"127.0.0.1",port:e},()=>{n.end(),t(!0)});n.setTimeout(500),n.on("timeout",()=>{n.destroy(),t(!1)}),n.on("error",()=>t(!1))})}async function Jn(e){let t=Kn(e),n=t.port??(Number(process.env.CORTEX_TUI_PORT)||3003);await Vn(n)||(process.stderr.write(`Cortex daemon is not running on port ${n}.
24
- Start it with: cortex daemon
25
- `),process.exit(1)),m(X)||(y.error(`TUI entry not found: ${X}`),y.error("Run `npm run build` first."),process.exit(1));let r=[];t.resume&&r.push("--resume"),t.project&&r.push("--project",t.project),T(X,r,{stdio:"inherit",env:{...process.env,CORTEX_TUI_PORT:String(n)}}).on("exit",o=>process.exit(o??0)),await new Promise(()=>{})}function N(){if(!m(h))return{result:{exitCode:0,stdout:`Cortex daemon is not running.
26
- `,stderr:""}};let e=A(h);if(e===null){try{Z(h)}catch{}return{result:{exitCode:0,stdout:`Cortex daemon is not running (removed corrupted PID file).
27
- `,stderr:""}}}if(!xe(h,e)){try{Z(h)}catch{}return{result:{exitCode:0,stdout:`Cortex daemon is not running (removed stale PID file for PID ${e}).
28
- `,stderr:""}}}return{pid:e}}async function Bn(){let e=N();if("result"in e)return Pt(e.result);let t=await Wn(e.pid);return t.daemonGone?Pt(t.result):t.result}async function Pt(e){let{exitCode:t,stdout:n,stderr:r}=e;try{let{stopLaunchedLocalClients:i}=await import("./local-client-stop-SQRU7ZZM.js");for(let{device:o,pid:s,outcome:a}of await i())a==="stopped"&&(n+=`Stopped local client ${o} (PID ${s}).
29
- `),a==="unverified"&&(r+=`Left local client ${o} (PID ${s}) running: could not confirm the process is its client.
30
- `),a==="survived"&&(t=1,r+=`Local client ${o} (PID ${s}) did not exit.
31
- `)}catch(i){r+=`Could not stop the local client: ${i.message||String(i)}
32
- `}return{exitCode:t,stdout:n,stderr:r}}async function Wn(e){try{process.kill(e,"SIGTERM")}catch(i){return{daemonGone:!1,result:{exitCode:1,stdout:"",stderr:`Failed to send signal to daemon (PID ${e}): ${i.message}
33
- `}}}let t=1e4,n=200,r=Date.now()+t;for(;Date.now()<r;){await new Promise(i=>setTimeout(i,n));try{process.kill(e,0)}catch{break}}try{process.kill(e,0);try{process.kill(e,"SIGKILL")}catch{}return{daemonGone:!w(e),result:{exitCode:1,stdout:"",stderr:`Daemon (PID ${e}) did not stop within ${t/1e3}s. Forcibly killed (SIGKILL).
34
- `}}}catch{}try{A(h)===e&&Z(h)}catch{}return{daemonGone:!0,result:{exitCode:0,stdout:`Cortex daemon stopped (PID ${e}).
35
- `,stderr:""}}}function Et(e){try{let t=`/proc/${e}/stat`;if(!m(t))return"unknown";let n=Q(t,"utf8"),r=n.lastIndexOf(")"),i=n.substring(r+2).split(" "),o=parseInt(i[19],10);if(!Number.isFinite(o))return"unknown";let s=Q("/proc/uptime","utf8"),a=parseFloat(s.split(" ")[0]),jt=Date.now()-a*1e3+o/100*1e3,te=Date.now()-jt;return te<0?"unknown":Ie(te)}catch{return"unknown"}}function Yn(){let e=N();if("result"in e)return e.result;let{pid:t}=e,n=Et(t),r=["Cortex daemon is running.",` PID: ${t}`,` Uptime: ${n}`],i=A(L);return i===null?r.push(" Child: starting..."):w(i)?r.push(` Child: app.js (PID ${i}, uptime ${Et(i)})`):r.push(` Child: none (stale PID ${i} \u2014 daemon will restart)`),{exitCode:0,stdout:r.join(`
36
- `)+`
37
- `,stderr:""}}function qn(){let e=N();if("result"in e)return{exitCode:1,stdout:"",stderr:`Cortex daemon is not running. Nothing to restart.
38
- `};try{return G(),{exitCode:0,stdout:`Restart signal sent to daemon (PID ${e.pid}).
39
- `,stderr:""}}catch(t){return{exitCode:1,stdout:"",stderr:`Failed to signal daemon restart: ${t.message||String(t)}
40
- `}}}function _t(e){if("result"in N())return{exitCode:1,stdout:"",stderr:`Cortex daemon is not running.
41
- `};let t=A(L);if(t===null)return{exitCode:1,stdout:"",stderr:`No child PID file found. Is app.js running?
42
- `};if(!w(t))return{exitCode:1,stdout:"",stderr:`Child process (PID ${t}) is not running.
43
- `};let n=e?"SIGKILL":"SIGTERM";try{process.kill(t,n)}catch(r){return{exitCode:1,stdout:"",stderr:`Failed to send ${n} to app.js (PID ${t}): ${r.message}
44
- `}}return{exitCode:0,stdout:`Sent ${n} to app.js (PID ${t}). Daemon will restart it automatically.
45
- `,stderr:""}}function Xn(){let e={INSTALL_ROOT:re,...g()},t=d.join(e.CONFIG_DIR,".env"),n=d.join(e.CONFIG_DIR,"mcp-config.json"),r=d.join(e.STORE_DIR,"agent-state.json"),i=d.join(e.STORE_DIR,"mode.json"),o=0;try{o=Hn(e.STORE_DIR).length}catch{}let s={dataDirExists:m(e.DATA_DIR)&&o>0,dotEnvExists:m(t),mcpConfigExists:m(n),modeJsonExists:m(r)||m(i)};return We(e,s)}function O(e,t){let n=e.indexOf(t);return n!==-1&&e[n+1]?e[n+1]:void 0}async function zn(e){if(e.includes("--help")||e.includes("-h"))return{exitCode:0,stdout:qe(),stderr:""};let t=O(e,"--home"),n=O(e,"--gateway-config-dir"),r=O(e,"--answers");try{let i=r?Be(Q(d.resolve(r),"utf-8")):void 0;return await Ye({homeDir:t,gatewayConfigDir:n,force:e.includes("--force"),answers:i,jsonEvents:e.includes("--json")}),{exitCode:0,stdout:"",stderr:""}}catch(i){return i instanceof He&&i.exitCode===130?{exitCode:130,stdout:"",stderr:l("init.cancel")}:{exitCode:1,stdout:"",stderr:i.message||String(i)}}}function Qn(){let e=ae;try{return G(e),{exitCode:0,stdout:`Restart trigger touched: ${e}
46
- If a daemon is running it will drain and respawn app.js.
47
- `,stderr:""}}catch(t){return{exitCode:1,stdout:"",stderr:`Could not write ${e}: ${t.message||String(t)}`}}}function Zn(e,t){if(t.droppedFromDiscovery.length===0)return;let n=t.droppedFromDiscovery.map(r=>`${r.mode}/${r.endpoint}`).join(", ");e.push(`WARNING: preserved ${t.droppedFromDiscovery.length} existing gateway mode(s) not reported by discovery: ${n}`),e.push(" (if these should auto-detect, check `cortex auth status` and log the provider in)")}function er(e,t){if(t.length!==0){e.push(`WARNING: ${t.length} model selection(s) reference an unconfigured gateway route:`);for(let n of t)e.push(` - ${n.model}: ${n.reason}`)}}function tr(e,t,n,r,i){let o=Ae(d.dirname(r)),s=o.favorites.map(p=>p.model).join(", "),a=[t?`[TEST MODE] Output directory: ${t}`:"",`Gateway config: ${n}`,`Models: ${r}`,`Discovered ${e.length} endpoint modes`,`Favorites: ${s} (default: ${o.default.model})`];return Zn(a,i),er(a,we(i.endpoints,t)),a.filter(Boolean).join(`
48
- `)}async function nr(e){let t=await ve();if(!t.some(o=>o.models.length>0))return{exitCode:0,stdout:`No backends discovered. Log into Claude Code and/or PI first.
49
- `,stderr:""};let{path:n,result:r}=Ce(t,e),i=Pe(t,{outputDir:e});return{exitCode:0,stdout:tr(t,e,n,i,r),stderr:""}}async function rr(e){if(e.includes("--help")||e.includes("-h"))return{exitCode:0,stdout:Xe(),stderr:""};try{return e.includes("--dry-run")?{exitCode:0,stdout:await be(),stderr:""}:await nr(O(e,"--output-dir"))}catch(t){return{exitCode:1,stdout:"",stderr:t.message||String(t)}}}async function ir(e){let{runCli:t,getInstallHelp:n}=await import("./install-cli-4IZCSDFZ.js");return e.includes("--help")||e.includes("-h")?{exitCode:0,stdout:n(),stderr:""}:t(e)}function or(e){return e[1]==="--hard"?_t(!1):e[1]==="--force"?_t(!0):qn()}function sr(e){return e[0]==="stop"?Bn():e[0]==="status"?Yn():e[0]==="restart"?or(e):null}async function ar(e){let t=sr(e);return t||(e.includes("--help")||e.includes("-h")?{exitCode:0,stdout:I(),stderr:""}:e.includes("--version")||e.includes("-V")?{exitCode:0,stdout:`${M}
50
- `,stderr:""}:{exitCode:0,stdout:"",stderr:`'daemon' must be run from the main entry point, not imported.
51
- Use: node dist/entry/cli.js daemon`})}var lr={init:e=>zn(e),config:()=>({exitCode:0,stdout:Xn(),stderr:""}),auth:(e,t)=>ft(e,t.getAuthStatus??_,t.customProviderStores??_e()),doctor:e=>lt(e),feishu:e=>Ve(e),restart:()=>Qn(),"setup-gateway":e=>rr(e),ui:e=>xt(e),client:e=>$t(e),path:e=>At(e),install:e=>ir(e),schedule:async e=>(await import("./schedule-cli-OLASBBYJ.js")).runScheduleCli(e),memory:async e=>(await import("./memory-cli-PYOILNN5.js")).runMemoryCli(e),start:()=>({exitCode:0,stdout:"",stderr:`'start' must be run from the main entry point, not imported.
52
- Use: node dist/entry/cli.js start`}),daemon:e=>ar(e)};async function z(e,t={}){if(e.length===0||e[0]==="--help"||e[0]==="-h")return{exitCode:0,stdout:I(),stderr:""};let n=lr[e[0]];return n?n(e.slice(1),t):{exitCode:1,stdout:"",stderr:`Unknown command: '${e[0]}'. Use --help to see available commands.`}}function ur(){let e=process.argv.slice(2);(e.length===0||e[0]==="--help"||e[0]==="-h")&&(console.log(I()),process.exit(0));let t=e[0],n=e.slice(1);if((n.includes("--help")||n.includes("-h"))&&(t==="daemon"&&(console.log(I()),process.exit(0)),t==="start"&&(console.log(I()),process.exit(0)),t==="tui"&&(console.log(ze()),process.exit(0))),(n.includes("--version")||n.includes("-V"))&&t==="daemon"&&(console.log(M),process.exit(0)),t==="start"){m(q)||(y.error(`Entry not found: ${q}`),y.error("Run `npm run build` first."),process.exit(1)),T(q,[],{cwd:C,stdio:"inherit",env:{...process.env}}).on("exit",i=>process.exit(i??0));return}if(t==="daemon"){if(n[0]==="restart-self"){z(["daemon","stop"]).then(async i=>{i.stdout&&console.log(i.stdout),i.stderr&&console.error(i.stderr),m($)||(y.error(`Entry not found: ${$}`),y.error("Run `npm run build` first."),process.exit(1)),console.log("Starting daemon..."),T($,[],{cwd:C,detached:!0,stdio:"ignore",env:{...process.env}}),process.exit(0)});return}if(n[0]==="stop"||n[0]==="status"||n[0]==="restart"){z(e).then(i=>{i.stdout&&console.log(i.stdout),i.stderr&&console.error(i.stderr),process.exit(i.exitCode)});return}m($)||(y.error(`Entry not found: ${$}`),y.error("Run `npm run build` first."),process.exit(1));let r={cwd:C,windowsHide:!0,detached:!0,stdio:"ignore",env:{...process.env}};T($,[],r),process.exit(0)}if(t==="tui"){Jn(n);return}z(e).then(r=>{r.stdout&&console.log(r.stdout),r.stderr&&console.error(r.stderr),process.exit(r.exitCode)})}he(new URL("dist/entry/cli.js",__cortexPackageRoot).href)&&ur();export{Kn as a,Vn as b,Jn as c,Xn as d,z as e,ur as f};
@@ -1,7 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{a as Ze}from"./chunk-JERCOLY3.js";import{a as O}from"./chunk-OKRK6JPY.js";import{a as he,b as me,e as ge,f as ye}from"./chunk-BGVHA2D4.js";import{a as P}from"./chunk-LCKVYFMD.js";import{c as pe}from"./chunk-STUHNKQS.js";import{a as ue}from"./chunk-Q4UGYGU5.js";import{d as v}from"./chunk-W5LGYSPZ.js";import{e as l}from"./chunk-NAA7GF6Q.js";import{h as fe}from"./chunk-QWAQHHRS.js";import{a as Qe,b as A,j as p,k as F,l as h,m as le,n as de}from"./chunk-J5DVLUKY.js";import{e as ce}from"./chunk-WHC7AYZD.js";var I=ce(Ze(),1);import{copyFileSync as Pe,existsSync as z,readFileSync as Fe}from"fs";import*as M from"path";function et(e){return new Promise(t=>{setTimeout(t,e).unref?.()})}var m=class{options;entries=[];nextRefreshAt=0;inFlight=null;refreshQueued=!1;now;constructor(t){this.options=t,this.now=t.now??Date.now}peek(){let t=this.options.clone;return t?this.entries.map(t):[...this.entries]}get(){let t=this.peek();return this.now()>=this.nextRefreshAt&&!this.inFlight&&this.startRefresh(),t}async ensure(t){if(this.entries.length>0)return this.get();!this.inFlight&&this.now()>=this.nextRefreshAt&&this.startRefresh();let n=this.inFlight;return n&&await Promise.race([n,et(t)]),this.peek()}refresh(){if(!this.inFlight){this.startRefresh();return}this.refreshQueued=!0}startRefresh(){let t=Promise.resolve().then(this.options.scan).then(n=>this.accept(n)).catch(n=>this.reject(n)).finally(()=>this.finishRefresh(t));this.inFlight=t}finishRefresh(t){this.inFlight===t&&(this.inFlight=null,this.refreshQueued&&(this.refreshQueued=!1,this.startRefresh()))}accept(t){let{key:n,clone:o}=this.options,r=new Set,i=[];for(let s of t){if(n){let a=n(s);if(r.has(a))continue;r.add(a)}i.push(o?o(s):s)}this.entries=i,this.nextRefreshAt=this.now()+this.options.cacheTtlMs}reject(t){this.nextRefreshAt=this.now()+this.options.retryMs;let n=t instanceof Error?t.message:"unknown";this.options.logFailure?.(n)}};var Ae=ce(Qe(),1);import{execFile as tt,execFileSync as nt}from"child_process";import{createHash as ot}from"crypto";import{readFileSync as rt}from"fs";import*as S from"path";var it="oauth-2025-04-20",Ee="2023-06-01",st=6e4,at=2e3,ct=5e3;function L(e,t){try{return e(t)}catch{return null}}function j(e){return e.readFile??(t=>rt(t,"utf8"))}function g(e){if(typeof e!="string")return;let t=e.trim();if(!(!t||t==="undefined"||t==="null"))return t}function H(e){let t=g(e);return t===fe?void 0:t}function ut(e){let t=L(e,S.join(h,".env"));if(t===null)return{};try{return(0,Ae.parse)(t)}catch{return{}}}function be(e={}){let t=ut(j(e)),n=g(t.CLAUDE_CODE_OAUTH_TOKEN);return{ANTHROPIC_API_KEY:H(t.ANTHROPIC_API_KEY),ANTHROPIC_BASE_URL:g(t.ANTHROPIC_BASE_URL),CLAUDE_CODE_OAUTH_TOKEN:n,CLAUDE_CODE_OAUTH_TOKEN_EXPIRES_AT:n?g(t.CLAUDE_CODE_OAUTH_TOKEN_EXPIRES_AT):void 0}}function we(e={}){let t=e.env??process.env;return H(t.ANTHROPIC_API_KEY)??be(e).ANTHROPIC_API_KEY??null}function _e(e){return{"x-api-key":e,"anthropic-version":Ee}}function E(e){return{authorization:`Bearer ${e}`,"anthropic-beta":it,"anthropic-version":Ee}}function U(e={}){return e.claudeConfigDir??de}function lt(e={}){return S.join(U(e),".credentials.json")}function $(e){return typeof e=="string"&&e.trim()?e.trim():null}function ve(e){return typeof e!="number"||!Number.isFinite(e)||Number.isNaN(new Date(e).getTime())?null:e}function ke(e){let t;try{t=JSON.parse(e)?.claudeAiOauth}catch{return null}if(!t||typeof t!="object"||Array.isArray(t))return null;let n=t,o={accessToken:$(n.accessToken),refreshToken:$(n.refreshToken),expiresAt:ve(n.expiresAt),refreshExpiresAt:ve(n.refreshTokenExpiresAt)};return o.accessToken||o.refreshToken?o:null}function xe(e={}){let t=L(j(e),lt(e));return t===null?null:ke(t)}function Oe(e,t){if(!e?.accessToken)return null;let n=(t.now??Date.now)();return e.expiresAt!==null&&e.expiresAt-st<=n?null:e.accessToken}function Se(e){return Oe(xe(e),e)}function Mn(e={}){let t=Se(e);return t?E(t):null}function In(e={}){let t=L(j(e),S.join(U(e),".claude.json"));if(t===null)return null;try{let n=JSON.parse(t)?.oauthAccount;return $(n?.organizationUuid)}catch{return null}}function K(e={}){let t=e.env??process.env,n=H(t.ANTHROPIC_API_KEY);if(n)return{headers:_e(n),source:"env-api-key"};let o=be(e);if(o.ANTHROPIC_API_KEY)return{headers:_e(o.ANTHROPIC_API_KEY),source:"dotenv-api-key"};let r=Se(e);if(r)return{headers:E(r),source:"claude-credentials"};let i=g(t.CLAUDE_CODE_OAUTH_TOKEN);return i?{headers:E(i),source:"env-oauth-token"}:o.CLAUDE_CODE_OAUTH_TOKEN?{headers:E(o.CLAUDE_CODE_OAUTH_TOKEN),source:"dotenv-oauth-token"}:null}function Te(e={}){return`Claude Code-credentials-${ot("sha256").update(U(e).normalize("NFC")).digest("hex").slice(0,8)}`}function dt(e){try{return nt("security",["find-generic-password","-s",e],{stdio:"ignore",timeout:at}),!0}catch{return!1}}function pt(e){return new Promise(t=>{try{tt("security",["find-generic-password","-s",e,"-w"],{encoding:"utf8",timeout:ct},(n,o)=>t(n?null:o.trim()||null))}catch{t(null)}})}async function Me(e={}){if((e.platform??process.platform)!=="darwin")return null;let o=await(e.readKeychain??pt)(Te(e)),r=Oe(o===null?null:ke(o),e);return r?{headers:E(r),source:"claude-keychain"}:null}function G(e={}){return xe(e)?!0:(e.platform??process.platform)!=="darwin"?!1:(e.probeKeychain??dt)(Te(e))}function Cn(e={}){let t=e.env??process.env;return g(t.ANTHROPIC_AUTH_TOKEN)?!0:K(e)!==null||G(e)}var Ie=l("anthropic-models"),ft=30*6e4,ht=5*6e4,mt=8e3,gt=1e4,yt=1e3,_t=1e6,T="[1m]",vt=["low","medium","high","xhigh","max"];function b(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function At(e){return((e.env??process.env).ANTHROPIC_BASE_URL?.trim()||"https://api.anthropic.com").replace(/\/+$/,"")}function Et(e){if(!b(e))return null;let t=e.effort;if(!b(t)||t.supported!==!0)return null;let n=vt.filter(o=>{let r=t[o];return b(r)&&r.supported===!0});return n.length>0?[...n]:null}function bt(e){if(!b(e))return null;let t=typeof e.id=="string"?e.id.trim():"";if(!t)return null;let n=typeof e.display_name=="string"?e.display_name.trim():"",o=e.max_input_tokens;return{id:t,displayName:n||null,maxInputTokens:typeof o=="number"&&Number.isFinite(o)?o:null,effortLevels:Et(e.capabilities)}}async function wt(e={}){let t=K(e)??await Me(e);if(!t)throw new Error("no Anthropic credential available to the daemon");let n=e.fetchImpl??fetch,o=`${At(e)}/v1/models?limit=${yt}`,r=await n(o,{method:"GET",headers:t.headers,signal:AbortSignal.timeout(gt)});if(!r.ok)throw new Error(`models request failed: HTTP ${r.status}`);let i=await r.json(),s=b(i)?i.data:null;if(!Array.isArray(s))throw new Error("models response carried no data array");let a=[];for(let u of s){let ae=bt(u);ae&&a.push(ae)}return Ie.debug(`discovered ${a.length} Anthropic models via ${t.source}`),a}function kt(e){return e.endsWith(T)?e.slice(0,-T.length):e}function xt(e,t){return e.startsWith(`${t}-`)&&/^\d{8}$/.test(e.slice(t.length+1))}function Ce(e,t=O){let n=[],o=new Set,r=i=>{o.has(i)||(o.add(i),n.push(i))};for(let i of e)r(i.id),(i.maxInputTokens??0)>=_t&&r(`${i.id}${T}`);for(let i of t){let s=kt(i);e.some(u=>u.id===s||xt(u.id,s))||r(i)}return n}function $n(e){let t={};for(let n of e)n.effortLevels&&(t[n.id]=[...n.effortLevels],t[`${n.id}${T}`]=[...n.effortLevels]);return t}function Ot(e={}){let t=new m({scan:e.fetchModels??(()=>wt()),now:e.now,cacheTtlMs:e.cacheTtlMs??ft,retryMs:e.retryMs??ht,key:n=>n.id,clone:n=>({...n,effortLevels:n.effortLevels?[...n.effortLevels]:null}),logFailure:n=>Ie.info(`Anthropic model discovery failed: ${n}`)});return{get:()=>t.get(),ensure:(n=mt)=>t.ensure(n)}}var De=Ot();var f=l("gateway-generator"),St=new Set(["host","port","mode","auth","status_check","max_body_size_mb","endpoint_modes","endpoints"]),B=100,Tt=["keys","base_url","auth_style","passthrough","fallbacks","model_fallbacks"],Y="default",$e={anthropic:{url:"https://api.anthropic.com",auth_style:"bearer"},fireworks:{url:"https://api.fireworks.ai/inference",auth_style:"bearer"},"github-copilot":{url:"https://api.individual.githubcopilot.com",auth_style:"bearer"},minimax:{url:"https://api.minimax.io/anthropic",auth_style:"bearer"},"minimax-cn":{url:"https://api.minimaxi.com/anthropic",auth_style:"bearer"},opencode:{url:"https://opencode.ai/inference",auth_style:"bearer"},"vercel-ai-gateway":{url:"https://ai-gateway.vercel.sh",auth_style:"bearer"},cerebras:{url:"https://api.cerebras.ai/v1",auth_style:"bearer"},deepseek:{url:"https://api.deepseek.com",auth_style:"bearer"},groq:{url:"https://api.groq.com/openai/v1",auth_style:"bearer"},huggingface:{url:"https://router.huggingface.co/v1",auth_style:"bearer"},"kimi-coding":{url:"https://api.kimi.com/coding/v1",auth_style:"bearer"},mistral:{url:"https://api.mistral.ai",auth_style:"bearer"},openai:{url:"https://api.openai.com/v1",auth_style:"bearer"},"opencode-go":{url:"https://opencode.ai/inference/go/v1",auth_style:"bearer"},openrouter:{url:"https://openrouter.ai/api/v1",auth_style:"bearer"},xai:{url:"https://api.x.ai/v1",auth_style:"bearer"},zai:{url:"https://api.z.ai/api/coding/paas/v4",auth_style:"bearer"},"openai-codex":{url:"https://chatgpt.com/backend-api",auth_style:"bearer"},"google-gemini-cli":{url:"https://cloudcode-pa.googleapis.com",auth_style:"bearer"},"google-antigravity":{url:"https://daily-cloudcode-pa.sandbox.googleapis.com",auth_style:"bearer"},google:{url:"https://generativelanguage.googleapis.com/v1beta",auth_style:"bearer"}},Mt={"kimi-coding":["https://api.kimi.com/coding"],opencode:["https://opencode.ai/zen"],"opencode-go":["https://opencode.ai/zen/go/v1"]};function It(e){let t=0;for(let[n,o]of Object.entries(Mt))for(let r of Object.values(e[n]??{}))o.includes(r.base_url)&&(r.base_url=$e[n].url,t+=1);return t}function Vn(e=M.join(F,"gateway.yaml")){let t=y(e);if(!t)return 0;let n=It(t.endpoints);return n===0?0:(Pe(e,`${e}.bak`),v(e,C({endpoints:t.endpoints,top:t.top,preservedCustom:[],droppedFromDiscovery:[]})),f.info(`Moved ${n} gateway route(s) off retired PI upstream URLs in ${e}`),n)}var Ct=["off","minimal","low","medium","high","xhigh","max"];function Dt(e){let t=e;if(!t||typeof t!="object"||!("reasoning"in t)&&!("thinkingLevelMap"in t))return;if(!t.reasoning)return[];let n=t.thinkingLevelMap;return Ct.filter(o=>{let r=n?.[o];return r===null?!1:o==="xhigh"||o==="max"?r!==void 0:!0})}async function W(){let{ModelRuntime:e}=await he();return(await(await e.create({authPath:ge(),modelsPath:ye(),allowModelNetwork:!1})).getAvailable()).map(o=>{let r=Dt(o);return{provider:o.provider,model:o.id,...r?{thinkingLevels:r}:{}}})}async function Rt(){try{return await W()}catch(e){let t=e instanceof Error?e.message:String(e);return f.info(`PI model scan failed \u2014 skipping PI provider discovery: ${t}`),[]}}async function Nt(e,t={}){let n=i=>!e||e.includes(i),o=n("claude")?await Pt(t):[],r=n("pi")?await $t(t):[];return[...o,...r]}function Re(e,t,n){let o=e==="api";return{mode:e,endpoint:"anthropic",base_url:"https://api.anthropic.com",auth_style:o?"anthropic":"bearer",keys:o?["$ANTHROPIC_API_KEY"]:[],passthrough:!0,models:[...t],gatewayManaged:!0,...n?{defaultModel:n}:{}}}async function Pt(e){let t=(e.claudeSubscription??(()=>G()))(),n=we()!==null;if(!t&&!n)return[];let o=e.anthropicModels??(()=>De.ensure()),r=Ce(await o()),i=O.find(a=>r.includes(a))??r[0],s=[];return t&&s.push(Re("plan",r,i)),n&&s.push(Re("api",r,i)),s}function Ft(e,t,n){let o=$e[e];return{mode:e,endpoint:e,base_url:o?.url??"",auth_style:o?.auth_style??"bearer",keys:[],passthrough:!0,models:t,gatewayManaged:!!o,...n&&t.includes(n)?{defaultModel:n}:{}}}async function $t(e){let t=new Map;for(let{provider:o,model:r}of await Rt())t.has(o)||t.set(o,[]),t.get(o).push(r);if(t.delete("anthropic"),t.size===0)return[];let n=await(e.piDefaultModels??(()=>me()))();return[...t].map(([o,r])=>Ft(o,r,n[o]))}function Lt(e){return e.charAt(0).toUpperCase()+e.slice(1)}function jt(e,t){let n=e.filter(i=>i.gatewayManaged!==!1),o={};for(let i of n)(o[i.endpoint]||=[]).push(i);let r=Ht(n,e,t);return Ut(r,o),Yt(r,e),r.push(""),r.join(`
5
- `)}function Ht(e,t,n){let o=[];o.push("# aistatus gateway \u2014 auto-generated by cortex init"),o.push(`# Generated: ${new Date().toISOString()}`),o.push("#"),o.push("# Per-mode routing: each mode maps to an endpoint + auth config."),o.push("# Managed keys are used first (with round-robin on 429/5xx),"),o.push("# then passthrough of the caller's own key when passthrough: true."),o.push("#"),o.push("# Docs: https://aistatus.cc/docs"),o.push("");let r=n||e[0]?.mode||t[0]?.mode||"api",i=e.map(s=>s.mode).filter((s,a,u)=>u.indexOf(s)===a);return o.push(`port: ${p.port}`),o.push(`mode: ${r}${i.length>0?` # active billing mode: ${i.join(" | ")}`:""}`),o.push("status_check: true"),o.push(`max_body_size_mb: ${B} # buffered request limit in MiB`),o}function Ut(e,t){for(let[n,o]of Object.entries(t)){e.push(""),e.push(`${n}:`);for(let r of o)Kt(e,r)}}function Kt(e,t){let n=t.mode==="plan"?"Anthropic Claude (OAuth passthrough, billed via subscription)":t.mode==="api"?"Anthropic Claude (API key, billed via API credits)":`${Lt(t.mode)} (PI-managed auth, routed through gateway)`;e.push(` # \u2500\u2500 ${n} \u2500\u2500`),e.push(` ${t.mode}:`),e.push(` base_url: ${t.base_url}`),e.push(` auth_style: ${t.auth_style}`),Gt(e,t)}function Gt(e,t){if(t.keys.length>0){e.push(" keys:");for(let n of t.keys)e.push(` - ${n}`)}else e.push(` # No managed keys \u2014 ${t.passthrough?"caller key passthrough":"waiting for key configuration"}`);t.passthrough&&t.keys.length>0&&e.push(" passthrough: true")}function Yt(e,t){let n=t.filter(o=>o.gatewayManaged===!1);if(n.length>0){e.push(""),e.push("# Skipped (no known upstream URL in PI_PROVIDER_UPSTREAM):");for(let o of n)e.push(`# ${o.mode} (${o.models.length} model${o.models.length===1?"":"s"})`);e.push("# These providers appear in models.json but are not routed through this gateway.")}}function w(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function zt(e){return Tt.some(t=>t in e)}function Ne(e){return JSON.parse(JSON.stringify(e))}function y(e){if(!z(e))return null;let t;try{t=(0,I.parse)(Fe(e,"utf-8"))}catch(r){return f.warn(`Failed to parse existing gateway.yaml (${e}): ${r.message} \u2014 regenerating from scratch`),null}if(!w(t))return null;let n={},o={};for(let[r,i]of Object.entries(t)){if(St.has(r)){n[r]=i;continue}if(w(i)){if(zt(i)){o[r]??={},o[r][Y]=i;continue}for(let[s,a]of Object.entries(i))w(a)&&(o[r]??={},o[r][s]=a)}}return{top:n,endpoints:o}}function Bt(e){let t={};for(let n of e){if(n.gatewayManaged===!1)continue;let o={base_url:n.base_url,auth_style:n.auth_style};n.keys.length>0&&(o.keys=[...n.keys],n.passthrough&&(o.passthrough=!0)),t[n.endpoint]??={},t[n.endpoint][n.mode]=o}return t}function Wt(e,t,n){let o=Bt(e),r=t?Ne(t.endpoints):{},{preservedCustom:i,droppedFromDiscovery:s}=Vt(r,o);Jt(r,o);let a=qt(r,e,n,t?.top.mode),u=t?Ne(t.top):{};return u.port=A(p,u.port),u.mode=a,u.status_check=u.status_check??!0,u.max_body_size_mb=u.max_body_size_mb??B,{endpoints:r,top:u,preservedCustom:i,droppedFromDiscovery:s}}function Vt(e,t){let n=[],o=[];for(let[r,i]of Object.entries(e))for(let s of Object.keys(i)){if(t[r]?.[s])continue;n.push({endpoint:r,mode:s}),r==="anthropic"&&(s==="plan"||s==="api")||o.push({endpoint:r,mode:s})}return{preservedCustom:n,droppedFromDiscovery:o}}function Jt(e,t){for(let[n,o]of Object.entries(t)){e[n]??={};for(let[r,i]of Object.entries(o))e[n][r]||(e[n][r]=i)}}function qt(e,t,n,o){let r=new Set;for(let a of Object.values(e))for(let u of Object.keys(a))r.add(u);let i=typeof o=="string"?o:void 0,s=t.find(a=>a.gatewayManaged!==!1)?.mode;return[n,i,s].find(a=>a&&r.has(a))??r.values().next().value??"api"}function C(e){let t={};t.port=A(p,e.top.port),t.mode=e.top.mode,t.status_check=e.top.status_check??!0,t.max_body_size_mb=e.top.max_body_size_mb??B;for(let n of["host","auth","endpoint_modes","endpoints"])e.top[n]!==void 0&&(t[n]=e.top[n]);return Xt(t,e.endpoints),Qt()+(0,I.stringify)(t,{lineWidth:0})}function Xt(e,t){for(let[n,o]of Object.entries(t)){let r=Object.keys(o);r.length===1&&r[0]===Y?e[n]=o[Y]:e[n]=o}}function Qt(){return["# aistatus gateway \u2014 managed by cortex (merge mode).",`# Generated: ${new Date().toISOString()}`,"#","# `cortex init` / `cortex setup-gateway` ADD newly discovered modes; existing modes and their","# keys are preserved as-is (never overwritten). Edit a route here to change its URL/keys.","# NOTE: inline comments inside existing blocks are not retained across regeneration.","#","# Docs: https://aistatus.cc/docs",""].join(`
6
- `)}function Jn(e,t,n){let o=M.join(t||F,"gateway.yaml"),r=y(o),i=Wt(e,r,n),s=C(i);if(z(o))try{Pe(o,o+".bak"),f.info(`Backed up existing gateway.yaml to ${o}.bak`)}catch(a){f.warn(`Failed to backup existing gateway.yaml: ${a.message}`)}return v(o,s),f.info(`Written merged gateway.yaml to ${o}`),{path:o,result:i}}function qn(e,t=h){let n=M.join(t,"models.json"),o;try{if(!z(n))return[];o=JSON.parse(Fe(n,"utf8"))}catch(i){return f.warn(`Failed to read models.json for validation: ${i.message}`),[]}return w(o)?[o.default,...Array.isArray(o.favorites)?o.favorites:[]].filter(w).flatMap(i=>Zt(i,e)):[]}function Zt(e,t){let n=typeof e.provider=="string"?e.provider:void 0,o=e.backend==="claude"?"anthropic":n,r=typeof e.mode=="string"?e.mode:"",i=String(e.model??"(unknown)");if(!o)return[{model:i,mode:r,reason:"PI model is missing a provider (cannot resolve gateway endpoint)"}];let s=t[o]??{};return(r?!!s[r]:Object.keys(s).length>0)?[]:[{model:i,mode:r,provider:n,reason:`endpoint "${o}" has no configured ${r?`mode "${r}"`:"route"} in gateway.yaml`}]}async function Xn(){let e=await Nt();return e.length===0?`# No backends discovered. Log into Claude Code and/or PI first.
7
- `:jt(e)}import{readFileSync as Le}from"node:fs";import*as je from"node:path";var V=l("models-repo"),X=0,He=je.join(h,"models.json"),io=new ue;function so(){return X}var J=class{filePath;cache=null;constructor(t=He){this.filePath=t}readSync(){return this.cache||(this.cache=JSON.parse(Le(this.filePath,"utf8"))),this.cache}readIfPresent(){try{return this.readSync()}catch(t){if(t.code==="ENOENT")return null;throw t}}invalidate(){this.cache=null,X+=1}reload(){let t=JSON.parse(Le(this.filePath,"utf8"));this.cache=t}},Q=new J,q=null;function ao(e){q=e}function en(e,t){try{e.reload(),X+=1,t?.(),V.info("Hot-reload: models.json reloaded"),q?.(`${P.refresh} \`models.json\` hot-reloaded`)}catch(n){V.error(`Hot-reload models.json failed: ${n.message} \u2014 keeping previous config`),q?.(`${P.warning} \`models.json\` hot-reload FAILED \u2014 keeping previous config`)}}function co(e=Q,t=He,n){let o=null,i=pe({label:"models.json",filePath:t,onChange:()=>{o&&clearTimeout(o),o=setTimeout(()=>{o=null,en(e,n)},300)},warn:s=>V.error(s)});return()=>{i.close(),o&&clearTimeout(o),o=null}}var tn=l("pi-adapter"),nn=5*6e4,on=3e4,rn=12e3;function sn(e={}){let t=new m({scan:e.scan??W,now:e.now,cacheTtlMs:e.cacheTtlMs??nn,retryMs:e.retryMs??on,key:o=>`${o.provider}\0${o.model}`,clone:o=>({...o}),logFailure:o=>tn.info(`PI provider refresh failed: ${o}`)}),n=()=>t.get();return{getProviders:()=>Array.from(new Set(n().map(o=>o.provider))),getModels:n,peekModels:()=>t.peek(),ensureModels:(o=rn)=>t.ensure(o),refresh:()=>t.refresh()}}var Ue=sn();import{copyFileSync as an,existsSync as cn}from"fs";var un=l("pi-custom-providers"),Ke=p.configPath;function Z(e){let t=y(e);return t?{top:{...t.top},endpoints:t.endpoints}:{top:{},endpoints:{}}}function Ge(e,t){if(cn(e))try{an(e,`${e}.bak`)}catch(o){un.warn(`Failed to back up ${e}: ${o.message}`)}let n=C({endpoints:t.endpoints,top:t.top,preservedCustom:[],droppedFromDiscovery:[]});v(e,n)}function Eo(e,t,n){let{endpoints:o}=Z(e);return o[t]?.[n]??null}function bo(e,t){let n=Z(e),o={base_url:t.base_url,auth_style:t.auth_style,passthrough:t.passthrough};t.keys.length>0&&(o.keys=[...t.keys]),n.endpoints[t.endpoint]={...n.endpoints[t.endpoint],[t.mode]:o},n.top.port=A(p,n.top.port),n.top.status_check??=!0,(typeof n.top.mode!="string"||n.top.mode==="")&&(n.top.mode=t.mode),Ge(e,n)}function wo(e,t,n){let o=Z(e),r=o.endpoints[t];if(!r||!(n in r))return!1;let i={...r};return delete i[n],Object.keys(i).length===0?delete o.endpoints[t]:o.endpoints[t]=i,Ge(e,o),!0}function k(e){return JSON.stringify([e.backend,e.provider,e.model])}var ln={claude:["low","medium","high","xhigh","max"],pi:["off","minimal","low","medium","high","xhigh","max"]};function dn(e,t){return ln[e]?.includes(t)??!1}var Ye=/^[a-zA-Z0-9_-]+$/;function x(e){let t=e;if(!t||t.backend!=="claude"&&t.backend!=="pi")throw new Error("Invalid backend");if(typeof t.model!="string"||!t.model.trim())throw new Error("Model must be a non-empty string");if(!(t.backend==="claude"?t.provider===null:typeof t.provider=="string"&&Ye.test(t.provider)))throw new Error("Invalid provider: PI requires a provider; Claude requires null")}function D(e){x(e);let t=e;if(t.thinking!==null&&!dn(t.backend,t.thinking))throw new Error(`Invalid thinking for backend '${t.backend}'`);if(typeof t.mode!="string"||!Ye.test(t.mode))throw new Error("Invalid mode")}function d(e){let{backend:t,provider:n,model:o,thinking:r,mode:i}=e;return{backend:t,provider:n,model:o,thinking:r,mode:i}}var ze=null;function pn(e){let t=e;if(D(t?.default),!Array.isArray(t.favorites))throw new Error("favorites must be an array");let n=new Set;for(let o of t.favorites){x(o);let r=k(o);if(n.has(r))throw new Error(`Duplicate favorite: ${o.model}`);n.add(r)}}function R(){try{let e=Q.readSync();return e!==ze&&(pn(e),ze=e),{default:d(e.default),favorites:e.favorites.map(ee)}}catch(e){throw new Error(`Failed to load models.json: ${e.message}`)}}function ee({backend:e,provider:t,model:n}){return{backend:e,provider:t,model:n}}function te(){return R().default}function Do(){return R().favorites}function We(e){let t;try{t=R()}catch{return null}if(t.default.backend===e)return t.default;let n=t.favorites.find(o=>o.backend===e);return n?fn(n):null}function fn(e){x(e);let t=Be()[k(e)];return{...ee(e),...t??{thinking:null,mode:hn(e)}}}function hn(e,t=()=>y(Ke)){if(e.backend==="pi")return e.provider;let n=t()?.endpoints?.anthropic;return Object.keys(n??{})[0]??"plan"}function mn(e){let t=e.indexOf("/");if(t<0)return null;let n={backend:"pi",provider:e.slice(0,t),model:e.slice(t+1)};return x(n),n}function gn(e,t){let o=[t.default,...t.favorites,...Ue.peekModels().map(r=>({...r,backend:"pi"}))].find(r=>r.backend==="pi"&&r.model===e);if(o)return ee(o);if(t.default.backend==="pi")return{backend:"pi",provider:t.default.provider,model:e};throw new Error(`Unknown PI model '${e}': specify provider/model or favorite a model first`)}function Ro(e,t){let n=e.trim();if(!n)throw new Error("Model must be a non-empty string");let o=mn(n);if(o)return o;let r=R();return(t??r.default.backend)==="claude"?{backend:"claude",provider:null,model:n}:gn(n,r)}import{readFileSync as yn,renameSync as _n,writeFileSync as vn}from"node:fs";import*as qe from"node:path";var re=qe.join(le,"agent-state.json");function N(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Ve(e){try{return D(e),d(e)}catch{return null}}function ne(e,t){let n=Object.entries(N(e)).map(([o,r])=>[o,t(r)]);return Object.fromEntries(n.filter(([,o])=>o!==null))}function An(e){let t=N(e);return!(t.thinking===null||typeof t.thinking=="string"&&!!t.thinking)||typeof t.mode!="string"||!t.mode?null:{thinking:t.thinking,mode:t.mode}}function oe(e){return typeof e=="string"&&e?e:null}function Je(e){let t=N(e),n={channelSelections:ne(t.channelSelections,Ve),modelMemory:ne(t.modelMemory,An),defaultAgent:oe(t.defaultAgent),channelAgents:ne(t.channelAgents,oe)},o=Ve(t.selectionDefault);if(o){n.selectionDefault=o;let r=oe(N(t.selectionDefault).agentName);r&&(n.selectionDefault.agentName=r)}return n}function ie(){try{return Je(JSON.parse(yn(re,"utf8")))}catch{return Je(null)}}function Xe(e){let t={};for(let o of["channelSelections","modelMemory","channelAgents"])Object.keys(e[o]).length&&(t[o]=e[o]);e.defaultAgent&&(t.defaultAgent=e.defaultAgent),e.selectionDefault&&(t.selectionDefault=e.selectionDefault);let n=`${re}.tmp`;vn(n,JSON.stringify(t)),_n(n,re)}var c=ie();function Ko(){c=ie()}function _(e){Xe(e),c=e}function se(e,t,n){let o={...e};return n!==null?o[t]=n:delete o[t],o}function En(e){let t=e?c.channelSelections[e]:null;return t?d(t):null}function Go(e,t){let n=t?d(t):null;_({...c,channelSelections:se(c.channelSelections,e,n)})}function Be(){return Object.fromEntries(Object.entries(c.modelMemory).map(([e,t])=>[e,{...t}]))}function Yo(e){let t={thinking:e.thinking,mode:e.mode};_({...c,modelMemory:se(c.modelMemory,k(e),t)})}function zo(){try{return We("claude")?.model??"opus"}catch{return"opus"}}function Bo(e){let t=En(e);if(t)return t.backend;try{return te().backend}catch{return"claude"}}function Wo(e){let t=e?.agentName??c.selectionDefault?.agentName,n=e?{...d(e),...t?{agentName:t}:{}}:void 0;_({...c,selectionDefault:n})}function Vo(e){let t={...c.selectionDefault??te()};e?t.agentName=e:delete t.agentName,_({...c,selectionDefault:t})}function Jo(){return c.selectionDefault?{...c.selectionDefault}:null}function qo(e){return e&&c.channelAgents[e]||c.defaultAgent}function bn(e,t){if(!t)return _({...c,defaultAgent:e});_({...c,channelAgents:se(c.channelAgents,t,e)})}function Xo(e){c.channelAgents[e]&&bn(null,e)}function Qo(){return{...c.channelAgents}}export{g as a,H as b,be as c,xe as d,Mn as e,In as f,G as g,Cn as h,Ce as i,$n as j,De as k,Vn as l,Nt as m,y as n,Jn as o,qn as p,Xn as q,Ue as r,He as s,io as t,so as u,Q as v,ao as w,co as x,Ke as y,Eo as z,bo as A,wo as B,k as C,ln as D,dn as E,x as F,D as G,Ko as H,En as I,Go as J,Be as K,Yo as L,zo as M,Bo as N,Wo as O,Vo as P,Jo as Q,qo as R,bn as S,Xo as T,Qo as U,te as V,Do as W,We as X,fn as Y,hn as Z,Ro as _};
@@ -1,12 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{a as V,c as Q}from"./chunk-HALUQ7ZF.js";import{a as H}from"./chunk-Q4UGYGU5.js";import{c as K}from"./chunk-W5LGYSPZ.js";import{e as a}from"./chunk-E7ZMYIY6.js";import{l as W,m as X}from"./chunk-J5DVLUKY.js";import*as k from"path";import w from"node:fs/promises";var at=2160*60*60*1e3,A={daily_usd:300,monthly_usd:8e3,projects:{}};function M(t){return typeof t=="number"&&Number.isFinite(t)&&t>0}function ct(t){if(!t||typeof t!="object"||Array.isArray(t))return{};let e={};for(let[o,n]of Object.entries(t)){if(!o||!n||typeof n!="object")continue;let{daily_usd:s,monthly_usd:i}=n;!M(s)||!M(i)||(e[o]={daily_usd:s,monthly_usd:i})}return e}function ut(t){let e=t&&typeof t=="object"?t:{};return{daily_usd:M(e.daily_usd)?e.daily_usd:A.daily_usd,monthly_usd:M(e.monthly_usd)?e.monthly_usd:A.monthly_usd,projects:ct(e.projects)}}function dt(){return process.env.CORTEX_COSTS_FILE||k.join(X,"costs.jsonl")}function lt(){return process.env.CORTEX_BUDGET_FILE||k.join(W,"budget.json")}var z=class{costMutex=new H;_ready=!1;_cache=null;_budgetRepo=null;_costsPath;_budgetPath;constructor(e={}){this._costsPath=e.costsPath??null,this._budgetPath=e.budgetPath??null}get costFilePath(){return this._costsPath??dt()}get budgetRepo(){return this._budgetRepo||(this._budgetRepo=new Q({filePath:this._budgetPath??lt(),defaultValue:()=>({...A,projects:{}}),migrate:ut})),this._budgetRepo}async _ensureReady(){if(this._ready)return;let e=this.costFilePath;await w.mkdir(k.dirname(e),{recursive:!0});let o=await this._readFileEntries(e),n=Date.now()-at,s=o.filter(i=>new Date(i.timestamp).getTime()>n);if(s.length<o.length){let i=s.map(c=>JSON.stringify(c)).join(`
5
- `)+`
6
- `;await K(e,i)}this._ready=!0}async _readEntriesRange(e,o,n){if(n<=o)return{entries:[],consumedTo:o};let s=await w.open(e,"r");try{let i=Buffer.allocUnsafe(n-o),{bytesRead:c}=await s.read(i,0,i.length,o),u=c>0?i.lastIndexOf(10,c-1):-1;return u<0?{entries:[],consumedTo:o}:{entries:i.toString("utf8",0,u+1).split(`
7
- `).filter(h=>h.trim()!=="").map(h=>JSON.parse(h)),consumedTo:o+u+1}}finally{await s.close()}}async _readFileEntries(e){try{return(await w.readFile(e,"utf8")).split(`
8
- `).filter(n=>n.trim()!=="").map(n=>JSON.parse(n))}catch(o){if(o.code==="ENOENT")return[];throw o}}async recordEntry(e){await this.costMutex.run(async()=>{await this._ensureReady(),await w.appendFile(this.costFilePath,JSON.stringify(e)+`
9
- `,"utf8")})}async recordEntryBatch(e){if(e.length===0)return;let o=e.map(n=>JSON.stringify(n)).join(`
10
- `)+`
11
- `;await this.costMutex.run(async()=>{await this._ensureReady(),await w.appendFile(this.costFilePath,o,"utf8")})}async readCosts(){await this._ensureReady();let e=this.costFilePath,o,n,s;try{let d=await w.stat(e);o=d.ino,n=d.size,s=d.mtimeMs}catch(d){if(d.code!=="ENOENT")throw d;return this._cache=null,{entries:[]}}let i=this._cache?.path===e&&this._cache.ino===o?this._cache:null;if(i&&n===i.size&&s===i.mtimeMs)return{entries:i.entries.slice()};if(i&&n>i.size){let{entries:d,consumedTo:h}=await this._readEntriesRange(e,i.size,n),l=i.entries.concat(d);return this._cache={path:e,ino:o,size:h,mtimeMs:s,entries:l},{entries:l.slice()}}let{entries:c,consumedTo:u}=await this._readEntriesRange(e,0,n);return this._cache={path:e,ino:o,size:u,mtimeMs:s,entries:c},{entries:c.slice()}}async readBudget(){return this.budgetRepo.read()}async writeBudget(e){await this.budgetRepo.write(e)}invalidateBudget(){this._budgetRepo?.invalidate()}async flush(){await this.costMutex.run(async()=>{}),this._budgetRepo&&await this._budgetRepo.flush()}_testReset(){this._budgetRepo=null,this._ready=!1,this._cache=null}},y=new z;V(y);function ht(t,e){let o=e?t.projects?.[e]:void 0;return o?{daily_usd:o.daily_usd,monthly_usd:o.monthly_usd,scope:"project"}:{daily_usd:t.daily_usd,monthly_usd:t.monthly_usd,scope:"global"}}var yt=["total","api","plan"];function st(t){return t==="plan"?"plan":"api"}function j(){return{today:0,week:0,month:0,total:0}}function E(){return Object.fromEntries(yt.map(t=>[t,0]))}function O(t,e,o){t.total+=o,t[e]+=o}async function Rt(t){let e=t.source||"estimate",o=[t.input_tokens,t.output_tokens,t.cache_read_tokens,t.cache_creation_tokens,t.provider_requests].some(s=>s!=null);if(e==="estimate"&&!t.cost_usd&&!o)return;let n={timestamp:new Date().toISOString(),project:t.project||"general",trigger:t.trigger||"unknown",cost_usd:t.cost_usd??null,num_turns:t.num_turns??null,duration_s:t.duration_s??null,backend:t.backend||"claude",mode:st(t.mode),source:e,input_tokens:t.input_tokens??null,output_tokens:t.output_tokens??null,cache_read_tokens:t.cache_read_tokens??null,cache_creation_tokens:t.cache_creation_tokens??null,provider_requests:Number.isSafeInteger(t.provider_requests)&&Number(t.provider_requests)>0?t.provider_requests:null,session_id:t.session_id??null,execution_id:t.execution_id??null,attempt_id:t.attempt_id??null,root_attempt_id:t.root_attempt_id??null,trial_id:t.trial_id??null,root_run_id:t.root_run_id??null};t.prompt_tokens!==void 0&&(n.prompt_tokens=t.prompt_tokens),t.provider&&(n.provider=t.provider),t.model&&(n.model=t.model),await y.recordEntry(n)}function L(){return{input:0,output:0}}var Z=1440*60*1e3,mt=14;function tt(t){let e=t.getFullYear(),o=String(t.getMonth()+1).padStart(2,"0"),n=String(t.getDate()).padStart(2,"0");return`${e}-${o}-${n}`}function S(t,e,o,n,s){t.total+=e,o&&(t.today+=e),n&&(t.week+=e),s&&(t.month+=e)}async function it(t,e){let o=await y.readCosts(),n=await y.readBudget(),s=e?.now??Date.now(),i=new Date(s);i.setHours(0,0,0,0);let c=new Date(s-7*Z),u=new Date(s);u.setDate(1),u.setHours(0,0,0,0);let d=[];for(let r=mt-1;r>=0;r--){let p=new Date(i);p.setDate(p.getDate()-r),d.push(tt(p))}let h=new Map(d.map(r=>[r,0])),l={today:E(),week:E(),month:E(),total:E()},B={},x={},R={},F={},T={},_={today:L(),month:L(),total:L()},Y=0,q=0;for(let r of o.entries){let p=st(r.mode),m=r.cost_usd||0,v=r.source||"estimate",$=r.backend||"claude",P=new Date(r.timestamp),f=P>=i,b=P>=c,g=P>=u;if(!t||r.project===t){Y++,r.cost_usd==null&&q++,O(l.total,p,m),f&&O(l.today,p,m),b&&O(l.week,p,m),g&&O(l.month,p,m);let C=Object.hasOwn(r,"prompt_tokens")?r.prompt_tokens||0:r.input_tokens||0,N=r.output_tokens||0;_.total.input+=C,_.total.output+=N,f&&(_.today.input+=C,_.today.output+=N),g&&(_.month.input+=C,_.month.output+=N);let I=tt(P);h.has(I)&&h.set(I,h.get(I)+m),R[r.trigger]||(R[r.trigger]=j()),S(R[r.trigger],m,f,b,g)}B[r.project]||(B[r.project]=j()),x[r.trigger]||(x[r.trigger]=j()),F[v]||(F[v]=j()),T[$]||(T[$]=j()),S(B[r.project],m,f,b,g),S(x[r.trigger],m,f,b,g),S(F[v],m,f,b,g),S(T[$],m,f,b,g)}let U=l.today.total,G=(s-i.getTime())/Z,rt=G>0?U/G:U,D=ht(n,t);return{today:l.today.total,week:l.week.total,month:l.month.total,total:l.total.total,byMode:l,byProject:B,byTrigger:x,bySource:F,byBackend:T,tokens:_,entryCount:Y,unpricedCount:q,dailyBudget:D.daily_usd,monthlyBudget:D.monthly_usd,budgetScope:D.scope,forecastToday:rt,dailyCost:d.map(r=>({date:r,cost:h.get(r)})),byTriggerScoped:R}}async function Ft(t){let e=t??null,o=await it(e),{dailyBudget:n,monthlyBudget:s}=o;return{withinBudget:o.today<n&&o.month<s,dailyBudget:n,dailySpent:o.today,dailyRemaining:Math.max(0,n-o.today),monthlyBudget:s,monthlySpent:o.month,monthlyRemaining:Math.max(0,s-o.month),byMode:o.byMode,project:e,scope:o.budgetScope}}async function Tt({daily_usd:t,monthly_usd:e,project:o}){let n=await y.readBudget();if(o){if(t==null||e==null)throw Object.assign(new Error("A per-project budget must set both daily and monthly limits"),{code:"invalid-args"});return n.projects={...n.projects,[o]:{daily_usd:t,monthly_usd:e}},await y.writeBudget(n),{daily_usd:t,monthly_usd:e,scope:"project"}}return t!=null&&(n.daily_usd=t),e!=null&&(n.monthly_usd=e),await y.writeBudget(n),{daily_usd:n.daily_usd,monthly_usd:n.monthly_usd,scope:"global"}}async function Pt(t){let e=await y.readBudget();if(!e.projects?.[t])return!1;let{[t]:o,...n}=e.projects;return e.projects=n,await y.writeBudget(e),!0}async function Mt(){let t=await y.readBudget();return Object.entries(t.projects??{}).map(([e,o])=>({project:e,...o})).sort((e,o)=>e.project.localeCompare(o.project))}function et(t,e){return{today:t.today[e],week:t.week[e],month:t.month[e],total:t.total[e]}}function ot(t,e){return` - ${a("notice.cost.modeLine",{label:t,today:e.today.toFixed(2),week:e.week.toFixed(2),month:e.month.toFixed(2),total:e.total.toFixed(2)})}`}function nt(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}k`:String(t)}function pt(t,e){return`\u2022 ${a("notice.cost.statsLine",{name:t,today:e.today.toFixed(2),month:e.month.toFixed(2),total:e.total.toFixed(2)})}`}function J(t,e,o){t.push(""),t.push(`_${e}_`);for(let[n,s]of Object.entries(o).sort((i,c)=>c[1].total-i[1].total))t.push(pt(n,s))}function _t(t,e){if(!t)return`*${a("notice.cost.title")}*`;let o=e==="project"?a("notice.cost.scopeProject"):a("notice.cost.scopeInherited");return`*${a("notice.cost.titleProject",{project:t})}* _(${o})_`}async function Et(t=null){let e=await it(t),o=Math.max(0,e.dailyBudget-e.today),n=Math.max(0,e.monthlyBudget-e.month),s=[];s.push(_t(t,e.budgetScope)),s.push(`\u2022 ${a("notice.cost.today",{spent:e.today.toFixed(2),budget:e.dailyBudget,remaining:o.toFixed(2)})}`),s.push(`\u2022 ${a("notice.cost.month",{spent:e.month.toFixed(2),budget:e.monthlyBudget,remaining:n.toFixed(2)})}`),s.push(`\u2022 ${a("notice.cost.week",{spent:e.week.toFixed(2)})}`),s.push(`\u2022 ${a("notice.cost.total",{spent:e.total.toFixed(2)})}`),s.push(""),s.push(`_${a("notice.cost.byMode")}_`),s.push(ot("API",et(e.byMode,"api"))),s.push(ot("Plan",et(e.byMode,"plan"))),Object.keys(e.bySource).length>0&&J(s,a("notice.cost.bySource"),e.bySource),"pi"in e.byBackend&&J(s,a("notice.cost.byBackend"),e.byBackend);let i=e.tokens;if(i.total.input>0||i.total.output>0){s.push(""),s.push(`_${a("notice.cost.tokenUsage")}_`);for(let[c,u]of[["notice.cost.tokensToday",i.today],["notice.cost.tokensMonth",i.month],["notice.cost.tokensTotal",i.total]])s.push(`\u2022 ${a(c,{input:nt(u.input),output:nt(u.output)})}`)}if(!t&&Object.keys(e.byProject).length>0){s.push(""),s.push(`_${a("notice.cost.byProject")}_`);for(let[c,u]of Object.entries(e.byProject).sort((d,h)=>h[1].month-d[1].month))s.push(`\u2022 ${a("notice.cost.projectLine",{name:c,today:u.today.toFixed(2),month:u.month.toFixed(2)})}`)}return Object.keys(e.byTrigger).length>0&&J(s,a("notice.cost.byTrigger"),e.byTrigger),s.join(`
12
- `)}export{y as a,Rt as b,it as c,Ft as d,Tt as e,Pt as f,Mt as g,nt as h,Et as i};
@@ -1,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{b as e}from"./chunk-OSEIQ7SS.js";var r;function i(t){r=t}var n=()=>e(async()=>r??await import("./bedrock-converse-stream-5UPX4NTQ.js"));export{i as a,n as b};
@@ -1,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- var o={"anthropic-messages":{"chat:claude-fable-5":{id:"claude-fable-5",name:"Claude Fable 5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:10,output:50,cacheRead:1,cacheWrite:12.5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,forceAdaptiveThinking:!0},thinkingLevelMap:{off:null,xhigh:"xhigh",max:"max"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-fable-5.1":{id:"claude-fable-5.1",name:"Claude Fable 5.1",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:10,output:50,cacheRead:.25,cacheWrite:12.5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,forceAdaptiveThinking:!0},thinkingLevelMap:{off:null,xhigh:"xhigh",max:"max"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-haiku-4.5":{id:"claude-haiku-4.5",name:"Claude Haiku 4.5 (latest)",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:1,output:5,cacheRead:.1,cacheWrite:1.25},contextWindow:2e5,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsEagerToolInputStreaming:!1},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-haiku-5.5":{id:"claude-haiku-5.5",name:"Claude Haiku 5.5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.1,output:.5,cacheRead:.01,cacheWrite:.125,tiers:[{inputTokensAbove:1e5,input:.5,output:2.5,cacheRead:.05,cacheWrite:.625}]},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,forceAdaptiveThinking:!0,supportsTemperature:!1},thinkingLevelMap:{xhigh:"xhigh",max:"max"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-opus-4.8":{id:"claude-opus-4.8",name:"Claude Opus 4.8",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,forceAdaptiveThinking:!0,supportsTemperature:!1},thinkingLevelMap:{xhigh:"xhigh",max:"max",minimal:"low"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-opus-5":{id:"claude-opus-5",name:"Claude Opus 5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,forceAdaptiveThinking:!0,supportsTemperature:!1},thinkingLevelMap:{xhigh:"xhigh",max:"max",minimal:"low"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-opus-5.5":{id:"claude-opus-5.5",name:"Claude Opus 5.5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:4,output:20,cacheRead:.2,cacheWrite:5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,forceAdaptiveThinking:!0,supportsTemperature:!1},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-sonnet-4.6":{id:"claude-sonnet-4.6",name:"Claude Sonnet 4.6",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:1e6,maxTokens:32e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{max:"max",minimal:"low"},compat:{forceAdaptiveThinking:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-sonnet-5":{id:"claude-sonnet-5",name:"Claude Sonnet 5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:10,cacheRead:.2,cacheWrite:2.5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{xhigh:"xhigh",max:"max"},compat:{forceAdaptiveThinking:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:claude-sonnet-5.5":{id:"claude-sonnet-5.5",name:"Claude Sonnet 5.5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:10,cacheRead:.1,cacheWrite:2.5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsMidConvoSystemMessages:!0,forceAdaptiveThinking:!0,supportsTemperature:!1},thinkingLevelMap:{xhigh:"xhigh",max:"max"},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"}},"openai-completions":{"chat:gemini-3.8-flash":{id:"gemini-3.8-flash",name:"Gemini 3.8 Flash",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.75,output:3.75,cacheRead:.075,cacheWrite:0},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStrictMode:!0,supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gemini-4-argon":{id:"gemini-4-argon",name:"Gemini 4 Argon",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:10,cacheRead:.1,cacheWrite:0},contextWindow:1048576,maxTokens:65536,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStrictMode:!0,supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:kimi-k3":{id:"kimi-k3",name:"Kimi K3",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:0},contextWindow:1048576,maxTokens:131072,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStrictMode:!0,supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,supportsMidConvoSystemMessages:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"}},"openai-responses":{"chat:gpt-5.3-codex":{id:"gpt-5.3-codex",name:"GPT-5.3 Codex",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.4-nano":{id:"gpt-5.4-nano",name:"GPT-5.4 nano",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.2,output:1.25,cacheRead:.02,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.6-luna":{id:"gpt-5.6-luna",name:"GPT-5.6 Luna",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.2,output:1.2,cacheRead:.02,cacheWrite:.25,tiers:[{inputTokensAbove:2e5,input:.4,output:1.8,cacheRead:.04,cacheWrite:.5}]},contextWindow:105e4,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.6-sol":{id:"gpt-5.6-sol",name:"GPT-5.6 Sol",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:4,output:20,cacheRead:.4,cacheWrite:5,tiers:[{inputTokensAbove:272e3,input:8,output:30,cacheRead:.8,cacheWrite:10}]},contextWindow:105e4,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.6-terra":{id:"gpt-5.6-terra",name:"GPT-5.6 Terra",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:12,cacheRead:.2,cacheWrite:2.5,tiers:[{inputTokensAbove:272e3,input:4,output:18,cacheRead:.4,cacheWrite:5}]},contextWindow:105e4,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-6-astra":{id:"gpt-6-astra",name:"GPT-6 Astra",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:10,output:50,cacheRead:1,cacheWrite:12.5,tiers:[{inputTokensAbove:272e3,input:20,output:75,cacheRead:2,cacheWrite:25}]},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-6-luna":{id:"gpt-6-luna",name:"GPT-6 Luna",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.1,output:.5,cacheRead:.01,cacheWrite:.125,tiers:[{inputTokensAbove:272e3,input:.2,output:.75,cacheRead:.02,cacheWrite:.25}]},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:"none",minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-6-sol":{id:"gpt-6-sol",name:"GPT-6 Sol",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:10,cacheRead:.2,cacheWrite:2.5,tiers:[{inputTokensAbove:272e3,input:4,output:15,cacheRead:.4,cacheWrite:5}]},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:"none",minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-6.1-sol":{id:"gpt-6.1-sol",name:"GPT-6.1 Sol",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:10,cacheRead:.1,cacheWrite:2.5,tiers:[{inputTokensAbove:272e3,input:4,output:15,cacheRead:.2,cacheWrite:5}]},contextWindow:105e4,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0,supportsMidConvoSystemMessages:!0,supportsAdditionalTools:!0},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:grok-4.5":{id:"grok-4.5",name:"Grok 4.5",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:6,cacheRead:.5,cacheWrite:0,tiers:[{inputTokensAbove:2e5,input:4,output:12,cacheRead:1,cacheWrite:0}]},contextWindow:5e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:null,max:null},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:grok-4.6":{id:"grok-4.6",name:"Grok 4.6",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:6,cacheRead:.5,cacheWrite:0,tiers:[{inputTokensAbove:2e5,input:4,output:12,cacheRead:1,cacheWrite:0}]},contextWindow:5e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:grok-4.7":{id:"grok-4.7",name:"Grok 4.7",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:6,cacheRead:.5,cacheWrite:0,tiers:[{inputTokensAbove:2e5,input:4,output:12,cacheRead:1,cacheWrite:0}]},contextWindow:5e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:mai-code-1.1-flash":{id:"mai-code-1.1-flash",name:"MAI-Code-1.1-Flash",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.2,output:1.2,cacheRead:.02,cacheWrite:0},contextWindow:256e3,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:null,max:null},inputLimits:{images:{resize:{maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80}}},type:"chat"}}};function a(e,t){return Object.fromEntries(Object.values(e).flatMap(i=>Object.values(i)).filter(i=>i.type===t).map(i=>[i.id,i]))}function s(e,t){return a(t,"chat")}function n(e,t){return a(t,"image")}function p(e,t){return a(t,"classifier")}var d=s("github-copilot",o),m=n("github-copilot",o),g=p("github-copilot",o);export{s as a,n as b,p as c,d,m as e,g as f};
@@ -1,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{c as k}from"./chunk-HALUQ7ZF.js";import{D as w,E as T,V as a,Y as S,_}from"./chunk-TZFLHVOQ.js";import{m as l}from"./chunk-J5DVLUKY.js";function D(e){if(!e||typeof e=="object")return!1;let t=typeof e=="string"?e:String(e);return!(!t.trim()||t==="null"||t==="undefined")}function J(e,t){return e.some(n=>n.status==="running"&&n.kind==="scheduled"&&n.scheduleTaskId===t)}var I=["interval","daily","weekly","once"],N={sun:0,mon:1,tue:2,wed:3,thu:4,fri:5,sat:6},u=class extends Error{field;value;constructor(t,n,r){super(n),this.field=t,this.value=r,this.name="ScheduleSpecError"}},$={s:1e3,m:6e4,h:36e5,d:864e5};function R(e){let t=e?.trim().match(/^(\d+(?:\.\d+)?)(s|m|h|d)$/i);return t?Math.round(parseFloat(t[1])*$[t[2].toLowerCase()]):null}function f(e,t){if(e===void 0||e==="")throw new u(t,`${t} is required (e.g. 30m, 2h, 1d)`);let n=typeof e=="number"?Math.round(e):R(e);if(n===null||!Number.isFinite(n)||n<=0)throw new u(t,`invalid ${t}: '${e}' (use 30s, 5m, 2h, 1d)`,e);return n}function m(e){if(!e)throw new u("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 u("time",`invalid time: '${e}' (use HH:MM, 24-hour)`,e);return t[0]}function b(e){if(e===void 0||e==="")throw new u("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):N[t];if(!Number.isInteger(n)||n<0||n>6)throw new u("dayOfWeek",`invalid dayOfWeek: '${e}' (use sun..sat or 0-6)`,e);return n}function E(e){let t=typeof e=="string"?e.trim():"";if(!D(t))throw new u("message","message must be a non-empty prompt",e);return t}function C(e){return I.includes(e)}var H={interval:e=>({type:"interval",intervalMs:f(e.interval,"interval")}),daily:e=>({type:"daily",time:m(e.time)}),weekly:e=>({type:"weekly",dayOfWeek:b(e.dayOfWeek),time:m(e.time)}),once:e=>({type:"once",delayMs:f(e.delay,"delay")})};function Z(e){if(!C(e.type))throw new u("type",`invalid type: '${e.type}' (valid: ${I.join(", ")})`,e.type);let t=H[e.type](e),n=e.preCheck?.trim();return{...t,message:E(e.message),projectId:e.projectId?.trim()||"general",selection:e.selection?{...e.selection}:void 0,...n?{preCheck:n}:{}}}var L=new Set(["memory-index-regen"]),v=["message","projectId","selection","dispatchType","preCheck"],F={interval:["intervalMs"],daily:["time"],weekly:["dayOfWeek","time"],once:["runAt"]};function W(e,t){let n=Object.keys(t);if(n.length===0)throw new u("patch","nothing to update \u2014 provide at least one field");let r=new Set([...v,...F[e]]),s=n.filter(i=>!r.has(i));if(s.length)throw new u("patch",`invalid fields for ${e}: ${s.join(", ")}`,s)}function U(e){if(e.dispatchType&&L.has(e.dispatchType))throw new u("dispatchType",`built-in job dispatch type cannot be scheduled: ${e.dispatchType}`);if("intervalMs"in e&&f(e.intervalMs,"intervalMs"),"dayOfWeek"in e&&b(e.dayOfWeek),"runAt"in e&&!(Number.isFinite(e.runAt)&&e.runAt>0))throw new u("runAt","runAt must be a positive epoch ms",e.runAt)}function j(e,t){W(e,t),U(t);let n={...t};return"message"in t&&(n.message=E(t.message)),"time"in t&&(n.time=m(t.time)),n}function B(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 V(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 Y(e,t=Date.now()){return e.type==="daily"?B(e.time,t):e.type==="weekly"?V(e.dayOfWeek,e.time,t):e.intervalMs||6e4}function c(e,t=Date.now()){e.type!=="once"&&(e.nextRun=e.isPaused?null:t+Y(e,t))}function M(e,t,n,r){let{message:s,projectId:i,preCheck:o,selection:y,...d}=e,x={id:t,message:s,projectId:i,selection:{...r},preCheck:o,createdAt:n};if(d.type==="once")return{...x,type:"once",runAt:n+d.delayMs};let g={...x,...d,lastRun:null,nextRun:null};return c(g,n),g}function se(e,t,n){if(e===void 0&&t===void 0)return;let r=e===void 0?n??a():S(_(e));if(t===void 0)return{...r};if(!T(r.backend,t)){let s=w[r.backend].join(", ");throw new u("thinking",`Invalid thinking '${t}' for ${r.backend}. Valid values: ${s}`,t)}return{...r,thinking:t}}import*as h from"path";import*as O from"fs";var z=h.join(l,"schedules.json"),K=h.join(l,"channel-registry.json");function P(){return{tasks:[]}}function A(e){try{let t=O.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 ae(e){return A()[e]??null}function G(e){return function(n){if(typeof n!="object"||n===null||!("tasks"in n))return P();let r=n,s=A(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}return r}}var p=class{_repo;constructor(t=z,n){this._repo=new k({filePath:t,defaultValue:P,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()}},ce=new p,de=new Set(["task-dispatch","task-archive"]);import{randomBytes as q}from"crypto";async function he(e,t,n={}){let r=M(t,q(4).toString("hex"),Date.now(),t.selection??a()),s=n.idempotencyKey;return s&&(r.idempotencyKey=s),e.mutate(i=>{let o=s?i.tasks.find(y=>y.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 ye(e,t,n){return e.updateTask(t,r=>{Object.assign(r,j(r.type,n)),c(r)})}function xe(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 ge(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}),c(n))})}export{D as a,J as b,I as c,u as d,f as e,b as f,C as g,Z as h,j as i,Y as j,se as k,z as l,ae as m,p as n,ce as o,de as p,he as q,ye as r,xe as s,ge as t};
@@ -1,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import i from"node:fs/promises";import m from"node:path";var g=10,O=3e4,M=2e4,A=1e3;function p(t){return`${t}.mutation-lock`}var w=class extends Error{filePath;timeoutMs;holderPid;constructor(e,r,n){let a=n===null?"":` held by pid ${n}`;super(`Timed out after ${r} ms waiting for the lock on ${e} (${p(e)}${a}).`),this.filePath=e,this.timeoutMs=r,this.holderPid=n,this.name="FileLockTimeoutError"}};function _(t){try{return process.kill(t,0),!0}catch(e){return e?.code!=="ESRCH"}}async function y(t){try{let e=await i.readFile(`/proc/${t}/stat`,"utf8");return e.slice(e.lastIndexOf(")")+2).split(" ")[19]??null}catch{return null}}async function u(t){try{let e=JSON.parse(await i.readFile(m.join(t,"owner.json"),"utf8"));return typeof e.pid!="number"||typeof e.token!="string"?null:{pid:e.pid,token:e.token,processStart:typeof e.processStart=="string"?e.processStart:null,acquiredAt:typeof e.acquiredAt=="number"?e.acquiredAt:null}}catch{return null}}async function v(t){if(!_(t.pid))return!0;let e=await y(t.pid);return t.processStart!==null&&e!==null&&t.processStart!==e}async function l(t){let e;try{e=Date.now()-(await i.stat(t)).mtimeMs}catch{return!1}let r=await u(t);return r?r.acquiredAt!==null&&Date.now()-r.acquiredAt>M?!0:v(r):e>A}async function I(t,e){if((await u(t))?.token!==e)return;let r=`${t}.released.${encodeURIComponent(e)}`;try{await i.rename(t,r),(await u(r))?.token===e&&await i.rm(r,{recursive:!0,force:!0})}catch{}}async function L(t){if(await l(t))try{let e=await i.stat(t);await i.writeFile(m.join(t,".reclaimed"),"");let r=await i.stat(t);if(r.dev!==e.dev||r.ino!==e.ino||await u(t)&&!await l(t))return;let n=`${r.dev}.${r.ino}.${String(r.ctimeMs).replace(".","-")}`,a=`${t}.reclaimed.${n}`;await i.rename(t,a),await i.rm(a,{recursive:!0,force:!0})}catch{}}async function F(t){let e=`${process.pid}:${Date.now()}:${Math.random()}`,r=`${t}.candidate.${encodeURIComponent(e)}`;try{await i.mkdir(r);let n={pid:process.pid,token:e,processStart:await y(process.pid),acquiredAt:Date.now()};return await i.writeFile(m.join(r,"owner.json"),JSON.stringify(n),{mode:384}),await i.rename(r,t),()=>I(t,e)}catch(n){if(await i.rm(r,{recursive:!0,force:!0}),n?.code==="EEXIST"||n?.code==="ENOTEMPTY")return null;throw n}}async function x(t,e){e.signal?.throwIfAborted(),await i.mkdir(m.dirname(t),{recursive:!0});let r=p(t),n=e.timeoutMs??O,a=Date.now()+n;for(;Date.now()<a;){e.signal?.throwIfAborted();let c=await F(r);if(c)return c;await l(r)?await L(r):await new Promise(T=>setTimeout(T,g))}throw new w(t,n,(await u(r))?.pid??null)}async function S(t,e,r={}){let n=await x(t,r);try{return await e()}finally{await n()}}import s from"node:fs/promises";import{writeFileSync as D,renameSync as $,mkdirSync as N}from"node:fs";import d from"node:path";import*as h from"node:os";var E=d.join(h.homedir(),".cortex");function R(){return!!process.env.NODE_TEST_CONTEXT}function f(t){if(!R())return;let e=d.resolve(t);if(e===E||e.startsWith(E+d.sep))throw new Error(`atomicWrite blocked: test process attempted to write under the real ~/.cortex (${e}). Isolate state first: run the test through vitest \u2014 \`npm test\` / \`npm run test:file <file>\` \u2014 whose setup file points CORTEX_HOME at an isolated temp home.`)}function o(t){if(t?.aborted)throw t.reason instanceof Error?t.reason:new Error("Atomic write aborted.")}async function b(t){try{return await s.readFile(t,"utf8")}catch(e){if(e.code==="ENOENT")return"";throw e}}async function k(t,e){try{await s.chmod(t,e)}catch(r){if(r.code!=="ENOENT")throw r}}async function J(t,e,r={}){f(t),await S(t,async()=>{o(r.signal);let n=await b(t);o(r.signal);let a=await e(n);o(r.signal),a!==n?await q(t,a,r):r.mode!==void 0&&await k(t,r.mode)},{signal:r.signal})}async function q(t,e,r={}){f(t),o(r.signal),await s.mkdir(d.dirname(t),{recursive:!0}),o(r.signal);let n=Math.random().toString(36).slice(2,8),a=`${t}.tmp.${process.pid}.${Date.now()}.${n}`,c=!1;try{await s.writeFile(a,e,{encoding:"utf8",mode:r.mode}),o(r.signal),r.mode!==void 0&&await s.chmod(a,r.mode),o(r.signal),$(a,t),c=!0}finally{c||await s.rm(a,{force:!0})}}function Y(t,e){f(t),N(d.dirname(t),{recursive:!0});let r=Math.random().toString(36).slice(2,8),n=`${t}.tmp.${process.pid}.${Date.now()}.${r}`;D(n,e,"utf8"),$(n,t)}export{S as a,J as b,q as c,Y as d};
@@ -1,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- var d="https://radius.pi.dev";function a(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let r=t;return typeof r.id=="string"&&typeof r.name=="string"&&typeof r.reasoning=="boolean"&&Array.isArray(r.input)&&typeof r.cost=="object"&&r.cost!==null&&!Array.isArray(r.cost)&&typeof r.contextWindow=="number"&&typeof r.maxTokens=="number"}function s(t){if(typeof t!="object"||t===null||Array.isArray(t))return;let{baseUrl:r,models:e}=t;if(!(typeof r!="string"||!Array.isArray(e)))return{baseUrl:r,models:e.filter(a).map(n=>({...n}))}}function p(t){return(/^https?:\/\//iu.test(t)?t:`https://${t}`).replace(/\/+$/u,"")}function u(t){return s(t?.gatewayConfig)}function f(t,r){return r.models.map(e=>({...e,api:"pi-messages",provider:t,baseUrl:r.baseUrl}))}function l(t,r){let e=u(r);return e?f(t,e):[]}function c(t){let r=t.trim();return r.length>512?`${r.slice(0,512)}\u2026`:r}async function y(t,r,e){let n={accept:"application/json"};r&&(n.authorization=`Bearer ${r}`);let o=await fetch(new URL("/v1/config",t),{headers:n,signal:e});if(!o.ok)throw new Error(`Could not load Radius config from ${t}: ${o.status}: ${c(await o.text())}`);let i=s(await o.json());if(!i)throw new Error(`Invalid Radius config from ${t}`);return i}export{d as a,p as b,f as c,l as d,y as e};