@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 +1,4 @@
1
1
  import { createRequire as __cortexCreateRequire } from 'node:module';
2
2
  const require = __cortexCreateRequire(import.meta.url);
3
3
  const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{e as a}from"./chunk-NAA7GF6Q.js";import*as p from"crypto";import{mkdirSync as m,readFileSync as y,renameSync as g,writeFileSync as S}from"fs";import*as d from"path";var f=a("ui-http"),x="ui-pairing.json",A=600*1e3,w=20,i="0123456789ABCDEFGHJKMNPQRSTVWXYZ",l=8,I={O:"0",I:"1",L:"1"};function E(r){let n=r.toUpperCase().replace(/[\s-]/g,"");if(n.length!==l)return null;let e=[...n].map(o=>I[o]??o).join("");return[...e].every(o=>i.includes(o))?e:null}function L(r){return`${r.slice(0,4)}-${r.slice(4)}`}function N(){return[...p.randomBytes(l)].map(n=>i[n%i.length]).join("")}function u(r,n){let e=null;try{e=JSON.parse(y(r,"utf8"))}catch{}let o={};for(let[t,s]of Object.entries(e?.codes??{}))typeof s=="number"&&s>n&&(o[t]=s);return{codes:o,failures:typeof e?.failures=="number"?e.failures:0}}function c(r,n){try{m(d.dirname(r),{recursive:!0});let e=`${r}.${process.pid}.tmp`;S(e,JSON.stringify(n),{mode:384}),g(e,r)}catch(e){f.warn(`could not persist pairing codes: ${e.message}`)}}function C(r){let n=r.now??(()=>Date.now()),{file:e}=r;return{create(){let o=n(),t=u(e,o),s=N();return t.codes[s]=o+A,t.failures=0,c(e,t),{code:L(s),expiresAt:t.codes[s]}},redeem(o){let t=u(e,n()),s=E(o);return s&&s in t.codes?(delete t.codes[s],c(e,t),!0):(t.failures+=1,t.failures>=w&&(f.warn("too many wrong pairing codes \u2014 voiding every outstanding code"),t.codes={},t.failures=0),c(e,t),!1)}}}export{x as a,A as b,E as c,C as d};
4
+ import{e as a}from"./chunk-7W7VYUTK.js";import*as p from"crypto";import{mkdirSync as m,readFileSync as y,renameSync as g,writeFileSync as S}from"fs";import*as d from"path";var f=a("ui-http"),x="ui-pairing.json",A=600*1e3,w=20,i="0123456789ABCDEFGHJKMNPQRSTVWXYZ",l=8,I={O:"0",I:"1",L:"1"};function E(r){let n=r.toUpperCase().replace(/[\s-]/g,"");if(n.length!==l)return null;let e=[...n].map(o=>I[o]??o).join("");return[...e].every(o=>i.includes(o))?e:null}function L(r){return`${r.slice(0,4)}-${r.slice(4)}`}function N(){return[...p.randomBytes(l)].map(n=>i[n%i.length]).join("")}function u(r,n){let e=null;try{e=JSON.parse(y(r,"utf8"))}catch{}let o={};for(let[t,s]of Object.entries(e?.codes??{}))typeof s=="number"&&s>n&&(o[t]=s);return{codes:o,failures:typeof e?.failures=="number"?e.failures:0}}function c(r,n){try{m(d.dirname(r),{recursive:!0});let e=`${r}.${process.pid}.tmp`;S(e,JSON.stringify(n),{mode:384}),g(e,r)}catch(e){f.warn(`could not persist pairing codes: ${e.message}`)}}function C(r){let n=r.now??(()=>Date.now()),{file:e}=r;return{create(){let o=n(),t=u(e,o),s=N();return t.codes[s]=o+A,t.failures=0,c(e,t),{code:L(s),expiresAt:t.codes[s]}},redeem(o){let t=u(e,n()),s=E(o);return s&&s in t.codes?(delete t.codes[s],c(e,t),!0):(t.failures+=1,t.failures>=w&&(f.warn("too many wrong pairing codes \u2014 voiding every outstanding code"),t.codes={},t.failures=0),c(e,t),!1)}}}export{x as a,A as b,E as c,C as d};
@@ -0,0 +1,6 @@
1
+ import { createRequire as __cortexCreateRequire } from 'node:module';
2
+ const require = __cortexCreateRequire(import.meta.url);
3
+ const __cortexPackageRoot = new URL("../../", import.meta.url);
4
+ import{i as C,y as J,z as H}from"./chunk-6G3OYMCV.js";import{M as O,S as W,c as U,d as b,e as V,f as B,l as S,q as z,r as R,s as G}from"./chunk-2BVUA256.js";import*as x from"node:fs";import{createRequire as we}from"node:module";import*as f from"node:path";import{fileURLToPath as $}from"node:url";import{EventEmitter as de}from"node:events";function K(){let e=new de;return{emit:(r,l)=>{e.emit(r,l)},on:(r,l)=>{let s=async a=>{try{await l(a)}catch(o){console.error(`Event handler error (${r}):`,o)}};return e.on(r,s),()=>e.off(r,s)},clear:()=>{e.removeAllListeners()}}}import{constants as A}from"node:buffer";import{spawn as ue}from"node:child_process";import{constants as fe}from"node:os";import{StringDecoder as X}from"node:string_decoder";var pe=Math.min(256*1024*1024,A.MAX_STRING_LENGTH),ge=5e3;async function q(e,r,l,s){let a=s?.maxBuffer??pe;if(!Number.isInteger(a)||a<0||a>A.MAX_STRING_LENGTH)throw new RangeError(`maxBuffer must be an integer between 0 and ${A.MAX_STRING_LENGTH} bytes`);let o=ue(e,r,{cwd:l,shell:!1,stdio:["ignore","pipe","pipe"]}),i="",d="",c=new X("utf8"),p=new X("utf8"),y=0,m=!1,t=!1,n,u,g=()=>{t||(t=!0,o.kill("SIGTERM"),u=setTimeout(()=>{o.exitCode===null&&o.signalCode===null&&o.kill("SIGKILL")},ge))};s?.signal&&(s.signal.aborted?g():s.signal.addEventListener("abort",g,{once:!0})),s?.timeout&&s.timeout>0&&(n=setTimeout(g,s.timeout));let h=w=>{if(m)return;let E=a-y;return w.length<=E?(y+=w.length,w):(m=!0,o.stdout?.destroy(),o.stderr?.destroy(),g(),E>0?w.subarray(0,E):void 0)};o.stdout?.on("data",w=>{let E=h(w);E&&(i+=c.write(E))}),o.stderr?.on("data",w=>{let E=h(w);E&&(d+=p.write(E))});let v;try{v=await U(o)}catch(w){if(!(w instanceof Error))throw w;v=1,d||(d=w.message)}finally{clearTimeout(n),clearTimeout(u),s?.signal?.removeEventListener("abort",g)}m||(i+=c.end(),d+=p.end());let M=v??(o.signalCode?128+(fe.signals[o.signalCode]??0):1);return{stdout:i,stderr:d,code:m&&M===0?1:M,killed:t,truncated:m}}import{readFileSync as he}from"node:fs";var me=["extensions","skills","prompts","themes"];function Y(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Q(e){try{let r=JSON.parse(z(he(e,"utf-8")));if(!Y(r)||!Y(r.pi))return null;let l={};for(let a of me){let o=r.pi[a];Array.isArray(o)&&o.every(i=>typeof i=="string")&&(l[a]=o)}let s=r.pi.changelogPath;return typeof s=="string"&&(l.changelogPath=s),l}catch{return null}}function Je(e){return JSON.stringify({source:e.source,scope:e.scope})}var Z="builtin:";function ee(e){if(e.startsWith(Z))return"builtin";if(e.startsWith("<")&&e.endsWith(">"))return e.slice(1,-1).split(":")[0]||"temporary"}function I(e){return e.startsWith(Z)||e.startsWith("<")}function He(e){return I(e)?e:V(b(e))}function Ke(e,r){return{path:e,source:r.source,scope:r.scope,origin:r.origin,baseDir:r.baseDir,...r.changelogPath?{changelogPath:r.changelogPath}:{}}}function te(e,r){return{path:e,source:r.source,scope:r.scope??"temporary",origin:r.origin??"top-level",baseDir:r.baseDir,...r.changelogPath?{changelogPath:r.changelogPath}:{}}}var L=process.env.PI_TIMING==="1",T=new Map;function ye(e="main"){L&&T.set(e,{timings:[],lastTime:Date.now()})}function _(e,r="main"){if(!L)return;let l=Date.now();T.has(r)||ye(r);let s=T.get(r);s.timings.push({label:e,ms:l-s.lastTime}),s.lastTime=l}function ve(e,r){let l=r.filter(s=>s.ms>=0);if(l.length!==0){console.error(`
5
+ --- ${e} ---`);for(let s of l)console.error(` ${s.label}: ${s.ms}ms`);console.error(` TOTAL: ${l.reduce((s,a)=>s+a.ms,0)}ms`),console.error(`${"-".repeat(e.length+8)}
6
+ `)}}function qe(){if(L)for(let[e,r]of T)ve(`Startup Timings: ${e}`,r.timings)}var N=we(new URL("vendor/pi/dist/core/extensions/loader.js",__cortexPackageRoot).href),xe="sea"in process.features&&process.features.sea===!0||process.getBuiltinModule("node:sea")?.isSea()===!0,Ee=!R&&f.extname($(new URL("vendor/pi/dist/core/extensions/loader.js",__cortexPackageRoot).href))===".ts",ie=R||xe||G,re;function Se(){return re??=(ie?import("./jiti-static-loader-W3QZ4GDS.js"):import("./jiti-loader-WANUXUDO.js")).then(e=>e.createJiti),re}var ne;function se(){return ne??=import("./virtual-modules-H4DXPJZB.js").then(e=>e.VIRTUAL_MODULES),ne}var k=null;function Me(){if(k)return k;let e=f.dirname($(new URL("vendor/pi/dist/core/extensions/loader.js",__cortexPackageRoot).href)),r=f.resolve(e,"../..","index.js"),l=N.resolve("typebox"),s=N.resolve("typebox/compile"),a=N.resolve("typebox/value"),o=f.resolve(e,"../../../../"),i=(u,g)=>{let h=f.join(o,u);return x.existsSync(h)?h:$(import.meta.resolve(g))},d=r,c=i("agent/dist/index.js","@earendil-works/pi-agent-core"),p=i("tui/dist/index.js","@earendil-works/pi-tui"),y=f.resolve(e,"pi-ai-extension-view.js"),m=i("ai/dist/models.js","@earendil-works/pi-ai/models"),t=i("ai/dist/oauth.js","@earendil-works/pi-ai/oauth"),n=i("ai/dist/providers/all.js","@earendil-works/pi-ai/providers/all");return k={"@earendil-works/pi-coding-agent":d,"@earendil-works/pi-agent-core":c,"@earendil-works/pi-tui":p,"@earendil-works/pi-ai/providers/all":n,"@earendil-works/pi-ai/compat":y,"@earendil-works/pi-ai/models":m,"@earendil-works/pi-ai/oauth":t,"@earendil-works/pi-ai":y,"@mariozechner/pi-coding-agent":d,"@mariozechner/pi-agent-core":c,"@mariozechner/pi-tui":p,"@mariozechner/pi-ai/providers/all":n,"@mariozechner/pi-ai/compat":y,"@mariozechner/pi-ai/models":m,"@mariozechner/pi-ai/oauth":t,"@mariozechner/pi-ai":y,typebox:l,"typebox/compile":s,"typebox/value":a,"@sinclair/typebox":l,"@sinclair/typebox/compile":s,"@sinclair/typebox/value":a},k}var P,F=0,D=new Map;function Pe(){D.clear(),P=void 0,F++}function be(e){let r=S(e);return P!==void 0&&!B(P,r)&&Pe(),P=r,{cwd:r,generation:F}}function Te(){let e=()=>{throw new Error("Extension runtime not initialized. Action methods cannot be called during extension loading.")},r={},l=new Set,s=()=>{if(r.staleMessage)throw new Error(r.staleMessage)},a={sendMessage:e,sendUserMessage:e,appendEntry:e,setSessionName:e,getSessionName:e,setLabel:e,getActiveTools:e,getAllTools:e,getSettings:e,setActiveTools:e,refreshTools:()=>{},getCommands:e,setModel:()=>Promise.reject(new Error("Extension runtime not initialized")),getThinkingLevel:e,setThinkingLevel:e,flagValues:new Map,pendingProviderRegistrations:[],pendingNativeProviderRegistrations:[],mcpServers:new H,pendingVirtualModelRegistrations:[],createContext:e,assertActive:s,invalidate:o=>{if(!r.staleMessage){r.staleMessage=o??"This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().";for(let i of l)i();l.clear()}},trackEventBusSubscription:o=>{let i=!0,d=()=>{i&&(i=!1,l.delete(d),o())};return l.add(d),d},reportError:()=>{},registerProvider:(o,i,d="<unknown>")=>{a.pendingProviderRegistrations.push({name:o,config:i,extensionPath:d})},registerNativeProvider:(o,i="<unknown>")=>{a.pendingNativeProviderRegistrations.push({provider:o,extensionPath:i})},unregisterProvider:o=>{a.pendingProviderRegistrations=a.pendingProviderRegistrations.filter(i=>i.name!==o),a.pendingNativeProviderRegistrations=a.pendingNativeProviderRegistrations.filter(i=>i.provider.id!==o)},registerVirtualModel:(o,i="<unknown>")=>{a.pendingVirtualModelRegistrations.push({definition:o,extensionPath:i})},unregisterVirtualModel:(o,i)=>{a.pendingVirtualModelRegistrations=a.pendingVirtualModelRegistrations.filter(({definition:d})=>d.provider!==o||d.id!==i)}};return a}var ke=["user","assistant","assistant-thinking"];function Re(e,r,l,s){let a=new Map,o=[],i=[],d="loading",c=()=>{if(d==="failed")throw new Error(`Extension "${e.path}" failed to load and its API is no longer active.`);r.assertActive()},p=t=>{d==="loading"?o.push(t):t()},y=()=>{a.clear(),o.length=0,i.length=0};return{api:{on(t,n){c();let u=(...h)=>n(...h),g=e.handlers.get(t)??[];return g.push(u),e.handlers.set(t,g),()=>{let h=e.handlers.get(t);if(!h)return;let v=h.indexOf(u);v!==-1&&(h.splice(v,1),h.length===0&&e.handlers.delete(t))}},registerTool(t){if(c(),typeof t.parameters!="object"||t.parameters===null||Array.isArray(t.parameters))throw new Error(`Tool "${t.name}" registered by extension "${e.path}" must define an object parameter schema.`);e.tools.set(t.name,{definition:t,sourceInfo:e.sourceInfo}),r.refreshTools()},registerCommand(t,n){if(c(),typeof t!="string"||t.length===0)throw new Error(`Command registered by extension "${e.path}" must have a non-empty string name. Use pi.registerCommand("name", { description, handler }).`);if(typeof n?.handler!="function")throw new Error(`Command "/${t}" registered by extension "${e.path}" must define handler().`);e.commands.set(t,{name:t,sourceInfo:e.sourceInfo,...n})},registerShortcut(t,n){c(),e.shortcuts.set(t,{shortcut:t,extensionPath:e.path,...n})},registerFlag(t,n){if(c(),n.default!==void 0&&typeof n.default!==n.type)throw new Error(`Invalid default for flag "${t}": expected ${n.type}, got ${typeof n.default}`);e.flags.set(t,{name:t,extensionPath:e.path,...n}),n.default!==void 0&&!r.flagValues.has(t)&&(d==="loading"?a.has(t)||a.set(t,n.default):r.flagValues.set(t,n.default))},registerMessageRenderer(t,n){c(),e.messageRenderers.set(t,n)},registerMarkdownTransformer(t,n){c(),e.markdownTransformer={transformer:t,messageTypes:new Set(n?.messageTypes??ke)}},registerEntryRenderer(t,n){c(),e.entryRenderers??=new Map,e.entryRenderers.set(t,n)},registerToolRenderer(t){c(),e.toolRenderers??=[],e.toolRenderers.push(t)},getFlag(t){if(c(),!!e.flags.has(t))return r.flagValues.has(t)?r.flagValues.get(t):a.get(t)},sendMessage(t,n){c(),r.sendMessage(t,n)},sendUserMessage(t,n){c(),r.sendUserMessage(t,n)},appendEntry(t,n){c(),r.appendEntry(t,n)},setSessionName(t){c(),r.setSessionName(t)},getSessionName(){return c(),r.getSessionName()},setLabel(t,n){c(),r.setLabel(t,n)},exec(t,n,u){return c(),q(t,n,u?.cwd??l,u)},getActiveTools(){return c(),r.getActiveTools()},getAllTools(){return c(),r.getAllTools()},getSettings(){return c(),r.getSettings()},setActiveTools(t){c(),r.setActiveTools(t)},getCommands(){return c(),r.getCommands()},setModel(t){return c(),r.setModel(t)},getThinkingLevel(){return c(),r.getThinkingLevel()},setThinkingLevel(t){c(),r.setThinkingLevel(t)},registerProvider(t,n){if(c(),typeof t=="string"){if(!n)throw new Error("Provider config is required when registering by name");p(()=>r.registerProvider(t,n,e.path));return}p(()=>r.registerNativeProvider(t,e.path))},unregisterProvider(t){c(),p(()=>r.unregisterProvider(t,e.path))},registerMcpServer(t,n){c();let u=J(t,n);if(typeof u=="string")throw new Error(`Invalid MCP server registered by extension "${e.path}": ${u}`);let g=r.mcpServers.get(t)?.extensionPath;if(g!==void 0&&g!==e.path)throw new Error(`MCP server "${t}" is already registered by extension "${g}"`);let h=r.mcpServers.list().find(M=>M.name!==t&&C(M.name)===C(t));if(h)throw new Error(`MCP server "${t}" conflicts with registered server "${h.name}"`);let v={name:t,config:structuredClone(u),extensionPath:e.path};p(()=>r.mcpServers.register(v))},unregisterMcpServer(t){c(),p(()=>r.mcpServers.unregister(t,e.path))},getMcpServers(){return c(),r.mcpServers.list()},registerVirtualModel(t){c();let n={...t,route:u=>t.route(u,r.createContext())};p(()=>r.registerVirtualModel(n,e.path))},unregisterVirtualModel(t,n){c(),p(()=>r.unregisterVirtualModel(t,n))},events:{emit(t,n){c(),s.emit(t,n)},on(t,n){c();let u=async h=>{try{await n(h)}catch(v){r.reportError({extensionPath:e.path,event:`events:${t}`,error:v instanceof Error?v.message:String(v),stack:v instanceof Error?v.stack:void 0})}},g=r.trackEventBusSubscription(s.on(t,u));return d==="loading"&&i.push(g),g}}},commit:()=>{if(d==="loading"){r.assertActive();for(let[t,n]of a)r.flagValues.has(t)||r.flagValues.set(t,n);for(let t of o)t();d="active",y()}},discard:()=>{if(d==="loading"){d="failed";for(let t of i)t();y()}}}}function oe(e){return e!==void 0&&P===e.cwd&&F===e.generation}async function Ce(e,r){if(oe(r)){let d=D.get(e);if(d)return d}let l=await Se(),s=ie?{virtualModules:await se(),tryNative:!1}:Ee?{virtualModules:await se(),tsconfigPaths:!0}:{alias:Me()},i=await l(new URL("vendor/pi/dist/core/extensions/loader.js",__cortexPackageRoot).href,{moduleCache:!1,...s}).import(b(e),{default:!0});if(typeof i=="function")return oe(r)&&D.set(e,i),i}function Ae(e,r){let l=ee(e)??"local",s=I(e)?void 0:f.dirname(r);return{path:e,resolvedPath:r,sourceInfo:te(e,{source:l,baseDir:s}),handlers:new Map,tools:new Map,messageRenderers:new Map,entryRenderers:new Map,commands:new Map,flags:new Map,shortcuts:new Map}}async function ae(e,r,l,s,a,o){let i=Ae(r,l),d=Re(i,o,s,a);try{await e(d.api),d.commit()}catch(c){throw d.discard(),c}return _(`${r} factory`,"extensions"),i}async function Ie(e,r,l,s,a){let o=S(e,r,{normalizeUnicodeSpaces:!0});try{let i=await Ce(o,a);return _(`${e} module import`,"extensions"),i?{extension:await ae(i,e,o,r,l,s),error:null}:{extension:null,error:`Extension does not export a valid factory function: ${e}`}}catch(i){return{extension:null,error:`Failed to load extension: ${i instanceof Error?i.message:String(i)}`}}}async function lt(e,r,l,s,a="<inline>"){let o=S(r);return ae(e,a,a,o,l,s)}async function ce(e,r,l,s,a=!1){let o=[],i=[],d=[],c=a?be(r):void 0,p=c?.cwd??S(r),y=l??K(),m=s??Te();for(let t of e){let{extension:n,error:u}=await Ie(t,p,y,m,c);if(u){i.push({path:t,error:u});continue}n&&o.push(n)}return{extensions:o,errors:i,warnings:d,runtime:m}}async function Le(e,r,l,s){return ce(e,r,l,s)}async function dt(e,r,l,s){return ce(e,r,l,s,!0)}function _e(e){return e.endsWith(".ts")||e.endsWith(".js")}function le(e){let r=f.join(e,"package.json");if(x.existsSync(r)){let a=Q(r);if(a?.extensions?.length){let o=[];for(let i of a.extensions){let d=f.resolve(e,i);x.existsSync(d)&&o.push(d)}if(o.length>0)return o}}let l=f.join(e,"index.ts"),s=f.join(e,"index.js");return x.existsSync(l)?[l]:x.existsSync(s)?[s]:null}function j(e){if(!x.existsSync(e))return[];let r=[];try{let l=x.readdirSync(e,{withFileTypes:!0});for(let s of l){let a=f.join(e,s.name);if((s.isFile()||s.isSymbolicLink())&&_e(s.name)){r.push(a);continue}if(s.isDirectory()||s.isSymbolicLink()){let o=le(a);o&&r.push(...o)}}}catch{return[]}return r}async function ut(e,r,l=W(),s){let a=S(r),o=S(l),i=[],d=new Set,c=m=>{for(let t of m){let n=f.resolve(t);d.has(n)||(d.add(n),i.push(t))}},p=f.join(a,O,"extensions");c(j(p));let y=f.join(o,"extensions");c(j(y));for(let m of e){let t=S(m,a,{normalizeUnicodeSpaces:!0});if(x.existsSync(t)&&x.statSync(t).isDirectory()){let n=le(t);if(n){c(n);continue}c(j(t));continue}c([t])}return Le(i,a,s)}export{K as a,Q as b,Je as c,Z as d,ee as e,I as f,He as g,Ke as h,te as i,ye as j,_ as k,qe as l,Pe as m,Te as n,lt as o,Le as p,dt as q,ut as r};
@@ -0,0 +1,4 @@
1
+ import { createRequire as __cortexCreateRequire } from 'node:module';
2
+ const require = __cortexCreateRequire(import.meta.url);
3
+ const __cortexPackageRoot = new URL("../../", import.meta.url);
4
+ import{$ as z,J as L,K as M,N as C,O as V,Q as w,R as P,T as m,Y as $,Z as d,aa as O,b as _,ba as A,ca as U,d as E,da as x,ea as B,fa as H,i as S,j as v,k,n as f,p as R,q,s as I,u as T}from"./chunk-TMV2ZDOI.js";var b=class{constructor(e){this._server=e}requestStream(e,t,i){return this._server.requestStream(e,t,i)}createMessageStream(e,t){let i=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!i?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let s=e.messages[e.messages.length-1],r=Array.isArray(s.content)?s.content:[s.content],a=r.some(o=>o.type==="tool_result"),n=e.messages.length>1?e.messages[e.messages.length-2]:void 0,p=n?Array.isArray(n.content)?n.content:[n.content]:[],c=p.some(o=>o.type==="tool_use");if(a){if(r.some(o=>o.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let o=new Set(p.filter(h=>h.type==="tool_use").map(h=>h.id)),l=new Set(r.filter(h=>h.type==="tool_result").map(h=>h.toolUseId));if(o.size!==l.size||![...o].every(h=>l.has(h)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},w,t)}elicitInputStream(e,t){let i=this._server.getClientCapabilities(),s=e.mode??"form";switch(s){case"url":{if(!i?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!i?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let r=s==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:r},m,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,i){return this._server.getTaskResult({taskId:e},t,i)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}};var j=class extends z{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(C.options.map((i,s)=>[i,s])),this.isMessageIgnored=(i,s)=>{let r=this._loggingLevels.get(s);return r?this.LOG_LEVEL_SEVERITY.get(i)<this.LOG_LEVEL_SEVERITY.get(r):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new A,this.setRequestHandler(q,i=>this._oninitialize(i)),this.setNotificationHandler(I,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(V,async(i,s)=>{let r=s.sessionId||s.requestInfo?.headers["mcp-session-id"]||void 0,{level:a}=i.params,n=C.safeParse(a);return n.success&&this._loggingLevels.set(r,n.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new b(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=O(this._capabilities,e)}setRequestHandler(e,t){let s=E(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let r=S(s);if(typeof r!="string")throw new Error("Schema method literal must be a string");if(r==="tools/call"){let n=async(p,c)=>{let o=_(M,p);if(!o.success){let u=o.error instanceof Error?o.error.message:String(o.error);throw new d(f.InvalidParams,`Invalid tools/call request: ${u}`)}let{params:l}=o.data,h=await Promise.resolve(t(p,c));if(l.task){let u=_(T,h);if(!u.success){let G=u.error instanceof Error?u.error.message:String(u.error);throw new d(f.InvalidParams,`Invalid task creation result: ${G}`)}return u.data}let g=_(L,h);if(!g.success){let u=g.error instanceof Error?g.error.message:String(g.error);throw new d(f.InvalidParams,`Invalid tools/call result: ${u}`)}return g.data};return super.setRequestHandler(e,n)}return super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){x(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&U(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:k.includes(t)?t:v,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},R)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let i=e.messages[e.messages.length-1],s=Array.isArray(i.content)?i.content:[i.content],r=s.some(c=>c.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,n=a?Array.isArray(a.content)?a.content:[a.content]:[],p=n.some(c=>c.type==="tool_use");if(r){if(s.some(c=>c.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!p)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(p){let c=new Set(n.filter(l=>l.type==="tool_use").map(l=>l.id)),o=new Set(s.filter(l=>l.type==="tool_result").map(l=>l.toolUseId));if(c.size!==o.size||![...c].every(l=>o.has(l)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},P,t):this.request({method:"sampling/createMessage",params:e},w,t)}async elicitInput(e,t){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let s=e;return this.request({method:"elicitation/create",params:s},m,t)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let s=e.mode==="form"?e:{...e,mode:"form"},r=await this.request({method:"elicitation/create",params:s},m,t);if(r.action==="accept"&&r.content&&s.requestedSchema)try{let n=this._jsonSchemaValidator.getValidator(s.requestedSchema)(r.content);if(!n.valid)throw new d(f.InvalidParams,`Elicitation response content does not match requested schema: ${n.errorMessage}`)}catch(a){throw a instanceof d?a:new d(f.InternalError,`Error validating elicitation response: ${a instanceof Error?a.message:String(a)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},$,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};import N from"node:process";var D=class{constructor(e=N.stdin,t=N.stdout,i){this._stdin=e,this._stdout=t,this._started=!1,this._ondata=s=>{try{this._readBuffer.append(s),this.processReadBuffer()}catch(r){this.onerror?.(r),this.close().catch(()=>{})}},this._onerror=s=>{this.onerror?.(s)},this._readBuffer=new B({maxBufferSize:i?.maxBufferSize})}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(t=>{let i=H(e);this._stdout.write(i)?t():this._stdout.once("drain",t)})}};export{j as a,D as b};
@@ -0,0 +1,11 @@
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,n=`
5
+ `){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join(n)}function i(e){let n=[r(e.content)];for(let t of Object.values(e.sections??{}))t!==null&&n.push(t);return n.filter(t=>t.length>0).join(`
6
+
7
+ `)}function c(e){let n=[],t=r(e.content);t.length>0&&n.push(t);for(let[o,s]of Object.entries(e.sections??{}))n.push(s===null?`Removed system prompt section "${o}".`:`Updated system prompt section "${o}":
8
+
9
+ ${s}`);return n.join(`
10
+
11
+ `)}function p(e,n,t=e.length){return`${e.slice(n,t)} `.slice(0,-1)}export{r as a,i as b,c,p as d};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __cortexCreateRequire } from 'node:module';
2
2
  const require = __cortexCreateRequire(import.meta.url);
3
3
  const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{a as t,c as f}from"./chunk-E7ZMYIY6.js";import{l as s}from"./chunk-J5DVLUKY.js";import*as r from"fs";import*as o from"path";var c=o.join(s,"preferences.json");function i(){try{let e=JSON.parse(r.readFileSync(c,"utf8"));return e&&typeof e=="object"?e:{}}catch{return{}}}function d(){return t(i().lang)}function p(e){let a=t(e),l={...i(),lang:a};r.mkdirSync(o.dirname(c),{recursive:!0}),r.writeFileSync(c,JSON.stringify(l,null,2)+`
4
+ import{a as t,c as f}from"./chunk-7GGPYU5E.js";import{j as s}from"./chunk-T54CZKNJ.js";import*as r from"fs";import*as o from"path";var c=o.join(s,"preferences.json");function i(){try{let e=JSON.parse(r.readFileSync(c,"utf8"));return e&&typeof e=="object"?e:{}}catch{return{}}}function d(){return t(i().lang)}function p(e){let a=t(e),l={...i(),lang:a};r.mkdirSync(o.dirname(c),{recursive:!0}),r.writeFileSync(c,JSON.stringify(l,null,2)+`
5
5
  `)}function g(e=process.env){return e.CORTEX_LANG?"env":i().lang?"file":"default"}function x(e,a){let n=t(e);return p(n),f(n),a?.(n),n}export{d as a,g as b,x as c};
@@ -1,4 +1,4 @@
1
1
  import { createRequire as __cortexCreateRequire } from 'node:module';
2
2
  const require = __cortexCreateRequire(import.meta.url);
3
3
  const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{e as s,m,n as p,o as l,t as x}from"./chunk-3YHOCPQU.js";var d={adapter:null,bus:null,notify:null,deliverScheduledTurn:null};function A(t){let e=d[t];if(!e)throw new Error(`job ctx: ${t} not injected`);return e}var u=[],L=1;function h(t){u.unshift({id:`sn-${L++}`,ts:new Date().toISOString(),level:t.level??"info",text:t.text,...t.title!==void 0?{title:t.title}:{}}),u.length>50&&(u.length=50)}function j(t){return t===void 0?u.slice():u.slice(0,t)}function M(t){h({level:t.level??"info",text:t.text,...t.title!==void 0?{title:t.title}:{}}),d.bus?.publish({type:"system.notice",level:t.level??"info",text:t.text,...t.title!==void 0?{title:t.title}:{}})}async function F(t,e){M(e);try{let r={type:"system-notice"},i={text:e.text,...e.richBlocks?{richBlocks:e.richBlocks}:{}};return(e.actions?.length?await t.postInteractive(r,{...i,actions:e.actions}):await t.postMessage(r,i)).conduit.length>0}catch{return!1}}import{mkdirSync as O,readdirSync as P,readFileSync as I,rmSync as _,writeFileSync as D}from"node:fs";function X(t,e,r,i){return{backend:t,provider:e,model:r,billing:i,outcomes:{completed:0,failed:0,cancelled:0,rateLimited:0},failures:{},retries:0,fallbacks:0,ttftMs:s("ttftMs"),durationS:s("turnDurationS"),contextPctAtEnd:s("contextPct"),compactions:{auto:0,manual:0},tokens:{input:0,output:0,cacheRead:0,cacheWrite:0}}}var S=()=>({completed:0,failed:0,cancelled:0});function a(t){return{day:t,turns:{},features:{},messagesByChannel:{},uiOps:{},tools:{},agent:{userInterrupts:0,superseded:0,sessionTurns:{},workers:S(),subagents:S()},perf:{startups:[],eventLoopP99s:[],web:{loads:0,ttfbMs:s("webLoadMs"),firstRenderMs:s("webLoadMs"),interactiveMs:s("webLoadMs")},sseReconnects:0,remoteClientDisconnects:0},errors:{byModule:{},samples:[]}}}var T=1440,C=7,o=null,c=m,R=Date.now;function y(t){return new Date(t).toISOString().slice(0,10)}function v(t){try{return JSON.parse(I(t,"utf8"))}catch{return null}}function w(t){try{O(c,{recursive:!0}),D(l(t.day,c),JSON.stringify(t),"utf8")}catch{}}function E(){let t=y(R());if(o?.day===t)return o;o&&w(o);let e=v(l(t,c));return o=e?.day===t?{...a(t),...e}:a(t),o}function z(t){if(x())try{t(E())}catch{}}function Q(t,e){t.perf.eventLoopP99s.push(e),t.perf.eventLoopP99s.length>T&&t.perf.eventLoopP99s.shift()}function N(){o&&w(o)}function g(){try{return P(c).filter(t=>t.startsWith(p)&&t.endsWith(".json")).map(t=>t.slice(p.length,-5))}catch{return[]}}function V(t=R()){let e=y(t);o&&o.day!==e&&N(),o?.day!==e&&(o=null);let r=y(t-C*24*60*60*1e3),i=g().filter(n=>n<e).sort();for(let n of i.filter(f=>f<r))b(n);return i.filter(n=>n>=r).flatMap(n=>{let f=v(l(n,c));return f?.day===n?[{...a(n),...f}]:[]})}function b(t){_(l(t,c),{force:!0})}function Z(){o=null;for(let t of g())b(t)}export{d as a,A as b,j as c,M as d,F as e,X as f,y as g,z as h,Q as i,N as j,V as k,b as l,Z as m};
4
+ import{e as s,n as m,p,q as l,v as x}from"./chunk-KST6OY76.js";var d={adapter:null,bus:null,notify:null,deliverScheduledTurn:null};function A(t){let e=d[t];if(!e)throw new Error(`job ctx: ${t} not injected`);return e}var u=[],L=1;function h(t){u.unshift({id:`sn-${L++}`,ts:new Date().toISOString(),level:t.level??"info",text:t.text,...t.title!==void 0?{title:t.title}:{}}),u.length>50&&(u.length=50)}function j(t){return t===void 0?u.slice():u.slice(0,t)}function M(t){h({level:t.level??"info",text:t.text,...t.title!==void 0?{title:t.title}:{}}),d.bus?.publish({type:"system.notice",level:t.level??"info",text:t.text,...t.title!==void 0?{title:t.title}:{}})}async function F(t,e){M(e);try{let r={type:"system-notice"},i={text:e.text,...e.richBlocks?{richBlocks:e.richBlocks}:{}};return(e.actions?.length?await t.postInteractive(r,{...i,actions:e.actions}):await t.postMessage(r,i)).conduit.length>0}catch{return!1}}import{mkdirSync as O,readdirSync as P,readFileSync as I,rmSync as _,writeFileSync as D}from"node:fs";function X(t,e,r,i){return{backend:t,provider:e,model:r,billing:i,outcomes:{completed:0,failed:0,cancelled:0,rateLimited:0},failures:{},retries:0,fallbacks:0,ttftMs:s("ttftMs"),durationS:s("turnDurationS"),contextPctAtEnd:s("contextPct"),compactions:{auto:0,manual:0},tokens:{input:0,output:0,cacheRead:0,cacheWrite:0}}}var S=()=>({completed:0,failed:0,cancelled:0});function a(t){return{day:t,turns:{},features:{},messagesByChannel:{},uiOps:{},tools:{},agent:{userInterrupts:0,superseded:0,sessionTurns:{},workers:S(),subagents:S()},perf:{startups:[],eventLoopP99s:[],web:{loads:0,ttfbMs:s("webLoadMs"),firstRenderMs:s("webLoadMs"),interactiveMs:s("webLoadMs")},sseReconnects:0,remoteClientDisconnects:0},errors:{byModule:{},samples:[]}}}var T=1440,C=7,o=null,c=m,R=Date.now;function y(t){return new Date(t).toISOString().slice(0,10)}function v(t){try{return JSON.parse(I(t,"utf8"))}catch{return null}}function w(t){try{O(c,{recursive:!0}),D(l(t.day,c),JSON.stringify(t),"utf8")}catch{}}function E(){let t=y(R());if(o?.day===t)return o;o&&w(o);let e=v(l(t,c));return o=e?.day===t?{...a(t),...e}:a(t),o}function z(t){if(x())try{t(E())}catch{}}function Q(t,e){t.perf.eventLoopP99s.push(e),t.perf.eventLoopP99s.length>T&&t.perf.eventLoopP99s.shift()}function N(){o&&w(o)}function g(){try{return P(c).filter(t=>t.startsWith(p)&&t.endsWith(".json")).map(t=>t.slice(p.length,-5))}catch{return[]}}function V(t=R()){let e=y(t);o&&o.day!==e&&N(),o?.day!==e&&(o=null);let r=y(t-C*24*60*60*1e3),i=g().filter(n=>n<e).sort();for(let n of i.filter(f=>f<r))b(n);return i.filter(n=>n>=r).flatMap(n=>{let f=v(l(n,c));return f?.day===n?[{...a(n),...f}]:[]})}function b(t){_(l(t,c),{force:!0})}function Z(){o=null;for(let t of g())b(t)}export{d as a,A as b,j as c,M as d,F as e,X as f,y as g,z as h,Q as i,N as j,V as k,b as l,Z as m};
@@ -0,0 +1,6 @@
1
+ import { createRequire as __cortexCreateRequire } from 'node:module';
2
+ const require = __cortexCreateRequire(import.meta.url);
3
+ const __cortexPackageRoot = new URL("../../", import.meta.url);
4
+ import{M as ye,P as me,Q as we,l as R,n as H,o as T,p}from"./chunk-C6YVF7EI.js";import{a as pe}from"./chunk-ITGCWQFK.js";import{a as _}from"./chunk-LCKVYFMD.js";import{e as fe}from"./chunk-SM45TH22.js";import{p as he,q as D}from"./chunk-LIIZI3HY.js";import{a as m}from"./chunk-Q4UGYGU5.js";import{e as ue}from"./chunk-7W7VYUTK.js";import{j as de,k as w}from"./chunk-T54CZKNJ.js";import{readFileSync as ge}from"node:fs";import*as be from"node:path";var Y=ue("models-repo"),W=0,ke=be.join(de,"models.json"),_t=new m;function Ht(){return W}function Se(t){let e=JSON.parse(t);return e?.default?{...e,default:D(e.default)}:e}var J=class{filePath;cache=null;constructor(e=ke){this.filePath=e}readSync(){return this.cache||(this.cache=Se(ge(this.filePath,"utf8"))),this.cache}readIfPresent(){try{return this.readSync()}catch(e){if(e.code==="ENOENT")return null;throw e}}invalidate(){this.cache=null,W+=1}reload(){this.cache=Se(ge(this.filePath,"utf8"))}},P=new J,K=null;function Yt(t){K=t}function tn(t,e){try{t.reload(),W+=1,e?.(),Y.info("Hot-reload: models.json reloaded"),K?.(`${_.refresh} \`models.json\` hot-reloaded`)}catch(n){Y.error(`Hot-reload models.json failed: ${n.message} \u2014 keeping previous config`),K?.(`${_.warning} \`models.json\` hot-reload FAILED \u2014 keeping previous config`)}}function Jt(t=P,e=ke,n){let i=null,s=fe({label:"models.json",filePath:e,onChange:()=>{i&&clearTimeout(i),i=setTimeout(()=>{i=null,tn(t,n)},300)},warn:o=>Y.error(o)});return()=>{s.close(),i&&clearTimeout(i),i=null}}import*as ze from"node:path";import{isDeepStrictEqual as ut}from"node:util";import ve from"node:fs";import u from"node:fs/promises";import Q from"node:path";import on from"node:readline";function V(t){return typeof t=="string"&&t.length>0}function rn(t){if(!t||typeof t!="object")return;let e=t;if(V(e.after))return{after:e.after};if(V(e.before))return{before:e.before}}function G(t){let e=rn(t),n=t?.file;return e&&V(n)?{file:n,...e}:void 0}var sn=1,an=256,cn=16*1024*1024,ln=1024*1024,dn=Q.join(w,"channel-registry.json"),un=/^\[[^\]]+:[^\]]+\]$/;function A(){return{live:new Map,pending:new Map,bindings:new Map,turns:new Map,conversations:new Map,eventCount:0,fileSize:0,compactedFileSize:0}}function Ae(t){return t.replace(/\.jsonl$/,".json")}function fn(t){return`${Ae(t)}.bak`}function Ee(t,e){return t==="scheduled"?"scheduled":e&&un.test(e)?"thread":"direct"}function xe(t,e){let n={fileSize:t.fileSize,eventCount:t.eventCount,liveCount:t.live.size};if(e.shouldCompact)return e.shouldCompact(n);let i=Math.max(512,t.live.size*4,hn(t)*2),r=Math.max(cn,t.compactedFileSize*2);return t.fileSize>r||t.eventCount>i}function hn(t){let e=0;for(let n of t.turns.values())e+=n.length;return t.live.size+t.pending.size+t.bindings.size+t.conversations.size+e}async function Ce(t,e={}){return await mn(t),await at(t),Cn(t,e)}async function f(t,e,n,i={}){await Z(t,e,[n],i)}async function Z(t,e,n,i={}){if(n.length===0)return;let r=new Set;for(let l of n){if("id"in l){if(r.has(l.id))throw new Error(`Session appears twice in one append batch: ${l.id}`);r.add(l.id)}Wn(e,l)}let s=n.map(l=>`${JSON.stringify(l)}
5
+ `).join(""),o=await it(t,s,i.writeAppend);for(let l of n)Ne(e,l);e.eventCount+=n.length,e.fileSize=o}async function q(t,e,n={}){let i=Be(e);await Le(t,i),e.eventCount=i.length,e.fileSize=(await u.stat(t)).size,e.compactedFileSize=e.fileSize,n.onCompact?.()}function Be(t){let e=[];for(let n of t.live.values())e.push(pn(n));for(let n of t.pending.values())e.push(yn(n.session,n.cleanup));for(let[n,i]of t.bindings)e.push({v:1,op:"bind",channel:n,sessionId:i});for(let[n,i]of t.conversations)e.push({v:1,op:"conversation",channel:n,kind:"set",fields:i});for(let[n,i]of t.turns)for(let r of i)e.push({v:1,op:"turn",channel:n,kind:"begin",turn:r});return e}function pn(t){return{v:1,op:"put",id:t.sessionId,record:t}}function yn(t,e){return{v:1,op:"delete-intent",id:t.sessionId,record:t,cleanup:e}}async function mn(t){await u.mkdir(Q.dirname(t),{recursive:!0});let e=await O(t),n=Ae(t),i=await O(n);if(e&&i&&e.size===0&&i.size>0)throw new Error(`Empty JSONL hides non-empty legacy registry: ${t}`);if(!e){if(i)return wn(t,n);await u.writeFile(t,"",{flag:"a"})}}async function wn(t,e){let n=JSON.parse(await u.readFile(e,"utf8")),i=A();for(let r of await bn(n))Ue(i,r);await gn(e,fn(t)),await Le(t,Be(i))}async function gn(t,e){let n=await Sn(e);await u.copyFile(t,n,ve.constants.COPYFILE_EXCL)}async function Sn(t){if(await O(t)===null)return t;let e=new Date().toISOString().replace(/[:.]/g,"-");for(let n=0;n<1e3;n+=1){let i=`${t}.${e}.${n+1}`;if(await O(i)===null)return i}throw new Error(`Could not allocate session registry backup path: ${t}`)}async function bn(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("legacy session registry must be a plain object");let e=Object.entries(t);return e.length===0?[]:kn(e)==="new"?In(e):await vn(e)}function kn(t){let e=!1,n=!1;for(let[,i]of t){if(!i||typeof i!="object"||Array.isArray(i))throw new Error("legacy session registry entries must be objects");let r=i,s=Object.hasOwn(r,"name"),o=Object.hasOwn(r,"sessionId");if(s)e=!0;else if(o)n=!0;else throw new Error("legacy session registry entry format is unrecognizable");if(e&&n)throw new Error("legacy session registry mixes old and new formats")}return e?"new":"old"}function In(t){return t.map(([e,n])=>{let i=n,r=ee(i.kind),s=E(i.label);return X(i.origin===void 0?{...i,origin:Ee(r,s)}:i,e)})}async function vn(t){let e=await An(),n=new Map;for(let[,i]of t)En(n,e,i);return Array.from(n.values())}async function An(){try{let t=JSON.parse(await u.readFile(dn,"utf8"));return Object.fromEntries(Object.entries(t).map(([e,n])=>[n,e]))}catch{return{}}}function En(t,e,n){if(!n||typeof n!="object"||Array.isArray(n))throw new Error("legacy session registry entries must be objects");let i=n,r=a(i.sessionId),s=xn(e,i),o=t.get(r);(!o||o.lastUsedAt<=s.lastUsedAt)&&t.set(r,s)}function xn(t,e){let n=e.kind==="scheduled"?"scheduled":"local",i=E(e.label);return{sessionId:String(e.sessionId),projectId:t[a(e.channel)]||"general",channel:a(e.channel),backend:a(e.backend),kind:n,origin:Ee(n,i),createdAt:a(e.createdAt),lastUsedAt:a(e.lastUsedAt),label:i,selection:j(e.selection),...e.profileName!==void 0?{profileName:e.profileName}:{},agentName:c(e.agentName),backendSessionId:c(e.backendSessionId),lastReadAt:c(e.lastReadAt),scheduleId:c(e.scheduleId),contextUsage:e.contextUsage}}async function Cn(t,e){let n=A(),i=ve.createReadStream(t,{encoding:"utf8"}),r=on.createInterface({input:i,crlfDelay:1/0}),s=0;for await(let o of r)s+=1,Ne(n,Bn(o,s)),s%(e.yieldEvery??an)===0&&await dt();return n.eventCount=s,n.fileSize=(await u.stat(t)).size,n}function Bn(t,e){if(!t)throw new Error(`Malformed session registry line ${e}: empty line`);let n;try{n=JSON.parse(t)}catch{throw new Error(`Malformed session registry line ${e}`)}return Dn(n,e)}function Dn(t,e){let n=t,i=n?.v,r=n?.op;if(i!==sn)throw new Error(`Unknown session registry version at line ${e}`);if(r==="put"){let s=F(n,e);return{v:1,op:r,id:s,record:X(n.record,s)}}if(r==="delete-intent"){let s=F(n,e);return{v:1,op:r,id:s,record:X(n.record,s),cleanup:On(n.cleanup)}}if(r==="delete-commit")return{v:1,op:r,id:F(n,e)};if(r==="patch")return Rn(n,e);if(r==="bind")return Pn(n,e);if(r==="unbind")return{v:1,op:"unbind",channel:v(n,"channel",e)};if(r==="conversation")return Mn(n,e);if(r==="turn")return Fn(n,e);throw new Error(`Unknown session registry op at line ${e}`)}function F(t,e){let n=t?.id;if(typeof n!="string"||!n)throw new Error(`Malformed session registry id at line ${e}`);return n}function v(t,e,n){let i=t?.[e];if(typeof i!="string"||!i)throw new Error(`Malformed session registry ${e} at line ${n}`);return i}function Rn(t,e){let n=F(t,e),i=$n(t.fields);return Array.isArray(t.unset)&&t.unset.includes("profileName")&&Object.assign(i,{profileName:void 0}),{v:1,op:"patch",id:n,fields:i,...Tn(t.unset,e)}}function Tn(t,e){if(t===void 0)return{};if(!Array.isArray(t))throw new Error(`Invalid session registry patch unset at line ${e}`);let n=t.map(r=>typeof r=="string"?Me(r):r);if(n.some(r=>r!==null&&!Ln.has(r)))throw new Error(`Invalid session registry patch unset at line ${e}`);let i=n.filter(r=>r!==null);return i.length?{unset:i}:{}}function Pn(t,e){return{v:1,op:"bind",channel:v(t,"channel",e),sessionId:v(t,"sessionId",e)}}function Fn(t,e){let n=v(t,"channel",e),i=t?.kind;if(i==="begin")return{v:1,op:"turn",channel:n,kind:i,turn:zn(t.turn)};if(i==="patch")return{v:1,op:"turn",channel:n,kind:i,turnIndex:M(t.turnIndex),fields:Yn(t.fields)};if(i==="truncate")return{v:1,op:"turn",channel:n,kind:i,fromIndex:M(t.fromIndex)};if(i==="clear")return{v:1,op:"turn",channel:n,kind:i};throw new Error(`Unknown session registry turn kind at line ${e}`)}function Mn(t,e){let n=v(t,"channel",e),i=t?.kind;if(i==="set")return{v:1,op:"conversation",channel:n,kind:i,fields:Kn(t.fields)};if(i==="clear")return{v:1,op:"conversation",channel:n,kind:i};throw new Error(`Unknown session registry conversation kind at line ${e}`)}function On(t){if(t===void 0)return{claudeBackupPaths:[]};if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Invalid session registry delete cleanup");let e=t.claudeBackupPaths;if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error("Invalid session registry Claude backup paths");return{claudeBackupPaths:[...new Set(e)]}}function X(t,e){let n=t,i={sessionId:a(n?.sessionId),projectId:a(n?.projectId),channel:a(n?.channel),backend:a(n?.backend),kind:ee(n?.kind),origin:Re(n?.origin),createdAt:a(n?.createdAt),lastUsedAt:a(n?.lastUsedAt),label:E(n?.label),starred:g(n?.starred),labelRenamed:g(n?.labelRenamed),selection:j(n?.selection),...n?.profileName!==void 0?{profileName:n.profileName}:{},agentName:c(n?.agentName),backendSessionId:c(n?.backendSessionId),lastReadAt:c(n?.lastReadAt),scheduleId:c(n?.scheduleId),boardId:c(n?.boardId??n?.commissionId),boardBlockFor:c(n?.boardBlockFor??n?.commissionBlockFor),contextUsage:n?.contextUsage,teamLeadId:c(n?.teamLeadId),workerName:c(n?.workerName),workerBrief:c(n?.workerBrief),workerBlockFor:c(n?.workerBlockFor),clean:g(n?.clean),workspaceDir:c(n?.workspaceDir),allowedPaths:De(n?.allowedPaths),allowedPathsBlockFor:c(n?.allowedPathsBlockFor)};return i.selection&&delete i.profileName,jn(i,e)}function jn(t,e){if(t.sessionId!==e)throw new Error(`Session registry record id mismatch for ${e}`);return t}function a(t){if(typeof t!="string")throw new Error("Invalid session registry string field");return t}function E(t){if(t==null||t==="")return null;if(typeof t!="string")throw new Error("Invalid session registry nullable string");return t}function j(t){if(t==null)return null;let e=t;if(e.backend!=="claude"&&e.backend!=="pi")throw new Error("Invalid session registry selection backend");return{backend:e.backend,provider:h(e.provider),model:a(e.model),thinking:h(e.thinking),connection:Nn(e)}}function Nn(t){return t.backend!=="claude"?null:"connection"in t?h(t.connection):he("claude",t.mode)}function g(t){if(t!==void 0){if(typeof t!="boolean")throw new Error("Invalid session registry boolean field");return t}}function c(t){if(t!==void 0)return E(t)}function De(t){if(t!==void 0){if(!Array.isArray(t))throw new Error("Invalid session registry allowed paths");return t.map(Un)}}function Un(t){let e=t;if(!e||typeof e!="object"||typeof e.path!="string"||typeof e.write!="boolean")throw new Error("Invalid session registry allowed path");return e.device===void 0?{path:e.path,write:e.write}:{device:a(e.device),path:e.path,write:e.write}}function ee(t){if(t==="local"||t==="scheduled")return t;throw new Error("Invalid session registry kind")}function Re(t){if(t==="direct"||t==="thread"||t==="scheduled")return t;throw new Error("Invalid session registry origin")}function M(t){if(typeof t!="number"||!Number.isFinite(t))throw new Error("Invalid session registry number field");return t}function h(t){if(t===null)return null;if(typeof t=="string")return t;throw new Error("Invalid session registry turn nullable string")}function Te(t){if(!Array.isArray(t)||t.some(e=>typeof e!="string"))throw new Error("Invalid session registry string array");return[...t]}function Pe(t){if(t==="processing"||t==="completed"||t==="superseded")return t;throw new Error("Invalid session registry turn status")}var Fe={projectId:a,channel:a,backend:a,kind:ee,origin:Re,createdAt:a,lastUsedAt:a,label:E,starred:g,labelRenamed:g,selection:j,agentName:c,backendSessionId:c,lastReadAt:c,scheduleId:c,boardId:c,boardBlockFor:c,contextUsage:t=>t,teamLeadId:c,workerName:c,workerBrief:c,workerBlockFor:c,clean:g,workspaceDir:c,allowedPaths:De,allowedPathsBlockFor:c},ne=Object.keys(Fe),Ln=new Set(ne),Ie={commissionId:"boardId",commissionBlockFor:"boardBlockFor",commissionDraft:null,workerRetiredAt:null,profileName:null,browser:null};function Me(t){return Object.hasOwn(Ie,t)?Ie[t]:t}function $n(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Invalid session registry patch fields");let e=t,n={};for(let i of Object.keys(e)){if(i==="profileName"){n[i]=e[i];continue}let r=Me(i);if(r===null||r!==i&&Object.hasOwn(e,r))continue;let s=Fe[r];if(!s)throw new Error(`Unknown session registry patch field: ${i}`);n[r]=s(e[i])}return n}function zn(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Invalid session registry turn record");let e=t;return{turnIndex:M(e.turnIndex),userMessageTs:a(e.userMessageTs),userMessageText:a(e.userMessageText),statusMessageTs:h(e.statusMessageTs),responseMessageTimestamps:Te(e.responseMessageTimestamps),executionId:h(e.executionId),backupPath:h(e.backupPath),..._n(e.anchor),status:Pe(e.status),createdAt:a(e.createdAt),updatedAt:a(e.updatedAt)}}function _n(t){let e=G(t);return e?{anchor:e}:{}}var Hn={turnIndex:M,userMessageTs:a,userMessageText:a,statusMessageTs:h,responseMessageTimestamps:Te,executionId:h,backupPath:h,anchor:G,status:Pe,createdAt:a,updatedAt:a};function Yn(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Invalid session registry turn patch");let e=t,n={};for(let i of Object.keys(e)){let r=Hn[i];if(!r)throw new Error(`Unknown session registry turn field: ${i}`);n[i]=r(e[i])}return n}var Jn={sessionId:h,backend:a,selection:j,updatedAt:a};function Kn(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Invalid session registry conversation fields");let e=t,n={};for(let i of Object.keys(e)){if(i==="profileName"){n[i]=e[i];continue}let r=Jn[i];if(i!=="sessionName"){if(!r)throw new Error(`Unknown session registry conversation field: ${i}`);n[i]=r(e[i])}}return n}function Wn(t,e){e.op==="put"&&Oe(t,e.record),e.op==="delete-intent"&&Gn(t,e.record),e.op==="delete-commit"&&je(t,e.id),e.op==="patch"&&Vn(t,e.id)}function Vn(t,e){if(!t.live.has(e))throw new Error(`Patch for non-live session: ${e}`)}function Oe(t,e){if(t.pending.has(e.sessionId))throw new Error(`Cannot revive pending-deletion session: ${e.sessionId}`)}function Gn(t,e){if(!t.live.get(e.sessionId))throw new Error(`Delete intent for missing session: ${e.sessionId}`)}function je(t,e){if(!t.pending.has(e))throw new Error(`Delete commit for missing intent: ${e}`)}function Ne(t,e){if(e.op==="put")return Ue(t,e.record);if(e.op==="delete-intent")return nt(t,e.record,e.cleanup);if(e.op==="delete-commit")return tt(t,e.id);if(e.op==="patch")return Xn(t,e);if(e.op==="bind")return Qn(t,e.channel,e.sessionId);if(e.op==="unbind")return Zn(t,e.channel);if(e.op==="conversation")return et(t,e);qn(t,e)}function Xn(t,e){let n=t.live.get(e.id);if(!n)return;let i={...n,...e.fields};for(let r of e.unset??[])delete i[r];(i.selection||i.profileName===void 0)&&delete i.profileName,t.live.set(e.id,i)}function Qn(t,e,n){t.bindings.set(e,n)}function Zn(t,e){t.bindings.delete(e)}function qn(t,e){let n=t.turns.get(e.channel)??[];if(e.kind==="begin")n.push(e.turn),t.turns.set(e.channel,n);else if(e.kind==="patch"){let i=n.findIndex(r=>r.turnIndex===e.turnIndex);i>=0&&(n[i]={...n[i],...e.fields})}else e.kind==="truncate"?t.turns.set(e.channel,n.filter(i=>i.turnIndex<e.fromIndex)):t.turns.delete(e.channel)}function et(t,e){if(e.kind==="clear"){t.conversations.delete(e.channel);return}let i={...t.conversations.get(e.channel)??{sessionId:null,backend:"",selection:null,updatedAt:""},...e.fields};i.selection&&delete i.profileName,t.conversations.set(e.channel,i)}function Ue(t,e){Oe(t,e),t.live.set(e.sessionId,e)}function nt(t,e,n={claudeBackupPaths:[]}){t.live.delete(e.sessionId),t.pending.set(e.sessionId,{session:e,cleanup:n})}function tt(t,e){je(t,e),t.pending.delete(e);for(let[n,i]of t.bindings)i===e&&(t.bindings.delete(n),t.turns.delete(n),t.conversations.delete(n))}async function it(t,e,n){let i=await u.open(t,"a+"),r=(await i.stat()).size;try{return await(n?n(i,e):i.writeFile(e,"utf8")),await i.sync(),(await i.stat()).size}catch(s){throw await i.truncate(r),await i.sync(),s}finally{await i.close()}}async function Le(t,e){let n=`${t}.tmp.${process.pid}.${Date.now()}`;try{await rt(n,e),await u.rename(n,t),await ot(t)}catch(i){throw await st(n),i}}async function rt(t,e){let n=await u.open(t,"w");try{let i=[],r=0;for(let s of e){let o=`${JSON.stringify(s)}
6
+ `;i.push(o),r+=o.length,!(r<ln)&&(await n.writeFile(i.join(""),"utf8"),i=[],r=0)}i.length&&await n.writeFile(i.join(""),"utf8"),await n.sync()}finally{await n.close()}}async function ot(t){if(process.platform==="win32")return;let e=await u.open(Q.dirname(t),"r");try{await e.sync()}finally{await e.close()}}async function st(t){try{await u.rm(t,{force:!0})}catch(e){if(e.code!=="ENOENT")throw e}}async function at(t){let e=await u.open(t,"r+");try{let n=(await e.stat()).size,i=await ct(e,n);if(i===n)return;await e.truncate(i),await e.sync()}finally{await e.close()}}async function ct(t,e){if(e===0)return 0;let n=Buffer.alloc(Math.min(e,4096));if(await t.read(n,0,n.length,e-n.length),n[n.length-1]===10)return e;let i=n.lastIndexOf(10);return i>=0?e-n.length+i+1:lt(t,e-n.length)}async function lt(t,e){let n=e;for(;n>0;){let i=Math.min(n,4096),r=Buffer.alloc(i);n-=i,await t.read(r,0,i,n);let s=r.lastIndexOf(10);if(s>=0)return n+s+1}return 0}async function O(t){try{return await u.stat(t)}catch{return null}}async function dt(){await new Promise(t=>setImmediate(t))}var ft=ze.join(w,"session-registry.jsonl");function ht(t,e){let n={},i=[];for(let r of ne){let s=t[r],o=e[r],l=s!==void 0,B=o!==void 0;if(!(!l&&!B)){if(l&&!B){i.push(r);continue}ut(s,o)||(n[r]=o)}}return Object.keys(n).length===0&&i.length===0?null:{fields:n,unset:i}}function S(t){return{...t,selection:t.selection?{...t.selection}:null}}function y(t){return Array.from(t,S).sort((e,n)=>n.lastUsedAt.localeCompare(e.lastUsedAt))}function pt(t){return Array.from(t,e=>({session:S(e.session),cleanup:{claudeBackupPaths:[...e.cleanup.claudeBackupPaths]}})).sort((e,n)=>n.session.lastUsedAt.localeCompare(e.session.lastUsedAt))}function te(t){return t?.substring(0,60)||null}function yt(t){return t instanceof Date?t.getTime():t}function mt(t){let e=new Date(t).getTime();return Number.isFinite(e)?e:null}function wt(t,e){return e===null?(delete t.contextUsage,t):(t.contextUsage=e,t)}function _e(t){return t.backendSessionId===void 0?t.sessionId:t.backendSessionId}var re=class{filePath;mutex=new m;options;state=A();loaded=!1;conduitResolvers=[];constructor(e=ft,n={}){this.filePath=e,this.options=n}async registerSession(e){await this.withState(n=>this.doRegisterSession(n,e))}async doRegisterSession(e,n){let i=new Date().toISOString();await this.writePut(e,{sessionId:n.sessionId,projectId:n.projectId??"general",channel:n.channel,backend:n.backend,kind:n.kind,origin:n.origin??(n.kind==="scheduled"?"scheduled":"direct"),createdAt:i,lastUsedAt:i,label:te(n.label),selection:n.selection?{...n.selection}:null,agentName:n.agentName??null,backendSessionId:n.backendSessionId??null,scheduleId:n.scheduleId??null,boardId:n.boardId??null,...n.teamLeadId?{teamLeadId:n.teamLeadId,workerName:n.workerName??null,workerBrief:n.workerBrief??null}:{},...n.clean?{clean:!0,workspaceDir:n.workspaceDir??null}:{},...n.clean&&n.allowedPaths?.length?{allowedPaths:n.allowedPaths.map(r=>({...r}))}:{}})}async convertToDirect(e,n){return this.updateById(e,i=>({...i,channel:n.channel,kind:"local",origin:"direct"}))}async updateSession(e,n){if("sessionId"in n)throw new Error("updateSession may not change sessionId");await this.withState(i=>this.doUpdateSession(i,e,n))}async doUpdateSession(e,n,i){let r=e.live.get(n);r&&await this.writePatch(e,r,{...r,lastUsedAt:i.lastUsedAt??r.lastUsedAt,label:i.label!==void 0?te(i.label):r.label,selection:i.selection!==void 0?i.selection:r.selection,backend:i.backend??r.backend,agentName:i.agentName!==void 0?i.agentName:r.agentName,backendSessionId:i.backendSessionId!==void 0?i.backendSessionId:r.backendSessionId,contextUsage:i.contextUsage!==void 0?i.contextUsage:r.contextUsage})}async updateContextUsage(e,n){await this.updateById(e,i=>wt({...i},n))}async listRecentSessions(e=10){return this.withState(async n=>y(n.live.values()).slice(0,e))}async getById(e){return this.withState(async n=>{let i=n.live.get(e);return i?S(i):null})}async listByProject(e){return this.withState(async n=>y(N(n,i=>i.projectId===e)))}async listByOrigin(e,n){return this.withState(async i=>y(N(i,r=>r.origin===e&&(n===void 0||r.projectId===n))))}async listWorkers(e){return this.withState(async n=>y(N(n,i=>i.teamLeadId===e)))}async listResumable(e){return this.withState(async n=>y(N(n,i=>i.kind!=="scheduled"&&(e===void 0||i.projectId===e))))}async touchSessionUse(e){return this.withState(async n=>{let i=n.live.get(e);return!i||n.pending.has(e)?!1:(await this.writePatch(n,i,{...i,lastUsedAt:new Date().toISOString()}),!0)})}async setStarred(e,n){return this.updateById(e,i=>({...i,starred:n}))}async rename(e,n){return this.updateById(e,i=>({...i,label:n,labelRenamed:!0}))}async fillLabelIfAbsent(e,n){let i=te(n.trim());return this.updateById(e,r=>r.label?.trim()||!i?r:{...r,label:i})}async markRead(e){await this.updateById(e,n=>({...n,lastReadAt:new Date().toISOString()}))}async bindBoard(e,n){return this.updateById(e,i=>i.boardId===n?i:{...i,boardId:n})}async markBoardBlockDelivered(e,n){return this.updateById(e,i=>({...i,boardBlockFor:n}))}async clearBoardBlockDelivery(e){return this.updateById(e,n=>n.boardBlockFor==null?n:{...n,boardBlockFor:null})}async markWorkerBlockDelivered(e,n){return this.updateById(e,i=>i.workerBlockFor===n?i:{...i,workerBlockFor:n})}async clearWorkerBlockDelivery(e){return this.updateById(e,n=>n.workerBlockFor==null?n:{...n,workerBlockFor:null})}async setAllowedPaths(e,n){return this.updateById(e,i=>({...i,allowedPaths:n.map(r=>({...r}))}))}async markAllowedPathsBlockDelivered(e,n){return this.updateById(e,i=>(i.allowedPathsBlockFor??null)===n?i:{...i,allowedPathsBlockFor:n})}async clearAllowedPathsBlockDelivery(e){return this.updateById(e,n=>n.allowedPathsBlockFor==null?n:{...n,allowedPathsBlockFor:null})}registerConduitResolver(e){return this.conduitResolvers.push(e),()=>{let n=this.conduitResolvers.indexOf(e);n>=0&&this.conduitResolvers.splice(n,1)}}async getBoundSessionId(e){for(let n of this.conduitResolvers){let i=n(e);if(typeof i=="string"&&i)return i}return this.withState(async n=>n.bindings.get(e)??null)}async bindChannel(e,n){await this.withState(i=>this.doBindChannel(i,e,n))}async unbindChannel(e){await this.withState(n=>this.doUnbindChannel(n,e))}async releaseChannels(e){let n=new Set(e);return n.size===0?0:this.withState(async i=>{let r=Array.from(i.bindings).filter(([,o])=>n.has(o)).map(([o])=>o),s=Array.from(i.conversations).filter(([,o])=>o.sessionId&&n.has(o.sessionId)).map(([o])=>o);return await this.appendBatch(i,[...r.map(o=>({v:1,op:"unbind",channel:o})),...s.flatMap(o=>[{v:1,op:"conversation",channel:o,kind:"clear"},{v:1,op:"turn",channel:o,kind:"clear"}])]),new Set([...r,...s]).size})}async listBindings(){return this.withState(async e=>Array.from(e.bindings,([n,i])=>({channel:n,sessionId:i})))}async beginTurn(e,n){await this.withState(i=>this.doBeginTurn(i,e,n))}async patchTurn(e,n,i){await this.withState(r=>this.doPatchTurn(r,e,n,i))}async truncateTurns(e,n){await this.withState(i=>this.doTruncateTurns(i,e,n))}async clearTurns(e){await this.withState(n=>this.doClearTurns(n,e))}async getTurns(e){return this.withState(async n=>x(n,e))}async getConversationHeader(e){return this.withState(async n=>ie(n,e))}async setConversation(e,n){await this.withState(i=>this.doSetConversation(i,e,n))}async clearConversation(e){await this.withState(n=>this.doClearConversation(n,e))}async readConversation(e){return this.withState(async n=>{let i=ie(n,e);return i?{header:i,turns:x(n,e)}:null})}async listConversations(){return this.withState(async e=>Array.from(e.conversations,([n,i])=>({channel:n,header:{...i},turns:x(e,n)})))}async batch(e){return this.withState(n=>e(this.batchOps(n)))}batchOps(e){return{registerSession:n=>this.doRegisterSession(e,n),updateSession:(n,i)=>{if("sessionId"in i)throw new Error("updateSession may not change sessionId");return this.doUpdateSession(e,n,i)},updateById:(n,i)=>this.doUpdateById(e,n,i),bindChannel:(n,i)=>this.doBindChannel(e,n,i),unbindChannel:n=>this.doUnbindChannel(e,n),beginTurn:(n,i)=>this.doBeginTurn(e,n,i),patchTurn:(n,i,r)=>this.doPatchTurn(e,n,i,r),truncateTurns:(n,i)=>this.doTruncateTurns(e,n,i),clearTurns:n=>this.doClearTurns(e,n),setConversation:(n,i)=>this.doSetConversation(e,n,i),clearConversation:n=>this.doClearConversation(e,n),getTurns:n=>x(e,n),getConversationHeader:n=>ie(e,n)}}async doBindChannel(e,n,i){e.bindings.get(n)!==i&&(await f(this.filePath,e,{v:1,op:"bind",channel:n,sessionId:i},this.options),await this.maybeCompact(e))}async doUnbindChannel(e,n){e.bindings.has(n)&&(await f(this.filePath,e,{v:1,op:"unbind",channel:n},this.options),await this.maybeCompact(e))}async doBeginTurn(e,n,i){await f(this.filePath,e,{v:1,op:"turn",channel:n,kind:"begin",turn:{...i}},this.options),await this.maybeCompact(e)}async doPatchTurn(e,n,i,r){await f(this.filePath,e,{v:1,op:"turn",channel:n,kind:"patch",turnIndex:i,fields:{...r}},this.options),await this.maybeCompact(e)}async doTruncateTurns(e,n,i){await f(this.filePath,e,{v:1,op:"turn",channel:n,kind:"truncate",fromIndex:i},this.options),await this.maybeCompact(e)}async doClearTurns(e,n){await f(this.filePath,e,{v:1,op:"turn",channel:n,kind:"clear"},this.options),await this.maybeCompact(e)}async doSetConversation(e,n,i){await f(this.filePath,e,{v:1,op:"conversation",channel:n,kind:"set",fields:{...i}},this.options),await this.maybeCompact(e)}async doClearConversation(e,n){e.conversations.has(n)&&(await f(this.filePath,e,{v:1,op:"conversation",channel:n,kind:"clear"},this.options),await this.maybeCompact(e))}async listPendingDeletions(){return this.withState(async e=>pt(e.pending.values()))}async beginDeleteExpired(e,n,i=$e){return this.withState(async r=>{let s=gt(y(r.live.values()),yt(e),new Set(n));return this.writeDeleteIntents(r,s,i)})}async beginDelete(e,n=$e){return this.withState(async i=>{let r=new Set(e),s=y(i.live.values()).filter(o=>r.has(o.sessionId)||!!o.teamLeadId&&r.has(o.teamLeadId));return this.writeDeleteIntents(i,s,n)})}async commitDeletion(e){return(await this.commitDeletions([e])).length>0}async commitDeletions(e){return this.withState(async n=>{let i=[...new Set(e)].filter(r=>n.pending.has(r));return await this.appendBatch(n,i.map(r=>({v:1,op:"delete-commit",id:r}))),i})}async compactNow(){await this.withState(async e=>{await q(this.filePath,e,this.options)})}invalidate(){this.state=A(),this.loaded=!1}flush(){return this.mutex.run(async()=>{})}withState(e){return this.mutex.run(async()=>e(await this.loadState()))}async loadState(){return this.loaded||(this.state=await Ce(this.filePath,this.options),this.loaded=!0),this.state}async writePut(e,n){await f(this.filePath,e,{v:1,op:"put",id:n.sessionId,record:n},this.options),await this.maybeCompact(e)}async updateById(e,n){return this.withState(i=>this.doUpdateById(i,e,n))}async doUpdateById(e,n,i){let r=e.live.get(n);if(!r)return null;let s=i(S(r));return await this.writePatch(e,r,s),s}async writePatch(e,n,i){let r=ht(n,i);r&&(await f(this.filePath,e,{v:1,op:"patch",id:n.sessionId,fields:r.fields,...r.unset.length?{unset:r.unset}:{}},this.options),await this.maybeCompact(e))}async writeDeleteIntents(e,n,i){let r=St(e),s=[];for(let o of n){let l=(r.get(o.sessionId)??[]).flatMap(B=>x(e,B));s.push({session:S(o),cleanup:await i(S(o),l)})}return await this.appendBatch(e,s.map(({session:o,cleanup:l})=>({v:1,op:"delete-intent",id:o.sessionId,record:o,cleanup:l}))),s}async appendBatch(e,n){n.length!==0&&(await Z(this.filePath,e,n,this.options),await this.maybeCompact(e))}async maybeCompact(e){xe(e,this.options)&&await q(this.filePath,e,this.options)}},$e=async()=>({claudeBackupPaths:[]});function gt(t,e,n){let i=o=>{if(o.starred===!0||o.boardId)return!1;let l=mt(o.lastUsedAt);return l!==null&&l<e},r=new Set(t.filter(o=>!o.teamLeadId&&!n.has(o.sessionId)&&i(o)).map(o=>o.sessionId)),s=new Set(t.map(o=>o.sessionId));return t.filter(o=>{if(n.has(o.sessionId)||o.starred===!0)return!1;let l=o.teamLeadId&&s.has(o.teamLeadId)?o.teamLeadId:null;return l?r.has(l):i(o)})}function x(t,e){return(t.turns.get(e)??[]).map(n=>({...n}))}function ie(t,e){let n=t.conversations.get(e);return n?{...n}:null}function St(t){let e=new Map;for(let[n,i]of t.conversations){if(!i.sessionId)continue;let r=e.get(i.sessionId)??[];r.push(n),e.set(i.sessionId,r)}return e}function*N(t,e){for(let n of t.live.values())e(n)&&(yield n)}var b=new re;pe(b);var He=null;function bt(t){let e=t;if(T(e?.default),!Array.isArray(e.favorites))throw new Error("favorites must be an array");let n=new Set;for(let i of e.favorites){H(i);let r=R(i);if(n.has(r))throw new Error(`Duplicate favorite: ${i.model}`);n.add(r)}}function L(){try{let t=P.readSync();return t!==He&&(bt(t),He=t),{default:p(t.default),favorites:t.favorites.map(U)}}catch(t){throw new Error(`Failed to load models.json: ${t.message}`)}}function U({backend:t,provider:e,model:n}){return{backend:t,provider:e,model:n}}function k(){return L().default}function ui(){return L().favorites}function Ye(){return P.readIfPresent()?.default?k():null}function $(t){let e;try{e=L()}catch{return null}if(e.default.backend===t)return U(e.default);let n=e.favorites.find(i=>i.backend===t);return n?U(n):null}function kt(t){let e=t.indexOf("/");if(e<0)return null;let n={backend:"pi",provider:t.slice(0,e),model:t.slice(e+1)};return H(n),n}function It(t,e){let n=[e.default,...e.favorites].filter(s=>s.backend==="pi"),i=me(ye.peek(),t).filter(s=>s.backend==="pi"),r=[...n,...i].find(s=>s.model===t);if(r)return U(r);if(e.default.backend==="pi")return{backend:"pi",provider:e.default.provider,model:t};throw new Error(`Unknown PI model '${t}': specify provider/model or favorite a model first`)}function fi(t,e){let n=t.trim();if(!n)throw new Error("Model must be a non-empty string");let i=kt(n);if(i)return i;let r=L();return(e??r.default.backend)==="claude"?{backend:"claude",provider:null,model:n}:It(n,r)}import{readFileSync as vt,renameSync as At,writeFileSync as Et}from"node:fs";import*as We from"node:path";var ae=We.join(w,"agent-state.json");function z(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Je(t){let e=D(t);try{return T(e),p(e)}catch{return null}}function oe(t,e){let n=Object.entries(z(t)).map(([i,r])=>[i,e(r)]);return Object.fromEntries(n.filter(([,i])=>i!==null))}function xt(t){let e=z(t);return e.thinking===null||typeof e.thinking=="string"&&!!e.thinking?{thinking:e.thinking}:null}function se(t){return typeof t=="string"&&t?t:null}function Ke(t){let e=z(t),n={channelSelections:oe(e.channelSelections,Je),modelMemory:oe(e.modelMemory,xt),defaultAgent:se(e.defaultAgent),channelAgents:oe(e.channelAgents,se)},i=Je(e.selectionDefault);if(i){n.selectionDefault=i;let r=se(z(e.selectionDefault).agentName);r&&(n.selectionDefault.agentName=r)}return n}function ce(){try{return Ke(JSON.parse(vt(ae,"utf8")))}catch{return Ke(null)}}function Ve(t){let e={};for(let i of["channelSelections","modelMemory","channelAgents"])Object.keys(t[i]).length&&(e[i]=t[i]);t.defaultAgent&&(e.defaultAgent=t.defaultAgent),t.selectionDefault&&(e.selectionDefault=t.selectionDefault);let n=`${ae}.tmp`;Et(n,JSON.stringify(e)),At(n,ae)}var d=ce();function Ii(){d=ce()}function I(t){Ve(t),d=t}function le(t,e,n){let i={...t};return n!==null?i[e]=n:delete i[e],i}function C(t){let e=t?d.channelSelections[t]:null;return e?p(e):null}function Ge(t,e){let n=e?p(e):null;I({...d,channelSelections:le(d.channelSelections,t,n)})}function Xe(){return Object.fromEntries(Object.entries(d.modelMemory).map(([t,e])=>[t,{...e}]))}function Qe(t){let e={thinking:t.thinking};I({...d,modelMemory:le(d.modelMemory,R(t),e)})}function vi(){try{return $("claude")?.model??"opus"}catch{return"opus"}}function Ai(t){let e=C(t);if(e)return e.backend;try{return k().backend}catch{return"claude"}}function Ze(t){let e=t?.agentName??d.selectionDefault?.agentName,n=t?{...p(t),...e?{agentName:e}:{}}:void 0;I({...d,selectionDefault:n})}function Ei(t){let e={...d.selectionDefault??k()};t?e.agentName=t:delete e.agentName,I({...d,selectionDefault:e})}function xi(){return d.selectionDefault?{...d.selectionDefault}:null}function Ci(t){return t&&d.channelAgents[t]||d.defaultAgent}function Ct(t,e){if(!e)return I({...d,defaultAgent:t});I({...d,channelAgents:le(d.channelAgents,e,t)})}function Bi(t){d.channelAgents[t]&&Ct(null,t)}function Di(){return{...d.channelAgents}}var Bt={selection:Ye,forBackend:$};function Dt(t={}){return{...t,defaults:Bt,memory:Xe}}function qe(t,e={}){return we(Dt(t),e)}async function en(t){let e=await b.getBoundSessionId(t);return e?b.getById(e):null}async function ji(t){let e=await en(t),n=qe({session:e?.selection,draft:C(t)});if(n.ok===!1)throw new Error(`No model is configured for this conversation (${n.reason})`);return n.effective}function Ni(t){return C(t)??k()}function Rt(t){let e=t.currentBackend!==t.targetBackend;return t.hasHistory&&e?{allowed:!1,reason:"cross-backend-live-session"}:{allowed:!0,backendChanged:e}}function nn(t,e,n){return{...t??{backend:"claude",provider:null,model:"",thinking:null,connection:null},ok:!1,backendChanged:!1,reason:e,...n?{allowed:n}:{}}}function Tt(t){let{channel:e,seedDefault:n,inventory:i,catalog:r,...s}=t;return s}var Pt=new m;function Ui(t){return Pt.run(()=>Ft(t))}async function Ft(t){let e=await en(t.channel),n=qe({session:e?.selection,draft:C(t.channel),inventory:t.inventory,catalog:t.catalog},Tt(t));return n.ok===!1?nn(n.base,n.reason,n.allowed):Mt(t,n.base,n.selection,e)}async function Mt(t,e,n,i){let r=!!(i&&_e(i))||(await b.getTurns(t.channel)).length>0,s=i?.backend??e?.backend??n.backend,o=Rt({currentBackend:s,targetBackend:n.backend,hasHistory:r});return o.allowed?(i&&await b.updateSession(i.sessionId,{backend:n.backend,selection:n}),Ge(t.channel,n),Qe(n),t.channel.startsWith("web:")&&t.seedDefault!==!1&&Ze(n),{...n,ok:!0,backendChanged:o.backendChanged}):{...nn(e,"cross-backend-live-session"),currentBackend:s,targetBackend:n.backend}}export{ke as a,_t as b,Ht as c,P as d,Yt as e,Jt as f,k as g,ui as h,Ye as i,fi as j,_e as k,re as l,b as m,Ii as n,C as o,Ge as p,Xe as q,Qe as r,vi as s,Ai as t,Ei as u,xi as v,Ci as w,Ct as x,Bi as y,Di as z,qe as A,ji as B,Ni as C,Ui as D};
@@ -1,4 +1,4 @@
1
1
  import { createRequire as __cortexCreateRequire } from 'node:module';
2
2
  const require = __cortexCreateRequire(import.meta.url);
3
3
  const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{r as c}from"./chunk-J5DVLUKY.js";import{existsSync as i,mkdirSync as s,readFileSync as n,statSync as m,writeFileSync as u,unlinkSync as a,utimesSync as p}from"fs";import{execFileSync as l}from"node:child_process";import{dirname as f}from"node:path";var d=100,S=2e3;function T(t){try{return process.kill(t,0),!0}catch{return!1}}function x(t){let e=n(`/proc/${t}/stat`,"utf8"),r=Number(e.slice(e.lastIndexOf(")")+2).split(" ")[19]);return(Number(/^btime (\d+)$/m.exec(n("/proc/stat","utf8"))?.[1])+r/d)*1e3}function w(t){let e=`[DateTimeOffset]::new((Get-Process -Id ${t} -ErrorAction Stop).StartTime).ToUnixTimeMilliseconds()`;return Number(l("powershell.exe",["-NoProfile","-NonInteractive","-Command",e],{encoding:"utf8",timeout:1e4,windowsHide:!0,stdio:["ignore","pipe","ignore"]}).trim())}function y(t){return new Date(l("ps",["-o","lstart=","-p",String(t)],{encoding:"utf8",timeout:5e3,env:{...process.env,LC_ALL:"C"},stdio:["ignore","pipe","ignore"]}).trim()).getTime()}var _={linux:x,win32:w};function E(t){let e=_[process.platform]??y;try{let r=e(t);return Number.isFinite(r)&&r>0?r:null}catch{return null}}function N(t,e){if(!T(e))return!1;let r=E(e),o=m(t,{throwIfNoEntry:!1})?.mtimeMs;return r===null||o===void 0?!0:r<=o+S}function A(t){try{let e=Number(n(t,"utf8").trim());return Number.isInteger(e)&&e>0?e:null}catch{return null}}function I(t){let e=A(t);return e!==null&&N(t,e)?e:null}function g(t=c){if(s(f(t),{recursive:!0}),!i(t)){u(t,"");return}let e=new Date;p(t,e,e)}function h(t){s(f(t),{recursive:!0});let e=I(t);if(e!==null)return{acquired:!1,holderPid:e};let r=i(t);return u(t,String(process.pid),"utf8"),{acquired:!0,stale:r}}function v(t){try{if(!i(t))return;let e=n(t,"utf8").trim();Number(e)===process.pid&&a(t)}catch{}}export{T as a,N as b,A as c,I as d,g as e,h as f,v as g};
4
+ import{s as c}from"./chunk-T54CZKNJ.js";import{existsSync as i,mkdirSync as s,readFileSync as n,statSync as m,writeFileSync as u,unlinkSync as a,utimesSync as p}from"fs";import{execFileSync as l}from"node:child_process";import{dirname as f}from"node:path";var d=100,S=2e3;function T(t){try{return process.kill(t,0),!0}catch{return!1}}function x(t){let e=n(`/proc/${t}/stat`,"utf8"),r=Number(e.slice(e.lastIndexOf(")")+2).split(" ")[19]);return(Number(/^btime (\d+)$/m.exec(n("/proc/stat","utf8"))?.[1])+r/d)*1e3}function w(t){let e=`[DateTimeOffset]::new((Get-Process -Id ${t} -ErrorAction Stop).StartTime).ToUnixTimeMilliseconds()`;return Number(l("powershell.exe",["-NoProfile","-NonInteractive","-Command",e],{encoding:"utf8",timeout:1e4,windowsHide:!0,stdio:["ignore","pipe","ignore"]}).trim())}function y(t){return new Date(l("ps",["-o","lstart=","-p",String(t)],{encoding:"utf8",timeout:5e3,env:{...process.env,LC_ALL:"C"},stdio:["ignore","pipe","ignore"]}).trim()).getTime()}var _={linux:x,win32:w};function E(t){let e=_[process.platform]??y;try{let r=e(t);return Number.isFinite(r)&&r>0?r:null}catch{return null}}function N(t,e){if(!T(e))return!1;let r=E(e),o=m(t,{throwIfNoEntry:!1})?.mtimeMs;return r===null||o===void 0?!0:r<=o+S}function A(t){try{let e=Number(n(t,"utf8").trim());return Number.isInteger(e)&&e>0?e:null}catch{return null}}function I(t){let e=A(t);return e!==null&&N(t,e)?e:null}function g(t=c){if(s(f(t),{recursive:!0}),!i(t)){u(t,"");return}let e=new Date;p(t,e,e)}function h(t){s(f(t),{recursive:!0});let e=I(t);if(e!==null)return{acquired:!1,holderPid:e};let r=i(t);return u(t,String(process.pid),"utf8"),{acquired:!0,stale:r}}function v(t){try{if(!i(t))return;let e=n(t,"utf8").trim();Number(e)===process.pid&&a(t)}catch{}}export{T as a,N as b,A as c,I as d,g as e,h as f,v as g};
@@ -0,0 +1,4 @@
1
+ import { createRequire as __cortexCreateRequire } from 'node:module';
2
+ const require = __cortexCreateRequire(import.meta.url);
3
+ const __cortexPackageRoot = new URL("../../", import.meta.url);
4
+ import{a as e}from"./chunk-SDUS2H3E.js";var t={transport:"auto",sessionShareDestination:"auto",steeringMode:"one-at-a-time",followUpMode:"one-at-a-time",compaction:{enabled:!0,reserveTokens:16384,keepRecentTokens:2e4},branchSummary:{reserveTokens:16384,skipPrompt:!1},retry:{enabled:!0,maxRetries:3,baseDelayMs:2e3,maxAgentDelayMs:e,provider:{maxRetryDelayMs:6e4}},hideThinkingBlock:!1,showCacheMissNotices:!1,quietStartup:!1,defaultProjectTrust:"ask",collapseChangelog:!1,enableInstallTelemetry:!0,enableAnalytics:!1,enableSkillCommands:!0,terminal:{showImages:!0,imageWidthCells:60,clearOnShrink:!1,showTerminalProgress:!1},images:{autoResize:!0,blockImages:!1},doubleEscapeAction:"tree",treeFilterMode:"default",editorPaddingX:0,outputPad:1,autocompleteMaxVisible:5,markdown:{codeBlockIndent:" ",mermaid:"streaming"},warnings:{anthropicExtraUsage:!0},codemode:{mode:"on",inlineBudget:3e3},cacheWarming:"idle",tuiMode:"fullscreen",fullscreenExitOutput:"transcript",fullscreenScrollbar:"auto",fullscreenCopyOnSelect:!0,fullscreenWheelScrollLines:"auto"};export{t as a};
@@ -0,0 +1,15 @@
1
+ import { createRequire as __cortexCreateRequire } from 'node:module';
2
+ const require = __cortexCreateRequire(import.meta.url);
3
+ const __cortexPackageRoot = new URL("../../", import.meta.url);
4
+ import{e as ce,g as de,h as d,i as pe}from"./chunk-Y3AOGNDT.js";import{a as ne,b as re}from"./chunk-2YTYYG4K.js";import{a as le}from"./chunk-IWY2HIFK.js";import{b as ue,d as fe}from"./chunk-RW2F2QNP.js";import{g as C}from"./chunk-OZXMPBUX.js";import{a as oe,d as ie,e as se}from"./chunk-UEEW2R4E.js";import{a as w}from"./chunk-LCKVYFMD.js";import{e as I}from"./chunk-BKYP6AGM.js";import{d as T,v as ae}from"./chunk-KST6OY76.js";import{d as ee,e as te}from"./chunk-SM45TH22.js";import{e as Y}from"./chunk-TRXLIL7V.js";import{e as y}from"./chunk-7GGPYU5E.js";import{e as f}from"./chunk-7W7VYUTK.js";import{j as K,u as Q}from"./chunk-T54CZKNJ.js";var Ve="server-update",Xe=5*6e4,D=null;function Qt(e){let t=e.now??Date.now();D={phase:e.phase??null,expiresAt:t+Xe}}function en(){D=null}function he(e=Date.now()){return D?e>=D.expiresAt?(D=null,null):{phase:D.phase}:null}function tn(e=Date.now()){return he(e)!==null}var me=160;function Ze(e){let t=e.replace(/\s+/g," ").trim();return t?t.length>me?`${t.slice(0,me)}\u2026`:t:"(no text)"}async function nn(e){let t=he()?.phase??"restart",n=t===Ve;if(e.interactive){let o={type:"interactive-reply",conduit:e.channel,sessionId:""},i=n?y("startup.updateHold"):y("startup.rebuildHold",{phase:t});await e.adapter.postMessage(o,{text:`${w.warning} ${i}`}).catch(()=>{});return}let r={channel:e.channel,preview:Ze(e.text)};await ce(e.adapter,{level:"warning",title:n?y("notice.serverUpdate.title"):y("notice.rebuild.title"),text:n?y("startup.updateHoldDropped",r):y("startup.rebuildHoldDropped",{phase:t,...r})}).catch(()=>{})}import{readFileSync as we,existsSync as Ye}from"fs";import*as ye from"path";var m=f("machine-registry"),$=ye.join(K,"machines.json"),E={},ge=!1,R=null,S=null;function Ke(e,t){if(typeof t.cortexPath!="string"||typeof t.gpuCount!="number")throw new Error(`Invalid machine entry "${e}": requires cortexPath (string) and gpuCount (number)`);let n=t.clientConnection??"direct";if(n!=="direct"&&n!=="ssh-reverse")throw new Error(`Invalid machine entry "${e}": clientConnection must be direct or ssh-reverse`);if(n==="ssh-reverse"&&!t.ssh?.trim())throw new Error(`Invalid machine entry "${e}": ssh-reverse requires ssh`);if(t.clientReversePort!==void 0){if(n!=="ssh-reverse")throw new Error(`Invalid machine entry "${e}": clientReversePort requires ssh-reverse`);if(!Number.isInteger(t.clientReversePort)||t.clientReversePort<1024||t.clientReversePort>65535)throw new Error(`Invalid machine entry "${e}": clientReversePort must be an integer in 1024..65535`)}}var j=null;function fn(e){j=e}var Se=null;function dn(e){Se=e}function Qe(e,t,n){e!==t?(m.info(`Hot-reload: machines changed [${e}] \u2192 [${t}]`),j?.(`${w.refresh} \`machines.json\` hot-reloaded: [${e}] \u2192 [${t}]`)):(m.info(`Hot-reload: ${n} machines reloaded`),j?.(`${w.refresh} \`machines.json\` hot-reloaded (${n} machines)`)),Se?.()}function be(e=!0){try{let t=we($,"utf-8"),n=JSON.parse(t);for(let[s,c]of Object.entries(n))Ke(s,c);let r=Object.keys(E).sort().join(","),o=Object.keys(n).sort().join(","),i=ge;E=n,ge=!0,i?Qe(r,o,Object.keys(n).length):m.info(`Loaded ${Object.keys(n).length} machines: ${Object.keys(n).join(", ")}`)}catch(t){let n=`[machine-registry] Failed to load ${$}: ${t.message}`;if(e)throw new Error(n);m.error(n+" \u2014 keeping previous config"),j?.(`${w.warning} \`machines.json\` hot-reload FAILED \u2014 keeping previous config`)}}function W(){return E}var et=64;function tt(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=et}function nt(e,t){try{let n=JSON.parse(we($,"utf-8"));return n[e]?(n[e].gpuCount=t,Y($,`${JSON.stringify(n,null,2)}
5
+ `),!0):!1}catch(n){return m.error(`Failed to persist gpuCount for ${e}: ${n.message}`),!1}}function ke(e,t){let n=E[e];if(!n||!tt(t))return"skipped";if(n.gpuCount===t)return"unchanged";if(!nt(e,t))return"skipped";let r=n.gpuCount;return n.gpuCount=t,m.info(`${e}: gpuCount ${r} \u2192 ${t} (client-reported)`),j?.(`${w.refresh} \`${e}\` gpuCount ${r} \u2192 ${t} (reported by its client)`),"updated"}function pn(){return Object.keys(E)[0]||"local"}function rt(){S&&clearTimeout(S),S=setTimeout(()=>{S=null,be(!1)},300)}function mn(){R?.close(),R=te({label:"machines.json",filePath:$,onChange:rt,warn:e=>m.error(e)})}function hn(){R?.close(),R=null,S&&clearTimeout(S),S=null}if(Ye($))try{be()}catch(e){m.error(`Auto-load failed: ${e.message}`)}var ot=3e4,it=f("hook-bus"),Ce=[],De=null;function st(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ct(e,t){return e===void 0?!0:st(e)?Object.entries(e).every(([n,r])=>Object.hasOwn(t,n)&&t[n]===r):!1}function at(e,t){let n=e.run.script===void 0?void 0:fe(e.run.script,De??ue());return{id:e.id,command:n===void 0?e.run.command:"node",args:n,timeoutMs:e.run.timeout===void 0?t:e.run.timeout*1e3,result:e.result}}function lt(e,t,n){return Ce.filter(r=>r.enabled!==!1).filter(r=>r.event===e).filter(r=>ct(r.matcher,t)).map(r=>at(r,n))}function L(e,t){let n=t instanceof Error?t.message:String(t);return it.error(`Hook ${e} failed: ${n}`),{id:e,error:n}}function ut(e,t){return e.result==="stdout-as-prompt"?{id:e.id,result:t.trim()}:{id:e.id}}function ft(e,t,n){let r=ut(e,t);return n?{...r,stderr:n}:r}async function dt(e,t,n){try{let r=await le({command:e.command,args:e.args,timeoutMs:e.timeoutMs,stdinPayload:t,env:n,label:e.id});return r.error?L(e.id,r.error):ft(e,r.stdout,r.stderr)}catch(r){return L(e.id,r)}}function bn(e){Ce=[...e.entries],De=e.scriptDirs??null}function pt(e){let t=JSON.stringify(e);if(t===void 0)throw new TypeError("Hook payload is not JSON-serializable");return t}async function F(e,t,n){let r=[...lt(e,t,n?.defaultTimeoutMs??ot),...n?.scopedHooks??[]];if(r.length===0)return[];let o;try{o=pt(t)}catch(s){return r.map(c=>L(c.id,s))}let i=[];for(let s of r)i.push(await dt(s,o,n?.env));return i}var U=null;function $e(e){U=e}function Dn(e,t){if(!(!U||!ae()))try{U(e,t)}catch{}}function _(e,t=1){t<=0||d(n=>{n.features[e]=(n.features[e]??0)+t})}function mt(e){d(t=>{t.messagesByChannel[e]=(t.messagesByChannel[e]??0)+1}),C("first_session")}function xn(e){return e.startsWith("slack")?"slack":e.startsWith("feishu")?"feishu":e.startsWith("tui")?"tui":"other"}function ht(e){d(t=>{t.uiOps[e]=(t.uiOps[e]??0)+1})}var gt=new Set(["sessions.send","sessions.createAndSend"]),wt=new Set(["sessions.create","sessions.createAndSend"]);function Tn(e,t,n){ht(e),t&&(gt.has(e)&&mt(n??"other"),wt.has(e)&&(_("session_created"),C("first_session")))}var yt={"/webhook/subagent":{start:"subagent_run"},"/webhook/team":{spawn:"worker_spawned"},"/webhook/board":{open:"board_opened"},"/webhook/waitpoint":{create:"waitpoint_created"}},O={day:"",ids:new Set};function St(e){let t=de(Date.now());O.day!==t&&Object.assign(O,{day:t,ids:new Set});let n=typeof e=="string"?e:"";O.ids.has(n)||(O.ids.add(n),_("browser_session"))}function Rn(e,t){let n=t??{};if(e==="/webhook/browser"&&n.action==="lease")return St(n.sessionId);let r=yt[e??""]?.[String(n.action)];r&&(_(r),r==="worker_spawned"&&C("first_worker"))}function On(e=1){e<=0||(_("schedule_created",e),C("first_schedule"))}function ve(e,t=process.env.CORTEX_MACHINE){e!==t&&(_("remote_client_connected"),C("first_remote_client"))}function Ee(){d(e=>{e.perf.remoteClientDisconnects+=1})}function An(e){d(t=>pe(t,e))}var je=[];function Hn(e,t=performance.now()){je.push([e,t])}function Nn(e,t=performance.now()){let n={imports:Math.round(e)},r=e;for(let[o,i]of je)n[o]=Math.max(0,Math.round(i-r)),r=i;n.total=Math.round(t),d(o=>{o.perf.startups.push(n),o.perf.startups.length>10&&o.perf.startups.shift()})}var bt=/^(?::[A-Za-z][A-Za-z0-9_]{0,30}|\*|[a-z][a-z-]{0,23})$/;function kt(e){return!e||e.length>80||!e.startsWith("/")?null:e.split("/").filter(n=>n!=="").every(n=>bt.test(n))?e:null}function Ct(e){d(({perf:{web:t}})=>{t.loads+=1,e.ttfbMs!==null&&(t.ttfbMs[T("webLoadMs",e.ttfbMs)]+=1),e.firstRenderMs!==null&&(t.firstRenderMs[T("webLoadMs",e.firstRenderMs)]+=1),e.interactiveMs!==null&&(t.interactiveMs[T("webLoadMs",e.interactiveMs)]+=1)})}function Dt(e,t){if(e.kind==="crash"){let{crashKind:r,errorName:o,message:i,stack:s,buildStamp:c,uptimeS:P}=e;return I({component:"web",kind:r,errorName:o,message:i,stack:s,buildStamp:c,uptimeS:P,client:t,route:kt(e.route)})}if(e.kind!=="native_crash")return;let n=new Date(e.at);I({component:e.component,kind:"panic",errorName:"panic",message:e.message,stack:e.stack,buildStamp:e.appVersion,client:t,at:Number.isNaN(n.getTime())?new Date:n})}function $t(e,t){if(e.kind==="load")return Ct(e);if(e.kind==="sse_reconnect")return d(n=>{n.perf.sseReconnects+=e.count});Dt(e,t)}function Pn(){$e($t)}import*as Le from"http";import*as Fe from"crypto";import*as Me from"crypto";var vt=f("reverse-stream"),Et="/reverse",_e=1e4,jt=64,h=new Map;function xe(e){if(!e)return null;let t=new URL(e,"http://placeholder");if(t.pathname!==Et)return null;let n=t.searchParams.get("stream");return n&&/^[0-9a-f]{32}$/.test(n)?n:null}function Te(e,t){if(h.size>=jt)throw new Error(`too many pending reverse streams (${h.size})`);let n=Me.randomBytes(16).toString("hex"),r,o,i=new Promise((c,P)=>{r=c,o=P}),s=setTimeout(()=>{h.delete(n),o(new Error(`device ${e} did not open a stream to ${t} within ${_e}ms`))},_e);return s.unref?.(),h.set(n,{device:e,target:t,resolve:r,reject:o,timer:s}),{id:n,socket:i}}function Ln(e,t,n){let{id:r,socket:o}=Te(e,`${t}:${n}`);return{id:r,message:{type:"open-stream",streamId:r,host:t,port:n},socket:o}}function Fn(e,t){let{id:n,socket:r}=Te(e,t);return{id:n,message:{type:"open-file-stream",streamId:n,path:t},socket:r}}function Re(e,t){let n=h.get(e);return n?(clearTimeout(n.timer),h.delete(e),vt.info(`stream ${e.slice(0,8)} claimed by ${n.device} \u2192 ${n.target}`),n.resolve(t),!0):!1}function z(e){let t=0;for(let[n,r]of h)r.device===e&&(clearTimeout(r.timer),h.delete(n),r.reject(new Error(`device ${e} disconnected before opening the stream`)),t++);return t}var b=new Map,M=new Map,Oe=6e4;function Ae(){return Oe}function He(e,t,n,r,o){let i=setTimeout(()=>{b.delete(e),o(new Error(`Command to "${t}" timed out after ${n/1e3}s`))},n);b.set(e,{device:t,resolve:r,reject:o,timer:i})}function A(e){let t=b.get(e);t&&(clearTimeout(t.timer),b.delete(e))}function Ne(e){let t=e.commandId?b.get(e.commandId):void 0;t&&(A(e.commandId),e.success?t.resolve(e.data):t.reject(new Error(e.error||"Command failed")))}function G(e,t){for(let[n,r]of[...b])e(n,r)&&(A(n),r.reject(t))}function B(e){clearTimeout(M.get(e)),M.delete(e)}function Pe(e,t){B(e),[...b.values()].some(n=>n.device===e)&&M.set(e,setTimeout(()=>{M.delete(e),G((n,r)=>r.device===e,t)},Oe))}function Ie(e,t){B(e);let n=new Set(t??[]),r=new Error(`Device "${e}" disconnected and the command's result was lost`);G((o,i)=>i.device===e&&!n.has(o),r)}function We(e){for(let t of[...M.keys()])B(t);G(()=>!0,e)}var a=f("client-manager"),q=null;function Kn(e){q=e}var x=null;function Qn(e){x=e}var u=new Map,N=new Map,k=new Map,Ue=0,g=null,H=null,V=null,J=null,ze="Server shutting down",_t=15e3,Mt=12e4,xt=3e4;function Ge(e,t){t!==ze&&Ee(),F("cortex:client.disconnected",t?{device:e,reason:t}:{device:e}).catch(()=>{})}function X(e,t){u.delete(e),N.set(e,Date.now()),a.info(`Device disconnected: ${e}${t?` (${t})`:""}`),Ge(e,t);let n=z(e);n>0&&a.info(`cancelled ${n} pending reverse stream(s) for ${e}`),Pe(e,new Error(`Device "${e}" disconnected${t?` (${t})`:""}`)),x?.onDeviceGone(e)}function Be(e,t){for(let n of[...k.get(e)??[]])n(t);k.delete(e)}function Tt(e){return Array.isArray(e.inflight)?e.inflight.filter(t=>typeof t=="string"):void 0}function Je(e){let t=u.get(e);if(!t)throw new Error(`Device "${e}" is not online`);if(t.ws.readyState!==ne.default.OPEN)throw X(e,"WebSocket is not open"),new Error(`Device "${e}" WebSocket is not open`);return t.ws}function Rt(e){return!!e&&(e==="::1"||/^(::ffff:)?127\./.test(e))}function Ot(e){return typeof e.pid=="number"&&Number.isInteger(e.pid)&&e.pid>0?e.pid:null}function At(e,t,n){if(n!==null&&t.pid===n){a.info(`Device ${t.device} reconnected before its old socket closed; retiring the old one`),u.delete(t.device),z(t.device);try{t.ws.terminate()}catch{}return!0}return a.info(`Device ${t.device} already connected, rejecting new connection`),e.close(4002,"Device already connected"),!1}function Ht(e,t,n){if(!t)return e.close(4001,"Missing device name"),!1;if(!Object.hasOwn(W(),t))return e.close(4005,"Unknown device"),!1;let r=u.get(t);return!r||r.ws===e||At(e,r,n)}function Nt(e,t,n){let r=t.device,o=Ot(t);if(!Ht(e,r,o))return null;let i=typeof t.bundleHash=="string"&&t.bundleHash?t.bundleHash:null,s=t.platform||"unknown";u.set(r,{device:r,platform:s,capabilities:t.capabilities||[],connectedAt:new Date,lastHeartbeat:new Date,bundleHash:i,pid:o,ws:e}),a.info(`Device connected: ${r} (${s})`),N.delete(r),Ie(r,Tt(t)),Be(r,!0),ve(r),F("cortex:client.connected",{device:r}).catch(()=>{}),ke(r,typeof t.gpuCount=="number"?t.gpuCount:null);try{q?.onHello(r,i)}catch(c){a.warn(`onHello hook failed for ${r}: ${c.message}`)}try{x?.onHello?.(r,{pid:o,loopback:Rt(n)})}catch(c){a.warn(`lifecycle hello hook failed for ${r}: ${c.message}`)}return r}function Pt(e){try{let t=JSON.parse(e);return t&&typeof t.type=="string"?t:null}catch{return null}}function It(e,t){try{q?.onUpdateResult(e,{ok:!!t.ok,hash:typeof t.hash=="string"?t.hash:void 0,error:typeof t.error=="string"?t.error:void 0})}catch(n){a.warn(`onUpdateResult hook failed for ${e}: ${n.message}`)}}function Wt(e,t){if(e.type==="result")return Ne(e);if(t)if(e.type==="heartbeat"){let n=u.get(t);n&&(n.lastHeartbeat=new Date)}else e.type==="update-result"&&It(t,e)}function Lt(e,t){let n=e.req.headers[oe],r=Array.isArray(n)?n[0]:n;if(ie(se(),r))return t(!0);let o=e.req.socket?.remoteAddress||"unknown";a.warn(`WS auth rejected from ${o}: ${r?"invalid token":"missing token"}`),t(!1,401,"Unauthorized")}function Ft(e,t){let n=null;e.on("message",r=>{let o=Pt(r.toString());o?.type==="hello"?n=Nt(e,o,t):o&&Wt(o,n)}),e.on("close",(r,o)=>{n&&u.get(n)?.ws===e&&X(n,o.toString().trim()||void 0)}),e.on("error",r=>{a.error(`WebSocket error for ${n||"unknown"}: ${r.message}`)})}function Ut(e,t){let n=xe(t.url);if(!n)return Ft(e,t.socket?.remoteAddress);Re(n,e)||(a.warn("reverse callback with an unknown stream id \u2014 closing"),e.close(4004,"Unknown stream"))}function zt(){let e=Date.now(),t=[...u.values()].filter(n=>e-n.lastHeartbeat.getTime()>_t);for(let n of t)if(u.get(n.device)===n){try{n.ws.close(4003,"Heartbeat timeout")}catch{}X(n.device,"Heartbeat timeout")}}function Gt(e,t,n){let r=g;if(!r){t.write(`HTTP/1.1 503 Service Unavailable\r
6
+ \r
7
+ `),t.destroy();return}r.handleUpgrade(e,t,n,o=>r.emit("connection",o,e))}function er(e,t,n={listen:!0}){if(g){a.warn("Already running");return}V=e,Ue=Date.now(),x?.onStart(),g=new re.default({noServer:!0,verifyClient:Lt}),g.on("connection",Ut),g.on("error",r=>{a.error(`Server error: ${r.message}`)}),n.listen!==!1?Bt(e,t):a.info(`Client hub started (clients connect on port ${e})`),H=setInterval(zt,5e3)}function Bt(e,t){let n=Le.createServer((r,o)=>{o.writeHead(426),o.end("Upgrade Required")});n.on("upgrade",(r,o,i)=>Gt(r,o,i)),n.on("error",r=>a.error(`Client listener on port ${e} failed: ${r.message}`)),n.listen(e,t,()=>a.info(`WebSocket server started on port ${e}`)),J=n}async function tr(){H&&clearInterval(H),H=null,We(new Error("Client manager shutting down"));for(let t of[...k.keys()])Be(t,!1);N.clear();for(let[,t]of u){try{t.ws.close(1001,"Server shutting down")}catch{}Ge(t.device,ze)}u.clear();let e=g;g=null,e&&e.close(),J?.close(),J=null,await x?.onStop(),V=null,e&&a.info("WebSocket server stopped")}function nr(){let e=[];for(let[,t]of u)e.push({device:t.device,platform:t.platform,connectedAt:t.connectedAt,lastHeartbeat:t.lastHeartbeat,capabilities:t.capabilities,bundleHash:t.bundleHash});return e}function rr(e){return u.has(e)}function or(e){if(u.has(e))return Promise.resolve(!0);if(!g||!Object.hasOwn(W(),e))return Promise.resolve(!1);let t=(N.get(e)??Ue)+Ae()-Date.now();return t<=0?Promise.resolve(!1):new Promise(n=>{let r=k.get(e)??new Set;k.set(e,r);let o=s=>{clearTimeout(i),r.delete(o),r.size===0&&k.get(e)===r&&k.delete(e),n(s)},i=setTimeout(()=>o(!1),t);r.add(o)})}function ir(){return V}function sr(e,t){Je(e).send(JSON.stringify(t))}function cr(e,t){let n;try{n=Je(e)}catch(i){return Promise.reject(i)}let r=Fe.randomBytes(8).toString("hex"),o=t.timeout||(t.action==="bash"?Mt:xt);return new Promise((i,s)=>{He(r,e,o,i,s);try{let c={type:"command",commandId:r,action:t.action,params:t.params};n.send(JSON.stringify(c))}catch(c){A(r),s(new Error(`Failed to send command to "${e}": ${c.message}`))}})}import*as l from"node:fs";import*as p from"node:path";var v=f("project-store"),Jt=1e3;function qe(e,t,n){return[`# ${e} Status`,"","Updated: \u2014","","## Current Situation",t,"","## In Flight & New Variables","none","","## Blockers & Pending Decisions","none","","## Next Step",n,""].join(`
8
+ `)}var qt=qe("general","Synthetic umbrella project \u2014 collects work not scoped to a specific project.","none"),Vt=`# general
9
+
10
+ Synthetic umbrella project \u2014 always present. Created automatically by the system.
11
+ `,Xt=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,Z=class{projectsDir;watchEnabled;projects=[];initialized=!1;watchMonitor=null;debounceTimer=null;constructor(t={}){this.projectsDir=t.projectsDir??Q,this.watchEnabled=t.watchEnabled??!0}async initialize(){this.initialized||(this.scaffoldGeneral(),this.scan(),this.initialized=!0,this.watchEnabled&&this.startWatcher(),v.info(`ProjectStore initialized: ${this.projects.length} projects (${this.projectsDir})`))}list(){return[...this.projects]}get(t){return this.projects.find(n=>n.id===t)}exists(t){return this.projects.some(n=>n.id===t)}getDefault(){return this.projects.find(t=>t.kind==="general")}resolveFromMessage(t){if(!t)return this.getDefault();let n=t.match(/\[project:([^\]]+)\]/);if(n)return this.get(n[1])??this.getDefault();let r=t.toLowerCase(),o=null,i=0;for(let s of this.projects){if(s.kind==="general")continue;let c=s.id.toLowerCase();r.includes(c)&&s.id.length>i&&(o=s,i=s.id.length)}return o??this.getDefault()}refresh(){this.scan()}createProject(t){let n=typeof t=="string"?t.trim():"";if(!n||n==="general"||!Xt.test(n)||p.basename(n)!==n)return{ok:!1,code:"invalid-name",message:`Invalid project name: ${JSON.stringify(t)}`};let r=p.join(this.projectsDir,n);if(this.exists(n)||l.existsSync(r))return{ok:!1,code:"already-exists",message:`Project already exists: ${n}`};this.scaffoldProject(r,qe(n,"New project \u2014 not yet oriented.","Define mission.md and roadmap.md."),`# ${n}
12
+
13
+ ${n} project.
14
+ `),v.info(`Created project at ${r}`),this.scan();let o=this.get(n);return o?{ok:!0,project:o}:{ok:!1,code:"invalid-name",message:`Project not registered after creation: ${n}`}}async removeProject(t){let n=this.get(t);return!n||n.kind!=="user"||!n.contextDir?!1:((await l.promises.lstat(n.contextDir).catch(()=>null))?.isDirectory()&&await l.promises.rm(n.contextDir,{recursive:!0,force:!0}),v.info(`Deleted project at ${n.contextDir}`),this.scan(),!0)}destroy(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.watchMonitor?.close(),this.watchMonitor=null,this.initialized=!1}scaffoldGeneral(){let t=p.join(this.projectsDir,"general");l.existsSync(t)||(this.scaffoldProject(t,qt,Vt),v.info(`Scaffolded general project at ${t}`))}scaffoldProject(t,n,r){l.mkdirSync(t,{recursive:!0}),l.writeFileSync(p.join(t,"STATUS.md"),n,"utf8"),l.writeFileSync(p.join(t,"AGENTS.md"),r,"utf8")}scan(){let t=[];t.push(this.makeGeneralProject());for(let n of this.readProjectDirNames()??[])n!=="general"&&t.push({id:n,name:n,kind:"user",contextDir:p.join(this.projectsDir,n)});this.projects=t}readProjectDirNames(){try{return l.readdirSync(this.projectsDir,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).map(t=>t.name)}catch{return null}}makeGeneralProject(){return{id:"general",name:"general",kind:"general",contextDir:p.join(this.projectsDir,"general")}}startWatcher(){this.watchMonitor=ee({label:"projects directory",snapshot:()=>this.readProjectDirNames()?.sort().join(`
15
+ `)??null,startWatching:t=>[l.watch(this.projectsDir,t)],onChange:()=>this.debouncedRescan(),warn:t=>v.error(t)})}debouncedRescan(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.scan(),v.debug("Rescanned projects after directory change")},Jt)}},dr=new Z;export{Ve as a,Qt as b,en as c,tn as d,nn as e,fn as f,dn as g,be as h,W as i,pn as j,mn as k,hn as l,Ln as m,Fn as n,bn as o,F as p,Dn as q,_ as r,mt as s,xn as t,Tn as u,Rn as v,On as w,An as x,Hn as y,Nn as z,Pn as A,Kn as B,Qn as C,Gt as D,er as E,tr as F,nr as G,rr as H,or as I,ir as J,sr as K,cr as L,dr as M};