@cortex-agent/server 2026.5.25 → 2026.6.15

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 (395) 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 +323 -30
  36. package/dist/core/i18n.d.ts +19 -0
  37. package/dist/core/i18n.js +46 -0
  38. package/dist/core/icons.d.ts +68 -0
  39. package/dist/core/icons.js +67 -0
  40. package/dist/core/locales/en.d.ts +438 -0
  41. package/dist/core/locales/en.js +24 -0
  42. package/dist/core/locales/slices/commands.d.ts +214 -0
  43. package/dist/core/locales/slices/commands.js +462 -0
  44. package/dist/core/locales/slices/init.d.ts +121 -0
  45. package/dist/core/locales/slices/init.js +380 -0
  46. package/dist/core/locales/slices/interactions.d.ts +47 -0
  47. package/dist/core/locales/slices/interactions.js +102 -0
  48. package/dist/core/locales/slices/lang.d.ts +8 -0
  49. package/dist/core/locales/slices/lang.js +18 -0
  50. package/dist/core/locales/slices/scheduling.d.ts +36 -0
  51. package/dist/core/locales/slices/scheduling.js +74 -0
  52. package/dist/core/locales/slices/startup.d.ts +6 -0
  53. package/dist/core/locales/slices/startup.js +14 -0
  54. package/dist/core/locales/slices/status.d.ts +20 -0
  55. package/dist/core/locales/slices/status.js +48 -0
  56. package/dist/core/locales/zh.d.ts +5 -0
  57. package/dist/core/locales/zh.js +23 -0
  58. package/dist/core/profile-generator.d.ts +6 -0
  59. package/dist/core/profile-generator.js +35 -7
  60. package/dist/core/running-executions.d.ts +51 -41
  61. package/dist/core/running-executions.js +120 -73
  62. package/dist/core/singleton-lock.d.ts +23 -0
  63. package/dist/core/singleton-lock.js +53 -0
  64. package/dist/core/status-format.js +4 -2
  65. package/dist/core/task-parser.d.ts +3 -0
  66. package/dist/core/task-parser.js +3 -1
  67. package/dist/core/types/thread-types.d.ts +54 -8
  68. package/dist/core/utils.d.ts +9 -1
  69. package/dist/core/utils.js +9 -1
  70. package/dist/domain/agents/config.d.ts +2 -1
  71. package/dist/domain/agents/config.js +25 -6
  72. package/dist/domain/agents/facade.d.ts +18 -0
  73. package/dist/domain/agents/facade.js +26 -3
  74. package/dist/domain/agents/profile-manager.d.ts +11 -0
  75. package/dist/domain/agents/profile-manager.js +21 -2
  76. package/dist/domain/costs/codex-usage-monitor.js +2 -1
  77. package/dist/domain/costs/rate-limit-throttle.js +14 -2
  78. package/dist/domain/executions/registry.d.ts +24 -0
  79. package/dist/domain/executions/registry.js +38 -0
  80. package/dist/domain/mcp/core-server.js +15 -3
  81. package/dist/domain/mcp/feishu/bitable.d.ts +3 -0
  82. package/dist/domain/mcp/feishu/bitable.js +168 -0
  83. package/dist/domain/mcp/feishu/block-types.d.ts +44 -0
  84. package/dist/domain/mcp/feishu/block-types.js +127 -0
  85. package/dist/domain/mcp/feishu/blocks-to-text.d.ts +19 -0
  86. package/dist/domain/mcp/feishu/blocks-to-text.js +43 -0
  87. package/dist/domain/mcp/feishu/client.d.ts +46 -0
  88. package/dist/domain/mcp/feishu/client.js +87 -0
  89. package/dist/domain/mcp/feishu/docx.d.ts +3 -0
  90. package/dist/domain/mcp/feishu/docx.js +163 -0
  91. package/dist/domain/mcp/feishu/drive.d.ts +23 -0
  92. package/dist/domain/mcp/feishu/drive.js +66 -0
  93. package/dist/domain/mcp/feishu/file.d.ts +14 -0
  94. package/dist/domain/mcp/feishu/file.js +107 -0
  95. package/dist/domain/mcp/feishu/index.d.ts +6 -0
  96. package/dist/domain/mcp/feishu/index.js +61 -0
  97. package/dist/domain/mcp/feishu/markdown-to-blocks.d.ts +40 -0
  98. package/dist/domain/mcp/feishu/markdown-to-blocks.js +191 -0
  99. package/dist/domain/mcp/feishu/sheets.d.ts +3 -0
  100. package/dist/domain/mcp/feishu/sheets.js +119 -0
  101. package/dist/domain/mcp/feishu/types.d.ts +26 -0
  102. package/dist/domain/mcp/feishu/types.js +38 -0
  103. package/dist/domain/mcp/feishu/user-auth.d.ts +140 -0
  104. package/dist/domain/mcp/feishu/user-auth.js +286 -0
  105. package/dist/domain/mcp/feishu/wiki.d.ts +3 -0
  106. package/dist/domain/mcp/feishu/wiki.js +77 -0
  107. package/dist/domain/mcp/feishu-server.d.ts +2 -0
  108. package/dist/domain/mcp/feishu-server.js +33 -0
  109. package/dist/domain/mcp/server.d.ts +0 -1
  110. package/dist/domain/mcp/server.js +6 -25
  111. package/dist/domain/mcp/slack-server.d.ts +3 -0
  112. package/dist/domain/mcp/slack-server.js +46 -0
  113. package/dist/domain/mcp/tools/context.js +1 -1
  114. package/dist/domain/mcp/tools/schedule.d.ts +1 -1
  115. package/dist/domain/mcp/tools/schedule.js +6 -20
  116. package/dist/domain/mcp/tools/slack.js +20 -7
  117. package/dist/domain/mcp/tools/thread-ops.d.ts +2 -0
  118. package/dist/domain/mcp/tools/thread-ops.js +121 -0
  119. package/dist/domain/mcp/tools/time.d.ts +2 -0
  120. package/dist/domain/mcp/tools/time.js +66 -0
  121. package/dist/domain/mcp/tools/tui-ask.js +1 -1
  122. package/dist/domain/mcp/tools/tui-plan.js +2 -2
  123. package/dist/domain/mcp/tui-server.js +1 -0
  124. package/dist/domain/monitor/disk-monitor.js +2 -1
  125. package/dist/domain/monitor/gpu-monitor.js +2 -1
  126. package/dist/domain/remote/client-hot-reload.js +3 -2
  127. package/dist/domain/remote/client-manager.js +8 -6
  128. package/dist/domain/scheduling/job-registry.d.ts +4 -0
  129. package/dist/domain/scheduling/job-registry.js +1 -0
  130. package/dist/domain/scheduling/jobs/_shared.js +2 -1
  131. package/dist/domain/scheduling/jobs/memory-index-regen.js +3 -2
  132. package/dist/domain/scheduling/jobs/scheduled-task.js +9 -23
  133. package/dist/domain/scheduling/jobs/sync-public.js +4 -3
  134. package/dist/domain/scheduling/jobs/target-dispatch.d.ts +1 -8
  135. package/dist/domain/scheduling/jobs/target-dispatch.js +0 -7
  136. package/dist/domain/scheduling/jobs/task-archive.js +3 -2
  137. package/dist/domain/scheduling/jobs/task-dispatch.js +126 -20
  138. package/dist/domain/scheduling/schedule-command.js +45 -43
  139. package/dist/domain/scheduling/scheduler.d.ts +1 -1
  140. package/dist/domain/scheduling/scheduler.js +2 -1
  141. package/dist/domain/sessions/session-hooks.d.ts +2 -2
  142. package/dist/domain/sessions/session-hooks.js +19 -18
  143. package/dist/domain/sessions/session-lifecycle.d.ts +38 -0
  144. package/dist/domain/sessions/session-lifecycle.js +44 -0
  145. package/dist/domain/system/github-release.d.ts +18 -0
  146. package/dist/domain/system/github-release.js +106 -0
  147. package/dist/domain/system/install-cli.d.ts +7 -0
  148. package/dist/domain/system/install-cli.js +106 -0
  149. package/dist/domain/system/preferences.d.ts +12 -0
  150. package/dist/domain/system/preferences.js +36 -0
  151. package/dist/domain/system/server-update-check.js +2 -2
  152. package/dist/domain/tasks/dispatch-utils.d.ts +58 -1
  153. package/dist/domain/tasks/dispatch-utils.js +53 -4
  154. package/dist/domain/tasks/dispatcher.d.ts +11 -2
  155. package/dist/domain/tasks/dispatcher.js +63 -7
  156. package/dist/domain/tasks/lint.js +28 -0
  157. package/dist/domain/tasks/mutator.d.ts +16 -3
  158. package/dist/domain/tasks/mutator.js +41 -12
  159. package/dist/domain/tasks/pending-tracker.js +6 -5
  160. package/dist/domain/tasks/system/task-cli.d.ts +2 -0
  161. package/dist/domain/tasks/system/task-cli.js +37 -6
  162. package/dist/domain/tasks/system/task-lifecycle-edit.js +6 -1
  163. package/dist/domain/tasks/system/task-mutations.d.ts +41 -3
  164. package/dist/domain/tasks/system/task-mutations.js +166 -8
  165. package/dist/domain/threads/contract.d.ts +17 -0
  166. package/dist/domain/threads/contract.js +59 -0
  167. package/dist/domain/threads/hook-runner.js +7 -6
  168. package/dist/domain/threads/index.d.ts +2 -0
  169. package/dist/domain/threads/index.js +3 -1
  170. package/dist/domain/threads/prompt-builder.d.ts +21 -1
  171. package/dist/domain/threads/prompt-builder.js +60 -4
  172. package/dist/domain/threads/runner.d.ts +6 -5
  173. package/dist/domain/threads/runner.js +128 -79
  174. package/dist/domain/threads/state-machine.d.ts +23 -21
  175. package/dist/domain/threads/state-machine.js +113 -54
  176. package/dist/domain/threads/template-loader.js +3 -2
  177. package/dist/domain/threads/tree.d.ts +45 -0
  178. package/dist/domain/threads/tree.js +171 -0
  179. package/dist/domain/tui-session/index.d.ts +2 -0
  180. package/dist/domain/tui-session/index.js +3 -0
  181. package/dist/domain/tui-session/tui-session-service.d.ts +2 -0
  182. package/dist/domain/tui-session/tui-session-service.js +103 -0
  183. package/dist/domain/tui-session/types.d.ts +67 -0
  184. package/dist/domain/tui-session/types.js +4 -0
  185. package/dist/domain/ui-service/index.d.ts +5 -0
  186. package/dist/domain/ui-service/index.js +3 -0
  187. package/dist/domain/ui-service/mutate/executions.d.ts +4 -0
  188. package/dist/domain/ui-service/mutate/executions.js +15 -0
  189. package/dist/domain/ui-service/mutate/schedules.d.ts +10 -0
  190. package/dist/domain/ui-service/mutate/schedules.js +39 -0
  191. package/dist/domain/ui-service/mutate/tasks.d.ts +23 -0
  192. package/dist/domain/ui-service/mutate/tasks.js +59 -0
  193. package/dist/domain/ui-service/mutate/threads.d.ts +4 -0
  194. package/dist/domain/ui-service/mutate/threads.js +21 -0
  195. package/dist/domain/ui-service/query/cost.d.ts +3 -0
  196. package/dist/domain/ui-service/query/cost.js +6 -0
  197. package/dist/domain/ui-service/query/executions.d.ts +2 -0
  198. package/dist/domain/ui-service/query/executions.js +35 -0
  199. package/dist/domain/ui-service/query/projects.d.ts +2 -0
  200. package/dist/domain/ui-service/query/projects.js +30 -0
  201. package/dist/domain/ui-service/query/schedules.d.ts +2 -0
  202. package/dist/domain/ui-service/query/schedules.js +23 -0
  203. package/dist/domain/ui-service/query/sessions.d.ts +2 -0
  204. package/dist/domain/ui-service/query/sessions.js +35 -0
  205. package/dist/domain/ui-service/query/tasks.d.ts +2 -0
  206. package/dist/domain/ui-service/query/tasks.js +30 -0
  207. package/dist/domain/ui-service/query/threads.d.ts +2 -0
  208. package/dist/domain/ui-service/query/threads.js +27 -0
  209. package/dist/domain/ui-service/subscribe.d.ts +5 -0
  210. package/dist/domain/ui-service/subscribe.js +118 -0
  211. package/dist/domain/ui-service/types.d.ts +237 -0
  212. package/dist/domain/ui-service/types.js +5 -0
  213. package/dist/domain/ui-service/ui-service.d.ts +2 -0
  214. package/dist/domain/ui-service/ui-service.js +83 -0
  215. package/dist/entry/app.js +130 -8
  216. package/dist/entry/cli.d.ts +12 -0
  217. package/dist/entry/cli.js +122 -12
  218. package/dist/entry/daemon.js +12 -30
  219. package/dist/entry/feishu-login.d.ts +28 -0
  220. package/dist/entry/feishu-login.js +218 -0
  221. package/dist/entry/init.d.ts +29 -5
  222. package/dist/entry/init.js +323 -233
  223. package/dist/entry/startup-notify.js +6 -3
  224. package/dist/events/event-types.d.ts +14 -0
  225. package/dist/hooks/cortex-md-injector.mjs +47 -31
  226. package/dist/hooks/post-task-hook.mjs +6 -0
  227. package/dist/hooks/task-status-check.mjs +8 -0
  228. package/dist/orchestration/agent-runner.d.ts +2 -1
  229. package/dist/orchestration/agent-runner.js +55 -55
  230. package/dist/orchestration/conduit-queue.d.ts +18 -0
  231. package/dist/orchestration/conduit-queue.js +32 -0
  232. package/dist/orchestration/conversation-runner.d.ts +48 -0
  233. package/dist/orchestration/conversation-runner.js +109 -0
  234. package/dist/orchestration/dispatch-reconciler.js +8 -1
  235. package/dist/orchestration/interactions/ask-user-question.d.ts +1 -1
  236. package/dist/orchestration/interactions/ask-user-question.js +3 -3
  237. package/dist/orchestration/interactions/interaction-handlers.js +55 -23
  238. package/dist/orchestration/interactions/plan-handler.d.ts +2 -2
  239. package/dist/orchestration/interactions/plan-handler.js +4 -3
  240. package/dist/orchestration/interactions/update-prompt-slack.js +11 -10
  241. package/dist/orchestration/interactions/update-prompt.d.ts +6 -0
  242. package/dist/orchestration/interactions/update-prompt.js +155 -0
  243. package/dist/orchestration/lifecycle.d.ts +4 -4
  244. package/dist/orchestration/lifecycle.js +25 -22
  245. package/dist/orchestration/orchestrator.d.ts +1 -1
  246. package/dist/orchestration/routing/commands/cancel.js +45 -52
  247. package/dist/orchestration/routing/commands/channel.js +41 -27
  248. package/dist/orchestration/routing/commands/cost.js +11 -2
  249. package/dist/orchestration/routing/commands/device.js +12 -9
  250. package/dist/orchestration/routing/commands/dispatch.js +11 -10
  251. package/dist/orchestration/routing/commands/index.d.ts +1 -1
  252. package/dist/orchestration/routing/commands/index.js +15 -10
  253. package/dist/orchestration/routing/commands/lang.d.ts +3 -0
  254. package/dist/orchestration/routing/commands/lang.js +31 -0
  255. package/dist/orchestration/routing/commands/mode.js +32 -30
  256. package/dist/orchestration/routing/commands/nvtop.js +15 -13
  257. package/dist/orchestration/routing/commands/orient.js +2 -1
  258. package/dist/orchestration/routing/commands/schedule.js +23 -22
  259. package/dist/orchestration/routing/commands/sendfile.js +9 -7
  260. package/dist/orchestration/routing/commands/session.d.ts +1 -1
  261. package/dist/orchestration/routing/commands/session.js +24 -39
  262. package/dist/orchestration/routing/commands/status.js +78 -71
  263. package/dist/orchestration/routing/commands/tail.js +7 -5
  264. package/dist/orchestration/routing/commands/task.js +25 -23
  265. package/dist/orchestration/routing/commands/thread-handlers.js +55 -44
  266. package/dist/orchestration/routing/edit-handler.js +8 -7
  267. package/dist/orchestration/routing/hook-bridge-subscribers.js +17 -1
  268. package/dist/orchestration/routing/message-router.d.ts +1 -1
  269. package/dist/orchestration/routing/message-router.js +9 -9
  270. package/dist/orchestration/routing/webhook.js +233 -2
  271. package/dist/orchestration/status-helpers.d.ts +5 -1
  272. package/dist/orchestration/status-helpers.js +13 -11
  273. package/dist/orchestration/thread-callback.d.ts +67 -0
  274. package/dist/orchestration/thread-callback.js +465 -0
  275. package/dist/orchestration/thread-executor.d.ts +22 -1
  276. package/dist/orchestration/thread-executor.js +85 -36
  277. package/dist/platform/adapter.d.ts +6 -2
  278. package/dist/platform/adapters/composite-adapter.d.ts +89 -0
  279. package/dist/platform/adapters/composite-adapter.js +318 -0
  280. package/dist/platform/adapters/feishu-output-stream.d.ts +26 -4
  281. package/dist/platform/adapters/feishu-output-stream.js +274 -36
  282. package/dist/platform/adapters/feishu.d.ts +50 -5
  283. package/dist/platform/adapters/feishu.js +370 -116
  284. package/dist/platform/adapters/index.d.ts +24 -3
  285. package/dist/platform/adapters/index.js +89 -11
  286. package/dist/platform/adapters/project-conduits.d.ts +9 -0
  287. package/dist/platform/adapters/project-conduits.js +42 -0
  288. package/dist/platform/adapters/slack-project-conduits.d.ts +1 -9
  289. package/dist/platform/adapters/slack-project-conduits.js +6 -40
  290. package/dist/platform/adapters/slack.d.ts +9 -2
  291. package/dist/platform/adapters/slack.js +83 -39
  292. package/dist/platform/adapters/tui/index.d.ts +9 -0
  293. package/dist/platform/adapters/tui/index.js +10 -0
  294. package/dist/platform/adapters/tui/ports.d.ts +20 -0
  295. package/dist/platform/adapters/tui/ports.js +4 -0
  296. package/dist/platform/adapters/tui/tui-conduit-state.d.ts +10 -0
  297. package/dist/platform/adapters/tui/tui-conduit-state.js +17 -0
  298. package/dist/platform/adapters/tui/tui-connection.d.ts +30 -0
  299. package/dist/platform/adapters/tui/tui-connection.js +53 -0
  300. package/dist/platform/adapters/tui/tui-gateway.d.ts +120 -0
  301. package/dist/platform/adapters/tui/tui-gateway.js +919 -0
  302. package/dist/platform/adapters/tui/tui-notifications.d.ts +12 -0
  303. package/dist/platform/adapters/tui/tui-notifications.js +60 -0
  304. package/dist/platform/adapters/tui/tui-output-stream.d.ts +36 -0
  305. package/dist/platform/adapters/tui/tui-output-stream.js +99 -0
  306. package/dist/platform/adapters/tui/tui-transcript.d.ts +8 -0
  307. package/dist/platform/adapters/tui/tui-transcript.js +56 -0
  308. package/dist/platform/index.d.ts +1 -0
  309. package/dist/platform/index.js +2 -1
  310. package/dist/platform/interactive-builder.js +21 -19
  311. package/dist/platform/output-stream.d.ts +5 -0
  312. package/dist/platform/testing.d.ts +7 -11
  313. package/dist/platform/testing.js +18 -15
  314. package/dist/platform/tool-trace.js +15 -5
  315. package/dist/platform/tui/protocol.d.ts +355 -0
  316. package/dist/platform/tui/protocol.js +199 -0
  317. package/dist/platform/types.d.ts +12 -3
  318. package/dist/store/execution-repo.d.ts +6 -1
  319. package/dist/store/execution-repo.js +13 -3
  320. package/dist/store/hook-sync.d.ts +18 -0
  321. package/dist/store/hook-sync.js +92 -0
  322. package/dist/store/outbound-queue.js +2 -2
  323. package/dist/store/profile-repo.js +3 -2
  324. package/dist/store/schedule-repo.d.ts +1 -8
  325. package/dist/store/session-registry-repo.d.ts +9 -1
  326. package/dist/store/session-registry-repo.js +19 -3
  327. package/dist/store/session-repo.d.ts +14 -0
  328. package/dist/store/session-repo.js +23 -0
  329. package/dist/store/thread-repo.d.ts +3 -0
  330. package/dist/store/thread-repo.js +49 -2
  331. package/dist/store/version-migrations.d.ts +7 -0
  332. package/dist/store/version-migrations.js +183 -0
  333. package/dist/tui/App.d.ts +27 -0
  334. package/dist/tui/App.js +219 -0
  335. package/dist/tui/components/AskUserModal.d.ts +11 -0
  336. package/dist/tui/components/AskUserModal.js +364 -0
  337. package/dist/tui/components/ConfirmModal.d.ts +12 -0
  338. package/dist/tui/components/ConfirmModal.js +31 -0
  339. package/dist/tui/components/Dashboard.d.ts +23 -0
  340. package/dist/tui/components/Dashboard.js +80 -0
  341. package/dist/tui/components/DashboardCostTab.d.ts +7 -0
  342. package/dist/tui/components/DashboardCostTab.js +16 -0
  343. package/dist/tui/components/DashboardExecutionsTab.d.ts +11 -0
  344. package/dist/tui/components/DashboardExecutionsTab.js +94 -0
  345. package/dist/tui/components/DashboardSchedulesTab.d.ts +11 -0
  346. package/dist/tui/components/DashboardSchedulesTab.js +124 -0
  347. package/dist/tui/components/DashboardTasksTab.d.ts +12 -0
  348. package/dist/tui/components/DashboardTasksTab.js +200 -0
  349. package/dist/tui/components/DashboardThreadsTab.d.ts +11 -0
  350. package/dist/tui/components/DashboardThreadsTab.js +81 -0
  351. package/dist/tui/components/Header.d.ts +11 -0
  352. package/dist/tui/components/Header.js +5 -0
  353. package/dist/tui/components/InputBox.d.ts +10 -0
  354. package/dist/tui/components/InputBox.js +19 -0
  355. package/dist/tui/components/MessageRow.d.ts +7 -0
  356. package/dist/tui/components/MessageRow.js +10 -0
  357. package/dist/tui/components/Notifications.d.ts +19 -0
  358. package/dist/tui/components/Notifications.js +72 -0
  359. package/dist/tui/components/PlanFeedbackModal.d.ts +11 -0
  360. package/dist/tui/components/PlanFeedbackModal.js +161 -0
  361. package/dist/tui/components/ProjectSwitcher.d.ts +18 -0
  362. package/dist/tui/components/ProjectSwitcher.js +43 -0
  363. package/dist/tui/components/SessionPicker.d.ts +14 -0
  364. package/dist/tui/components/SessionPicker.js +34 -0
  365. package/dist/tui/components/SidePanel.d.ts +19 -0
  366. package/dist/tui/components/SidePanel.js +8 -0
  367. package/dist/tui/components/StatusLine.d.ts +10 -0
  368. package/dist/tui/components/StatusLine.js +29 -0
  369. package/dist/tui/components/Transcript.d.ts +13 -0
  370. package/dist/tui/components/Transcript.js +56 -0
  371. package/dist/tui/hooks/useDashboardData.d.ts +32 -0
  372. package/dist/tui/hooks/useDashboardData.js +104 -0
  373. package/dist/tui/hooks/useKeybindings.d.ts +19 -0
  374. package/dist/tui/hooks/useKeybindings.js +87 -0
  375. package/dist/tui/hooks/useMutate.d.ts +22 -0
  376. package/dist/tui/hooks/useMutate.js +56 -0
  377. package/dist/tui/hooks/useNotifications.d.ts +28 -0
  378. package/dist/tui/hooks/useNotifications.js +70 -0
  379. package/dist/tui/hooks/useTranscript.d.ts +39 -0
  380. package/dist/tui/hooks/useTranscript.js +265 -0
  381. package/dist/tui/hooks/useWsClient.d.ts +29 -0
  382. package/dist/tui/hooks/useWsClient.js +69 -0
  383. package/dist/tui/index.d.ts +2 -0
  384. package/dist/tui/index.js +210 -0
  385. package/dist/tui/logic.d.ts +16 -0
  386. package/dist/tui/logic.js +49 -0
  387. package/dist/tui/render/markdown.d.ts +10 -0
  388. package/dist/tui/render/markdown.js +38 -0
  389. package/dist/tui/render/rich-blocks.d.ts +11 -0
  390. package/dist/tui/render/rich-blocks.js +24 -0
  391. package/dist/tui/ws-client.d.ts +44 -0
  392. package/dist/tui/ws-client.js +157 -0
  393. package/package.json +11 -3
  394. package/dist/orchestration/channel-queue.d.ts +0 -18
  395. package/dist/orchestration/channel-queue.js +0 -32
@@ -10,6 +10,24 @@ import { GATEWAY_URL } from '../costs/gateway-manager.js';
10
10
  import { createLogger } from '../../core/log.js';
11
11
  import { loadCortexRules } from '../memory/rules-loader.js';
12
12
  const log = createLogger('facade');
13
+ // --- PI gateway routing ---
14
+ /**
15
+ * Build the gateway sub-path for a PI provider's models.json override, following the gateway's URL
16
+ * convention `/m/<mode>/<endpoint>`. The `mode` selects the gateway route (gateway.yaml owns the
17
+ * upstream + keys); the `provider` is both the PI `--provider` and the gateway endpoint segment.
18
+ *
19
+ * `provider` is required for pi profiles (validated at load time — no default, no fallback). Returns
20
+ * undefined when `mode` is absent — the PI adapter then falls back to the default `/<provider>` path
21
+ * (direct per-provider routing, no `/m/` mode indirection).
22
+ *
23
+ * Keeping this derivation in code (not in the profile) means profiles only carry the logical
24
+ * `mode` name; no gateway path string leaks into profiles.json.
25
+ */
26
+ export function buildPiGatewaySubPath(mode, provider) {
27
+ if (!mode)
28
+ return undefined;
29
+ return `/m/${mode}/${provider}`;
30
+ }
13
31
  // --- Adapter execution ---
14
32
  function buildSpawnConfig(options, config, anthropicBaseUrl) {
15
33
  // Pack the Cortex execution context only if at least one field is set, so adapters can
@@ -21,8 +39,9 @@ function buildSpawnConfig(options, config, anthropicBaseUrl) {
21
39
  sessionName: options.sessionName ?? null,
22
40
  executionId: options.executionId ?? null,
23
41
  useCoreMcp: options.useCoreMcp ?? undefined,
42
+ threadDepth: options.threadDepth ?? null,
24
43
  };
25
- const hasContext = !!(ctx.threadId || ctx.profile || ctx.project || ctx.sessionName || ctx.executionId || ctx.useCoreMcp);
44
+ const hasContext = !!(ctx.threadId || ctx.profile || ctx.project || ctx.sessionName || ctx.executionId || ctx.useCoreMcp || ctx.threadDepth != null);
26
45
  // Load global rules (no paths frontmatter) and inject as appendSystemPrompt.
27
46
  // Scoped rules (with paths) are handled by the Read/Grep PostToolUse hook.
28
47
  const rules = loadCortexRules();
@@ -50,7 +69,11 @@ function buildSpawnConfig(options, config, anthropicBaseUrl) {
50
69
  // PI-specific routing: provider name (= profile mode) + gateway base URL. PI adapter writes
51
70
  // a multi-provider models.json (writeProvidersConfig) so every PI provider lands on the
52
71
  // gateway. Claude / codex adapters ignore these fields.
53
- piProvider: config.backend === 'pi' && config.mode ? config.mode : undefined,
72
+ // PI routing: `provider` is the --provider (protocol; required for pi, validated at load — no
73
+ // default). The gateway sub-path `/m/<mode>/<provider>` is derived from the profile's logical
74
+ // `mode` (gateway.yaml owns the route).
75
+ piProvider: config.backend === 'pi' && config.provider ? config.provider : undefined,
76
+ piGatewayPath: config.backend === 'pi' && config.provider ? buildPiGatewaySubPath(config.mode, config.provider) : undefined,
54
77
  piGatewayBaseUrl: config.backend === 'pi' ? GATEWAY_URL : undefined,
55
78
  cortexContext: hasContext ? ctx : undefined,
56
79
  appendSystemPrompt,
@@ -154,7 +177,7 @@ export function runAgentOnce(message, options, config) {
154
177
  export function runAgent(message, options = {}) {
155
178
  const profileConfig = resolveProfileConfig(options.profileName);
156
179
  const configs = [
157
- { model: profileConfig.model, backend: profileConfig.backend, mode: profileConfig.mode, extraEnv: profileConfig.extraEnv, extraOption: profileConfig.extraOption, claudeBackend: profileConfig.claudeBackend },
180
+ { model: profileConfig.model, backend: profileConfig.backend, mode: profileConfig.mode, provider: profileConfig.provider, extraEnv: profileConfig.extraEnv, extraOption: profileConfig.extraOption, claudeBackend: profileConfig.claudeBackend },
158
181
  ...(profileConfig.fallback || []),
159
182
  ];
160
183
  // Single config — no fallback wrapper needed
@@ -1,7 +1,15 @@
1
1
  export interface ProfileEntry {
2
2
  model: string;
3
3
  backend?: string;
4
+ /** Gateway route mode — a logical name resolved by gateway.yaml (e.g. "plan", "api", "anthropic").
5
+ * Used for ALL backends to build the gateway URL `/m/<mode>/<endpoint>`; gateway.yaml owns the
6
+ * upstream URL + keys for each mode. (For claude the endpoint is "anthropic"; for pi it is the
7
+ * `provider` below.) */
4
8
  mode?: string;
9
+ /** PI `--provider` (protocol family, e.g. "anthropic", "openai-codex"). Only meaningful for
10
+ * backend='pi'; defaults to "anthropic" when omitted. Decoupled from `mode`: `mode` selects the
11
+ * gateway route, `provider` selects the PI request protocol + the gateway endpoint segment. */
12
+ provider?: string;
5
13
  extraEnv?: Record<string, string>;
6
14
  extraOption?: Record<string, string>;
7
15
  /** DR-0012: opt into TUI-mode Claude (interactive tmux + jsonl tail). Default 'print' for backward
@@ -21,6 +29,8 @@ export interface ResolvedProfileConfig {
21
29
  model: string;
22
30
  backend: string;
23
31
  mode: string | null;
32
+ /** PI `--provider` (protocol). null → adapter defaults to "anthropic". Ignored for non-pi backends. */
33
+ provider: string | null;
24
34
  extraEnv: Record<string, string>;
25
35
  extraOption: Record<string, string>;
26
36
  /** DR-0012: resolved claude adapter mode. 'print' (default, uses -p + stream-json) or 'tui'
@@ -30,6 +40,7 @@ export interface ResolvedProfileConfig {
30
40
  model: string;
31
41
  backend: string;
32
42
  mode: string | null;
43
+ provider: string | null;
33
44
  extraEnv: Record<string, string>;
34
45
  extraOption: Record<string, string>;
35
46
  claudeBackend: 'print' | 'tui';
@@ -6,6 +6,8 @@
6
6
  import { profileRepo } from '../../store/profile-repo.js';
7
7
  const PROFILE_NAME_RE = /^[a-zA-Z0-9_-]+$/;
8
8
  const MODE_NAME_RE = /^[a-zA-Z0-9_-]+$/;
9
+ // provider shares mode's safe-name shape (alphanumeric, dash, underscore).
10
+ const PROVIDER_NAME_RE = /^[a-zA-Z0-9_-]+$/;
9
11
  const ENV_KEY_RE = /^[A-Z_][A-Z0-9_]*$/;
10
12
  const VALID_BACKENDS = new Set(['claude', 'codex', 'pi']);
11
13
  function loadProfilesFile() {
@@ -18,7 +20,7 @@ function loadProfilesFile() {
18
20
  throw new Error(`Failed to load profiles.json: ${error.message}`);
19
21
  }
20
22
  }
21
- function validateProfileEntry(profile, label) {
23
+ function validateProfileEntry(profile, label, inheritedBackend = 'claude') {
22
24
  const p = profile;
23
25
  if (!p || typeof p !== 'object' || Array.isArray(p)) {
24
26
  throw new Error(`${label} must be an object`);
@@ -29,11 +31,23 @@ function validateProfileEntry(profile, label) {
29
31
  if (p.backend !== undefined && !VALID_BACKENDS.has(p.backend)) {
30
32
  throw new Error(`${label} has invalid backend: ${p.backend}`);
31
33
  }
34
+ // Effective backend resolves to the explicit value, else the inherited one (primary → fallback).
35
+ const effectiveBackend = typeof p.backend === 'string' ? p.backend : inheritedBackend;
36
+ // PI requires an explicit provider — no default, no fallback (the PI `--provider` / gateway
37
+ // endpoint group must be stated outright, never silently assumed).
38
+ if (effectiveBackend === 'pi' && p.provider === undefined) {
39
+ throw new Error(`${label} uses backend 'pi' and must declare an explicit provider (no default)`);
40
+ }
32
41
  if (p.mode !== undefined) {
33
42
  if (typeof p.mode !== 'string' || !MODE_NAME_RE.test(p.mode)) {
34
43
  throw new Error(`${label} has invalid mode: ${p.mode}`);
35
44
  }
36
45
  }
46
+ if (p.provider !== undefined) {
47
+ if (typeof p.provider !== 'string' || !PROVIDER_NAME_RE.test(p.provider)) {
48
+ throw new Error(`${label} has invalid provider: ${String(p.provider)}`);
49
+ }
50
+ }
37
51
  if (p.extraEnv !== undefined) {
38
52
  if (!p.extraEnv || typeof p.extraEnv !== 'object' || Array.isArray(p.extraEnv)) {
39
53
  throw new Error(`${label} extraEnv must be a plain object`);
@@ -96,12 +110,13 @@ function validateProfilesFile(data) {
96
110
  }
97
111
  validateProfileEntry(profile, `profile "${name}"`);
98
112
  const pe = profile;
113
+ const primaryBackend = typeof pe.backend === 'string' ? pe.backend : 'claude';
99
114
  if (pe.fallback !== undefined) {
100
115
  if (!Array.isArray(pe.fallback)) {
101
116
  throw new Error(`profile "${name}" fallback must be an array`);
102
117
  }
103
118
  pe.fallback.forEach((fb, i) => {
104
- validateProfileEntry(fb, `profile "${name}" fallback[${i}]`);
119
+ validateProfileEntry(fb, `profile "${name}" fallback[${i}]`, primaryBackend);
105
120
  });
106
121
  }
107
122
  }
@@ -143,6 +158,7 @@ function resolveProfileConfig(name = null) {
143
158
  model: profile.model,
144
159
  backend: profile.backend || 'claude',
145
160
  mode: profile.mode || null,
161
+ provider: profile.provider || null,
146
162
  extraEnv: { ...(profile.extraEnv || {}) },
147
163
  extraOption: { ...(profile.extraOption || {}) },
148
164
  claudeBackend: resolveClaudeBackend(profile),
@@ -151,6 +167,9 @@ function resolveProfileConfig(name = null) {
151
167
  model: fb.model,
152
168
  backend: fb.backend || primary.backend,
153
169
  mode: fb.mode || primary.mode,
170
+ // provider does NOT inherit from primary — pi entries must each declare it explicitly (enforced
171
+ // by validation), and non-pi entries leave it null.
172
+ provider: fb.provider || null,
154
173
  extraEnv: { ...(fb.extraEnv || {}) },
155
174
  extraOption: { ...(fb.extraOption || {}) },
156
175
  claudeBackend: fb.claudeBackend !== undefined ? resolveClaudeBackend(fb) : primary.claudeBackend,
@@ -3,6 +3,7 @@
3
3
  // pos: Codex usage monitoring module, alerts via PlatformAdapter when usage is below threshold
4
4
  // >>> If I am updated, update my header comment and CORTEX.md <<<
5
5
  import { createLogger } from '../../core/log.js';
6
+ import { Icons } from '../../core/icons.js';
6
7
  const log = createLogger('codex-usage');
7
8
  const rawThreshold = Number(process.env.CODEX_LOW_USAGE_THRESHOLD_PERCENT || 10);
8
9
  const THRESHOLD_PERCENT = Number.isFinite(rawThreshold)
@@ -61,7 +62,7 @@ async function maybeNotifyCodexLowUsage({ adapter, result }) {
61
62
  return `• ${label} ${e.scopeName}: remaining ${remaining} (used ${used}), reset ${formatResetAt(e.resetsAt)}`;
62
63
  });
63
64
  const logHint = result?.codexRawLogPath ? `\nlog: \`${result.codexRawLogPath}\`` : '';
64
- const text = [`:warning: Codex usage low (threshold: ${THRESHOLD_PERCENT}%)`, ...lines].join('\n') + logHint;
65
+ const text = [`${Icons.warning} Codex usage low (threshold: ${THRESHOLD_PERCENT}%)`, ...lines].join('\n') + logHint;
65
66
  try {
66
67
  await adapter.postMessage({ type: 'system-notice' }, { text });
67
68
  }
@@ -3,6 +3,7 @@
3
3
  // pos: Pure state tracker — no scheduler coupling. Mode-level rate limit tracking.
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
5
  import { createLogger } from '../../core/log.js';
6
+ import { Icons } from '../../core/icons.js';
6
7
  const log = createLogger('rate-limit-throttle');
7
8
  const UTILIZATION_THRESHOLD = 0.90;
8
9
  const RESUME_BUFFER_MS = 5_000;
@@ -27,13 +28,23 @@ function formatResetTime(epochSec) {
27
28
  month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', hour12: false,
28
29
  });
29
30
  }
31
+ function formatRemaining(epochSec) {
32
+ const totalSec = Math.max(0, Math.round(epochSec - Date.now() / 1000));
33
+ const h = Math.floor(totalSec / 3600);
34
+ const m = Math.floor((totalSec % 3600) / 60);
35
+ if (h > 0)
36
+ return `${h}h ${m}m`;
37
+ if (m > 0)
38
+ return `${m}m`;
39
+ return `${totalSec}s`;
40
+ }
30
41
  // --- Timer ---
31
42
  function clearThrottle() {
32
43
  _isThrottled = false;
33
44
  _resetsAt = null;
34
45
  _rateLimitedModes.clear();
35
46
  _resumeTimer = null;
36
- sendDM(':white_check_mark: Rate limit throttle cleared.');
47
+ sendDM(`${Icons.ok} Rate limit throttle cleared.`);
37
48
  _persistence?.save(null).catch(e => {
38
49
  log.error(`Failed to persist cleared throttle: ${e.message}`);
39
50
  });
@@ -100,8 +111,9 @@ async function handleRateLimitEvent(info, mode) {
100
111
  scheduleResumeTimer();
101
112
  await _persistence.save({ resetsAt: _resetsAt, activatedAt: Date.now(), modes: [..._rateLimitedModes] });
102
113
  const resetStr = formatResetTime(_resetsAt);
114
+ const remainingStr = formatRemaining(_resetsAt);
103
115
  const modeNote = mode ? ` (mode: ${mode})` : '';
104
- sendDM(`:warning: Rate limit throttle activated — utilization ${(info.utilization * 100).toFixed(0)}%${modeNote}.\nAuto-resume at ${resetStr}.`);
116
+ sendDM(`${Icons.warning} Rate limit throttle activated — utilization ${(info.utilization * 100).toFixed(0)}%${modeNote}.\nAuto-resume at ${resetStr} (in ${remainingStr}).`);
105
117
  }
106
118
  function isThrottled() {
107
119
  return _isThrottled;
@@ -1,8 +1,10 @@
1
1
  import { executionRepo, TERMINAL_STATUSES } from '../../store/execution-repo.js';
2
+ import type { AgentResult } from '../../core/types/agent-types.js';
2
3
  export type { ExecutionRecord, DispatchInfo } from '../../store/execution-repo.js';
3
4
  export { TERMINAL_STATUSES };
4
5
  export declare function getExecution(id: string): import("../../store/execution-repo.js").ExecutionRecord;
5
6
  export declare function getExecutionByTaskId(taskId: string | null | undefined): import("../../store/execution-repo.js").ExecutionRecord;
7
+ export declare function getAll(): import("../../store/execution-repo.js").ExecutionRecord[];
6
8
  export declare function getRunningExecutions(): import("../../store/execution-repo.js").ExecutionRecord[];
7
9
  export declare function findRunningDispatchMatch(opts: Parameters<typeof executionRepo.findRunningDispatchMatch>[0]): import("../../store/execution-repo.js").ExecutionRecord;
8
10
  export declare function startLocalExecution(opts: Parameters<typeof executionRepo.startLocalExecution>[0]): import("../../store/execution-repo.js").ExecutionRecord;
@@ -14,6 +16,28 @@ export declare function failExecution(id: string, metrics?: Parameters<typeof ex
14
16
  export declare function failExecutionByTaskId(taskId: string, metrics?: Parameters<typeof executionRepo.failExecutionByTaskId>[1]): import("../../store/execution-repo.js").ExecutionRecord;
15
17
  export declare function cancelExecution(id: string, metrics?: Parameters<typeof executionRepo.cancelExecution>[1]): import("../../store/execution-repo.js").ExecutionRecord;
16
18
  export declare function cancelExecutionByTaskId(taskId: string, metrics?: Parameters<typeof executionRepo.cancelExecutionByTaskId>[1]): import("../../store/execution-repo.js").ExecutionRecord;
19
+ /**
20
+ * Close an execution across BOTH ledgers in one call: finalize the persistent record
21
+ * (idempotent — terminal status is guarded in execution-repo) and tear down the in-memory
22
+ * live registry while publishing the matching agent.* lifecycle event.
23
+ *
24
+ * This is the single teardown every execution path should funnel through so the persistent
25
+ * status, the live registry, and the bus events never drift apart. In particular it gives
26
+ * thread steps their agent.completed/failed events, which the old event-less remove() skipped.
27
+ *
28
+ * Does NOT touch the busy-tracker — trackPendingTask(±1) is per-enqueue (a thread spans many
29
+ * steps under one +1), so it stays managed by the caller.
30
+ */
31
+ export declare function teardownExecution({ executionId, status, result, error, durationS, costUsd }: {
32
+ executionId: string | null;
33
+ status: 'completed' | 'failed' | 'cancelled';
34
+ result?: AgentResult | null;
35
+ error?: {
36
+ message?: string;
37
+ } | null;
38
+ durationS: number;
39
+ costUsd?: number;
40
+ }): any;
17
41
  export declare function markMissingRunningExecutionsStale(keepRunning?: Parameters<typeof executionRepo.markMissingRunningExecutionsStale>[0]): Promise<string[]>;
18
42
  export declare function reconcileStaleDispatches(opts: Parameters<typeof executionRepo.reconcileStaleDispatches>[0]): Promise<number>;
19
43
  /** @deprecated ExecutionRepo uses in-memory Map; cache clearing is a no-op. */
@@ -8,6 +8,7 @@ import { executionRepo, TERMINAL_STATUSES } from '../../store/execution-repo.js'
8
8
  import { PROJECTS_DIR } from '../../core/utils.js';
9
9
  import { readLock, releaseLock } from '../tasks/system/task-lock.js';
10
10
  import { createLogger } from '../../core/log.js';
11
+ import { runningExecutions } from '../../core/running-executions.js';
11
12
  export { TERMINAL_STATUSES };
12
13
  const lockLog = createLogger('execution-lock-release');
13
14
  /** Release any task locks still owned by `executionId` after its agent finished.
@@ -52,6 +53,9 @@ export function getExecution(id) {
52
53
  export function getExecutionByTaskId(taskId) {
53
54
  return executionRepo.getExecutionByTaskId(taskId);
54
55
  }
56
+ export function getAll() {
57
+ return executionRepo.getAll();
58
+ }
55
59
  export function getRunningExecutions() {
56
60
  return executionRepo.getRunningExecutions();
57
61
  }
@@ -104,6 +108,40 @@ export function cancelExecutionByTaskId(taskId, metrics) {
104
108
  return null;
105
109
  return cancelExecution(record.id, metrics);
106
110
  }
111
+ /**
112
+ * Close an execution across BOTH ledgers in one call: finalize the persistent record
113
+ * (idempotent — terminal status is guarded in execution-repo) and tear down the in-memory
114
+ * live registry while publishing the matching agent.* lifecycle event.
115
+ *
116
+ * This is the single teardown every execution path should funnel through so the persistent
117
+ * status, the live registry, and the bus events never drift apart. In particular it gives
118
+ * thread steps their agent.completed/failed events, which the old event-less remove() skipped.
119
+ *
120
+ * Does NOT touch the busy-tracker — trackPendingTask(±1) is per-enqueue (a thread spans many
121
+ * steps under one +1), so it stays managed by the caller.
122
+ */
123
+ export function teardownExecution({ executionId, status, result, error, durationS, costUsd }) {
124
+ if (!executionId)
125
+ return null;
126
+ let rec;
127
+ if (status === 'completed') {
128
+ rec = completeExecution(executionId, {
129
+ costUsd: result?.total_cost_usd, numTurns: result?.num_turns, durationS, finalOutput: result?.finalOutput || null,
130
+ });
131
+ runningExecutions.complete(executionId, costUsd ?? result?.total_cost_usd ?? 0);
132
+ }
133
+ else if (status === 'cancelled') {
134
+ rec = cancelExecution(executionId, { durationS });
135
+ // The kill already happened on the cancel path; supersede() publishes agent.superseded
136
+ // and removes the entry (a second kill() is harmless).
137
+ runningExecutions.supersede(executionId, 'cancelled');
138
+ }
139
+ else {
140
+ rec = failExecution(executionId, { durationS, error: error?.message || null });
141
+ runningExecutions.fail(executionId, error?.message ?? 'error');
142
+ }
143
+ return rec;
144
+ }
107
145
  // --- Async operations ---
108
146
  export async function markMissingRunningExecutionsStale(keepRunning) {
109
147
  const staled = await executionRepo.markMissingRunningExecutionsStale(keepRunning);
@@ -1,10 +1,13 @@
1
- // input: MCP SDK, task-ops tool module
2
- // output: MCP stdio service, exposing remote_* tools only
3
- // pos: Core MCP server — thread agents load only this one (no Slack/cost/schedule tools)
1
+ // input: MCP SDK, task-ops + time + thread-ops tool modules
2
+ // output: MCP stdio service, exposing remote_* tools, current_time, and thread_* tools
3
+ // pos: Core MCP server — thread agents load only this one (no Slack/cost/schedule tools).
4
+ // thread_* tools let any agent drive the Thread system via the daemon webhook.
4
5
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
6
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
6
7
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
7
8
  import { registerTaskOpsTools } from './tools/task-ops.js';
9
+ import { registerTimeTools } from './tools/time.js';
10
+ import { registerThreadTools } from './tools/thread-ops.js';
8
11
  import { isMainModule } from '../../core/utils.js';
9
12
  import { createLogger } from '../../core/log.js';
10
13
  import { CORTEX_VERSION } from '../../core/version.js';
@@ -12,6 +15,8 @@ const log = createLogger('mcp-core');
12
15
  // --- McpServer + tool registration ---
13
16
  const server = new McpServer({ name: 'cortex-core', version: CORTEX_VERSION });
14
17
  registerTaskOpsTools(server);
18
+ registerTimeTools(server);
19
+ registerThreadTools(server);
15
20
  // --- Exported tool name list (for verification) ---
16
21
  export const TOOL_NAMES = [
17
22
  'remote_bash',
@@ -20,6 +25,13 @@ export const TOOL_NAMES = [
20
25
  'remote_edit',
21
26
  'remote_glob',
22
27
  'remote_grep',
28
+ 'current_time',
29
+ 'thread_start',
30
+ 'thread_status',
31
+ 'thread_result',
32
+ 'thread_list',
33
+ 'thread_list_templates',
34
+ 'thread_cancel',
23
35
  ];
24
36
  // --- Start (called by barrel when run as standalone) ---
25
37
  export async function startServer() {
@@ -0,0 +1,3 @@
1
+ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ import { type FeishuToolDeps } from './types.js';
3
+ export declare function registerBitableTools(server: McpServer, deps: FeishuToolDeps): void;
@@ -0,0 +1,168 @@
1
+ // input: MCP SDK, zod, types (guard/ok/unwrap), lark client
2
+ // output: registerBitableTools — feishu_bitable_* tools (多维表格 app/table/field/record CRUD)
3
+ // pos: Feishu 多维表格 (bitable) structured-data authoring & querying for agents
4
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
+ import { z } from 'zod';
6
+ import { guard, ok, unwrap } from './types.js';
7
+ import { resolveDriveUrl, setLinkShare } from './drive.js';
8
+ function bitableHost() {
9
+ return process.env.FEISHU_DOMAIN === 'lark' ? 'larksuite.com' : 'feishu.cn';
10
+ }
11
+ /** A bitable app's URL (token is the app_token / base id). */
12
+ function bitableUrl(appToken) {
13
+ return `https://${bitableHost()}/base/${appToken}`;
14
+ }
15
+ export function registerBitableTools(server, deps) {
16
+ server.tool('feishu_bitable_create_app', 'Create a new Feishu bitable (多维表格) app. Returns app_token + url. By default link-shared to the tenant (anyone in the org with the link can edit) so a human can open it. Then use feishu_bitable_create_table to add tables.', {
17
+ name: z.string().optional().describe('App (base) name'),
18
+ folder_token: z.string().optional().describe('Drive folder token to create the base in (root of the app space if omitted)'),
19
+ share: z.enum(['tenant_edit', 'tenant_view', 'none']).optional().describe('Link-share level (default tenant_edit). none = keep private to the app.'),
20
+ }, async ({ name, folder_token, share }) => guard(deps.client, async (client) => {
21
+ const res = await client.bitable.v1.app.create({ data: { name, folder_token } });
22
+ const data = unwrap(res);
23
+ const token = data.app?.app_token ?? '';
24
+ const level = share ?? 'tenant_edit';
25
+ let shared = false;
26
+ if (level !== 'none') {
27
+ try {
28
+ shared = await setLinkShare(client, token, 'bitable', level);
29
+ }
30
+ catch { /* best-effort */ }
31
+ }
32
+ const url = data.app?.url ?? (await resolveDriveUrl(client, token, 'bitable')) ?? bitableUrl(token);
33
+ return ok({ app_token: token, name: data.app?.name ?? name, url, shared });
34
+ }));
35
+ server.tool('feishu_bitable_list_tables', 'List the tables in a bitable app. Returns table_id + name for each. Use a table_id with the record/field tools.', {
36
+ app_token: z.string().describe('The bitable app_token'),
37
+ page_token: z.string().optional().describe('Pagination token from a previous call'),
38
+ page_size: z.number().int().min(1).max(100).optional().describe('Page size (default 100)'),
39
+ }, async ({ app_token, page_token, page_size }) => guard(deps.client, async (client) => {
40
+ const res = await client.bitable.v1.appTable.list({
41
+ path: { app_token },
42
+ params: { page_size: page_size ?? 100, page_token },
43
+ });
44
+ const data = unwrap(res);
45
+ return ok({ app_token, tables: data.items ?? [], page_token: data.page_token, has_more: data.has_more ?? false });
46
+ }));
47
+ server.tool('feishu_bitable_create_table', 'Create a table in a bitable app. Optionally seed fields (each {field_name, type}). Returns the new table_id.', {
48
+ app_token: z.string().describe('The bitable app_token'),
49
+ name: z.string().describe('Table name'),
50
+ default_view_name: z.string().optional().describe('Name for the default grid view'),
51
+ fields: z.array(z.any()).optional().describe('Initial field descriptors [{field_name, type, property?}]'),
52
+ }, async ({ app_token, name, default_view_name, fields }) => guard(deps.client, async (client) => {
53
+ // Feishu rejects the body (1254001 WrongRequestBody) if default_view_name is sent without
54
+ // fields. Build the table object with only the keys that are valid for the given input:
55
+ // include fields when provided, and only attach default_view_name alongside fields.
56
+ const table = { name };
57
+ const hasFields = Array.isArray(fields) && fields.length > 0;
58
+ if (hasFields) {
59
+ table.fields = fields;
60
+ if (default_view_name)
61
+ table.default_view_name = default_view_name;
62
+ }
63
+ const res = await client.bitable.v1.appTable.create({
64
+ path: { app_token },
65
+ data: { table },
66
+ });
67
+ const data = unwrap(res);
68
+ return ok({ app_token, table_id: data.table_id, default_view_id: data.default_view_id });
69
+ }));
70
+ server.tool('feishu_bitable_delete_table', 'Delete a table from a bitable app. Irreversible — the table and all its records are removed.', {
71
+ app_token: z.string().describe('The bitable app_token'),
72
+ table_id: z.string().describe('The table to delete'),
73
+ }, async ({ app_token, table_id }) => guard(deps.client, async (client) => {
74
+ const res = await client.bitable.v1.appTable.delete({ path: { app_token, table_id } });
75
+ unwrap(res);
76
+ return ok({ app_token, table_id, deleted: true });
77
+ }));
78
+ server.tool('feishu_bitable_list_fields', 'List the fields (columns) of a bitable table. Returns field_id, field_name and type. Call before create/update records to learn the schema.', {
79
+ app_token: z.string().describe('The bitable app_token'),
80
+ table_id: z.string().describe('The table_id'),
81
+ page_token: z.string().optional().describe('Pagination token from a previous call'),
82
+ page_size: z.number().int().min(1).max(100).optional().describe('Page size (default 100)'),
83
+ }, async ({ app_token, table_id, page_token, page_size }) => guard(deps.client, async (client) => {
84
+ const res = await client.bitable.v1.appTableField.list({
85
+ path: { app_token, table_id },
86
+ params: { page_size: page_size ?? 100, page_token },
87
+ });
88
+ const data = unwrap(res);
89
+ return ok({ app_token, table_id, fields: data.items ?? [], page_token: data.page_token, has_more: data.has_more ?? false });
90
+ }));
91
+ server.tool('feishu_bitable_create_field', 'Add a field (column) to a bitable table. `type` is the Feishu field type code (1=text, 2=number, 3=single-select, 4=multi-select, 5=datetime, 7=checkbox, 11=user, …).', {
92
+ app_token: z.string().describe('The bitable app_token'),
93
+ table_id: z.string().describe('The table_id'),
94
+ field_name: z.string().describe('Field (column) name'),
95
+ type: z.number().int().describe('Feishu field type code'),
96
+ property: z.any().optional().describe('Type-specific property object (e.g. select options)'),
97
+ }, async ({ app_token, table_id, field_name, type, property }) => guard(deps.client, async (client) => {
98
+ const res = await client.bitable.v1.appTableField.create({
99
+ path: { app_token, table_id },
100
+ data: { field_name, type, property },
101
+ });
102
+ const data = unwrap(res);
103
+ return ok({ app_token, table_id, field: data.field ?? null });
104
+ }));
105
+ server.tool('feishu_bitable_list_records', 'Query records (rows) from a bitable table. Supports optional `filter` (conditions + conjunction) and `sort`. Returns records with record_id + fields.', {
106
+ app_token: z.string().describe('The bitable app_token'),
107
+ table_id: z.string().describe('The table_id'),
108
+ filter: z.any().optional().describe('Filter: { conjunction: "and"|"or", conditions: [{ field_name, operator, value }] }'),
109
+ sort: z.array(z.any()).optional().describe('Sort: [{ field_name, desc }]'),
110
+ field_names: z.array(z.string()).optional().describe('Restrict returned fields by name'),
111
+ page_token: z.string().optional().describe('Pagination token from a previous call'),
112
+ page_size: z.number().int().min(1).max(500).optional().describe('Page size (default 100, max 500)'),
113
+ }, async ({ app_token, table_id, filter, sort, field_names, page_token, page_size }) => guard(deps.client, async (client) => {
114
+ const res = await client.bitable.v1.appTableRecord.search({
115
+ path: { app_token, table_id },
116
+ params: { page_size: page_size ?? 100, page_token },
117
+ data: { filter, sort, field_names },
118
+ });
119
+ const data = unwrap(res);
120
+ return ok({ app_token, table_id, records: data.items ?? [], page_token: data.page_token, has_more: data.has_more ?? false });
121
+ }));
122
+ server.tool('feishu_bitable_create_records', 'Create one or more records (rows) in a bitable table. `records` is an array of { fields: { <field_name>: <value> } }. Returns the created records with record_ids.', {
123
+ app_token: z.string().describe('The bitable app_token'),
124
+ table_id: z.string().describe('The table_id'),
125
+ records: z.array(z.any()).describe('Records to create: [{ fields: { name: value, … } }]'),
126
+ }, async ({ app_token, table_id, records }) => guard(deps.client, async (client) => {
127
+ const res = await client.bitable.v1.appTableRecord.batchCreate({
128
+ path: { app_token, table_id },
129
+ data: { records },
130
+ });
131
+ const data = unwrap(res);
132
+ return ok({ app_token, table_id, records: data.records ?? [] });
133
+ }));
134
+ server.tool('feishu_bitable_update_records', 'Update one or more existing records. `records` is an array of { record_id, fields: { <field_name>: <value> } }. Locate record_ids with feishu_bitable_list_records.', {
135
+ app_token: z.string().describe('The bitable app_token'),
136
+ table_id: z.string().describe('The table_id'),
137
+ records: z.array(z.any()).describe('Records to update: [{ record_id, fields: { name: value, … } }]'),
138
+ }, async ({ app_token, table_id, records }) => guard(deps.client, async (client) => {
139
+ const res = await client.bitable.v1.appTableRecord.batchUpdate({
140
+ path: { app_token, table_id },
141
+ data: { records },
142
+ });
143
+ const data = unwrap(res);
144
+ return ok({ app_token, table_id, records: data.records ?? [] });
145
+ }));
146
+ server.tool('feishu_bitable_delete_records', 'Delete records by id. `record_ids` is an array of record_id strings.', {
147
+ app_token: z.string().describe('The bitable app_token'),
148
+ table_id: z.string().describe('The table_id'),
149
+ record_ids: z.array(z.string()).describe('Record ids to delete'),
150
+ }, async ({ app_token, table_id, record_ids }) => guard(deps.client, async (client) => {
151
+ const res = await client.bitable.v1.appTableRecord.batchDelete({
152
+ path: { app_token, table_id },
153
+ data: { records: record_ids },
154
+ });
155
+ const data = unwrap(res);
156
+ return ok({ app_token, table_id, deleted: data.records ?? record_ids });
157
+ }));
158
+ server.tool('feishu_bitable_delete_app', 'Delete (trash) an ENTIRE bitable app — the whole base and every table in it, not a single table. Moves it to the drive recycle bin (recoverable there). Use feishu_bitable_delete_table to drop one table instead. Requires the user to own the file (or have manage rights).', {
159
+ app_token: z.string().describe('The bitable app_token of the base to delete'),
160
+ }, async ({ app_token }) => guard(deps.client, async (client) => {
161
+ const res = await client.drive.v1.file.delete({
162
+ path: { file_token: app_token },
163
+ params: { type: 'bitable' },
164
+ });
165
+ unwrap(res);
166
+ return ok({ app_token, deleted: true });
167
+ }));
168
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Feishu docx `block_type` numeric enum.
3
+ *
4
+ * The @larksuiteoapi/node-sdk types declare `block_type: number` without the
5
+ * enum values, but the API requires the exact integer. Values verified against
6
+ * the official Feishu docx block data-structure documentation.
7
+ *
8
+ * Only the subset reachable from markdown conversion is enumerated here; the
9
+ * full Feishu enum has 30+ types (table, image, grid, …) reachable via the
10
+ * raw `blocks` escape hatch.
11
+ */
12
+ export declare const BlockType: {
13
+ readonly Page: 1;
14
+ readonly Text: 2;
15
+ readonly Heading1: 3;
16
+ readonly Heading2: 4;
17
+ readonly Heading3: 5;
18
+ readonly Heading4: 6;
19
+ readonly Heading5: 7;
20
+ readonly Heading6: 8;
21
+ readonly Heading7: 9;
22
+ readonly Heading8: 10;
23
+ readonly Heading9: 11;
24
+ readonly Bullet: 12;
25
+ readonly Ordered: 13;
26
+ readonly Code: 14;
27
+ readonly Quote: 15;
28
+ readonly Todo: 17;
29
+ readonly Callout: 19;
30
+ readonly Divider: 22;
31
+ };
32
+ export type BlockTypeName = keyof typeof BlockType;
33
+ /** The block-content key that pairs with each block_type in a block descriptor. */
34
+ export declare const BLOCK_TYPE_KEY: Record<number, string>;
35
+ /** Map a markdown ATX heading level (1-9) to its BlockType value. */
36
+ export declare function headingBlockType(level: number): number;
37
+ /**
38
+ * Feishu code block `style.language` numeric enum (subset of common languages).
39
+ * The API accepts an integer; 1 = PlainText is the safe default for unknown
40
+ * fences. Verified against the Feishu docx code-block language enum.
41
+ */
42
+ export declare const CodeLanguage: Record<string, number>;
43
+ /** Resolve a markdown code-fence language hint to its Feishu language code. */
44
+ export declare function codeLanguageCode(hint?: string): number;