@cortex-agent/server 2026.7.30 → 2026.8.3

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 (348) 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/domain/agent-run/access-probe-cli.d.ts +7 -0
  107. package/dist/domain/agent-run/access-probe-cli.js +139 -0
  108. package/dist/domain/agent-run/access-probe-policy.d.ts +61 -0
  109. package/dist/domain/agent-run/access-probe-policy.js +614 -0
  110. package/dist/domain/agent-run/access-probe.d.ts +21 -0
  111. package/dist/domain/agent-run/access-probe.js +194 -0
  112. package/dist/domain/agent-run/agent-run-cli.d.ts +19 -0
  113. package/dist/domain/agent-run/agent-run-cli.js +171 -0
  114. package/dist/domain/agent-run/atif.d.ts +54 -0
  115. package/dist/domain/agent-run/atif.js +211 -0
  116. package/dist/domain/agent-run/benchmark-local-thread-orchestrator.d.ts +32 -0
  117. package/dist/domain/agent-run/benchmark-local-thread-orchestrator.js +616 -0
  118. package/dist/domain/agent-run/benchmark-thread-identity.d.ts +34 -0
  119. package/dist/domain/agent-run/benchmark-thread-identity.js +106 -0
  120. package/dist/domain/agent-run/identity.d.ts +62 -0
  121. package/dist/domain/agent-run/identity.js +118 -0
  122. package/dist/domain/agent-run/journal.d.ts +51 -0
  123. package/dist/domain/agent-run/journal.js +259 -0
  124. package/dist/domain/agent-run/manifest-contract.d.ts +44 -0
  125. package/dist/domain/agent-run/manifest-contract.js +134 -0
  126. package/dist/domain/agent-run/manifest.d.ts +51 -0
  127. package/dist/domain/agent-run/manifest.js +801 -0
  128. package/dist/domain/agent-run/pinned-node-process.d.ts +35 -0
  129. package/dist/domain/agent-run/pinned-node-process.js +206 -0
  130. package/dist/domain/agent-run/role-surface.d.ts +4 -0
  131. package/dist/domain/agent-run/role-surface.js +99 -0
  132. package/dist/domain/agent-run/run-config.d.ts +22 -0
  133. package/dist/domain/agent-run/run-config.js +135 -0
  134. package/dist/domain/agent-run/runner.d.ts +7 -0
  135. package/dist/domain/agent-run/runner.js +518 -0
  136. package/dist/domain/agent-run/supervisor.d.ts +78 -0
  137. package/dist/domain/agent-run/supervisor.js +425 -0
  138. package/dist/domain/agent-run/trajectory-merge-cli.d.ts +11 -0
  139. package/dist/domain/agent-run/trajectory-merge-cli.js +111 -0
  140. package/dist/domain/agent-run/trajectory-merge.d.ts +39 -0
  141. package/dist/domain/agent-run/trajectory-merge.js +505 -0
  142. package/dist/domain/agents/config.d.ts +10 -0
  143. package/dist/domain/agents/config.js +149 -44
  144. package/dist/domain/agents/facade.d.ts +42 -7
  145. package/dist/domain/agents/facade.js +174 -170
  146. package/dist/domain/agents/provider-run-lifecycle.d.ts +18 -0
  147. package/dist/domain/agents/provider-run-lifecycle.js +60 -0
  148. package/dist/domain/auth/auth-events.d.ts +18 -0
  149. package/dist/domain/auth/auth-events.js +38 -0
  150. package/dist/domain/auth/auth-format.d.ts +2 -0
  151. package/dist/domain/auth/auth-format.js +58 -0
  152. package/dist/domain/auth/auth-status.d.ts +61 -0
  153. package/dist/domain/auth/auth-status.js +304 -0
  154. package/dist/domain/auth/auth-watch.d.ts +16 -0
  155. package/dist/domain/auth/auth-watch.js +125 -0
  156. package/dist/domain/auth/cc-login.d.ts +7 -0
  157. package/dist/domain/auth/cc-login.js +16 -0
  158. package/dist/domain/auth/cc-subscription.d.ts +38 -0
  159. package/dist/domain/auth/cc-subscription.js +204 -0
  160. package/dist/domain/auth/index.d.ts +12 -0
  161. package/dist/domain/auth/index.js +16 -0
  162. package/dist/domain/auth/login-flow.d.ts +120 -0
  163. package/dist/domain/auth/login-flow.js +253 -0
  164. package/dist/domain/auth/login-service.d.ts +32 -0
  165. package/dist/domain/auth/login-service.js +97 -0
  166. package/dist/domain/auth/logout.d.ts +32 -0
  167. package/dist/domain/auth/logout.js +123 -0
  168. package/dist/domain/auth/pi-login.d.ts +36 -0
  169. package/dist/domain/auth/pi-login.js +72 -0
  170. package/dist/domain/auth/pi-oauth.d.ts +36 -0
  171. package/dist/domain/auth/pi-oauth.js +84 -0
  172. package/dist/domain/auth/pi-runtime.d.ts +72 -0
  173. package/dist/domain/auth/pi-runtime.js +86 -0
  174. package/dist/domain/mcp/benchmark-thread-server.d.ts +1 -0
  175. package/dist/domain/mcp/benchmark-thread-server.js +26 -0
  176. package/dist/domain/mcp/tools/benchmark-thread-run.d.ts +23 -0
  177. package/dist/domain/mcp/tools/benchmark-thread-run.js +146 -0
  178. package/dist/domain/memory/user-context.js +6 -8
  179. package/dist/domain/monitor/disk-monitor.js +47 -16
  180. package/dist/domain/projects/project-store.js +23 -6
  181. package/dist/domain/remote/client-manager.js +12 -6
  182. package/dist/domain/scheduling/jobs/auth-expiry-scan.d.ts +14 -0
  183. package/dist/domain/scheduling/jobs/auth-expiry-scan.js +86 -0
  184. package/dist/domain/scheduling/jobs/task-dispatch.js +36 -40
  185. package/dist/domain/scheduling/runner.d.ts +2 -0
  186. package/dist/domain/scheduling/runner.js +7 -4
  187. package/dist/domain/sessions/session-backup.d.ts +14 -20
  188. package/dist/domain/sessions/session-backup.js +57 -68
  189. package/dist/domain/system/doctor.d.ts +4 -0
  190. package/dist/domain/system/doctor.js +113 -28
  191. package/dist/domain/system/server-update-check.js +7 -5
  192. package/dist/domain/system/system-notice.d.ts +3 -1
  193. package/dist/domain/system/system-notice.js +6 -11
  194. package/dist/domain/tasks/archiver.d.ts +1 -0
  195. package/dist/domain/tasks/archiver.js +13 -7
  196. package/dist/domain/tasks/claim-recovery.d.ts +3 -3
  197. package/dist/domain/tasks/claim-recovery.js +12 -8
  198. package/dist/domain/tasks/dispatch-utils.d.ts +15 -14
  199. package/dist/domain/tasks/dispatch-utils.js +22 -18
  200. package/dist/domain/tasks/dispatcher.d.ts +1 -0
  201. package/dist/domain/tasks/dispatcher.js +9 -5
  202. package/dist/domain/tasks/mutator.d.ts +21 -11
  203. package/dist/domain/tasks/mutator.js +30 -24
  204. package/dist/domain/tasks/pending-tracker.d.ts +5 -2
  205. package/dist/domain/tasks/pending-tracker.js +11 -5
  206. package/dist/domain/tasks/system/cortex-run.d.ts +2 -1
  207. package/dist/domain/tasks/system/cortex-run.js +24 -4
  208. package/dist/domain/tasks/system/task-cli.d.ts +1 -0
  209. package/dist/domain/tasks/system/task-cli.js +72 -22
  210. package/dist/domain/tasks/system/task-completion.d.ts +19 -2
  211. package/dist/domain/tasks/system/task-completion.js +31 -17
  212. package/dist/domain/tasks/system/task-file-input.d.ts +10 -0
  213. package/dist/domain/tasks/system/task-file-input.js +57 -0
  214. package/dist/domain/tasks/system/task-id-utils.d.ts +9 -9
  215. package/dist/domain/tasks/system/task-id-utils.js +13 -4
  216. package/dist/domain/tasks/system/task-lifecycle-edit.d.ts +6 -2
  217. package/dist/domain/tasks/system/task-lifecycle-edit.js +200 -6
  218. package/dist/domain/tasks/system/task-lock.js +19 -5
  219. package/dist/domain/tasks/system/task-mutations.d.ts +22 -12
  220. package/dist/domain/tasks/system/task-mutations.js +28 -4
  221. package/dist/domain/tasks/system/task-process.js +10 -8
  222. package/dist/domain/tasks/system/task-state.d.ts +65 -11
  223. package/dist/domain/tasks/system/task-state.js +86 -13
  224. package/dist/domain/threads/local-runtime-deps.d.ts +32 -0
  225. package/dist/domain/threads/local-runtime-deps.js +91 -0
  226. package/dist/domain/threads/local-runtime-scope.d.ts +6 -0
  227. package/dist/domain/threads/local-runtime-scope.js +12 -0
  228. package/dist/domain/threads/pending-user-inputs.d.ts +3 -0
  229. package/dist/domain/threads/pending-user-inputs.js +37 -0
  230. package/dist/domain/threads/prompt-builder.d.ts +12 -1
  231. package/dist/domain/threads/prompt-builder.js +73 -26
  232. package/dist/domain/threads/runner.d.ts +15 -3
  233. package/dist/domain/threads/runner.js +261 -105
  234. package/dist/domain/threads/state-machine.d.ts +1 -1
  235. package/dist/domain/threads/state-machine.js +17 -8
  236. package/dist/domain/ui-service/app-router.d.ts +86 -6
  237. package/dist/domain/ui-service/app-router.js +171 -133
  238. package/dist/domain/ui-service/input-schemas.d.ts +132 -10
  239. package/dist/domain/ui-service/input-schemas.js +59 -5
  240. package/dist/domain/ui-service/mutate/approvals.d.ts +2 -1
  241. package/dist/domain/ui-service/mutate/approvals.js +2 -1
  242. package/dist/domain/ui-service/mutate/auth.d.ts +6 -0
  243. package/dist/domain/ui-service/mutate/auth.js +83 -0
  244. package/dist/domain/ui-service/mutate/config.js +11 -10
  245. package/dist/domain/ui-service/query/approvals.js +3 -0
  246. package/dist/domain/ui-service/query/auth.d.ts +6 -0
  247. package/dist/domain/ui-service/query/auth.js +12 -0
  248. package/dist/domain/ui-service/query/config.d.ts +5 -5
  249. package/dist/domain/ui-service/query/config.js +27 -17
  250. package/dist/domain/ui-service/query/tasks.d.ts +1 -1
  251. package/dist/domain/ui-service/query/tasks.js +69 -30
  252. package/dist/domain/ui-service/query/threads.js +3 -3
  253. package/dist/domain/ui-service/types.d.ts +67 -8
  254. package/dist/domain/ui-service/types.js +2 -2
  255. package/dist/domain/ui-service/ui-service.js +16 -2
  256. package/dist/entry/admin-channel-hot-reload.d.ts +4 -0
  257. package/dist/entry/admin-channel-hot-reload.js +22 -0
  258. package/dist/entry/app.js +38 -38
  259. package/dist/entry/auth-cli.d.ts +10 -0
  260. package/dist/entry/auth-cli.js +52 -0
  261. package/dist/entry/cli-help.d.ts +5 -0
  262. package/dist/entry/cli-help.js +130 -0
  263. package/dist/entry/cli.d.ts +5 -5
  264. package/dist/entry/cli.js +174 -248
  265. package/dist/entry/daemon.d.ts +11 -0
  266. package/dist/entry/daemon.js +204 -103
  267. package/dist/entry/draft-attachments.d.ts +8 -0
  268. package/dist/entry/draft-attachments.js +83 -0
  269. package/dist/entry/feishu-login.d.ts +2 -6
  270. package/dist/entry/feishu-login.js +16 -21
  271. package/dist/entry/init.js +6 -4
  272. package/dist/entry/start-ui-http.d.ts +2 -8
  273. package/dist/entry/start-ui-http.js +7 -34
  274. package/dist/events/event-logger.js +11 -13
  275. package/dist/events/event-types.d.ts +19 -1
  276. package/dist/events/event-types.js +3 -3
  277. package/dist/events/index.d.ts +1 -1
  278. package/dist/events/index.js +3 -3
  279. package/dist/hooks/new-session-hook.mjs +2 -2
  280. package/dist/hooks/status-md-guard.mjs +193 -0
  281. package/dist/orchestration/agent-file-send.js +44 -14
  282. package/dist/orchestration/agent-runner.d.ts +7 -3
  283. package/dist/orchestration/agent-runner.js +65 -41
  284. package/dist/orchestration/conversation-runner.d.ts +5 -1
  285. package/dist/orchestration/conversation-runner.js +16 -7
  286. package/dist/orchestration/lifecycle.d.ts +23 -1
  287. package/dist/orchestration/lifecycle.js +103 -40
  288. package/dist/orchestration/mid-turn-inject.d.ts +2 -0
  289. package/dist/orchestration/mid-turn-inject.js +29 -13
  290. package/dist/orchestration/resume-dispatcher.d.ts +3 -5
  291. package/dist/orchestration/resume-dispatcher.js +9 -17
  292. package/dist/orchestration/routing/commands/index.d.ts +4 -1
  293. package/dist/orchestration/routing/commands/index.js +83 -61
  294. package/dist/orchestration/routing/commands/login-notice.d.ts +21 -0
  295. package/dist/orchestration/routing/commands/login-notice.js +97 -0
  296. package/dist/orchestration/routing/commands/login.d.ts +12 -0
  297. package/dist/orchestration/routing/commands/login.js +555 -0
  298. package/dist/orchestration/routing/commands/status.js +45 -59
  299. package/dist/orchestration/routing/edit-handler.d.ts +5 -0
  300. package/dist/orchestration/routing/edit-handler.js +127 -73
  301. package/dist/orchestration/routing/webhook.js +5 -4
  302. package/dist/orchestration/session-rewind.d.ts +5 -1
  303. package/dist/orchestration/session-rewind.js +106 -62
  304. package/dist/orchestration/session-send.d.ts +2 -0
  305. package/dist/orchestration/session-send.js +5 -6
  306. package/dist/orchestration/status-helpers.d.ts +1 -2
  307. package/dist/orchestration/status-helpers.js +7 -10
  308. package/dist/orchestration/thread-callback.d.ts +19 -11
  309. package/dist/orchestration/thread-callback.js +132 -61
  310. package/dist/orchestration/thread-executor.js +37 -27
  311. package/dist/orchestration/turn-mutation-lock.d.ts +3 -0
  312. package/dist/orchestration/turn-mutation-lock.js +36 -0
  313. package/dist/orchestration/turn-notify.d.ts +2 -5
  314. package/dist/orchestration/turn-notify.js +9 -21
  315. package/dist/platform/adapter.d.ts +1 -0
  316. package/dist/platform/adapter.js +2 -2
  317. package/dist/platform/adapters/composite-adapter.d.ts +2 -0
  318. package/dist/platform/adapters/composite-adapter.js +13 -3
  319. package/dist/platform/adapters/feishu.d.ts +2 -4
  320. package/dist/platform/adapters/feishu.js +38 -59
  321. package/dist/platform/adapters/index.d.ts +1 -1
  322. package/dist/platform/adapters/index.js +13 -12
  323. package/dist/platform/adapters/slack.d.ts +1 -1
  324. package/dist/platform/adapters/slack.js +12 -35
  325. package/dist/platform/index.d.ts +2 -1
  326. package/dist/platform/index.js +3 -3
  327. package/dist/platform/testing.d.ts +1 -0
  328. package/dist/platform/testing.js +13 -4
  329. package/dist/platform/tool-trace.js +6 -11
  330. package/dist/platform/ui-http/ui-http-server.d.ts +1 -1
  331. package/dist/platform/ui-http/ui-http-server.js +6 -18
  332. package/dist/store/execution-repo.d.ts +17 -1
  333. package/dist/store/execution-repo.js +55 -4
  334. package/dist/store/prompt-migration-replacements.d.ts +4 -0
  335. package/dist/store/prompt-migration-replacements.js +149 -0
  336. package/dist/store/thread-repo.d.ts +15 -4
  337. package/dist/store/thread-repo.js +61 -24
  338. package/dist/store/version-migrations.js +36 -1
  339. package/native/cortex-supervisor/dist/build-manifest.json +22 -0
  340. package/native/cortex-supervisor/dist/cortex-supervisor +0 -0
  341. package/package.json +5 -2
  342. package/web/dist/assets/index-DrNx9R6c.js +139 -0
  343. package/web/dist/assets/index-zpf3OSKC.css +1 -0
  344. package/web/dist/index.html +2 -2
  345. package/dist/domain/scheduling/jobs/failed-dispatch-reconciliation.d.ts +0 -1
  346. package/dist/domain/scheduling/jobs/failed-dispatch-reconciliation.js +0 -78
  347. package/web/dist/assets/index-B19jLgji.js +0 -138
  348. package/web/dist/assets/index-BuFyPyRW.css +0 -1
@@ -0,0 +1,235 @@
1
+ // input: CONFIG_DIR, settings spec, process env, filesystem
2
+ // output: validated settings, disk updates, and test reset
3
+ // pos: L0 file-backed runtime settings boundary
4
+ // >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
5
+ import { readFileSync, watch } from 'node:fs';
6
+ import path from 'node:path';
7
+ import { AsyncMutex } from './async-mutex.js';
8
+ import { atomicWrite } from './atomic-write.js';
9
+ import { createLogger } from './log.js';
10
+ import { CONFIG_DIR } from './paths.js';
11
+ import { SETTINGS_SPEC, } from './settings-spec.js';
12
+ export { SETTINGS_SPEC, } from './settings-spec.js';
13
+ const log = createLogger('settings');
14
+ const SETTINGS_FILE = path.join(CONFIG_DIR, 'settings.json');
15
+ const SETTING_KEYS = Object.keys(SETTINGS_SPEC);
16
+ const TRUTHY_ENV_KEYS = new Set(['adminChannel', 'feishuAdminChannel']);
17
+ const callbacks = new Set();
18
+ const loggedEnvFallbacks = new Set();
19
+ const writeMutex = new AsyncMutex();
20
+ let initialized = false;
21
+ let cachedOverrides = {};
22
+ let cachedSettings = null;
23
+ let cachedSettingsSnapshot = null;
24
+ let settingsWatcher = null;
25
+ let reloadTimer = null;
26
+ let selfWriting = false;
27
+ const typeValidators = {
28
+ boolean: (value) => typeof value === 'boolean',
29
+ number: (value) => typeof value === 'number' && Number.isFinite(value),
30
+ 'number|null': (value) => value === null || (typeof value === 'number' && Number.isFinite(value)),
31
+ 'string[]': (value) => Array.isArray(value) && value.every((item) => typeof item === 'string'),
32
+ 'string|null': (value) => value === null || typeof value === 'string',
33
+ };
34
+ export function validateSettingsOverrides(value) {
35
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
36
+ throw new TypeError('settings.json must contain a JSON object');
37
+ }
38
+ for (const key of SETTING_KEYS) {
39
+ if (!Object.hasOwn(value, key))
40
+ continue;
41
+ const entry = SETTINGS_SPEC[key];
42
+ if (!typeValidators[entry.type](value[key])) {
43
+ throw new TypeError(`settings.json key "${key}" must have type ${entry.type}`);
44
+ }
45
+ }
46
+ }
47
+ function readOverrides() {
48
+ try {
49
+ const parsed = JSON.parse(readFileSync(SETTINGS_FILE, 'utf8'));
50
+ validateSettingsOverrides(parsed);
51
+ return parsed;
52
+ }
53
+ catch (error) {
54
+ if (error?.code === 'ENOENT')
55
+ return {};
56
+ throw error;
57
+ }
58
+ }
59
+ function logEnvFallback(key, envVar) {
60
+ if (loggedEnvFallbacks.has(envVar))
61
+ return;
62
+ loggedEnvFallbacks.add(envVar);
63
+ log.warn(`Deprecated env ${envVar} supplies settings.${key}; move it to settings.json`);
64
+ }
65
+ function resolveSettingEntry(key, overrides, env, warnOnEnv) {
66
+ const entry = SETTINGS_SPEC[key];
67
+ if (Object.hasOwn(overrides, key)) {
68
+ return { key, value: overrides[key], source: 'file' };
69
+ }
70
+ const envVars = typeof entry.envVar === 'string' ? [entry.envVar] : entry.envVar;
71
+ for (const envVar of envVars) {
72
+ const raw = env[envVar];
73
+ if (raw === undefined || (TRUTHY_ENV_KEYS.has(key) && raw.length === 0))
74
+ continue;
75
+ if (warnOnEnv)
76
+ logEnvFallback(key, envVar);
77
+ return { key, value: entry.legacyParse(raw), source: 'env' };
78
+ }
79
+ return { key, value: entry.default, source: 'default' };
80
+ }
81
+ export function resolveSettingsSnapshot(overrides, env = process.env) {
82
+ validateSettingsOverrides(overrides);
83
+ return SETTING_KEYS.map((key) => resolveSettingEntry(key, overrides, env, false));
84
+ }
85
+ function resolveSettings(overrides) {
86
+ return Object.fromEntries(SETTING_KEYS.map((key) => {
87
+ const entry = resolveSettingEntry(key, overrides, process.env, true);
88
+ return [key, entry.value];
89
+ }));
90
+ }
91
+ function sameValue(left, right) {
92
+ if (Array.isArray(left) && Array.isArray(right)) {
93
+ return left.length === right.length && left.every((value, index) => value === right[index]);
94
+ }
95
+ return Object.is(left, right);
96
+ }
97
+ function changedKeys(previous, next) {
98
+ return SETTING_KEYS.filter((key) => !sameValue(previous[key], next[key]));
99
+ }
100
+ function emitChanges(previous, next) {
101
+ const changed = changedKeys(previous, next);
102
+ if (changed.length === 0)
103
+ return;
104
+ for (const callback of callbacks) {
105
+ try {
106
+ callback(changed);
107
+ }
108
+ catch (error) {
109
+ log.error('Settings change callback failed:', error);
110
+ }
111
+ }
112
+ }
113
+ function settingsFromSnapshot(snapshot) {
114
+ return Object.fromEntries(snapshot.map((entry) => [entry.key, entry.value]));
115
+ }
116
+ function snapshotWithValues(overrides, settings) {
117
+ return resolveSettingsSnapshot(overrides).map((entry) => ({
118
+ key: entry.key,
119
+ value: settings[entry.key],
120
+ source: entry.source,
121
+ }));
122
+ }
123
+ function acceptSnapshot(overrides, next, snapshot = snapshotWithValues(overrides, next)) {
124
+ const previous = cachedSettings;
125
+ cachedOverrides = overrides;
126
+ cachedSettings = next;
127
+ cachedSettingsSnapshot = snapshot;
128
+ if (previous)
129
+ emitChanges(previous, next);
130
+ }
131
+ function sameOverrides(left, right) {
132
+ return JSON.stringify(left) === JSON.stringify(right);
133
+ }
134
+ function scheduleReload() {
135
+ if (reloadTimer)
136
+ clearTimeout(reloadTimer);
137
+ reloadTimer = setTimeout(() => {
138
+ reloadTimer = null;
139
+ reloadSettings();
140
+ }, 300);
141
+ }
142
+ function reloadSettings() {
143
+ if (selfWriting)
144
+ return scheduleReload();
145
+ try {
146
+ const overrides = readOverrides();
147
+ if (sameOverrides(cachedOverrides, overrides))
148
+ return;
149
+ acceptSnapshot(overrides, resolveSettings(overrides));
150
+ log.info('Hot-reload: settings.json reloaded');
151
+ }
152
+ catch (error) {
153
+ log.error(`Hot-reload settings.json failed: ${error.message} — keeping previous settings`);
154
+ }
155
+ }
156
+ function handleWatchEvent(filename) {
157
+ if (filename !== null && filename.toString() !== 'settings.json')
158
+ return;
159
+ scheduleReload();
160
+ }
161
+ function startWatcher() {
162
+ try {
163
+ settingsWatcher = watch(CONFIG_DIR, (_eventType, filename) => handleWatchEvent(filename));
164
+ settingsWatcher.on('error', (error) => log.error('settings.json watcher failed:', error));
165
+ settingsWatcher.unref();
166
+ }
167
+ catch (error) {
168
+ log.error('Failed to watch settings.json:', error);
169
+ }
170
+ }
171
+ function initialize() {
172
+ if (initialized)
173
+ return;
174
+ initialized = true;
175
+ startWatcher();
176
+ try {
177
+ const overrides = readOverrides();
178
+ acceptSnapshot(overrides, resolveSettings(overrides));
179
+ }
180
+ catch (error) {
181
+ log.error(`Load settings.json failed: ${error.message} — using env/default settings`);
182
+ acceptSnapshot({}, resolveSettings({}));
183
+ }
184
+ }
185
+ export function resetSettingsForTests() {
186
+ if (reloadTimer)
187
+ clearTimeout(reloadTimer);
188
+ reloadTimer = null;
189
+ settingsWatcher?.close();
190
+ settingsWatcher = null;
191
+ initialized = false;
192
+ cachedOverrides = {};
193
+ cachedSettings = null;
194
+ cachedSettingsSnapshot = null;
195
+ selfWriting = false;
196
+ }
197
+ export function getSettings() {
198
+ initialize();
199
+ return cachedSettings;
200
+ }
201
+ export function getSettingsSnapshot() {
202
+ initialize();
203
+ return cachedSettingsSnapshot;
204
+ }
205
+ export function onSettingsChange(callback) {
206
+ initialize();
207
+ callbacks.add(callback);
208
+ return () => callbacks.delete(callback);
209
+ }
210
+ function readOverridesForUpdate() {
211
+ try {
212
+ return readOverrides();
213
+ }
214
+ catch (error) {
215
+ log.error(`Update settings.json read failed: ${error.message} — using previous settings`);
216
+ return cachedOverrides;
217
+ }
218
+ }
219
+ export async function updateSettings(partial) {
220
+ initialize();
221
+ const env = { ...process.env };
222
+ await writeMutex.run(async () => {
223
+ const nextOverrides = { ...readOverridesForUpdate(), ...partial };
224
+ const nextSnapshot = resolveSettingsSnapshot(nextOverrides, env);
225
+ const nextSettings = settingsFromSnapshot(nextSnapshot);
226
+ selfWriting = true;
227
+ try {
228
+ await atomicWrite(SETTINGS_FILE, `${JSON.stringify(nextOverrides, null, 2)}\n`);
229
+ acceptSnapshot(nextOverrides, nextSettings, nextSnapshot);
230
+ }
231
+ finally {
232
+ selfWriting = false;
233
+ }
234
+ });
235
+ }
@@ -17,6 +17,8 @@ export interface Task {
17
17
  blocked_by: string | null;
18
18
  claimed_by: string | null;
19
19
  claimed_at: string | null;
20
+ /** Opaque dispatch incarnation retained through valid automated completion for callback fencing. */
21
+ dispatch_generation: string | null;
20
22
  paused: boolean;
21
23
  approval_needed: boolean;
22
24
  approved_at: string | null;
@@ -31,6 +33,9 @@ export interface Task {
31
33
  origin_channel: string | null;
32
34
  origin_thread_id: string | null;
33
35
  }
36
+ export interface TaskGenerationExpectation {
37
+ generation: string | null;
38
+ }
34
39
  export interface LockState {
35
40
  owner: string;
36
41
  acquired_at: string;
@@ -52,6 +57,11 @@ declare function serializeTasksFileWithLock({ tasks, lock }: {
52
57
  lock?: LockState | null;
53
58
  }): string;
54
59
  declare function getTasksYamlPath(project: string): string;
60
+ /** Test seam: cumulative cache hit/miss counters for the scanAllTasks content cache. */
61
+ declare function _tasksFileCacheStats(): {
62
+ hits: number;
63
+ misses: number;
64
+ };
55
65
  declare function scanAllTasks(project?: string | null): Task[];
56
66
  declare function completedHashSet(tasks: Task[]): Set<string>;
57
67
  declare function isActionable(task: Task, completedHashes?: Set<string> | null): boolean;
@@ -75,4 +85,4 @@ declare function depsPayload(task: Task, tasks: Task[]): {
75
85
  dependents: string[];
76
86
  depends_on: Task[];
77
87
  };
78
- export { PRIORITY_ORDER, VALID_STATUSES, completedHashSet, depsPayload, filterTasks, getTaskStats, getTaskStatsFromTasks, getTasksYamlPath, isActionable, parseTasksFile, parseTasksFileWithLock, printStatsText, printTaskListToString, rawToTask, scanAllTasks, scanAvailableTasks, serializeTasksFile, serializeTasksFileWithLock, showPayload, taskToYamlObj, taskStatuses, taskTags, };
88
+ export { PRIORITY_ORDER, VALID_STATUSES, completedHashSet, depsPayload, filterTasks, getTaskStats, getTaskStatsFromTasks, getTasksYamlPath, isActionable, parseTasksFile, parseTasksFileWithLock, printStatsText, printTaskListToString, rawToTask, scanAllTasks, scanAvailableTasks, _tasksFileCacheStats, serializeTasksFile, serializeTasksFileWithLock, showPayload, taskToYamlObj, taskStatuses, taskTags, };
@@ -1,3 +1,7 @@
1
+ // input: fs/path/crypto, YAML task files, project paths
2
+ // output: Task parsing, serialization, filtering, and generation types
3
+ // pos: Canonical TASKS.yaml schema and query helpers
4
+ // >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
1
5
  import * as fs from 'node:fs';
2
6
  import * as path from 'node:path';
3
7
  import { parse as yamlParse, stringify as yamlStringify } from 'yaml';
@@ -11,6 +15,7 @@ const YAML_TO_TS = {
11
15
  'blocked-by': 'blocked_by',
12
16
  'claimed-by': 'claimed_by',
13
17
  'claimed-at': 'claimed_at',
18
+ 'dispatch-generation': 'dispatch_generation',
14
19
  'approval-needed': 'approval_needed',
15
20
  'approved-at': 'approved_at',
16
21
  'not-before': 'not_before',
@@ -43,6 +48,7 @@ const TASK_DEFAULTS = {
43
48
  blocked_by: null,
44
49
  claimed_by: null,
45
50
  claimed_at: null,
51
+ dispatch_generation: null,
46
52
  paused: false,
47
53
  approval_needed: false,
48
54
  approved_at: null,
@@ -77,6 +83,7 @@ function rawToTask(raw, project) {
77
83
  blocked_by: mapped.blocked_by != null ? String(mapped.blocked_by) : null,
78
84
  claimed_by: mapped.claimed_by != null ? String(mapped.claimed_by) : null,
79
85
  claimed_at: mapped.claimed_at != null ? String(mapped.claimed_at) : null,
86
+ dispatch_generation: mapped.dispatch_generation != null ? String(mapped.dispatch_generation) : null,
80
87
  paused: Boolean(mapped.paused),
81
88
  approval_needed: Boolean(mapped.approval_needed),
82
89
  approved_at: mapped.approved_at != null ? String(mapped.approved_at) : null,
@@ -134,7 +141,8 @@ function parseTasksFileWithLock(content, project) {
134
141
  const REQUIRED_KEYS = ['id', 'text', 'why', 'done_when', 'priority', 'status', 'template', 'plan'];
135
142
  const OPTIONAL_KEY_ORDER = [
136
143
  'parent', 'depends_on', 'gpu', 'gpu_count', 'blocked_by', 'claimed_by', 'claimed_at',
137
- 'paused', 'approval_needed', 'approved_at', 'not_before', 'pending_at', 'completed_at', 'completed_note',
144
+ 'dispatch_generation', 'paused', 'approval_needed', 'approved_at', 'not_before', 'pending_at',
145
+ 'completed_at', 'completed_note',
138
146
  'origin_session_id', 'origin_channel', 'origin_thread_id',
139
147
  ];
140
148
  function isDefault(key, value) {
@@ -177,6 +185,29 @@ function serializeTasksFileWithLock({ tasks, lock }) {
177
185
  function getTasksYamlPath(project) {
178
186
  return path.join(PROJECTS_DIR, project, 'TASKS.yaml');
179
187
  }
188
+ /** Content-keyed parse cache. YAML parsing dominates scan cost (seconds across projects on the
189
+ * dispatch hot path); the raw read is cheap. Keyed by exact file content, so edits from ANY
190
+ * process (CLI, git pull, other threads) invalidate naturally — no mtime-granularity races.
191
+ * Results are structuredClone'd on the way out so callers can never mutate the cached copy. */
192
+ const tasksFileCache = new Map();
193
+ let tasksCacheHits = 0;
194
+ let tasksCacheMisses = 0;
195
+ function parseTasksFileCached(tasksPath, project) {
196
+ const content = fs.readFileSync(tasksPath, 'utf8');
197
+ const hit = tasksFileCache.get(tasksPath);
198
+ if (hit && hit.content === content) {
199
+ tasksCacheHits++;
200
+ return structuredClone(hit.tasks);
201
+ }
202
+ tasksCacheMisses++;
203
+ const tasks = parseTasksFile(content, project);
204
+ tasksFileCache.set(tasksPath, { content, tasks });
205
+ return structuredClone(tasks);
206
+ }
207
+ /** Test seam: cumulative cache hit/miss counters for the scanAllTasks content cache. */
208
+ function _tasksFileCacheStats() {
209
+ return { hits: tasksCacheHits, misses: tasksCacheMisses };
210
+ }
180
211
  function scanAllTasks(project = null) {
181
212
  if (!fs.existsSync(PROJECTS_DIR))
182
213
  return [];
@@ -187,7 +218,7 @@ function scanAllTasks(project = null) {
187
218
  const tasksPath = getTasksYamlPath(projectName);
188
219
  if (!fs.existsSync(tasksPath))
189
220
  continue;
190
- tasks.push(...parseTasksFile(fs.readFileSync(tasksPath, 'utf8'), projectName));
221
+ tasks.push(...parseTasksFileCached(tasksPath, projectName));
191
222
  }
192
223
  return tasks;
193
224
  }
@@ -439,4 +470,4 @@ function depsPayload(task, tasks) {
439
470
  payload.dependents = depMap[task.id] || [];
440
471
  return payload;
441
472
  }
442
- export { PRIORITY_ORDER, VALID_STATUSES, completedHashSet, depsPayload, filterTasks, getTaskStats, getTaskStatsFromTasks, getTasksYamlPath, isActionable, parseTasksFile, parseTasksFileWithLock, printStatsText, printTaskListToString, rawToTask, scanAllTasks, scanAvailableTasks, serializeTasksFile, serializeTasksFileWithLock, showPayload, taskToYamlObj, taskStatuses, taskTags, };
473
+ export { PRIORITY_ORDER, VALID_STATUSES, completedHashSet, depsPayload, filterTasks, getTaskStats, getTaskStatsFromTasks, getTasksYamlPath, isActionable, parseTasksFile, parseTasksFileWithLock, printStatsText, printTaskListToString, rawToTask, scanAllTasks, scanAvailableTasks, _tasksFileCacheStats, serializeTasksFile, serializeTasksFileWithLock, showPayload, taskToYamlObj, taskStatuses, taskTags, };
@@ -1,4 +1,11 @@
1
1
  export type ChatNoticeLevel = 'info' | 'warning' | 'error';
2
+ export interface AuthNoticeAction {
3
+ kind: 'auth-login';
4
+ noticeId: string;
5
+ backend: 'claude' | 'pi';
6
+ provider: string;
7
+ authType: 'oauth' | 'api_key';
8
+ }
2
9
  /** Backend-neutral snapshot of the tokens currently occupying an agent's context window. */
3
10
  export interface ContextUsage {
4
11
  usedTokens: number | null;
@@ -15,9 +22,21 @@ export interface AskUserQuestionInfo {
15
22
  questions: string[];
16
23
  sessionId: string;
17
24
  }
25
+ export interface ReportedAccountingSnapshot {
26
+ readonly usageReported: boolean;
27
+ readonly inputTokens: number | null;
28
+ readonly outputTokens: number | null;
29
+ readonly promptTokens: number | null;
30
+ readonly cachedTokens: number | null;
31
+ readonly model: string | null;
32
+ }
18
33
  export interface AgentResult {
19
34
  sessionId: string | null;
20
35
  total_cost_usd: number | null;
36
+ /** Present only when a provenance-sensitive caller needs reported zero distinguished from absent cost. */
37
+ costReported?: boolean;
38
+ /** Immutable result-event accounting used by provenance-sensitive event serialization. */
39
+ reportedAccounting?: ReportedAccountingSnapshot;
21
40
  num_turns: number | null;
22
41
  rateLimited: boolean;
23
42
  rateLimitMessage: string | null;
@@ -1,5 +1,5 @@
1
1
  // input: nothing (leaf type-only module)
2
- // output: Agent results with provider identity, handles, and usage types
2
+ // output: Agent results, auth actions, and exact usage types
3
3
  // pos: Shared type definitions for agent execution and messages
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
5
  export {};
@@ -1,3 +1,5 @@
1
+ import type { NormalizedEvent } from '../../agent-adapter/normalize/event-types.js';
2
+ import type { AgentProcessSpawner, McpComposition } from '../../agent-adapter/types.js';
1
3
  export type ThreadId = string;
2
4
  export type AgentSlotId = string;
3
5
  export type ThreadStatus = 'running' | 'waiting' | 'rate_limited' | 'completed' | 'failed' | 'cancelled' | 'aborted';
@@ -24,6 +26,7 @@ export interface AgentDefinition {
24
26
  outputStyle?: string;
25
27
  tools?: string;
26
28
  pluginDirs?: string[];
29
+ mcpComposition?: McpComposition;
27
30
  /** Optional per-stage prompt map. When set, `promptTemplate` is ignored and the engine
28
31
  * selects one stage per step based on the transition target (`"agent:stage"` syntax). */
29
32
  stages?: Record<string, StageDefinition>;
@@ -55,6 +58,7 @@ export interface AgentSlotConfig {
55
58
  outputStyle?: string;
56
59
  tools?: string;
57
60
  pluginDirs?: string[];
61
+ mcpComposition?: McpComposition;
58
62
  /** Per-stage prompts (merged from AgentDefinition; templates currently don't override per stage). */
59
63
  stages?: Record<string, StageDefinition>;
60
64
  /** Default stage when a transition target omits the `:stage` suffix. */
@@ -142,6 +146,8 @@ export interface ThreadTemplate {
142
146
  entryStage?: string;
143
147
  maxTotalSteps: number;
144
148
  maxTotalCostUsd?: number;
149
+ /** Suppress registry, scoped lifecycle, and backend hooks for isolated templates. */
150
+ disableHooks?: boolean;
145
151
  hooks?: ThreadHooks;
146
152
  }
147
153
  /** A compact template that inherits a named "shell" (a parameterized transition-graph
@@ -228,6 +234,11 @@ export interface AgentSlot {
228
234
  status: 'idle' | 'running' | 'completed';
229
235
  lastOutput: string | null;
230
236
  persistSession: boolean;
237
+ /** Backend session of a step interrupted mid-flight by a provider error/rate limit, set only
238
+ * when the attempt streamed real activity. One-shot: the rerun consumes it (beginStepSession)
239
+ * to resume the interrupted session with a continuation reminder instead of restarting the
240
+ * step from the original prompt. */
241
+ interruptedBackendSessionId?: string | null;
231
242
  }
232
243
  export interface ThreadRecord {
233
244
  id: ThreadId;
@@ -266,6 +277,11 @@ export interface ThreadContract {
266
277
  deliverablePath?: string | null;
267
278
  budgetUsd?: number | null;
268
279
  }
280
+ /** User input reserved while a thread step prepares any attached platform files. */
281
+ export interface BufferedThreadUserInput {
282
+ id: string;
283
+ text: string;
284
+ }
269
285
  /** Caller-provided metadata stored on ThreadRecord, used by thread-runner for execution registry etc. */
270
286
  export interface ThreadMetadata {
271
287
  scheduleTaskId?: string | null;
@@ -284,8 +300,10 @@ export interface ThreadMetadata {
284
300
  * parent (interactive parent → resume its channel session) or address a notice to it. */
285
301
  parentChannel?: string | null;
286
302
  parentProfile?: string | null;
287
- /** Messages buffered while a step was executing, to be included in the next step's prompt. */
303
+ /** Control/callback notices buffered for the next step. */
288
304
  pendingMessages?: string[];
305
+ /** Ordered user inputs buffered while their platform files are prepared. */
306
+ pendingUserInputs?: BufferedThreadUserInput[];
289
307
  /** Root of the thread tree this thread belongs to. Unset on root threads —
290
308
  * use tree.getRootThreadId() which falls back to the thread's own id. */
291
309
  rootThreadId?: string | null;
@@ -334,11 +352,11 @@ export interface ThreadMetadata {
334
352
  /** Task association persisted for lifecycle payloads and resumed dispatch work. */
335
353
  taskId?: string | null;
336
354
  taskProject?: string | null;
355
+ /** Opaque TASKS.yaml dispatch incarnation used to fence completion and terminal callbacks. */
356
+ dispatchGeneration?: string | null;
337
357
  /** Task text (TASKS.yaml `text`) at dispatch time, for the thread step status line so a glance
338
358
  * shows what is running. Persisted because status updates outlive the in-memory selected task. */
339
359
  taskText?: string | null;
340
- /** Followup created when a failed dispatch left completed-task review unresolved. */
341
- reviewLeakFollowupTaskId?: string | null;
342
360
  /** Set when the thread was paused (status==='rate_limited') by an API rate limit, so the
343
361
  * resume path and startup recovery can tell a rate-limit pause apart from a real failure. */
344
362
  interruptedByRateLimit?: boolean;
@@ -380,6 +398,31 @@ export interface TransitionResult {
380
398
  reason: 'transition' | 'converged' | 'max_iterations' | 'cost_limit' | 'no_matching_transition';
381
399
  }
382
400
  import type { PlatformAdapter, MessageRef, Destination } from '../../platform/index.js';
401
+ export interface BenchmarkThreadEvent {
402
+ step: number;
403
+ agentSlotId: AgentSlotId;
404
+ event: NormalizedEvent;
405
+ }
406
+ export interface BenchmarkThreadRunOptions {
407
+ /** Absolute grader workspace used by every benchmark step's backend process. */
408
+ workspaceCwd: string;
409
+ /** Frozen trial profile; benchmark templates cannot select a different identity. */
410
+ resolvedProfileName: string;
411
+ expectedBackend: 'claude';
412
+ expectedModel: string;
413
+ disableHooks: true;
414
+ disableControlPlane: true;
415
+ failFastOnRateLimit: true;
416
+ /** Optional containment-aware process boundary forwarded to every step. */
417
+ spawner?: AgentProcessSpawner;
418
+ /** Required trajectory sink invoked synchronously for every normalized event. */
419
+ requiredEventSink?: (input: BenchmarkThreadEvent) => void;
420
+ limits?: {
421
+ maxSteps: number;
422
+ maxCostUsd?: number;
423
+ deadlineMs?: number;
424
+ };
425
+ }
383
426
  export interface RunThreadOptions {
384
427
  adapter: PlatformAdapter;
385
428
  channel: string;
@@ -421,4 +464,6 @@ export interface RunThreadOptions {
421
464
  onTransition?: ThreadHookConfig;
422
465
  onEnd?: ThreadHookConfig;
423
466
  };
467
+ /** Presence selects the isolated benchmark runtime; absence preserves daemon behavior. */
468
+ benchmark?: BenchmarkThreadRunOptions;
424
469
  }
@@ -1,5 +1,5 @@
1
- // input: thread template config and durable runtime state
2
- // output: thread state, outage retries, and lifecycle types
1
+ // input: thread config, benchmark events, process spawning
2
+ // output: thread state, buffered-input, runtime lifecycle types
3
3
  // pos: Shared type definitions for the thread system
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
5
  export {};
@@ -0,0 +1,7 @@
1
+ interface ProbeCliIo {
2
+ stdout: NodeJS.WritableStream;
3
+ stderr: NodeJS.WritableStream;
4
+ }
5
+ export declare function runAccessProbeCli(args: string[], io?: ProbeCliIo, env?: NodeJS.ProcessEnv): Promise<number>;
6
+ export declare function getAccessProbeHelp(): string;
7
+ export {};
@@ -0,0 +1,139 @@
1
+ // input: flags, env, stdout, and stderr
2
+ // output: JSON verdict, summary, help, and exit code
3
+ // pos: Standalone CLI for pinned Node syscall probes
4
+ // >>> If I am updated, update my header and folder CORTEX.md <<<
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { formatError, formatHelp } from '../../core/cli-utils.js';
9
+ import { formatAccessProbeSummary, runNodeAccessProbe } from './access-probe.js';
10
+ const SINGLE_FLAGS = new Set([
11
+ '--trial-root', '--workspace', '--entry', '--install-root', '--host-home',
12
+ '--host-cortex-home', '--strace-path', '--timeout-ms',
13
+ ]);
14
+ const REPEATED_FLAGS = new Set(['--entry-arg', '--node-import']);
15
+ const ALL_FLAGS = [...SINGLE_FLAGS, ...REPEATED_FLAGS];
16
+ const HELP_OPTIONS = [
17
+ { flag: '--trial-root <dir>', description: 'Scratch root for every pinned child path' },
18
+ { flag: '--workspace <dir>', description: 'Allowed task workspace and child cwd' },
19
+ { flag: '--entry <file>', description: 'Arbitrary Node entry to trace' },
20
+ { flag: '--install-root <dir>', description: 'Read-only Cortex install root' },
21
+ { flag: '--host-home <dir>', description: 'Host home whose dotfiles are denied' },
22
+ { flag: '--host-cortex-home <dir>', description: 'Host Cortex tree denied in full' },
23
+ { flag: '--entry-arg <value>', description: 'Entry argument; repeat as needed' },
24
+ { flag: '--node-import <module>', description: 'Node --import value; repeat as needed' },
25
+ { flag: '--strace-path <path>', description: 'strace executable', default: 'strace from PATH' },
26
+ { flag: '--timeout-ms <n>', description: 'Hard trace timeout', default: '30000' },
27
+ { flag: '--help, -h', description: 'Show this help' },
28
+ ];
29
+ const HELP_EXAMPLE = {
30
+ description: 'Create a no-op entry and probe it from the package root',
31
+ command: [
32
+ 'mkdir -p /tmp/cortex-access-probe/workspace &&',
33
+ "printf '' > /tmp/cortex-access-probe/entry.mjs &&",
34
+ 'node dist/domain/agent-run/access-probe-cli.js',
35
+ '--trial-root /tmp/cortex-access-probe/trial',
36
+ '--workspace /tmp/cortex-access-probe/workspace',
37
+ '--entry /tmp/cortex-access-probe/entry.mjs --install-root .',
38
+ '--host-home "$HOME" --host-cortex-home "${CORTEX_HOME:-$HOME/.cortex}"',
39
+ ].join(' '),
40
+ };
41
+ function fail(message, hint) {
42
+ throw new Error(formatError(message, { validValues: ALL_FLAGS, hint }));
43
+ }
44
+ function appendValue(target, flag, value) {
45
+ target.set(flag, [...(target.get(flag) ?? []), value]);
46
+ }
47
+ function parseValues(args) {
48
+ const single = new Map();
49
+ const repeated = new Map();
50
+ for (let index = 0; index < args.length; index += 2) {
51
+ const flag = args[index];
52
+ const value = args[index + 1];
53
+ if (!ALL_FLAGS.includes(flag))
54
+ fail(`Unknown option: '${flag}'`);
55
+ if (value === undefined)
56
+ fail(`Missing value for ${flag}`);
57
+ if (REPEATED_FLAGS.has(flag))
58
+ appendValue(repeated, flag, value);
59
+ else if (single.has(flag))
60
+ fail(`Duplicate option: '${flag}'`);
61
+ else
62
+ single.set(flag, value);
63
+ }
64
+ return { single, repeated };
65
+ }
66
+ function required(values, flag) {
67
+ const value = values.get(flag);
68
+ if (value)
69
+ return value;
70
+ return fail(`Missing required ${flag}`, 'Run with --help for a complete example.');
71
+ }
72
+ function existingPath(value, flag, type) {
73
+ try {
74
+ const resolved = fs.realpathSync(value);
75
+ const stat = fs.statSync(resolved);
76
+ if ((type === 'file' && stat.isFile()) || (type === 'directory' && stat.isDirectory())) {
77
+ return resolved;
78
+ }
79
+ }
80
+ catch { }
81
+ return fail(`Invalid ${flag}: '${value}'`, `Provide an existing ${type}.`);
82
+ }
83
+ function milliseconds(value) {
84
+ if (value === undefined)
85
+ return undefined;
86
+ const parsed = Number(value);
87
+ if (Number.isSafeInteger(parsed) && parsed > 0)
88
+ return parsed;
89
+ return fail(`Invalid --timeout-ms: '${value}'`, 'Use a positive integer number of milliseconds.');
90
+ }
91
+ function probeOptions(values, env) {
92
+ const single = values.single;
93
+ const imports = values.repeated.get('--node-import') ?? [];
94
+ return {
95
+ trialRoot: path.resolve(required(single, '--trial-root')),
96
+ workspaceCwd: existingPath(required(single, '--workspace'), '--workspace', 'directory'),
97
+ entry: existingPath(required(single, '--entry'), '--entry', 'file'),
98
+ args: values.repeated.get('--entry-arg') ?? [],
99
+ nodeArgs: imports.flatMap(value => ['--import', value]),
100
+ parentEnv: env,
101
+ installRoot: existingPath(required(single, '--install-root'), '--install-root', 'directory'),
102
+ hostHome: path.resolve(required(single, '--host-home')),
103
+ hostCortexHome: path.resolve(required(single, '--host-cortex-home')),
104
+ stracePath: single.get('--strace-path'),
105
+ timeoutMs: milliseconds(single.get('--timeout-ms')),
106
+ };
107
+ }
108
+ export async function runAccessProbeCli(args, io = { stdout: process.stdout, stderr: process.stderr }, env = process.env) {
109
+ if (args.includes('--help') || args.includes('-h')) {
110
+ io.stdout.write(`${getAccessProbeHelp()}\n`);
111
+ return 0;
112
+ }
113
+ try {
114
+ const verdict = await runNodeAccessProbe(probeOptions(parseValues(args), env));
115
+ io.stdout.write(`${JSON.stringify(verdict)}\n`);
116
+ io.stderr.write(`${formatAccessProbeSummary(verdict)}\n`);
117
+ return verdict.ok ? 0 : 1;
118
+ }
119
+ catch (error) {
120
+ io.stderr.write(`${error?.message ?? String(error)}\n`);
121
+ return 2;
122
+ }
123
+ }
124
+ export function getAccessProbeHelp() {
125
+ return formatHelp({
126
+ name: 'node dist/domain/agent-run/access-probe-cli.js',
127
+ description: 'Trace and classify a Node entry against the Cortex benchmark isolation policy.',
128
+ usage: 'node dist/domain/agent-run/access-probe-cli.js --trial-root <dir> --workspace <dir> --entry <file> --install-root <dir> --host-home <dir> --host-cortex-home <dir> [options]',
129
+ options: HELP_OPTIONS,
130
+ examples: [HELP_EXAMPLE],
131
+ });
132
+ }
133
+ function isMainModule() {
134
+ return process.argv[1] !== undefined
135
+ && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url);
136
+ }
137
+ if (isMainModule()) {
138
+ void runAccessProbeCli(process.argv.slice(2)).then(code => { process.exitCode = code; });
139
+ }