@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
@@ -0,0 +1,140 @@
1
+ export type FeishuDomain = 'feishu' | 'lark';
2
+ /** Persisted user token bundle (epoch-ms expiries so freshness is a pure comparison). */
3
+ export interface UserToken {
4
+ access_token: string;
5
+ refresh_token: string;
6
+ access_expires_at: number;
7
+ refresh_expires_at: number;
8
+ scope?: string;
9
+ obtained_at: number;
10
+ }
11
+ /** Minimal fetch surface (injectable in tests). Mirrors the global fetch we actually use. */
12
+ export type FetchLike = (url: string, init: {
13
+ method: string;
14
+ headers: Record<string, string>;
15
+ body: string;
16
+ }) => Promise<{
17
+ ok: boolean;
18
+ status: number;
19
+ json: () => Promise<any>;
20
+ }>;
21
+ /** Thrown when there is no usable user token and the operator must (re-)run `cortex feishu login`. */
22
+ export declare class FeishuUserTokenError extends Error {
23
+ constructor(message: string);
24
+ }
25
+ export interface OAuthHosts {
26
+ /** Host that serves the user-facing authorization (consent) page. */
27
+ authorizeBase: string;
28
+ /** Host that serves the OAuth token endpoint (code exchange + refresh). */
29
+ tokenBase: string;
30
+ }
31
+ /**
32
+ * OAuth hosts per Feishu/Lark deployment. Feishu hosts are from the official OAuth v2 docs;
33
+ * the larksuite.com equivalents mirror the same path layout (not separately documented).
34
+ */
35
+ export declare function hostsFor(domain?: FeishuDomain): OAuthHosts;
36
+ /**
37
+ * Default user scopes requested at login when neither --scope nor FEISHU_USER_SCOPE is set.
38
+ * Chosen to keep the WHOLE set review-free (免审) — so a developer can `cortex feishu login` and
39
+ * click "开通并授权" without any scope tripping Feishu's review gate. Verified empirically:
40
+ * - docx:document / sheets:spreadsheet / bitable:app / wiki:wiki — create/read/write content
41
+ * (link-share via permissionPublic also works on these resource scopes alone).
42
+ * - space:document:delete — whole-file delete (drive.v1.file.delete accepts this in place of
43
+ * the broad, review-gated drive:drive).
44
+ * Intentionally omitted: drive:drive (broad, review-gated) and drive:drive:readonly (review-gated;
45
+ * there is no 免审 read:meta alternative). The only casualty is docx canonical-URL resolution via
46
+ * meta.batchQuery — callers fall back to a constructed https://feishu.cn/docx/<id> link, which
47
+ * still redirects to the doc for its owner. Add drive:drive:readonly via --scope if you accept a
48
+ * review step and want the canonical tenant-subdomain URL. Unopened scopes are ignored at consent.
49
+ */
50
+ export declare const DEFAULT_DOC_SCOPE = "docx:document sheets:spreadsheet bitable:app wiki:wiki space:document:delete im:resource";
51
+ /** Default location of the on-disk token store (alongside .env in CONFIG_DIR). */
52
+ export declare function userTokenPath(): string;
53
+ /** Build the OAuth authorization URL the operator opens in a browser to grant access. */
54
+ export declare function buildAuthorizeUrl(opts: {
55
+ appId: string;
56
+ redirectUri: string;
57
+ scope?: string;
58
+ state?: string;
59
+ domain?: FeishuDomain;
60
+ }): string;
61
+ /** Accept either a bare authorization code or a full callback URL; return the code or null. */
62
+ export declare function parseCodeFromInput(input: string): string | null;
63
+ /** Exchange an authorization code for a user_access_token + refresh_token. */
64
+ export declare function exchangeCode(opts: {
65
+ appId: string;
66
+ appSecret: string;
67
+ code: string;
68
+ redirectUri?: string;
69
+ domain?: FeishuDomain;
70
+ fetchImpl?: FetchLike;
71
+ now?: () => number;
72
+ }): Promise<UserToken>;
73
+ /** Response of the device-authorization request. */
74
+ export interface DeviceAuthorization {
75
+ device_code: string;
76
+ user_code: string;
77
+ verification_uri: string;
78
+ /** verification_uri with user_code pre-filled (falls back to verification_uri). */
79
+ verification_uri_complete: string;
80
+ /** seconds until the device_code expires. */
81
+ expires_in: number;
82
+ /** seconds the client must wait between token polls. */
83
+ interval: number;
84
+ }
85
+ /**
86
+ * Request a device authorization code. The app (client_id/secret) authenticates via
87
+ * HTTP Basic; the body carries client_id + scope (offline_access is always included).
88
+ */
89
+ export declare function requestDeviceAuthorization(opts: {
90
+ appId: string;
91
+ appSecret: string;
92
+ scope?: string;
93
+ domain?: FeishuDomain;
94
+ fetchImpl?: FetchLike;
95
+ }): Promise<DeviceAuthorization>;
96
+ /**
97
+ * Poll the token endpoint with the device_code until the user authorizes (success),
98
+ * the code is denied/expires (throws), or the deadline passes (throws). Honours the
99
+ * server-suggested interval and backs off on `slow_down`.
100
+ */
101
+ export declare function pollDeviceToken(opts: {
102
+ appId: string;
103
+ appSecret: string;
104
+ deviceCode: string;
105
+ interval?: number;
106
+ expiresIn?: number;
107
+ domain?: FeishuDomain;
108
+ fetchImpl?: FetchLike;
109
+ now?: () => number;
110
+ /** Injectable wait (defaults to setTimeout) — lets tests run the loop instantly. */
111
+ sleep?: (ms: number) => Promise<void>;
112
+ /** Called once per pending/slow_down poll (e.g. to print progress). */
113
+ onPending?: () => void;
114
+ }): Promise<UserToken>;
115
+ /** Refresh a user_access_token using the (rotating) refresh_token. */
116
+ export declare function refreshUserToken(opts: {
117
+ appId: string;
118
+ appSecret: string;
119
+ refreshToken: string;
120
+ domain?: FeishuDomain;
121
+ fetchImpl?: FetchLike;
122
+ now?: () => number;
123
+ }): Promise<UserToken>;
124
+ export declare function saveUserToken(tok: UserToken, file?: string): void;
125
+ export declare function loadUserToken(file?: string): UserToken | null;
126
+ export declare function clearUserToken(file?: string): boolean;
127
+ /**
128
+ * Return a valid user_access_token, refreshing (and persisting) it when near expiry.
129
+ * Throws FeishuUserTokenError — never falls back to bot identity — when no token exists
130
+ * or the refresh_token itself has expired.
131
+ */
132
+ export declare function getValidUserAccessToken(opts: {
133
+ appId: string;
134
+ appSecret: string;
135
+ domain?: FeishuDomain;
136
+ file?: string;
137
+ fetchImpl?: FetchLike;
138
+ now?: () => number;
139
+ bufferMs?: number;
140
+ }): Promise<string>;
@@ -0,0 +1,286 @@
1
+ // input: Feishu OAuth v2 endpoints (authen/v2/oauth/token, accounts device_authorization),
2
+ // CONFIG_DIR, global fetch
3
+ // output: user_access_token acquisition — device-authorization grant (default: requestDevice-
4
+ // Authorization + pollDeviceToken) and the legacy authorize-URL + code exchange (manual
5
+ // fallback) — plus refresh, on-disk store, and getValidUserAccessToken() (auto-refresh)
6
+ // pos: Powers FEISHU_AUTH_MODE=user — MCP doc tools act as the operator's Feishu account.
7
+ // Messaging (platform/adapters/feishu.ts) is unaffected; it stays app/bot identity.
8
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
9
+ import * as path from 'path';
10
+ import { readFileSync, writeFileSync, mkdirSync, existsSync, unlinkSync } from 'fs';
11
+ import { CONFIG_DIR } from '../../../core/utils.js';
12
+ /** Thrown when there is no usable user token and the operator must (re-)run `cortex feishu login`. */
13
+ export class FeishuUserTokenError extends Error {
14
+ constructor(message) {
15
+ super(message);
16
+ this.name = 'FeishuUserTokenError';
17
+ }
18
+ }
19
+ /**
20
+ * OAuth hosts per Feishu/Lark deployment. Feishu hosts are from the official OAuth v2 docs;
21
+ * the larksuite.com equivalents mirror the same path layout (not separately documented).
22
+ */
23
+ export function hostsFor(domain) {
24
+ return domain === 'lark'
25
+ ? { authorizeBase: 'https://accounts.larksuite.com', tokenBase: 'https://open.larksuite.com' }
26
+ : { authorizeBase: 'https://accounts.feishu.cn', tokenBase: 'https://open.feishu.cn' };
27
+ }
28
+ const TOKEN_PATH = '/open-apis/authen/v2/oauth/token';
29
+ const AUTHORIZE_PATH = '/open-apis/authen/v1/authorize';
30
+ /** Device Authorization Grant (RFC 8628) endpoint — served by the accounts (authorize) host. */
31
+ const DEVICE_AUTH_PATH = '/oauth/v1/device_authorization';
32
+ /** grant_type for exchanging a device_code at the token endpoint. */
33
+ const DEVICE_GRANT = 'urn:ietf:params:oauth:grant-type:device_code';
34
+ /** offline_access is required for the token endpoint to return a refresh_token. */
35
+ const REQUIRED_SCOPE = 'offline_access';
36
+ /**
37
+ * Default user scopes requested at login when neither --scope nor FEISHU_USER_SCOPE is set.
38
+ * Chosen to keep the WHOLE set review-free (免审) — so a developer can `cortex feishu login` and
39
+ * click "开通并授权" without any scope tripping Feishu's review gate. Verified empirically:
40
+ * - docx:document / sheets:spreadsheet / bitable:app / wiki:wiki — create/read/write content
41
+ * (link-share via permissionPublic also works on these resource scopes alone).
42
+ * - space:document:delete — whole-file delete (drive.v1.file.delete accepts this in place of
43
+ * the broad, review-gated drive:drive).
44
+ * Intentionally omitted: drive:drive (broad, review-gated) and drive:drive:readonly (review-gated;
45
+ * there is no 免审 read:meta alternative). The only casualty is docx canonical-URL resolution via
46
+ * meta.batchQuery — callers fall back to a constructed https://feishu.cn/docx/<id> link, which
47
+ * still redirects to the doc for its owner. Add drive:drive:readonly via --scope if you accept a
48
+ * review step and want the canonical tenant-subdomain URL. Unopened scopes are ignored at consent.
49
+ */
50
+ export const DEFAULT_DOC_SCOPE = 'docx:document sheets:spreadsheet bitable:app wiki:wiki space:document:delete im:resource';
51
+ /** Default location of the on-disk token store (alongside .env in CONFIG_DIR). */
52
+ export function userTokenPath() {
53
+ return path.join(CONFIG_DIR, 'feishu-user-token.json');
54
+ }
55
+ /** Merge caller scope(s) with the mandatory offline_access scope, de-duplicated. */
56
+ function normalizeScope(scope) {
57
+ const parts = new Set((scope ?? '').split(/\s+/).filter(Boolean));
58
+ parts.add(REQUIRED_SCOPE);
59
+ return [...parts].join(' ');
60
+ }
61
+ /** Build the OAuth authorization URL the operator opens in a browser to grant access. */
62
+ export function buildAuthorizeUrl(opts) {
63
+ const { authorizeBase } = hostsFor(opts.domain);
64
+ const url = new URL(authorizeBase + AUTHORIZE_PATH);
65
+ url.searchParams.set('client_id', opts.appId);
66
+ url.searchParams.set('redirect_uri', opts.redirectUri);
67
+ url.searchParams.set('response_type', 'code');
68
+ url.searchParams.set('scope', normalizeScope(opts.scope));
69
+ if (opts.state)
70
+ url.searchParams.set('state', opts.state);
71
+ return url.toString();
72
+ }
73
+ /** Accept either a bare authorization code or a full callback URL; return the code or null. */
74
+ export function parseCodeFromInput(input) {
75
+ const trimmed = (input ?? '').trim();
76
+ if (!trimmed)
77
+ return null;
78
+ if (/^https?:\/\//i.test(trimmed)) {
79
+ try {
80
+ return new URL(trimmed).searchParams.get('code');
81
+ }
82
+ catch {
83
+ return null;
84
+ }
85
+ }
86
+ return trimmed;
87
+ }
88
+ /** Map a raw OAuth token response into a persisted UserToken (computing absolute expiries). */
89
+ function toUserToken(data, now, prevRefresh) {
90
+ const accessTtl = Number(data.expires_in ?? 0) * 1000;
91
+ const refreshTtl = Number(data.refresh_token_expires_in ?? 0) * 1000;
92
+ return {
93
+ access_token: String(data.access_token ?? ''),
94
+ // refresh_token may be omitted on refresh responses; keep the previous one if so.
95
+ refresh_token: String(data.refresh_token ?? prevRefresh ?? ''),
96
+ access_expires_at: now + accessTtl,
97
+ refresh_expires_at: now + refreshTtl,
98
+ scope: data.scope,
99
+ obtained_at: now,
100
+ };
101
+ }
102
+ /** POST the OAuth token endpoint and surface API-level errors (code != 0 / error field). */
103
+ async function postToken(hosts, body, fetchImpl) {
104
+ const res = await fetchImpl(hosts.tokenBase + TOKEN_PATH, {
105
+ method: 'POST',
106
+ headers: { 'Content-Type': 'application/json; charset=utf-8' },
107
+ body: JSON.stringify(body),
108
+ });
109
+ const data = await res.json().catch(() => ({}));
110
+ if (!res.ok || (typeof data.code === 'number' && data.code !== 0) || data.error) {
111
+ const msg = data.error_description || data.error || data.msg || `HTTP ${res.status}`;
112
+ const code = data.code ?? data.error ?? res.status;
113
+ throw new Error(`Feishu OAuth error ${code}: ${msg}`);
114
+ }
115
+ return data;
116
+ }
117
+ /** Exchange an authorization code for a user_access_token + refresh_token. */
118
+ export async function exchangeCode(opts) {
119
+ const fetchImpl = opts.fetchImpl ?? globalThis.fetch;
120
+ const now = (opts.now ?? Date.now)();
121
+ const body = {
122
+ grant_type: 'authorization_code',
123
+ client_id: opts.appId,
124
+ client_secret: opts.appSecret,
125
+ code: opts.code,
126
+ };
127
+ if (opts.redirectUri)
128
+ body.redirect_uri = opts.redirectUri;
129
+ const data = await postToken(hostsFor(opts.domain), body, fetchImpl);
130
+ return toUserToken(data, now);
131
+ }
132
+ /** base64 of "appId:appSecret" for the HTTP Basic auth header. */
133
+ function basicAuth(appId, appSecret) {
134
+ return Buffer.from(`${appId}:${appSecret}`, 'utf8').toString('base64');
135
+ }
136
+ /** Encode a flat string map as application/x-www-form-urlencoded. */
137
+ function formEncode(params) {
138
+ return Object.entries(params)
139
+ .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
140
+ .join('&');
141
+ }
142
+ /**
143
+ * Request a device authorization code. The app (client_id/secret) authenticates via
144
+ * HTTP Basic; the body carries client_id + scope (offline_access is always included).
145
+ */
146
+ export async function requestDeviceAuthorization(opts) {
147
+ const fetchImpl = opts.fetchImpl ?? globalThis.fetch;
148
+ const hosts = hostsFor(opts.domain);
149
+ const res = await fetchImpl(hosts.authorizeBase + DEVICE_AUTH_PATH, {
150
+ method: 'POST',
151
+ headers: {
152
+ 'Content-Type': 'application/x-www-form-urlencoded',
153
+ Authorization: `Basic ${basicAuth(opts.appId, opts.appSecret)}`,
154
+ },
155
+ body: formEncode({ client_id: opts.appId, scope: normalizeScope(opts.scope) }),
156
+ });
157
+ const data = await res.json().catch(() => ({}));
158
+ if (!res.ok || data.error || !data.device_code) {
159
+ const msg = data.error_description || data.error || data.msg || `HTTP ${res.status}`;
160
+ throw new Error(`Feishu device authorization failed: ${msg}`);
161
+ }
162
+ const verificationUri = String(data.verification_uri ?? '');
163
+ return {
164
+ device_code: String(data.device_code),
165
+ user_code: String(data.user_code ?? ''),
166
+ verification_uri: verificationUri,
167
+ verification_uri_complete: String(data.verification_uri_complete || verificationUri),
168
+ expires_in: Number(data.expires_in ?? 300),
169
+ interval: Number(data.interval ?? 5),
170
+ };
171
+ }
172
+ /**
173
+ * Poll the token endpoint with the device_code until the user authorizes (success),
174
+ * the code is denied/expires (throws), or the deadline passes (throws). Honours the
175
+ * server-suggested interval and backs off on `slow_down`.
176
+ */
177
+ export async function pollDeviceToken(opts) {
178
+ const fetchImpl = opts.fetchImpl ?? globalThis.fetch;
179
+ const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
180
+ const clock = opts.now ?? Date.now;
181
+ const hosts = hostsFor(opts.domain);
182
+ const maxInterval = 60;
183
+ let interval = Math.max(1, opts.interval ?? 5);
184
+ const deadline = clock() + (opts.expiresIn ?? 300) * 1000;
185
+ for (;;) {
186
+ await sleep(interval * 1000);
187
+ const res = await fetchImpl(hosts.tokenBase + TOKEN_PATH, {
188
+ method: 'POST',
189
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
190
+ body: formEncode({
191
+ grant_type: DEVICE_GRANT,
192
+ device_code: opts.deviceCode,
193
+ client_id: opts.appId,
194
+ client_secret: opts.appSecret,
195
+ }),
196
+ });
197
+ const data = await res.json().catch(() => ({}));
198
+ const err = data.error;
199
+ if (!err && data.access_token) {
200
+ return toUserToken(data, clock());
201
+ }
202
+ if (err === 'authorization_pending') {
203
+ opts.onPending?.();
204
+ }
205
+ else if (err === 'slow_down') {
206
+ interval = Math.min(maxInterval, interval + 5);
207
+ opts.onPending?.();
208
+ }
209
+ else if (err) {
210
+ throw new Error(`Feishu device login failed: ${data.error_description || err}`);
211
+ }
212
+ if (clock() >= deadline) {
213
+ throw new Error('Feishu device login timed out before authorization completed.');
214
+ }
215
+ }
216
+ }
217
+ /** Refresh a user_access_token using the (rotating) refresh_token. */
218
+ export async function refreshUserToken(opts) {
219
+ const fetchImpl = opts.fetchImpl ?? globalThis.fetch;
220
+ const now = (opts.now ?? Date.now)();
221
+ const data = await postToken(hostsFor(opts.domain), {
222
+ grant_type: 'refresh_token',
223
+ client_id: opts.appId,
224
+ client_secret: opts.appSecret,
225
+ refresh_token: opts.refreshToken,
226
+ }, fetchImpl);
227
+ return toUserToken(data, now, opts.refreshToken);
228
+ }
229
+ // ── On-disk token store ──────────────────────────────────────────
230
+ export function saveUserToken(tok, file = userTokenPath()) {
231
+ mkdirSync(path.dirname(file), { recursive: true });
232
+ writeFileSync(file, JSON.stringify(tok, null, 2), { mode: 0o600 });
233
+ }
234
+ export function loadUserToken(file = userTokenPath()) {
235
+ if (!existsSync(file))
236
+ return null;
237
+ try {
238
+ return JSON.parse(readFileSync(file, 'utf8'));
239
+ }
240
+ catch {
241
+ return null;
242
+ }
243
+ }
244
+ export function clearUserToken(file = userTokenPath()) {
245
+ if (!existsSync(file))
246
+ return false;
247
+ try {
248
+ unlinkSync(file);
249
+ return true;
250
+ }
251
+ catch {
252
+ return false;
253
+ }
254
+ }
255
+ // ── High-level: a valid access token, auto-refreshed ─────────────
256
+ const RELOGIN = 'Run `cortex feishu login` to authorize a Feishu user account.';
257
+ /**
258
+ * Return a valid user_access_token, refreshing (and persisting) it when near expiry.
259
+ * Throws FeishuUserTokenError — never falls back to bot identity — when no token exists
260
+ * or the refresh_token itself has expired.
261
+ */
262
+ export async function getValidUserAccessToken(opts) {
263
+ const file = opts.file ?? userTokenPath();
264
+ const now = (opts.now ?? Date.now)();
265
+ const buffer = opts.bufferMs ?? 120_000; // refresh 2 min early
266
+ const tok = loadUserToken(file);
267
+ if (!tok || !tok.access_token) {
268
+ throw new FeishuUserTokenError(`No Feishu user token found. ${RELOGIN}`);
269
+ }
270
+ if (now < tok.access_expires_at - buffer) {
271
+ return tok.access_token;
272
+ }
273
+ if (!tok.refresh_token || now >= tok.refresh_expires_at) {
274
+ throw new FeishuUserTokenError(`Feishu user token expired and cannot be refreshed. ${RELOGIN}`);
275
+ }
276
+ const refreshed = await refreshUserToken({
277
+ appId: opts.appId,
278
+ appSecret: opts.appSecret,
279
+ refreshToken: tok.refresh_token,
280
+ domain: opts.domain,
281
+ fetchImpl: opts.fetchImpl,
282
+ now: () => now,
283
+ });
284
+ saveUserToken(refreshed, file);
285
+ return refreshed.access_token;
286
+ }
@@ -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 registerWikiTools(server: McpServer, deps: FeishuToolDeps): void;
@@ -0,0 +1,77 @@
1
+ // input: MCP SDK, zod, types (guard/ok/unwrap), lark client
2
+ // output: registerWikiTools — feishu_wiki_* tools (knowledge-base spaces & nodes)
3
+ // pos: Feishu 知识库 (wiki) space/node browsing & authoring 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
+ function wikiHost() {
8
+ return process.env.FEISHU_DOMAIN === 'lark' ? 'larksuite.com' : 'feishu.cn';
9
+ }
10
+ /** A wiki node's wiki-space URL (token is the node_token). */
11
+ function wikiUrl(token) {
12
+ return `https://${wikiHost()}/wiki/${token}`;
13
+ }
14
+ export function registerWikiTools(server, deps) {
15
+ server.tool('feishu_wiki_list_spaces', 'List the Feishu knowledge-base (wiki) spaces the app can access. Returns space_id + name. Use a space_id with feishu_wiki_list_nodes to browse its pages.', {
16
+ page_token: z.string().optional().describe('Pagination token from a previous call'),
17
+ page_size: z.number().int().min(1).max(50).optional().describe('Page size (default 20, max 50)'),
18
+ }, async ({ page_token, page_size }) => guard(deps.client, async (client) => {
19
+ const res = await client.wiki.v2.space.list({
20
+ params: { page_size: page_size ?? 20, page_token },
21
+ });
22
+ const data = unwrap(res);
23
+ return ok({ spaces: data.items ?? [], page_token: data.page_token, has_more: data.has_more ?? false });
24
+ }));
25
+ server.tool('feishu_wiki_list_nodes', 'List child nodes (pages) of a wiki space, optionally under a parent node. Each node carries node_token plus obj_token/obj_type — pass a docx node\'s obj_token as document_id to the feishu_docx_* tools to read/edit its content.', {
26
+ space_id: z.string().describe('The wiki space_id (from feishu_wiki_list_spaces)'),
27
+ parent_node_token: z.string().optional().describe('List children under this node (top level if omitted)'),
28
+ page_token: z.string().optional().describe('Pagination token from a previous call'),
29
+ page_size: z.number().int().min(1).max(50).optional().describe('Page size (default 50, max 50)'),
30
+ }, async ({ space_id, parent_node_token, page_token, page_size }) => guard(deps.client, async (client) => {
31
+ const res = await client.wiki.v2.spaceNode.list({
32
+ path: { space_id },
33
+ params: { page_size: page_size ?? 50, page_token, parent_node_token },
34
+ });
35
+ const data = unwrap(res);
36
+ return ok({ space_id, nodes: data.items ?? [], page_token: data.page_token, has_more: data.has_more ?? false });
37
+ }));
38
+ server.tool('feishu_wiki_get_node', 'Get a wiki node by its token. Returns obj_token + obj_type (e.g. docx/sheet/bitable) so you can hand off to the matching feishu_docx_* / feishu_sheets_* / feishu_bitable_* tools.', {
39
+ token: z.string().describe('The wiki node_token (or a wiki-doc token)'),
40
+ obj_type: z.string().optional().describe('Optional object type hint (wiki | docx | …)'),
41
+ }, async ({ token, obj_type }) => guard(deps.client, async (client) => {
42
+ const res = await client.wiki.v2.space.getNode({
43
+ params: { token, obj_type },
44
+ });
45
+ const data = unwrap(res);
46
+ return ok({ node: data.node ?? null });
47
+ }));
48
+ server.tool('feishu_wiki_create_node', 'Create a new node (page) in a wiki space. Defaults to a docx document — after creating, use the returned obj_token as document_id with feishu_docx_append to add content.', {
49
+ space_id: z.string().describe('The wiki space_id to create the node in'),
50
+ title: z.string().optional().describe('Node title'),
51
+ obj_type: z.string().optional().describe('Object type: docx (default), sheet, bitable, mindnote'),
52
+ parent_node_token: z.string().optional().describe('Create under this node (space root if omitted)'),
53
+ }, async ({ space_id, title, obj_type, parent_node_token }) => guard(deps.client, async (client) => {
54
+ const res = await client.wiki.v2.spaceNode.create({
55
+ path: { space_id },
56
+ data: { obj_type: obj_type ?? 'docx', node_type: 'origin', parent_node_token, title },
57
+ });
58
+ const data = unwrap(res);
59
+ const node = data.node ?? {};
60
+ return ok({ node, url: node.node_token ? wikiUrl(node.node_token) : undefined });
61
+ }));
62
+ server.tool('feishu_wiki_update_node_title', 'Rename a wiki node (updates its title only). Locate node_token with feishu_wiki_list_nodes first.', {
63
+ space_id: z.string().describe('The wiki space_id'),
64
+ node_token: z.string().describe('The node to rename'),
65
+ title: z.string().describe('New title'),
66
+ }, async ({ space_id, node_token, title }) => guard(deps.client, async (client) => {
67
+ const res = await client.wiki.v2.spaceNode.updateTitle({
68
+ path: { space_id, node_token },
69
+ data: { title },
70
+ });
71
+ unwrap(res);
72
+ return ok({ space_id, node_token, title, updated: true });
73
+ }));
74
+ // NOTE: wiki node *search* (wiki.v1.node.search) and *space creation* require a USER access token;
75
+ // the cortex-feishu server authenticates as the app (tenant token) only, so those are intentionally
76
+ // not exposed. The node tools above work once the app is added as a member of a wiki space.
77
+ }
@@ -0,0 +1,2 @@
1
+ export declare const TOOL_NAMES: readonly string[];
2
+ export declare function startServer(): Promise<void>;
@@ -0,0 +1,33 @@
1
+ // input: MCP SDK, feishu/ tool registration, lark client builder
2
+ // output: cortex-feishu MCP stdio server — Feishu tools (docx/wiki/bitable/sheets + drive sharing)
3
+ // pos: Standalone MCP server (peer of core-server.ts & server.ts); loaded only for Feishu-originated
4
+ // sessions (channel carries the `feishu:` prefix) — Claude via mcp-config-feishu.json layering,
5
+ // PI via the mcp-bridge feishu handle. Not loaded for thread/core sessions.
6
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
7
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
8
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
9
+ import { registerFeishuTools, FEISHU_TOOL_NAMES } from './feishu/index.js';
10
+ import { buildFeishuClientFromEnv } from './feishu/client.js';
11
+ import { isMainModule } from '../../core/utils.js';
12
+ import { createLogger } from '../../core/log.js';
13
+ import { CORTEX_VERSION } from '../../core/version.js';
14
+ const log = createLogger('mcp-feishu');
15
+ // --- Client from env (null when unconfigured → tools fail with friendly message) ---
16
+ const client = buildFeishuClientFromEnv();
17
+ // --- McpServer + tool registration ---
18
+ const server = new McpServer({ name: 'cortex-feishu', version: CORTEX_VERSION });
19
+ registerFeishuTools(server, { client });
20
+ export const TOOL_NAMES = FEISHU_TOOL_NAMES;
21
+ export async function startServer() {
22
+ if (!client) {
23
+ log.warn('FEISHU_APP_ID / FEISHU_APP_SECRET not set — Feishu document tools will return a not-configured error');
24
+ }
25
+ const transport = new StdioServerTransport();
26
+ await server.connect(transport);
27
+ }
28
+ if (isMainModule(import.meta.url)) {
29
+ startServer().catch((e) => {
30
+ log.error(e);
31
+ process.exit(1);
32
+ });
33
+ }
@@ -1,3 +1,2 @@
1
1
  export declare const TOOL_NAMES: readonly string[];
2
2
  export declare function startServer(): Promise<void>;
3
- export { uploadFileToSlack } from './tools/slack.js';
@@ -1,24 +1,19 @@
1
- // input: MCP SDK, Slack WebClient, 4 tool-family modules (no remote_* — those live in core-server.ts)
2
- // output: MCP stdio service, exposing slack/cost/query/context/schedule tools
3
- // pos: Ext MCP server — direct-agent-only tools (Slack, cost, executions, context, schedule)
1
+ // input: MCP SDK, 3 tool-family modules (no remote_* — those live in core-server.ts, no slack_send_file — that lives in slack-server.ts)
2
+ // output: MCP stdio service, exposing cost/query/context/schedule tools
3
+ // pos: Ext MCP server — platform-agnostic tools (cost, executions, context, schedule)
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
5
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
6
6
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
7
- import { WebClient } from '@slack/web-api';
8
- import { registerSlackTools } from './tools/slack.js';
9
7
  import { registerCostTools } from './tools/cost.js';
10
8
  import { registerExecutionTools } from './tools/executions.js';
11
9
  import { registerContextTools } from './tools/context.js';
12
10
  import { registerScheduleTools } from './tools/schedule.js';
11
+ import { executionRepo } from '../../store/execution-repo.js';
13
12
  import { isMainModule } from '../../core/utils.js';
14
13
  import { createLogger } from '../../core/log.js';
15
14
  import { CORTEX_VERSION } from '../../core/version.js';
16
15
  const log = createLogger('mcp-server');
17
16
  // --- Config from env / CLI args ---
18
- const token = process.env.SLACK_BOT_TOKEN;
19
- const fallbackChannel = process.env.SLACK_CHANNEL;
20
- const branchMachine = process.env.CORTEX_BRANCH_MACHINE;
21
- const fallbackCallbackSource = process.env.CORTEX_CALLBACK_SOURCE;
22
17
  function getCliArg(name) {
23
18
  const idx = process.argv.indexOf(name);
24
19
  if (idx !== -1 && idx + 1 < process.argv.length)
@@ -31,26 +26,15 @@ function getCliArg(name) {
31
26
  const routeContextFile = getCliArg('--route-context-file') ||
32
27
  process.env.CORTEX_ROUTE_CONTEXT_FILE ||
33
28
  null;
34
- // --- Slack client ---
35
- const slack = token ? new WebClient(token) : null;
36
29
  // --- McpServer + tool registration ---
37
- const server = new McpServer({ name: 'cortex', version: CORTEX_VERSION });
38
- const slackDeps = {
39
- slack,
40
- fallbackChannel,
41
- routeContextFile,
42
- branchMachine,
43
- callbackSource: fallbackCallbackSource,
44
- };
30
+ const server = new McpServer({ name: 'cortex-ext', version: CORTEX_VERSION });
45
31
  const contextDeps = { routeContextFile };
46
- registerSlackTools(server, slackDeps);
47
32
  registerCostTools(server);
48
33
  registerExecutionTools(server);
49
34
  registerContextTools(server, contextDeps);
50
35
  registerScheduleTools(server, contextDeps);
51
36
  // --- Exported tool name list (for verification) ---
52
37
  export const TOOL_NAMES = [
53
- 'slack_send_file',
54
38
  'cost_query',
55
39
  'query_executions',
56
40
  'cortex_context',
@@ -63,13 +47,10 @@ export const TOOL_NAMES = [
63
47
  ];
64
48
  // --- Start (called by barrel when run as standalone) ---
65
49
  export async function startServer() {
66
- if (!token || !fallbackChannel) {
67
- log.warn('SLACK_BOT_TOKEN or SLACK_CHANNEL not set — slack_send_file will be unavailable');
68
- }
50
+ executionRepo.load();
69
51
  const transport = new StdioServerTransport();
70
52
  await server.connect(transport);
71
53
  }
72
- export { uploadFileToSlack } from './tools/slack.js';
73
54
  if (isMainModule(import.meta.url)) {
74
55
  startServer().catch((e) => {
75
56
  log.error(e);
@@ -0,0 +1,3 @@
1
+ export declare const TOOL_NAMES: readonly string[];
2
+ export declare function startServer(): Promise<void>;
3
+ export { uploadFileToSlack } from './tools/slack.js';