@cortex-agent/server 2026.5.25-1 → 2026.6.11

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 (354) hide show
  1. package/defaults/config/thread-templates.json +28 -1
  2. package/defaults/hooks/cortex-md-injector.mjs +47 -31
  3. package/defaults/hooks/post-task-hook.mjs +6 -0
  4. package/defaults/hooks/task-status-check.mjs +8 -0
  5. package/defaults/mcp-config-slack.json +11 -0
  6. package/defaults/plugins/cortex-stage-gate/skills/task/SKILL.md +18 -0
  7. package/defaults/plugins/cortex-system/skills/schedule/SKILL.md +5 -6
  8. package/defaults/prompts/directives/manager.md +67 -0
  9. package/dist/agent-adapter/claude/adapter-tui.d.ts +35 -3
  10. package/dist/agent-adapter/claude/adapter-tui.js +91 -12
  11. package/dist/agent-adapter/claude/adapter.js +11 -0
  12. package/dist/agent-adapter/claude/defaults.d.ts +30 -0
  13. package/dist/agent-adapter/claude/defaults.js +30 -0
  14. package/dist/agent-adapter/claude/jsonl-tail.d.ts +2 -2
  15. package/dist/agent-adapter/claude/jsonl-tail.js +25 -20
  16. package/dist/agent-adapter/claude/spawn-args.d.ts +11 -0
  17. package/dist/agent-adapter/claude/spawn-args.js +49 -7
  18. package/dist/agent-adapter/claude/tmux-control.d.ts +20 -0
  19. package/dist/agent-adapter/claude/tmux-control.js +54 -8
  20. package/dist/agent-adapter/codex/adapter.js +1 -1
  21. package/dist/agent-adapter/normalize/event-types.d.ts +1 -0
  22. package/dist/agent-adapter/pi/adapter.js +46 -19
  23. package/dist/agent-adapter/pi/agent-dir.d.ts +21 -0
  24. package/dist/agent-adapter/pi/agent-dir.js +53 -2
  25. package/dist/agent-adapter/pi/event-parser.js +13 -1
  26. package/dist/agent-adapter/pi/mcp-bridge.d.ts +12 -0
  27. package/dist/agent-adapter/pi/mcp-bridge.js +47 -9
  28. package/dist/agent-adapter/pi/tool-shims.d.ts +14 -0
  29. package/dist/agent-adapter/pi/tool-shims.js +167 -140
  30. package/dist/agent-adapter/types.d.ts +7 -2
  31. package/dist/core/atomic-write.js +21 -0
  32. package/dist/core/config-generator.d.ts +10 -0
  33. package/dist/core/config-generator.js +28 -0
  34. package/dist/core/gateway-generator.d.ts +77 -7
  35. package/dist/core/gateway-generator.js +301 -29
  36. package/dist/core/icons.d.ts +68 -0
  37. package/dist/core/icons.js +67 -0
  38. package/dist/core/profile-generator.d.ts +6 -0
  39. package/dist/core/profile-generator.js +35 -7
  40. package/dist/core/running-executions.d.ts +51 -41
  41. package/dist/core/running-executions.js +120 -73
  42. package/dist/core/status-format.js +3 -2
  43. package/dist/core/task-parser.d.ts +3 -0
  44. package/dist/core/task-parser.js +3 -1
  45. package/dist/core/types/thread-types.d.ts +54 -8
  46. package/dist/domain/agents/facade.d.ts +18 -0
  47. package/dist/domain/agents/facade.js +26 -3
  48. package/dist/domain/agents/profile-manager.d.ts +11 -0
  49. package/dist/domain/agents/profile-manager.js +21 -2
  50. package/dist/domain/costs/codex-usage-monitor.js +2 -1
  51. package/dist/domain/costs/rate-limit-throttle.js +14 -2
  52. package/dist/domain/executions/registry.d.ts +24 -0
  53. package/dist/domain/executions/registry.js +38 -0
  54. package/dist/domain/mcp/core-server.js +15 -3
  55. package/dist/domain/mcp/feishu/bitable.d.ts +3 -0
  56. package/dist/domain/mcp/feishu/bitable.js +168 -0
  57. package/dist/domain/mcp/feishu/block-types.d.ts +44 -0
  58. package/dist/domain/mcp/feishu/block-types.js +127 -0
  59. package/dist/domain/mcp/feishu/blocks-to-text.d.ts +19 -0
  60. package/dist/domain/mcp/feishu/blocks-to-text.js +43 -0
  61. package/dist/domain/mcp/feishu/client.d.ts +46 -0
  62. package/dist/domain/mcp/feishu/client.js +87 -0
  63. package/dist/domain/mcp/feishu/docx.d.ts +3 -0
  64. package/dist/domain/mcp/feishu/docx.js +163 -0
  65. package/dist/domain/mcp/feishu/drive.d.ts +23 -0
  66. package/dist/domain/mcp/feishu/drive.js +66 -0
  67. package/dist/domain/mcp/feishu/file.d.ts +14 -0
  68. package/dist/domain/mcp/feishu/file.js +107 -0
  69. package/dist/domain/mcp/feishu/index.d.ts +6 -0
  70. package/dist/domain/mcp/feishu/index.js +61 -0
  71. package/dist/domain/mcp/feishu/markdown-to-blocks.d.ts +40 -0
  72. package/dist/domain/mcp/feishu/markdown-to-blocks.js +191 -0
  73. package/dist/domain/mcp/feishu/sheets.d.ts +3 -0
  74. package/dist/domain/mcp/feishu/sheets.js +119 -0
  75. package/dist/domain/mcp/feishu/types.d.ts +26 -0
  76. package/dist/domain/mcp/feishu/types.js +38 -0
  77. package/dist/domain/mcp/feishu/user-auth.d.ts +140 -0
  78. package/dist/domain/mcp/feishu/user-auth.js +286 -0
  79. package/dist/domain/mcp/feishu/wiki.d.ts +3 -0
  80. package/dist/domain/mcp/feishu/wiki.js +77 -0
  81. package/dist/domain/mcp/feishu-server.d.ts +2 -0
  82. package/dist/domain/mcp/feishu-server.js +33 -0
  83. package/dist/domain/mcp/server.d.ts +0 -1
  84. package/dist/domain/mcp/server.js +6 -25
  85. package/dist/domain/mcp/slack-server.d.ts +3 -0
  86. package/dist/domain/mcp/slack-server.js +46 -0
  87. package/dist/domain/mcp/tools/context.js +1 -1
  88. package/dist/domain/mcp/tools/schedule.d.ts +1 -1
  89. package/dist/domain/mcp/tools/schedule.js +6 -20
  90. package/dist/domain/mcp/tools/slack.js +20 -7
  91. package/dist/domain/mcp/tools/thread-ops.d.ts +2 -0
  92. package/dist/domain/mcp/tools/thread-ops.js +121 -0
  93. package/dist/domain/mcp/tools/time.d.ts +2 -0
  94. package/dist/domain/mcp/tools/time.js +66 -0
  95. package/dist/domain/mcp/tools/tui-ask.js +1 -1
  96. package/dist/domain/mcp/tools/tui-plan.js +2 -2
  97. package/dist/domain/mcp/tui-server.js +1 -0
  98. package/dist/domain/monitor/disk-monitor.js +2 -1
  99. package/dist/domain/monitor/gpu-monitor.js +2 -1
  100. package/dist/domain/remote/client-hot-reload.js +3 -2
  101. package/dist/domain/remote/client-manager.js +8 -6
  102. package/dist/domain/scheduling/job-registry.d.ts +4 -0
  103. package/dist/domain/scheduling/job-registry.js +1 -0
  104. package/dist/domain/scheduling/jobs/_shared.js +2 -1
  105. package/dist/domain/scheduling/jobs/memory-index-regen.js +3 -2
  106. package/dist/domain/scheduling/jobs/scheduled-task.js +9 -23
  107. package/dist/domain/scheduling/jobs/sync-public.js +4 -3
  108. package/dist/domain/scheduling/jobs/target-dispatch.d.ts +1 -8
  109. package/dist/domain/scheduling/jobs/target-dispatch.js +0 -7
  110. package/dist/domain/scheduling/jobs/task-archive.js +3 -2
  111. package/dist/domain/scheduling/jobs/task-dispatch.js +120 -10
  112. package/dist/domain/scheduling/schedule-command.js +16 -15
  113. package/dist/domain/scheduling/scheduler.d.ts +1 -1
  114. package/dist/domain/scheduling/scheduler.js +2 -1
  115. package/dist/domain/sessions/session-hooks.d.ts +2 -2
  116. package/dist/domain/sessions/session-hooks.js +19 -18
  117. package/dist/domain/sessions/session-lifecycle.d.ts +38 -0
  118. package/dist/domain/sessions/session-lifecycle.js +44 -0
  119. package/dist/domain/system/install-cli.d.ts +7 -0
  120. package/dist/domain/system/install-cli.js +106 -0
  121. package/dist/domain/tasks/dispatch-utils.d.ts +58 -1
  122. package/dist/domain/tasks/dispatch-utils.js +53 -4
  123. package/dist/domain/tasks/dispatcher.js +26 -0
  124. package/dist/domain/tasks/lint.js +28 -0
  125. package/dist/domain/tasks/mutator.d.ts +16 -3
  126. package/dist/domain/tasks/mutator.js +41 -12
  127. package/dist/domain/tasks/pending-tracker.js +6 -5
  128. package/dist/domain/tasks/system/task-cli.d.ts +2 -0
  129. package/dist/domain/tasks/system/task-cli.js +37 -6
  130. package/dist/domain/tasks/system/task-lifecycle-edit.js +6 -1
  131. package/dist/domain/tasks/system/task-mutations.d.ts +41 -3
  132. package/dist/domain/tasks/system/task-mutations.js +166 -8
  133. package/dist/domain/threads/contract.d.ts +17 -0
  134. package/dist/domain/threads/contract.js +59 -0
  135. package/dist/domain/threads/hook-runner.js +7 -6
  136. package/dist/domain/threads/index.d.ts +2 -0
  137. package/dist/domain/threads/index.js +3 -1
  138. package/dist/domain/threads/prompt-builder.d.ts +15 -1
  139. package/dist/domain/threads/prompt-builder.js +41 -2
  140. package/dist/domain/threads/runner.d.ts +6 -5
  141. package/dist/domain/threads/runner.js +128 -79
  142. package/dist/domain/threads/state-machine.d.ts +23 -21
  143. package/dist/domain/threads/state-machine.js +113 -54
  144. package/dist/domain/threads/template-loader.js +3 -2
  145. package/dist/domain/threads/tree.d.ts +45 -0
  146. package/dist/domain/threads/tree.js +171 -0
  147. package/dist/domain/tui-session/index.d.ts +2 -0
  148. package/dist/domain/tui-session/index.js +3 -0
  149. package/dist/domain/tui-session/tui-session-service.d.ts +2 -0
  150. package/dist/domain/tui-session/tui-session-service.js +103 -0
  151. package/dist/domain/tui-session/types.d.ts +67 -0
  152. package/dist/domain/tui-session/types.js +4 -0
  153. package/dist/domain/ui-service/index.d.ts +5 -0
  154. package/dist/domain/ui-service/index.js +3 -0
  155. package/dist/domain/ui-service/mutate/executions.d.ts +4 -0
  156. package/dist/domain/ui-service/mutate/executions.js +15 -0
  157. package/dist/domain/ui-service/mutate/schedules.d.ts +10 -0
  158. package/dist/domain/ui-service/mutate/schedules.js +39 -0
  159. package/dist/domain/ui-service/mutate/tasks.d.ts +23 -0
  160. package/dist/domain/ui-service/mutate/tasks.js +59 -0
  161. package/dist/domain/ui-service/mutate/threads.d.ts +4 -0
  162. package/dist/domain/ui-service/mutate/threads.js +21 -0
  163. package/dist/domain/ui-service/query/cost.d.ts +3 -0
  164. package/dist/domain/ui-service/query/cost.js +6 -0
  165. package/dist/domain/ui-service/query/executions.d.ts +2 -0
  166. package/dist/domain/ui-service/query/executions.js +35 -0
  167. package/dist/domain/ui-service/query/projects.d.ts +2 -0
  168. package/dist/domain/ui-service/query/projects.js +30 -0
  169. package/dist/domain/ui-service/query/schedules.d.ts +2 -0
  170. package/dist/domain/ui-service/query/schedules.js +23 -0
  171. package/dist/domain/ui-service/query/sessions.d.ts +2 -0
  172. package/dist/domain/ui-service/query/sessions.js +35 -0
  173. package/dist/domain/ui-service/query/tasks.d.ts +2 -0
  174. package/dist/domain/ui-service/query/tasks.js +30 -0
  175. package/dist/domain/ui-service/query/threads.d.ts +2 -0
  176. package/dist/domain/ui-service/query/threads.js +27 -0
  177. package/dist/domain/ui-service/subscribe.d.ts +5 -0
  178. package/dist/domain/ui-service/subscribe.js +118 -0
  179. package/dist/domain/ui-service/types.d.ts +237 -0
  180. package/dist/domain/ui-service/types.js +5 -0
  181. package/dist/domain/ui-service/ui-service.d.ts +2 -0
  182. package/dist/domain/ui-service/ui-service.js +83 -0
  183. package/dist/entry/app.js +94 -5
  184. package/dist/entry/cli.d.ts +12 -0
  185. package/dist/entry/cli.js +122 -12
  186. package/dist/entry/feishu-login.d.ts +28 -0
  187. package/dist/entry/feishu-login.js +218 -0
  188. package/dist/entry/init.d.ts +25 -2
  189. package/dist/entry/init.js +211 -64
  190. package/dist/events/event-types.d.ts +14 -0
  191. package/dist/hooks/cortex-md-injector.mjs +47 -31
  192. package/dist/hooks/post-task-hook.mjs +6 -0
  193. package/dist/hooks/task-status-check.mjs +8 -0
  194. package/dist/orchestration/agent-runner.d.ts +2 -1
  195. package/dist/orchestration/agent-runner.js +55 -55
  196. package/dist/orchestration/conduit-queue.d.ts +18 -0
  197. package/dist/orchestration/conduit-queue.js +32 -0
  198. package/dist/orchestration/conversation-runner.d.ts +48 -0
  199. package/dist/orchestration/conversation-runner.js +109 -0
  200. package/dist/orchestration/dispatch-reconciler.js +8 -1
  201. package/dist/orchestration/interactions/ask-user-question.d.ts +1 -1
  202. package/dist/orchestration/interactions/ask-user-question.js +3 -3
  203. package/dist/orchestration/interactions/interaction-handlers.js +48 -17
  204. package/dist/orchestration/interactions/plan-handler.d.ts +2 -2
  205. package/dist/orchestration/interactions/plan-handler.js +4 -3
  206. package/dist/orchestration/interactions/update-prompt.d.ts +6 -0
  207. package/dist/orchestration/interactions/update-prompt.js +100 -0
  208. package/dist/orchestration/lifecycle.d.ts +4 -4
  209. package/dist/orchestration/lifecycle.js +24 -22
  210. package/dist/orchestration/orchestrator.d.ts +1 -1
  211. package/dist/orchestration/routing/commands/cancel.js +39 -47
  212. package/dist/orchestration/routing/commands/channel.js +24 -11
  213. package/dist/orchestration/routing/commands/cost.js +2 -1
  214. package/dist/orchestration/routing/commands/device.js +3 -2
  215. package/dist/orchestration/routing/commands/dispatch.js +6 -5
  216. package/dist/orchestration/routing/commands/index.d.ts +1 -1
  217. package/dist/orchestration/routing/commands/index.js +11 -10
  218. package/dist/orchestration/routing/commands/mode.js +19 -18
  219. package/dist/orchestration/routing/commands/nvtop.js +10 -9
  220. package/dist/orchestration/routing/commands/sendfile.js +7 -6
  221. package/dist/orchestration/routing/commands/session.d.ts +1 -1
  222. package/dist/orchestration/routing/commands/session.js +17 -33
  223. package/dist/orchestration/routing/commands/tail.js +4 -3
  224. package/dist/orchestration/routing/commands/task.js +4 -3
  225. package/dist/orchestration/routing/commands/thread-handlers.js +16 -6
  226. package/dist/orchestration/routing/edit-handler.js +8 -7
  227. package/dist/orchestration/routing/hook-bridge-subscribers.js +17 -1
  228. package/dist/orchestration/routing/message-router.d.ts +1 -1
  229. package/dist/orchestration/routing/message-router.js +9 -9
  230. package/dist/orchestration/routing/webhook.js +233 -2
  231. package/dist/orchestration/status-helpers.d.ts +5 -1
  232. package/dist/orchestration/status-helpers.js +7 -6
  233. package/dist/orchestration/thread-callback.d.ts +67 -0
  234. package/dist/orchestration/thread-callback.js +465 -0
  235. package/dist/orchestration/thread-executor.d.ts +22 -1
  236. package/dist/orchestration/thread-executor.js +85 -36
  237. package/dist/platform/adapter.d.ts +6 -2
  238. package/dist/platform/adapters/composite-adapter.d.ts +89 -0
  239. package/dist/platform/adapters/composite-adapter.js +318 -0
  240. package/dist/platform/adapters/feishu-output-stream.d.ts +26 -4
  241. package/dist/platform/adapters/feishu-output-stream.js +274 -36
  242. package/dist/platform/adapters/feishu.d.ts +50 -5
  243. package/dist/platform/adapters/feishu.js +370 -116
  244. package/dist/platform/adapters/index.d.ts +24 -3
  245. package/dist/platform/adapters/index.js +89 -11
  246. package/dist/platform/adapters/project-conduits.d.ts +9 -0
  247. package/dist/platform/adapters/project-conduits.js +42 -0
  248. package/dist/platform/adapters/slack-project-conduits.d.ts +1 -9
  249. package/dist/platform/adapters/slack-project-conduits.js +6 -40
  250. package/dist/platform/adapters/slack.d.ts +9 -2
  251. package/dist/platform/adapters/slack.js +83 -39
  252. package/dist/platform/adapters/tui/index.d.ts +9 -0
  253. package/dist/platform/adapters/tui/index.js +10 -0
  254. package/dist/platform/adapters/tui/ports.d.ts +20 -0
  255. package/dist/platform/adapters/tui/ports.js +4 -0
  256. package/dist/platform/adapters/tui/tui-conduit-state.d.ts +10 -0
  257. package/dist/platform/adapters/tui/tui-conduit-state.js +17 -0
  258. package/dist/platform/adapters/tui/tui-connection.d.ts +30 -0
  259. package/dist/platform/adapters/tui/tui-connection.js +53 -0
  260. package/dist/platform/adapters/tui/tui-gateway.d.ts +120 -0
  261. package/dist/platform/adapters/tui/tui-gateway.js +919 -0
  262. package/dist/platform/adapters/tui/tui-notifications.d.ts +12 -0
  263. package/dist/platform/adapters/tui/tui-notifications.js +60 -0
  264. package/dist/platform/adapters/tui/tui-output-stream.d.ts +36 -0
  265. package/dist/platform/adapters/tui/tui-output-stream.js +99 -0
  266. package/dist/platform/adapters/tui/tui-transcript.d.ts +8 -0
  267. package/dist/platform/adapters/tui/tui-transcript.js +56 -0
  268. package/dist/platform/index.d.ts +1 -0
  269. package/dist/platform/index.js +2 -1
  270. package/dist/platform/interactive-builder.js +3 -2
  271. package/dist/platform/output-stream.d.ts +5 -0
  272. package/dist/platform/testing.d.ts +7 -11
  273. package/dist/platform/testing.js +18 -15
  274. package/dist/platform/tool-trace.js +15 -5
  275. package/dist/platform/tui/protocol.d.ts +355 -0
  276. package/dist/platform/tui/protocol.js +199 -0
  277. package/dist/platform/types.d.ts +12 -3
  278. package/dist/store/execution-repo.d.ts +6 -1
  279. package/dist/store/execution-repo.js +13 -3
  280. package/dist/store/hook-sync.d.ts +18 -0
  281. package/dist/store/hook-sync.js +92 -0
  282. package/dist/store/outbound-queue.js +2 -2
  283. package/dist/store/profile-repo.js +3 -2
  284. package/dist/store/schedule-repo.d.ts +1 -8
  285. package/dist/store/session-registry-repo.d.ts +9 -1
  286. package/dist/store/session-registry-repo.js +19 -3
  287. package/dist/store/session-repo.d.ts +14 -0
  288. package/dist/store/session-repo.js +23 -0
  289. package/dist/store/thread-repo.d.ts +3 -0
  290. package/dist/store/thread-repo.js +49 -2
  291. package/dist/store/version-migrations.js +95 -0
  292. package/dist/tui/App.d.ts +27 -0
  293. package/dist/tui/App.js +219 -0
  294. package/dist/tui/components/AskUserModal.d.ts +11 -0
  295. package/dist/tui/components/AskUserModal.js +364 -0
  296. package/dist/tui/components/ConfirmModal.d.ts +12 -0
  297. package/dist/tui/components/ConfirmModal.js +31 -0
  298. package/dist/tui/components/Dashboard.d.ts +23 -0
  299. package/dist/tui/components/Dashboard.js +80 -0
  300. package/dist/tui/components/DashboardCostTab.d.ts +7 -0
  301. package/dist/tui/components/DashboardCostTab.js +16 -0
  302. package/dist/tui/components/DashboardExecutionsTab.d.ts +11 -0
  303. package/dist/tui/components/DashboardExecutionsTab.js +94 -0
  304. package/dist/tui/components/DashboardSchedulesTab.d.ts +11 -0
  305. package/dist/tui/components/DashboardSchedulesTab.js +124 -0
  306. package/dist/tui/components/DashboardTasksTab.d.ts +12 -0
  307. package/dist/tui/components/DashboardTasksTab.js +200 -0
  308. package/dist/tui/components/DashboardThreadsTab.d.ts +11 -0
  309. package/dist/tui/components/DashboardThreadsTab.js +81 -0
  310. package/dist/tui/components/Header.d.ts +11 -0
  311. package/dist/tui/components/Header.js +5 -0
  312. package/dist/tui/components/InputBox.d.ts +10 -0
  313. package/dist/tui/components/InputBox.js +19 -0
  314. package/dist/tui/components/MessageRow.d.ts +7 -0
  315. package/dist/tui/components/MessageRow.js +10 -0
  316. package/dist/tui/components/Notifications.d.ts +19 -0
  317. package/dist/tui/components/Notifications.js +72 -0
  318. package/dist/tui/components/PlanFeedbackModal.d.ts +11 -0
  319. package/dist/tui/components/PlanFeedbackModal.js +161 -0
  320. package/dist/tui/components/ProjectSwitcher.d.ts +18 -0
  321. package/dist/tui/components/ProjectSwitcher.js +43 -0
  322. package/dist/tui/components/SessionPicker.d.ts +14 -0
  323. package/dist/tui/components/SessionPicker.js +34 -0
  324. package/dist/tui/components/SidePanel.d.ts +19 -0
  325. package/dist/tui/components/SidePanel.js +8 -0
  326. package/dist/tui/components/StatusLine.d.ts +10 -0
  327. package/dist/tui/components/StatusLine.js +29 -0
  328. package/dist/tui/components/Transcript.d.ts +13 -0
  329. package/dist/tui/components/Transcript.js +56 -0
  330. package/dist/tui/hooks/useDashboardData.d.ts +32 -0
  331. package/dist/tui/hooks/useDashboardData.js +104 -0
  332. package/dist/tui/hooks/useKeybindings.d.ts +19 -0
  333. package/dist/tui/hooks/useKeybindings.js +87 -0
  334. package/dist/tui/hooks/useMutate.d.ts +22 -0
  335. package/dist/tui/hooks/useMutate.js +56 -0
  336. package/dist/tui/hooks/useNotifications.d.ts +28 -0
  337. package/dist/tui/hooks/useNotifications.js +70 -0
  338. package/dist/tui/hooks/useTranscript.d.ts +39 -0
  339. package/dist/tui/hooks/useTranscript.js +265 -0
  340. package/dist/tui/hooks/useWsClient.d.ts +29 -0
  341. package/dist/tui/hooks/useWsClient.js +69 -0
  342. package/dist/tui/index.d.ts +2 -0
  343. package/dist/tui/index.js +210 -0
  344. package/dist/tui/logic.d.ts +16 -0
  345. package/dist/tui/logic.js +49 -0
  346. package/dist/tui/render/markdown.d.ts +10 -0
  347. package/dist/tui/render/markdown.js +38 -0
  348. package/dist/tui/render/rich-blocks.d.ts +11 -0
  349. package/dist/tui/render/rich-blocks.js +24 -0
  350. package/dist/tui/ws-client.d.ts +44 -0
  351. package/dist/tui/ws-client.js +157 -0
  352. package/package.json +11 -3
  353. package/dist/orchestration/channel-queue.d.ts +0 -18
  354. package/dist/orchestration/channel-queue.js +0 -32
@@ -135,6 +135,14 @@ class ClaudeSession {
135
135
  if (this.context?.useCoreMcp) {
136
136
  spawnOptions.mcpConfigPath = CORE_MCP_CONFIG;
137
137
  }
138
+ // Sessions that originate from Slack (channel carries the SlackAdapter `slack:` prefix) load the
139
+ // cortex-slack MCP server so the agent can send files to Slack. buildSpawnArgs suppresses
140
+ // it for thread/core sessions (CORE_MCP_CONFIG) regardless of this flag.
141
+ spawnOptions.loadSlackMcp = this.channel.startsWith('slack:');
142
+ // Sessions that originate from Feishu (channel carries the FeishuAdapter `feishu:` prefix) load the
143
+ // cortex-feishu MCP server so the agent can read/write Feishu documents. buildSpawnArgs suppresses
144
+ // it for thread/core sessions (CORE_MCP_CONFIG) regardless of this flag.
145
+ spawnOptions.loadFeishuMcp = this.channel.startsWith('feishu:');
138
146
  const args = buildSpawnArgs(spawnOptions);
139
147
  log.info(`Spawning persistent process: ${this.sessionId.substring(0, 8)} ${this.needsResume ? '(resume)' : '(new)'}`);
140
148
  this.proc = spawn('claude', args, { cwd: DATA_DIR, env, stdio: ['pipe', 'pipe', 'pipe'] });
@@ -493,6 +501,9 @@ function getOrCreateTuiSession(config, sessionIdEffective) {
493
501
  pluginDirs: opts.pluginDirs,
494
502
  outputStyle: opts.outputStyle,
495
503
  extraOption: opts.extraOption ?? null,
504
+ // Mirror the print-mode rule (spawnProcess): template thread sessions load only the core MCP
505
+ // server. buildSpawnArgs reads this CORE_MCP_CONFIG marker to also suppress the TUI bridge.
506
+ mcpConfigPath: opts.context?.useCoreMcp ? CORE_MCP_CONFIG : undefined,
496
507
  callbackSource: opts.callbackSource,
497
508
  scheduleTaskId: opts.scheduleTaskId,
498
509
  anthropicBaseUrl: opts.anthropicBaseUrl,
@@ -2,11 +2,38 @@ import { HOOKS_DIR } from '../../core/utils.js';
2
2
  export declare const MAX_TIMEOUT = 30000000;
3
3
  export declare const IDLE_SESSION_TIMEOUT: number;
4
4
  export declare const TURN_IDLE_TIMEOUT: number;
5
+ /** DR-0012: fast-fail window for a fresh turn. The jsonl file appears only after the first submit,
6
+ * so the tail no longer blocks at spawn; this bounds the "claude never started" case to seconds
7
+ * instead of the 60-min TURN_IDLE_TIMEOUT. Cleared on the first jsonl event of the turn. */
8
+ export declare const JSONL_FIRST_EVENT_TIMEOUT: number;
9
+ /** DR-0012: delay between pasting the prompt and sending Enter. Claude Code's Ink TUI uses
10
+ * bracketed paste; an Enter sent immediately after paste-buffer is swallowed and the prompt is
11
+ * never submitted. A short settle delay lets the paste register before the submit keystroke.
12
+ * Verified empirically (2.1.160): 0ms → never submits; ~300ms+ → reliable. */
13
+ export declare const PASTE_SUBMIT_DELAY_MS = 400;
14
+ /** DR-0012: after spawning the tmux session, Claude's Ink TUI takes several seconds to boot and
15
+ * start accepting input. Pasting before then drops the prompt into a not-yet-ready terminal, so
16
+ * the submit Enter does nothing and no jsonl is ever written (the turn then dies on the
17
+ * first-event watchdog). We poll capture-pane for a readiness marker before the first paste.
18
+ * Verified empirically (2.1.162): paste at ~0s → never submits; paste after the prompt UI is
19
+ * drawn (~5-6s) → reliable. */
20
+ export declare const PANE_READY_TIMEOUT: number;
21
+ export declare const PANE_READY_POLL_MS = 250;
22
+ /** Markers that prove the Claude TUI prompt is interactive and ready to receive a paste. The
23
+ * bottom status line ("bypass permissions on …") and the shortcuts hint only render once the
24
+ * Ink app has finished its initial layout. */
25
+ export declare const PANE_READY_MARKER: RegExp;
5
26
  export declare const LOGS_DIR: string;
6
27
  export declare const MCP_CONFIG: string;
7
28
  export declare const CORE_MCP_CONFIG: string;
8
29
  /** DR-0012: TUI-mode-exclusive MCP set (only cortex-tui-bridge server, no core/ext leakage). */
9
30
  export declare const TUI_MCP_CONFIG: string;
31
+ /** Slack platform-specific tools (cortex-slack server). Layered on top of the full config via the variadic
32
+ * `--mcp-config` only for sessions that originate from Slack (channel carries the `slack:` prefix). */
33
+ export declare const SLACK_MCP_CONFIG: string;
34
+ /** Feishu document tools (cortex-feishu server). Layered on top of the full config via the variadic
35
+ * `--mcp-config` only for sessions that originate from Feishu (channel carries the `feishu:` prefix). */
36
+ export declare const FEISHU_MCP_CONFIG: string;
10
37
  export declare const PROJECT_SETTINGS: string;
11
38
  export declare const DEFAULT_PLAN_DIRS: string[];
12
39
  export declare const DEFAULT_TOOLS = "Agent,AskUserQuestion,Bash,Edit,EnterPlanMode,ExitPlanMode,Glob,Grep,Read,Skill,TaskStop,TodoWrite,WebFetch,WebSearch,Write";
@@ -18,6 +45,9 @@ export declare const DEFAULT_TOOLS = "Agent,AskUserQuestion,Bash,Edit,EnterPlanM
18
45
  * Tool name prefix `mcp__<server-name>__<tool-name>` is Claude's canonical form for MCP tools.
19
46
  */
20
47
  export declare const TUI_TOOLS: string;
48
+ /** Native interaction tools that must be stripped in TUI mode (all sessions, including threads).
49
+ * These tools require stdin/stdout interaction that TUI mode cannot provide. */
50
+ export declare const TUI_STRIP_TOOLS: Set<string>;
21
51
  /** DR-0012: tmux session name prefix for TUI-mode Claude processes. */
22
52
  export declare const TUI_TMUX_NAME_PREFIX = "cortex-claude-";
23
53
  /** DR-0012: Base directory where Claude writes per-session jsonl transcripts (per-cwd encoded). */
@@ -9,12 +9,39 @@ import { DATA_DIR, CONFIG_DIR, HOOKS_DIR } from '../../core/utils.js';
9
9
  export const MAX_TIMEOUT = 30_000_000;
10
10
  export const IDLE_SESSION_TIMEOUT = 65 * 60 * 1000;
11
11
  export const TURN_IDLE_TIMEOUT = 60 * 60 * 1000;
12
+ /** DR-0012: fast-fail window for a fresh turn. The jsonl file appears only after the first submit,
13
+ * so the tail no longer blocks at spawn; this bounds the "claude never started" case to seconds
14
+ * instead of the 60-min TURN_IDLE_TIMEOUT. Cleared on the first jsonl event of the turn. */
15
+ export const JSONL_FIRST_EVENT_TIMEOUT = 30 * 1000;
16
+ /** DR-0012: delay between pasting the prompt and sending Enter. Claude Code's Ink TUI uses
17
+ * bracketed paste; an Enter sent immediately after paste-buffer is swallowed and the prompt is
18
+ * never submitted. A short settle delay lets the paste register before the submit keystroke.
19
+ * Verified empirically (2.1.160): 0ms → never submits; ~300ms+ → reliable. */
20
+ export const PASTE_SUBMIT_DELAY_MS = 400;
21
+ /** DR-0012: after spawning the tmux session, Claude's Ink TUI takes several seconds to boot and
22
+ * start accepting input. Pasting before then drops the prompt into a not-yet-ready terminal, so
23
+ * the submit Enter does nothing and no jsonl is ever written (the turn then dies on the
24
+ * first-event watchdog). We poll capture-pane for a readiness marker before the first paste.
25
+ * Verified empirically (2.1.162): paste at ~0s → never submits; paste after the prompt UI is
26
+ * drawn (~5-6s) → reliable. */
27
+ export const PANE_READY_TIMEOUT = 25 * 1000;
28
+ export const PANE_READY_POLL_MS = 250;
29
+ /** Markers that prove the Claude TUI prompt is interactive and ready to receive a paste. The
30
+ * bottom status line ("bypass permissions on …") and the shortcuts hint only render once the
31
+ * Ink app has finished its initial layout. */
32
+ export const PANE_READY_MARKER = /bypass permissions on|\? for shortcuts/;
12
33
  export const LOGS_DIR = path.join(DATA_DIR, 'logs', 'sessions');
13
34
  mkdirSync(LOGS_DIR, { recursive: true });
14
35
  export const MCP_CONFIG = path.join(CONFIG_DIR, 'mcp-config.json');
15
36
  export const CORE_MCP_CONFIG = path.join(CONFIG_DIR, 'mcp-config-core.json');
16
37
  /** DR-0012: TUI-mode-exclusive MCP set (only cortex-tui-bridge server, no core/ext leakage). */
17
38
  export const TUI_MCP_CONFIG = path.join(CONFIG_DIR, 'mcp-config-tui.json');
39
+ /** Slack platform-specific tools (cortex-slack server). Layered on top of the full config via the variadic
40
+ * `--mcp-config` only for sessions that originate from Slack (channel carries the `slack:` prefix). */
41
+ export const SLACK_MCP_CONFIG = path.join(CONFIG_DIR, 'mcp-config-slack.json');
42
+ /** Feishu document tools (cortex-feishu server). Layered on top of the full config via the variadic
43
+ * `--mcp-config` only for sessions that originate from Feishu (channel carries the `feishu:` prefix). */
44
+ export const FEISHU_MCP_CONFIG = path.join(CONFIG_DIR, 'mcp-config-feishu.json');
18
45
  // User-customizable Claude settings live under DATA_DIR (init copies the seed from
19
46
  // defaults/.claude/settings.json on first run). The installed package's defaults/.claude/
20
47
  // is read-only and used only as the init source.
@@ -34,6 +61,9 @@ export const TUI_TOOLS = [
34
61
  'mcp__cortex-tui-bridge__cortex_plan_exit',
35
62
  'mcp__cortex-tui-bridge__cortex_ask_user',
36
63
  ].join(',');
64
+ /** Native interaction tools that must be stripped in TUI mode (all sessions, including threads).
65
+ * These tools require stdin/stdout interaction that TUI mode cannot provide. */
66
+ export const TUI_STRIP_TOOLS = new Set(['AskUserQuestion', 'EnterPlanMode', 'ExitPlanMode']);
37
67
  /** DR-0012: tmux session name prefix for TUI-mode Claude processes. */
38
68
  export const TUI_TMUX_NAME_PREFIX = 'cortex-claude-';
39
69
  /** DR-0012: Base directory where Claude writes per-session jsonl transcripts (per-cwd encoded). */
@@ -24,7 +24,8 @@ export declare class JsonlEventNormalizer {
24
24
  export interface JsonlTailOptions {
25
25
  /** Read pre-existing content when start() is called. Default false (skip to end-of-file). */
26
26
  fromStart?: boolean;
27
- /** Max time to wait for file to appear before start() rejects, in ms. Default 5000. */
27
+ /** @deprecated No longer used. start() is non-blocking and never rejects on a missing file —
28
+ * the tail polls until the file appears. Kept for backward-compatible construction. */
28
29
  waitForFileMs?: number;
29
30
  /** Poll interval for file size changes, in ms. Default 200. fs.watch is not used because it's
30
31
  * unreliable on some filesystems; polling is universal and the throughput here is low. */
@@ -59,7 +60,6 @@ export declare class JsonlTail extends EventEmitter {
59
60
  on<K extends keyof JsonlTailEvents>(event: K, listener: JsonlTailEvents[K]): this;
60
61
  start(): Promise<void>;
61
62
  stop(): Promise<void>;
62
- private waitForFile;
63
63
  private schedulePoll;
64
64
  private readNewBytes;
65
65
  private drainBuffer;
@@ -6,10 +6,23 @@ 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
- /** Tool names that signal AskUserQuestion semantics (native + TUI-mode MCP replacement). */
9
+ /**
10
+ * Tool names that signal AskUserQuestion semantics worth translating into an ACTIONABLE
11
+ * `ask_user_question` NormalizedEvent (which drives the post-hoc Slack posting machinery:
12
+ * facade.onAskUserQuestion + lifecycle.sendMessages).
13
+ *
14
+ * Only the NATIVE `AskUserQuestion` belongs here. The TUI-mode MCP replacement
15
+ * `mcp__cortex-tui-bridge__cortex_ask_user` is deliberately EXCLUDED: it is self-contained — it
16
+ * posts the Slack card, blocks, and returns the answer inline through its own webhook
17
+ * (tui-ask.ts:82 → /hook/ask-user-question → ask-user.requested → hook-bridge-subscribers). The
18
+ * jsonl normalizer is a passive transcript observer; synthesizing an actionable event for an
19
+ * already-resolved tool double-/triple-posts the same question (the stray `Answer (0/1)` cards,
20
+ * one titled `undefined` because this path drops the header). It still surfaces as a plain
21
+ * `tool_use` event below, so the `cortex_ask_user ×1` tool trace renders normally. This mirrors
22
+ * print mode, where extractAskUserQuestions (event-parser.ts) matches only the native tool too.
23
+ */
10
24
  const ASK_USER_TOOL_NAMES = new Set([
11
25
  'AskUserQuestion',
12
- 'mcp__cortex-tui-bridge__cortex_ask_user',
13
26
  ]);
14
27
  /** Tool names that signal "enter plan mode" semantics (native + TUI-mode MCP replacement). */
15
28
  const PLAN_ENTER_TOOL_NAMES = new Set([
@@ -240,17 +253,22 @@ export class JsonlTail extends EventEmitter {
240
253
  return super.on(event, listener);
241
254
  }
242
255
  async start() {
243
- const existedBeforeStart = fs.existsSync(this.filePath);
244
- await this.waitForFile();
245
256
  if (this.stopped)
246
257
  return;
247
- // Read from start when: explicitly requested OR file did not exist before start()
248
- // (in the latter case, everything in it is "new" from our perspective).
258
+ // Non-blocking on a missing file. Current Claude Code creates the session transcript only
259
+ // AFTER the first message is submitted, so the tail must attach BEFORE the file exists
260
+ // (DR-0012 soak finding). We therefore do NOT wait for / require the file here — we begin
261
+ // polling immediately and readNewBytes() picks it up the moment Claude creates it.
262
+ const existedBeforeStart = fs.existsSync(this.filePath);
263
+ // Read from start when: explicitly requested OR file does not exist yet (in the latter case,
264
+ // everything that gets written is "new" from our perspective — i.e. the whole first turn).
249
265
  if (this.fromStart || !existedBeforeStart) {
250
266
  this.offset = 0;
251
- this.readNewBytes();
267
+ this.readNewBytes(); // no-op while the file is absent — statSync is guarded
252
268
  }
253
269
  else {
270
+ // Resume: the file already holds prior turns; seek to EOF so we don't reprocess history
271
+ // (which would re-emit a stale turn_duration and prematurely complete the new turn).
254
272
  try {
255
273
  const st = fs.statSync(this.filePath);
256
274
  this.offset = st.size;
@@ -268,19 +286,6 @@ export class JsonlTail extends EventEmitter {
268
286
  this.pollTimer = null;
269
287
  }
270
288
  }
271
- async waitForFile() {
272
- const deadline = Date.now() + this.waitForFileMs;
273
- while (Date.now() < deadline) {
274
- if (this.stopped)
275
- return;
276
- if (fs.existsSync(this.filePath))
277
- return;
278
- await new Promise(r => setTimeout(r, 50));
279
- }
280
- if (fs.existsSync(this.filePath))
281
- return;
282
- throw new Error(`jsonl-tail: file did not appear within ${this.waitForFileMs}ms: ${this.filePath}`);
283
- }
284
289
  schedulePoll() {
285
290
  if (this.stopped)
286
291
  return;
@@ -15,6 +15,14 @@ export interface ClaudeSpawnOptions {
15
15
  sessionId: string;
16
16
  /** Override MCP config path. Thread sessions pass CORE_MCP_CONFIG (remote_* only). */
17
17
  mcpConfigPath?: string;
18
+ /** 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/core
20
+ * sessions (CORE_MCP_CONFIG), which must stay on the core server set only. */
21
+ loadSlackMcp?: boolean;
22
+ /** Layer the cortex-feishu MCP server on top of the base config. Set by the adapter for sessions
23
+ * that originate from Feishu (channel carries the `feishu:` prefix). Ignored for thread/core
24
+ * sessions (CORE_MCP_CONFIG), which must stay on the core server set only. */
25
+ loadFeishuMcp?: boolean;
18
26
  /** Extra CLI options from profile (e.g. {"--thinking": "xhigh"}). */
19
27
  extraOption?: Record<string, string> | null;
20
28
  /** DR-0012: select adapter mode. Default 'print' preserves -p stream-json behavior. */
@@ -34,5 +42,8 @@ export interface CortexAgentContext {
34
42
  executionId?: string | null;
35
43
  /** When true, load only core MCP server (remote_* tools). */
36
44
  useCoreMcp?: boolean;
45
+ /** Recursion depth of the owning thread, surfaced as CORTEX_THREAD_DEPTH so the thread_start
46
+ * MCP tool can forward it and the daemon-side depth guard can cap nested thread spawning. */
47
+ threadDepth?: number | null;
37
48
  }
38
49
  export declare function buildClaudeEnv(channel: string, sessionId: string, callbackSource?: string | null, scheduleTaskId?: string | null, anthropicBaseUrl?: string, extraEnv?: Record<string, string>, context?: CortexAgentContext): NodeJS.ProcessEnv;
@@ -2,22 +2,49 @@
2
2
  // output: buildSpawnArgs + buildClaudeEnv pure functions
3
3
  // pos: Construct Claude CLI argv and process environment variables
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
- import { DEFAULT_TOOLS, MCP_CONFIG, TUI_MCP_CONFIG, TUI_TOOLS } from './defaults.js';
5
+ import { DEFAULT_TOOLS, MCP_CONFIG, CORE_MCP_CONFIG, TUI_MCP_CONFIG, SLACK_MCP_CONFIG, FEISHU_MCP_CONFIG, TUI_TOOLS, TUI_STRIP_TOOLS } from './defaults.js';
6
+ // CORE_MCP_CONFIG is the thread/core marker: callers set mcpConfigPath to it for template thread
7
+ // sessions (remote_* only). buildSpawnArgs uses identity against it to decide whether to layer the
8
+ // TUI bridge server on top.
6
9
  import { buildHooksSettings } from './hooks-builder.js';
7
10
  export function buildSpawnArgs(options) {
8
11
  const mode = options.mode ?? 'print';
9
- // Per-mode defaults: TUI mode loads the TUI MCP set + tool whitelist that excludes
10
- // AskUserQuestion / EnterPlanMode / ExitPlanMode (replaced by cortex-tui-bridge MCP tools).
11
- const mcpConfigDefault = mode === 'tui' ? TUI_MCP_CONFIG : MCP_CONFIG;
12
- const toolsDefault = mode === 'tui' ? TUI_TOOLS : DEFAULT_TOOLS;
13
- const mcpConfig = options.mcpConfigPath || mcpConfigDefault;
12
+ // MCP server selection is identical to print mode: the base config follows the caller's
13
+ // mcpConfigPath (CORE_MCP_CONFIG for thread/core sessions) and otherwise the full MCP_CONFIG
14
+ // (cortex-core + cortex-ext). TUI mode additionally layers the cortex-tui-bridge server on top
15
+ // (its cortex_plan_*/cortex_ask_user tools replace the native EnterPlanMode/ExitPlanMode/
16
+ // AskUserQuestion), EXCEPT for thread/core sessions — threads run no plan/ask interactions and
17
+ // must stay on the core server set only. `--mcp-config` is variadic, so we pass both files.
18
+ const isCoreOnly = options.mcpConfigPath === CORE_MCP_CONFIG;
19
+ const baseMcpConfig = options.mcpConfigPath || MCP_CONFIG;
20
+ const mcpConfigs = [baseMcpConfig];
21
+ if (mode === 'tui' && !isCoreOnly)
22
+ mcpConfigs.push(TUI_MCP_CONFIG);
23
+ // Slack-originated sessions additionally layer the cortex-slack server (slack_send_file tool).
24
+ // Suppressed for thread/core sessions, which run no file-sending work and stay on the core set only.
25
+ if (options.loadSlackMcp && !isCoreOnly)
26
+ mcpConfigs.push(SLACK_MCP_CONFIG);
27
+ // Feishu-originated sessions additionally layer the cortex-feishu server (Feishu document tools).
28
+ // Suppressed for thread/core sessions, which run no document work and stay on the core set only.
29
+ if (options.loadFeishuMcp && !isCoreOnly)
30
+ mcpConfigs.push(FEISHU_MCP_CONFIG);
31
+ // TUI tool whitelist swaps the three native interaction tools for their MCP bridge equivalents;
32
+ // thread/core TUI sessions have no bridge server, so they fall back to the standard tool set.
33
+ const toolsDefault = (mode === 'tui' && !isCoreOnly) ? TUI_TOOLS : DEFAULT_TOOLS;
14
34
  const args = [];
15
35
  if (mode === 'print') {
16
36
  // Stream-json over stdio for -p mode (current behavior — preserved exactly for regression)
17
37
  args.push('-p', '--input-format', 'stream-json', '--output-format', 'stream-json', '--verbose');
18
38
  }
39
+ // TUI mode: strip native interaction tools (AskUserQuestion / EnterPlanMode / ExitPlanMode)
40
+ // from ALL sessions (user messages and threads alike). These tools require stdin/stdout
41
+ // interaction that tmux-pasted TUI sessions cannot provide.
42
+ let effectiveTools = options.tools || toolsDefault;
43
+ if (mode === 'tui' && options.tools) {
44
+ effectiveTools = options.tools.split(',').filter(t => !TUI_STRIP_TOOLS.has(t)).join(',');
45
+ }
19
46
  // Both modes: permission bypass + MCP + tools
20
- args.push('--dangerously-skip-permissions', '--permission-mode', 'bypassPermissions', '--mcp-config', mcpConfig, '--tools', options.tools || toolsDefault);
47
+ args.push('--dangerously-skip-permissions', '--permission-mode', 'bypassPermissions', '--mcp-config', ...mcpConfigs, '--tools', effectiveTools);
21
48
  if (options.systemPrompt)
22
49
  args.push('--system-prompt', options.systemPrompt);
23
50
  if (options.appendSystemPrompt)
@@ -52,7 +79,19 @@ export function buildClaudeEnv(channel, sessionId, callbackSource, scheduleTaskI
52
79
  delete env[key];
53
80
  }
54
81
  env.CLAUDE_CODE_DISABLE_AUTO_MEMORY = '1';
82
+ // Startup-latency trims — kill network round-trips and first-run/IDE checks that Claude performs
83
+ // at launch but Cortex never benefits from (headless tmux/-p, plugin-loaded skills, no IDE). These
84
+ // only remove non-essential startup work; none change model behavior or disable experiment gates
85
+ // (we deliberately do NOT set DISABLE_TELEMETRY / NONESSENTIAL_TRAFFIC, which would). Must be set
86
+ // AFTER the CLAUDE_CODE* strip loop above. See code.claude.com/docs/en/env-vars.
87
+ env.DISABLE_AUTOUPDATER = '1'; // no npm registry update check at launch
88
+ env.CLAUDE_CODE_DISABLE_OFFICIAL_MARKETPLACE_AUTOINSTALL = '1'; // skip first-run marketplace install
89
+ env.CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL = '1'; // no IDE extension auto-install
90
+ env.CLAUDE_CODE_AUTO_CONNECT_IDE = 'false'; // no IDE auto-connect probe
91
+ env.CLAUDE_CODE_DISABLE_POLICY_SKILLS = '1'; // skip system managed-skills dir (Cortex uses pluginDirs)
92
+ env.CLAUDE_CODE_DISABLE_TERMINAL_TITLE = '1'; // no title updates; also skips the title-gen Haiku call in -p
55
93
  env.SLACK_CHANNEL = channel;
94
+ env.FEISHU_CHANNEL = channel;
56
95
  env.SLACK_BOT_TOKEN = process.env.SLACK_BOT_TOKEN;
57
96
  env.CORTEX_SESSION_ID = sessionId;
58
97
  if (callbackSource)
@@ -65,8 +104,11 @@ export function buildClaudeEnv(channel, sessionId, callbackSource, scheduleTaskI
65
104
  delete env.CORTEX_PROFILE;
66
105
  delete env.CORTEX_PROJECT;
67
106
  delete env.CORTEX_SESSION_NAME;
107
+ delete env.CORTEX_THREAD_DEPTH;
68
108
  if (context?.threadId)
69
109
  env.CORTEX_THREAD_ID = context.threadId;
110
+ if (context?.threadDepth != null)
111
+ env.CORTEX_THREAD_DEPTH = String(context.threadDepth);
70
112
  if (context?.profile)
71
113
  env.CORTEX_PROFILE = context.profile;
72
114
  if (context?.project)
@@ -34,6 +34,13 @@ export declare class TmuxControl {
34
34
  /**
35
35
  * Create a detached tmux session running the given command in the given cwd.
36
36
  * Throws on tmux non-zero exit (e.g. duplicate session name).
37
+ *
38
+ * Env + command are NOT placed on the tmux command line. tmux packs the whole new-session
39
+ * invocation (argv + every `-e KEY=VAL`) into a single control-socket imsg with a ~16KB ceiling;
40
+ * the agent-server's full environment (~8KB+) plus claude's long `--append-system-prompt` /
41
+ * `--settings` arguments blow past it ("command too long"). Instead we stage a launcher script
42
+ * that exports the env and `exec`s the command, so the tmux command line stays a few dozen bytes.
43
+ * @see DR-0012 — TUI command-length fix.
37
44
  */
38
45
  newSession(opts: NewSessionOptions): void;
39
46
  /** Kill a tmux session. Idempotent: missing session is not an error (matches tmux's own semantics for our use case). */
@@ -53,6 +60,12 @@ export declare class TmuxControl {
53
60
  * Why a named buffer + -d: tmux has a global anonymous paste buffer; concurrent sessions on the same
54
61
  * tmux server would race. Named buffers + -d (auto-delete after paste) avoid that.
55
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
+ *
56
69
  * @see DR-0012 spike §4 — paste-buffer is more reliable than send-keys -l for special chars.
57
70
  */
58
71
  pasteText(name: string, text: string): void;
@@ -67,3 +80,10 @@ export declare class TmuxControl {
67
80
  */
68
81
  listSessions(prefix?: string): string[];
69
82
  }
83
+ /**
84
+ * Write a self-deleting bash launcher that exports `env` then `exec`s `command`, returning its path.
85
+ * On Linux the open file descriptor keeps the script readable after `rm "$0"`, so bash finishes
86
+ * reading the remaining lines from the still-open inode (verified). The caller runs it via
87
+ * `tmux new-session -- bash <path>`; on a failed spawn the caller unlinks it instead.
88
+ */
89
+ export declare function writeLauncherScript(env: Record<string, string>, command: string[]): string;
@@ -35,24 +35,33 @@ export class TmuxControl {
35
35
  /**
36
36
  * Create a detached tmux session running the given command in the given cwd.
37
37
  * Throws on tmux non-zero exit (e.g. duplicate session name).
38
+ *
39
+ * Env + command are NOT placed on the tmux command line. tmux packs the whole new-session
40
+ * invocation (argv + every `-e KEY=VAL`) into a single control-socket imsg with a ~16KB ceiling;
41
+ * the agent-server's full environment (~8KB+) plus claude's long `--append-system-prompt` /
42
+ * `--settings` arguments blow past it ("command too long"). Instead we stage a launcher script
43
+ * that exports the env and `exec`s the command, so the tmux command line stays a few dozen bytes.
44
+ * @see DR-0012 — TUI command-length fix.
38
45
  */
39
46
  newSession(opts) {
40
47
  const cols = opts.cols ?? 200;
41
48
  const rows = opts.rows ?? 50;
49
+ const launcherPath = writeLauncherScript(opts.env ?? {}, opts.command);
42
50
  const args = [
43
51
  'new-session', '-d', '-s', opts.name,
44
52
  '-c', opts.cwd,
45
53
  '-x', String(cols), '-y', String(rows),
54
+ '--',
55
+ 'bash', launcherPath,
46
56
  ];
47
- if (opts.env) {
48
- for (const [k, v] of Object.entries(opts.env)) {
49
- args.push('-e', `${k}=${v}`);
50
- }
51
- }
52
- args.push('--');
53
- args.push(...opts.command);
54
57
  const r = this.exec(args);
55
58
  if (r.status !== 0) {
59
+ // The launcher normally self-deletes once bash runs it; on a failed spawn bash never runs,
60
+ // so clean it up here to avoid leaking the staged script.
61
+ try {
62
+ fs.unlinkSync(launcherPath);
63
+ }
64
+ catch { /* best effort */ }
56
65
  throw new Error(`tmux new-session failed (status=${r.status}): ${r.stderr.trim() || r.stdout.trim() || '<no stderr>'}`);
57
66
  }
58
67
  }
@@ -80,6 +89,12 @@ export class TmuxControl {
80
89
  * Why a named buffer + -d: tmux has a global anonymous paste buffer; concurrent sessions on the same
81
90
  * tmux server would race. Named buffers + -d (auto-delete after paste) avoid that.
82
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
+ *
83
98
  * @see DR-0012 spike §4 — paste-buffer is more reliable than send-keys -l for special chars.
84
99
  */
85
100
  pasteText(name, text) {
@@ -91,7 +106,7 @@ export class TmuxControl {
91
106
  if (r1.status !== 0) {
92
107
  throw new Error(`tmux load-buffer failed (status=${r1.status}): ${r1.stderr.trim()}`);
93
108
  }
94
- const r2 = this.exec(['paste-buffer', '-d', '-b', bufName, '-t', name]);
109
+ const r2 = this.exec(['paste-buffer', '-p', '-d', '-b', bufName, '-t', name]);
95
110
  if (r2.status !== 0) {
96
111
  throw new Error(`tmux paste-buffer failed (status=${r2.status}): ${r2.stderr.trim()}`);
97
112
  }
@@ -125,3 +140,34 @@ export class TmuxControl {
125
140
  return names.filter(n => n.startsWith(prefix));
126
141
  }
127
142
  }
143
+ // =====================================================================================
144
+ // Launcher script staging (newSession command-length workaround)
145
+ // =====================================================================================
146
+ /** POSIX single-quote escape: wrap in '…' and rewrite embedded ' as '\''. Safe for arbitrary
147
+ * bytes including newlines, backticks, `$`, and quotes (verified against the claude system-prompt
148
+ * payload). */
149
+ function shQuote(s) {
150
+ return `'${s.replace(/'/g, `'\\''`)}'`;
151
+ }
152
+ /** Only export env keys that are valid POSIX shell identifiers. Skips exotic keys such as
153
+ * bash-exported functions (`BASH_FUNC_xxx%%`) whose names would break an `export` statement. */
154
+ const SHELL_IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;
155
+ /**
156
+ * Write a self-deleting bash launcher that exports `env` then `exec`s `command`, returning its path.
157
+ * On Linux the open file descriptor keeps the script readable after `rm "$0"`, so bash finishes
158
+ * reading the remaining lines from the still-open inode (verified). The caller runs it via
159
+ * `tmux new-session -- bash <path>`; on a failed spawn the caller unlinks it instead.
160
+ */
161
+ export function writeLauncherScript(env, command) {
162
+ const id = crypto.randomBytes(6).toString('hex');
163
+ const launcherPath = path.join(os.tmpdir(), `cortex-tmux-launch-${id}.sh`);
164
+ const lines = ['#!/usr/bin/env bash', 'rm -f "$0"'];
165
+ for (const [k, v] of Object.entries(env)) {
166
+ if (!SHELL_IDENT.test(k))
167
+ continue;
168
+ lines.push(`export ${k}=${shQuote(v)}`);
169
+ }
170
+ lines.push(`exec ${command.map(shQuote).join(' ')}`);
171
+ fs.writeFileSync(launcherPath, lines.join('\n') + '\n', { mode: 0o700 });
172
+ return launcherPath;
173
+ }
@@ -153,7 +153,7 @@ function buildMcpBlock(channel, sessionId, callbackSource, routeContextPath, con
153
153
  if (context?.threadId)
154
154
  return coreSection;
155
155
  // Direct sessions: core + ext (everything else)
156
- const extSection = `\n[mcp_servers.cortex-ext]\ncommand = "node"\nargs = ["${escapedPath(extServerPath)}", "--route-context-file", "${escapedPath(routeContextPath)}"]\n\n[mcp_servers.cortex-ext.env]\n${formatEnv({ SLACK_BOT_TOKEN: process.env.SLACK_BOT_TOKEN || '', SLACK_CHANNEL: channel || '' })}\n`;
156
+ const extSection = `\n[mcp_servers.cortex-ext]\ncommand = "node"\nargs = ["${escapedPath(extServerPath)}", "--route-context-file", "${escapedPath(routeContextPath)}"]\n\n[mcp_servers.cortex-ext.env]\n${formatEnv({ SLACK_BOT_TOKEN: process.env.SLACK_BOT_TOKEN || '', SLACK_CHANNEL: channel || '', FEISHU_CHANNEL: channel || '' })}\n`;
157
157
  return coreSection + extSection;
158
158
  }
159
159
  // ============================================================
@@ -51,6 +51,7 @@ export type NormalizedEvent = {
51
51
  type: 'turn_complete';
52
52
  numTurns: number;
53
53
  totalCostUsd: number | null;
54
+ error?: string | null;
54
55
  } | {
55
56
  type: 'error';
56
57
  message: string;
@@ -11,9 +11,10 @@ import { CAPABILITIES_BY_BACKEND } from '../capabilities.js';
11
11
  import { buildSpawnArgs } from './spawn-args.js';
12
12
  import { createLineSplitter, encodeCommand } from './framing.js';
13
13
  import { piRpcLineToNormalized, createPIEventParserState } from './event-parser.js';
14
- import { PI_AGENT_DIR, PI_SESSIONS_DIR, writeProvidersConfig, ensureAuthVisible } from './agent-dir.js';
14
+ import { PI_AGENT_DIR, PI_SESSIONS_DIR, writeProvidersConfig, buildProviderOverrides, ensureAuthVisible } from './agent-dir.js';
15
15
  import { parsePiListModelsOutput } from '../../core/gateway-generator.js';
16
16
  import { buildPrompt } from '../normalize/prompt-builder.js';
17
+ import { fromCanonical } from '../normalize/tool-names.js';
17
18
  const log = createLogger('pi-adapter');
18
19
  function buildPromptText(msg) {
19
20
  return buildPrompt(msg.text, msg.attachments ?? []);
@@ -329,19 +330,28 @@ class PISession {
329
330
  }
330
331
  const t = this.pendingTurn;
331
332
  this.pendingTurn = null;
332
- const result = {
333
- sessionId: this.sessionId,
334
- total_cost_usd: evt.totalCostUsd,
335
- num_turns: evt.numTurns,
336
- rateLimited: t.rateLimited,
337
- rateLimitMessage: null,
338
- planFilePath: t.planFilePath,
339
- enteredPlanMode: false,
340
- exitedPlanMode: t.planFilePath !== null,
341
- askUserQuestions: t.askUserQuestions.length > 0 ? t.askUserQuestions : undefined,
342
- finalOutput: null,
343
- };
344
- t.resolve(result);
333
+ if (evt.error) {
334
+ // Turn-level error (e.g. gateway "400 Unknown mode") — fail the turn so the lifecycle
335
+ // shows ❌ Error and posts the message, matching the Claude adapter's is_error path.
336
+ // Fall through (no continue) so turn_complete is still pushed to this.events and the
337
+ // facade event loop terminates cleanly, exactly like the fatal-error branch below.
338
+ t.reject(new Error(evt.error));
339
+ }
340
+ else {
341
+ const result = {
342
+ sessionId: this.sessionId,
343
+ total_cost_usd: evt.totalCostUsd,
344
+ num_turns: evt.numTurns,
345
+ rateLimited: t.rateLimited,
346
+ rateLimitMessage: null,
347
+ planFilePath: t.planFilePath,
348
+ enteredPlanMode: false,
349
+ exitedPlanMode: t.planFilePath !== null,
350
+ askUserQuestions: t.askUserQuestions.length > 0 ? t.askUserQuestions : undefined,
351
+ finalOutput: null,
352
+ };
353
+ t.resolve(result);
354
+ }
345
355
  }
346
356
  else if (evt.type === 'error' && evt.fatal) {
347
357
  this.flushTextBuffer();
@@ -541,12 +551,17 @@ export class PIAdapter {
541
551
  log.warn(`Failed to mirror PI auth.json: ${err.message}`);
542
552
  }
543
553
  try {
544
- const providers = discoverPIProviders();
545
- if (providers.length > 0) {
546
- writeProvidersConfig(providers.map(name => ({ name })), config.piGatewayBaseUrl);
554
+ // Override set = providers PI reports creds for (discovered) ∪ the provider THIS spawn
555
+ // uses (config.piProvider). The current provider is always routed through the gateway even
556
+ // when discovery doesn't list it (e.g. an anthropic-protocol relay whose key the gateway
557
+ // injects). config.piGatewayPath, when set, decouples the gateway route from the provider name.
558
+ const discovered = discoverPIProviders();
559
+ const overrides = buildProviderOverrides(discovered, config.piProvider ?? null, config.piGatewayPath ?? null);
560
+ if (overrides.length > 0) {
561
+ writeProvidersConfig(overrides, config.piGatewayBaseUrl);
547
562
  }
548
563
  else {
549
- log.warn('pi --list-models returned no providers; PI subprocess may fail to authenticate');
564
+ log.warn('No PI providers to route (empty discovery and no profile provider); PI subprocess may fail to authenticate');
550
565
  }
551
566
  }
552
567
  catch (err) {
@@ -554,8 +569,20 @@ export class PIAdapter {
554
569
  }
555
570
  }
556
571
  const env = { ...process.env, ...(config.env ?? {}), PI_CODING_AGENT_DIR: PI_AGENT_DIR };
557
- if (config.channel)
572
+ if (config.channel) {
558
573
  env.SLACK_CHANNEL = config.channel;
574
+ env.FEISHU_CHANNEL = config.channel;
575
+ }
576
+ // Forward the agent's tool allowlist (Claude-native names) so tool-shims.ts can gate which
577
+ // pseudo-tools it registers — mirroring the Claude backend's `--tools` allowlist. Without this,
578
+ // thread-dispatched agents (whose config excludes AskUserQuestion/EnterPlanMode/ExitPlanMode)
579
+ // would still be handed those interaction tools and deadlock on an approval no human can answer.
580
+ const allowedTools = config.rawTools
581
+ ?? (config.tools && config.tools.length > 0
582
+ ? config.tools.map((t) => fromCanonical('claude', t)).filter((n) => !!n).join(',')
583
+ : undefined);
584
+ if (allowedTools)
585
+ env.CORTEX_PI_ALLOWED_TOOLS = allowedTools;
559
586
  const cwd = config.cwd ?? DATA_DIR;
560
587
  const session = new PISession({
561
588
  sessionKey: config.sessionKey,
@@ -17,6 +17,12 @@ export interface ProviderOverride {
17
17
  * (e.g. deepseek's anthropic-compat endpoint: `/deepseek/anthropic`).
18
18
  */
19
19
  basePath?: string;
20
+ /**
21
+ * Per-spawn PI compat flags to write into this provider's models.json entry.
22
+ * Merged ON TOP of PROVIDER_COMPAT_OVERRIDES (explicit wins). Normally unset —
23
+ * the static table covers the known cases.
24
+ */
25
+ compat?: Record<string, unknown>;
20
26
  }
21
27
  export interface WriteProvidersOpts {
22
28
  /** Override target file path. Defaults to PI_MODELS_PATH. */
@@ -30,6 +36,21 @@ export interface WriteProvidersOpts {
30
36
  * Called by PIAdapter.spawn() — sole writer of this file, no other code path touches it.
31
37
  */
32
38
  export declare function writeProvidersConfig(providers: ProviderOverride[], gatewayUrl: string, opts?: WriteProvidersOpts): void;
39
+ /**
40
+ * Compute the set of PI providers whose baseUrl should be overridden to the gateway for a spawn.
41
+ *
42
+ * Design: "route through gateway" and "PI has credentials" are independent concerns. Discovery
43
+ * (`pi --list-models`) only reports providers the user is authenticated to, but a profile may
44
+ * legitimately route a provider through the gateway even without direct PI credentials (the
45
+ * gateway injects managed keys). So the override set is the union of:
46
+ * - `discovered` — providers PI reports creds for (credential passthrough via auth.json)
47
+ * - `currentProvider` — the provider THIS spawn uses (`--provider`); it MUST be routed, always
48
+ *
49
+ * `gatewayPath`, when set, becomes the current provider's `basePath` (decouples the gateway route
50
+ * from the provider name — e.g. provider "anthropic" landing on "/deepseek-anthropic"). It wins
51
+ * over the default `/<name>` even if the current provider was also discovered.
52
+ */
53
+ export declare function buildProviderOverrides(discovered: string[], currentProvider: string | null, gatewayPath?: string | null): ProviderOverride[];
33
54
  export interface EnsureAuthVisibleOpts {
34
55
  /** Source: where the user's PI auth.json lives. Defaults to ~/.pi/agent/auth.json. */
35
56
  userAuthPath?: string;