@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
@@ -29,6 +29,8 @@ export declare const CORE_MCP_CONFIG: string;
29
29
  export declare const TASKS_MCP_CONFIG: string;
30
30
  export declare const MANAGER_QA_MCP_CONFIG: string;
31
31
  export declare const THREAD_MCP_CONFIG: string;
32
+ export declare const EMPTY_MCP_CONFIG: string;
33
+ export declare const BENCHMARK_THREAD_MCP_CONFIG: string;
32
34
  /** DR-0012: TUI-mode-exclusive MCP set (only cortex-tui-bridge server, no core/ext leakage). */
33
35
  export declare const TUI_MCP_CONFIG: string;
34
36
  /** Slack platform-specific tools (cortex-slack server). Layered on top of the full config via the variadic
@@ -1,10 +1,9 @@
1
- // input: Cortex paths, filesystem, operating-system paths
2
- // output: Claude constants, MCP paths, and CancelledError
3
- // pos: Shared Claude adapter defaults
1
+ // input: Cortex paths, filesystem, OS paths
2
+ // output: Claude constants, MCP paths, CancelledError
3
+ // pos: Claude defaults and config paths
4
4
  // >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
5
5
  import * as path from 'path';
6
6
  import * as os from 'os';
7
- import { mkdirSync } from 'fs';
8
7
  import { DATA_DIR, CONFIG_DIR, HOOKS_DIR } from '../../core/utils.js';
9
8
  export const MAX_TIMEOUT = 30_000_000;
10
9
  export const IDLE_SESSION_TIMEOUT = 65 * 60 * 1000;
@@ -31,12 +30,13 @@ export const PANE_READY_POLL_MS = 250;
31
30
  * Ink app has finished its initial layout. */
32
31
  export const PANE_READY_MARKER = /bypass permissions on|\? for shortcuts/;
33
32
  export const LOGS_DIR = path.join(DATA_DIR, 'logs', 'sessions');
34
- mkdirSync(LOGS_DIR, { recursive: true });
35
33
  export const MCP_CONFIG = path.join(CONFIG_DIR, 'mcp-config.json');
36
34
  export const CORE_MCP_CONFIG = path.join(CONFIG_DIR, 'mcp-config-core.json');
37
35
  export const TASKS_MCP_CONFIG = path.join(CONFIG_DIR, 'mcp-config-tasks.json');
38
36
  export const MANAGER_QA_MCP_CONFIG = path.join(CONFIG_DIR, 'mcp-config-manager-qa.json');
39
37
  export const THREAD_MCP_CONFIG = path.join(CONFIG_DIR, 'mcp-config-thread.json');
38
+ export const EMPTY_MCP_CONFIG = path.join(CONFIG_DIR, 'mcp-config-empty.json');
39
+ export const BENCHMARK_THREAD_MCP_CONFIG = path.join(CONFIG_DIR, 'mcp-config-benchmark-thread.json');
40
40
  /** DR-0012: TUI-mode-exclusive MCP set (only cortex-tui-bridge server, no core/ext leakage). */
41
41
  export const TUI_MCP_CONFIG = path.join(CONFIG_DIR, 'mcp-config-tui.json');
42
42
  /** Slack platform-specific tools (cortex-slack server). Layered on top of the full config via the variadic
@@ -3,18 +3,13 @@
3
3
  export interface StreamDeltaState {
4
4
  /** `message.id` of the message being streamed — the first half of every blockId. */
5
5
  messageId: string | null;
6
+ /** Backend-reported model for the current message. */
7
+ model: string | null;
6
8
  /** blockId of the text block currently open, awaiting its complete `assistant` event. */
7
9
  textBlockId: string | null;
8
10
  }
9
11
  export declare function createStreamDeltaState(): StreamDeltaState;
10
- /**
11
- * Translate one raw stdout line (already JSON-parsed) into an incremental text chunk, advancing
12
- * `state`. Returns null for every line that is not a non-empty text delta — including all complete
13
- * events, which keep travelling their existing path untouched.
14
- *
15
- * `blockId` is `${message.id}:${content_block_index}` per the streaming contract: stable for one
16
- * assistant text block and shared with the finalizing message via {@link takeTextBlockId}.
17
- */
12
+ /** Translate a partial stdout event into one text delta while advancing the message cursor. */
18
13
  export declare function parseStreamEvent(data: any, state: StreamDeltaState): {
19
14
  text: string;
20
15
  blockId: string;
@@ -1,52 +1,49 @@
1
- // input: Claude stream-json events (complete + `stream_event` partials), user message, sessionId
2
- // output: formatters, extractors, buildPrompt, plan-file helpers, stream-delta cursor
3
- // pos: Claude event parsing, plan file tracking, and token-level delta extraction
4
- // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
1
+ // input: Claude complete and partial stream events
2
+ // output: prompt helpers and stream cursors
3
+ // pos: Claude stream event parser
4
+ // >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
5
5
  import { readFileSync } from 'fs';
6
6
  import { CancelledError, DEFAULT_PLAN_DIRS, PROJECT_SETTINGS } from './defaults.js';
7
7
  import { summarizeToolInput } from './tool-summarizers.js';
8
8
  import { buildPrompt as sharedBuildPrompt } from '../normalize/prompt-builder.js';
9
9
  export function createStreamDeltaState() {
10
- return { messageId: null, textBlockId: null };
10
+ return { messageId: null, model: null, textBlockId: null };
11
11
  }
12
- /**
13
- * Translate one raw stdout line (already JSON-parsed) into an incremental text chunk, advancing
14
- * `state`. Returns null for every line that is not a non-empty text delta — including all complete
15
- * events, which keep travelling their existing path untouched.
16
- *
17
- * `blockId` is `${message.id}:${content_block_index}` per the streaming contract: stable for one
18
- * assistant text block and shared with the finalizing message via {@link takeTextBlockId}.
19
- */
12
+ function observeMessageStart(event, state) {
13
+ state.messageId = typeof event.message?.id === 'string' ? event.message.id : null;
14
+ state.model = typeof event.message?.model === 'string' ? event.message.model : null;
15
+ state.textBlockId = null;
16
+ }
17
+ function observeBlockStart(event, state) {
18
+ if (event.content_block?.type !== 'text' || !state.messageId)
19
+ return;
20
+ if (typeof event.index !== 'number')
21
+ return;
22
+ state.textBlockId = `${state.messageId}:${event.index}`;
23
+ }
24
+ /** Translate a partial stdout event into one text delta while advancing the message cursor. */
20
25
  export function parseStreamEvent(data, state) {
21
26
  if (!data || data.type !== 'stream_event')
22
27
  return null;
23
- const ev = data.event;
24
- if (!ev || typeof ev.type !== 'string')
28
+ const event = data.event;
29
+ if (!event || typeof event.type !== 'string')
25
30
  return null;
26
- if (ev.type === 'message_start') {
27
- state.messageId = typeof ev.message?.id === 'string' ? ev.message.id : null;
28
- state.textBlockId = null;
31
+ if (event.type === 'message_start') {
32
+ observeMessageStart(event, state);
29
33
  return null;
30
34
  }
31
- if (ev.type === 'content_block_start') {
32
- if (ev.content_block?.type === 'text' && state.messageId && typeof ev.index === 'number') {
33
- state.textBlockId = `${state.messageId}:${ev.index}`;
34
- }
35
+ if (event.type === 'content_block_start') {
36
+ observeBlockStart(event, state);
35
37
  return null;
36
38
  }
37
- if (ev.type !== 'content_block_delta')
38
- return null;
39
- if (ev.delta?.type !== 'text_delta')
39
+ if (event.type !== 'content_block_delta' || event.delta?.type !== 'text_delta')
40
40
  return null;
41
- const text = ev.delta.text;
41
+ const text = event.delta.text;
42
42
  if (typeof text !== 'string' || text.length === 0)
43
43
  return null;
44
- // No message_start seen (stream joined mid-flight): a blockId would be fabricated and could
45
- // never match the finalizing message, so drop the chunk rather than render an orphan row.
46
- if (!state.messageId || typeof ev.index !== 'number')
44
+ if (!state.messageId || typeof event.index !== 'number')
47
45
  return null;
48
- const blockId = `${state.messageId}:${ev.index}`;
49
- // A delta for a block whose content_block_start was missed still identifies its own block.
46
+ const blockId = `${state.messageId}:${event.index}`;
50
47
  state.textBlockId = blockId;
51
48
  return { text, blockId };
52
49
  }
@@ -1,8 +1,9 @@
1
- // input: tools, declarative hook registry, Claude defaults
2
- // output: buildHooksSettings + hardcoded rollback hook table
1
+ // input: tools, hook registry, Claude defaults, runtime settings
2
+ // output: buildHooksSettings and hardcoded rollback table
3
3
  // pos: Builds safe Claude hook settings from the registry
4
4
  // >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
5
5
  import * as path from 'path';
6
+ import { getSettings } from '../../core/settings.js';
6
7
  import { filterHookEntries, loadHookRegistry } from '../../store/hook-registry.js';
7
8
  import { DEFAULT_TOOLS, HOOKS_DIR, HOOK_TIMEOUT_S } from './defaults.js';
8
9
  const AGENT_EVENT_NAMES = {
@@ -107,7 +108,7 @@ function compileRegistryHooks(toolsList) {
107
108
  }
108
109
  export function buildHooksSettings(tools) {
109
110
  const toolsList = (tools || DEFAULT_TOOLS).split(',').map((tool) => tool.trim());
110
- if (process.env.CORTEX_HOOKS_LEGACY === '1')
111
+ if (getSettings().hooksLegacy)
111
112
  return buildLegacyHooksSettings(toolsList);
112
113
  return compileRegistryHooks(toolsList);
113
114
  }
@@ -1,11 +1,46 @@
1
- // input: Path to Claude session jsonl file, raw jsonl entries
2
- // output: JsonlTail (file watcher emitting raw events) + JsonlEventNormalizer (raw → NormalizedEvent)
3
- // pos: DR-0012 Phase 1 — bridges Claude's interactive-mode jsonl transcript to Cortex's NormalizedEvent stream
4
- // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
1
+ // input: Claude transcript paths and JSONL records
2
+ // output: transcript events with cache-read accounting
3
+ // pos: Claude transcript event normalizer
4
+ // >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
5
5
  import { EventEmitter } from 'node:events';
6
6
  import * as fs from 'fs';
7
7
  import { isPlanFilePath } from './event-parser.js';
8
8
  import { usageToCost } from './cost-from-usage.js';
9
+ // =====================================================================================
10
+ // JsonlEventNormalizer — pure: jsonl raw event → NormalizedEvent[]
11
+ // =====================================================================================
12
+ function exactToken(value) {
13
+ return Number.isSafeInteger(value) && Number(value) >= 0;
14
+ }
15
+ function summarizeUsage(entries) {
16
+ let totalCost = 0;
17
+ let costKnown = true;
18
+ let tokensIn = 0;
19
+ let tokensOut = 0;
20
+ let cachedTokens = 0;
21
+ let promptKnown = true;
22
+ let cachedKnown = true;
23
+ let model = '';
24
+ for (const entry of entries) {
25
+ const result = usageToCost(entry.usage, entry.model);
26
+ if (result === null)
27
+ costKnown = false;
28
+ else
29
+ totalCost += result.totalUsd;
30
+ const input = entry.usage.input_tokens;
31
+ const created = entry.usage.cache_creation_input_tokens;
32
+ const read = entry.usage.cache_read_input_tokens;
33
+ const cacheIsKnown = exactToken(created) && exactToken(read);
34
+ promptKnown &&= exactToken(input) && cacheIsKnown;
35
+ cachedKnown &&= cacheIsKnown;
36
+ tokensIn += (input ?? 0) + (created ?? 0) + (read ?? 0);
37
+ tokensOut += entry.usage.output_tokens ?? 0;
38
+ cachedTokens += read ?? 0;
39
+ if (entry.model)
40
+ model = entry.model;
41
+ }
42
+ return { totalCost, costKnown, tokensIn, tokensOut, cachedTokens, promptKnown, cachedKnown, model };
43
+ }
9
44
  /**
10
45
  * Tool names that signal AskUserQuestion semantics worth translating into an ACTIONABLE
11
46
  * `ask_user_question` NormalizedEvent (which drives the post-hoc Slack posting machinery:
@@ -78,11 +113,16 @@ export class JsonlEventNormalizer {
78
113
  });
79
114
  this.turnCount += 1;
80
115
  }
116
+ const model = typeof msg.model === 'string' ? msg.model : undefined;
81
117
  for (const block of (msg.content || [])) {
82
118
  if (!block || typeof block !== 'object')
83
119
  continue;
84
120
  if (block.type === 'text' && typeof block.text === 'string' && block.text.length > 0) {
85
- events.push({ type: 'assistant_text', text: block.text, blockId: typeof block.id === 'string' ? block.id : msgId });
121
+ events.push({
122
+ type: 'assistant_text', text: block.text,
123
+ blockId: typeof block.id === 'string' ? block.id : msgId,
124
+ ...(model !== undefined ? { model } : {}),
125
+ });
86
126
  }
87
127
  else if (block.type === 'tool_use') {
88
128
  const toolUseId = typeof block.id === 'string' ? block.id : '';
@@ -146,42 +186,21 @@ export class JsonlEventNormalizer {
146
186
  }
147
187
  handleTurnDuration(_raw) {
148
188
  const events = [];
149
- let totalCost = 0;
150
- let costKnown = true;
151
- let tokensIn = 0;
152
- let tokensOut = 0;
153
- let lastModel = '';
154
- for (const entry of this.currentTurnUsages) {
155
- const result = usageToCost(entry.usage, entry.model);
156
- if (result === null)
157
- costKnown = false;
158
- else
159
- totalCost += result.totalUsd;
160
- tokensIn +=
161
- (entry.usage.input_tokens ?? 0)
162
- + (entry.usage.cache_creation_input_tokens ?? 0)
163
- + (entry.usage.cache_read_input_tokens ?? 0);
164
- tokensOut += (entry.usage.output_tokens ?? 0);
165
- if (entry.model)
166
- lastModel = entry.model;
167
- }
168
- const numTurns = this.turnCount;
189
+ const usage = summarizeUsage(this.currentTurnUsages);
169
190
  if (this.currentTurnUsages.length > 0) {
170
191
  events.push({
171
- type: 'cost_record',
172
- provider: 'claude',
173
- model: lastModel,
174
- tokens_in: tokensIn,
175
- tokens_out: tokensOut,
176
- cost_usd: costKnown ? totalCost : null,
192
+ type: 'cost_record', provider: 'claude', model: usage.model,
193
+ tokens_in: usage.tokensIn, tokens_out: usage.tokensOut,
194
+ prompt_tokens: usage.promptKnown ? usage.tokensIn : null,
195
+ cached_tokens: usage.cachedKnown ? usage.cachedTokens : null,
196
+ cost_usd: usage.costKnown ? usage.totalCost : null,
177
197
  });
178
198
  }
179
199
  events.push({
180
- type: 'turn_complete',
181
- numTurns,
182
- totalCostUsd: costKnown && this.currentTurnUsages.length > 0 ? totalCost : null,
200
+ type: 'turn_complete', numTurns: this.turnCount,
201
+ totalCostUsd: usage.costKnown && this.currentTurnUsages.length > 0
202
+ ? usage.totalCost : null,
183
203
  });
184
- // Reset per-turn state (msg.id set kept — it's session-scoped, not turn-scoped).
185
204
  this.currentTurnUsages = [];
186
205
  this.turnCount = 0;
187
206
  return events;
@@ -1,3 +1,4 @@
1
+ import type { McpComposition } from '../types.js';
1
2
  /**
2
3
  * Adapter mode selector. `print` (default) uses `-p` + stream-json; `tui` uses interactive TUI
3
4
  * under tmux with jsonl tail (DR-0012). Both modes share the rest of the CLI surface.
@@ -13,17 +14,23 @@ export interface ClaudeSpawnOptions {
13
14
  outputStyle?: string | null;
14
15
  needsResume: boolean;
15
16
  sessionId: string;
16
- /** Override MCP config path. Thread sessions pass CORE_MCP_CONFIG as their marker. */
17
- mcpConfigPath?: string;
17
+ /** Declared MCP privilege surface. Defaults to the ordinary direct surface. */
18
+ mcpComposition?: McpComposition;
19
+ /** Concrete MCP files supplied by a frozen one-shot run configuration. */
20
+ mcpConfigPaths?: string[] | null;
21
+ /** Omit all configured hooks for isolated one-shot execution. */
22
+ disableHooks?: boolean;
23
+ /** Explicit partial-message policy; absent reads the daemon setting. */
24
+ streamDeltas?: boolean;
18
25
  /** Layer the cortex-slack MCP server on top of the base config. Set by the adapter for sessions
19
- * that originate from Slack (channel carries the `slack:` prefix). Ignored for thread sessions. */
26
+ * that originate from Slack (channel carries the `slack:` prefix). Direct composition only. */
20
27
  loadSlackMcp?: boolean;
21
28
  /** Layer the cortex-feishu MCP server on top of the base config. Set by the adapter for sessions
22
- * that originate from Feishu (channel carries the `feishu:` prefix). Ignored for thread sessions. */
29
+ * that originate from Feishu (channel carries the `feishu:` prefix). Direct composition only. */
23
30
  loadFeishuMcp?: boolean;
24
31
  /** Layer the cortex-web MCP server on top of the base config. Set by the adapter for sessions that
25
32
  * originate from the Web UI (channel carries the `web:` prefix), enabling the send_file tool.
26
- * Ignored for thread sessions. */
33
+ * Direct composition only. */
27
34
  loadWebMcp?: boolean;
28
35
  /** Thinking level from the profile's `thinking` field → `--effort <level>`
29
36
  * (low/medium/high/xhigh/max). Absent → no flag. */
@@ -35,15 +42,10 @@ export interface ClaudeSpawnOptions {
35
42
  /** True for user-message-initiated sessions (not thread/scheduled pipeline workers). In print
36
43
  * mode, such sessions additionally get the cortex-tui-bridge MCP interaction tools
37
44
  * (cortex_plan_enter/exit, cortex_ask_user) because the native EnterPlanMode/ExitPlanMode/
38
- * AskUserQuestion are filtered out by headless `-p`. Thread/core sessions never get them. */
45
+ * AskUserQuestion are filtered out by headless `-p`. Non-direct compositions never get them. */
39
46
  isUserInitiated?: boolean;
40
47
  }
41
- /**
42
- * Kill switch for token-level assistant streaming (`CORTEX_STREAM_DELTAS=0`). Read at call time, so
43
- * a daemon restart is enough to flip it. When off, print mode drops `--include-partial-messages`
44
- * and the CLI emits no `stream_event` lines at all — the delta pipeline goes dark at the source.
45
- * Only the literal `0` disables; anything else (unset included) keeps streaming on.
46
- */
48
+ /** Token-level assistant streaming gate, read for each spawn argument build. */
47
49
  export declare function isStreamDeltasEnabled(): boolean;
48
50
  export declare function buildSpawnArgs(options: ClaudeSpawnOptions): string[];
49
51
  /** Cortex agent execution context — surfaces as CORTEX_* env vars so MCP tools
@@ -69,5 +71,6 @@ export interface CortexAgentContext {
69
71
  * current task as the parent of a child task without the agent re-declaring it. */
70
72
  taskId?: string | null;
71
73
  taskProject?: string | null;
74
+ taskGeneration?: string | null;
72
75
  }
73
76
  export declare function buildClaudeEnv(channel: string, sessionId: string, callbackSource?: string | null, scheduleTaskId?: string | null, anthropicBaseUrl?: string, extraEnv?: Record<string, string>, context?: CortexAgentContext): NodeJS.ProcessEnv;
@@ -1,49 +1,46 @@
1
- // input: Claude options, scoped MCP paths, hooks, environment
2
- // output: Claude CLI arguments and authoritative child environment
3
- // pos: Claude process spawn configuration
1
+ // input: Claude options, task context, composition, hooks
2
+ // output: Claude CLI arguments and isolated child environment
3
+ // pos: Resolves Claude process configuration
4
4
  // >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
5
- import { CORE_MCP_CONFIG, DEFAULT_TOOLS, FEISHU_MCP_CONFIG, MANAGER_QA_MCP_CONFIG, MCP_CONFIG, SLACK_MCP_CONFIG, TASKS_MCP_CONFIG, THREAD_MCP_CONFIG, TUI_BRIDGE_TOOLS, TUI_MCP_CONFIG, TUI_STRIP_TOOLS, TUI_TOOLS, WEB_MCP_CONFIG, } from './defaults.js';
6
- // CORE_MCP_CONFIG is the thread marker: callers set mcpConfigPath to it for template sessions.
7
- // buildSpawnArgs then layers task monitoring, manager answers, and thread control onto that base.
5
+ import { BENCHMARK_THREAD_MCP_CONFIG, CORE_MCP_CONFIG, DEFAULT_TOOLS, EMPTY_MCP_CONFIG, FEISHU_MCP_CONFIG, MANAGER_QA_MCP_CONFIG, MCP_CONFIG, SLACK_MCP_CONFIG, TASKS_MCP_CONFIG, THREAD_MCP_CONFIG, TUI_BRIDGE_TOOLS, TUI_MCP_CONFIG, TUI_STRIP_TOOLS, TUI_TOOLS, WEB_MCP_CONFIG, } from './defaults.js';
6
+ import { getSettings } from '../../core/settings.js';
8
7
  import { buildHooksSettings } from './hooks-builder.js';
9
- /**
10
- * Kill switch for token-level assistant streaming (`CORTEX_STREAM_DELTAS=0`). Read at call time, so
11
- * a daemon restart is enough to flip it. When off, print mode drops `--include-partial-messages`
12
- * and the CLI emits no `stream_event` lines at all — the delta pipeline goes dark at the source.
13
- * Only the literal `0` disables; anything else (unset included) keeps streaming on.
14
- */
8
+ /** Token-level assistant streaming gate, read for each spawn argument build. */
15
9
  export function isStreamDeltasEnabled() {
16
- return process.env.CORTEX_STREAM_DELTAS !== '0';
10
+ return getSettings().streamDeltas;
17
11
  }
12
+ const MCP_CONFIGS = {
13
+ direct: [MCP_CONFIG],
14
+ 'thread-control': [CORE_MCP_CONFIG, TASKS_MCP_CONFIG, MANAGER_QA_MCP_CONFIG, THREAD_MCP_CONFIG],
15
+ none: [EMPTY_MCP_CONFIG],
16
+ 'benchmark-thread-run': [BENCHMARK_THREAD_MCP_CONFIG],
17
+ };
18
18
  export function buildSpawnArgs(options) {
19
19
  const mode = options.mode ?? 'print';
20
- // Direct sessions use the full config (core + tasks + manager answers + ext). Template threads
21
- // compose isolated core + tasks + manager-answer + thread-control privilege layers.
22
- // The interaction bridge and platform-specific servers remain direct-session-only.
23
- const isThreadSession = options.mcpConfigPath === CORE_MCP_CONFIG;
24
- const wantsInteractionBridge = !isThreadSession
20
+ const composition = options.mcpComposition ?? 'direct';
21
+ const isDirect = composition === 'direct';
22
+ const wantsInteractionBridge = isDirect
25
23
  && (mode === 'tui' || (mode === 'print' && !!options.isUserInitiated));
26
- const baseMcpConfig = options.mcpConfigPath || MCP_CONFIG;
27
- const mcpConfigs = isThreadSession
28
- ? [baseMcpConfig, TASKS_MCP_CONFIG, MANAGER_QA_MCP_CONFIG, THREAD_MCP_CONFIG]
29
- : [baseMcpConfig];
24
+ const mcpConfigs = options.mcpConfigPaths
25
+ ? [...options.mcpConfigPaths]
26
+ : [...MCP_CONFIGS[composition]];
30
27
  if (wantsInteractionBridge)
31
28
  mcpConfigs.push(TUI_MCP_CONFIG);
32
29
  // Slack-originated sessions additionally layer the cortex-slack server (slack_send_file tool).
33
- // Suppressed for thread/core sessions, which run no file-sending work and stay on the core set only.
34
- if (options.loadSlackMcp && !isThreadSession)
30
+ // Suppressed for non-direct compositions.
31
+ if (options.loadSlackMcp && isDirect)
35
32
  mcpConfigs.push(SLACK_MCP_CONFIG);
36
33
  // Feishu-originated sessions additionally layer the cortex-feishu server (Feishu document tools).
37
- // Suppressed for thread/core sessions, which run no document work and stay on the core set only.
38
- if (options.loadFeishuMcp && !isThreadSession)
34
+ // Suppressed for non-direct compositions.
35
+ if (options.loadFeishuMcp && isDirect)
39
36
  mcpConfigs.push(FEISHU_MCP_CONFIG);
40
37
  // Web-UI-originated sessions additionally layer the cortex-web server (send_file tool).
41
- // Suppressed for thread/core sessions, which stay on the core set only.
42
- if (options.loadWebMcp && !isThreadSession)
38
+ // Suppressed for non-direct compositions.
39
+ if (options.loadWebMcp && isDirect)
43
40
  mcpConfigs.push(WEB_MCP_CONFIG);
44
41
  // TUI tool whitelist swaps the three native interaction tools for their MCP bridge equivalents;
45
- // thread/core TUI sessions have no bridge server, so they fall back to the standard tool set.
46
- const toolsDefault = (mode === 'tui' && !isThreadSession) ? TUI_TOOLS : DEFAULT_TOOLS;
42
+ // non-direct TUI sessions have no bridge server, so they fall back to the standard tool set.
43
+ const toolsDefault = (mode === 'tui' && isDirect) ? TUI_TOOLS : DEFAULT_TOOLS;
47
44
  const args = [];
48
45
  if (mode === 'print') {
49
46
  // Stream-json over stdio for -p mode (current behavior — preserved exactly for regression)
@@ -61,7 +58,7 @@ export function buildSpawnArgs(options) {
61
58
  // It is what lets the Web UI show text as it is generated instead of waiting for the whole
62
59
  // block (measured gap on a long reply: first delta at ~3.5s vs the complete event at ~25s).
63
60
  // TUI mode reads the session jsonl, not stdout, so the flag would be pure overhead there.
64
- if (isStreamDeltasEnabled())
61
+ if (options.streamDeltas ?? isStreamDeltasEnabled())
65
62
  args.push('--include-partial-messages');
66
63
  }
67
64
  // TUI mode: strip native interaction tools (AskUserQuestion / EnterPlanMode / ExitPlanMode)
@@ -71,7 +68,7 @@ export function buildSpawnArgs(options) {
71
68
  if (mode === 'tui' && options.tools) {
72
69
  effectiveTools = options.tools.split(',').filter(t => !TUI_STRIP_TOOLS.has(t)).join(',');
73
70
  }
74
- // Print mode, user-initiated non-thread sessions: append the cortex-tui-bridge interaction tools.
71
+ // Print mode, user-initiated direct sessions: append the cortex-tui-bridge interaction tools.
75
72
  // The native EnterPlanMode/ExitPlanMode/AskUserQuestion are dropped by headless -p regardless of
76
73
  // the allowlist, so these MCP equivalents are the only way plan/ask reaches the user. TUI mode
77
74
  // already carries them via TUI_TOOLS, so only the print branch needs the append.
@@ -79,7 +76,11 @@ export function buildSpawnArgs(options) {
79
76
  effectiveTools = [effectiveTools, ...TUI_BRIDGE_TOOLS].filter(Boolean).join(',');
80
77
  }
81
78
  // Both modes: permission bypass + MCP + tools
82
- args.push('--dangerously-skip-permissions', '--permission-mode', 'bypassPermissions', '--mcp-config', ...mcpConfigs, '--tools', effectiveTools);
79
+ args.push('--dangerously-skip-permissions', '--permission-mode', 'bypassPermissions', '--mcp-config', ...mcpConfigs);
80
+ if (composition === 'none' || composition === 'benchmark-thread-run') {
81
+ args.push('--strict-mcp-config');
82
+ }
83
+ args.push('--tools', effectiveTools);
83
84
  if (options.systemPrompt)
84
85
  args.push('--system-prompt', options.systemPrompt);
85
86
  if (options.appendSystemPrompt)
@@ -99,7 +100,9 @@ export function buildSpawnArgs(options) {
99
100
  for (const [k, v] of Object.entries(options.extraOption))
100
101
  args.push(k, v);
101
102
  }
102
- const settings = { hooks: buildHooksSettings(options.tools) };
103
+ const settings = {
104
+ hooks: options.disableHooks ? {} : buildHooksSettings(options.tools),
105
+ };
103
106
  if (options.outputStyle)
104
107
  settings.outputStyle = options.outputStyle;
105
108
  args.push('--settings', JSON.stringify(settings));
@@ -140,6 +143,10 @@ export function buildClaudeEnv(channel, sessionId, callbackSource, scheduleTaskI
140
143
  env.CORTEX_SCHEDULE_TASK_ID = scheduleTaskId;
141
144
  if (anthropicBaseUrl)
142
145
  env.ANTHROPIC_BASE_URL = anthropicBaseUrl;
146
+ if (extraEnv) {
147
+ for (const [key, value] of Object.entries(extraEnv))
148
+ env[key] = value;
149
+ }
143
150
  delete env.CORTEX_THREAD_ID;
144
151
  delete env.CORTEX_PROFILE;
145
152
  delete env.CORTEX_PROJECT;
@@ -147,6 +154,7 @@ export function buildClaudeEnv(channel, sessionId, callbackSource, scheduleTaskI
147
154
  delete env.CORTEX_THREAD_DEPTH;
148
155
  delete env.CORTEX_TASK_ID;
149
156
  delete env.CORTEX_TASK_PROJECT;
157
+ delete env.CORTEX_TASK_GENERATION;
150
158
  if (context?.threadId)
151
159
  env.CORTEX_THREAD_ID = context.threadId;
152
160
  if (context?.threadDepth != null)
@@ -163,9 +171,7 @@ export function buildClaudeEnv(channel, sessionId, callbackSource, scheduleTaskI
163
171
  env.CORTEX_TASK_ID = context.taskId;
164
172
  if (context?.taskProject)
165
173
  env.CORTEX_TASK_PROJECT = context.taskProject;
166
- if (extraEnv) {
167
- for (const [k, v] of Object.entries(extraEnv))
168
- env[k] = v;
169
- }
174
+ if (context?.taskGeneration)
175
+ env.CORTEX_TASK_GENERATION = context.taskGeneration;
170
176
  return env;
171
177
  }
@@ -51,25 +51,12 @@ export declare class TmuxControl {
51
51
  */
52
52
  sendKeys(name: string, ...keys: string[]): void;
53
53
  /**
54
- * Paste arbitrary text (including multi-line + non-ASCII + shell metachars) into the session's
55
- * input area without submitting it. Internally: write text to a tempfile → tmux load-buffer (named
56
- * buffer to avoid concurrent collisions) → tmux paste-buffer -d (free buffer after paste) → unlink tempfile.
57
- *
58
- * Does NOT send Enter — caller decides whether to submit (typically `sendKeys(name, 'Enter')` after).
59
- *
60
- * Why a named buffer + -d: tmux has a global anonymous paste buffer; concurrent sessions on the same
61
- * tmux server would race. Named buffers + -d (auto-delete after paste) avoid that.
62
- *
63
- * Why -p (bracketed paste): Claude's Ink TUI only registers input wrapped in bracketed-paste escape
64
- * sequences (ESC[200~ … ESC[201~) as a paste. Without -p (Claude ≥2.1.162) the text lands but the
65
- * prompt buffer never accepts it, so the follow-up Enter submits nothing and no jsonl is written —
66
- * the turn then dies on the first-event watchdog. Verified: with -p, paste→Enter submits and Claude
67
- * responds; without it the pane goes blank and the transcript only contains session-init lines.
68
- *
69
- * @see DR-0012 spike §4 — paste-buffer is more reliable than send-keys -l for special chars.
54
+ * Paste arbitrary text without exposing it in process argv. A unique 0600 tempfile feeds a named
55
+ * tmux buffer; cleanup explicitly removes both artifacts on success and every failure path.
56
+ * Does not submit Enter. `-p` supplies the bracketed-paste sequences required by Claude's Ink TUI.
70
57
  */
71
58
  pasteText(name: string, text: string): void;
72
- /** Read the current visible pane content. Used only for diagnostics — production paths rely on jsonl. */
59
+ /** Read visible pane content for TUI diagnostics and bounded authentication parsing. */
73
60
  capturePane(name: string): string;
74
61
  /**
75
62
  * List all tmux session names on the server, optionally filtered by prefix.
@@ -1,7 +1,7 @@
1
- // input: tmux command argv (string[])
2
- // output: TmuxControl class with hasSession / newSession / killSession / sendKeys / pasteText / capturePane / listSessions
3
- // pos: Foundational utility for Claude TUI adapter (DR-0012 Phase 1) — wraps tmux CLI behind an injectable exec
4
- // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
1
+ // input: child processes, filesystem, and tmux argv
2
+ // output: TmuxControl and launcher staging
3
+ // pos: Claude tmux command wrapper
4
+ // >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
5
5
  import { spawnSync } from 'child_process';
6
6
  import * as fs from 'fs';
7
7
  import * as os from 'os';
@@ -80,45 +80,31 @@ export class TmuxControl {
80
80
  this.exec(['send-keys', '-t', name, ...keys]);
81
81
  }
82
82
  /**
83
- * Paste arbitrary text (including multi-line + non-ASCII + shell metachars) into the session's
84
- * input area without submitting it. Internally: write text to a tempfile → tmux load-buffer (named
85
- * buffer to avoid concurrent collisions) → tmux paste-buffer -d (free buffer after paste) → unlink tempfile.
86
- *
87
- * Does NOT send Enter — caller decides whether to submit (typically `sendKeys(name, 'Enter')` after).
88
- *
89
- * Why a named buffer + -d: tmux has a global anonymous paste buffer; concurrent sessions on the same
90
- * tmux server would race. Named buffers + -d (auto-delete after paste) avoid that.
91
- *
92
- * Why -p (bracketed paste): Claude's Ink TUI only registers input wrapped in bracketed-paste escape
93
- * sequences (ESC[200~ … ESC[201~) as a paste. Without -p (Claude ≥2.1.162) the text lands but the
94
- * prompt buffer never accepts it, so the follow-up Enter submits nothing and no jsonl is written —
95
- * the turn then dies on the first-event watchdog. Verified: with -p, paste→Enter submits and Claude
96
- * responds; without it the pane goes blank and the transcript only contains session-init lines.
97
- *
98
- * @see DR-0012 spike §4 — paste-buffer is more reliable than send-keys -l for special chars.
83
+ * Paste arbitrary text without exposing it in process argv. A unique 0600 tempfile feeds a named
84
+ * tmux buffer; cleanup explicitly removes both artifacts on success and every failure path.
85
+ * Does not submit Enter. `-p` supplies the bracketed-paste sequences required by Claude's Ink TUI.
99
86
  */
100
87
  pasteText(name, text) {
101
88
  const bufName = `cortex-${crypto.randomBytes(6).toString('hex')}`;
102
89
  const tmpfile = path.join(os.tmpdir(), `cortex-tmux-paste-${bufName}.txt`);
103
- fs.writeFileSync(tmpfile, text, 'utf8');
90
+ let bufferLoaded = false;
91
+ fs.writeFileSync(tmpfile, text, { encoding: 'utf8', mode: 0o600 });
104
92
  try {
105
- const r1 = this.exec(['load-buffer', '-b', bufName, tmpfile]);
106
- if (r1.status !== 0) {
107
- throw new Error(`tmux load-buffer failed (status=${r1.status}): ${r1.stderr.trim()}`);
93
+ const loaded = this.exec(['load-buffer', '-b', bufName, tmpfile]);
94
+ if (loaded.status !== 0) {
95
+ throw new Error(`tmux load-buffer failed (status=${loaded.status}): ${loaded.stderr.trim()}`);
108
96
  }
109
- const r2 = this.exec(['paste-buffer', '-p', '-d', '-b', bufName, '-t', name]);
110
- if (r2.status !== 0) {
111
- throw new Error(`tmux paste-buffer failed (status=${r2.status}): ${r2.stderr.trim()}`);
97
+ bufferLoaded = true;
98
+ const pasted = this.exec(['paste-buffer', '-p', '-b', bufName, '-t', name]);
99
+ if (pasted.status !== 0) {
100
+ throw new Error(`tmux paste-buffer failed (status=${pasted.status}): ${pasted.stderr.trim()}`);
112
101
  }
113
102
  }
114
103
  finally {
115
- try {
116
- fs.unlinkSync(tmpfile);
117
- }
118
- catch { /* best effort */ }
104
+ cleanupPasteArtifacts(this.exec, bufName, tmpfile, bufferLoaded);
119
105
  }
120
106
  }
121
- /** Read the current visible pane content. Used only for diagnostics — production paths rely on jsonl. */
107
+ /** Read visible pane content for TUI diagnostics and bounded authentication parsing. */
122
108
  capturePane(name) {
123
109
  const r = this.exec(['capture-pane', '-t', name, '-p']);
124
110
  return r.stdout;
@@ -140,6 +126,27 @@ export class TmuxControl {
140
126
  return names.filter(n => n.startsWith(prefix));
141
127
  }
142
128
  }
129
+ function cleanupPasteArtifacts(exec, bufferName, tempfile, bufferLoaded) {
130
+ let failed = false;
131
+ try {
132
+ fs.unlinkSync(tempfile);
133
+ }
134
+ catch (error) {
135
+ if (error.code !== 'ENOENT')
136
+ failed = true;
137
+ }
138
+ try {
139
+ const deleted = exec(['delete-buffer', '-b', bufferName]);
140
+ if (bufferLoaded && deleted.status !== 0)
141
+ failed = true;
142
+ }
143
+ catch {
144
+ if (bufferLoaded)
145
+ failed = true;
146
+ }
147
+ if (failed)
148
+ throw new Error('tmux paste cleanup failed.');
149
+ }
143
150
  // =====================================================================================
144
151
  // Launcher script staging (newSession command-length workaround)
145
152
  // =====================================================================================