@cortex-agent/server 2026.7.30 → 2026.8.3-2

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 (353) hide show
  1. package/README.md +1 -1
  2. package/defaults/CORTEX.md +1 -0
  3. package/defaults/config/CORTEX.md +2 -1
  4. package/defaults/config/hooks/13-status-md-guard.json +11 -0
  5. package/defaults/config/hooks/CORTEX.md +1 -0
  6. package/defaults/config/mcp-config-empty.json +3 -0
  7. package/defaults/config/thread-templates/agents/benchmark-coder.json +22 -0
  8. package/defaults/config/thread-templates/agents/benchmark-reviewer.json +22 -0
  9. package/defaults/config/thread-templates/agents/coder-reviewer.json +4 -9
  10. package/defaults/config/thread-templates/agents/coder.json +4 -14
  11. package/defaults/config/thread-templates/templates/benchmark-coder-review.json +37 -0
  12. package/defaults/config/thread-templates/templates/coder-review.json +3 -27
  13. package/defaults/context/projects/CORTEX.md +1 -1
  14. package/defaults/data/schedules.json +12 -0
  15. package/defaults/hooks/CORTEX.md +1 -0
  16. package/defaults/hooks/new-session-hook.mjs +2 -2
  17. package/defaults/hooks/status-md-guard.mjs +193 -0
  18. package/defaults/plugins/cortex-coder/.claude-plugin/plugin.json +1 -1
  19. package/defaults/plugins/cortex-coder/skills/develop/SKILL.md +28 -2
  20. package/defaults/plugins/cortex-common/.claude-plugin/plugin.json +1 -1
  21. package/defaults/plugins/cortex-common/skills/compound/SKILL.md +1 -1
  22. package/defaults/plugins/cortex-common/skills/compound-simple/SKILL.md +4 -2
  23. package/defaults/plugins/cortex-common/skills/postmortem/SKILL.md +1 -1
  24. package/defaults/plugins/cortex-stage-gate/.claude-plugin/plugin.json +1 -1
  25. package/defaults/plugins/cortex-stage-gate/skills/director-method/SKILL.md +1 -1
  26. package/defaults/plugins/cortex-stage-gate/skills/need-approval/SKILL.md +1 -0
  27. package/defaults/plugins/cortex-stage-gate/skills/reorient/SKILL.md +2 -2
  28. package/defaults/plugins/cortex-stage-gate/skills/task/SKILL.md +11 -8
  29. package/defaults/plugins/cortex-system/skills/feedback/SKILL.md +1 -1
  30. package/defaults/plugins/cortex-system/skills/project-init/SKILL.md +13 -16
  31. package/defaults/prompts/directives/coder-reviewer.md +24 -20
  32. package/defaults/prompts/directives/coder.md +4 -5
  33. package/defaults/prompts/directives/director.md +4 -10
  34. package/defaults/prompts/directives/manager.md +9 -10
  35. package/defaults/prompts/systemPrompts/worker.md +2 -2
  36. package/defaults/rules/cortex-md.md +31 -0
  37. package/defaults/rules/experiment-format.md +8 -1
  38. package/defaults/rules/issues-md.md +10 -9
  39. package/defaults/rules/meta-conventions.md +5 -4
  40. package/defaults/rules/mission-md.md +2 -1
  41. package/defaults/rules/status-md.md +39 -21
  42. package/dist/agent-adapter/bg-wait.d.ts +10 -12
  43. package/dist/agent-adapter/bg-wait.js +209 -129
  44. package/dist/agent-adapter/claude/adapter-tui.d.ts +3 -1
  45. package/dist/agent-adapter/claude/adapter-tui.js +8 -5
  46. package/dist/agent-adapter/claude/adapter.d.ts +43 -14
  47. package/dist/agent-adapter/claude/adapter.js +276 -161
  48. package/dist/agent-adapter/claude/defaults.d.ts +2 -0
  49. package/dist/agent-adapter/claude/defaults.js +5 -5
  50. package/dist/agent-adapter/claude/event-parser.d.ts +3 -8
  51. package/dist/agent-adapter/claude/event-parser.js +28 -31
  52. package/dist/agent-adapter/claude/hooks-builder.js +4 -3
  53. package/dist/agent-adapter/claude/jsonl-tail.js +54 -35
  54. package/dist/agent-adapter/claude/spawn-args.d.ts +15 -12
  55. package/dist/agent-adapter/claude/spawn-args.js +44 -38
  56. package/dist/agent-adapter/claude/tmux-control.d.ts +4 -17
  57. package/dist/agent-adapter/claude/tmux-control.js +39 -32
  58. package/dist/agent-adapter/event-tee.d.ts +19 -0
  59. package/dist/agent-adapter/event-tee.js +145 -0
  60. package/dist/agent-adapter/index.d.ts +1 -0
  61. package/dist/agent-adapter/index.js +7 -3
  62. package/dist/agent-adapter/normalize/event-types.d.ts +17 -9
  63. package/dist/agent-adapter/normalize/event-types.js +4 -4
  64. package/dist/agent-adapter/pi/adapter.d.ts +16 -4
  65. package/dist/agent-adapter/pi/adapter.js +69 -36
  66. package/dist/agent-adapter/pi/discovery.d.ts +19 -3
  67. package/dist/agent-adapter/pi/discovery.js +81 -43
  68. package/dist/agent-adapter/pi/event-parser.js +4 -2
  69. package/dist/agent-adapter/pi/spawn-args.d.ts +2 -4
  70. package/dist/agent-adapter/pi/spawn-args.js +6 -5
  71. package/dist/agent-adapter/types.d.ts +43 -2
  72. package/dist/agent-adapter/types.js +8 -4
  73. package/dist/core/atomic-write.d.ts +6 -1
  74. package/dist/core/atomic-write.js +183 -7
  75. package/dist/core/cli-utils.d.ts +15 -2
  76. package/dist/core/cli-utils.js +46 -41
  77. package/dist/core/config-generator.d.ts +4 -0
  78. package/dist/core/config-generator.js +34 -21
  79. package/dist/core/json-repository.d.ts +4 -0
  80. package/dist/core/json-repository.js +6 -3
  81. package/dist/core/locales/en.d.ts +94 -0
  82. package/dist/core/locales/slices/commands.d.ts +76 -0
  83. package/dist/core/locales/slices/commands.js +155 -1
  84. package/dist/core/locales/slices/status.d.ts +18 -0
  85. package/dist/core/locales/slices/status.js +43 -2
  86. package/dist/core/log.d.ts +5 -0
  87. package/dist/core/log.js +25 -23
  88. package/dist/core/pi-session-filename.d.ts +2 -0
  89. package/dist/core/pi-session-filename.js +18 -0
  90. package/dist/core/resume-reminder.d.ts +5 -0
  91. package/dist/core/resume-reminder.js +18 -0
  92. package/dist/core/runtime-env.d.ts +1 -0
  93. package/dist/core/runtime-env.js +15 -0
  94. package/dist/core/settings-migration.d.ts +5 -0
  95. package/dist/core/settings-migration.js +128 -0
  96. package/dist/core/settings-spec.d.ts +174 -0
  97. package/dist/core/settings-spec.js +150 -0
  98. package/dist/core/settings.d.ts +10 -0
  99. package/dist/core/settings.js +235 -0
  100. package/dist/core/task-parser.d.ts +11 -1
  101. package/dist/core/task-parser.js +34 -3
  102. package/dist/core/types/agent-types.d.ts +19 -0
  103. package/dist/core/types/agent-types.js +1 -1
  104. package/dist/core/types/thread-types.d.ts +48 -3
  105. package/dist/core/types/thread-types.js +2 -2
  106. package/dist/core/utils.d.ts +21 -1
  107. package/dist/core/utils.js +37 -1
  108. package/dist/domain/agent-run/access-probe-cli.d.ts +7 -0
  109. package/dist/domain/agent-run/access-probe-cli.js +139 -0
  110. package/dist/domain/agent-run/access-probe-policy.d.ts +61 -0
  111. package/dist/domain/agent-run/access-probe-policy.js +614 -0
  112. package/dist/domain/agent-run/access-probe.d.ts +21 -0
  113. package/dist/domain/agent-run/access-probe.js +194 -0
  114. package/dist/domain/agent-run/agent-run-cli.d.ts +19 -0
  115. package/dist/domain/agent-run/agent-run-cli.js +171 -0
  116. package/dist/domain/agent-run/atif.d.ts +54 -0
  117. package/dist/domain/agent-run/atif.js +211 -0
  118. package/dist/domain/agent-run/benchmark-local-thread-orchestrator.d.ts +32 -0
  119. package/dist/domain/agent-run/benchmark-local-thread-orchestrator.js +616 -0
  120. package/dist/domain/agent-run/benchmark-thread-identity.d.ts +34 -0
  121. package/dist/domain/agent-run/benchmark-thread-identity.js +106 -0
  122. package/dist/domain/agent-run/identity.d.ts +62 -0
  123. package/dist/domain/agent-run/identity.js +118 -0
  124. package/dist/domain/agent-run/journal.d.ts +51 -0
  125. package/dist/domain/agent-run/journal.js +259 -0
  126. package/dist/domain/agent-run/manifest-contract.d.ts +44 -0
  127. package/dist/domain/agent-run/manifest-contract.js +134 -0
  128. package/dist/domain/agent-run/manifest.d.ts +51 -0
  129. package/dist/domain/agent-run/manifest.js +801 -0
  130. package/dist/domain/agent-run/pinned-node-process.d.ts +35 -0
  131. package/dist/domain/agent-run/pinned-node-process.js +206 -0
  132. package/dist/domain/agent-run/role-surface.d.ts +4 -0
  133. package/dist/domain/agent-run/role-surface.js +99 -0
  134. package/dist/domain/agent-run/run-config.d.ts +22 -0
  135. package/dist/domain/agent-run/run-config.js +135 -0
  136. package/dist/domain/agent-run/runner.d.ts +7 -0
  137. package/dist/domain/agent-run/runner.js +518 -0
  138. package/dist/domain/agent-run/supervisor.d.ts +78 -0
  139. package/dist/domain/agent-run/supervisor.js +425 -0
  140. package/dist/domain/agent-run/trajectory-merge-cli.d.ts +11 -0
  141. package/dist/domain/agent-run/trajectory-merge-cli.js +111 -0
  142. package/dist/domain/agent-run/trajectory-merge.d.ts +39 -0
  143. package/dist/domain/agent-run/trajectory-merge.js +505 -0
  144. package/dist/domain/agents/config.d.ts +10 -0
  145. package/dist/domain/agents/config.js +149 -44
  146. package/dist/domain/agents/facade.d.ts +42 -7
  147. package/dist/domain/agents/facade.js +174 -170
  148. package/dist/domain/agents/provider-run-lifecycle.d.ts +18 -0
  149. package/dist/domain/agents/provider-run-lifecycle.js +60 -0
  150. package/dist/domain/auth/auth-events.d.ts +18 -0
  151. package/dist/domain/auth/auth-events.js +38 -0
  152. package/dist/domain/auth/auth-format.d.ts +2 -0
  153. package/dist/domain/auth/auth-format.js +58 -0
  154. package/dist/domain/auth/auth-status.d.ts +61 -0
  155. package/dist/domain/auth/auth-status.js +304 -0
  156. package/dist/domain/auth/auth-watch.d.ts +16 -0
  157. package/dist/domain/auth/auth-watch.js +125 -0
  158. package/dist/domain/auth/cc-login.d.ts +7 -0
  159. package/dist/domain/auth/cc-login.js +16 -0
  160. package/dist/domain/auth/cc-subscription.d.ts +38 -0
  161. package/dist/domain/auth/cc-subscription.js +204 -0
  162. package/dist/domain/auth/index.d.ts +12 -0
  163. package/dist/domain/auth/index.js +16 -0
  164. package/dist/domain/auth/login-flow.d.ts +120 -0
  165. package/dist/domain/auth/login-flow.js +253 -0
  166. package/dist/domain/auth/login-service.d.ts +32 -0
  167. package/dist/domain/auth/login-service.js +97 -0
  168. package/dist/domain/auth/logout.d.ts +32 -0
  169. package/dist/domain/auth/logout.js +123 -0
  170. package/dist/domain/auth/pi-login.d.ts +36 -0
  171. package/dist/domain/auth/pi-login.js +72 -0
  172. package/dist/domain/auth/pi-oauth.d.ts +36 -0
  173. package/dist/domain/auth/pi-oauth.js +84 -0
  174. package/dist/domain/auth/pi-runtime.d.ts +72 -0
  175. package/dist/domain/auth/pi-runtime.js +86 -0
  176. package/dist/domain/mcp/benchmark-thread-server.d.ts +1 -0
  177. package/dist/domain/mcp/benchmark-thread-server.js +26 -0
  178. package/dist/domain/mcp/tools/benchmark-thread-run.d.ts +23 -0
  179. package/dist/domain/mcp/tools/benchmark-thread-run.js +146 -0
  180. package/dist/domain/memory/user-context.js +6 -8
  181. package/dist/domain/monitor/disk-monitor.js +47 -16
  182. package/dist/domain/projects/project-store.js +23 -6
  183. package/dist/domain/remote/client-hot-reload.d.ts +9 -1
  184. package/dist/domain/remote/client-hot-reload.js +60 -12
  185. package/dist/domain/remote/client-manager.js +12 -6
  186. package/dist/domain/scheduling/jobs/auth-expiry-scan.d.ts +14 -0
  187. package/dist/domain/scheduling/jobs/auth-expiry-scan.js +86 -0
  188. package/dist/domain/scheduling/jobs/task-dispatch.js +36 -40
  189. package/dist/domain/scheduling/runner.d.ts +2 -0
  190. package/dist/domain/scheduling/runner.js +7 -4
  191. package/dist/domain/sessions/session-backup.d.ts +14 -20
  192. package/dist/domain/sessions/session-backup.js +57 -68
  193. package/dist/domain/system/doctor.d.ts +4 -0
  194. package/dist/domain/system/doctor.js +113 -28
  195. package/dist/domain/system/install-cli.js +8 -3
  196. package/dist/domain/system/server-update-check.js +7 -5
  197. package/dist/domain/system/system-notice.d.ts +3 -1
  198. package/dist/domain/system/system-notice.js +6 -11
  199. package/dist/domain/tasks/archiver.d.ts +1 -0
  200. package/dist/domain/tasks/archiver.js +13 -7
  201. package/dist/domain/tasks/claim-recovery.d.ts +3 -3
  202. package/dist/domain/tasks/claim-recovery.js +12 -8
  203. package/dist/domain/tasks/dispatch-utils.d.ts +15 -14
  204. package/dist/domain/tasks/dispatch-utils.js +22 -18
  205. package/dist/domain/tasks/dispatcher.d.ts +1 -0
  206. package/dist/domain/tasks/dispatcher.js +9 -5
  207. package/dist/domain/tasks/mutator.d.ts +21 -11
  208. package/dist/domain/tasks/mutator.js +30 -24
  209. package/dist/domain/tasks/pending-tracker.d.ts +5 -2
  210. package/dist/domain/tasks/pending-tracker.js +11 -5
  211. package/dist/domain/tasks/system/cortex-run.d.ts +2 -1
  212. package/dist/domain/tasks/system/cortex-run.js +24 -4
  213. package/dist/domain/tasks/system/task-cli.d.ts +1 -0
  214. package/dist/domain/tasks/system/task-cli.js +72 -22
  215. package/dist/domain/tasks/system/task-completion.d.ts +19 -2
  216. package/dist/domain/tasks/system/task-completion.js +31 -17
  217. package/dist/domain/tasks/system/task-file-input.d.ts +10 -0
  218. package/dist/domain/tasks/system/task-file-input.js +57 -0
  219. package/dist/domain/tasks/system/task-id-utils.d.ts +9 -9
  220. package/dist/domain/tasks/system/task-id-utils.js +13 -4
  221. package/dist/domain/tasks/system/task-lifecycle-edit.d.ts +6 -2
  222. package/dist/domain/tasks/system/task-lifecycle-edit.js +200 -6
  223. package/dist/domain/tasks/system/task-lock.js +19 -5
  224. package/dist/domain/tasks/system/task-mutations.d.ts +22 -12
  225. package/dist/domain/tasks/system/task-mutations.js +28 -4
  226. package/dist/domain/tasks/system/task-process.js +10 -8
  227. package/dist/domain/tasks/system/task-state.d.ts +65 -11
  228. package/dist/domain/tasks/system/task-state.js +86 -13
  229. package/dist/domain/threads/local-runtime-deps.d.ts +32 -0
  230. package/dist/domain/threads/local-runtime-deps.js +91 -0
  231. package/dist/domain/threads/local-runtime-scope.d.ts +6 -0
  232. package/dist/domain/threads/local-runtime-scope.js +12 -0
  233. package/dist/domain/threads/pending-user-inputs.d.ts +3 -0
  234. package/dist/domain/threads/pending-user-inputs.js +37 -0
  235. package/dist/domain/threads/prompt-builder.d.ts +12 -1
  236. package/dist/domain/threads/prompt-builder.js +73 -26
  237. package/dist/domain/threads/runner.d.ts +15 -3
  238. package/dist/domain/threads/runner.js +261 -105
  239. package/dist/domain/threads/state-machine.d.ts +1 -1
  240. package/dist/domain/threads/state-machine.js +17 -8
  241. package/dist/domain/ui-service/app-router.d.ts +86 -6
  242. package/dist/domain/ui-service/app-router.js +171 -133
  243. package/dist/domain/ui-service/input-schemas.d.ts +132 -10
  244. package/dist/domain/ui-service/input-schemas.js +59 -5
  245. package/dist/domain/ui-service/mutate/approvals.d.ts +2 -1
  246. package/dist/domain/ui-service/mutate/approvals.js +2 -1
  247. package/dist/domain/ui-service/mutate/auth.d.ts +6 -0
  248. package/dist/domain/ui-service/mutate/auth.js +83 -0
  249. package/dist/domain/ui-service/mutate/config.js +11 -10
  250. package/dist/domain/ui-service/query/approvals.js +3 -0
  251. package/dist/domain/ui-service/query/auth.d.ts +6 -0
  252. package/dist/domain/ui-service/query/auth.js +12 -0
  253. package/dist/domain/ui-service/query/config.d.ts +5 -5
  254. package/dist/domain/ui-service/query/config.js +27 -17
  255. package/dist/domain/ui-service/query/tasks.d.ts +1 -1
  256. package/dist/domain/ui-service/query/tasks.js +69 -30
  257. package/dist/domain/ui-service/query/threads.js +3 -3
  258. package/dist/domain/ui-service/types.d.ts +67 -8
  259. package/dist/domain/ui-service/types.js +2 -2
  260. package/dist/domain/ui-service/ui-service.js +16 -2
  261. package/dist/entry/admin-channel-hot-reload.d.ts +4 -0
  262. package/dist/entry/admin-channel-hot-reload.js +22 -0
  263. package/dist/entry/app.js +38 -38
  264. package/dist/entry/auth-cli.d.ts +10 -0
  265. package/dist/entry/auth-cli.js +52 -0
  266. package/dist/entry/cli-help.d.ts +5 -0
  267. package/dist/entry/cli-help.js +130 -0
  268. package/dist/entry/cli.d.ts +5 -5
  269. package/dist/entry/cli.js +174 -248
  270. package/dist/entry/daemon.d.ts +11 -0
  271. package/dist/entry/daemon.js +204 -103
  272. package/dist/entry/draft-attachments.d.ts +8 -0
  273. package/dist/entry/draft-attachments.js +83 -0
  274. package/dist/entry/feishu-login.d.ts +2 -6
  275. package/dist/entry/feishu-login.js +16 -21
  276. package/dist/entry/init.js +6 -4
  277. package/dist/entry/start-ui-http.d.ts +2 -8
  278. package/dist/entry/start-ui-http.js +7 -34
  279. package/dist/events/event-logger.js +11 -13
  280. package/dist/events/event-types.d.ts +19 -1
  281. package/dist/events/event-types.js +3 -3
  282. package/dist/events/index.d.ts +1 -1
  283. package/dist/events/index.js +3 -3
  284. package/dist/hooks/new-session-hook.mjs +2 -2
  285. package/dist/hooks/status-md-guard.mjs +193 -0
  286. package/dist/orchestration/agent-file-send.js +44 -14
  287. package/dist/orchestration/agent-runner.d.ts +7 -3
  288. package/dist/orchestration/agent-runner.js +65 -41
  289. package/dist/orchestration/conversation-runner.d.ts +5 -1
  290. package/dist/orchestration/conversation-runner.js +16 -7
  291. package/dist/orchestration/lifecycle.d.ts +23 -1
  292. package/dist/orchestration/lifecycle.js +103 -40
  293. package/dist/orchestration/mid-turn-inject.d.ts +2 -0
  294. package/dist/orchestration/mid-turn-inject.js +29 -13
  295. package/dist/orchestration/resume-dispatcher.d.ts +3 -5
  296. package/dist/orchestration/resume-dispatcher.js +9 -17
  297. package/dist/orchestration/routing/commands/index.d.ts +4 -1
  298. package/dist/orchestration/routing/commands/index.js +83 -61
  299. package/dist/orchestration/routing/commands/login-notice.d.ts +21 -0
  300. package/dist/orchestration/routing/commands/login-notice.js +97 -0
  301. package/dist/orchestration/routing/commands/login.d.ts +12 -0
  302. package/dist/orchestration/routing/commands/login.js +555 -0
  303. package/dist/orchestration/routing/commands/status.js +45 -59
  304. package/dist/orchestration/routing/edit-handler.d.ts +5 -0
  305. package/dist/orchestration/routing/edit-handler.js +127 -73
  306. package/dist/orchestration/routing/webhook.js +5 -4
  307. package/dist/orchestration/session-rewind.d.ts +5 -1
  308. package/dist/orchestration/session-rewind.js +106 -62
  309. package/dist/orchestration/session-send.d.ts +2 -0
  310. package/dist/orchestration/session-send.js +5 -6
  311. package/dist/orchestration/status-helpers.d.ts +1 -2
  312. package/dist/orchestration/status-helpers.js +7 -10
  313. package/dist/orchestration/thread-callback.d.ts +19 -11
  314. package/dist/orchestration/thread-callback.js +132 -61
  315. package/dist/orchestration/thread-executor.js +37 -27
  316. package/dist/orchestration/turn-mutation-lock.d.ts +3 -0
  317. package/dist/orchestration/turn-mutation-lock.js +36 -0
  318. package/dist/orchestration/turn-notify.d.ts +2 -5
  319. package/dist/orchestration/turn-notify.js +9 -21
  320. package/dist/platform/adapter.d.ts +1 -0
  321. package/dist/platform/adapter.js +2 -2
  322. package/dist/platform/adapters/composite-adapter.d.ts +2 -0
  323. package/dist/platform/adapters/composite-adapter.js +13 -3
  324. package/dist/platform/adapters/feishu.d.ts +2 -4
  325. package/dist/platform/adapters/feishu.js +38 -59
  326. package/dist/platform/adapters/index.d.ts +1 -1
  327. package/dist/platform/adapters/index.js +13 -12
  328. package/dist/platform/adapters/slack.d.ts +1 -1
  329. package/dist/platform/adapters/slack.js +12 -35
  330. package/dist/platform/index.d.ts +2 -1
  331. package/dist/platform/index.js +3 -3
  332. package/dist/platform/testing.d.ts +1 -0
  333. package/dist/platform/testing.js +13 -4
  334. package/dist/platform/tool-trace.js +6 -11
  335. package/dist/platform/ui-http/ui-http-server.d.ts +1 -1
  336. package/dist/platform/ui-http/ui-http-server.js +6 -18
  337. package/dist/store/execution-repo.d.ts +17 -1
  338. package/dist/store/execution-repo.js +55 -4
  339. package/dist/store/prompt-migration-replacements.d.ts +4 -0
  340. package/dist/store/prompt-migration-replacements.js +149 -0
  341. package/dist/store/thread-repo.d.ts +15 -4
  342. package/dist/store/thread-repo.js +61 -24
  343. package/dist/store/version-migrations.js +36 -1
  344. package/native/cortex-supervisor/dist/build-manifest.json +22 -0
  345. package/native/cortex-supervisor/dist/cortex-supervisor +0 -0
  346. package/package.json +5 -2
  347. package/web/dist/assets/index-XqBCYtkw.js +139 -0
  348. package/web/dist/assets/index-zpf3OSKC.css +1 -0
  349. package/web/dist/index.html +2 -2
  350. package/dist/domain/scheduling/jobs/failed-dispatch-reconciliation.d.ts +0 -1
  351. package/dist/domain/scheduling/jobs/failed-dispatch-reconciliation.js +0 -78
  352. package/web/dist/assets/index-B19jLgji.js +0 -138
  353. package/web/dist/assets/index-BuFyPyRW.css +0 -1
@@ -0,0 +1,23 @@
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ import { z } from 'zod';
3
+ export declare const BENCHMARK_THREAD_POLICY_ENV = "CORTEX_BENCHMARK_THREAD_POLICY_PATH";
4
+ export declare const MAX_BENCHMARK_HANDOFF_LENGTH = 2000;
5
+ declare const policySchema: z.ZodObject<{
6
+ schema_version: z.ZodLiteral<"cortex-benchmark-thread-policy/1">;
7
+ canonical_instruction: z.ZodString;
8
+ workspace_cwd: z.ZodString;
9
+ template: z.ZodLiteral<"benchmark-coder-review">;
10
+ profile_name: z.ZodString;
11
+ root_run_id: z.ZodString;
12
+ trajectory_root: z.ZodString;
13
+ limits: z.ZodObject<{
14
+ max_calls: z.ZodLiteral<1>;
15
+ max_steps: z.ZodNumber;
16
+ max_cost_usd: z.ZodNumber;
17
+ deadline_epoch_ms: z.ZodNumber;
18
+ }, z.core.$strict>;
19
+ }, z.core.$strict>;
20
+ type BenchmarkThreadPolicy = Readonly<z.infer<typeof policySchema>>;
21
+ export declare function loadBenchmarkThreadPolicy(env?: NodeJS.ProcessEnv): BenchmarkThreadPolicy;
22
+ export declare function registerBenchmarkThreadRunTool(server: McpServer, policy: BenchmarkThreadPolicy, shutdownSignal: AbortSignal): void;
23
+ export {};
@@ -0,0 +1,146 @@
1
+ // input: immutable benchmark policy, MCP request signal, local orchestrator
2
+ // output: one bounded blocking thread_run tool registration
3
+ // pos: Benchmark-only thread admission and result boundary
4
+ // >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { z } from 'zod';
8
+ import { runBenchmarkThread, } from '../../agent-run/benchmark-local-thread-orchestrator.js';
9
+ export const BENCHMARK_THREAD_POLICY_ENV = 'CORTEX_BENCHMARK_THREAD_POLICY_PATH';
10
+ export const MAX_BENCHMARK_HANDOFF_LENGTH = 2_000;
11
+ const MAX_BENCHMARK_SUMMARY_CODE_POINTS = 2_000;
12
+ const policySchema = z.object({
13
+ schema_version: z.literal('cortex-benchmark-thread-policy/1'),
14
+ canonical_instruction: z.string().min(1),
15
+ workspace_cwd: z.string().min(1).refine(path.isAbsolute, 'workspace_cwd must be absolute'),
16
+ template: z.literal('benchmark-coder-review'),
17
+ profile_name: z.string().min(1),
18
+ root_run_id: z.string().min(1),
19
+ trajectory_root: z.string().min(1).refine(path.isAbsolute, 'trajectory_root must be absolute'),
20
+ limits: z.object({
21
+ max_calls: z.literal(1),
22
+ max_steps: z.number().int().positive(),
23
+ max_cost_usd: z.number().nonnegative().finite(),
24
+ deadline_epoch_ms: z.number().int().positive(),
25
+ }).strict(),
26
+ }).strict();
27
+ const inputSchema = z.object({
28
+ handoff: z.string().max(MAX_BENCHMARK_HANDOFF_LENGTH).optional(),
29
+ }).strict();
30
+ const summarySchema = z.string()
31
+ .max(MAX_BENCHMARK_SUMMARY_CODE_POINTS * 2)
32
+ .refine(value => Array.from(value).length <= MAX_BENCHMARK_SUMMARY_CODE_POINTS, `Summary must not exceed ${MAX_BENCHMARK_SUMMARY_CODE_POINTS} Unicode code points`);
33
+ const outputSchema = z.object({
34
+ thread_id: z.string().min(1),
35
+ status: z.literal('completed'),
36
+ artifact_path: z.string().nullable(),
37
+ trajectory_paths: z.object({ journal: z.string(), manifest: z.string() }).strict(),
38
+ steps: z.number().int().nonnegative(),
39
+ cost_usd: z.number().nonnegative(),
40
+ duration_ms: z.number().nonnegative(),
41
+ summary: summarySchema,
42
+ }).strict();
43
+ function readPolicyFile(file) {
44
+ if (!path.isAbsolute(file))
45
+ throw new Error(`${BENCHMARK_THREAD_POLICY_ENV} must be absolute`);
46
+ const stat = fs.statSync(file);
47
+ if (!stat.isFile())
48
+ throw new Error('Benchmark thread policy must be a regular file');
49
+ if ((stat.mode & 0o222) !== 0)
50
+ throw new Error('Benchmark thread policy must be read-only');
51
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
52
+ }
53
+ export function loadBenchmarkThreadPolicy(env = process.env) {
54
+ const file = env[BENCHMARK_THREAD_POLICY_ENV];
55
+ if (!file)
56
+ throw new Error(`${BENCHMARK_THREAD_POLICY_ENV} is required`);
57
+ const policy = policySchema.parse(readPolicyFile(file));
58
+ Object.freeze(policy.limits);
59
+ return Object.freeze(policy);
60
+ }
61
+ function linkedSignal(request, shutdown) {
62
+ const controller = new AbortController();
63
+ const link = (signal) => {
64
+ if (signal.aborted)
65
+ controller.abort(signal.reason);
66
+ else
67
+ signal.addEventListener('abort', () => controller.abort(signal.reason), { once: true });
68
+ };
69
+ link(request);
70
+ link(shutdown);
71
+ return controller.signal;
72
+ }
73
+ function orchestratorRequest(policy, input, signal) {
74
+ return {
75
+ workspaceCwd: policy.workspace_cwd,
76
+ template: policy.template,
77
+ instruction: policy.canonical_instruction,
78
+ handoff: input.handoff,
79
+ profileName: policy.profile_name,
80
+ rootRunId: policy.root_run_id,
81
+ trajectoryRoot: policy.trajectory_root,
82
+ limits: {
83
+ maxSteps: policy.limits.max_steps,
84
+ maxCostUsd: policy.limits.max_cost_usd,
85
+ deadlineEpochMs: policy.limits.deadline_epoch_ms,
86
+ },
87
+ signal,
88
+ };
89
+ }
90
+ function successPayload(result) {
91
+ return {
92
+ thread_id: result.threadId,
93
+ status: 'completed',
94
+ artifact_path: result.artifactPath,
95
+ trajectory_paths: { journal: result.journalPath, manifest: result.manifestPath },
96
+ steps: result.steps,
97
+ cost_usd: result.costUsd,
98
+ duration_ms: result.durationMs,
99
+ summary: result.summary,
100
+ };
101
+ }
102
+ function textResult(payload, isError = false) {
103
+ return {
104
+ content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }],
105
+ ...(isError ? { isError: true } : {}),
106
+ };
107
+ }
108
+ function failedRunResult(result) {
109
+ return textResult({
110
+ code: `benchmark_thread_${result.state}`,
111
+ status: result.state,
112
+ terminal_reason: result.terminalReason,
113
+ }, true);
114
+ }
115
+ function callLimitResult() {
116
+ return textResult({
117
+ code: 'benchmark_thread_call_limit_exceeded',
118
+ message: 'thread_run has already been admitted for this trial',
119
+ }, true);
120
+ }
121
+ export function registerBenchmarkThreadRunTool(server, policy, shutdownSignal) {
122
+ let admitted = false;
123
+ server.registerTool('thread_run', {
124
+ description: 'Run the trial policy\'s fixed benchmark coder-review thread once and block until its durable terminal state is committed. The optional handoff adds supplementary context; execution policy cannot be supplied through tool input.',
125
+ inputSchema,
126
+ outputSchema,
127
+ }, async (input, extra) => {
128
+ if (admitted)
129
+ return callLimitResult();
130
+ admitted = true;
131
+ try {
132
+ const signal = linkedSignal(extra.signal, shutdownSignal);
133
+ const result = await runBenchmarkThread(orchestratorRequest(policy, input, signal));
134
+ if (result.state !== 'completed' || !result.manifestCommitted) {
135
+ return failedRunResult(result);
136
+ }
137
+ const payload = successPayload(result);
138
+ return { ...textResult(payload), structuredContent: payload };
139
+ }
140
+ catch (error) {
141
+ return textResult({
142
+ code: 'benchmark_thread_run_failed', message: error.message,
143
+ }, true);
144
+ }
145
+ });
146
+ }
@@ -1,12 +1,10 @@
1
- // input: CONTEXT_DIR, fs
2
- // output: loadUserContext()
3
- // pos: user profile injection — reads USER.md and injects into thread-free conversation
4
- // turns only (buildConversationPrompt), and only on a session's FIRST turn (the caller
5
- // gates via includeUserContext; session resume keeps it in history thereafter).
6
- // Thread steps never carry the user profile.
7
- // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
1
+ // input: context path, filesystem, runtime settings
2
+ // output: loadUserContext
3
+ // pos: Loads the user profile for direct conversation turns
4
+ // >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
8
5
  import { readFileSync, statSync } from 'fs';
9
6
  import * as path from 'path';
7
+ import { getSettings } from '../../core/settings.js';
10
8
  import { CONTEXT_DIR } from '../../core/utils.js';
11
9
  const USER_MD_PATH = path.join(CONTEXT_DIR, 'user', 'USER.md');
12
10
  let cachedContent = null;
@@ -30,7 +28,7 @@ function readUserMd() {
30
28
  * do NOT inject this — only the direct conversation path calls it.
31
29
  */
32
30
  export function loadUserContext() {
33
- if (process.env.CORTEX_DISABLE_USER_CONTEXT === '1')
31
+ if (getSettings().disableUserContext)
34
32
  return null;
35
33
  const content = readUserMd();
36
34
  if (!content)
@@ -1,19 +1,23 @@
1
- // input: PlatformAdapter, periodic timer, fs.statfs
1
+ // input: PlatformAdapter, settings, DATA_DIR, fs.statfs
2
2
  // output: init/stop/checkDiskOnce + alert helpers
3
- // pos: root filesystem capacity alert monitoring
3
+ // pos: Cortex data filesystem capacity alert monitoring
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
5
  import { promises as fsp } from 'fs';
6
6
  import { emitSystemNotice } from '../system/system-notice.js';
7
7
  import { createLogger } from '../../core/log.js';
8
+ import { DATA_DIR } from '../../core/paths.js';
9
+ import { getSettings, onSettingsChange } from '../../core/settings.js';
8
10
  import { Icons } from '../../core/icons.js';
9
11
  const log = createLogger('disk-monitor');
10
12
  const DEFAULT_CHECK_INTERVAL_MS = 5 * 60 * 1000;
11
13
  const WARN_BYTES = 500 * 1024 * 1024;
12
14
  const HYSTERESIS_BYTES = 1024 * 1024 * 1024;
13
15
  const REALERT_COOLDOWN_MS = 60 * 60 * 1000;
14
- const WATCH_PATH = '/';
16
+ const WATCH_PATH = DATA_DIR;
15
17
  let _adapter = null;
16
18
  let _timer = null;
19
+ let _unsubscribeSettings = null;
20
+ let _intervalMs = DEFAULT_CHECK_INTERVAL_MS;
17
21
  let _state = { hasAlerted: false, lastAlertAt: null };
18
22
  function formatBytes(bytes) {
19
23
  if (bytes >= 1024 * 1024 * 1024)
@@ -49,6 +53,8 @@ function sendDM(text) {
49
53
  void emitSystemNotice(_adapter, { text, level: 'warning', title: 'Disk' });
50
54
  }
51
55
  async function checkDiskOnce() {
56
+ if (!getSettings().diskMonitor)
57
+ return;
52
58
  let freeBytes;
53
59
  try {
54
60
  freeBytes = await getFreeBytes(WATCH_PATH);
@@ -57,6 +63,8 @@ async function checkDiskOnce() {
57
63
  log.error(`statfs(${WATCH_PATH}) failed: ${e.message}`);
58
64
  return;
59
65
  }
66
+ if (!getSettings().diskMonitor)
67
+ return;
60
68
  const decision = shouldAlert(freeBytes, _state, Date.now());
61
69
  _state = decision.newState;
62
70
  if (decision.alert) {
@@ -65,28 +73,51 @@ async function checkDiskOnce() {
65
73
  sendDM(msg);
66
74
  }
67
75
  }
76
+ function stopTimer() {
77
+ if (!_timer)
78
+ return;
79
+ clearInterval(_timer);
80
+ _timer = null;
81
+ }
82
+ function startTimer() {
83
+ if (_timer)
84
+ return;
85
+ _timer = setInterval(() => {
86
+ checkDiskOnce().catch(e => log.error(`check failed: ${e.message}`));
87
+ }, _intervalMs);
88
+ checkDiskOnce().catch(e => log.error(`initial check failed: ${e.message}`));
89
+ }
90
+ function syncMonitorState() {
91
+ if (!getSettings().diskMonitor) {
92
+ stopTimer();
93
+ _state = { hasAlerted: false, lastAlertAt: null };
94
+ return;
95
+ }
96
+ startTimer();
97
+ }
68
98
  function initDiskMonitor(adapter, intervalMs = DEFAULT_CHECK_INTERVAL_MS) {
69
- if (_timer) {
99
+ if (_adapter) {
70
100
  log.info('Already initialized, skipping');
71
101
  return;
72
102
  }
73
103
  _adapter = adapter;
74
- _timer = setInterval(() => { checkDiskOnce().catch(e => log.error(`check failed: ${e.message}`)); }, intervalMs);
75
- checkDiskOnce().catch(e => log.error(`initial check failed: ${e.message}`));
76
- log.info(`Initialized (interval=${Math.round(intervalMs / 1000)}s, warn<${formatBytes(WARN_BYTES)}, recover>=${formatBytes(HYSTERESIS_BYTES)})`);
104
+ _intervalMs = intervalMs;
105
+ _unsubscribeSettings = onSettingsChange((changedKeys) => {
106
+ if (changedKeys.includes('diskMonitor'))
107
+ syncMonitorState();
108
+ });
109
+ syncMonitorState();
110
+ log.info(`Initialized (path=${WATCH_PATH}, enabled=${getSettings().diskMonitor}, interval=${Math.round(intervalMs / 1000)}s, warn<${formatBytes(WARN_BYTES)}, recover>=${formatBytes(HYSTERESIS_BYTES)})`);
77
111
  }
78
112
  function stopDiskMonitor() {
79
- if (_timer) {
80
- clearInterval(_timer);
81
- _timer = null;
82
- }
113
+ stopTimer();
114
+ _unsubscribeSettings?.();
115
+ _unsubscribeSettings = null;
83
116
  _adapter = null;
117
+ _intervalMs = DEFAULT_CHECK_INTERVAL_MS;
118
+ _state = { hasAlerted: false, lastAlertAt: null };
84
119
  }
85
120
  function _testReset() {
86
- if (_timer)
87
- clearInterval(_timer);
88
- _timer = null;
89
- _adapter = null;
90
- _state = { hasAlerted: false, lastAlertAt: null };
121
+ stopDiskMonitor();
91
122
  }
92
123
  export { initDiskMonitor, stopDiskMonitor, checkDiskOnce, shouldAlert, formatBytes, WARN_BYTES, HYSTERESIS_BYTES, REALERT_COOLDOWN_MS, _testReset, };
@@ -11,11 +11,28 @@ import { PROJECTS_DIR } from '../../core/paths.js';
11
11
  import { createLogger } from '../../core/log.js';
12
12
  const log = createLogger('project-store');
13
13
  const DEBOUNCE_MS = 1000;
14
- const GENERAL_SCAFFOLD_STATUS = `# general
15
-
16
- Status: active
17
-
18
- `;
14
+ /** STATUS.md scaffold following the state-register skeleton (rules/status-md.md). */
15
+ function scaffoldStatus(id, situation, nextStep) {
16
+ return [
17
+ `# ${id} Status`,
18
+ '',
19
+ 'Updated: —',
20
+ '',
21
+ '## Current Situation',
22
+ situation,
23
+ '',
24
+ '## In Flight & New Variables',
25
+ 'none',
26
+ '',
27
+ '## Blockers & Pending Decisions',
28
+ 'none',
29
+ '',
30
+ '## Next Step',
31
+ nextStep,
32
+ '',
33
+ ].join('\n');
34
+ }
35
+ const GENERAL_SCAFFOLD_STATUS = scaffoldStatus('general', 'Synthetic umbrella project — collects work not scoped to a specific project.', 'none');
19
36
  const GENERAL_SCAFFOLD_CORTEX = `# general
20
37
 
21
38
  Synthetic umbrella project — always present. Created automatically by the system.
@@ -122,7 +139,7 @@ export class ProjectStore {
122
139
  if (this.exists(id) || fs.existsSync(projectDir)) {
123
140
  return { ok: false, code: 'already-exists', message: `Project already exists: ${id}` };
124
141
  }
125
- this.scaffoldProject(projectDir, `# ${id}\n\nStatus: active\n\n`, `# ${id}\n\n${id} project.\n`);
142
+ this.scaffoldProject(projectDir, scaffoldStatus(id, 'New project — not yet oriented.', 'Define mission.md and roadmap.md.'), `# ${id}\n\n${id} project.\n`);
126
143
  log.info(`Created project at ${projectDir}`);
127
144
  // Refresh the cache so the new project is immediately visible.
128
145
  this.scan();
@@ -1,3 +1,4 @@
1
+ import { type MachineEntry } from '../tasks/dispatch-utils.js';
1
2
  interface DeviceResult {
2
3
  device: string;
3
4
  updated: boolean;
@@ -13,6 +14,13 @@ interface ClientUpdateResult {
13
14
  devices: DeviceResult[];
14
15
  duration: number;
15
16
  }
17
+ /**
18
+ * Remote counterpart of resolveNpmGlobalPrefix: same derivation, done in the
19
+ * remote shell (the prefix is a property of the remote host, not of this one).
20
+ * Windows hosts keep the plain command — npm there installs into the roaming
21
+ * prefix owned by the user, so EACCES is not a failure mode.
22
+ */
23
+ declare function buildRemoteNpmUpdateCommand(reg: MachineEntry): string;
16
24
  interface LocalUpdateDeps {
17
25
  getInstalledVersion: () => string | null;
18
26
  kill: () => Promise<boolean>;
@@ -22,5 +30,5 @@ interface LocalUpdateDeps {
22
30
  declare function updateClientReleaseLocal(device: string, latestVersion: string, deps: LocalUpdateDeps): Promise<DeviceResult>;
23
31
  declare function checkAndUpdateClients(): Promise<ClientUpdateResult | null>;
24
32
  declare function formatUpdateSlackMessage(result: ClientUpdateResult): string;
25
- export { checkAndUpdateClients, formatUpdateSlackMessage, updateClientReleaseLocal };
33
+ export { checkAndUpdateClients, formatUpdateSlackMessage, updateClientReleaseLocal, buildRemoteNpmUpdateCommand, };
26
34
  export type { ClientUpdateResult, DeviceResult, LocalUpdateDeps };
@@ -7,10 +7,10 @@
7
7
  // (local npm + process.kill + detached respawn).
8
8
  import * as fs from 'fs';
9
9
  import * as path from 'path';
10
- import { execSync, execFile, spawn } from 'child_process';
10
+ import { execSync, execFile, execFileSync, spawn } from 'child_process';
11
11
  import { getMachineRegistry } from '../tasks/dispatch-utils.js';
12
12
  import { sshExec, clientPids, buildRemoteSpawnCommand, buildRemoteInstallCommand } from './client-manager.js';
13
- import { STORE_DIR } from '../../core/utils.js';
13
+ import { STORE_DIR, withNpmPrefix } from '../../core/utils.js';
14
14
  import { createLogger } from '../../core/log.js';
15
15
  import { Icons } from '../../core/icons.js';
16
16
  const log = createLogger('client-hot-reload');
@@ -128,6 +128,32 @@ function scpToRemote(host, localPath, remotePath, timeout = 60000) {
128
128
  });
129
129
  });
130
130
  }
131
+ // --- Release mode: npm global prefix resolution ---
132
+ const CLIENT_PKG = '@cortex-agent/client';
133
+ /**
134
+ * The client is installed as the `cortex-client` binary — resolve the npm global
135
+ * prefix from it (see resolveNpmGlobalPrefix), so the version probe and the update
136
+ * both act on the root the client actually lives in rather than npm's default.
137
+ */
138
+ function clientNpmArgs(args) {
139
+ return withNpmPrefix(args, 'cortex-client');
140
+ }
141
+ /**
142
+ * Remote counterpart of resolveNpmGlobalPrefix: same derivation, done in the
143
+ * remote shell (the prefix is a property of the remote host, not of this one).
144
+ * Windows hosts keep the plain command — npm there installs into the roaming
145
+ * prefix owned by the user, so EACCES is not a failure mode.
146
+ */
147
+ function buildRemoteNpmUpdateCommand(reg) {
148
+ const plain = `npm update -g ${CLIENT_PKG} 2>&1`;
149
+ if (reg.win)
150
+ return plain;
151
+ return [
152
+ 'b="$(command -v cortex-client 2>/dev/null)"; p=""',
153
+ '[ -n "$b" ] && p="$(dirname "$(dirname "$b")")"',
154
+ `if [ -n "$p" ] && [ -d "$p/lib/node_modules" ]; then npm update -g --prefix "$p" ${CLIENT_PKG} 2>&1; else ${plain}; fi`,
155
+ ].join('; ');
156
+ }
131
157
  // --- Release mode: npm registry helpers ---
132
158
  function getNpmRegistryVersion() {
133
159
  try {
@@ -143,14 +169,22 @@ function getNpmRegistryVersion() {
143
169
  }
144
170
  }
145
171
  function getLocalInstalledVersion() {
172
+ // Must use the same prefix as the update below, or the probe reads a different
173
+ // (empty) global root and reports the client as missing on every check.
174
+ let out = '';
146
175
  try {
147
- const result = execSync('npm ls -g @cortex-agent/client --json 2>/dev/null || true', {
176
+ out = execFileSync('npm', clientNpmArgs(['ls', '-g', CLIENT_PKG, '--json']), {
148
177
  encoding: 'utf8',
149
178
  timeout: 15000,
150
179
  stdio: 'pipe',
151
180
  }).trim();
152
- const parsed = JSON.parse(result);
153
- return parsed?.dependencies?.['@cortex-agent/client']?.version || null;
181
+ }
182
+ catch (err) {
183
+ // `npm ls` exits non-zero when the package is absent, but still prints JSON.
184
+ out = String(err?.stdout ?? '').trim();
185
+ }
186
+ try {
187
+ return JSON.parse(out)?.dependencies?.[CLIENT_PKG]?.version || null;
154
188
  }
155
189
  catch {
156
190
  return null;
@@ -158,7 +192,7 @@ function getLocalInstalledVersion() {
158
192
  }
159
193
  function npmUpdateLocal() {
160
194
  return new Promise((resolve, reject) => {
161
- execFile('npm', ['update', '-g', '@cortex-agent/client'], { timeout: 120000 }, (err, stdout, stderr) => {
195
+ execFile('npm', clientNpmArgs(['update', '-g', CLIENT_PKG]), { timeout: 120000 }, (err, stdout, stderr) => {
162
196
  if (err)
163
197
  reject(new Error(`npm update error: ${err.message}\n${stderr}`));
164
198
  else
@@ -166,9 +200,17 @@ function npmUpdateLocal() {
166
200
  });
167
201
  });
168
202
  }
169
- async function getRemoteInstalledVersion(host) {
203
+ async function getRemoteInstalledVersion(reg) {
204
+ const host = reg.ssh;
170
205
  try {
171
- const cmd = 'npm ls -g @cortex-agent/client --json 2>/dev/null || true';
206
+ // Same prefix caveat as the local probe: read the root the client is installed in.
207
+ const cmd = reg.win
208
+ ? `npm ls -g ${CLIENT_PKG} --json 2>/dev/null || true`
209
+ : [
210
+ 'b="$(command -v cortex-client 2>/dev/null)"; p=""',
211
+ '[ -n "$b" ] && p="$(dirname "$(dirname "$b")")"',
212
+ `if [ -n "$p" ] && [ -d "$p/lib/node_modules" ]; then npm ls -g --prefix "$p" ${CLIENT_PKG} --json 2>/dev/null || true; else npm ls -g ${CLIENT_PKG} --json 2>/dev/null || true; fi`,
213
+ ].join('; ');
172
214
  const result = await sshExec(host, cmd, 15000);
173
215
  try {
174
216
  const parsed = JSON.parse(result);
@@ -294,6 +336,12 @@ async function updateClientReleaseLocal(device, latestVersion, deps) {
294
336
  catch (err) {
295
337
  res.error = err.message;
296
338
  log.warn(` ${device}: local release update failed — ${res.error}`);
339
+ // The client was already killed. A failed update must not leave the device
340
+ // offline — bring it back up on the old binary.
341
+ try {
342
+ res.restarted = await deps.restart();
343
+ }
344
+ catch { }
297
345
  }
298
346
  return res;
299
347
  }
@@ -311,7 +359,7 @@ async function updateClientRelease(device, reg, latestVersion) {
311
359
  }
312
360
  try {
313
361
  // 1. Check remote installed version
314
- const remoteVer = await getRemoteInstalledVersion(reg.ssh);
362
+ const remoteVer = await getRemoteInstalledVersion(reg);
315
363
  res.oldVersion = remoteVer || '?';
316
364
  if (remoteVer === latestVersion) {
317
365
  log.info(` ${device}: already at latest (${latestVersion})`);
@@ -319,8 +367,8 @@ async function updateClientRelease(device, reg, latestVersion) {
319
367
  }
320
368
  // 2. Kill existing client
321
369
  await killClientOnDevice(device, reg);
322
- // 3. npm update
323
- const updateOutput = await sshExec(reg.ssh, 'npm update -g @cortex-agent/client 2>&1', 60000);
370
+ // 3. npm update (prefix resolved in the remote shell — see buildRemoteNpmUpdateCommand)
371
+ const updateOutput = await sshExec(reg.ssh, buildRemoteNpmUpdateCommand(reg), 60000);
324
372
  res.updated = true;
325
373
  log.info(` ${device}: npm update output: ${updateOutput.slice(0, 200)}`);
326
374
  // 4. Restart client
@@ -443,4 +491,4 @@ function formatUpdateSlackMessage(result) {
443
491
  }
444
492
  return lines.join('\n');
445
493
  }
446
- export { checkAndUpdateClients, formatUpdateSlackMessage, updateClientReleaseLocal };
494
+ export { checkAndUpdateClients, formatUpdateSlackMessage, updateClientReleaseLocal, buildRemoteNpmUpdateCommand, };
@@ -1,5 +1,5 @@
1
- // input: cortex-client WebSockets, machine registry, HookBus
2
- // output: client.connected/disconnected{device[,reason]}; commands
1
+ // input: cortex-client WebSockets, tasks, executions, machine registry
2
+ // output: client lifecycle, commands, fenced task callbacks
3
3
  // pos: Registers, routes and restarts remote clients
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
5
  import { WebSocketServer, WebSocket } from 'ws';
@@ -485,7 +485,7 @@ function normalizeGpuPayload(raw) {
485
485
  return { indices, memoryMb };
486
486
  }
487
487
  async function handleTaskCallback(ws, msg) {
488
- const { taskProject, taskId, termination, exitCode, durationHuman, remoteResultPath, remoteLogPath, device, callbackId, logTail, gpu } = msg;
488
+ const { taskProject, taskId, dispatchGeneration, termination, exitCode, durationHuman, remoteResultPath, remoteLogPath, device, callbackId, logTail, gpu } = msg;
489
489
  // Capture the per-execution GPU onto the dispatch execution record (DR-0018 §6.3 B2-followup).
490
490
  // Keyed by taskId, independent of task status, and done BEFORE the idempotency short-circuits so
491
491
  // it lands even on an "already done" callback. No-op when no execution is registered for the task
@@ -529,15 +529,21 @@ async function handleTaskCallback(ws, msg) {
529
529
  // is woken by exactly these events, possibly days after dispatch.
530
530
  let result;
531
531
  if (isSuccess) {
532
- result = await taskMutator.complete(taskId, note, { skipVerify: true, skipVerifyReason: 'remote-run' });
532
+ result = await taskMutator.complete(taskId, note, {
533
+ skipVerify: true,
534
+ skipVerifyReason: 'remote-run',
535
+ ownership: { generation: dispatchGeneration ?? null },
536
+ });
533
537
  }
534
538
  else {
535
- result = await taskMutator.block(taskId, note);
539
+ result = await taskMutator.block(taskId, note, {
540
+ ownership: { generation: dispatchGeneration ?? null },
541
+ });
536
542
  }
537
543
  const ackMessage = result.verify_warning
538
544
  ? `${result.message} (${result.verify_warning})`
539
545
  : result.message;
540
- sendAck(ws, callbackId, result.success, ackMessage);
546
+ sendAck(ws, callbackId, result.stale ? true : result.success, ackMessage);
541
547
  }
542
548
  export { startClientManager, stopClientManager, getOnlineDevices, isDeviceOnline, sendCommand, startRemoteClient, startAllRemoteClients, buildRemoteSpawnCommand, buildRemoteInstallCommand, clientPids, sshExec,
543
549
  // Test-only hooks (prefixed with _ by convention).
@@ -0,0 +1,14 @@
1
+ import type { AuthNoticeAction } from '../../../core/types/agent-types.js';
2
+ import { type AuthStatusSnapshot } from '../../auth/auth-status.js';
3
+ import { type WasAuthRecentlyNotified } from '../../auth/auth-watch.js';
4
+ import type { ButtonElement, PlatformAdapter } from '../../../platform/index.js';
5
+ type BuildPlatformAction = (action: AuthNoticeAction, channel: string, noticeText: string) => ButtonElement;
6
+ export interface AuthExpiryScanDependencies {
7
+ now?: () => number;
8
+ readStatus?: () => Promise<AuthStatusSnapshot>;
9
+ wasRecentlyNotified?: WasAuthRecentlyNotified;
10
+ buildPlatformAction: BuildPlatformAction;
11
+ }
12
+ export declare function initAuthExpiryScan(buildPlatformAction: BuildPlatformAction): void;
13
+ export declare function runAuthExpiryScan(adapter: PlatformAdapter, dependencies: AuthExpiryScanDependencies): Promise<void>;
14
+ export {};
@@ -0,0 +1,86 @@
1
+ // input: auth status, auth-watch debounce, system notice delivery
2
+ // output: self-registering daily in-use authentication warning job
3
+ // pos: Scheduled authentication expiry and logout scanner
4
+ // >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
5
+ import { t } from '../../../core/i18n.js';
6
+ import { getAuthStatus, preferredAuthType, } from '../../auth/auth-status.js';
7
+ import { wasAuthRecentlyNotified, } from '../../auth/auth-watch.js';
8
+ import { emitSystemNotice } from '../../system/system-notice.js';
9
+ import { ctx, register } from '../job-registry.js';
10
+ const WARNING_STATES = new Set(['expiring', 'expired', 'logged-out']);
11
+ const STATE_KEYS = {
12
+ expiring: 'notify.authExpiry.state.expiring',
13
+ expired: 'notify.authExpiry.state.expired',
14
+ 'logged-out': 'notify.authExpiry.state.loggedOut',
15
+ };
16
+ let productionActionBuilder = null;
17
+ export function initAuthExpiryScan(buildPlatformAction) {
18
+ productionActionBuilder = buildPlatformAction;
19
+ }
20
+ function isWarningAccount(account) {
21
+ return account.inUse && WARNING_STATES.has(account.state);
22
+ }
23
+ function expirySuffix(account) {
24
+ const parts = [];
25
+ if (account.expiresAt) {
26
+ parts.push(t('notify.authExpiry.expiresAt', { expiresAt: account.expiresAt }));
27
+ }
28
+ if (account.refreshExpiresAt) {
29
+ parts.push(t('notify.authExpiry.refreshExpiresAt', {
30
+ expiresAt: account.refreshExpiresAt,
31
+ }));
32
+ }
33
+ return parts.length === 0 ? '' : ` ${parts.join(' ')}`;
34
+ }
35
+ function noticeText(account) {
36
+ return t('notify.authExpiry.body', {
37
+ backend: account.backend,
38
+ provider: account.provider,
39
+ state: t(STATE_KEYS[account.state]),
40
+ expiry: expirySuffix(account),
41
+ guidance: t('notify.authExpiry.guide.action'),
42
+ });
43
+ }
44
+ function noticeBlocks(text, button) {
45
+ const blocks = [{ type: 'section', text, format: 'markdown' }];
46
+ if (button)
47
+ blocks.push({ type: 'actions', elements: [button] });
48
+ return blocks;
49
+ }
50
+ async function warnAccount(adapter, snapshot, account, dependencies) {
51
+ const text = noticeText(account);
52
+ const authType = preferredAuthType(snapshot, account.backend, account.provider);
53
+ const action = authType ? dependencies.buildPlatformAction({
54
+ kind: 'auth-login',
55
+ noticeId: `auth-expiry:${account.backend}:${account.provider}:${(dependencies.now ?? Date.now)()}`,
56
+ backend: account.backend,
57
+ provider: account.provider,
58
+ authType,
59
+ }, '', text) : null;
60
+ await emitSystemNotice(adapter, {
61
+ title: t('notify.authExpiry.title'),
62
+ text,
63
+ level: account.state === 'expiring' ? 'warning' : 'error',
64
+ richBlocks: noticeBlocks(text, action),
65
+ });
66
+ }
67
+ export async function runAuthExpiryScan(adapter, dependencies) {
68
+ const snapshot = await (dependencies.readStatus ?? getAuthStatus)();
69
+ const recentlyNotified = dependencies.wasRecentlyNotified ?? wasAuthRecentlyNotified;
70
+ for (const account of snapshot.accounts) {
71
+ if (!isWarningAccount(account))
72
+ continue;
73
+ if (recentlyNotified(account.backend, account.provider))
74
+ continue;
75
+ await warnAccount(adapter, snapshot, account, dependencies);
76
+ }
77
+ }
78
+ register('auth-expiry-scan', async () => {
79
+ const adapter = ctx.adapter;
80
+ if (!adapter || !productionActionBuilder) {
81
+ throw new Error('auth-expiry-scan dependencies are not initialized');
82
+ }
83
+ await runAuthExpiryScan(adapter, {
84
+ buildPlatformAction: productionActionBuilder,
85
+ });
86
+ });