@cortex-agent/server 2026.11.17 → 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 (338) hide show
  1. package/README.md +5 -5
  2. package/THIRD_PARTY_NOTICES.txt +860 -294
  3. package/defaults/hooks/quota-stop.mjs +37 -0
  4. package/defaults/prompts/clean-workspace.md +5 -0
  5. package/dist/agent-adapter/claude/remote-mcp-proxy.js +1 -1
  6. package/dist/chunks/agent-runner-LVZVKBZX.js +4 -0
  7. package/dist/chunks/anthropic-messages-TT6454AA.js +8 -0
  8. package/dist/chunks/azure-openai-responses-52LR2XZD.js +4 -0
  9. package/dist/chunks/bedrock-converse-stream-EOZGYUNY.js +60 -0
  10. package/dist/chunks/child-runner-SMG2VOU5.js +4 -0
  11. package/dist/chunks/chunk-24DH4IR5.js +4 -0
  12. package/dist/chunks/chunk-25XKBRDT.js +70 -0
  13. package/dist/chunks/{chunk-VTL3Z2OP.js → chunk-2ABET62E.js} +1 -1
  14. package/dist/chunks/chunk-2BVUA256.js +4 -0
  15. package/dist/chunks/{chunk-4YLAGSDM.js → chunk-2WFL62UO.js} +1 -1
  16. package/dist/chunks/{chunk-LQTFDC67.js → chunk-335SSANX.js} +1 -1
  17. package/dist/chunks/chunk-377OPTXX.js +17 -0
  18. package/dist/chunks/chunk-3EZNVLBF.js +129 -0
  19. package/dist/chunks/{chunk-V6X7Y62J.js → chunk-3O6ZG5HA.js} +1 -1
  20. package/dist/chunks/{chunk-6AKUD3CF.js → chunk-3XLHL5YT.js} +1 -1
  21. package/dist/chunks/{chunk-2ATTYCRJ.js → chunk-4HRI75GU.js} +1 -1
  22. package/dist/chunks/chunk-4JBYLRPM.js +57 -0
  23. package/dist/chunks/chunk-4KKV7VKE.js +4 -0
  24. package/dist/chunks/chunk-4KQHDDC5.js +4 -0
  25. package/dist/chunks/chunk-4SWD4JMP.js +33 -0
  26. package/dist/chunks/chunk-52VCLZS5.js +4 -0
  27. package/dist/chunks/chunk-54P7TSY3.js +10 -0
  28. package/dist/chunks/chunk-5DVSAXOI.js +7 -0
  29. package/dist/chunks/chunk-5F3A62YS.js +4 -0
  30. package/dist/chunks/{chunk-S3MR37DL.js → chunk-5FHETFZM.js} +1 -1
  31. package/dist/chunks/{chunk-CEGSDGYQ.js → chunk-5LBLRAHS.js} +1 -1
  32. package/dist/chunks/chunk-5UYVNA3W.js +4 -0
  33. package/dist/chunks/chunk-6G3OYMCV.js +21 -0
  34. package/dist/chunks/chunk-7GGPYU5E.js +30 -0
  35. package/dist/chunks/chunk-7TYSMLUV.js +4 -0
  36. package/dist/chunks/chunk-7W7VYUTK.js +5 -0
  37. package/dist/chunks/chunk-AXYAZTTN.js +6 -0
  38. package/dist/chunks/chunk-B3NB243Z.js +4 -0
  39. package/dist/chunks/{chunk-XPPZ6Y3X.js → chunk-BKYP6AGM.js} +1 -1
  40. package/dist/chunks/{chunk-QUXPMNFQ.js → chunk-BVEDNESB.js} +1 -1
  41. package/dist/chunks/chunk-BWDJS6A4.js +12 -0
  42. package/dist/chunks/chunk-C6YVF7EI.js +4 -0
  43. package/dist/chunks/chunk-CEJIYYVE.js +15 -0
  44. package/dist/chunks/{chunk-5PAW3DEU.js → chunk-CI2RHH74.js} +4 -4
  45. package/dist/chunks/{chunk-OFEPDNRB.js → chunk-CMSOOLJB.js} +1 -1
  46. package/dist/chunks/chunk-CSVTYYLP.js +4 -0
  47. package/dist/chunks/chunk-DE5EGVKG.js +6 -0
  48. package/dist/chunks/{chunk-E6BYRULL.js → chunk-DK3RPZOQ.js} +1 -1
  49. package/dist/chunks/{chunk-ROVKOIHF.js → chunk-DK4UCK7L.js} +1 -1
  50. package/dist/chunks/chunk-DYLBVUAU.js +4 -0
  51. package/dist/chunks/{chunk-WBSE3EF3.js → chunk-FDC2GRBK.js} +1 -1
  52. package/dist/chunks/chunk-FE7HH5JS.js +18 -0
  53. package/dist/chunks/chunk-FYD57YRO.js +436 -0
  54. package/dist/chunks/chunk-G264APQN.js +5 -0
  55. package/dist/chunks/chunk-G4JYZFEO.js +11 -0
  56. package/dist/chunks/chunk-GFFM56U2.js +4 -0
  57. package/dist/chunks/chunk-GOS3P7KS.js +132 -0
  58. package/dist/chunks/{chunk-2VVRTJQN.js → chunk-HVN37UXD.js} +1 -1
  59. package/dist/chunks/{chunk-53TQNK7Z.js → chunk-IGZWZP7Z.js} +1 -1
  60. package/dist/chunks/{chunk-AFTBQRPN.js → chunk-IJ7XFQMI.js} +1 -1
  61. package/dist/chunks/{chunk-U23S37TT.js → chunk-IMMGYDAB.js} +1 -1
  62. package/dist/chunks/chunk-IOWBF7UK.js +10 -0
  63. package/dist/chunks/{chunk-MGYYSX7Y.js → chunk-ITGCWQFK.js} +1 -1
  64. package/dist/chunks/{chunk-QEL6CMLE.js → chunk-IVZ7QUEG.js} +1 -1
  65. package/dist/chunks/{chunk-EE3WT25T.js → chunk-IWY2HIFK.js} +1 -1
  66. package/dist/chunks/{chunk-KGJZAYQD.js → chunk-J7OBATRN.js} +1 -1
  67. package/dist/chunks/{chunk-NXZS5PEW.js → chunk-JGUEIW2W.js} +1 -1
  68. package/dist/chunks/chunk-JZ7U7RUK.js +351 -0
  69. package/dist/chunks/{chunk-VIMHSW6J.js → chunk-KJUQCCB5.js} +1 -1
  70. package/dist/chunks/{chunk-BUZQBTV2.js → chunk-KST6OY76.js} +1 -1
  71. package/dist/chunks/{chunk-KDPY2YA3.js → chunk-KZSAFVSY.js} +2 -2
  72. package/dist/chunks/chunk-LD2ZSH3M.js +903 -0
  73. package/dist/chunks/{chunk-RYLSRII6.js → chunk-LE6QPXN6.js} +1 -1
  74. package/dist/chunks/{chunk-TX46YMGI.js → chunk-LIIZI3HY.js} +1 -1
  75. package/dist/chunks/{chunk-3CZPBLB3.js → chunk-MJQ2D2OP.js} +1 -1
  76. package/dist/chunks/{chunk-P7TVR4GY.js → chunk-NHHR4DCF.js} +1 -1
  77. package/dist/chunks/chunk-NW4GW47L.js +4 -0
  78. package/dist/chunks/chunk-OALEJ6FG.js +60 -0
  79. package/dist/chunks/chunk-OIV4DIMB.js +4 -0
  80. package/dist/chunks/{chunk-T73GHMFB.js → chunk-OJ37ZWBG.js} +1 -1
  81. package/dist/chunks/{chunk-7GEBDPTT.js → chunk-OZXMPBUX.js} +1 -1
  82. package/dist/chunks/chunk-PG7452XE.js +4 -0
  83. package/dist/chunks/chunk-PJCUB7YJ.js +4 -0
  84. package/dist/chunks/{chunk-RA2BUYI3.js → chunk-PTS3J4DQ.js} +1 -1
  85. package/dist/chunks/{chunk-2ROGTDM2.js → chunk-PVVEEBUU.js} +1 -1
  86. package/dist/chunks/{chunk-W6AKCEYF.js → chunk-Q7BZLPBU.js} +1 -1
  87. package/dist/chunks/{chunk-SY2HV3V5.js → chunk-QC66ZXPP.js} +1 -1
  88. package/dist/chunks/chunk-QXFWIL4C.js +4 -0
  89. package/dist/chunks/{chunk-NRD57ICT.js → chunk-R2CCD4OF.js} +1 -1
  90. package/dist/chunks/{chunk-R52AVUQB.js → chunk-RG5GP4RB.js} +1 -1
  91. package/dist/chunks/{chunk-IKLTEWA3.js → chunk-RW2F2QNP.js} +1 -1
  92. package/dist/chunks/{chunk-XEBEWR6Y.js → chunk-RWPO3NZ3.js} +1 -1
  93. package/dist/chunks/chunk-SDUS2H3E.js +4 -0
  94. package/dist/chunks/chunk-SIHGKM4E.js +4 -0
  95. package/dist/chunks/{chunk-NNBSSISP.js → chunk-SKHFU5DI.js} +1 -1
  96. package/dist/chunks/{chunk-STUHNKQS.js → chunk-SM45TH22.js} +1 -1
  97. package/dist/chunks/chunk-T54CZKNJ.js +6 -0
  98. package/dist/chunks/chunk-TRXLIL7V.js +4 -0
  99. package/dist/chunks/{chunk-KUDK7GPS.js → chunk-UEEW2R4E.js} +1 -1
  100. package/dist/chunks/chunk-UHXPRU6G.js +10 -0
  101. package/dist/chunks/chunk-UPQVWHZ3.js +4 -0
  102. package/dist/chunks/{chunk-BDLKI2NT.js → chunk-VHX2GHBF.js} +1 -1
  103. package/dist/chunks/chunk-VOAKRJ4R.js +4 -0
  104. package/dist/chunks/{chunk-FP7ML72L.js → chunk-WU7RNAZD.js} +1 -1
  105. package/dist/chunks/chunk-WZC4TDDM.js +6 -0
  106. package/dist/chunks/chunk-X2TKJ7KR.js +11 -0
  107. package/dist/chunks/{chunk-H4QZ2P3Z.js → chunk-X5ND4H4P.js} +1 -1
  108. package/dist/chunks/{chunk-5A6CA5TM.js → chunk-Y3AOGNDT.js} +1 -1
  109. package/dist/chunks/chunk-Y6DGVTKM.js +6 -0
  110. package/dist/chunks/{chunk-LP7T32PW.js → chunk-YAEHSSR4.js} +1 -1
  111. package/dist/chunks/chunk-YWPBE5LP.js +4 -0
  112. package/dist/chunks/chunk-ZAVX7G2M.js +15 -0
  113. package/dist/chunks/chunk-ZD2M73XA.js +19 -0
  114. package/dist/chunks/chunk-ZD4O6NPV.js +4 -0
  115. package/dist/chunks/chunk-ZNAMETPQ.js +4 -0
  116. package/dist/chunks/chunk-ZY6N5LVQ.js +4 -0
  117. package/dist/chunks/chunk-ZYQ4TDTT.js +81 -0
  118. package/dist/chunks/cli-VB2N7HEK.js +55 -0
  119. package/dist/chunks/cloudflare-workers-ai-system-one-YKU742EC.js +4 -0
  120. package/dist/chunks/context-CI2FKEQE.js +4 -0
  121. package/dist/chunks/cost-CZRRSIUF.js +5 -0
  122. package/dist/chunks/dist-QCNQN6DY.js +4 -0
  123. package/dist/chunks/{easter-egg-3d-CZH7AYZ7.js → easter-egg-3d-XR5S2O3T.js} +1 -1
  124. package/dist/chunks/execution-repo-5TLV2NM4.js +4 -0
  125. package/dist/chunks/{executions-BN6OLLVM.js → executions-I3UUIGSL.js} +1 -1
  126. package/dist/chunks/file-Y5G56IUT.js +4 -0
  127. package/dist/chunks/github-copilot-BRU2SRRZ.js +4 -0
  128. package/dist/chunks/google-generative-ai-ZF5QEUZV.js +4 -0
  129. package/dist/chunks/google-vertex-4PJZZI3Y.js +4 -0
  130. package/dist/chunks/init-A6GY656J.js +4 -0
  131. package/dist/chunks/{install-cli-ABBD7DO5.js → install-cli-FALWKQYO.js} +1 -1
  132. package/dist/chunks/{interaction-ask-EE2UPR3Q.js → interaction-ask-O5HGF6CH.js} +1 -1
  133. package/dist/chunks/{interaction-plan-C446T2GZ.js → interaction-plan-JTVDN3BC.js} +1 -1
  134. package/dist/chunks/kimi-coding-ZCIBMDZ6.js +4 -0
  135. package/dist/chunks/{llama-cpp-classify-IA2F2H7A.js → llama-cpp-classify-NRUXAIGQ.js} +3 -3
  136. package/dist/chunks/local-client-stop-RS4AHNF4.js +4 -0
  137. package/dist/chunks/memory-cli-DIT4DQF3.js +11 -0
  138. package/dist/chunks/meta-JQH66YU7.js +4 -0
  139. package/dist/chunks/mistral-conversations-CXHOECUV.js +7 -0
  140. package/dist/chunks/model-resolver-GIBPYRKP.js +4 -0
  141. package/dist/chunks/monitor-Z2HKNY5E.js +4 -0
  142. package/dist/chunks/openai-codex-responses-U6DGMGDK.js +12 -0
  143. package/dist/chunks/openai-completions-PP4XLLOM.js +9 -0
  144. package/dist/chunks/{openai-decisions-P5UX7BWY.js → openai-decisions-JU6QQKEM.js} +1 -1
  145. package/dist/chunks/openai-responses-2SG757TL.js +6 -0
  146. package/dist/chunks/openrouter-images-32M7YZWC.js +4 -0
  147. package/dist/chunks/pi-messages-VSINMXN4.js +10 -0
  148. package/dist/chunks/radius-THYKWV4E.js +4 -0
  149. package/dist/chunks/remote-ops-2WBEFQ3E.js +14 -0
  150. package/dist/chunks/runner-5MKMRTIN.js +4 -0
  151. package/dist/chunks/runtime-DST3H5JP.js +4 -0
  152. package/dist/chunks/schedule-cli-V7Y2BBVY.js +4 -0
  153. package/dist/chunks/slack-R7SEJYMY.js +4 -0
  154. package/dist/chunks/start-ui-http-7K5JOLPU.js +43 -0
  155. package/dist/chunks/subagent-Z5IQ4L54.js +4 -0
  156. package/dist/chunks/tool-shims-YCXZWTST.js +4 -0
  157. package/dist/chunks/typesafe-system-one-M2DABJSZ.js +4 -0
  158. package/dist/chunks/ui-board-HQIE4RZG.js +5 -0
  159. package/dist/chunks/ui-decision-YBZDS4YW.js +4 -0
  160. package/dist/chunks/{ui-file-6PLXHSTB.js → ui-file-SRD4ILBS.js} +1 -1
  161. package/dist/chunks/ui-view-Z25MTZT7.js +4 -0
  162. package/dist/chunks/virtual-modules-H4DXPJZB.js +4 -0
  163. package/dist/chunks/{waitpoint-W5M3BE55.js → waitpoint-M6JZBSLT.js} +1 -1
  164. package/dist/chunks/workers-SQ2R32TK.js +4 -0
  165. package/dist/client-bundle/client.mjs +229 -62
  166. package/dist/client-bundle/manifest.json +2 -2
  167. package/dist/core/pi-sdk.js +1 -1
  168. package/dist/domain/auth/cc-auth-cli.js +1 -1
  169. package/dist/domain/mcp/bundled-server.js +1 -1
  170. package/dist/domain/mcp/feishu/client.js +1 -1
  171. package/dist/entry/app.js +138 -556
  172. package/dist/entry/browser-cli.js +1 -1
  173. package/dist/entry/cli.js +1 -1
  174. package/dist/entry/cortex-cli.js +1 -1
  175. package/dist/entry/daemon.js +3 -3
  176. package/dist/entry/hook-cli.js +1 -1
  177. package/dist/entry/production-app-bootstrap.js +1 -1
  178. package/dist/entry/production-evidence-export-cli.js +1 -1
  179. package/dist/entry/signal-cli.js +1 -1
  180. package/dist/tui/index.js +1 -1
  181. package/package.json +1 -1
  182. package/vendor/pi/CHANGELOG.md +330 -0
  183. package/vendor/pi/dist/codemode-worker.js +2 -0
  184. package/vendor/pi/dist/core/export-html/ansi-to-html.js +57 -20
  185. package/vendor/pi/dist/core/export-html/template.css +9 -0
  186. package/vendor/pi/dist/core/export-html/template.js +166 -46
  187. package/vendor/pi/dist/core/export-html/tool-renderer.js +5 -3
  188. package/vendor/pi/dist/core/extensions/loader.js +1 -1
  189. package/vendor/pi/dist/extensions/codemode/execute.js +15 -13
  190. package/vendor/pi/dist/modes/interactive/theme/theme.js +36 -23
  191. package/vendor/pi/dist/utils/image-resize-worker.js +1 -1
  192. package/vendor/pi/dist/utils/image-resize.js +1 -1
  193. package/vendor/pi/docs/cli.md +35 -12
  194. package/vendor/pi/docs/custom-provider.md +2 -0
  195. package/vendor/pi/docs/environment-variables.md +2 -0
  196. package/vendor/pi/docs/extensions.md +3192 -225
  197. package/vendor/pi/docs/keybindings.md +2 -2
  198. package/vendor/pi/docs/llama-cpp.md +27 -19
  199. package/vendor/pi/docs/mcp.md +6 -4
  200. package/vendor/pi/docs/message-types.md +1 -1
  201. package/vendor/pi/docs/models-configuration.md +9 -3
  202. package/vendor/pi/docs/models.md +2 -1
  203. package/vendor/pi/docs/nvidia-rtx-llama-cpp.md +5 -5
  204. package/vendor/pi/docs/packages.md +24 -0
  205. package/vendor/pi/docs/prompt-templates.md +1 -1
  206. package/vendor/pi/docs/providers.md +4 -2
  207. package/vendor/pi/docs/quickstart.md +7 -3
  208. package/vendor/pi/docs/rpc-commands.md +1 -1
  209. package/vendor/pi/docs/rpc.md +4 -2
  210. package/vendor/pi/docs/sessions.md +17 -3
  211. package/vendor/pi/docs/settings.md +6 -5
  212. package/vendor/pi/docs/slash-commands.md +3 -2
  213. package/vendor/pi/docs/terminal-setup.md +3 -1
  214. package/vendor/pi/docs/tmux.md +6 -0
  215. package/vendor/pi/docs/tui.md +4 -0
  216. package/vendor/pi/docs/windows.md +27 -0
  217. package/vendor/pi/examples/extensions/README.md +2 -1
  218. package/vendor/pi/examples/extensions/custom-provider-anthropic/index.ts +27 -31
  219. package/vendor/pi/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  220. package/vendor/pi/examples/extensions/custom-provider-anthropic/package.json +1 -1
  221. package/vendor/pi/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  222. package/vendor/pi/examples/extensions/debug-provider.ts +2 -2
  223. package/vendor/pi/examples/extensions/gondolin/index.ts +4 -7
  224. package/vendor/pi/examples/extensions/gondolin/package-lock.json +19 -29
  225. package/vendor/pi/examples/extensions/gondolin/package.json +2 -2
  226. package/vendor/pi/examples/extensions/plan-mode/index.ts +23 -13
  227. package/vendor/pi/examples/extensions/plan-mode/utils.ts +42 -16
  228. package/vendor/pi/examples/extensions/preset.ts +2 -0
  229. package/vendor/pi/examples/extensions/reload-runtime.ts +17 -5
  230. package/vendor/pi/examples/extensions/subagent/README.md +14 -11
  231. package/vendor/pi/examples/extensions/subagent/index.ts +392 -171
  232. package/vendor/pi/examples/extensions/todo.ts +7 -0
  233. package/vendor/pi/examples/extensions/tools.ts +2 -0
  234. package/vendor/pi/examples/extensions/with-deps/package-lock.json +2 -2
  235. package/vendor/pi/examples/extensions/with-deps/package.json +1 -1
  236. package/vendor/pi/examples/tsconfig.json +208 -0
  237. package/vendor/pi/package.json +15 -16
  238. package/vendor/pi/schemas/models.schema.json +66 -37
  239. package/vendor/pi/schemas/settings.schema.json +18 -1
  240. package/vendor/pi-ai/bedrock.js +1 -1
  241. package/vendor/pi-ai/oauth-load.js +1 -1
  242. package/web/dist/assets/{board-math-css-BgIyUG-C.js → board-math-css-DKX6FcUS.js} +1 -1
  243. package/web/dist/assets/index-D11wi0uG.js +540 -0
  244. package/web/dist/assets/index-JedYumhY.css +1 -0
  245. package/web/dist/assets/{index-C2eMpcuI.js → index-jl30Gy8P.js} +1 -1
  246. package/web/dist/index.html +2 -2
  247. package/dist/chunks/anthropic-messages-M732OMEE.js +0 -8
  248. package/dist/chunks/azure-openai-responses-RAKTV6JY.js +0 -4
  249. package/dist/chunks/bedrock-converse-stream-WNUGNZ27.js +0 -62
  250. package/dist/chunks/child-runner-MO5RT6FH.js +0 -4
  251. package/dist/chunks/chunk-3CPIMAYX.js +0 -30
  252. package/dist/chunks/chunk-3ORG56I5.js +0 -8
  253. package/dist/chunks/chunk-4EX2JJWB.js +0 -4
  254. package/dist/chunks/chunk-5DF5WJNM.js +0 -60
  255. package/dist/chunks/chunk-7GAYFN52.js +0 -18
  256. package/dist/chunks/chunk-AVXDF7AG.js +0 -4
  257. package/dist/chunks/chunk-BJGYGEZO.js +0 -6
  258. package/dist/chunks/chunk-BZDIAI5M.js +0 -125
  259. package/dist/chunks/chunk-CK3P345X.js +0 -133
  260. package/dist/chunks/chunk-CVC66CFV.js +0 -33
  261. package/dist/chunks/chunk-ETIBCA2S.js +0 -4
  262. package/dist/chunks/chunk-FF7UELTU.js +0 -4
  263. package/dist/chunks/chunk-FX6MOGLR.js +0 -11
  264. package/dist/chunks/chunk-G2V65UBA.js +0 -4
  265. package/dist/chunks/chunk-HGPBHTVD.js +0 -6
  266. package/dist/chunks/chunk-IYVZHGUQ.js +0 -5
  267. package/dist/chunks/chunk-JJDEQ6N2.js +0 -4
  268. package/dist/chunks/chunk-KDYEGGMW.js +0 -4
  269. package/dist/chunks/chunk-L6VCIGWS.js +0 -11
  270. package/dist/chunks/chunk-LACGULCN.js +0 -10
  271. package/dist/chunks/chunk-LAWOWPZX.js +0 -363
  272. package/dist/chunks/chunk-NNTQUHLO.js +0 -877
  273. package/dist/chunks/chunk-OE4KH3NJ.js +0 -4
  274. package/dist/chunks/chunk-OSEIQ7SS.js +0 -4
  275. package/dist/chunks/chunk-PZMGBKUR.js +0 -13
  276. package/dist/chunks/chunk-QBKCAIJG.js +0 -4
  277. package/dist/chunks/chunk-QMSSIDRQ.js +0 -70
  278. package/dist/chunks/chunk-QUUEQRIT.js +0 -4
  279. package/dist/chunks/chunk-RA6HKFBV.js +0 -4
  280. package/dist/chunks/chunk-RDW6FRF5.js +0 -4
  281. package/dist/chunks/chunk-RF4JLYBX.js +0 -6
  282. package/dist/chunks/chunk-SFX7V5O2.js +0 -10
  283. package/dist/chunks/chunk-SKHLZ6XY.js +0 -9
  284. package/dist/chunks/chunk-STCNHXPJ.js +0 -6
  285. package/dist/chunks/chunk-UT6DGZDO.js +0 -4
  286. package/dist/chunks/chunk-VBN2JSER.js +0 -5
  287. package/dist/chunks/chunk-VK5J556O.js +0 -4
  288. package/dist/chunks/chunk-VPVSKJGX.js +0 -6
  289. package/dist/chunks/chunk-VQUPKMDR.js +0 -4
  290. package/dist/chunks/chunk-WEZWKMYU.js +0 -4
  291. package/dist/chunks/chunk-XYSXL3KX.js +0 -4
  292. package/dist/chunks/chunk-Y3GFB5XM.js +0 -8
  293. package/dist/chunks/chunk-YAAKL3QS.js +0 -80
  294. package/dist/chunks/chunk-YB5LUJHS.js +0 -65
  295. package/dist/chunks/chunk-YKKEI5GI.js +0 -4
  296. package/dist/chunks/chunk-Z24SBRJK.js +0 -4
  297. package/dist/chunks/cli-5DBTRMHU.js +0 -53
  298. package/dist/chunks/cloudflare-workers-ai-system-one-32JCFHI3.js +0 -4
  299. package/dist/chunks/context-GQKWKFRM.js +0 -4
  300. package/dist/chunks/cost-OOO32GLC.js +0 -5
  301. package/dist/chunks/dist-V5FRMUFH.js +0 -4
  302. package/dist/chunks/execution-repo-XXL4FXC6.js +0 -4
  303. package/dist/chunks/file-H572PL2Z.js +0 -4
  304. package/dist/chunks/github-copilot-HAI2DA62.js +0 -4
  305. package/dist/chunks/google-generative-ai-2G4ITOZL.js +0 -4
  306. package/dist/chunks/google-vertex-PACHCMRZ.js +0 -4
  307. package/dist/chunks/init-75F4V7SK.js +0 -4
  308. package/dist/chunks/kimi-coding-HMJRKCPA.js +0 -4
  309. package/dist/chunks/local-client-stop-5YOLXGYT.js +0 -4
  310. package/dist/chunks/memory-cli-5SSF6YJM.js +0 -11
  311. package/dist/chunks/meta-KY3LNFV2.js +0 -4
  312. package/dist/chunks/mistral-conversations-VHP63CDS.js +0 -7
  313. package/dist/chunks/model-resolver-FVJNZ6NA.js +0 -4
  314. package/dist/chunks/openai-codex-responses-EHJ4AZBE.js +0 -12
  315. package/dist/chunks/openai-completions-CRAGQFCE.js +0 -9
  316. package/dist/chunks/openai-responses-IZ22NVQ7.js +0 -6
  317. package/dist/chunks/openrouter-images-W2JAMSRH.js +0 -4
  318. package/dist/chunks/pi-messages-MJEEQU2R.js +0 -10
  319. package/dist/chunks/radius-ZM7ZRMXF.js +0 -4
  320. package/dist/chunks/remote-ops-O5CR4RGA.js +0 -14
  321. package/dist/chunks/runner-S6R3US24.js +0 -4
  322. package/dist/chunks/runtime-6YLTA2ZD.js +0 -4
  323. package/dist/chunks/schedule-cli-4T4YC5V5.js +0 -4
  324. package/dist/chunks/slack-2CGM4SMY.js +0 -4
  325. package/dist/chunks/start-ui-http-3D7QNHGB.js +0 -43
  326. package/dist/chunks/subagent-OZGUOV3J.js +0 -4
  327. package/dist/chunks/tool-shims-IA2WELXJ.js +0 -4
  328. package/dist/chunks/typesafe-system-one-6ULACYD4.js +0 -4
  329. package/dist/chunks/ui-board-H4INJD6C.js +0 -5
  330. package/dist/chunks/ui-decision-6HHNROIT.js +0 -4
  331. package/dist/chunks/ui-view-6MDU4GXY.js +0 -4
  332. package/dist/chunks/virtual-modules-OFI7QKYH.js +0 -4
  333. package/dist/chunks/workers-GTFP75MS.js +0 -4
  334. package/vendor/pi/examples/extensions/sandbox/index.ts +0 -321
  335. package/vendor/pi/examples/extensions/sandbox/package-lock.json +0 -92
  336. package/vendor/pi/examples/extensions/sandbox/package.json +0 -19
  337. package/web/dist/assets/index-9lyu2S6W.css +0 -1
  338. package/web/dist/assets/index-C-hpzey7.js +0 -532
@@ -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{q as c}from"./chunk-Z24SBRJK.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};