@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
@@ -2,14 +2,14 @@
2
2
  import { createRequire as __cortexCreateRequire } from 'node:module';
3
3
  const require = __cortexCreateRequire(import.meta.url);
4
4
  const __cortexPackageRoot = new URL("../../", import.meta.url);
5
- import{a as O,b as C,d as u,e as y,f as S,g as _,h as T}from"../chunks/chunk-ZFPMIQA3.js";import{a as x}from"../chunks/chunk-SUFW24P4.js";import{a as A,b as l}from"../chunks/chunk-PMG4YGDU.js";import"../chunks/chunk-NAA7GF6Q.js";import{b as E}from"../chunks/chunk-QWAQHHRS.js";import"../chunks/chunk-J5DVLUKY.js";import"../chunks/chunk-WHC7AYZD.js";import*as m from"node:path";import{spawn as W}from"node:child_process";var B={name:"cortex-browser",description:["Drive a real browser from any Cortex session: agent-browser, attached to the session's own tab","in the Chrome Cortex manages on the server or on one of your devices.","","Every argument except --device is passed to agent-browser. Full command guide:"," cortex-browser skills get core"].join(`
6
- `),usage:"cortex-browser [--device <name>] <agent-browser command> [args...]",options:[{flag:"--device <name>",description:"Whose Chrome: 'server' or a connected device. Sticks for the session",default:"the session's last device, else server"},{flag:"--help, -h",description:"Show this help (agent-browser <command> --help for one command)"}],examples:[{description:"Open a page and list what can be clicked",command:"cortex-browser open http://127.0.0.1:5173 && cortex-browser snapshot -i"},{description:"Click a ref from the snapshot, then capture the result",command:"cortex-browser click @e2 && cortex-browser screenshot ./after-click.png"},{description:"Use the Chrome on the user's machine (its localhost, its logins)",command:"cortex-browser --device my-pc open https://example.com"},{description:"Read the version-matched command reference",command:"cortex-browser skills get core --full"}]},L=new Set(["--cdp","--session","--no-pin-tab","--auto-connect","--provider","-p","--namespace","--engine","--executable-path"]),I=new Set(["skills","help"]),$={connect:"cortex-browser already connects each call to the session browser",install:"Chrome is managed by Cortex; agent-browser does not install its own",upgrade:"agent-browser is pinned to the version Cortex ships with",dashboard:"watch the browser in the Cortex app's Agent browser tab instead",mcp:"call cortex-browser commands directly"},N=new Set(["--session","--namespace","--executable-path","--extension","--init-script","--enable","--args","--user-agent","--proxy","--proxy-bypass","--ca-cert","--hide-scrollbars","--provider","-p","--screenshot-dir","--screenshot-quality","--screenshot-format","--input-mode","--cdp","--color-scheme","--download-path","--max-output","--allowed-domains","--action-policy","--confirm-actions","--idle-timeout","--engine","--model","--config","--profile","--restore-save","--restore-check-url","--restore-check-text","--restore-check-fn","--session-name","--state","--headers","--threshold","--baseline","-d","--depth","-s","--selector"]),M=new Set(["--screenshot-dir","--download-path","--baseline"]),k={screenshot:0,pdf:0,download:1,upload:1,record:0,trace:0,profiler:0,network:0,har:0,state:0,diff:0},P=/\.(png|jpe?g|webp|gif|pdf|webm|mp4|json|har|zip|txt|html?|csv|xml|md|log|cpuprofile)$/i,d=class extends Error{};function R(e){for(let r=0;r<e.length;r+=1){let t=e[r];if(t.startsWith("-")){N.has(t)&&(r+=1);continue}return{command:t,index:r}}return{command:null,index:-1}}function H(e){let r=null,t=[];for(let i=0;i<e.length;i+=1){let o=e[i];if(o==="--device"||o.startsWith("--device=")){let s=o==="--device"?e[i+1]:o.slice(9);if(!s||s.startsWith("-"))throw new d(l("--device requires a device name",{hint:"use 'server' for this machine, or a connected device name (cortex-browser --device my-pc open \u2026)"}));r=s,o==="--device"&&(i+=1);continue}let a=o.split("=")[0];if(L.has(a))throw new d(l(`${a} is set by cortex-browser and cannot be passed`,{hint:"cortex-browser attaches every call to this session's own tab; use --device to pick whose Chrome"}));o!=="--pin-tab"&&t.push(o)}let{command:n}=R(t),c=n===null&&!t.some(i=>i==="--version"||i==="-V");if(n&&Object.hasOwn($,n))throw new d(l(`'${n}' is not available through cortex-browser`,{hint:$[n]}));if(n==="close"&&t.includes("--all"))throw new d(l("'close --all' would disconnect every other session's browser",{hint:"use 'cortex-browser close' to close only this session's connection"}));return{help:c,device:r,args:t,command:n}}function D(e){return e.command&&I.has(e.command)||e.args.some(r=>r==="--help"||r==="-h")?!0:e.command===null&&e.args.some(r=>r==="--version"||r==="-V")}function j(e){return!e||e.startsWith("-")||e.startsWith("@")||e.includes("://")||/[*?{}[\]]/.test(e)||m.isAbsolute(e)?!1:e.startsWith("./")||e.startsWith("../")||P.test(e)}function K(e,r){let t=[...e];for(let o=0;o<t.length-1;o+=1)M.has(t[o])&&!m.isAbsolute(t[o+1])&&!t[o+1].startsWith("-")&&(t[o+1]=m.resolve(r,t[o+1]));let{command:n,index:c}=R(t);if(!n||!Object.hasOwn(k,n))return t;let i=k[n];for(let o=c+1;o<t.length;o+=1){let a=t[o];if(a.startsWith("-")){N.has(a)&&(o+=1);continue}if(i>0){i-=1;continue}j(a)&&(t[o]=m.resolve(r,a))}return t}async function X(e,r,t){let n=await fetch(e,{method:"POST",headers:{"content-type":"application/json",...t},body:JSON.stringify(r),signal:AbortSignal.timeout(18e4)}),c=await n.text(),i=c;try{i=JSON.parse(c)}catch{}return{status:n.status,body:i}}function F(e,r,t,n,c=!1){return new Promise(i=>{let o="",a=W(e,r,{env:t,cwd:n,stdio:[c?"ignore":"inherit",c?"ignore":"inherit","pipe"]});a.stderr?.on("data",s=>{o+=String(s)}),a.on("error",s=>i({code:127,stderr:`${o}cortex-browser: cannot run ${e}: ${s.message}
7
- `})),a.on("close",(s,h)=>i({code:s??(h?128:1),stderr:o}))})}var p=class extends Error{exitCode;constructor(r,t=1){super(r),this.exitCode=t}};async function G(e,r,t,n){let c=r.WEBHOOK_PORT||"3001",i=`http://127.0.0.1:${c}/webhook/browser`,o=setTimeout(()=>{e.writeErr(`cortex-browser: starting the browser${n?` on ${n}`:""}\u2026
8
- `)},e.slowNoticeMs),a;try{a=await e.post(i,{action:"lease",sessionId:t,device:n},{[x]:r.CORTEX_WEBHOOK_TOKEN||""})}catch(h){throw new p(l(`cannot reach the Cortex daemon at 127.0.0.1:${c}: ${h.message}`,{hint:"cortex-browser works inside Cortex sessions while the Cortex server is running"}))}finally{clearTimeout(o)}if(a.status===401)throw new p(l("the Cortex daemon rejected this call (bad or missing CORTEX_WEBHOOK_TOKEN)",{hint:"run cortex-browser from a Cortex session, which sets the token"}));if(a.status===404)throw new p(l("this Cortex server has no browser endpoint yet",{hint:"the server needs a restart onto the version that ships cortex-browser"}));let s=a.body;if(a.status!==200||!s?.success){let h=typeof s=="object"&&s?s.error:String(s??"");throw new p(l(`browser unavailable: ${h||`HTTP ${a.status}`}`,{hint:s?.hint}))}return s.data}async function V(e,r={}){let t=r.env??process.env,n=r.cwd??process.cwd(),c=r.writeErr??(s=>{process.stderr.write(s)}),i=r.exec??F,o=r.post??X,a;try{a=H(e)}catch(s){if(s instanceof d)return c(`${s.message}
9
- `),2;throw s}if(a.help)return process.stdout.write(`${A(B)}
10
- `),0;try{if(D(a)){let v=C(t),b=await i(v,a.args,_(t),n);return b.stderr&&c(b.stderr),b.code}let s=t.CORTEX_SESSION_ID||t.CORTEX_EXECUTION_ID||"";if(!s)return c(`${l("no Cortex session (CORTEX_SESSION_ID is unset)",{hint:"cortex-browser leases a browser per Cortex session; run it from a session's shell"})}
11
- `),2;let h=await G({post:o,writeErr:c,slowNoticeMs:r.slowNoticeMs??2e3},t,s,a.device),f=T(h.env,t),g=K(a.args,n),w=await i(h.bin,u(h.cdpEndpoint,h.abSession,g),f,n);return w.code!==0&&S(w.stderr)&&(await i(h.bin,u(h.cdpEndpoint,h.abSession,["tab","new"]),f,n,!0)).code===0&&(await i(h.bin,u(h.cdpEndpoint,h.abSession,y),f,n,!0),c(`cortex-browser: this session's previous tab is gone (closed after 10 idle minutes, or the browser restarted); continuing in a new blank tab
12
- `),w=await i(h.bin,u(h.cdpEndpoint,h.abSession,g),f,n)),w.stderr&&c(w.stderr),await o(`http://127.0.0.1:${t.WEBHOOK_PORT||"3001"}/webhook/browser`,{action:"report",sessionId:s},{[x]:t.CORTEX_WEBHOOK_TOKEN||""}).catch(()=>{}),w.code}catch(s){return s instanceof p?(c(`${s.message}
13
- `),s.exitCode):s instanceof O?(c(`${l(s.message,{hint:s.hint})}
5
+ import{a as C,b as y,d as u,e as S,f as O,g as _,h as A}from"../chunks/chunk-ZFPMIQA3.js";import{a as x}from"../chunks/chunk-UEEW2R4E.js";import{h as T,i as $}from"../chunks/chunk-BVEDNESB.js";import{a as k,b as h}from"../chunks/chunk-PMG4YGDU.js";import"../chunks/chunk-7W7VYUTK.js";import{b as E}from"../chunks/chunk-JGUEIW2W.js";import"../chunks/chunk-T54CZKNJ.js";import"../chunks/chunk-WHC7AYZD.js";import*as m from"node:path";import{spawn as M}from"node:child_process";var I={name:"cortex-browser",description:["Drive a real browser from any Cortex session: agent-browser, attached to the session's own tab","in the Chrome Cortex manages on the server or on one of your devices.","","Every argument except --device is passed to agent-browser. Full command guide:"," cortex-browser skills get core"].join(`
6
+ `),usage:"cortex-browser [--device <name>] <agent-browser command> [args...]",options:[{flag:"--device <name>",description:"Whose Chrome: 'server' or a connected device. Sticks for the session",default:"the session's last device, else server"},{flag:"--help, -h",description:"Show this help (agent-browser <command> --help for one command)"}],examples:[{description:"Open a page and list what can be clicked",command:"cortex-browser open http://127.0.0.1:5173 && cortex-browser snapshot -i"},{description:"Click a ref from the snapshot, then capture the result",command:"cortex-browser click @e2 && cortex-browser screenshot ./after-click.png"},{description:"Use the Chrome on the user's machine (its localhost, its logins)",command:"cortex-browser --device my-pc open https://example.com"},{description:"Read the version-matched command reference",command:"cortex-browser skills get core --full"}]},P=new Set(["--cdp","--session","--no-pin-tab","--auto-connect","--provider","-p","--namespace","--engine","--executable-path"]),B=new Set(["skills","help"]),N={connect:"cortex-browser already connects each call to the session browser",install:"Chrome is managed by Cortex; agent-browser does not install its own",upgrade:"agent-browser is pinned to the version Cortex ships with",dashboard:"watch the browser in the Cortex app's Agent browser tab instead",mcp:"call cortex-browser commands directly"},W=new Set(["--session","--namespace","--executable-path","--extension","--init-script","--enable","--args","--user-agent","--proxy","--proxy-bypass","--ca-cert","--hide-scrollbars","--provider","-p","--screenshot-dir","--screenshot-quality","--screenshot-format","--input-mode","--cdp","--color-scheme","--download-path","--max-output","--allowed-domains","--action-policy","--confirm-actions","--idle-timeout","--engine","--model","--config","--profile","--restore-save","--restore-check-url","--restore-check-text","--restore-check-fn","--session-name","--state","--headers","--threshold","--baseline","-d","--depth","-s","--selector"]),D=new Set(["--screenshot-dir","--download-path","--baseline"]),R={screenshot:0,pdf:0,download:1,upload:1,record:0,trace:0,profiler:0,network:0,har:0,state:0,diff:0},j=/\.(png|jpe?g|webp|gif|pdf|webm|mp4|json|har|zip|txt|html?|csv|xml|md|log|cpuprofile)$/i,d=class extends Error{};function L(e){for(let r=0;r<e.length;r+=1){let t=e[r];if(t.startsWith("-")){W.has(t)&&(r+=1);continue}return{command:t,index:r}}return{command:null,index:-1}}function H(e){let r=null,t=[];for(let i=0;i<e.length;i+=1){let o=e[i];if(o==="--device"||o.startsWith("--device=")){let s=o==="--device"?e[i+1]:o.slice(9);if(!s||s.startsWith("-"))throw new d(h("--device requires a device name",{hint:"use 'server' for this machine, or a connected device name (cortex-browser --device my-pc open \u2026)"}));r=s,o==="--device"&&(i+=1);continue}let a=o.split("=")[0];if(P.has(a))throw new d(h(`${a} is set by cortex-browser and cannot be passed`,{hint:"cortex-browser attaches every call to this session's own tab; use --device to pick whose Chrome"}));o!=="--pin-tab"&&t.push(o)}let{command:n}=L(t),c=n===null&&!t.some(i=>i==="--version"||i==="-V");if(n&&Object.hasOwn(N,n))throw new d(h(`'${n}' is not available through cortex-browser`,{hint:N[n]}));if(n==="close"&&t.includes("--all"))throw new d(h("'close --all' would disconnect every other session's browser",{hint:"use 'cortex-browser close' to close only this session's connection"}));return{help:c,device:r,args:t,command:n}}function X(e){return e.command&&B.has(e.command)||e.args.some(r=>r==="--help"||r==="-h")?!0:e.command===null&&e.args.some(r=>r==="--version"||r==="-V")}function K(e){return!e||e.startsWith("-")||e.startsWith("@")||e.includes("://")||/[*?{}[\]]/.test(e)||m.isAbsolute(e)?!1:e.startsWith("./")||e.startsWith("../")||j.test(e)}function F(e,r){let t=[...e];for(let o=0;o<t.length-1;o+=1)D.has(t[o])&&!m.isAbsolute(t[o+1])&&!t[o+1].startsWith("-")&&(t[o+1]=m.resolve(r,t[o+1]));let{command:n,index:c}=L(t);if(!n||!Object.hasOwn(R,n))return t;let i=R[n];for(let o=c+1;o<t.length;o+=1){let a=t[o];if(a.startsWith("-")){W.has(a)&&(o+=1);continue}if(i>0){i-=1;continue}K(a)&&(t[o]=m.resolve(r,a))}return t}async function G(e,r,t){let n=await fetch(e,{method:"POST",headers:{"content-type":"application/json",...t},body:JSON.stringify(r),signal:AbortSignal.timeout(18e4)}),c=await n.text(),i=c;try{i=JSON.parse(c)}catch{}return{status:n.status,body:i}}function U(e,r,t,n,c=!1){return new Promise(i=>{let o="",a=M(e,r,{env:t,cwd:n,stdio:[c?"ignore":"inherit",c?"ignore":"inherit","pipe"]});a.stderr?.on("data",s=>{o+=String(s)}),a.on("error",s=>i({code:127,stderr:`${o}cortex-browser: cannot run ${e}: ${s.message}
7
+ `})),a.on("close",(s,l)=>i({code:s??(l?128:1),stderr:o}))})}var p=class extends Error{exitCode;constructor(r,t=1){super(r),this.exitCode=t}};async function V(e,r,t,n){let c=T(r),i=`http://127.0.0.1:${c}/webhook/browser`,o=setTimeout(()=>{e.writeErr(`cortex-browser: starting the browser${n?` on ${n}`:""}\u2026
8
+ `)},e.slowNoticeMs),a;try{a=await e.post(i,{action:"lease",sessionId:t,device:n},{[x]:r.CORTEX_WEBHOOK_TOKEN||""})}catch(l){throw new p(h(`cannot reach the Cortex daemon at 127.0.0.1:${c}: ${l.message}`,{hint:"cortex-browser works inside Cortex sessions while the Cortex server is running"}))}finally{clearTimeout(o)}if(a.status===401)throw new p(h("the Cortex daemon rejected this call (bad or missing CORTEX_WEBHOOK_TOKEN)",{hint:"run cortex-browser from a Cortex session, which sets the token"}));if(a.status===404)throw new p(h("this Cortex server has no browser endpoint yet",{hint:"the server needs a restart onto the version that ships cortex-browser"}));let s=a.body;if(a.status!==200||!s?.success){let l=typeof s=="object"&&s?s.error:String(s??"");throw new p(h(`browser unavailable: ${l||`HTTP ${a.status}`}`,{hint:s?.hint}))}return s.data}async function z(e,r={}){let t=r.env??process.env,n=r.cwd??process.cwd(),c=r.writeErr??(s=>{process.stderr.write(s)}),i=r.exec??U,o=r.post??G,a;try{a=H(e)}catch(s){if(s instanceof d)return c(`${s.message}
9
+ `),2;throw s}if(a.help)return process.stdout.write(`${k(I)}
10
+ `),0;try{if(X(a)){let v=y(t),b=await i(v,a.args,_(t),n);return b.stderr&&c(b.stderr),b.code}let s=t.CORTEX_SESSION_ID||t.CORTEX_EXECUTION_ID||"";if(!s)return c(`${h("no Cortex session (CORTEX_SESSION_ID is unset)",{hint:"cortex-browser leases a browser per Cortex session; run it from a session's shell"})}
11
+ `),2;let l=await V({post:o,writeErr:c,slowNoticeMs:r.slowNoticeMs??2e3},t,s,a.device),f=A(l.env,t),g=F(a.args,n),w=await i(l.bin,u(l.cdpEndpoint,l.abSession,g),f,n);return w.code!==0&&O(w.stderr)&&(await i(l.bin,u(l.cdpEndpoint,l.abSession,["tab","new"]),f,n,!0)).code===0&&(await i(l.bin,u(l.cdpEndpoint,l.abSession,S),f,n,!0),c(`cortex-browser: this session's previous tab is gone (closed after 10 idle minutes, or the browser restarted); continuing in a new blank tab
12
+ `),w=await i(l.bin,u(l.cdpEndpoint,l.abSession,g),f,n)),w.stderr&&c(w.stderr),await o(`${$(t)}/webhook/browser`,{action:"report",sessionId:s},{[x]:t.CORTEX_WEBHOOK_TOKEN||""}).catch(()=>{}),w.code}catch(s){return s instanceof p?(c(`${s.message}
13
+ `),s.exitCode):s instanceof C?(c(`${h(s.message,{hint:s.hint})}
14
14
  `),1):(c(`cortex-browser: ${s.message}
15
- `),1)}}async function U(e=process.argv.slice(2)){process.exitCode=await V(e)}E(new URL("dist/entry/browser-cli.js",__cortexPackageRoot).href)&&U();export{d as BrowserUsageError,K as absolutizePaths,D as isLocalCommand,U as main,H as parseBrowserArgs,V as runBrowserCli};
15
+ `),1)}}async function J(e=process.argv.slice(2)){process.exitCode=await z(e)}E(new URL("dist/entry/browser-cli.js",__cortexPackageRoot).href)&&J();export{d as BrowserUsageError,F as absolutizePaths,X as isLocalCommand,J as main,H as parseBrowserArgs,z as runBrowserCli};
package/dist/entry/cli.js CHANGED
@@ -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{a,b,c,d,e,f}from"../chunks/chunk-TWAEABGG.js";import"../chunks/chunk-2ZNLUY2U.js";import"../chunks/chunk-PZMXHA6X.js";import"../chunks/chunk-6LZK4DDH.js";import"../chunks/chunk-REBNWCKI.js";import"../chunks/chunk-MFAEUHMV.js";import"../chunks/chunk-NKXV32S6.js";import"../chunks/chunk-ASYQHJVQ.js";import"../chunks/chunk-O3JW2F7D.js";import"../chunks/chunk-HU6UIDEJ.js";import"../chunks/chunk-TZFLHVOQ.js";import"../chunks/chunk-5NRGVROY.js";import"../chunks/chunk-YG7OEPR2.js";import"../chunks/chunk-7MU2AKNM.js";import"../chunks/chunk-LMSQZ6TQ.js";import"../chunks/chunk-JERCOLY3.js";import"../chunks/chunk-YHIWOGVL.js";import"../chunks/chunk-QEOFEETJ.js";import"../chunks/chunk-DGMNI4AO.js";import"../chunks/chunk-5T7IX5KN.js";import"../chunks/chunk-OKRK6JPY.js";import"../chunks/chunk-BGVHA2D4.js";import"../chunks/chunk-3OKHUVEM.js";import"../chunks/chunk-SUFW24P4.js";import"../chunks/chunk-OE4KH3NJ.js";import"../chunks/chunk-LCKVYFMD.js";import"../chunks/chunk-5M4PFLRW.js";import"../chunks/chunk-PMG4YGDU.js";import"../chunks/chunk-AAA3UBIS.js";import"../chunks/chunk-KENCMLRE.js";import"../chunks/chunk-3YHOCPQU.js";import"../chunks/chunk-MEPASGPP.js";import"../chunks/chunk-STUHNKQS.js";import"../chunks/chunk-PFMEUFJ7.js";import"../chunks/chunk-KRXTI4JO.js";import"../chunks/chunk-DPQPXBTP.js";import"../chunks/chunk-Q4UGYGU5.js";import"../chunks/chunk-W5LGYSPZ.js";import"../chunks/chunk-E7ZMYIY6.js";import"../chunks/chunk-NAA7GF6Q.js";import"../chunks/chunk-QWAQHHRS.js";import"../chunks/chunk-J5DVLUKY.js";import"../chunks/chunk-WHC7AYZD.js";export{c as cmdTui,d as getConfigOutput,f as main,a as parseTuiArgs,e as runCli,b as tuiPortListening};
4
+ import{a,b,c,d,e,f}from"../chunks/chunk-CI2RHH74.js";import"../chunks/chunk-KZSAFVSY.js";import"../chunks/chunk-Q7BZLPBU.js";import"../chunks/chunk-WU7RNAZD.js";import"../chunks/chunk-NHHR4DCF.js";import"../chunks/chunk-FDC2GRBK.js";import"../chunks/chunk-G264APQN.js";import"../chunks/chunk-5DVSAXOI.js";import"../chunks/chunk-HVN37UXD.js";import"../chunks/chunk-IGZWZP7Z.js";import"../chunks/chunk-Y6DGVTKM.js";import"../chunks/chunk-5NRGVROY.js";import"../chunks/chunk-LEAV3FFG.js";import"../chunks/chunk-4HRI75GU.js";import"../chunks/chunk-OZXMPBUX.js";import"../chunks/chunk-V7K3KNDM.js";import"../chunks/chunk-5T7IX5KN.js";import"../chunks/chunk-3O6ZG5HA.js";import"../chunks/chunk-UEEW2R4E.js";import"../chunks/chunk-VHX2GHBF.js";import"../chunks/chunk-C6YVF7EI.js";import"../chunks/chunk-ITGCWQFK.js";import"../chunks/chunk-PTS3J4DQ.js";import"../chunks/chunk-IMMGYDAB.js";import"../chunks/chunk-OJ37ZWBG.js";import"../chunks/chunk-SKHFU5DI.js";import"../chunks/chunk-V35MFAUQ.js";import"../chunks/chunk-OKRK6JPY.js";import"../chunks/chunk-52VCLZS5.js";import"../chunks/chunk-B3NB243Z.js";import"../chunks/chunk-LCKVYFMD.js";import"../chunks/chunk-5M4PFLRW.js";import"../chunks/chunk-BVEDNESB.js";import"../chunks/chunk-PMG4YGDU.js";import"../chunks/chunk-RG5GP4RB.js";import"../chunks/chunk-YAEHSSR4.js";import"../chunks/chunk-KST6OY76.js";import"../chunks/chunk-AXYAZTTN.js";import"../chunks/chunk-SM45TH22.js";import"../chunks/chunk-R2CCD4OF.js";import"../chunks/chunk-KRXTI4JO.js";import"../chunks/chunk-W34AK4SK.js";import"../chunks/chunk-LIIZI3HY.js";import"../chunks/chunk-Q4UGYGU5.js";import"../chunks/chunk-TRXLIL7V.js";import"../chunks/chunk-7GGPYU5E.js";import"../chunks/chunk-7W7VYUTK.js";import"../chunks/chunk-JGUEIW2W.js";import"../chunks/chunk-T54CZKNJ.js";import"../chunks/chunk-WHC7AYZD.js";export{c as cmdTui,d as getConfigOutput,f as main,a as parseTuiArgs,e as runCli,b as tuiPortListening};
@@ -2,4 +2,4 @@
2
2
  import { createRequire as __cortexCreateRequire } from 'node:module';
3
3
  const require = __cortexCreateRequire(import.meta.url);
4
4
  const __cortexPackageRoot = new URL("../../", import.meta.url);
5
- import{f as n}from"../chunks/chunk-TWAEABGG.js";import"../chunks/chunk-2ZNLUY2U.js";import"../chunks/chunk-PZMXHA6X.js";import"../chunks/chunk-6LZK4DDH.js";import"../chunks/chunk-REBNWCKI.js";import"../chunks/chunk-MFAEUHMV.js";import"../chunks/chunk-NKXV32S6.js";import"../chunks/chunk-ASYQHJVQ.js";import"../chunks/chunk-O3JW2F7D.js";import"../chunks/chunk-HU6UIDEJ.js";import"../chunks/chunk-TZFLHVOQ.js";import"../chunks/chunk-5NRGVROY.js";import"../chunks/chunk-YG7OEPR2.js";import"../chunks/chunk-7MU2AKNM.js";import"../chunks/chunk-LMSQZ6TQ.js";import"../chunks/chunk-JERCOLY3.js";import"../chunks/chunk-YHIWOGVL.js";import"../chunks/chunk-QEOFEETJ.js";import"../chunks/chunk-DGMNI4AO.js";import"../chunks/chunk-5T7IX5KN.js";import"../chunks/chunk-OKRK6JPY.js";import"../chunks/chunk-BGVHA2D4.js";import"../chunks/chunk-3OKHUVEM.js";import"../chunks/chunk-SUFW24P4.js";import"../chunks/chunk-OE4KH3NJ.js";import"../chunks/chunk-LCKVYFMD.js";import"../chunks/chunk-5M4PFLRW.js";import"../chunks/chunk-PMG4YGDU.js";import"../chunks/chunk-AAA3UBIS.js";import"../chunks/chunk-KENCMLRE.js";import"../chunks/chunk-3YHOCPQU.js";import"../chunks/chunk-MEPASGPP.js";import"../chunks/chunk-STUHNKQS.js";import"../chunks/chunk-PFMEUFJ7.js";import"../chunks/chunk-KRXTI4JO.js";import"../chunks/chunk-DPQPXBTP.js";import"../chunks/chunk-Q4UGYGU5.js";import"../chunks/chunk-W5LGYSPZ.js";import"../chunks/chunk-E7ZMYIY6.js";import"../chunks/chunk-NAA7GF6Q.js";import"../chunks/chunk-QWAQHHRS.js";import"../chunks/chunk-J5DVLUKY.js";import"../chunks/chunk-WHC7AYZD.js";n();
5
+ import{f as n}from"../chunks/chunk-CI2RHH74.js";import"../chunks/chunk-KZSAFVSY.js";import"../chunks/chunk-Q7BZLPBU.js";import"../chunks/chunk-WU7RNAZD.js";import"../chunks/chunk-NHHR4DCF.js";import"../chunks/chunk-FDC2GRBK.js";import"../chunks/chunk-G264APQN.js";import"../chunks/chunk-5DVSAXOI.js";import"../chunks/chunk-HVN37UXD.js";import"../chunks/chunk-IGZWZP7Z.js";import"../chunks/chunk-Y6DGVTKM.js";import"../chunks/chunk-5NRGVROY.js";import"../chunks/chunk-LEAV3FFG.js";import"../chunks/chunk-4HRI75GU.js";import"../chunks/chunk-OZXMPBUX.js";import"../chunks/chunk-V7K3KNDM.js";import"../chunks/chunk-5T7IX5KN.js";import"../chunks/chunk-3O6ZG5HA.js";import"../chunks/chunk-UEEW2R4E.js";import"../chunks/chunk-VHX2GHBF.js";import"../chunks/chunk-C6YVF7EI.js";import"../chunks/chunk-ITGCWQFK.js";import"../chunks/chunk-PTS3J4DQ.js";import"../chunks/chunk-IMMGYDAB.js";import"../chunks/chunk-OJ37ZWBG.js";import"../chunks/chunk-SKHFU5DI.js";import"../chunks/chunk-V35MFAUQ.js";import"../chunks/chunk-OKRK6JPY.js";import"../chunks/chunk-52VCLZS5.js";import"../chunks/chunk-B3NB243Z.js";import"../chunks/chunk-LCKVYFMD.js";import"../chunks/chunk-5M4PFLRW.js";import"../chunks/chunk-BVEDNESB.js";import"../chunks/chunk-PMG4YGDU.js";import"../chunks/chunk-RG5GP4RB.js";import"../chunks/chunk-YAEHSSR4.js";import"../chunks/chunk-KST6OY76.js";import"../chunks/chunk-AXYAZTTN.js";import"../chunks/chunk-SM45TH22.js";import"../chunks/chunk-R2CCD4OF.js";import"../chunks/chunk-KRXTI4JO.js";import"../chunks/chunk-W34AK4SK.js";import"../chunks/chunk-LIIZI3HY.js";import"../chunks/chunk-Q4UGYGU5.js";import"../chunks/chunk-TRXLIL7V.js";import"../chunks/chunk-7GGPYU5E.js";import"../chunks/chunk-7W7VYUTK.js";import"../chunks/chunk-JGUEIW2W.js";import"../chunks/chunk-T54CZKNJ.js";import"../chunks/chunk-WHC7AYZD.js";n();
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __cortexCreateRequire } from 'node:module';
2
2
  const require = __cortexCreateRequire(import.meta.url);
3
3
  const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{a as Ie,b as V,c as Ce,e as Oe,f as S,g as b,h as C,j as Pe}from"../chunks/chunk-REPYBMQS.js";import{e as Q}from"../chunks/chunk-52T37Y47.js";import{a as _e}from"../chunks/chunk-H2FP6DG4.js";import{b as Ne}from"../chunks/chunk-AAA3UBIS.js";import{f as xe,g as Te}from"../chunks/chunk-KENCMLRE.js";import"../chunks/chunk-3YHOCPQU.js";import"../chunks/chunk-MEPASGPP.js";import{a as F}from"../chunks/chunk-STUHNKQS.js";import"../chunks/chunk-PFMEUFJ7.js";import"../chunks/chunk-KRXTI4JO.js";import"../chunks/chunk-DPQPXBTP.js";import"../chunks/chunk-Q4UGYGU5.js";import"../chunks/chunk-W5LGYSPZ.js";import{a as Se,c as ve,e as ke}from"../chunks/chunk-E7ZMYIY6.js";import{e as Ee}from"../chunks/chunk-NAA7GF6Q.js";import{a as je,b as De,f as $e}from"../chunks/chunk-QWAQHHRS.js";import{c as we,f as Re,l as K,p as L,q as _,r as E}from"../chunks/chunk-J5DVLUKY.js";import"../chunks/chunk-WHC7AYZD.js";import{fork as Vt}from"child_process";import{watch as Y,existsSync as T,unlinkSync as de,statSync as tt,writeFileSync as Zt,readdirSync as en}from"fs";import*as p from"path";import{mkdtempSync as Mt,readdirSync as Wt,rmSync as Gt,statSync as Ut}from"node:fs";import{tmpdir as Ye}from"node:os";import*as k from"node:path";import*as d from"fs";import*as l from"path";var lt=["dist/","defaults/","web/dist/","bundled-dependencies/","scripts/install-bundled-dependencies.mjs","scripts/postinstall-restart-trigger.mjs","README.md"],ut=["dependencies","optionalDependencies","peerDependencies","bundleDependencies"];function v(e){return{blocked:e,targets:[],manifestSource:"",manifestDestination:""}}function Ae(e){try{return JSON.parse(d.readFileSync(e,"utf8"))}catch{return null}}var dt=/[*?[\]{}]/;function ft(e){let t=Array.isArray(e)?e.filter(i=>typeof i=="string"):[],n=t.filter(i=>!i.startsWith("!"));if(JSON.stringify([...n].sort())!==JSON.stringify([...lt].sort()))return{blocked:"package.json `files` changed \u2014 update EXPECTED_FILES in fast-install.ts",excluded:[]};let r=[];for(let i of t.filter(o=>o.startsWith("!"))){if(dt.test(i))return{blocked:`unsupported \`files\` negation: ${i}`,excluded:[]};r.push(l.posix.normalize(i.slice(1)).replace(/^\.\/|\/$/g,""))}return{blocked:null,excluded:r}}function pt(e,t){return t.filter(n=>n.startsWith(`${e.name}/`)).map(n=>l.join(e.source,n.slice(e.name.length+1)))}function Le(e){return JSON.stringify(ut.map(t=>{let n=e[t];return Array.isArray(n)?[t,[...n].sort()]:n&&typeof n=="object"?[t,Object.entries(n).sort(([r],[i])=>r.localeCompare(i))]:[t,null]}))}function mt(e,t){let n=e;for(;;){if(d.existsSync(l.join(n,"node_modules",t,"package.json")))return!0;let r=l.dirname(n);if(r===n)return!1;n=r}}function Fe(e){let t=ht(e);if(t)return v(t);let n=l.join(e.repoDir,"package.json"),r=Ae(n);if(!r)return v(`unreadable manifest: ${n}`);let i=Ae(l.join(e.installRoot,"package.json"));return i?bt(e,r,i):v("no installed manifest \u2014 package was never installed")}function ht({repoDir:e,installRoot:t}){return!e||!t?"repo or install root unset":l.resolve(e)===l.resolve(t)?"install root is the source checkout":null}function bt(e,t,n){if(n.cortexBundle===!0)return v("installed package is bundled \u2014 full install required");let r=ft(t.files);if(r.blocked)return v(r.blocked);let i=gt(e.installRoot,t,n);return i?v(i):yt(e,r.excluded)}function gt(e,t,n){if(Le(t)!==Le(n))return"dependency closure changed";let i=Object.keys(n.dependencies??{}).find(o=>!mt(e,o));return i?`installed dependency missing: ${i}`:null}function yt(e,t){let{repoDir:n,monorepoRoot:r,installRoot:i}=e,c=[{name:"dist",source:l.join(n,"dist"),destination:l.join(i,"dist")},{name:"defaults",source:l.join(n,"defaults"),destination:l.join(i,"defaults")},{name:"web/dist",source:l.join(r,"web","dist"),destination:l.join(i,"web","dist")}].filter(f=>d.existsSync(f.source)).map(f=>({...f,exclude:pt(f,t)}));return c.some(f=>f.name==="dist")?{blocked:null,targets:c,manifestSource:l.join(n,"package.json"),manifestDestination:l.join(i,"package.json")}:v(`no build output at ${l.join(n,"dist")}`)}function wt(e,t,n=[]){let r=`.cortex-fast-${process.pid}-${Date.now()}`,i=`${t}${r}.new`,o=`${t}${r}.old`,c=d.existsSync(t);try{d.mkdirSync(l.dirname(t),{recursive:!0}),d.cpSync(e,i,{recursive:!0,filter:f=>!n.some(ye=>f===ye||f.startsWith(`${ye}${l.sep}`))}),c&&d.renameSync(t,o),d.renameSync(i,t),c&&d.rmSync(o,{recursive:!0,force:!0})}catch(f){throw d.rmSync(i,{recursive:!0,force:!0}),c&&!d.existsSync(t)&&d.existsSync(o)&&d.renameSync(o,t),f}}function Be(e){if(e.blocked)throw new Error(`fast install blocked: ${e.blocked}`);for(let t of e.targets)wt(t.source,t.destination,t.exclude);return d.copyFileSync(e.manifestSource,e.manifestDestination),e.targets.map(t=>t.name)}import u from"node:fs";import a from"node:path";var Rt=["dist/","defaults/","web/dist/","vendor/","README.md","LICENSE","THIRD_PARTY_NOTICES.txt","scripts/bundle-prune-browser.mjs","scripts/postinstall-restart-trigger.mjs","!**/*.map"],P=["dist","defaults","web","vendor","scripts"],Z=["README.md","LICENSE","THIRD_PARTY_NOTICES.txt","package.json"],Et=["dist/entry/cli.js","dist/entry/daemon.js","dist/entry/production-app-bootstrap.js","dist/tui/index.js","dist/domain/mcp/bundled-server.js","dist/agent-adapter/claude/remote-mcp-proxy.js","dist/core/pi-sdk.js","dist/domain/auth/cc-auth-cli.js","web/dist/index.html","vendor/aistatus/gateway-cli.js","vendor/pi/dist/utils/image-resize-worker.js","vendor/pi/dist/utils/image-resize.js","vendor/pi/dist/core/extensions/loader.js","vendor/pi-ai/oauth-load.js","vendor/pi-ai/bedrock.js","vendor/pi/dist/extensions/codemode/execute.js","vendor/pi/dist/codemode-worker.js","vendor/quickjs.wasm","vendor/pi/package.json","vendor/pi/README.md","vendor/pi/CHANGELOG.md","scripts/bundle-prune-browser.mjs","scripts/postinstall-restart-trigger.mjs",...Z],St=[...P,"web/dist","dist/client-bundle","vendor/pi/docs","vendor/pi/examples","vendor/pi/schemas","vendor/pi/dist/modes/interactive/theme","vendor/pi/dist/modes/interactive/assets","vendor/pi/dist/core/export-html"],vt=["dependencies","optionalDependencies","peerDependencies","peerDependenciesMeta","bundleDependencies","bundledDependencies"];function ee(e){let t=JSON.parse(u.readFileSync(e,"utf8"));if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Invalid manifest: ${e}`);return t}function kt(e,t){return Array.isArray(e)&&JSON.stringify([...e].sort())===JSON.stringify([...t].sort())}function jt(e){if(e.name!=="@cortex-agent/server"||e.cortexBundle!==!0)throw new Error("Invalid bundle stage: expected @cortex-agent/server with cortexBundle:true");if(!kt(e.files,Rt))throw new Error("Invalid bundle stage: package.json `files` changed")}function Dt(e){let t=e.bin;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Invalid bundle stage: missing bin entries");let n=[e.main,...Object.values(t)];for(let r of n)$t(r);return n}function $t(e){if(typeof e!="string")throw new Error("Invalid bundle stage: missing runtime entry");if(!e.startsWith("dist/")||!e.endsWith(".js")||e.includes("\\"))throw new Error(`Invalid bundle stage entry: ${e}`);if(e.split("/").some(t=>t===".."||t==="."))throw new Error(`Unsafe stage entry: ${e}`)}function B(e,t,n){let r=a.join(e,t),i=u.lstatSync(r);if(!(n?i.isDirectory():i.isFile()))throw new Error(`Invalid bundle stage entry (wrong type or symlink): ${r}`)}function te(e){return u.readdirSync(e,{withFileTypes:!0}).flatMap(t=>{let n=a.join(e,t.name);if(t.isDirectory())return te(n);if(t.isFile())return[n];throw new Error(`Invalid bundle stage: symlink or special entry: ${n}`)})}function W(e){if(!e)throw new Error("Bundle stage directory unset");let t=ee(a.join(e,"package.json"));jt(t);for(let n of St)B(e,n,!0);for(let n of[...Et,...Dt(t)])B(e,n,!1);for(let n of P)te(a.join(e,n))}function M(e){let t=a.resolve(e);try{return u.realpathSync(t)}catch(n){if(n.code!=="ENOENT")throw n;return It(t)}}function It(e){return u.lstatSync(e,{throwIfNoEntry:!1})?.isSymbolicLink()?M(a.resolve(a.dirname(e),u.readlinkSync(e))):a.join(M(a.dirname(e)),a.basename(e))}function Me(e,t){let n=a.relative(e,t);return n===""||!n.startsWith(`..${a.sep}`)&&n!==".."&&!a.isAbsolute(n)}function Ge(e){if(!e.stageDir||!e.installRoot)throw new Error("Bundle stage and install roots must be separate and set");let t=M(e.stageDir),n=M(e.installRoot);if(Me(t,n)||Me(n,t))throw new Error("Bundle stage and install roots overlap; separate roots are required");return{stageDir:t,installRoot:n}}function We(e){return JSON.stringify(vt.map(t=>{let n=e[t];return Array.isArray(n)?[t,[...n].sort()]:n&&typeof n=="object"?[t,Object.entries(n).sort(([r],[i])=>r.localeCompare(i))]:[t,n??null]}))}function xt(e,t){let n=e;for(;;){if(u.existsSync(a.join(n,"node_modules",t,"package.json")))return!0;let r=a.dirname(n);if(r===n)return!1;n=r}}function Tt(e,t,n){if(We(t)!==We(n))return"dependency closure changed";let i=Object.keys(t.dependencies??{}).find(o=>!xt(e,o));return i?`installed dependency missing: ${i}`:null}function _t(e){try{for(let t of P)B(e,t,!0);for(let t of Z)B(e,t,!1);return null}catch{return"installed bundle layout is incomplete or incompatible"}}function Ct(e,t){let n;try{n=ee(a.join(e,"package.json"))}catch{return"no readable installed manifest \u2014 full install required"}return n.cortexBundle!==!0||n.name!=="@cortex-agent/server"?"installed package is not a Cortex bundle \u2014 full install required":Tt(e,t,n)??_t(e)}function Ue(e,t){return{name:t,source:a.join(e.stageDir,t),destination:a.join(e.installRoot,t),exclude:[]}}function ne(e){W(e.stageDir);let t=Ge(e),n=Ct(t.installRoot,ee(a.join(t.stageDir,"package.json"))),r=[...P,...Z.filter(i=>i!=="package.json")];return{...t,blocked:n,targets:n?[]:r.map(i=>Ue(t,i)),manifestSource:a.join(t.stageDir,"package.json"),manifestDestination:a.join(t.installRoot,"package.json")}}function Ot(e,t){return u.mkdirSync(a.join(t,"new")),u.mkdirSync(a.join(t,"old")),[...e.targets,Ue(e,"package.json")].map(n=>{let r=a.join(t,"new",n.name);return u.cpSync(n.source,r,{recursive:!0,dereference:!1,errorOnExist:!0,force:!1}),{destination:n.destination,staged:r,previous:a.join(t,"old",n.name),movedPrevious:!1,installedNew:!1}})}function Pt(e){u.renameSync(e.destination,e.previous),e.movedPrevious=!0,u.renameSync(e.staged,e.destination),e.installedNew=!0}function Nt(e){let t=[];for(let n of[...e].reverse())try{n.installedNew&&u.rmSync(n.destination,{recursive:!0,force:!0}),n.movedPrevious&&u.renameSync(n.previous,n.destination)}catch(r){t.push(r)}return t}function At(e,t,n){try{for(let r of e)Pt(r)}catch(r){let i=Nt(e);throw i.length?new AggregateError([r,...i],`Bundle rollback incomplete; backups retained at ${t}`):(u.rmSync(t,{recursive:!0,force:!0}),r)}try{u.rmSync(t,{recursive:!0,force:!0})}catch(r){n(`Bundle installed; backup cleanup failed at ${t}: ${r}`)}}function Xe(e,t=console.warn){if(e.blocked)throw new Error(`bundle install blocked: ${e.blocked}`);let n=ne(e);if(n.blocked)throw new Error(`bundle install blocked: ${n.blocked}`);let r=u.mkdtempSync(a.join(a.dirname(n.installRoot),".cortex-bundle-")),i;try{i=Ot(n,r)}catch(o){throw u.rmSync(r,{recursive:!0,force:!0}),o}return At(i,r,t),n.targets.map(o=>o.name)}function Lt(e,t){let n=t;for(;n!==e;){let r=u.lstatSync(n,{throwIfNoEntry:!1});if(r?.isSymbolicLink())throw new Error(`Source map destination is a symlink: ${n}`);if(r&&(n===t?!r.isFile():!r.isDirectory()))throw new Error(`Source map destination has incompatible type: ${n}`);n=a.dirname(n)}}function He(e,t){W(e);let n=Ge({stageDir:e,installRoot:t}),i=P.flatMap(o=>te(a.join(n.stageDir,o))).filter(o=>o.endsWith(".map")).map(o=>{let c=a.join(n.installRoot,a.relative(n.stageDir,o));return Lt(n.installRoot,c),{destination:c,content:u.readFileSync(o)}});for(let{destination:o,content:c}of i)u.mkdirSync(a.dirname(o),{recursive:!0}),u.writeFileSync(o,c)}import{spawn as Ft}from"node:child_process";function ze(e,t,n,r){return new Promise(i=>{let o=`[${e} ${t.join(" ")}]`;r.info(`${o} cwd=${n.cwd}`);let c=Ft(e,t,{...n,stdio:["ignore","pipe","pipe"]});c.stdout?.on("data",qe(r,o,"out")),c.stderr?.on("data",qe(r,o,"err")),c.on("exit",f=>{r.info(`${o} exit=${f}`),i(f??1)}),c.on("error",f=>{r.error(`${o} spawn error: ${f.message}`),i(1)})})}function qe(e,t,n){return r=>{for(let i of r.toString("utf8").split(`
5
- `))i.trim()&&e.info(`${t} ${n}: ${i}`)}}function re(e){let t=(r,i,o)=>({label:r,cmd:"npm",args:["run",o],cwd:i}),n=[t("server",e.repoDir,"build")];return e.uiContractDir&&n.push(t("ui-contract",e.uiContractDir,"build")),e.webDir?(n.push(t("web-typecheck",e.webDir,"typecheck")),[n,[t("web-bundle",e.webDir,"bundle")],[t("web-depcruise",e.webDir,"depcruise")]]):[n]}function ie(e,t=!0){let n=re(e).flat().map(r=>r.label);return t&&n.push("bundle"),[...n,"install","restart"]}async function Bt(e,t){for(let n of e){t.update(i=>S(i,n.label));let r=await t.run(n.cmd,n.args,{cwd:n.cwd});if(r!==0){let i=`exit ${r}`;return t.update(o=>b(o,n.label,"failed",i)),{label:n.label,detail:i}}t.update(i=>b(i,n.label,"done"))}return null}async function Je(e){let t=re(e.dirs);t.flat().some(r=>r.label==="web-bundle")||e.log.warn("WEB_DIR not found \u2014 skipping web build, pack will use stale web/dist if present");let n=(await Promise.all(t.map(r=>Bt(r,e)))).filter(r=>r!==null);return n.length===0?!0:(e.abort(n.map(r=>r.label).join(", "),n.map(r=>r.detail).join(", ")),!1)}function Xt(e){return e.bundle?e.bundleBlocked===null?"bundle-fast":"bundle-full":"source"}var j=class extends Error{step;constructor(t,n){super(n),this.step=t}};function U(e){return e instanceof Error?e.message:String(e)}async function Ke(e){try{return await Je(e)?await Ht(e):"finished"}catch(t){let n=t instanceof j?t.step:"install";return e.abort(n,U(t)),"finished"}}async function Ht(e){let t=e.bundle?Mt(k.join(Ye(),"cortex-rebuild-")):null;try{return await qt(e,t?k.join(t,"stage"):null)}finally{t&&Gt(t,{recursive:!0,force:!0})}}async function qt(e,t){if(t&&await zt(e,t),e.deferInstall())return"deferred";e.update(r=>S(r,"install"));let n=await Jt(e,t);return e.update(r=>b(r,"install","done",n)),e.log.info("Rebuild succeeded \u2014 restarting app.ts"),await e.restart(),"finished"}async function zt(e,t){e.update(n=>S(n,"bundle"));try{await G(e,"bundle",process.execPath,["scripts/bundle.mjs",t,"--sourcemap"],e.dirs.repoDir),W(t),e.update(n=>b(n,"bundle","done"))}catch(n){throw new j("bundle",U(n))}}async function Jt(e,t){if(!t)return Kt(e);let n=ne({stageDir:t,installRoot:e.installRoot}),r=Xt({bundle:e.bundle,bundleBlocked:n.blocked});if(r==="bundle-fast"){let o=Xe(n,c=>e.log.warn(c));return e.log.info(`Bundle fast install: ${o.join(", ")}`),r}e.log.info(`Bundle fast install unavailable (${n.blocked}) \u2014 packing staged bundle`);let i=await Qt(e,t);await Ve(e,i);try{He(t,e.installRoot)}catch(o){e.log.warn(`Bundle installed without complete local source maps: ${U(o)} \u2014 restarting app.ts`)}return"bundle-full"}function Yt(e){let t=Fe({repoDir:e.dirs.repoDir,monorepoRoot:k.dirname(e.dirs.repoDir),installRoot:e.installRoot});if(t.blocked)return e.log.info(`Fast install unavailable (${t.blocked}) \u2014 falling back to pack + install -g`),null;try{return Be(t)}catch(n){return e.log.warn(`Fast install failed (${U(n)}) \u2014 falling back to pack + install -g`),null}}async function Kt(e){let t=Yt(e);return t?(e.log.info(`Fast install: ${t.join(", ")}`),"fast"):(await G(e,"tgz cleanup","bash",["-c","rm -f cortex-agent-server-*.tgz"],e.dirs.repoDir),await G(e,"pack","npm",["pack"],e.dirs.repoDir),await Ve(e,Qe(e.dirs.repoDir)),"pack + install -g")}async function Qt(e,t){return await G(e,"pack","npm",["pack","--ignore-scripts"],t),Qe(t)}function Qe(e){let t=Wt(e).filter(n=>n.startsWith("cortex-agent-server-")&&n.endsWith(".tgz")).map(n=>({file:n,mtime:Ut(k.join(e,n)).mtimeMs})).sort((n,r)=>r.mtime-n.mtime);if(!t.length)throw new j("pack","npm pack succeeded but no cortex-agent-server-*.tgz found");return k.join(e,t[0].file)}async function Ve(e,t){e.log.info(`Packed tarball: ${t}`);let n=$e(["install","-g",t],e.installRoot),r={...process.env,CORTEX_SKIP_POSTINSTALL_RESTART:"1"},i=await e.run("npm",n,{cwd:Ye(),env:r});if(i!==0)throw new j("install",`exit ${i}`)}async function G(e,t,n,r,i){let o=await e.run(n,r,{cwd:i});if(o!==0)throw new j(t,`exit ${o}`)}Ie(p.join(K,".env"));var s=Ee("daemon"),tn=je(new URL("dist/entry/daemon.js",__cortexPackageRoot).href),nn=p.join(tn,"app.js"),D=p.join(K,".env"),y=process.env.CORTEX_REPO??"",nt=process.env.CORTEX_REBUILD_BUNDLE!=="0",w=y?p.join(y,"src"):"",q=y?p.dirname(y):"",oe=q?p.join(q,"web"):"",se=q?p.join(q,"packages","ui-contract"):"",rn=800,on=2500,fe=1e3,sn=3e4,an=1e4,cn=["tests/","tmp/","node_modules/","dist/","vendor/"],ln=[".d.ts",".test.ts",".spec.ts"],m=null,rt=0,$=fe,I=null,x=null,N=null,z=!1,R=!1,h=null,g=null,X=!1,ce=!1,J=null,le=null,it=[],O=null;function pe(){N&&(clearTimeout(N),N=null),I&&(clearTimeout(I),I=null),x&&(clearTimeout(x),x=null)}function un(e=null,t=null){let n=["pipe","ignore","ignore","ipc"],r={...process.env};return delete r.CORTEX_RESTART_REASON,delete r[V],e&&(r.CORTEX_RESTART_REASON=e),t&&(r[V]=t),{cwd:Re,windowsHide:!0,stdio:n,execArgv:[],env:r}}function me(){if(z)return;if(m){s.info("startChild called but child already running \u2014 skipping.");return}let e=J,t=le;J=null,le=null,s.info(e?`Starting app.ts (reason: ${e})...`:"Starting app.ts..."),rt=Date.now(),R=!1,h=null,m=Vt(nn,[],un(e,t)),s.info(`app.ts started \u2014 PID ${m.pid}`);try{Zt(_,String(m.pid),"utf8")}catch{}m.on("message",fn),m.on("exit",pn)}function dn(){R=!1;let e=h?` (pending restart: ${h})`:g?` (pending rebuild: ${g})`:"";if(s.info(`IPC \u2190 app.ts: idle${e}`),h){let t=h;h=null,he(t)}else if(g){let t=g;g=null,ct(t)}}function fn(e){e?.type==="busy"?(s.info("IPC \u2190 app.ts: busy"),R=!0):e?.type==="idle"&&dn()}function pn(e,t){m=null,R=!1;try{T(_)&&de(_)}catch{}if(z){s.info("app.ts exited (shutdown).");return}if(X){t&&s.info(`app.ts stopped (signal ${t}).`);return}mn(e,t)}function mn(e,t){let n=Date.now()-rt;n>an&&($=fe);let r=t?`crash (signal ${t})`:`crash (exit code ${e})`,i=Ce({code:e,signal:t,uptimeMs:n,backoffMs:$});s.info(t?`app.ts killed by signal ${t}.`:`app.ts exited with code ${e}.`),s.info(`Restarting in ${$}ms...`),pe(),N=setTimeout(()=>{N=null,J=r,le=i,me()},$),$=Math.min($*2,sn)}function ot(){return new Promise(e=>{if(!m)return e();let t=m;s.info(`Stopping app.ts (PID ${t.pid})...`);let n=setTimeout(()=>{s.info("Force killing app.ts...");try{t.kill("SIGKILL")}catch{}},5e3);t.once("exit",()=>{clearTimeout(n),e()}),t.kill("SIGTERM")})}async function he(e){return R?(s.info(`Restart deferred (app.ts is busy): ${e}`),h=e,H(!0,"restart",e),"deferred"):X?(s.info(`Restart deferred (already restarting): ${e}`),h=e,H(!0,"restart",e),"deferred"):(pe(),s.info(`Restarting: ${e}`),$=fe,X=!0,H(!0,"restart",e),await ot(),X=!1,h&&(s.info(`Absorbed deferred restart: ${h}`),h=null),J=e,me(),"restarted")}function hn(e){for(let t of e.splice(0))try{t.close()}catch{}}function bn(e,t){let n=[],r=i=>{n.push(Y(i,(c,f)=>t(c,f)));let o;try{o=en(i,{withFileTypes:!0})}catch{return}for(let c of o)c.isDirectory()&&(c.name.startsWith(".")||c.name==="node_modules"||r(p.join(i,c.name)))};try{r(e)}catch(i){throw hn(n),i}return n}function gn(e){try{return T(e)&&tt(e).isDirectory()}catch{return!1}}function Ze(e){if(!e)return;let t=String(e).replace(/\\/g,"/");t.endsWith(".ts")&&(ln.some(n=>t.endsWith(n))||cn.some(n=>t.startsWith(n)||t.includes(`/${n}`))||be(`src change: ${t}`))}function yn(){if(!w||!gn(w)){let e=y?`CORTEX_REPO=${y} set but ${w} not a directory`:"CORTEX_REPO unset";return s.warn(`${e} \u2014 src watcher disabled, only .restart trigger available`),null}return F({label:`Source ${w}`,warn:e=>s.warn(e),startWatching:()=>{if(process.platform==="win32"){let t=bn(w,(n,r)=>Ze(r));return s.info(`Watching src: ${w} (per-directory, *.ts, ${t.length} dirs)`),t}let e=Y(w,{recursive:!0},(t,n)=>Ze(n));return s.info(`Watching src: ${w} (recursive, *.ts)`),[e]}})}function et(){if(T(E)){try{de(E)}catch{}y?be("manual trigger (.restart file)"):ue("manual trigger (.restart file)")}}function wn(){let e=p.dirname(E),t=p.basename(E);return F({label:`Restart trigger ${E}`,warn:n=>s.warn(n),startWatching:()=>{let n=Y(e,(r,i)=>{i&&String(i)===t&&et()});return s.info(`Watching for restart trigger: ${E}`),[n]},poll:et})}function ae(e){try{let t=tt(e);return`${t.mtimeMs}:${t.size}`}catch{return null}}function Rn(e,t,n){let r=Y(e,(i,o)=>{o&&String(o)===t&&n()});return s.info(`Watching env file: ${D}`),[r]}function En(){let e=p.dirname(D);if(!T(e))return null;let t=p.basename(D),n=ae(D),r=()=>{n=ae(D),ue("env change (.env)")},i=()=>{let o=ae(D);o!==n&&(n=o,ue("env change (.env)"))};return F({label:`Environment file ${D}`,startWatching:()=>Rn(e,t,r),poll:i,warn:o=>s.warn(o)})}function Sn(){let e=[wn(),En()],t=yn();return t&&e.push(t),e.filter(n=>n!==null)}function ue(e){I&&clearTimeout(I),I=setTimeout(()=>{I=null,he(e)},rn)}function be(e){x&&clearTimeout(x),x=setTimeout(()=>{x=null,ct(e)},on)}function vn(e){return ke("notice.rebuild.aborted",{step:e.step,detail:e.detail,reason:e.reason})}function st(e){if(!(!m||!m.connected))try{m.send(e)}catch{}}function H(e,t,n){st({type:"rebuild-hold",hold:e,phase:t,reason:n})}function kn(e,t){return t?!0:!e||e.status!=="running"?!1:e.current==="install"||e.current==="restart"}function ge(e){O=e,Pe(e);let t=h!==null;H(kn(e,t),e.current??(t?"restart":null),e.reason)}function at(){return{repoDir:y,uiContractDir:se&&T(se)?se:null,webDir:oe&&T(oe)?oe:null}}async function jn(e){A(n=>S(n,"restart"));let t=await he(`src rebuild: ${e}`);A(n=>t==="restarted"?C(b(n,"restart","done"),"succeeded"):C(b(n,"restart","skipped","app.ts busy"),"deferred","Build and install succeeded; the restart is queued until app.ts goes idle."))}function A(e){O&&ge(e(O))}function Dn(e){return e==="bundle"?"bundle":e==="install"||e==="pack"||e==="tgz cleanup"?"install":null}function $n(e,t,n){ve(process.env.CORTEX_LANG?Se(process.env.CORTEX_LANG):_e());let r=vn({step:e,detail:t,reason:n});s.error(r);let i=Dn(e);A(o=>C(i?b(o,i,"failed",t):o,"aborted",r)),st({type:"rebuild-aborted",text:r})}function In(e){return R||ce?(s.info(`Rebuild deferred (${R?"app.ts busy":"already rebuilding"}): ${e}`),g=e,!1):y?(ce=!0,!0):(s.error(`Rebuild requested but CORTEX_REPO unset \u2014 ignoring: ${e}`),!1)}function xn(e){return R?(s.info(`Rebuild install deferred (app.ts busy): ${e} \u2014 retrying when app.ts goes idle`),g=e,A(t=>C(t,"deferred","Build finished; install and restart wait for app.ts to go idle.")),!0):!1}function Tn(e){return{dirs:at(),installRoot:we,bundle:nt,log:s,run:(t,n,r)=>ze(t,n,r,s),update:A,abort:(t,n)=>$n(t,n,e),deferInstall:()=>xn(e),restart:()=>jn(e)}}async function ct(e){if(!In(e))return;let t=!1;try{s.info(`Rebuild pipeline starting: ${e}`),ge(Oe({reason:e,names:ie(at(),nt),daemonPid:process.pid})),t=await Ke(Tn(e))==="deferred"}finally{_n(t)}}function _n(e){if(O?.status==="running"&&ge(C(O,"aborted","pipeline ended without restarting app.ts")),O=null,ce=!1,g&&!e){let t=g;g=null,s.info(`Consuming queued rebuild: ${t}`),be(t)}}function Cn(){for(let e of it.splice(0))e.close()}function On(){let e=async t=>{z||(z=!0,s.info(`Received ${t}, shutting down...`),pe(),Cn(),await ot(),s.info("Daemon stopped."),process.exit(0))};process.on("SIGINT",()=>e("SIGINT")),process.on("SIGTERM",()=>e("SIGTERM"))}function Pn(){let e=xe(L);if(e.acquired){e.stale&&s.info(`Removed stale PID file and reclaimed lock for PID ${process.pid}`);return}s.error(`Another Cortex daemon is already running (PID ${e.holderPid}, lockfile ${L}).
6
- Refusing to start a second instance \u2014 its app.ts already holds ports 3001/3002 and your child would crash-loop on EADDRINUSE.
7
- To restart the running daemon: \`touch agent-server/.restart\` (hot reload), or send SIGTERM to PID ${e.holderPid} and rerun.`),process.exit(1)}function Nn(){Te(L);try{T(_)&&de(_)}catch{}}function An(){let e=!1,t=(n,r)=>{if(!e){e=!0;try{s.error(`${n}: ${String(r)}`)}catch{}finally{e=!1}}};process.on("uncaughtException",n=>{t("uncaughtException",n?.stack??n),Q("daemon","uncaughtException",n)}),process.on("unhandledRejection",n=>{t("unhandledRejection",n instanceof Error?n.stack:n),Q("daemon","unhandledRejection",n)})}function Ln(){An(),Pn(),process.on("exit",Nn),s.info("Cortex Daemon starting..."),Ne(),On(),me(),it=Sn()}De(new URL("dist/entry/daemon.js",__cortexPackageRoot).href)&&Ln();export{un as buildChildProcessConfig,vn as buildRebuildAbortNotice,re as planRebuildLanes,ie as planRebuildStepNames,kn as rebuildHoldsTurns};
4
+ import{a as V,b as Q,c as Oe,e as Ae,f as S,g as b,h as _,j as Ne}from"../chunks/chunk-5UYVNA3W.js";import{f as K}from"../chunks/chunk-BKYP6AGM.js";import{a as Ce}from"../chunks/chunk-X5ND4H4P.js";import{a as De,d as $e,e as xe,g as Pe}from"../chunks/chunk-RG5GP4RB.js";import{f as Te,g as _e}from"../chunks/chunk-YAEHSSR4.js";import"../chunks/chunk-KST6OY76.js";import"../chunks/chunk-AXYAZTTN.js";import{c as F}from"../chunks/chunk-SM45TH22.js";import"../chunks/chunk-R2CCD4OF.js";import"../chunks/chunk-KRXTI4JO.js";import"../chunks/chunk-W34AK4SK.js";import"../chunks/chunk-LIIZI3HY.js";import"../chunks/chunk-Q4UGYGU5.js";import"../chunks/chunk-TRXLIL7V.js";import{a as Ee,c as Se,e as ve}from"../chunks/chunk-7GGPYU5E.js";import{e as Re}from"../chunks/chunk-7W7VYUTK.js";import{a as ke,b as je,f as Ie}from"../chunks/chunk-JGUEIW2W.js";import{b as ye,e as we,j as Y,q as L,r as T,s as E}from"../chunks/chunk-T54CZKNJ.js";import"../chunks/chunk-WHC7AYZD.js";import{fork as nn}from"child_process";import{watch as J,existsSync as x,unlinkSync as ue,statSync as rt,writeFileSync as rn,readdirSync as on}from"fs";import*as p from"path";import{mkdtempSync as Gt,readdirSync as Ht,rmSync as qt,statSync as zt}from"node:fs";import{tmpdir as Ke}from"node:os";import*as k from"node:path";import*as d from"fs";import*as l from"path";var pt=["dist/","defaults/","web/dist/","bundled-dependencies/","scripts/install-bundled-dependencies.mjs","scripts/postinstall-restart-trigger.mjs","README.md"],mt=["dependencies","optionalDependencies","peerDependencies","bundleDependencies"];function v(e){return{blocked:e,targets:[],manifestSource:"",manifestDestination:""}}function Le(e){try{return JSON.parse(d.readFileSync(e,"utf8"))}catch{return null}}var ht=/[*?[\]{}]/;function bt(e){let t=Array.isArray(e)?e.filter(i=>typeof i=="string"):[],n=t.filter(i=>!i.startsWith("!"));if(JSON.stringify([...n].sort())!==JSON.stringify([...pt].sort()))return{blocked:"package.json `files` changed \u2014 update EXPECTED_FILES in fast-install.ts",excluded:[]};let r=[];for(let i of t.filter(o=>o.startsWith("!"))){if(ht.test(i))return{blocked:`unsupported \`files\` negation: ${i}`,excluded:[]};r.push(l.posix.normalize(i.slice(1)).replace(/^\.\/|\/$/g,""))}return{blocked:null,excluded:r}}function gt(e,t){return t.filter(n=>n.startsWith(`${e.name}/`)).map(n=>l.join(e.source,n.slice(e.name.length+1)))}function Fe(e){return JSON.stringify(mt.map(t=>{let n=e[t];return Array.isArray(n)?[t,[...n].sort()]:n&&typeof n=="object"?[t,Object.entries(n).sort(([r],[i])=>r.localeCompare(i))]:[t,null]}))}function yt(e,t){let n=e;for(;;){if(d.existsSync(l.join(n,"node_modules",t,"package.json")))return!0;let r=l.dirname(n);if(r===n)return!1;n=r}}function Be(e){let t=wt(e);if(t)return v(t);let n=l.join(e.repoDir,"package.json"),r=Le(n);if(!r)return v(`unreadable manifest: ${n}`);let i=Le(l.join(e.installRoot,"package.json"));return i?Rt(e,r,i):v("no installed manifest \u2014 package was never installed")}function wt({repoDir:e,installRoot:t}){return!e||!t?"repo or install root unset":l.resolve(e)===l.resolve(t)?"install root is the source checkout":null}function Rt(e,t,n){if(n.cortexBundle===!0)return v("installed package is bundled \u2014 full install required");let r=bt(t.files);if(r.blocked)return v(r.blocked);let i=Et(e.installRoot,t,n);return i?v(i):St(e,r.excluded)}function Et(e,t,n){if(Fe(t)!==Fe(n))return"dependency closure changed";let i=Object.keys(n.dependencies??{}).find(o=>!yt(e,o));return i?`installed dependency missing: ${i}`:null}function St(e,t){let{repoDir:n,monorepoRoot:r,installRoot:i}=e,c=[{name:"dist",source:l.join(n,"dist"),destination:l.join(i,"dist")},{name:"defaults",source:l.join(n,"defaults"),destination:l.join(i,"defaults")},{name:"web/dist",source:l.join(r,"web","dist"),destination:l.join(i,"web","dist")}].filter(f=>d.existsSync(f.source)).map(f=>({...f,exclude:gt(f,t)}));return c.some(f=>f.name==="dist")?{blocked:null,targets:c,manifestSource:l.join(n,"package.json"),manifestDestination:l.join(i,"package.json")}:v(`no build output at ${l.join(n,"dist")}`)}function vt(e,t,n=[]){let r=`.cortex-fast-${process.pid}-${Date.now()}`,i=`${t}${r}.new`,o=`${t}${r}.old`,c=d.existsSync(t);try{d.mkdirSync(l.dirname(t),{recursive:!0}),d.cpSync(e,i,{recursive:!0,filter:f=>!n.some(ge=>f===ge||f.startsWith(`${ge}${l.sep}`))}),c&&d.renameSync(t,o),d.renameSync(i,t),c&&d.rmSync(o,{recursive:!0,force:!0})}catch(f){throw d.rmSync(i,{recursive:!0,force:!0}),c&&!d.existsSync(t)&&d.existsSync(o)&&d.renameSync(o,t),f}}function Me(e){if(e.blocked)throw new Error(`fast install blocked: ${e.blocked}`);for(let t of e.targets)vt(t.source,t.destination,t.exclude);return d.copyFileSync(e.manifestSource,e.manifestDestination),e.targets.map(t=>t.name)}import u from"node:fs";import a from"node:path";var kt=["dist/","defaults/","web/dist/","vendor/","README.md","LICENSE","THIRD_PARTY_NOTICES.txt","scripts/bundle-prune-browser.mjs","scripts/postinstall-restart-trigger.mjs","!**/*.map"],A=["dist","defaults","web","vendor","scripts"],Z=["README.md","LICENSE","THIRD_PARTY_NOTICES.txt","package.json"],jt=["dist/entry/cli.js","dist/entry/daemon.js","dist/entry/production-app-bootstrap.js","dist/tui/index.js","dist/domain/mcp/bundled-server.js","dist/agent-adapter/claude/remote-mcp-proxy.js","dist/core/pi-sdk.js","dist/domain/auth/cc-auth-cli.js","web/dist/index.html","vendor/pi/dist/utils/image-resize-worker.js","vendor/pi/dist/utils/image-resize.js","vendor/pi/dist/core/extensions/loader.js","vendor/pi-ai/oauth-load.js","vendor/pi-ai/bedrock.js","vendor/pi/dist/extensions/codemode/execute.js","vendor/pi/dist/codemode-worker.js","vendor/quickjs.wasm","vendor/pi/package.json","vendor/pi/README.md","vendor/pi/CHANGELOG.md","scripts/bundle-prune-browser.mjs","scripts/postinstall-restart-trigger.mjs",...Z],It=[...A,"web/dist","dist/client-bundle","vendor/pi/docs","vendor/pi/examples","vendor/pi/schemas","vendor/pi/dist/modes/interactive/theme","vendor/pi/dist/modes/interactive/assets","vendor/pi/dist/core/export-html"],Dt=["dependencies","optionalDependencies","peerDependencies","peerDependenciesMeta","bundleDependencies","bundledDependencies"];function ee(e){let t=JSON.parse(u.readFileSync(e,"utf8"));if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Invalid manifest: ${e}`);return t}function $t(e,t){return Array.isArray(e)&&JSON.stringify([...e].sort())===JSON.stringify([...t].sort())}function xt(e){if(e.name!=="@cortex-agent/server"||e.cortexBundle!==!0)throw new Error("Invalid bundle stage: expected @cortex-agent/server with cortexBundle:true");if(!$t(e.files,kt))throw new Error("Invalid bundle stage: package.json `files` changed")}function Tt(e){let t=e.bin;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Invalid bundle stage: missing bin entries");let n=[e.main,...Object.values(t)];for(let r of n)_t(r);return n}function _t(e){if(typeof e!="string")throw new Error("Invalid bundle stage: missing runtime entry");if(!e.startsWith("dist/")||!e.endsWith(".js")||e.includes("\\"))throw new Error(`Invalid bundle stage entry: ${e}`);if(e.split("/").some(t=>t===".."||t==="."))throw new Error(`Unsafe stage entry: ${e}`)}function B(e,t,n){let r=a.join(e,t),i=u.lstatSync(r);if(!(n?i.isDirectory():i.isFile()))throw new Error(`Invalid bundle stage entry (wrong type or symlink): ${r}`)}function te(e){return u.readdirSync(e,{withFileTypes:!0}).flatMap(t=>{let n=a.join(e,t.name);if(t.isDirectory())return te(n);if(t.isFile())return[n];throw new Error(`Invalid bundle stage: symlink or special entry: ${n}`)})}function W(e){if(!e)throw new Error("Bundle stage directory unset");let t=ee(a.join(e,"package.json"));xt(t);for(let n of It)B(e,n,!0);for(let n of[...jt,...Tt(t)])B(e,n,!1);for(let n of A)te(a.join(e,n))}function M(e){let t=a.resolve(e);try{return u.realpathSync(t)}catch(n){if(n.code!=="ENOENT")throw n;return Ct(t)}}function Ct(e){return u.lstatSync(e,{throwIfNoEntry:!1})?.isSymbolicLink()?M(a.resolve(a.dirname(e),u.readlinkSync(e))):a.join(M(a.dirname(e)),a.basename(e))}function We(e,t){let n=a.relative(e,t);return n===""||!n.startsWith(`..${a.sep}`)&&n!==".."&&!a.isAbsolute(n)}function Ue(e){if(!e.stageDir||!e.installRoot)throw new Error("Bundle stage and install roots must be separate and set");let t=M(e.stageDir),n=M(e.installRoot);if(We(t,n)||We(n,t))throw new Error("Bundle stage and install roots overlap; separate roots are required");return{stageDir:t,installRoot:n}}function Xe(e){return JSON.stringify(Dt.map(t=>{let n=e[t];return Array.isArray(n)?[t,[...n].sort()]:n&&typeof n=="object"?[t,Object.entries(n).sort(([r],[i])=>r.localeCompare(i))]:[t,n??null]}))}function Ot(e,t){let n=e;for(;;){if(u.existsSync(a.join(n,"node_modules",t,"package.json")))return!0;let r=a.dirname(n);if(r===n)return!1;n=r}}function At(e,t,n){if(Xe(t)!==Xe(n))return"dependency closure changed";let i=Object.keys(t.dependencies??{}).find(o=>!Ot(e,o));return i?`installed dependency missing: ${i}`:null}function Nt(e){try{for(let t of A)B(e,t,!0);for(let t of Z)B(e,t,!1);return null}catch{return"installed bundle layout is incomplete or incompatible"}}function Pt(e,t){let n;try{n=ee(a.join(e,"package.json"))}catch{return"no readable installed manifest \u2014 full install required"}return n.cortexBundle!==!0||n.name!=="@cortex-agent/server"?"installed package is not a Cortex bundle \u2014 full install required":At(e,t,n)??Nt(e)}function Ge(e,t){return{name:t,source:a.join(e.stageDir,t),destination:a.join(e.installRoot,t),exclude:[]}}function ne(e){W(e.stageDir);let t=Ue(e),n=Pt(t.installRoot,ee(a.join(t.stageDir,"package.json"))),r=[...A,...Z.filter(i=>i!=="package.json")];return{...t,blocked:n,targets:n?[]:r.map(i=>Ge(t,i)),manifestSource:a.join(t.stageDir,"package.json"),manifestDestination:a.join(t.installRoot,"package.json")}}function Lt(e,t){return u.mkdirSync(a.join(t,"new")),u.mkdirSync(a.join(t,"old")),[...e.targets,Ge(e,"package.json")].map(n=>{let r=a.join(t,"new",n.name);return u.cpSync(n.source,r,{recursive:!0,dereference:!1,errorOnExist:!0,force:!1}),{destination:n.destination,staged:r,previous:a.join(t,"old",n.name),movedPrevious:!1,installedNew:!1}})}function Ft(e){u.renameSync(e.destination,e.previous),e.movedPrevious=!0,u.renameSync(e.staged,e.destination),e.installedNew=!0}function Bt(e){let t=[];for(let n of[...e].reverse())try{n.installedNew&&u.rmSync(n.destination,{recursive:!0,force:!0}),n.movedPrevious&&u.renameSync(n.previous,n.destination)}catch(r){t.push(r)}return t}function Mt(e,t,n){try{for(let r of e)Ft(r)}catch(r){let i=Bt(e);throw i.length?new AggregateError([r,...i],`Bundle rollback incomplete; backups retained at ${t}`):(u.rmSync(t,{recursive:!0,force:!0}),r)}try{u.rmSync(t,{recursive:!0,force:!0})}catch(r){n(`Bundle installed; backup cleanup failed at ${t}: ${r}`)}}function He(e,t=console.warn){if(e.blocked)throw new Error(`bundle install blocked: ${e.blocked}`);let n=ne(e);if(n.blocked)throw new Error(`bundle install blocked: ${n.blocked}`);let r=u.mkdtempSync(a.join(a.dirname(n.installRoot),".cortex-bundle-")),i;try{i=Lt(n,r)}catch(o){throw u.rmSync(r,{recursive:!0,force:!0}),o}return Mt(i,r,t),n.targets.map(o=>o.name)}function Wt(e,t){let n=t;for(;n!==e;){let r=u.lstatSync(n,{throwIfNoEntry:!1});if(r?.isSymbolicLink())throw new Error(`Source map destination is a symlink: ${n}`);if(r&&(n===t?!r.isFile():!r.isDirectory()))throw new Error(`Source map destination has incompatible type: ${n}`);n=a.dirname(n)}}function qe(e,t){W(e);let n=Ue({stageDir:e,installRoot:t}),i=A.flatMap(o=>te(a.join(n.stageDir,o))).filter(o=>o.endsWith(".map")).map(o=>{let c=a.join(n.installRoot,a.relative(n.stageDir,o));return Wt(n.installRoot,c),{destination:c,content:u.readFileSync(o)}});for(let{destination:o,content:c}of i)u.mkdirSync(a.dirname(o),{recursive:!0}),u.writeFileSync(o,c)}import{spawn as Xt}from"node:child_process";function Je(e,t,n,r){return new Promise(i=>{let o=`[${e} ${t.join(" ")}]`;r.info(`${o} cwd=${n.cwd}`);let c=Xt(e,t,{...n,stdio:["ignore","pipe","pipe"]});c.stdout?.on("data",ze(r,o,"out")),c.stderr?.on("data",ze(r,o,"err")),c.on("exit",f=>{r.info(`${o} exit=${f}`),i(f??1)}),c.on("error",f=>{r.error(`${o} spawn error: ${f.message}`),i(1)})})}function ze(e,t,n){return r=>{for(let i of r.toString("utf8").split(`
5
+ `))i.trim()&&e.info(`${t} ${n}: ${i}`)}}function re(e){let t=(r,i,o)=>({label:r,cmd:"npm",args:["run",o],cwd:i}),n=[t("server",e.repoDir,"build")];return e.uiContractDir&&n.push(t("ui-contract",e.uiContractDir,"build")),e.webDir?(n.push(t("web-typecheck",e.webDir,"typecheck")),[n,[t("web-bundle",e.webDir,"bundle")],[t("web-depcruise",e.webDir,"depcruise")]]):[n]}function ie(e,t=!0){let n=re(e).flat().map(r=>r.label);return t&&n.push("bundle"),[...n,"install","restart"]}async function Ut(e,t){for(let n of e){t.update(i=>S(i,n.label));let r=await t.run(n.cmd,n.args,{cwd:n.cwd});if(r!==0){let i=`exit ${r}`;return t.update(o=>b(o,n.label,"failed",i)),{label:n.label,detail:i}}t.update(i=>b(i,n.label,"done"))}return null}async function Ye(e){let t=re(e.dirs);t.flat().some(r=>r.label==="web-bundle")||e.log.warn("WEB_DIR not found \u2014 skipping web build, pack will use stale web/dist if present");let n=(await Promise.all(t.map(r=>Ut(r,e)))).filter(r=>r!==null);return n.length===0?!0:(e.abort(n.map(r=>r.label).join(", "),n.map(r=>r.detail).join(", ")),!1)}function Jt(e){return e.bundle?e.bundleBlocked===null?"bundle-fast":"bundle-full":"source"}var j=class extends Error{step;constructor(t,n){super(n),this.step=t}};function U(e){return e instanceof Error?e.message:String(e)}async function Ve(e){try{return await Ye(e)?await Yt(e):"finished"}catch(t){let n=t instanceof j?t.step:"install";return e.abort(n,U(t)),"finished"}}async function Yt(e){let t=e.bundle?Gt(k.join(Ke(),"cortex-rebuild-")):null;try{return await Kt(e,t?k.join(t,"stage"):null)}finally{t&&qt(t,{recursive:!0,force:!0})}}async function Kt(e,t){if(t&&await Vt(e,t),e.deferInstall())return"deferred";e.update(r=>S(r,"install"));let n=await Qt(e,t);return e.update(r=>b(r,"install","done",n)),e.log.info("Rebuild succeeded \u2014 restarting app.ts"),await e.restart(),"finished"}async function Vt(e,t){e.update(n=>S(n,"bundle"));try{await X(e,"bundle",process.execPath,["scripts/bundle.mjs",t,"--sourcemap"],e.dirs.repoDir),W(t),e.update(n=>b(n,"bundle","done"))}catch(n){throw new j("bundle",U(n))}}async function Qt(e,t){if(!t)return en(e);let n=ne({stageDir:t,installRoot:e.installRoot}),r=Jt({bundle:e.bundle,bundleBlocked:n.blocked});if(r==="bundle-fast"){let o=He(n,c=>e.log.warn(c));return e.log.info(`Bundle fast install: ${o.join(", ")}`),r}e.log.info(`Bundle fast install unavailable (${n.blocked}) \u2014 packing staged bundle`);let i=await tn(e,t);await Ze(e,i);try{qe(t,e.installRoot)}catch(o){e.log.warn(`Bundle installed without complete local source maps: ${U(o)} \u2014 restarting app.ts`)}return"bundle-full"}function Zt(e){let t=Be({repoDir:e.dirs.repoDir,monorepoRoot:k.dirname(e.dirs.repoDir),installRoot:e.installRoot});if(t.blocked)return e.log.info(`Fast install unavailable (${t.blocked}) \u2014 falling back to pack + install -g`),null;try{return Me(t)}catch(n){return e.log.warn(`Fast install failed (${U(n)}) \u2014 falling back to pack + install -g`),null}}async function en(e){let t=Zt(e);return t?(e.log.info(`Fast install: ${t.join(", ")}`),"fast"):(await X(e,"tgz cleanup","bash",["-c","rm -f cortex-agent-server-*.tgz"],e.dirs.repoDir),await X(e,"pack","npm",["pack"],e.dirs.repoDir),await Ze(e,Qe(e.dirs.repoDir)),"pack + install -g")}async function tn(e,t){return await X(e,"pack","npm",["pack","--ignore-scripts"],t),Qe(t)}function Qe(e){let t=Ht(e).filter(n=>n.startsWith("cortex-agent-server-")&&n.endsWith(".tgz")).map(n=>({file:n,mtime:zt(k.join(e,n)).mtimeMs})).sort((n,r)=>r.mtime-n.mtime);if(!t.length)throw new j("pack","npm pack succeeded but no cortex-agent-server-*.tgz found");return k.join(e,t[0].file)}async function Ze(e,t){e.log.info(`Packed tarball: ${t}`);let n=Ie(["install","-g",t],e.installRoot),r={...process.env,CORTEX_SKIP_POSTINSTALL_RESTART:"1"},i=await e.run("npm",n,{cwd:Ke(),env:r});if(i!==0)throw new j("install",`exit ${i}`)}async function X(e,t,n,r,i){let o=await e.run(n,r,{cwd:i});if(o!==0)throw new j(t,`exit ${o}`)}var it=new Set(Object.keys(process.env));V(p.join(Y,".env"));var sn=new Set(Object.keys(process.env).filter(e=>!it.has(e))),s=Re("daemon"),an=ke(new URL("dist/entry/daemon.js",__cortexPackageRoot).href),cn=p.join(an,"app.js"),C=p.join(Y,".env"),y=process.env.CORTEX_REPO??"",ot=process.env.CORTEX_REBUILD_BUNDLE!=="0",R=y?p.join(y,"src"):"",H=y?p.dirname(y):"",oe=H?p.join(H,"web"):"",se=H?p.join(H,"packages","ui-contract"):"",ln=800,un=2500,de=1e3,dn=3e4,fn=1e4,pn=["tests/","tmp/","node_modules/","dist/","vendor/"],mn=[".d.ts",".test.ts",".spec.ts"],h=null,st=0,I=de,D=null,$=null,N=null,q=!1,w=!1,m=null,g=null,G=!1,ae=!1,z=null,ce=null,at=[],O=null;function fe(){N&&(clearTimeout(N),N=null),D&&(clearTimeout(D),D=null),$&&(clearTimeout($),$=null)}function hn(e=process.env,t=C,n=it,r=sn){let i={...e},o={};V(t,o);for(let c of r)c in o||delete i[c];for(let[c,f]of Object.entries(o))n.has(c)||(i[c]=f);return i}function bn(e=null,t=null){let n=["pipe","ignore","ignore","ipc"],r=hn();return delete r.CORTEX_RESTART_REASON,delete r[Q],e&&(r.CORTEX_RESTART_REASON=e),t&&(r[Q]=t),{cwd:we,windowsHide:!0,stdio:n,execArgv:[],env:r}}function pe(){if(q)return;if(h){s.info("startChild called but child already running \u2014 skipping.");return}let e=z,t=ce;z=null,ce=null,s.info(e?`Starting app.ts (reason: ${e})...`:"Starting app.ts..."),st=Date.now(),w=!1,m=null,xe(),h=nn(cn,[],bn(e,t)),s.info(`app.ts started \u2014 PID ${h.pid}`);try{rn(T,String(h.pid),"utf8")}catch{}h.on("message",yn),h.on("exit",wn)}function gn(){w=!1;let e=m?` (pending restart: ${m.reason})`:g?` (pending rebuild: ${g})`:"";if(s.info(`IPC \u2190 app.ts: idle${e}`),m){let t=m;m=null,me(t.reason,{afterInstall:t.holdsTurns})}else if(g){let t=g;g=null,ft(t)}}function yn(e){e?.type==="busy"?(s.info("IPC \u2190 app.ts: busy"),w=!0):e?.type==="idle"&&gn()}function wn(e,t){h=null,w=!1;try{x(T)&&ue(T)}catch{}if(q){s.info("app.ts exited (shutdown).");return}if(G){t&&s.info(`app.ts stopped (signal ${t}).`);return}if(!Rn(e)){let n=$e();s.error(`app.ts stopped: ${n?.message??"the main port could not be bound"} Not restarting until the configuration changes.`);return}En(e,t)}function Rn(e){return e!==De}function En(e,t){let n=Date.now()-st;n>fn&&(I=de);let r=t?`crash (signal ${t})`:`crash (exit code ${e})`,i=Oe({code:e,signal:t,uptimeMs:n,backoffMs:I});s.info(t?`app.ts killed by signal ${t}.`:`app.ts exited with code ${e}.`),s.info(`Restarting in ${I}ms...`),fe(),N=setTimeout(()=>{N=null,z=r,ce=i,pe()},I),I=Math.min(I*2,dn)}function ct(){return new Promise(e=>{if(!h)return e();let t=h;s.info(`Stopping app.ts (PID ${t.pid})...`);let n=setTimeout(()=>{s.info("Force killing app.ts...");try{t.kill("SIGKILL")}catch{}},5e3);t.once("exit",()=>{clearTimeout(n),e()}),t.kill("SIGTERM")})}async function me(e,t={}){return w||G?(s.info(`Restart deferred (${w?"app.ts is busy":"already restarting"}): ${e}`),m=On(m,e,t.afterInstall===!0),m.holdsTurns&&le(!0,"restart",e),"deferred"):(fe(),s.info(`Restarting: ${e}`),I=de,G=!0,le(!0,"restart",e),await ct(),G=!1,m&&(s.info(`Absorbed deferred restart: ${m.reason}`),m=null),z=e,pe(),"restarted")}function Sn(e){for(let t of e.splice(0))try{t.close()}catch{}}function vn(e,t){let n=[],r=i=>{n.push(J(i,(c,f)=>t(c,f)));let o;try{o=on(i,{withFileTypes:!0})}catch{return}for(let c of o)c.isDirectory()&&(c.name.startsWith(".")||c.name==="node_modules"||r(p.join(i,c.name)))};try{r(e)}catch(i){throw Sn(n),i}return n}function kn(e){try{return x(e)&&rt(e).isDirectory()}catch{return!1}}function et(e){if(!e)return;let t=String(e).replace(/\\/g,"/");t.endsWith(".ts")&&(mn.some(n=>t.endsWith(n))||pn.some(n=>t.startsWith(n)||t.includes(`/${n}`))||he(`src change: ${t}`))}function jn(){if(!R||!kn(R)){let e=y?`CORTEX_REPO=${y} set but ${R} not a directory`:"CORTEX_REPO unset";return s.warn(`${e} \u2014 src watcher disabled, only .restart trigger available`),null}return F({label:`Source ${R}`,warn:e=>s.warn(e),startWatching:()=>{if(process.platform==="win32"){let t=vn(R,(n,r)=>et(r));return s.info(`Watching src: ${R} (per-directory, *.ts, ${t.length} dirs)`),t}let e=J(R,{recursive:!0},(t,n)=>et(n));return s.info(`Watching src: ${R} (recursive, *.ts)`),[e]}})}function tt(){if(x(E)){try{ue(E)}catch{}y?he("manual trigger (.restart file)"):lt("manual trigger (.restart file)")}}function In(){let e=p.dirname(E),t=p.basename(E);return F({label:`Restart trigger ${E}`,warn:n=>s.warn(n),startWatching:()=>{let n=J(e,(r,i)=>{i&&String(i)===t&&tt()});return s.info(`Watching for restart trigger: ${E}`),[n]},poll:tt})}function nt(e){try{let t=rt(e);return`${t.mtimeMs}:${t.size}`}catch{return null}}function Dn(e){let t=nt(e);return()=>{let n=nt(e);return n===t?!1:(t=n,!0)}}function $n(e,t,n){let r=J(e,(i,o)=>{o&&String(o)===t&&n()});return s.info(`Watching env file: ${C}`),[r]}function xn(){let e=p.dirname(C);if(!x(e))return null;let t=p.basename(C),n=Dn(C),r=()=>{n()&&lt("env change (.env)")};return F({label:`Environment file ${C}`,startWatching:()=>$n(e,t,r),poll:r,warn:i=>s.warn(i)})}function Tn(){let e=[In(),xn()],t=jn();return t&&e.push(t),e.filter(n=>n!==null)}function lt(e){D&&clearTimeout(D),D=setTimeout(()=>{D=null,me(e)},ln)}function he(e){$&&clearTimeout($),$=setTimeout(()=>{$=null,ft(e)},un)}function _n(e){return ve("notice.rebuild.aborted",{step:e.step,detail:e.detail,reason:e.reason})}function ut(e){if(!(!h||!h.connected))try{h.send(e)}catch{}}function le(e,t,n){ut({type:"rebuild-hold",hold:e,phase:t,reason:n})}function Cn(e,t){return t?!0:!e||e.status!=="running"?!1:e.current==="install"||e.current==="restart"}function On(e,t,n){return{reason:t,holdsTurns:n||(e?.holdsTurns??!1)}}function be(e){O=e,Ne(e);let t=m?.holdsTurns??!1;le(Cn(e,t),e.current??(t?"restart":null),e.reason)}function dt(){return{repoDir:y,uiContractDir:se&&x(se)?se:null,webDir:oe&&x(oe)?oe:null}}async function An(e){P(n=>S(n,"restart"));let t=await me(`src rebuild: ${e}`,{afterInstall:!0});P(n=>t==="restarted"?_(b(n,"restart","done"),"succeeded"):_(b(n,"restart","skipped","app.ts busy"),"deferred","Build and install succeeded; the restart is queued until app.ts goes idle."))}function P(e){O&&be(e(O))}function Nn(e){return e==="bundle"?"bundle":e==="install"||e==="pack"||e==="tgz cleanup"?"install":null}function Pn(e,t,n){Se(process.env.CORTEX_LANG?Ee(process.env.CORTEX_LANG):Ce());let r=_n({step:e,detail:t,reason:n});s.error(r);let i=Nn(e);P(o=>_(i?b(o,i,"failed",t):o,"aborted",r)),ut({type:"rebuild-aborted",text:r})}function Ln(e){return w||ae?(s.info(`Rebuild deferred (${w?"app.ts busy":"already rebuilding"}): ${e}`),g=e,!1):y?(ae=!0,!0):(s.error(`Rebuild requested but CORTEX_REPO unset \u2014 ignoring: ${e}`),!1)}function Fn(e){return w?(s.info(`Rebuild install deferred (app.ts busy): ${e} \u2014 retrying when app.ts goes idle`),g=e,P(t=>_(t,"deferred","Build finished; install and restart wait for app.ts to go idle.")),!0):!1}function Bn(e){return{dirs:dt(),installRoot:ye,bundle:ot,log:s,run:(t,n,r)=>Je(t,n,r,s),update:P,abort:(t,n)=>Pn(t,n,e),deferInstall:()=>Fn(e),restart:()=>An(e)}}async function ft(e){if(!Ln(e))return;let t=!1;try{s.info(`Rebuild pipeline starting: ${e}`),be(Ae({reason:e,names:ie(dt(),ot),daemonPid:process.pid})),t=await Ve(Bn(e))==="deferred"}finally{Mn(t)}}function Mn(e){if(O?.status==="running"&&be(_(O,"aborted","pipeline ended without restarting app.ts")),O=null,ae=!1,g&&!e){let t=g;g=null,s.info(`Consuming queued rebuild: ${t}`),he(t)}}function Wn(){for(let e of at.splice(0))e.close()}function Xn(){let e=async t=>{q||(q=!0,s.info(`Received ${t}, shutting down...`),fe(),Wn(),await ct(),s.info("Daemon stopped."),process.exit(0))};process.on("SIGINT",()=>e("SIGINT")),process.on("SIGTERM",()=>e("SIGTERM"))}function Un(){let e=Te(L);if(e.acquired){e.stale&&s.info(`Removed stale PID file and reclaimed lock for PID ${process.pid}`);return}s.error(`Another Cortex daemon is already running (PID ${e.holderPid}, lockfile ${L}).
6
+ Refusing to start a second instance \u2014 its app.ts already serves this home on its main port (CORTEX_UI_PORT).
7
+ To restart the running daemon: \`touch agent-server/.restart\` (hot reload), or send SIGTERM to PID ${e.holderPid} and rerun.`),process.exit(1)}function Gn(){_e(L);try{x(T)&&ue(T)}catch{}}function Hn(){let e=!1,t=(n,r)=>{if(!e){e=!0;try{s.error(`${n}: ${String(r)}`)}catch{}finally{e=!1}}};process.on("uncaughtException",n=>{t("uncaughtException",n?.stack??n),K("daemon","uncaughtException",n)}),process.on("unhandledRejection",n=>{t("unhandledRejection",n instanceof Error?n.stack:n),K("daemon","unhandledRejection",n)})}function qn(){Hn(),Un(),process.on("exit",Gn),s.info("Cortex Daemon starting..."),Pe(),Xn(),pe(),at=Tn()}je(new URL("dist/entry/daemon.js",__cortexPackageRoot).href)&&qn();export{bn as buildChildProcessConfig,_n as buildRebuildAbortNotice,hn as childEnv,re as planRebuildLanes,ie as planRebuildStepNames,On as queueRestart,Cn as rebuildHoldsTurns,Rn as restartsAfterExit,Dn as stampChangeDetector};
@@ -2,6 +2,6 @@
2
2
  import { createRequire as __cortexCreateRequire } from 'node:module';
3
3
  const require = __cortexCreateRequire(import.meta.url);
4
4
  const __cortexPackageRoot = new URL("../../", import.meta.url);
5
- import{a as x}from"../chunks/chunk-FOJQXLL2.js";import{a as p}from"../chunks/chunk-A34TDMIC.js";import{a as m}from"../chunks/chunk-YAEVYJAR.js";import{a as y,f as g,g as w,i as b}from"../chunks/chunk-3THJYAEF.js";import{a as k}from"../chunks/chunk-D3NXKK2L.js";import"../chunks/chunk-LCKVYFMD.js";import"../chunks/chunk-5M4PFLRW.js";import{a as O,b as u,c as S,d as E}from"../chunks/chunk-PMG4YGDU.js";import"../chunks/chunk-W5LGYSPZ.js";import"../chunks/chunk-E7ZMYIY6.js";import"../chunks/chunk-NAA7GF6Q.js";import{b as f}from"../chunks/chunk-QWAQHHRS.js";import"../chunks/chunk-J5DVLUKY.js";import"../chunks/chunk-WHC7AYZD.js";import*as _ from"node:fs";import*as N from"node:http";var v=["list","show","enable","disable","test","ask"],D={name:"cortex-hook",description:"Inspect, manage, and execute Cortex hook declarations",usage:"cortex-hook <command> [options]",commands:[{name:"list",description:"List registry hooks"},{name:"show --id <id>",description:"Show one complete hook declaration"},{name:"enable --id <id>",description:"Enable a registry hook"},{name:"disable --id <id>",description:"Disable a registry hook"},{name:"test --id <id>",description:"Execute one hook with a payload"},{name:"ask --question <text>",description:"Ask the user a card question and block for the answer"}],options:[{flag:"--help, -h",description:"Show this help"}],examples:[{description:"List mounted declarations",command:"cortex-hook list"},{description:"Inspect one declaration",command:"cortex-hook show --id status-md-guard"},{description:"Execute with a payload file",command:"cortex-hook test --id status-md-guard --payload payload.json"},{description:"Ask the user from a hook",command:'cortex-hook ask --question "Clean old checkpoints?" --options "Clean|Keep" --level warning'}]},P={list:{name:"cortex-hook list",description:"List every registry hook declaration",usage:"cortex-hook list",options:[{flag:"--help, -h",description:"Show this help"}],examples:[{description:"List hooks as JSON",command:"cortex-hook list"}]},show:{name:"cortex-hook show",description:"Show one complete hook declaration",usage:"cortex-hook show --id <id>",options:[{flag:"--id <id>",description:"Hook id from cortex-hook list"},{flag:"--help, -h",description:"Show this help"}],examples:[{description:"Show a hook",command:"cortex-hook show --id status-md-guard"}]},enable:{name:"cortex-hook enable",description:"Enable one registry hook idempotently",usage:"cortex-hook enable --id <id> [--dry-run]",options:[{flag:"--id <id>",description:"Registry hook id"},{flag:"--dry-run",description:"Validate and preview without writing",default:"false"},{flag:"--help, -h",description:"Show this help"}],examples:[{description:"Preview enabling a hook",command:"cortex-hook enable --id status-md-guard --dry-run"},{description:"Enable a hook",command:"cortex-hook enable --id status-md-guard"}]},disable:{name:"cortex-hook disable",description:"Disable one registry hook idempotently",usage:"cortex-hook disable --id <id> [--dry-run]",options:[{flag:"--id <id>",description:"Registry hook id"},{flag:"--dry-run",description:"Validate and preview without writing",default:"false"},{flag:"--help, -h",description:"Show this help"}],examples:[{description:"Preview disabling a hook",command:"cortex-hook disable --id status-md-guard --dry-run"},{description:"Disable a hook",command:"cortex-hook disable --id status-md-guard"}]},test:{name:"cortex-hook test",description:"Execute one hook once with payload bytes delivered on stdin",usage:"cortex-hook test --id <id> --payload <file|->",options:[{flag:"--id <id>",description:"Hook id from cortex-hook list"},{flag:"--payload <file|->",description:"Payload file, or - to read stdin"},{flag:"--help, -h",description:"Show this help"}],examples:[{description:"Execute with a file",command:"cortex-hook test --id status-md-guard --payload payload.json"},{description:"Execute from stdin",command:"cat payload.json | cortex-hook test --id status-md-guard --payload -"}]},ask:{name:"cortex-hook ask",description:"Post an ask-user card on the session message platform and block until answered",usage:'cortex-hook ask --question <text> [--options "a|b"] [--level <level>] [--channel <id> | --session-id <id>]',options:[{flag:"--question <text>",description:"Single question text (or use --payload)"},{flag:"--header <text>",description:"Short card label (default: question prefix)"},{flag:'--options "a|b|c"',description:"Pipe-separated choice labels"},{flag:"--multi",description:"Allow selecting multiple options",default:"false"},{flag:"--level <level>",description:"Card severity: info, warn, warning, error"},{flag:"--channel <id>",description:"Target conduit (default: CORTEX_HOOK_CHANNEL / SLACK_CHANNEL)"},{flag:"--session-id <id>",description:"Resolve channel from a session (default: CORTEX_HOOK_SESSION_ID)"},{flag:"--payload <file|->",description:"JSON array of question objects, or - for stdin"},{flag:"--dry-run",description:"Smoke-test: journal only, resolve synthetically",default:"false"},{flag:"--help, -h",description:"Show this help"}],examples:[{description:"Warning card with choices",command:'cortex-hook ask --question "Disk almost full - clean old checkpoints?" --options "Clean|Keep" --level warning'},{description:"Multi-question payload from stdin",command:"cat questions.json | cortex-hook ask --payload - --session-id abc123"}]}},I={list:["--help","-h"],show:["--id","--help","-h"],enable:["--id","--dry-run","--help","-h"],disable:["--id","--dry-run","--help","-h"],test:["--id","--payload","--help","-h"],ask:["--question","--header","--options","--multi","--level","--channel","--session-id","--payload","--dry-run","--help","-h"]},C={"--id":"id","--payload":"payload","--question":"question","--header":"header","--options":"options","--level":"level","--channel":"channel","--session-id":"sessionId"},T={"--dry-run":"dryRun","--multi":"multi","--help":"help","-h":"help"};function d(o,e=0){return{exitCode:e,stdout:JSON.stringify(o,null,2),stderr:""}}function H(o){return{exitCode:1,stdout:"",stderr:o}}function r(o,e,t){return E(u(o,{validValues:e,hint:t}))}function K(o){return{registryDirs:o.registryDirs??y(),scriptDirs:o.scriptDirs??k(),askPost:o.askPost??B}}function A(o,e=!1){return{command:o,id:null,payload:null,question:null,header:null,options:null,level:null,channel:null,sessionId:null,multi:!1,dryRun:!1,help:e}}function $(o){if(o.length===0||o[0]==="--help"||o[0]==="-h")return A(null,!0);if(!v.includes(o[0]))throw r(`Unknown command: '${o[0]}'`,[...v]);return null}function J(o,e){let t=A(o),i=I[o];for(let s=0;s<e.length;s+=1){let n=e[s];if(!i.includes(n))throw r(`Unknown argument: '${n}'`,i);if(Object.hasOwn(C,n)){let a=e[s+1];if(!a||a.startsWith("--"))throw r(`${n} requires a value`);t[C[n]]=a,s+=1}else t[T[n]]=!0}return t}function j(o){if(!(o.help||o.command==="list"||o.command===null)){if(o.command==="ask"){if(!o.question&&!o.payload)throw r("ask requires --question or --payload",["--question <text>","--payload <file|->"]);return}if(!o.id)throw r("--id is required",["--id <id>"]);if(o.command==="test"&&!o.payload)throw r("--payload is required for test",["--payload <file>","--payload -"])}}function M(o){let e=$(o);if(e)return e;let t=J(o[0],o.slice(1));return j(t),t}function h(o,e){let t=e.find(i=>i.id===o);if(!t)throw r(`Unknown hook id: '${o}'`,e.map(i=>i.id));return t}function X(o){return{...o.entry,enabled:o.enabled,source:o.source}}function q(o,e,t,i){let s={ok:!0,id:o.id,enabled:e,changed:t,dry_run:i,source:o.source,timestamp:new Date().toISOString()};return i&&(s.would_set={enabled:e}),s}function F(o,e){let t=h(o.parsed.id,o.hooks);if(o.parsed.dryRun)return d(q(t,e,t.enabled!==e,!0));let{changed:i}=x(o.options.registryDirs,t.id,e);return d(q(t,e,i,!1))}function L(o){if(o==="-")return S();try{return _.readFileSync(o,"utf8")}catch(e){let t=e instanceof Error?e.message:String(e);throw r(`Cannot read --payload file '${o}': ${t}`,["existing file path","-"])}}async function W(o){let e=h(o.parsed.id,o.hooks),t=L(o.parsed.payload),i=await m(b(e,o.options.scriptDirs,t)),s={ok:i.exitCode===0&&!i.error,id:e.id,exit_code:i.exitCode,stdout:i.stdout,stderr:i.stderr};return i.error&&(s.error=i.error),d(s,i.exitCode??(i.error?1:0))}function B(o,e,t){let i=JSON.stringify(e);return new Promise((s,n)=>{let a=N.request(o,{method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(i),...t},timeout:36e5},l=>{let c="";l.on("data",R=>{c+=R}),l.on("end",()=>{try{s({status:l.statusCode??0,body:JSON.parse(c)})}catch{n(new Error(`invalid webhook response: ${c}`))}})});a.on("error",n),a.on("timeout",()=>{a.destroy(),n(new Error("webhook request timed out"))}),a.write(i),a.end()})}function U(o){if(o.payload){let t=L(o.payload),i;try{i=JSON.parse(t)}catch(s){throw r(`--payload is not valid JSON: ${s.message}`,["JSON array of question objects"])}if(!Array.isArray(i)||i.length===0)throw r("--payload must be a non-empty JSON array of question objects");return i}let e=o.question;return[{question:e,header:o.header??e.slice(0,12),multiSelect:o.multi,options:o.options?o.options.split("|").map(t=>({label:t.trim()})):[]}]}function V(o,e){let t=o.channel??process.env.CORTEX_HOOK_CHANNEL??process.env.SLACK_CHANNEL??null,i=o.sessionId??process.env.CORTEX_HOOK_SESSION_ID??null;if(!t&&!i)throw r("No target: no channel or session in flags or hook env",["--channel <id>","--session-id <id>"],"Hook environments set CORTEX_HOOK_CHANNEL / SLACK_CHANNEL / CORTEX_HOOK_SESSION_ID automatically");let s=o.level===null?null:p(o.level);if(o.level!==null&&!s)throw r(`Invalid --level: '${o.level}'`,["info","warn","warning","error"]);return{...t?{channel:t}:{},...i?{sessionId:i}:{},questions:e,...s?{level:s}:{},...o.dryRun?{dryRun:!0}:{}}}function z(o){if(o.status!==200)return H(u(`Webhook returned status ${o.status}: ${o.body?.error??JSON.stringify(o.body??{})}`));if(o.body?.error){let e=o.body.error==="timeout";return d({ok:!1,error:o.body.error,...e?{answers:{}}:{}},e?2:1)}return o.body?.dryRun?d({ok:!0,dry_run:!0,answers:{}}):d({ok:!0,answers:o.body?.answers??{}})}async function G(o){let e=U(o.parsed),t=V(o.parsed,e),s=`http://127.0.0.1:${parseInt(process.env.WEBHOOK_PORT||"3001",10)}/hook/ask-user-question`,n={"x-cortex-token":process.env.CORTEX_WEBHOOK_TOKEN||""};return z(await o.options.askPost(s,t,n))}async function Q(o){let e=o.parsed.command;return e==="list"?d({ok:!0,hooks:o.hooks.map(w)}):e==="show"?d({ok:!0,hook:X(h(o.parsed.id,o.hooks))}):e==="enable"||e==="disable"?F(o,e==="enable"):e==="ask"?G(o):W(o)}async function Y(o,e={}){try{let t=M(o);if(t.help){let n=t.command===null?D:P[t.command];return{exitCode:0,stdout:O(n),stderr:""}}let i=K(e),s=g(i.registryDirs);return await Q({parsed:t,hooks:s,options:i})}catch(t){return H(t instanceof Error?t.message:String(t))}}async function Z(o=process.argv.slice(2)){let e=await Y(o);e.stdout&&process.stdout.write(`${e.stdout}
5
+ import{a as S}from"../chunks/chunk-QC66ZXPP.js";import{a as p}from"../chunks/chunk-5LBLRAHS.js";import{a as m}from"../chunks/chunk-IWY2HIFK.js";import{a as g,f as w,g as b,i as x}from"../chunks/chunk-PG7452XE.js";import{b as k}from"../chunks/chunk-RW2F2QNP.js";import"../chunks/chunk-LCKVYFMD.js";import"../chunks/chunk-5M4PFLRW.js";import{i as y}from"../chunks/chunk-BVEDNESB.js";import{a as O,b as u,c as E,d as v}from"../chunks/chunk-PMG4YGDU.js";import"../chunks/chunk-TRXLIL7V.js";import"../chunks/chunk-7GGPYU5E.js";import"../chunks/chunk-7W7VYUTK.js";import{b as f}from"../chunks/chunk-JGUEIW2W.js";import"../chunks/chunk-T54CZKNJ.js";import"../chunks/chunk-WHC7AYZD.js";import*as N from"node:fs";import*as H from"node:http";var C=["list","show","enable","disable","test","ask"],P={name:"cortex-hook",description:"Inspect, manage, and execute Cortex hook declarations",usage:"cortex-hook <command> [options]",commands:[{name:"list",description:"List registry hooks"},{name:"show --id <id>",description:"Show one complete hook declaration"},{name:"enable --id <id>",description:"Enable a registry hook"},{name:"disable --id <id>",description:"Disable a registry hook"},{name:"test --id <id>",description:"Execute one hook with a payload"},{name:"ask --question <text>",description:"Ask the user a card question and block for the answer"}],options:[{flag:"--help, -h",description:"Show this help"}],examples:[{description:"List mounted declarations",command:"cortex-hook list"},{description:"Inspect one declaration",command:"cortex-hook show --id status-md-guard"},{description:"Execute with a payload file",command:"cortex-hook test --id status-md-guard --payload payload.json"},{description:"Ask the user from a hook",command:'cortex-hook ask --question "Clean old checkpoints?" --options "Clean|Keep" --level warning'}]},I={list:{name:"cortex-hook list",description:"List every registry hook declaration",usage:"cortex-hook list",options:[{flag:"--help, -h",description:"Show this help"}],examples:[{description:"List hooks as JSON",command:"cortex-hook list"}]},show:{name:"cortex-hook show",description:"Show one complete hook declaration",usage:"cortex-hook show --id <id>",options:[{flag:"--id <id>",description:"Hook id from cortex-hook list"},{flag:"--help, -h",description:"Show this help"}],examples:[{description:"Show a hook",command:"cortex-hook show --id status-md-guard"}]},enable:{name:"cortex-hook enable",description:"Enable one registry hook idempotently",usage:"cortex-hook enable --id <id> [--dry-run]",options:[{flag:"--id <id>",description:"Registry hook id"},{flag:"--dry-run",description:"Validate and preview without writing",default:"false"},{flag:"--help, -h",description:"Show this help"}],examples:[{description:"Preview enabling a hook",command:"cortex-hook enable --id status-md-guard --dry-run"},{description:"Enable a hook",command:"cortex-hook enable --id status-md-guard"}]},disable:{name:"cortex-hook disable",description:"Disable one registry hook idempotently",usage:"cortex-hook disable --id <id> [--dry-run]",options:[{flag:"--id <id>",description:"Registry hook id"},{flag:"--dry-run",description:"Validate and preview without writing",default:"false"},{flag:"--help, -h",description:"Show this help"}],examples:[{description:"Preview disabling a hook",command:"cortex-hook disable --id status-md-guard --dry-run"},{description:"Disable a hook",command:"cortex-hook disable --id status-md-guard"}]},test:{name:"cortex-hook test",description:"Execute one hook once with payload bytes delivered on stdin",usage:"cortex-hook test --id <id> --payload <file|->",options:[{flag:"--id <id>",description:"Hook id from cortex-hook list"},{flag:"--payload <file|->",description:"Payload file, or - to read stdin"},{flag:"--help, -h",description:"Show this help"}],examples:[{description:"Execute with a file",command:"cortex-hook test --id status-md-guard --payload payload.json"},{description:"Execute from stdin",command:"cat payload.json | cortex-hook test --id status-md-guard --payload -"}]},ask:{name:"cortex-hook ask",description:"Post an ask-user card on the session message platform and block until answered",usage:'cortex-hook ask --question <text> [--options "a|b"] [--level <level>] [--channel <id> | --session-id <id>]',options:[{flag:"--question <text>",description:"Single question text (or use --payload)"},{flag:"--header <text>",description:"Short card label (default: question prefix)"},{flag:'--options "a|b|c"',description:"Pipe-separated choice labels"},{flag:"--multi",description:"Allow selecting multiple options",default:"false"},{flag:"--level <level>",description:"Card severity: info, warn, warning, error"},{flag:"--channel <id>",description:"Target conduit (default: CORTEX_HOOK_CHANNEL / SLACK_CHANNEL)"},{flag:"--session-id <id>",description:"Resolve channel from a session (default: CORTEX_HOOK_SESSION_ID)"},{flag:"--payload <file|->",description:"JSON array of question objects, or - for stdin"},{flag:"--dry-run",description:"Smoke-test: journal only, resolve synthetically",default:"false"},{flag:"--help, -h",description:"Show this help"}],examples:[{description:"Warning card with choices",command:'cortex-hook ask --question "Disk almost full - clean old checkpoints?" --options "Clean|Keep" --level warning'},{description:"Multi-question payload from stdin",command:"cat questions.json | cortex-hook ask --payload - --session-id abc123"}]}},T={list:["--help","-h"],show:["--id","--help","-h"],enable:["--id","--dry-run","--help","-h"],disable:["--id","--dry-run","--help","-h"],test:["--id","--payload","--help","-h"],ask:["--question","--header","--options","--multi","--level","--channel","--session-id","--payload","--dry-run","--help","-h"]},q={"--id":"id","--payload":"payload","--question":"question","--header":"header","--options":"options","--level":"level","--channel":"channel","--session-id":"sessionId"},$={"--dry-run":"dryRun","--multi":"multi","--help":"help","-h":"help"};function d(o,e=0){return{exitCode:e,stdout:JSON.stringify(o,null,2),stderr:""}}function A(o){return{exitCode:1,stdout:"",stderr:o}}function r(o,e,t){return v(u(o,{validValues:e,hint:t}))}function K(o){return{registryDirs:o.registryDirs??g(),scriptDirs:o.scriptDirs??k(),askPost:o.askPost??B}}function L(o,e=!1){return{command:o,id:null,payload:null,question:null,header:null,options:null,level:null,channel:null,sessionId:null,multi:!1,dryRun:!1,help:e}}function J(o){if(o.length===0||o[0]==="--help"||o[0]==="-h")return L(null,!0);if(!C.includes(o[0]))throw r(`Unknown command: '${o[0]}'`,[...C]);return null}function j(o,e){let t=L(o),i=T[o];for(let n=0;n<e.length;n+=1){let s=e[n];if(!i.includes(s))throw r(`Unknown argument: '${s}'`,i);if(Object.hasOwn(q,s)){let a=e[n+1];if(!a||a.startsWith("--"))throw r(`${s} requires a value`);t[q[s]]=a,n+=1}else t[$[s]]=!0}return t}function M(o){if(!(o.help||o.command==="list"||o.command===null)){if(o.command==="ask"){if(!o.question&&!o.payload)throw r("ask requires --question or --payload",["--question <text>","--payload <file|->"]);return}if(!o.id)throw r("--id is required",["--id <id>"]);if(o.command==="test"&&!o.payload)throw r("--payload is required for test",["--payload <file>","--payload -"])}}function X(o){let e=J(o);if(e)return e;let t=j(o[0],o.slice(1));return M(t),t}function h(o,e){let t=e.find(i=>i.id===o);if(!t)throw r(`Unknown hook id: '${o}'`,e.map(i=>i.id));return t}function F(o){return{...o.entry,enabled:o.enabled,source:o.source}}function _(o,e,t,i){let n={ok:!0,id:o.id,enabled:e,changed:t,dry_run:i,source:o.source,timestamp:new Date().toISOString()};return i&&(n.would_set={enabled:e}),n}function U(o,e){let t=h(o.parsed.id,o.hooks);if(o.parsed.dryRun)return d(_(t,e,t.enabled!==e,!0));let{changed:i}=S(o.options.registryDirs,t.id,e);return d(_(t,e,i,!1))}function R(o){if(o==="-")return E();try{return N.readFileSync(o,"utf8")}catch(e){let t=e instanceof Error?e.message:String(e);throw r(`Cannot read --payload file '${o}': ${t}`,["existing file path","-"])}}async function W(o){let e=h(o.parsed.id,o.hooks),t=R(o.parsed.payload),i=await m(x(e,o.options.scriptDirs,t)),n={ok:i.exitCode===0&&!i.error,id:e.id,exit_code:i.exitCode,stdout:i.stdout,stderr:i.stderr};return i.error&&(n.error=i.error),d(n,i.exitCode??(i.error?1:0))}function B(o,e,t){let i=JSON.stringify(e);return new Promise((n,s)=>{let a=H.request(o,{method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(i),...t},timeout:36e5},l=>{let c="";l.on("data",D=>{c+=D}),l.on("end",()=>{try{n({status:l.statusCode??0,body:JSON.parse(c)})}catch{s(new Error(`invalid webhook response: ${c}`))}})});a.on("error",s),a.on("timeout",()=>{a.destroy(),s(new Error("webhook request timed out"))}),a.write(i),a.end()})}function V(o){if(o.payload){let t=R(o.payload),i;try{i=JSON.parse(t)}catch(n){throw r(`--payload is not valid JSON: ${n.message}`,["JSON array of question objects"])}if(!Array.isArray(i)||i.length===0)throw r("--payload must be a non-empty JSON array of question objects");return i}let e=o.question;return[{question:e,header:o.header??e.slice(0,12),multiSelect:o.multi,options:o.options?o.options.split("|").map(t=>({label:t.trim()})):[]}]}function z(o,e){let t=o.channel??process.env.CORTEX_HOOK_CHANNEL??process.env.SLACK_CHANNEL??null,i=o.sessionId??process.env.CORTEX_HOOK_SESSION_ID??null;if(!t&&!i)throw r("No target: no channel or session in flags or hook env",["--channel <id>","--session-id <id>"],"Hook environments set CORTEX_HOOK_CHANNEL / SLACK_CHANNEL / CORTEX_HOOK_SESSION_ID automatically");let n=o.level===null?null:p(o.level);if(o.level!==null&&!n)throw r(`Invalid --level: '${o.level}'`,["info","warn","warning","error"]);return{...t?{channel:t}:{},...i?{sessionId:i}:{},questions:e,...n?{level:n}:{},...o.dryRun?{dryRun:!0}:{}}}function G(o){if(o.status!==200)return A(u(`Webhook returned status ${o.status}: ${o.body?.error??JSON.stringify(o.body??{})}`));if(o.body?.error){let e=o.body.error==="timeout";return d({ok:!1,error:o.body.error,...e?{answers:{}}:{}},e?2:1)}return o.body?.dryRun?d({ok:!0,dry_run:!0,answers:{}}):d({ok:!0,answers:o.body?.answers??{}})}async function Q(o){let e=V(o.parsed),t=z(o.parsed,e),i=`${y()}/hook/ask-user-question`,n={"x-cortex-token":process.env.CORTEX_WEBHOOK_TOKEN||""};return G(await o.options.askPost(i,t,n))}async function Y(o){let e=o.parsed.command;return e==="list"?d({ok:!0,hooks:o.hooks.map(b)}):e==="show"?d({ok:!0,hook:F(h(o.parsed.id,o.hooks))}):e==="enable"||e==="disable"?U(o,e==="enable"):e==="ask"?Q(o):W(o)}async function Z(o,e={}){try{let t=X(o);if(t.help){let s=t.command===null?P:I[t.command];return{exitCode:0,stdout:O(s),stderr:""}}let i=K(e),n=w(i.registryDirs);return await Y({parsed:t,hooks:n,options:i})}catch(t){return A(t instanceof Error?t.message:String(t))}}async function oo(o=process.argv.slice(2)){let e=await Z(o);e.stdout&&process.stdout.write(`${e.stdout}
6
6
  `),e.stderr&&process.stderr.write(`${e.stderr}
7
- `),process.exitCode=e.exitCode}f(new URL("dist/entry/hook-cli.js",__cortexPackageRoot).href)&&Z();export{Z as main,Y as runHookCli};
7
+ `),process.exitCode=e.exitCode}f(new URL("dist/entry/hook-cli.js",__cortexPackageRoot).href)&&oo();export{oo as main,Z as runHookCli};
@@ -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{b as n}from"../chunks/chunk-QWAQHHRS.js";import"../chunks/chunk-J5DVLUKY.js";import"../chunks/chunk-WHC7AYZD.js";import i from"node:fs";import s from"node:path";function c(o){let e=JSON.parse(o),t=e&&typeof e=="object"?Object.keys(e).sort():[];if(!(t.length===2&&t[0]==="clientToken"&&t[1]==="webhookToken"&&typeof e.clientToken=="string"&&/^[0-9a-f]{64}$/.test(e.clientToken)&&typeof e.webhookToken=="string"&&/^[0-9a-f]{64}$/.test(e.webhookToken)&&e.clientToken!==e.webhookToken))throw new Error("production server auth file is invalid");return e}function a(o,e=process.env){if(!s.isAbsolute(o))throw new Error("production server auth path must be absolute");let t;try{t=i.readFileSync(o,"utf8")}finally{i.rmSync(o,{force:!0})}let r=c(t);e.CORTEX_CLIENT_TOKEN=r.clientToken,e.CORTEX_WEBHOOK_TOKEN=r.webhookToken,delete e.CORTEX_PRODUCTION_AUTH_FILE}async function T(){let o=process.env.CORTEX_PRODUCTION_AUTH_FILE;if(!o)throw new Error("CORTEX_PRODUCTION_AUTH_FILE is required");a(o),await import("./app.js")}n(new URL("dist/entry/production-app-bootstrap.js",__cortexPackageRoot).href)&&T().catch(o=>{process.stderr.write(`${o.stack??String(o)}
4
+ import{b as n}from"../chunks/chunk-JGUEIW2W.js";import"../chunks/chunk-T54CZKNJ.js";import"../chunks/chunk-WHC7AYZD.js";import i from"node:fs";import s from"node:path";function c(o){let e=JSON.parse(o),t=e&&typeof e=="object"?Object.keys(e).sort():[];if(!(t.length===2&&t[0]==="clientToken"&&t[1]==="webhookToken"&&typeof e.clientToken=="string"&&/^[0-9a-f]{64}$/.test(e.clientToken)&&typeof e.webhookToken=="string"&&/^[0-9a-f]{64}$/.test(e.webhookToken)&&e.clientToken!==e.webhookToken))throw new Error("production server auth file is invalid");return e}function a(o,e=process.env){if(!s.isAbsolute(o))throw new Error("production server auth path must be absolute");let t;try{t=i.readFileSync(o,"utf8")}finally{i.rmSync(o,{force:!0})}let r=c(t);e.CORTEX_CLIENT_TOKEN=r.clientToken,e.CORTEX_WEBHOOK_TOKEN=r.webhookToken,delete e.CORTEX_PRODUCTION_AUTH_FILE}async function T(){let o=process.env.CORTEX_PRODUCTION_AUTH_FILE;if(!o)throw new Error("CORTEX_PRODUCTION_AUTH_FILE is required");a(o),await import("./app.js")}n(new URL("dist/entry/production-app-bootstrap.js",__cortexPackageRoot).href)&&T().catch(o=>{process.stderr.write(`${o.stack??String(o)}
5
5
  `),process.exitCode=1});export{a as consumeProductionServerAuth};
@@ -2,7 +2,7 @@
2
2
  import { createRequire as __cortexCreateRequire } from 'node:module';
3
3
  const require = __cortexCreateRequire(import.meta.url);
4
4
  const __cortexPackageRoot = new URL("../../", import.meta.url);
5
- import{r as b,t as pt,u as mt,w as ft}from"../chunks/chunk-EQITBTJC.js";import{a as G}from"../chunks/chunk-UD3NMUHR.js";import{h as A}from"../chunks/chunk-LEUENXI2.js";import"../chunks/chunk-HALUQ7ZF.js";import"../chunks/chunk-3THJYAEF.js";import"../chunks/chunk-D3NXKK2L.js";import"../chunks/chunk-OE4KH3NJ.js";import"../chunks/chunk-5M4PFLRW.js";import{a as ht,b as yt,c as gt}from"../chunks/chunk-PMG4YGDU.js";import"../chunks/chunk-Q4UGYGU5.js";import"../chunks/chunk-W5LGYSPZ.js";import"../chunks/chunk-E7ZMYIY6.js";import{c as _t}from"../chunks/chunk-NAA7GF6Q.js";import{b as lt}from"../chunks/chunk-QWAQHHRS.js";import"../chunks/chunk-J5DVLUKY.js";import"../chunks/chunk-WHC7AYZD.js";import Yn from"node:fs";import Vn from"node:path";import{createHash as qn,randomUUID as Un}from"node:crypto";import p from"node:fs";import m from"node:path";import{spawnSync as Ln}from"node:child_process";import{createHash as fn}from"node:crypto";function S(t){throw new Error(`malformed_fragment:${t}`)}function le(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function z(t){return t.event.type}function pe(t,e){let n=[],o=[],r=e,s=e;for(;r<t.length&&z(t[r])!=="tool_result";){if(z(t[r])==="tool_use"){n.push(...o,t[r]),o=[],r+=1,s=r;continue}o.push(t[r]),r+=1}return{records:n,next:s}}function me(t,e,n,o){let r=[],s=new Set(n),a=new Set([...n].filter(d=>o.has(d))),c=e;for(;c<t.length&&s.size>0;){let d=t[c],u=d.event;u.type==="tool_result"&&(n.has(u.toolUseId)?(s.delete(u.toolUseId),a.delete(u.toolUseId)):a.size===0&&S("unpaired_tool_result")),r.push(d),c+=1}return a.size>0&&S("unclosed_subagent_span"),{records:r,next:c}}function fe(t,e,n){let o=pe(t,e),r=o.records.flatMap(u=>u.event.type==="tool_use"?[u.event.toolUseId]:[]),s=new Set(r);s.size!==r.length&&S("duplicate_tool_call_id");let a=me(t,o.next,s,n),c=a.records.flatMap(u=>u.event.type==="tool_result"?[u.event.toolUseId]:[]);new Set(c).size!==c.length&&S("duplicate_tool_result");let d=[...s,...a.records.flatMap(u=>u.event.type==="tool_use"?[u.event.toolUseId]:[])];return new Set(d).size!==d.length&&S("duplicate_tool_call_id"),{group:{records:[...o.records,...a.records]},next:a.next}}function he(t){return new Set(t.flatMap(e=>e.event.type==="subagent_activity"?[e.event.parentToolUseId]:[]))}function ye(t){let e=[],n=he(t),o=0;for(;o<t.length;){let r=z(t[o]);if(r==="tool_result"&&S("unpaired_tool_result"),r!=="tool_use"){e.push({records:[t[o]]}),o+=1;continue}let s=fe(t,o,n);e.push(s.group),o=s.next}return e}function ge(t){return le(t)?t:{value:t}}function be(t){return t.records.flatMap(e=>{let n=e.event;return n.type!=="tool_use"?[]:[{tool_call_id:n.toolUseId,function_name:n.name,arguments:ge(n.input)}]})}function xe(t){return t.records.flatMap(e=>{let n=e.event;return n.type!=="tool_result"?[]:[{source_call_id:n.toolUseId,content:n.content,subagent_trajectory_ref:null,extra:{ok:n.ok}}]})}function ve(t){if(t.records.length===1){let e=t.records[0].event;if(e.type==="assistant_text"||e.type==="assistant_delta")return e.text}return JSON.stringify(t.records.map(e=>e.event))}function Ee(t,e){let n=t.records[0],o=be(t),r=xe(t);return{step_id:e,timestamp:n.ts,source:"agent",model_name:n.reported_model,message:ve(t),reasoning_content:null,...o.length>0?{tool_calls:o}:{},...r.length>0?{observation:{results:r}}:{},extra:{source_events:t.records}}}function ke(t){return{name:`cortex-${t.header.agent_slot}`,version:t.header.bundle_manifest_hash,model_name:t.events[0]?.requested_model??null,extra:{agent_slot:t.header.agent_slot,model_execution_identity_hash:t.header.model_execution_identity_hash,role_tool_surface_hash:t.header.role_tool_surface_hash,bundle_manifest_hash:t.header.bundle_manifest_hash,journal_schema_version:t.header.schema_version}}}function Se(t){return{root_run_id:t.header.root_run_id,session_id:t.header.session_id,agent_slot:t.header.agent_slot,resolved_cwd:t.header.resolved_cwd,model_execution_identity_hash:t.header.model_execution_identity_hash,role_tool_surface_hash:t.header.role_tool_surface_hash,bundle_manifest_hash:t.header.bundle_manifest_hash,journal_sha256:t.terminal.journal_sha256,terminal:{state:t.terminal.state,terminal_reason:t.terminal.terminal_reason}}}function je(t){let e=String(t.terminal.state),n=String(t.terminal.terminal_reason);return{step_id:1,timestamp:t.terminal.ended_at,source:"system",message:`Terminal state ${e}; reason ${n}`,extra:{synthesized_from:"terminal_manifest"}}}function Ae(t){return t.events.length===0?[je(t)]:ye(t.events).map((e,n)=>Ee(e,n+1))}function bt(t){let e=t.fragment,n={schema_version:"ATIF-v1.7",trajectory_id:e.header.session_id,agent:ke(e),steps:Ae(e),extra:Se(e)};return t.children.length>0&&(n.subagent_trajectories=t.children.map(bt)),n}function xt(t){let e=bt(t);return e.extra.subagent_link_source="explicit",e.extra.final_metrics_status="unavailable",e}import Y from"node:path";var kt="cortex-bench-manifest/2",Ie=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/,Ne=/^[a-f0-9]{64}$/,Te=["model_execution_identity_hash","role_tool_surface_hash","bundle_manifest_hash"],we=["schema_version","state","started_at","ended_at","journal_path","journal_sha256","event_count","steps","cost_usd","tokens",...Te,"terminal_reason"],St={completed:["ok"],failed:["child_failure","trajectory_write_failed","containment_failure","rate_limited","protocol_violation","step_limit_exceeded","cost_limit_exceeded","provider_error"],cancelled:["cancelled"],timeout:["deadline","deadline_exceeded"],aborted:["aborted"]};function jt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function At(t,e){let n=new Set(e);return e.every(o=>Object.hasOwn(t,o))&&Object.keys(t).every(o=>n.has(o))}function vt(t){if(typeof t!="string"||!Ie.test(t))return!1;try{return new Date(t).toISOString()===t}catch{return!1}}function R(t){return typeof t=="string"&&Ne.test(t)}function Oe(t){return Number.isInteger(t)&&Number(t)>=0}function $e(t){return typeof t=="number"&&Number.isFinite(t)}function Et(t){return t===null||$e(t)}function Me(t){return t===null||typeof t=="number"&&Number.isFinite(t)&&t>=0}function It(t){return t==="completed"||t==="failed"||t==="cancelled"||t==="timeout"||t==="aborted"}function Re(t){return Object.values(St).some(e=>e.includes(t))}function V(t,e){return!It(t)||!Re(e)?!1:St[t].includes(e)}function Pe(t){if(!jt(t))return!1;let e=["input","output","cache_read","cache_creation"];return At(t,e)&&e.every(n=>Me(t[n]))}var Ce=[["schema_version",t=>t.schema_version===kt],["state",t=>It(t.state)],["started_at",t=>vt(t.started_at)],["ended_at",t=>vt(t.ended_at)],["journal_path",t=>typeof t.journal_path=="string"&&t.journal_path.length>0],["journal_sha256",t=>R(t.journal_sha256)],["event_count",t=>Oe(t.event_count)],["steps",t=>Et(t.steps)],["cost_usd",t=>Et(t.cost_usd)],["tokens",t=>Pe(t.tokens)],["model_execution_identity_hash",t=>R(t.model_execution_identity_hash)],["role_tool_surface_hash",t=>R(t.role_tool_surface_hash)],["bundle_manifest_hash",t=>R(t.bundle_manifest_hash)],["terminal_reason",t=>V(t.state,t.terminal_reason)]];function Nt(t){return!jt(t)||!At(t,we)?"envelope":Ce.find(([,e])=>!e(t))?.[0]??null}function De(t,e){let n=Y.resolve(t);return Y.relative(n,Y.resolve(n,e))}function Tt(t){return{schema_version:kt,state:t.state,started_at:t.startedAt,ended_at:t.endedAt,journal_path:De(t.trajectoryRoot,t.journalPath),journal_sha256:t.journalSha256,event_count:t.eventCount,steps:t.steps,cost_usd:t.costUsd,tokens:t.tokens,model_execution_identity_hash:t.modelExecutionIdentityHash,role_tool_surface_hash:t.roleToolSurfaceHash,bundle_manifest_hash:t.bundleManifestHash,terminal_reason:t.terminalReason}}var qe=/^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/,P=class extends Error{constructor(e){super(`not a decimal string: ${e}`),this.name="DecimalTextError"}};function X(t){return typeof t=="string"&&qe.test(t)}function Ue(t){if(!X(t))throw new P(String(t));let[e,n]=t.split(/[eE]/),[o,r=""]=e.replace(/^[+-]/,"").split("."),s=BigInt(`${o}${r}`)*(t.startsWith("-")?-1n:1n);return Le({units:s,scale:r.length-Number(n??0)})}function wt(t){let e=t.units<0n,n=(e?-t.units:t.units).toString().padStart(t.scale+1,"0"),o=n.length-t.scale,r=t.scale>0?n.slice(o).replace(/0+$/,""):"",s=r?`${n.slice(0,o)}.${r}`:n.slice(0,o);return e&&t.units!==0n?`-${s}`:s}function Ot(t){if(!Number.isFinite(t))throw new P(String(t));return Ue(String(t))}function Le(t){return t.scale>=0?t:{units:t.units*10n**BigInt(-t.scale),scale:0}}var Fe="cortex-bench-accounting/2",He="cortex-bench-proxy-export/1",Je=["proxy_not_started","counter_unreadable","audit_log_unreadable","no_echo_received","no_cache_breakdown_reported","journal_absent","journal_underivable","operand_unavailable"],W=class extends Error{constructor(e){super(`accounting input invalid: ${e}`),this.name="AccountingInputError"}};function Mt(t,e){let n=Be(t),o=Ge(e);return Pt({schema_version:Fe,trial_id:Ye(t.trial_id),proxy:n,journal:o,unaccounted_roles:Ke(n,o,e.roles)})}function Rt(t){return typeof t!="number"||!Number.isFinite(t)||t<0?{status:"unavailable",reason:"journal_underivable"}:{status:"available",value:wt(Ot(t))}}function Ke(t,e,n){if(t.requests.status!=="available"||e.requests.status!=="available")return[];let o=t.requests.value-e.requests.value;return o<=0?[]:[{kind:"proxy_excess",journal_roles:[...n],requests:{status:"available",value:o}}]}function Be(t){return g(t?.schema_version===He,"proxy.schema_version"),g(t.source==="proxy_export","proxy.source"),{requests:y(t.requests,"proxy.requests"),cached_tokens:y(t.cached_tokens,"proxy.cached_tokens"),input_tokens:y(t.input_tokens,"proxy.input_tokens"),output_tokens:y(t.output_tokens,"proxy.output_tokens"),audit_log:$t(t.audit_log,"proxy.audit_log"),lease_echo:$t(t.lease_echo,"proxy.lease_echo"),source:"proxy_export"}}function Ge(t){return g(t?.source==="trajectory_merge","journal.source"),g(Array.isArray(t.roles),"journal.roles"),{requests:y(t.requests,"journal.requests"),cost_usd:ze(t.cost_usd,"journal.cost_usd"),steps:y(t.steps,"journal.steps"),tokens:{input:y(t.tokens?.input,"journal.tokens.input"),output:y(t.tokens?.output,"journal.tokens.output"),cached:y(t.tokens?.cached,"journal.tokens.cached")},source:"trajectory_merge"}}function Z(t,e,n){g(typeof t=="object"&&t!==null,e);let o=t;return o.status==="unavailable"?(g(Je.includes(o.reason),`${e}.reason`),{status:"unavailable",reason:o.reason}):(g(o.status==="available",`${e}.status`),g(n(o.value),`${e}.value`),{status:"available",value:o.value})}function y(t,e){return Z(t,e,n=>Number.isSafeInteger(n)&&n>=0)}function ze(t,e){return Z(t,e,n=>X(n)&&!n.startsWith("-"))}function $t(t,e){let n=Z(t,e,o=>typeof o=="object"&&o!==null);return n.status!=="available"?n:{status:"available",value:structuredClone(n.value)}}function Ye(t){return g(typeof t=="string"&&t.length>0,"proxy.trial_id"),t}function g(t,e){if(!t)throw new W(e)}function Pt(t){for(let e of Object.values(t))e!==null&&typeof e=="object"&&Pt(e);return Object.freeze(t)}var Ct=["spawn","decompose","depends_on","dispatch","proposal","seal","delivery","verdict","rework","supersede","rotation","question","answer"],Ve=["spawn","decompose","depends_on","dispatch","delivery","verdict","rework","question","answer"],Xe=new Set(Ve);function Dt(t){return Xe.has(t)}var qt=Object.freeze({spawn:{from:["attempt"],to:["attempt"]},decompose:{from:["attempt"],to:["task"]},depends_on:{from:["task"],to:["task"]},dispatch:{from:["task"],to:["attempt"]},proposal:{from:["attempt"],to:["proposal"]},seal:{from:["proposal"],to:["outcome"]},delivery:{from:["outcome"],to:["attempt"]},verdict:{from:["attempt"],to:["attempt"]},rework:{from:["attempt"],to:["attempt"]},supersede:{from:["attempt"],to:["attempt"]},rotation:{from:["attempt"],to:["attempt"]},question:{from:["attempt"],to:["attempt"]},answer:{from:["attempt"],to:["attempt"]}});function Ut(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t,n=["input","output","cache_read","cache_creation"];return Object.keys(e).length===n.length&&n.every(o=>Object.hasOwn(e,o)&&(e[o]===null||typeof e[o]=="number"&&Number.isFinite(e[o])&&e[o]>=0))}var C=["trial_id","root_run_id","task_id","parent_task_id","dispatch_generation","attempt_id","attempt_ordinal","session_id","execution_id","task_ancestry","role","backend","provider","requested_model","reported_model","model_execution_identity_hash","role_tool_surface_hash","bundle_manifest_hash","terminal_state","terminal_reason","disposition","superseded_by","artifact_path","artifact_sha256","journal_path","journal_sha256","event_count","terminal_manifest_path","terminal_manifest_sha256","edges","started_at","ended_at","steps","cost_usd","tokens","provider_requests"];function Lt(t){let e=new Map;for(let o of t){let r=e.get(o.task_id);r?r.push(o):e.set(o.task_id,[o])}let n=new Map;for(let o of e.values())[...o].sort((s,a)=>s.started_at<a.started_at?-1:s.started_at>a.started_at?1:s.attempt_id<a.attempt_id?-1:s.attempt_id>a.attempt_id?1:0).forEach((s,a)=>n.set(s.attempt_id,a+1));return n}var Kt="cortex-bench-composite-manifest/3",We=["G1","G2","G3","G4","G5","G6","G7","G8"],Bt=Object.freeze({direct:Object.freeze(["D1","D2","D3","D4","D5","D6"]),"coder-review":Object.freeze(["C1","C2","C3","C4","C5","C6","C7","C8"]),manager:Object.freeze(["M-1","M-2","M-3","M-4","M-5","M-6","M-7","M-8","M-9","M-10","M-11","M-12","M-13","M-14","M-15","M-16"])});function Gt(t){return[...We,...Bt[t]]}var D=["schema_version","trial_id","root_run_id","arm_name","arm_canonical_sha256","identity","nodes","edges","roots","accounting","predicate"];var Ze=new Set(["attempt_missing_lifecycle_pair","lifecycle_pair_missing_attempt"]);function Qe(t){return t==="attempt_unaccounted"?39:40}function I(t){return t.id}function f(t){return`${t.ref}\0${I(t)}`}var Ft=new Map(Ct.map((t,e)=>[t,e+1]));function j(t,e){return t<e?-1:t>e?1:0}function q(t,e){return Ft.get(t.kind)-Ft.get(e.kind)||j(t.from.ref,e.from.ref)||j(I(t.from),I(e.from))||j(t.to.ref,e.to.ref)||j(I(t.to),I(e.to))}var zt=new Set(["spawn","decompose","dispatch"]);function Yt(t,e){let n=new Map;for(let c of t){if(!zt.has(c.kind))continue;let d=f(c.from),u=n.get(d);u?u.push(f(c.to)):n.set(d,[f(c.to)])}let o=f({ref:"attempt",id:e}),r=new Map([[o,0]]),s=[o];for(;s.length>0;){let c=s.shift(),d=r.get(c);for(let u of n.get(c)??[])r.has(u)||(r.set(u,d+1),s.push(u))}let a=new Map;for(let[c,d]of r){let[u,h]=c.split("\0");u==="attempt"&&a.set(h,d)}return a}function tn(t){let e=new Map,n=new Set;for(let s of t){if(!zt.has(s.kind))continue;let a=f(s.from),c=f(s.to);n.add(a),n.add(c);let d=e.get(a);d?d.push(c):e.set(a,[c])}let o=new Map,r=s=>{let a=o.get(s);if(a==="open")return!0;if(a==="closed")return!1;o.set(s,"open");for(let c of e.get(s)??[])if(r(c))return!0;return o.set(s,"closed"),!1};for(let s of n)if(r(s))return!0;return!1}var en="not evaluated at this pin";function nn(t,e){let n=Gt(t).map(o=>{let r=e?.[o];return r?{check_id:o,result:r.result,detail:r.detail}:{check_id:o,result:"unavailable",detail:en}});return{mode:t,checks:n}}function Vt(t){let e=[...t.edges].sort(q),n=Yt(e,t.roots.root_attempt_id),r=t.nodes.map(s=>({...s,edges:e.filter(a=>a.from.ref==="attempt"&&a.from.id===s.attempt_id)})).sort((s,a)=>(n.get(s.attempt_id)??Number.MAX_SAFE_INTEGER)-(n.get(a.attempt_id)??Number.MAX_SAFE_INTEGER)||s.attempt_ordinal-a.attempt_ordinal||j(s.attempt_id,a.attempt_id));return{schema_version:Kt,trial_id:t.trial_id,root_run_id:t.root_run_id,arm_name:t.arm_name,arm_canonical_sha256:t.arm_canonical_sha256,identity:t.identity,nodes:r,edges:e,roots:t.roots,accounting:t.accounting,predicate:nn(t.mode,t.evaluatedChecks)}}function Ht(t){return{ref:t.ref,id:t.id}}function Xt(t){return{kind:t.kind,from:Ht(t.from),to:Ht(t.to)}}function on(t){let e={};for(let n of C)if(n==="edges")e[n]=t.edges.map(Xt);else if(n==="tokens"){let o=t.tokens;e[n]={input:o.input,output:o.output,cache_read:o.cache_read,cache_creation:o.cache_creation}}else e[n]=t[n];return e}function Wt(t){let e={};for(let n of D)n==="nodes"?e[n]=t.nodes.map(on):n==="edges"?e[n]=t.edges.map(Xt):n==="roots"?e[n]={root_attempt_id:t.roots.root_attempt_id,root_task_id:t.roots.root_task_id}:n==="predicate"?e[n]={mode:t.predicate.mode,checks:t.predicate.checks.map(o=>({check_id:o.check_id,result:o.result,detail:o.detail}))}:e[n]=t[n];return Buffer.from(`${JSON.stringify(e,null,2)}
5
+ import{t as b,v as pt,w as mt,y as ft}from"../chunks/chunk-IOWBF7UK.js";import{a as G}from"../chunks/chunk-2ABET62E.js";import{h as A}from"../chunks/chunk-2WFL62UO.js";import"../chunks/chunk-PG7452XE.js";import"../chunks/chunk-RW2F2QNP.js";import"../chunks/chunk-VHX2GHBF.js";import"../chunks/chunk-C6YVF7EI.js";import"../chunks/chunk-ITGCWQFK.js";import"../chunks/chunk-PTS3J4DQ.js";import"../chunks/chunk-IMMGYDAB.js";import"../chunks/chunk-OJ37ZWBG.js";import"../chunks/chunk-SKHFU5DI.js";import"../chunks/chunk-V35MFAUQ.js";import"../chunks/chunk-OKRK6JPY.js";import"../chunks/chunk-52VCLZS5.js";import"../chunks/chunk-B3NB243Z.js";import"../chunks/chunk-5M4PFLRW.js";import{a as ht,b as yt,c as gt}from"../chunks/chunk-PMG4YGDU.js";import"../chunks/chunk-LIIZI3HY.js";import"../chunks/chunk-Q4UGYGU5.js";import"../chunks/chunk-TRXLIL7V.js";import"../chunks/chunk-7GGPYU5E.js";import{c as _t}from"../chunks/chunk-7W7VYUTK.js";import{b as lt}from"../chunks/chunk-JGUEIW2W.js";import"../chunks/chunk-T54CZKNJ.js";import"../chunks/chunk-WHC7AYZD.js";import Yn from"node:fs";import Vn from"node:path";import{createHash as qn,randomUUID as Un}from"node:crypto";import p from"node:fs";import m from"node:path";import{spawnSync as Ln}from"node:child_process";import{createHash as fn}from"node:crypto";function S(t){throw new Error(`malformed_fragment:${t}`)}function le(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function z(t){return t.event.type}function pe(t,e){let n=[],o=[],r=e,s=e;for(;r<t.length&&z(t[r])!=="tool_result";){if(z(t[r])==="tool_use"){n.push(...o,t[r]),o=[],r+=1,s=r;continue}o.push(t[r]),r+=1}return{records:n,next:s}}function me(t,e,n,o){let r=[],s=new Set(n),a=new Set([...n].filter(d=>o.has(d))),c=e;for(;c<t.length&&s.size>0;){let d=t[c],u=d.event;u.type==="tool_result"&&(n.has(u.toolUseId)?(s.delete(u.toolUseId),a.delete(u.toolUseId)):a.size===0&&S("unpaired_tool_result")),r.push(d),c+=1}return a.size>0&&S("unclosed_subagent_span"),{records:r,next:c}}function fe(t,e,n){let o=pe(t,e),r=o.records.flatMap(u=>u.event.type==="tool_use"?[u.event.toolUseId]:[]),s=new Set(r);s.size!==r.length&&S("duplicate_tool_call_id");let a=me(t,o.next,s,n),c=a.records.flatMap(u=>u.event.type==="tool_result"?[u.event.toolUseId]:[]);new Set(c).size!==c.length&&S("duplicate_tool_result");let d=[...s,...a.records.flatMap(u=>u.event.type==="tool_use"?[u.event.toolUseId]:[])];return new Set(d).size!==d.length&&S("duplicate_tool_call_id"),{group:{records:[...o.records,...a.records]},next:a.next}}function he(t){return new Set(t.flatMap(e=>e.event.type==="subagent_activity"?[e.event.parentToolUseId]:[]))}function ye(t){let e=[],n=he(t),o=0;for(;o<t.length;){let r=z(t[o]);if(r==="tool_result"&&S("unpaired_tool_result"),r!=="tool_use"){e.push({records:[t[o]]}),o+=1;continue}let s=fe(t,o,n);e.push(s.group),o=s.next}return e}function ge(t){return le(t)?t:{value:t}}function be(t){return t.records.flatMap(e=>{let n=e.event;return n.type!=="tool_use"?[]:[{tool_call_id:n.toolUseId,function_name:n.name,arguments:ge(n.input)}]})}function xe(t){return t.records.flatMap(e=>{let n=e.event;return n.type!=="tool_result"?[]:[{source_call_id:n.toolUseId,content:n.content,subagent_trajectory_ref:null,extra:{ok:n.ok}}]})}function ve(t){if(t.records.length===1){let e=t.records[0].event;if(e.type==="assistant_text"||e.type==="assistant_delta")return e.text}return JSON.stringify(t.records.map(e=>e.event))}function Ee(t,e){let n=t.records[0],o=be(t),r=xe(t);return{step_id:e,timestamp:n.ts,source:"agent",model_name:n.reported_model,message:ve(t),reasoning_content:null,...o.length>0?{tool_calls:o}:{},...r.length>0?{observation:{results:r}}:{},extra:{source_events:t.records}}}function ke(t){return{name:`cortex-${t.header.agent_slot}`,version:t.header.bundle_manifest_hash,model_name:t.events[0]?.requested_model??null,extra:{agent_slot:t.header.agent_slot,model_execution_identity_hash:t.header.model_execution_identity_hash,role_tool_surface_hash:t.header.role_tool_surface_hash,bundle_manifest_hash:t.header.bundle_manifest_hash,journal_schema_version:t.header.schema_version}}}function Se(t){return{root_run_id:t.header.root_run_id,session_id:t.header.session_id,agent_slot:t.header.agent_slot,resolved_cwd:t.header.resolved_cwd,model_execution_identity_hash:t.header.model_execution_identity_hash,role_tool_surface_hash:t.header.role_tool_surface_hash,bundle_manifest_hash:t.header.bundle_manifest_hash,journal_sha256:t.terminal.journal_sha256,terminal:{state:t.terminal.state,terminal_reason:t.terminal.terminal_reason}}}function je(t){let e=String(t.terminal.state),n=String(t.terminal.terminal_reason);return{step_id:1,timestamp:t.terminal.ended_at,source:"system",message:`Terminal state ${e}; reason ${n}`,extra:{synthesized_from:"terminal_manifest"}}}function Ae(t){return t.events.length===0?[je(t)]:ye(t.events).map((e,n)=>Ee(e,n+1))}function bt(t){let e=t.fragment,n={schema_version:"ATIF-v1.7",trajectory_id:e.header.session_id,agent:ke(e),steps:Ae(e),extra:Se(e)};return t.children.length>0&&(n.subagent_trajectories=t.children.map(bt)),n}function xt(t){let e=bt(t);return e.extra.subagent_link_source="explicit",e.extra.final_metrics_status="unavailable",e}import Y from"node:path";var kt="cortex-bench-manifest/2",Ie=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/,Ne=/^[a-f0-9]{64}$/,Te=["model_execution_identity_hash","role_tool_surface_hash","bundle_manifest_hash"],we=["schema_version","state","started_at","ended_at","journal_path","journal_sha256","event_count","steps","cost_usd","tokens",...Te,"terminal_reason"],St={completed:["ok"],failed:["child_failure","trajectory_write_failed","containment_failure","rate_limited","protocol_violation","step_limit_exceeded","cost_limit_exceeded","provider_error"],cancelled:["cancelled"],timeout:["deadline","deadline_exceeded"],aborted:["aborted"]};function jt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function At(t,e){let n=new Set(e);return e.every(o=>Object.hasOwn(t,o))&&Object.keys(t).every(o=>n.has(o))}function vt(t){if(typeof t!="string"||!Ie.test(t))return!1;try{return new Date(t).toISOString()===t}catch{return!1}}function R(t){return typeof t=="string"&&Ne.test(t)}function Oe(t){return Number.isInteger(t)&&Number(t)>=0}function $e(t){return typeof t=="number"&&Number.isFinite(t)}function Et(t){return t===null||$e(t)}function Me(t){return t===null||typeof t=="number"&&Number.isFinite(t)&&t>=0}function It(t){return t==="completed"||t==="failed"||t==="cancelled"||t==="timeout"||t==="aborted"}function Re(t){return Object.values(St).some(e=>e.includes(t))}function V(t,e){return!It(t)||!Re(e)?!1:St[t].includes(e)}function Pe(t){if(!jt(t))return!1;let e=["input","output","cache_read","cache_creation"];return At(t,e)&&e.every(n=>Me(t[n]))}var Ce=[["schema_version",t=>t.schema_version===kt],["state",t=>It(t.state)],["started_at",t=>vt(t.started_at)],["ended_at",t=>vt(t.ended_at)],["journal_path",t=>typeof t.journal_path=="string"&&t.journal_path.length>0],["journal_sha256",t=>R(t.journal_sha256)],["event_count",t=>Oe(t.event_count)],["steps",t=>Et(t.steps)],["cost_usd",t=>Et(t.cost_usd)],["tokens",t=>Pe(t.tokens)],["model_execution_identity_hash",t=>R(t.model_execution_identity_hash)],["role_tool_surface_hash",t=>R(t.role_tool_surface_hash)],["bundle_manifest_hash",t=>R(t.bundle_manifest_hash)],["terminal_reason",t=>V(t.state,t.terminal_reason)]];function Nt(t){return!jt(t)||!At(t,we)?"envelope":Ce.find(([,e])=>!e(t))?.[0]??null}function De(t,e){let n=Y.resolve(t);return Y.relative(n,Y.resolve(n,e))}function Tt(t){return{schema_version:kt,state:t.state,started_at:t.startedAt,ended_at:t.endedAt,journal_path:De(t.trajectoryRoot,t.journalPath),journal_sha256:t.journalSha256,event_count:t.eventCount,steps:t.steps,cost_usd:t.costUsd,tokens:t.tokens,model_execution_identity_hash:t.modelExecutionIdentityHash,role_tool_surface_hash:t.roleToolSurfaceHash,bundle_manifest_hash:t.bundleManifestHash,terminal_reason:t.terminalReason}}var qe=/^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/,P=class extends Error{constructor(e){super(`not a decimal string: ${e}`),this.name="DecimalTextError"}};function X(t){return typeof t=="string"&&qe.test(t)}function Ue(t){if(!X(t))throw new P(String(t));let[e,n]=t.split(/[eE]/),[o,r=""]=e.replace(/^[+-]/,"").split("."),s=BigInt(`${o}${r}`)*(t.startsWith("-")?-1n:1n);return Le({units:s,scale:r.length-Number(n??0)})}function wt(t){let e=t.units<0n,n=(e?-t.units:t.units).toString().padStart(t.scale+1,"0"),o=n.length-t.scale,r=t.scale>0?n.slice(o).replace(/0+$/,""):"",s=r?`${n.slice(0,o)}.${r}`:n.slice(0,o);return e&&t.units!==0n?`-${s}`:s}function Ot(t){if(!Number.isFinite(t))throw new P(String(t));return Ue(String(t))}function Le(t){return t.scale>=0?t:{units:t.units*10n**BigInt(-t.scale),scale:0}}var Fe="cortex-bench-accounting/2",He="cortex-bench-proxy-export/1",Je=["proxy_not_started","counter_unreadable","audit_log_unreadable","no_echo_received","no_cache_breakdown_reported","journal_absent","journal_underivable","operand_unavailable"],W=class extends Error{constructor(e){super(`accounting input invalid: ${e}`),this.name="AccountingInputError"}};function Mt(t,e){let n=Be(t),o=Ge(e);return Pt({schema_version:Fe,trial_id:Ye(t.trial_id),proxy:n,journal:o,unaccounted_roles:Ke(n,o,e.roles)})}function Rt(t){return typeof t!="number"||!Number.isFinite(t)||t<0?{status:"unavailable",reason:"journal_underivable"}:{status:"available",value:wt(Ot(t))}}function Ke(t,e,n){if(t.requests.status!=="available"||e.requests.status!=="available")return[];let o=t.requests.value-e.requests.value;return o<=0?[]:[{kind:"proxy_excess",journal_roles:[...n],requests:{status:"available",value:o}}]}function Be(t){return g(t?.schema_version===He,"proxy.schema_version"),g(t.source==="proxy_export","proxy.source"),{requests:y(t.requests,"proxy.requests"),cached_tokens:y(t.cached_tokens,"proxy.cached_tokens"),input_tokens:y(t.input_tokens,"proxy.input_tokens"),output_tokens:y(t.output_tokens,"proxy.output_tokens"),audit_log:$t(t.audit_log,"proxy.audit_log"),lease_echo:$t(t.lease_echo,"proxy.lease_echo"),source:"proxy_export"}}function Ge(t){return g(t?.source==="trajectory_merge","journal.source"),g(Array.isArray(t.roles),"journal.roles"),{requests:y(t.requests,"journal.requests"),cost_usd:ze(t.cost_usd,"journal.cost_usd"),steps:y(t.steps,"journal.steps"),tokens:{input:y(t.tokens?.input,"journal.tokens.input"),output:y(t.tokens?.output,"journal.tokens.output"),cached:y(t.tokens?.cached,"journal.tokens.cached")},source:"trajectory_merge"}}function Z(t,e,n){g(typeof t=="object"&&t!==null,e);let o=t;return o.status==="unavailable"?(g(Je.includes(o.reason),`${e}.reason`),{status:"unavailable",reason:o.reason}):(g(o.status==="available",`${e}.status`),g(n(o.value),`${e}.value`),{status:"available",value:o.value})}function y(t,e){return Z(t,e,n=>Number.isSafeInteger(n)&&n>=0)}function ze(t,e){return Z(t,e,n=>X(n)&&!n.startsWith("-"))}function $t(t,e){let n=Z(t,e,o=>typeof o=="object"&&o!==null);return n.status!=="available"?n:{status:"available",value:structuredClone(n.value)}}function Ye(t){return g(typeof t=="string"&&t.length>0,"proxy.trial_id"),t}function g(t,e){if(!t)throw new W(e)}function Pt(t){for(let e of Object.values(t))e!==null&&typeof e=="object"&&Pt(e);return Object.freeze(t)}var Ct=["spawn","decompose","depends_on","dispatch","proposal","seal","delivery","verdict","rework","supersede","rotation","question","answer"],Ve=["spawn","decompose","depends_on","dispatch","delivery","verdict","rework","question","answer"],Xe=new Set(Ve);function Dt(t){return Xe.has(t)}var qt=Object.freeze({spawn:{from:["attempt"],to:["attempt"]},decompose:{from:["attempt"],to:["task"]},depends_on:{from:["task"],to:["task"]},dispatch:{from:["task"],to:["attempt"]},proposal:{from:["attempt"],to:["proposal"]},seal:{from:["proposal"],to:["outcome"]},delivery:{from:["outcome"],to:["attempt"]},verdict:{from:["attempt"],to:["attempt"]},rework:{from:["attempt"],to:["attempt"]},supersede:{from:["attempt"],to:["attempt"]},rotation:{from:["attempt"],to:["attempt"]},question:{from:["attempt"],to:["attempt"]},answer:{from:["attempt"],to:["attempt"]}});function Ut(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t,n=["input","output","cache_read","cache_creation"];return Object.keys(e).length===n.length&&n.every(o=>Object.hasOwn(e,o)&&(e[o]===null||typeof e[o]=="number"&&Number.isFinite(e[o])&&e[o]>=0))}var C=["trial_id","root_run_id","task_id","parent_task_id","dispatch_generation","attempt_id","attempt_ordinal","session_id","execution_id","task_ancestry","role","backend","provider","requested_model","reported_model","model_execution_identity_hash","role_tool_surface_hash","bundle_manifest_hash","terminal_state","terminal_reason","disposition","superseded_by","artifact_path","artifact_sha256","journal_path","journal_sha256","event_count","terminal_manifest_path","terminal_manifest_sha256","edges","started_at","ended_at","steps","cost_usd","tokens","provider_requests"];function Lt(t){let e=new Map;for(let o of t){let r=e.get(o.task_id);r?r.push(o):e.set(o.task_id,[o])}let n=new Map;for(let o of e.values())[...o].sort((s,a)=>s.started_at<a.started_at?-1:s.started_at>a.started_at?1:s.attempt_id<a.attempt_id?-1:s.attempt_id>a.attempt_id?1:0).forEach((s,a)=>n.set(s.attempt_id,a+1));return n}var Kt="cortex-bench-composite-manifest/3",We=["G1","G2","G3","G4","G5","G6","G7","G8"],Bt=Object.freeze({direct:Object.freeze(["D1","D2","D3","D4","D5","D6"]),"coder-review":Object.freeze(["C1","C2","C3","C4","C5","C6","C7","C8"]),manager:Object.freeze(["M-1","M-2","M-3","M-4","M-5","M-6","M-7","M-8","M-9","M-10","M-11","M-12","M-13","M-14","M-15","M-16"])});function Gt(t){return[...We,...Bt[t]]}var D=["schema_version","trial_id","root_run_id","arm_name","arm_canonical_sha256","identity","nodes","edges","roots","accounting","predicate"];var Ze=new Set(["attempt_missing_lifecycle_pair","lifecycle_pair_missing_attempt"]);function Qe(t){return t==="attempt_unaccounted"?39:40}function I(t){return t.id}function f(t){return`${t.ref}\0${I(t)}`}var Ft=new Map(Ct.map((t,e)=>[t,e+1]));function j(t,e){return t<e?-1:t>e?1:0}function q(t,e){return Ft.get(t.kind)-Ft.get(e.kind)||j(t.from.ref,e.from.ref)||j(I(t.from),I(e.from))||j(t.to.ref,e.to.ref)||j(I(t.to),I(e.to))}var zt=new Set(["spawn","decompose","dispatch"]);function Yt(t,e){let n=new Map;for(let c of t){if(!zt.has(c.kind))continue;let d=f(c.from),u=n.get(d);u?u.push(f(c.to)):n.set(d,[f(c.to)])}let o=f({ref:"attempt",id:e}),r=new Map([[o,0]]),s=[o];for(;s.length>0;){let c=s.shift(),d=r.get(c);for(let u of n.get(c)??[])r.has(u)||(r.set(u,d+1),s.push(u))}let a=new Map;for(let[c,d]of r){let[u,h]=c.split("\0");u==="attempt"&&a.set(h,d)}return a}function tn(t){let e=new Map,n=new Set;for(let s of t){if(!zt.has(s.kind))continue;let a=f(s.from),c=f(s.to);n.add(a),n.add(c);let d=e.get(a);d?d.push(c):e.set(a,[c])}let o=new Map,r=s=>{let a=o.get(s);if(a==="open")return!0;if(a==="closed")return!1;o.set(s,"open");for(let c of e.get(s)??[])if(r(c))return!0;return o.set(s,"closed"),!1};for(let s of n)if(r(s))return!0;return!1}var en="not evaluated at this pin";function nn(t,e){let n=Gt(t).map(o=>{let r=e?.[o];return r?{check_id:o,result:r.result,detail:r.detail}:{check_id:o,result:"unavailable",detail:en}});return{mode:t,checks:n}}function Vt(t){let e=[...t.edges].sort(q),n=Yt(e,t.roots.root_attempt_id),r=t.nodes.map(s=>({...s,edges:e.filter(a=>a.from.ref==="attempt"&&a.from.id===s.attempt_id)})).sort((s,a)=>(n.get(s.attempt_id)??Number.MAX_SAFE_INTEGER)-(n.get(a.attempt_id)??Number.MAX_SAFE_INTEGER)||s.attempt_ordinal-a.attempt_ordinal||j(s.attempt_id,a.attempt_id));return{schema_version:Kt,trial_id:t.trial_id,root_run_id:t.root_run_id,arm_name:t.arm_name,arm_canonical_sha256:t.arm_canonical_sha256,identity:t.identity,nodes:r,edges:e,roots:t.roots,accounting:t.accounting,predicate:nn(t.mode,t.evaluatedChecks)}}function Ht(t){return{ref:t.ref,id:t.id}}function Xt(t){return{kind:t.kind,from:Ht(t.from),to:Ht(t.to)}}function on(t){let e={};for(let n of C)if(n==="edges")e[n]=t.edges.map(Xt);else if(n==="tokens"){let o=t.tokens;e[n]={input:o.input,output:o.output,cache_read:o.cache_read,cache_creation:o.cache_creation}}else e[n]=t[n];return e}function Wt(t){let e={};for(let n of D)n==="nodes"?e[n]=t.nodes.map(on):n==="edges"?e[n]=t.edges.map(Xt):n==="roots"?e[n]={root_attempt_id:t.roots.root_attempt_id,root_task_id:t.roots.root_task_id}:n==="predicate"?e[n]={mode:t.predicate.mode,checks:t.predicate.checks.map(o=>({check_id:o.check_id,result:o.result,detail:o.detail}))}:e[n]=t[n];return Buffer.from(`${JSON.stringify(e,null,2)}
6
6
  `,"utf8")}var rn=["requests","cached_tokens","input_tokens","output_tokens","audit_log","lease_echo","source"],sn=["requests","cost_usd","steps","tokens","source"],an=/^[a-f0-9]{64}$/;function Q(t){return typeof t=="string"&&an.test(t)}function Jt(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=Object.entries(t);return e.length>0&&e.every(([n,o])=>n.length>0&&Q(o))}function cn(t){if(Object.keys(t).length!==C.length||!C.every(r=>Object.hasOwn(t,r)))return!1;let n=[t.journal_path,t.terminal_manifest_path,t.session_id,t.execution_id],o=[t.model_execution_identity_hash,t.role_tool_surface_hash,t.bundle_manifest_hash,t.journal_sha256,t.terminal_manifest_sha256];return n.every(r=>typeof r=="string"&&r.length>0)&&t.terminal_manifest_path.endsWith(".terminal.json")&&o.every(Q)&&Number.isInteger(t.event_count)&&t.event_count>=0&&Ut(t.tokens)&&(t.provider_requests===null||Number.isInteger(t.provider_requests)&&t.provider_requests>0)&&V(t.terminal_state,t.terminal_reason)}function Zt(t,e){let n=[],o=(i,l)=>{n.push({code:i,failure_code:Qe(Ze.has(i)?"attempt_unaccounted":"composite_manifest_invalid"),detail:l})},r=t,s=Object.keys(r),a=new Set(D);for(let i of s)a.has(i)||o("unknown_top_level_member",i);for(let i of D)Object.hasOwn(r,i)||o("top_level_member_missing",i);let c=D.filter(i=>Object.hasOwn(r,i)),d=s.filter(i=>a.has(i));d.join(",")!==c.join(",")&&o("member_order_invalid",`expected ${c.join(",")}, got ${d.join(",")}`),t.schema_version!==Kt&&o("schema_version_invalid",String(t.schema_version));let u=t.nodes??[],h=t.edges??[];u.length===0&&o("nodes_empty","a trial with no attempt has no manifest to publish");let w=new Set;for(let i of u)w.has(i.attempt_id)&&o("attempt_id_not_unique",i.attempt_id),w.add(i.attempt_id);let ce=new Set(u.map(i=>i.task_id)),rt=i=>{switch(i.ref){case"attempt":case"proposal":case"outcome":return w.has(i.id);case"task":return ce.has(i.id)}};for(let i of h){if(!Dt(i.kind)){o("edge_kind_out_of_contract",i.kind);continue}let l=qt[i.kind];l.from.includes(i.from.ref)||o("edge_endpoint_type_invalid",`${i.kind}.from may not be ${i.from.ref}`),l.to.includes(i.to.ref)||o("edge_endpoint_type_invalid",`${i.kind}.to may not be ${i.to.ref}`),rt(i.from)||o("edge_endpoint_unresolved",`${i.kind}.from ${f(i.from)}`),rt(i.to)||o("edge_endpoint_unresolved",`${i.kind}.to ${f(i.to)}`)}let st=new Set;for(let i of h){let l=`${i.kind}\0${f(i.from)}\0${f(i.to)}`;st.has(l)&&o("edge_duplicated",l),st.add(l)}let de=[...h].sort(q);h.some((i,l)=>q(i,de[l])!==0)&&o("edges_out_of_order","edges are not in (kind, from, to) order");let O=t.roots?.root_attempt_id;tn(h)&&o("attempt_dag_cycle","spawn/decompose/dispatch subset contains a cycle");let $=Yt(h,O);for(let i of u)$.has(i.attempt_id)||o("attempt_dag_unrooted",i.attempt_id);let ue=[...u].sort((i,l)=>($.get(i.attempt_id)??Number.MAX_SAFE_INTEGER)-($.get(l.attempt_id)??Number.MAX_SAFE_INTEGER)||i.attempt_ordinal-l.attempt_ordinal||j(i.attempt_id,l.attempt_id));u.some((i,l)=>i.attempt_id!==ue[l].attempt_id)&&o("nodes_out_of_order","nodes are not in (depth, attempt_ordinal, attempt_id) order");let it=new Set(e.lifecycleStems);for(let i of u)it.has(i.attempt_id)||o("attempt_missing_lifecycle_pair",i.attempt_id);for(let i of it)w.has(i)||o("lifecycle_pair_missing_attempt",i);for(let i of u){let l=h.filter(M=>M.from.ref==="attempt"&&M.from.id===i.attempt_id),ut=i.edges??[];ut.length===l.length&&l.every((M,_e)=>q(M,ut[_e])===0)||o("node_edge_projection_mismatch",i.attempt_id)}let at=u.find(i=>i.attempt_id===O);(!at||$.get(O)!==0||!at.session_id)&&o("roots_parent_attempt_invalid",String(O));for(let i of u)i.trial_id!==t.trial_id&&o("node_trial_id_mismatch",i.attempt_id);t.accounting?.trial_id!==t.trial_id&&o("accounting_trial_id_mismatch",String(t.accounting?.trial_id));let ct=Object.keys(t.accounting?.proxy??{}),dt=Object.keys(t.accounting?.journal??{});ct.join(",")!==rn.join(",")&&o("accounting_shape_invalid",`proxy keys ${ct.join(",")}`),dt.join(",")!==sn.join(",")&&o("accounting_shape_invalid",`journal keys ${dt.join(",")}`);let H=t.identity;(!Jt(H?.model_execution_identity_hash)||!Jt(H?.role_tool_surface_hash)||!Q(H?.bundle_manifest_hash))&&o("identity_invalid","spawn-time identity is absent or malformed");for(let i of u){(!Number.isInteger(i.attempt_ordinal)||i.attempt_ordinal<1)&&o("attempt_ordinal_invalid",`${i.attempt_id} ordinal ${i.attempt_ordinal}`),cn(i)||o("attempt_evidence_invalid",i.attempt_id),i.superseded_by!==null&&o("superseded_by_unresolved",i.attempt_id);let l=i.task_ancestry??[];(l.length===0||l[l.length-1]!==i.task_id)&&o("task_ancestry_invalid",i.attempt_id)}let J=t.predicate?.mode,K=J&&Bt[J]?Gt(J):null,B=(t.predicate?.checks??[]).map(i=>i.check_id);if(K){let i=K.filter(l=>!B.includes(l));i.length>0?o("predicate_checks_incomplete",i.join(",")):B.join(",")!==K.join(",")&&o("predicate_checks_out_of_order",B.join(","))}for(let i of t.predicate?.checks??[])(i.result==="pass"?i.detail===null:typeof i.detail=="string"&&i.detail.length>0)||o("predicate_check_detail_invalid",i.check_id);return n}import{createHash as dn}from"node:crypto";import un from"node:fs";var Qt="cortex-bench-journal/2";function x(t){throw new Error(`production evidence journal invalid: ${t}`)}function _n(t){return dn("sha256").update(t).digest("hex")}function ln(t,e){return(t.length===0||t.at(-1)!==10)&&x(`${e} is incomplete`),t.toString("utf8").trimEnd().split(`
7
7
  `).map((n,o)=>{try{let r=JSON.parse(n);if(!r||typeof r!="object"||Array.isArray(r))throw new Error;return r}catch{return x(`${e} row ${o+1} is malformed`)}})}function pn(t,e){let o=[[t.schema_version,Qt,"schema"],[t.type,"run_header","header"],[t.root_run_id,e.root_run_id,"root run"],[t.session_id,e.session_id,"session"],[t.agent_slot,b,"role"],[t.model_execution_identity_hash,e.model_execution_identity_hash,"model identity"],[t.role_tool_surface_hash,e.role_tool_surface_hash,"role identity"],[t.bundle_manifest_hash,e.bundle_manifest_hash,"bundle identity"]].find(([r,s])=>r!==s);o&&x(`${o[2]} mismatch for ${e.attempt_id}`)}function mn(t,e){(t.schema_version!==Qt||t.type!=="event")&&x(`event schema mismatch for ${e.attempt_id}`),[[t.root_run_id,e.root_run_id],[t.session_id,e.session_id],[t.agent_slot,b],[t.backend,e.backend],[t.provider,e.provider],[t.requested_model,e.requested_model],[t.model_execution_identity_hash,e.model_execution_identity_hash],[t.role_tool_surface_hash,e.role_tool_surface_hash],[t.bundle_manifest_hash,e.bundle_manifest_hash]].some(([o,r])=>o!==r)&&x(`event identity mismatch for ${e.attempt_id}`)}function te(t,e){let n;try{n=un.readFileSync(t.journal_path)}catch{return x(`bytes missing for ${e.attempt_id}`)}_n(n)!==t.journal_sha256&&x(`hash mismatch for ${e.attempt_id}`);let o=ln(n,e.attempt_id);pn(o[0]??{},e);let r=o.slice(1);r.length!==t.event_count&&x(`event count mismatch for ${e.attempt_id}`),r.forEach(a=>mn(a,e));let s=r.map(a=>a.reported_model).filter(a=>typeof a=="string"&&a.length>0);return{bytes:n,header:o[0],events:r,reportedModel:s.at(-1)??null,rateLimited:r.some(a=>a.event?.type==="rate_limit")}}var hn=/^[a-f0-9]{64}$/,yn=/^[A-Za-z0-9._-]+$/,T=class extends Error{constructor(e){super(`production evidence export failed: ${e}`),this.name="ProductionEvidenceExportError"}};function _(t){throw new T(t)}function k(t,e){return(typeof t!="string"||t.length===0)&&_(`${e} is missing`),t}function U(t,e){let n=k(t,e);return hn.test(n)||_(`${e} is not sha256`),n}function tt(t,e){let n=k(t,e);return(Number.isNaN(Date.parse(n))||new Date(n).toISOString()!==n)&&_(`${e} is invalid`),n}function L(t,e){return(!t||typeof t!="object"||Array.isArray(t))&&_(`${e} must be an object`),t}function gn(t,e){return typeof t=="string"&&e.includes(t)}function bn(t){if(t===void 0)return;let e=L(t,"evaluated checks");for(let[n,o]of Object.entries(e)){let r=L(o,`evaluated check ${n}`);gn(r.result,["pass","fail","unavailable"])||_(`evaluated check ${n} result is invalid`),r.detail!==null&&typeof r.detail!="string"&&_(`evaluated check ${n} detail is invalid`),r.result==="fail"&&_("failed predicate cannot be published")}}function et(t){let e=L(t,"input");k(e.outputDirectory,"output directory"),k(e.trialId,"trial identity"),k(e.rootRunId,"root run identity"),k(e.armName,"arm name"),U(e.armCanonicalSha256,"arm canonical hash"),U(e.bundleManifestHash,"bundle manifest hash"),L(e.proxyExport,"proxy export").trial_id!==e.trialId&&_("proxy trial identity mismatch"),bn(e.evaluatedChecks)}function xn(t){return fn("sha256").update(t).digest("hex")}function vn(t,e){(t.trial_id!==e.trialId||t.root_run_id!==e.rootRunId)&&_(`attempt scope mismatch for ${t.attempt_id}`),t.bundle_manifest_hash!==e.bundleManifestHash&&_(`bundle identity mismatch for ${t.attempt_id}`),U(t.model_execution_identity_hash,"model execution identity"),U(t.role_tool_surface_hash,"role tool identity"),yn.test(t.attempt_id)||_(`attempt path identity invalid: ${t.attempt_id}`)}function En(t,e){let n=tt(t.runtime.startedAt,"execution started_at"),o=tt(t.runtime.endedAt,"execution ended_at"),r=tt(e.frozen_at,"identity frozen_at");(n>r||r>o)&&_(`attempt timing mismatch for ${e.attempt_id}`),t.session.sessionId!==e.session_id&&_(`execution linkage mismatch for ${e.attempt_id}`),["completed","failed","cancelled"].includes(t.status)||_(`execution is not classifiable for ${e.attempt_id}`)}function kn(t,e){return[[t.execution_id,e.execution_id],[t.session_id,e.session_id],[t.root_attempt_id,e.root_attempt_id]].every(([o,r])=>o===r)}function Sn(t,e,n){let o=new Map(e.map(s=>[s.attempt_id,s])),r=new Map;for(let s of t.filter(a=>a.trial_id===n.trialId)){s.root_run_id!==n.rootRunId&&_("cost root run identity mismatch");let a=k(s.attempt_id,"cost attempt identity"),c=o.get(a);(!c||!kn(s,c))&&_(`cost attribution mismatch for ${a}`);let d=r.get(a)??[];d.push(s),r.set(a,d)}return r}function jn(t,e,n,o){let r=Sn(o,n,t);return n.map(s=>{vn(s,t);let a=e.getJournal(s.execution_id);(!a||a.attempt_id!==s.attempt_id||a.execution_id!==s.execution_id)&&_(`journal record missing for ${s.attempt_id}`);let c=e.getExecution(s.execution_id);return c||_(`execution record missing for ${s.attempt_id}`),En(c,s),{identity:s,journal:a,execution:c,parsedJournal:te(a,s),costs:r.get(s.attempt_id)??[]}})}function E(t,e){if(t.length===0)return null;let n=t.map(e);return n.some(o=>o==null)?null:(n.some(o=>typeof o!="number"||!Number.isFinite(o)||o<0)&&_("cost row contains an invalid counter"),n.reduce((o,r)=>o+r,0))}function An(t){let e=E(t.costs,n=>n.provider_requests);return e===0&&_(`provider request zero stand-in for ${t.identity.attempt_id}`),{steps:E(t.costs,n=>n.num_turns)??t.execution.metrics.numTurns,costUsd:E(t.costs,n=>n.cost_usd)??t.execution.metrics.costUsd,tokens:{input:E(t.costs,n=>n.input_tokens),output:E(t.costs,n=>n.output_tokens),cache_read:E(t.costs,n=>n.cache_read_tokens),cache_creation:E(t.costs,n=>n.cache_creation_tokens)},providerRequests:e}}function In(t){return{completed:{state:"completed",reason:"ok"},cancelled:{state:"cancelled",reason:"cancelled"},failed:t.parsedJournal.rateLimited?{state:"failed",reason:"rate_limited"}:{state:"failed",reason:"child_failure"}}[t.execution.status]??_(`terminal outcome missing for ${t.identity.attempt_id}`)}function Nn(t){return t.flatMap(e=>e.identity.spawn_parent_attempt_id?[{kind:"spawn",from:{ref:"attempt",id:e.identity.spawn_parent_attempt_id},to:{ref:"attempt",id:e.identity.attempt_id}}]:[])}function Tn(t,e,n,o,r){let s=Tt({trajectoryRoot:"/",state:e,startedAt:t.execution.runtime.startedAt,endedAt:t.execution.runtime.endedAt,journalPath:r,journalSha256:t.journal.journal_sha256,eventCount:t.journal.event_count,steps:o.steps,costUsd:o.costUsd,tokens:{input:o.tokens.input,output:o.tokens.output,cache_read:o.tokens.cache_read,cache_creation:o.tokens.cache_creation},modelExecutionIdentityHash:t.identity.model_execution_identity_hash,roleToolSurfaceHash:t.identity.role_tool_surface_hash,bundleManifestHash:t.identity.bundle_manifest_hash,terminalReason:n}),a=Nt(s);return a&&_(`terminal manifest ${a} for ${t.identity.attempt_id}`),Buffer.from(`${JSON.stringify(s)}
8
8
  `,"utf8")}function wn(t,e){return t.map(n=>{let o=In(n),r=An(n),s=n.identity.attempt_id===e,a=s?"events.jsonl":`journals/${n.identity.attempt_id}.ndjson`,c=s?`run-${n.identity.root_run_id}.terminal.json`:`${n.identity.attempt_id}.terminal.json`,d=Tn(n,o.state,o.reason,r,a);return{source:n,state:o.state,reason:o.reason,usage:r,journalPath:a,terminalPath:c,terminalBytes:d,terminalSha256:xn(d)}})}function On(t){let e=Lt(t.map(n=>({attempt_id:n.source.identity.attempt_id,task_id:n.source.identity.trial_id,started_at:n.source.execution.runtime.startedAt})));return t.map(n=>{let{identity:o,execution:r,parsedJournal:s,journal:a}=n.source;return{trial_id:o.trial_id,root_run_id:o.root_run_id,task_id:o.trial_id,parent_task_id:null,dispatch_generation:null,attempt_id:o.attempt_id,attempt_ordinal:e.get(o.attempt_id),session_id:o.session_id,execution_id:o.execution_id,task_ancestry:[o.trial_id],role:b,backend:o.backend,provider:o.provider,requested_model:o.requested_model,reported_model:s.reportedModel,model_execution_identity_hash:o.model_execution_identity_hash,role_tool_surface_hash:o.role_tool_surface_hash,bundle_manifest_hash:o.bundle_manifest_hash,terminal_state:n.state,terminal_reason:n.reason,disposition:"none",superseded_by:null,artifact_path:null,artifact_sha256:null,journal_path:n.journalPath,journal_sha256:a.journal_sha256,event_count:a.event_count,terminal_manifest_path:n.terminalPath,terminal_manifest_sha256:n.terminalSha256,edges:[],started_at:r.runtime.startedAt,ended_at:r.runtime.endedAt,steps:n.usage.steps,cost_usd:n.usage.costUsd,tokens:n.usage.tokens,provider_requests:n.usage.providerRequests}})}function ee(t,e){let n=new Set(t.map(o=>e(o.identity)));return n.size!==1&&_(`role identity drift for ${b}`),{[b]:[...n][0]}}function N(t){return t.some(e=>e===null)?{status:"unavailable",reason:"journal_underivable"}:{status:"available",value:t.reduce((e,n)=>e+n,0)}}function $n(t){let e=t.map(o=>o.usage.costUsd),n=e.some(o=>o===null)?{status:"unavailable",reason:"journal_underivable"}:Rt(e.reduce((o,r)=>o+r,0));return{requests:N(t.map(o=>o.usage.providerRequests)),cost_usd:n,steps:N(t.map(o=>o.usage.steps)),tokens:{input:N(t.map(o=>o.usage.tokens.input)),output:N(t.map(o=>o.usage.tokens.output)),cached:N(t.map(o=>o.usage.tokens.cache_read))},source:"trajectory_merge",roles:[b]}}function Mn(t){let e=t.filter(n=>n.identity.spawn_parent_attempt_id===null&&n.identity.attempt_id===n.identity.root_attempt_id);return e.length!==1&&_(`real production root resolves to ${e.length} attempts`),e[0]}function Rn(t){return Buffer.from(`${JSON.stringify({root_run_id:t.source.identity.root_run_id,session_id:t.source.identity.session_id,ts:t.source.execution.runtime.startedAt,journal_path:t.journalPath})}
@@ -2,6 +2,6 @@
2
2
  import { createRequire as __cortexCreateRequire } from 'node:module';
3
3
  const require = __cortexCreateRequire(import.meta.url);
4
4
  const __cortexPackageRoot = new URL("../../", import.meta.url);
5
- import{a as S,b as n,c as y,d as c}from"../chunks/chunk-PMG4YGDU.js";import{b as w}from"../chunks/chunk-QWAQHHRS.js";import"../chunks/chunk-J5DVLUKY.js";import"../chunks/chunk-WHC7AYZD.js";import*as d from"node:fs";import*as $ from"node:os";import*as a from"node:path";var k={name:"cortex-signal",description:"Tell Cortex that something it is waiting for has finished.",usage:"cortex-signal [--id wp_\u2026] [--secret \u2026] [--status ok|fail|progress] [--message TEXT] [--exit-code N]",options:[{flag:"--id <wp_\u2026>",description:"Waitpoint id",default:"$CORTEX_SIGNAL_ID"},{flag:"--secret <hex>",description:"Capability issued with the waitpoint",default:"$CORTEX_SIGNAL_SECRET"},{flag:"--status <s>",description:"ok | fail | progress",default:"ok"},{flag:"--exit-code <n>",description:"Set status from a command exit code (0 = ok, else fail)"},{flag:"--message <text>",description:"One-line summary shown in the wake message"},{flag:"--member <name>",description:"Which member of a multi-job waitpoint this is (required when it names members)"},{flag:"--data <@file|->",description:"Extra payload from a file or stdin (treated as data, not instructions)"},{flag:"--url <url>",description:"Daemon signal endpoint",default:"http://127.0.0.1:$WEBHOOK_PORT/webhook/signal"},{flag:"--no-spool",description:"Fail instead of spooling to disk when the daemon is unreachable"},{flag:"--help, -h",description:"Show this help"}],examples:[{description:"Report the exit code of the command that just ran",command:"python train.py; cortex-signal --exit-code $?"},{description:"Report one arm of a multi-job waitpoint",command:'cortex-signal --member arm2 --status ok --message "33,120 steps"'},{description:"Attach the tail of a log as data",command:"tail -c 2000 train.log | cortex-signal --exit-code $? --data -"}]},b={"--id":"id","--secret":"secret","--status":"status","--message":"message","--member":"member","--data":"data","--exit-code":"exitCode","--url":"url"},C=["ok","fail","progress"];function R(t){let e={help:!1,id:null,secret:null,status:null,message:null,data:null,member:null,exitCode:null,url:null,noSpool:!1};for(let o=0;o<t.length;o+=1){let s=t[o];if(s==="--help"||s==="-h"){e.help=!0;continue}if(s==="--no-spool"){e.noSpool=!0;continue}let r=b[s];if(!r)throw c(n(`Unknown argument: '${s}'`,{validValues:[...Object.keys(b),"--no-spool","--help"]}));let l=t[o+1];if(l===void 0||l.startsWith("--")&&r!=="message")throw c(n(`${s} requires a value`));e[r]=l,o+=1}return e}function j(t){if(t.status!==null&&!C.includes(t.status))throw c(n(`Invalid --status '${t.status}'`,{validValues:C}));if(t.exitCode===null)return{status:t.status??"ok",message:t.message};let e=Number.parseInt(t.exitCode,10);if(!Number.isFinite(e))throw c(n(`--exit-code must be a number, got '${t.exitCode}'`));return{status:t.status??(e===0?"ok":"fail"),message:t.message??`exit=${e}`}}function v(t){if(t!==null){if(t==="-")return y();if(t.startsWith("@")){let e=t.slice(1);try{return d.readFileSync(e,"utf8")}catch(o){throw c(n(`Cannot read --data file '${e}': ${o.message}`))}}return t}}async function A(t,e){let o=await fetch(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)}),s=await o.text(),r=s;try{r=JSON.parse(s)}catch{}return{status:o.status,body:r}}function N(t){let e=t.CORTEX_HOME?a.resolve(t.CORTEX_HOME):a.join($.homedir(),".cortex");return a.join(e,"tmp","signals")}function I(t,e,o){d.mkdirSync(t,{recursive:!0});let s=a.join(t,`${e}.tmp`);d.writeFileSync(s,o),d.renameSync(s,a.join(t,e))}async function L(t,e={}){let o=e.env??process.env;try{let s=R(t);if(s.help||t.length===0)return{exitCode:0,stdout:S(k),stderr:""};let r=s.id??o.CORTEX_SIGNAL_ID??null,l=s.secret??o.CORTEX_SIGNAL_SECRET??null;if(!r||!l)return{exitCode:2,stdout:"",stderr:n("A waitpoint id and secret are required",{hint:"Pass --id/--secret, or export CORTEX_SIGNAL_ID and CORTEX_SIGNAL_SECRET (wait_create prints both)."})};let{status:E,message:f}=j(s),u={id:r,secret:l,status:E};f&&(u.message=f),s.member&&(u.member=s.member);let m=v(s.data);m!==void 0&&(u.data=m);let O=o.WEBHOOK_PORT||"3001",p=s.url??`http://127.0.0.1:${O}/webhook/signal`,_=e.post??A,i;try{i=await _(p,u)}catch(h){if(s.noSpool)return{exitCode:1,stdout:"",stderr:n(`Cannot reach ${p}: ${h.message}`)};let g=e.spoolDir??N(o),x=`${Date.now()}-${process.pid}-${Math.random().toString(36).slice(2,8)}.json`;return I(g,x,JSON.stringify(u)),{exitCode:0,stdout:`spooled ${a.join(g,x)}`,stderr:""}}if(i.status===202)return{exitCode:0,stdout:`accepted${i.body?.fired?" (waitpoint fired)":i.body?.held?" (hourly wake cap reached; the wake is delivered once it clears)":""}`,stderr:""};if(i.status===410)return{exitCode:0,stdout:`already resolved (${i.body?.state??"unknown"})`,stderr:""};let T=typeof i.body=="object"&&i.body?.error?i.body.error:String(i.body??"");return{exitCode:1,stdout:"",stderr:n(`Signal refused (HTTP ${i.status}): ${T}`)}}catch(s){let r=s.cliMessage;return r?{exitCode:2,stdout:"",stderr:r}:{exitCode:1,stdout:"",stderr:s.message}}}async function X(t=process.argv.slice(2)){let e=await L(t);e.stdout&&process.stdout.write(`${e.stdout}
5
+ import{i as g}from"../chunks/chunk-BVEDNESB.js";import{a as x,b as i,c as S,d as u}from"../chunks/chunk-PMG4YGDU.js";import{b as h}from"../chunks/chunk-JGUEIW2W.js";import"../chunks/chunk-T54CZKNJ.js";import"../chunks/chunk-WHC7AYZD.js";import*as a from"node:fs";import*as $ from"node:os";import*as n from"node:path";var O={name:"cortex-signal",description:"Tell Cortex that something it is waiting for has finished.",usage:"cortex-signal [--id wp_\u2026] [--secret \u2026] [--status ok|fail|progress] [--message TEXT] [--exit-code N]",options:[{flag:"--id <wp_\u2026>",description:"Waitpoint id",default:"$CORTEX_SIGNAL_ID"},{flag:"--secret <hex>",description:"Capability issued with the waitpoint",default:"$CORTEX_SIGNAL_SECRET"},{flag:"--status <s>",description:"ok | fail | progress",default:"ok"},{flag:"--exit-code <n>",description:"Set status from a command exit code (0 = ok, else fail)"},{flag:"--message <text>",description:"One-line summary shown in the wake message"},{flag:"--member <name>",description:"Which member of a multi-job waitpoint this is (required when it names members)"},{flag:"--data <@file|->",description:"Extra payload from a file or stdin (treated as data, not instructions)"},{flag:"--url <url>",description:"Daemon signal endpoint",default:"http://127.0.0.1:$CORTEX_UI_PORT/webhook/signal (port from the env, else the home .env)"},{flag:"--no-spool",description:"Fail instead of spooling to disk when the daemon is unreachable or refuses the signal"},{flag:"--help, -h",description:"Show this help"}],examples:[{description:"Report the exit code of the command that just ran",command:"python train.py; cortex-signal --exit-code $?"},{description:"Report one arm of a multi-job waitpoint",command:'cortex-signal --member arm2 --status ok --message "33,120 steps"'},{description:"Attach the tail of a log as data",command:"tail -c 2000 train.log | cortex-signal --exit-code $? --data -"}]},w={"--id":"id","--secret":"secret","--status":"status","--message":"message","--member":"member","--data":"data","--exit-code":"exitCode","--url":"url"},y=["ok","fail","progress"];function R(t){let e={help:!1,id:null,secret:null,status:null,message:null,data:null,member:null,exitCode:null,url:null,noSpool:!1};for(let s=0;s<t.length;s+=1){let o=t[s];if(o==="--help"||o==="-h"){e.help=!0;continue}if(o==="--no-spool"){e.noSpool=!0;continue}let r=w[o];if(!r)throw u(i(`Unknown argument: '${o}'`,{validValues:[...Object.keys(w),"--no-spool","--help"]}));let l=t[s+1];if(l===void 0||l.startsWith("--")&&r!=="message")throw u(i(`${o} requires a value`));e[r]=l,s+=1}return e}function v(t){if(t.status!==null&&!y.includes(t.status))throw u(i(`Invalid --status '${t.status}'`,{validValues:y}));if(t.exitCode===null)return{status:t.status??"ok",message:t.message};let e=Number.parseInt(t.exitCode,10);if(!Number.isFinite(e))throw u(i(`--exit-code must be a number, got '${t.exitCode}'`));return{status:t.status??(e===0?"ok":"fail"),message:t.message??`exit=${e}`}}function j(t){if(t!==null){if(t==="-")return S();if(t.startsWith("@")){let e=t.slice(1);try{return a.readFileSync(e,"utf8")}catch(s){throw u(i(`Cannot read --data file '${e}': ${s.message}`))}}return t}}async function A(t,e){let s=await fetch(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)}),o=await s.text(),r=o;try{r=JSON.parse(o)}catch{}return{status:s.status,body:r}}function b(t){let e=t.CORTEX_HOME?n.resolve(t.CORTEX_HOME):n.join($.homedir(),".cortex");return n.join(e,"tmp","signals")}function N(t,e,s){a.mkdirSync(t,{recursive:!0});let o=n.join(t,`${e}.tmp`);a.writeFileSync(o,s),a.renameSync(o,n.join(t,e))}function C(t,e,s){let o=`${Date.now()}-${process.pid}-${Math.random().toString(36).slice(2,8)}.json`;return N(e,o,JSON.stringify(t)),{exitCode:0,stdout:`spooled ${n.join(e,o)}${s?` (${s})`:""}`,stderr:""}}function E(t){let e=typeof t.body=="object"&&t.body?.error?t.body.error:String(t.body??"");return`HTTP ${t.status}: ${e}`}var I=new Set([401,413,422]);function L(t,e,s){return t.status===202?{exitCode:0,stdout:`accepted${t.body?.fired?" (waitpoint fired)":t.body?.held?" (hourly wake cap reached; the wake is delivered once it clears)":""}`,stderr:""}:t.status===410?{exitCode:0,stdout:`already resolved (${t.body?.state??"unknown"})`,stderr:""}:e||I.has(t.status)?{exitCode:1,stdout:"",stderr:i(`Signal refused (${E(t)})`)}:s()}async function X(t,e={}){let s=e.env??process.env;try{let o=R(t);if(o.help||t.length===0)return{exitCode:0,stdout:x(O),stderr:""};let r=o.id??s.CORTEX_SIGNAL_ID??null,l=o.secret??s.CORTEX_SIGNAL_SECRET??null;if(!r||!l)return{exitCode:2,stdout:"",stderr:i("A waitpoint id and secret are required",{hint:"Pass --id/--secret, or export CORTEX_SIGNAL_ID and CORTEX_SIGNAL_SECRET (wait_create prints both)."})};let{status:_,message:f}=v(o),d={id:r,secret:l,status:_};f&&(d.message=f),o.member&&(d.member=o.member);let m=j(o.data);m!==void 0&&(d.data=m);let p=o.url??`${g(s)}/webhook/signal`,T=e.post??A,c;try{c=await T(p,d)}catch(k){return o.noSpool?{exitCode:1,stdout:"",stderr:i(`Cannot reach ${p}: ${k.message}`)}:C(d,e.spoolDir??b(s),"")}return L(c,o.noSpool,()=>C(d,e.spoolDir??b(s),E(c)))}catch(o){let r=o.cliMessage;return r?{exitCode:2,stdout:"",stderr:r}:{exitCode:1,stdout:"",stderr:o.message}}}async function D(t=process.argv.slice(2)){let e=await X(t);e.stdout&&process.stdout.write(`${e.stdout}
6
6
  `),e.stderr&&process.stderr.write(`${e.stderr}
7
- `),process.exitCode=e.exitCode}w(new URL("dist/entry/signal-cli.js",__cortexPackageRoot).href)&&X();export{X as main,R as parseSignalArgs,L as runSignalCli};
7
+ `),process.exitCode=e.exitCode}h(new URL("dist/entry/signal-cli.js",__cortexPackageRoot).href)&&D();export{D as main,R as parseSignalArgs,X as runSignalCli};