@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
@@ -0,0 +1,127 @@
1
+ // input: none (pure constants)
2
+ // output: Feishu docx BlockType numeric enum + code-language enum + style color maps
3
+ // pos: Shared constants for markdown→block conversion and block rendering
4
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
+ /**
6
+ * Feishu docx `block_type` numeric enum.
7
+ *
8
+ * The @larksuiteoapi/node-sdk types declare `block_type: number` without the
9
+ * enum values, but the API requires the exact integer. Values verified against
10
+ * the official Feishu docx block data-structure documentation.
11
+ *
12
+ * Only the subset reachable from markdown conversion is enumerated here; the
13
+ * full Feishu enum has 30+ types (table, image, grid, …) reachable via the
14
+ * raw `blocks` escape hatch.
15
+ */
16
+ export const BlockType = {
17
+ Page: 1,
18
+ Text: 2,
19
+ Heading1: 3,
20
+ Heading2: 4,
21
+ Heading3: 5,
22
+ Heading4: 6,
23
+ Heading5: 7,
24
+ Heading6: 8,
25
+ Heading7: 9,
26
+ Heading8: 10,
27
+ Heading9: 11,
28
+ Bullet: 12,
29
+ Ordered: 13,
30
+ Code: 14,
31
+ Quote: 15,
32
+ Todo: 17,
33
+ Callout: 19,
34
+ Divider: 22,
35
+ };
36
+ /** The block-content key that pairs with each block_type in a block descriptor. */
37
+ export const BLOCK_TYPE_KEY = {
38
+ [BlockType.Text]: 'text',
39
+ [BlockType.Heading1]: 'heading1',
40
+ [BlockType.Heading2]: 'heading2',
41
+ [BlockType.Heading3]: 'heading3',
42
+ [BlockType.Heading4]: 'heading4',
43
+ [BlockType.Heading5]: 'heading5',
44
+ [BlockType.Heading6]: 'heading6',
45
+ [BlockType.Heading7]: 'heading7',
46
+ [BlockType.Heading8]: 'heading8',
47
+ [BlockType.Heading9]: 'heading9',
48
+ [BlockType.Bullet]: 'bullet',
49
+ [BlockType.Ordered]: 'ordered',
50
+ [BlockType.Code]: 'code',
51
+ [BlockType.Quote]: 'quote',
52
+ [BlockType.Todo]: 'todo',
53
+ [BlockType.Callout]: 'callout',
54
+ [BlockType.Divider]: 'divider',
55
+ };
56
+ /** Map a markdown ATX heading level (1-9) to its BlockType value. */
57
+ export function headingBlockType(level) {
58
+ const clamped = Math.min(Math.max(level, 1), 9);
59
+ return BlockType.Heading1 + (clamped - 1);
60
+ }
61
+ /**
62
+ * Feishu code block `style.language` numeric enum (subset of common languages).
63
+ * The API accepts an integer; 1 = PlainText is the safe default for unknown
64
+ * fences. Verified against the Feishu docx code-block language enum.
65
+ */
66
+ export const CodeLanguage = {
67
+ plaintext: 1,
68
+ abap: 2,
69
+ ada: 3,
70
+ apache: 4,
71
+ apex: 5,
72
+ assembly: 6,
73
+ bash: 7,
74
+ sh: 7,
75
+ shell: 7,
76
+ csharp: 8,
77
+ 'c#': 8,
78
+ cpp: 9,
79
+ 'c++': 9,
80
+ c: 10,
81
+ css: 12,
82
+ diff: 14,
83
+ dockerfile: 16,
84
+ go: 20,
85
+ golang: 20,
86
+ graphql: 21,
87
+ groovy: 22,
88
+ html: 23,
89
+ json: 28,
90
+ java: 25,
91
+ javascript: 26,
92
+ js: 26,
93
+ kotlin: 30,
94
+ latex: 31,
95
+ lua: 33,
96
+ makefile: 34,
97
+ markdown: 35,
98
+ md: 35,
99
+ matlab: 36,
100
+ nginx: 39,
101
+ 'objective-c': 40,
102
+ php: 43,
103
+ python: 49,
104
+ py: 49,
105
+ r: 50,
106
+ ruby: 52,
107
+ rb: 52,
108
+ rust: 53,
109
+ rs: 53,
110
+ scala: 54,
111
+ scss: 56,
112
+ sql: 60,
113
+ swift: 64,
114
+ toml: 67,
115
+ typescript: 68,
116
+ ts: 68,
117
+ vue: 72,
118
+ xml: 73,
119
+ yaml: 74,
120
+ yml: 74,
121
+ };
122
+ /** Resolve a markdown code-fence language hint to its Feishu language code. */
123
+ export function codeLanguageCode(hint) {
124
+ if (!hint)
125
+ return CodeLanguage.plaintext;
126
+ return CodeLanguage[hint.trim().toLowerCase()] ?? CodeLanguage.plaintext;
127
+ }
@@ -0,0 +1,19 @@
1
+ /** Human-readable name for a block_type value (e.g. 3 → "heading1"). */
2
+ export declare function blockTypeName(blockType: number): string;
3
+ interface ApiBlock {
4
+ block_id?: string;
5
+ parent_id?: string;
6
+ block_type: number;
7
+ [key: string]: unknown;
8
+ }
9
+ /** Extract the concatenated plain text from a Feishu API block's elements. */
10
+ export declare function blockToText(blockData: ApiBlock): string;
11
+ export interface BlockSummary {
12
+ block_id: string | undefined;
13
+ type: string;
14
+ parent_id: string | undefined;
15
+ text: string;
16
+ }
17
+ /** Condense a list of API blocks into id/type/parent/text rows for agent navigation. */
18
+ export declare function summarizeBlocks(blocks: ApiBlock[]): BlockSummary[];
19
+ export {};
@@ -0,0 +1,43 @@
1
+ // input: block-types (BlockType enum, key map)
2
+ // output: blockToText / summarizeBlocks — render Feishu API blocks to text + summaries
3
+ // pos: Read/locate path for feishu_docx_list_blocks & get_content
4
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
+ import { BlockType, BLOCK_TYPE_KEY } from './block-types.js';
6
+ const TYPE_NAME = {
7
+ [BlockType.Page]: 'page',
8
+ ...Object.fromEntries(Object.entries(BLOCK_TYPE_KEY).map(([n, key]) => [Number(n), key])),
9
+ };
10
+ /** Human-readable name for a block_type value (e.g. 3 → "heading1"). */
11
+ export function blockTypeName(blockType) {
12
+ return TYPE_NAME[blockType] ?? `unknown(${blockType})`;
13
+ }
14
+ /** Extract the concatenated plain text from a Feishu API block's elements. */
15
+ export function blockToText(blockData) {
16
+ const key = BLOCK_TYPE_KEY[blockData.block_type];
17
+ if (!key)
18
+ return '';
19
+ const content = blockData[key];
20
+ const elements = content?.elements;
21
+ if (!Array.isArray(elements))
22
+ return '';
23
+ let text = '';
24
+ for (const el of elements) {
25
+ // text_run / mention_user / mention_doc / equation all carry a text-ish payload;
26
+ // we only surface the literal `content` field where present.
27
+ for (const v of Object.values(el)) {
28
+ if (v && typeof v === 'object' && typeof v.content === 'string') {
29
+ text += v.content;
30
+ }
31
+ }
32
+ }
33
+ return text;
34
+ }
35
+ /** Condense a list of API blocks into id/type/parent/text rows for agent navigation. */
36
+ export function summarizeBlocks(blocks) {
37
+ return blocks.map((b) => ({
38
+ block_id: b.block_id,
39
+ type: blockTypeName(b.block_type),
40
+ parent_id: b.parent_id,
41
+ text: blockToText(b),
42
+ }));
43
+ }
@@ -0,0 +1,46 @@
1
+ import * as lark from '@larksuiteoapi/node-sdk';
2
+ export type LarkClient = lark.Client;
3
+ export interface FeishuClientConfig {
4
+ appId: string;
5
+ appSecret: string;
6
+ domain?: 'feishu' | 'lark';
7
+ }
8
+ /**
9
+ * Logger that routes ALL lark SDK output to stderr. CRITICAL for the cortex-feishu MCP server:
10
+ * it speaks the MCP JSON-RPC protocol over stdout, but the lark SDK logs via console.log (stdout)
11
+ * by default. Any SDK info/error log emitted during a tool call (e.g. a Feishu API permission
12
+ * error) would otherwise interleave with the protocol stream and corrupt the response. Console.error
13
+ * writes to stderr, which the MCP transport ignores.
14
+ */
15
+ export declare const stderrLogger: {
16
+ error: (...m: unknown[]) => void;
17
+ warn: (...m: unknown[]) => void;
18
+ info: (...m: unknown[]) => void;
19
+ debug: (...m: unknown[]) => void;
20
+ trace: (...m: unknown[]) => void;
21
+ };
22
+ /** Construct a Feishu OpenAPI client (mirrors FeishuAdapter's constructor). */
23
+ export declare function createFeishuClient(config: FeishuClientConfig): LarkClient;
24
+ /**
25
+ * Wrap a lark client so EVERY leaf API call (e.g. client.docx.v1.document.create)
26
+ * is automatically tagged with a freshly-resolved user_access_token via
27
+ * lark.withUserAccessToken — without editing each of the ~35 tool call sites.
28
+ *
29
+ * A recursive Proxy descends the resource tree (returning child proxies for objects)
30
+ * and, on a method call, resolves the token first then invokes the real method with the
31
+ * token option appended. The token is fetched per call so refreshes are picked up, and a
32
+ * failing provider rejects the call (surfaced by guard()) — it never falls back to bot auth.
33
+ */
34
+ export declare function wrapWithUserToken(client: LarkClient, getToken: () => Promise<string>): LarkClient;
35
+ /**
36
+ * Build a client from environment variables. Returns null when credentials are
37
+ * absent so the server can register tools that fail with a friendly message
38
+ * rather than crashing at startup.
39
+ *
40
+ * FEISHU_AUTH_MODE selects identity for document operations (binary, no fallback):
41
+ * - 'bot' (default): app/tenant identity (docs owned by the bot).
42
+ * - 'user': the operator's Feishu account (docs owned by the user). App credentials are
43
+ * still required (used to refresh the user token). A missing/expired user token makes
44
+ * doc tools fail with a re-login hint rather than silently reverting to bot identity.
45
+ */
46
+ export declare function buildFeishuClientFromEnv(env?: NodeJS.ProcessEnv): LarkClient | null;
@@ -0,0 +1,87 @@
1
+ // input: @larksuiteoapi/node-sdk, env (FEISHU_APP_ID/SECRET/DOMAIN/AUTH_MODE), user-auth
2
+ // output: buildFeishuClientFromEnv() → lark.Client | null (null when unconfigured);
3
+ // wrapWithUserToken() to act as a Feishu user (FEISHU_AUTH_MODE=user)
4
+ // pos: Shared Feishu OpenAPI client for all feishu_* MCP doc tools. In user mode every
5
+ // leaf API call is auto-tagged with the operator's user_access_token; messaging
6
+ // (platform/adapters/feishu.ts) is separate and always stays bot/app identity.
7
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
8
+ import * as lark from '@larksuiteoapi/node-sdk';
9
+ import { getValidUserAccessToken } from './user-auth.js';
10
+ /**
11
+ * Logger that routes ALL lark SDK output to stderr. CRITICAL for the cortex-feishu MCP server:
12
+ * it speaks the MCP JSON-RPC protocol over stdout, but the lark SDK logs via console.log (stdout)
13
+ * by default. Any SDK info/error log emitted during a tool call (e.g. a Feishu API permission
14
+ * error) would otherwise interleave with the protocol stream and corrupt the response. Console.error
15
+ * writes to stderr, which the MCP transport ignores.
16
+ */
17
+ export const stderrLogger = {
18
+ error: (...m) => console.error('[lark:error]', ...m),
19
+ warn: (...m) => console.error('[lark:warn]', ...m),
20
+ info: (...m) => console.error('[lark:info]', ...m),
21
+ debug: (...m) => console.error('[lark:debug]', ...m),
22
+ trace: (...m) => console.error('[lark:trace]', ...m),
23
+ };
24
+ /** Construct a Feishu OpenAPI client (mirrors FeishuAdapter's constructor). */
25
+ export function createFeishuClient(config) {
26
+ const domain = config.domain === 'lark' ? lark.Domain.Lark : lark.Domain.Feishu;
27
+ return new lark.Client({
28
+ appId: config.appId,
29
+ appSecret: config.appSecret,
30
+ appType: lark.AppType.SelfBuild,
31
+ domain,
32
+ // Force SDK logs to stderr — stdout carries the MCP JSON-RPC protocol (see stderrLogger).
33
+ logger: stderrLogger,
34
+ loggerLevel: lark.LoggerLevel.warn,
35
+ });
36
+ }
37
+ /**
38
+ * Wrap a lark client so EVERY leaf API call (e.g. client.docx.v1.document.create)
39
+ * is automatically tagged with a freshly-resolved user_access_token via
40
+ * lark.withUserAccessToken — without editing each of the ~35 tool call sites.
41
+ *
42
+ * A recursive Proxy descends the resource tree (returning child proxies for objects)
43
+ * and, on a method call, resolves the token first then invokes the real method with the
44
+ * token option appended. The token is fetched per call so refreshes are picked up, and a
45
+ * failing provider rejects the call (surfaced by guard()) — it never falls back to bot auth.
46
+ */
47
+ export function wrapWithUserToken(client, getToken) {
48
+ const wrap = (target) => new Proxy(target, {
49
+ get(t, prop, receiver) {
50
+ const value = Reflect.get(t, prop, receiver);
51
+ if (typeof value === 'function') {
52
+ return (payload, options) => getToken().then((token) => {
53
+ const tokenOpt = lark.withUserAccessToken(token);
54
+ const merged = { ...(options ?? {}), lark: { ...(options?.lark ?? {}), ...tokenOpt.lark } };
55
+ return value.call(t, payload, merged);
56
+ });
57
+ }
58
+ if (value && typeof value === 'object')
59
+ return wrap(value);
60
+ return value;
61
+ },
62
+ });
63
+ return wrap(client);
64
+ }
65
+ /**
66
+ * Build a client from environment variables. Returns null when credentials are
67
+ * absent so the server can register tools that fail with a friendly message
68
+ * rather than crashing at startup.
69
+ *
70
+ * FEISHU_AUTH_MODE selects identity for document operations (binary, no fallback):
71
+ * - 'bot' (default): app/tenant identity (docs owned by the bot).
72
+ * - 'user': the operator's Feishu account (docs owned by the user). App credentials are
73
+ * still required (used to refresh the user token). A missing/expired user token makes
74
+ * doc tools fail with a re-login hint rather than silently reverting to bot identity.
75
+ */
76
+ export function buildFeishuClientFromEnv(env = process.env) {
77
+ const appId = env.FEISHU_APP_ID;
78
+ const appSecret = env.FEISHU_APP_SECRET;
79
+ if (!appId || !appSecret)
80
+ return null;
81
+ const domain = env.FEISHU_DOMAIN || undefined;
82
+ const client = createFeishuClient({ appId, appSecret, domain });
83
+ if (env.FEISHU_AUTH_MODE === 'user') {
84
+ return wrapWithUserToken(client, () => getValidUserAccessToken({ appId, appSecret, domain }));
85
+ }
86
+ return client;
87
+ }
@@ -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 registerDocxTools(server: McpServer, deps: FeishuToolDeps): void;
@@ -0,0 +1,163 @@
1
+ // input: MCP SDK, zod, markdown-to-blocks, blocks-to-text, types, client
2
+ // output: registerDocxTools — feishu_docx_* tools (create/read/list/append/insert/update/delete)
3
+ // pos: Feishu 云文档 (docx) block-level authoring & editing 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 { markdownToBlocks } from './markdown-to-blocks.js';
7
+ import { summarizeBlocks } from './blocks-to-text.js';
8
+ import { guard, ok, unwrap } from './types.js';
9
+ import { BLOCK_TYPE_KEY } from './block-types.js';
10
+ import { resolveDriveUrl, setLinkShare } from './drive.js';
11
+ const REV = -1; // document_revision_id: -1 = latest
12
+ function docUrl(documentId) {
13
+ const host = process.env.FEISHU_DOMAIN === 'lark' ? 'larksuite.com' : 'feishu.cn';
14
+ return `https://${host}/docx/${documentId}`;
15
+ }
16
+ /** Resolve tool input into block descriptors: raw `blocks` wins, else parse markdown. */
17
+ function resolveChildren(markdown, blocks) {
18
+ if (Array.isArray(blocks) && blocks.length > 0)
19
+ return blocks;
20
+ if (typeof markdown === 'string')
21
+ return markdownToBlocks(markdown);
22
+ return [];
23
+ }
24
+ /** Extract the inline `elements` array from a single block descriptor (for patch). */
25
+ function elementsOf(block) {
26
+ const key = BLOCK_TYPE_KEY[block.block_type];
27
+ const payload = key ? block[key] : undefined;
28
+ return payload?.elements ?? [];
29
+ }
30
+ export function registerDocxTools(server, deps) {
31
+ server.tool('feishu_docx_create', 'Create a new Feishu cloud document (docx). Returns document_id + the canonical url. By default the doc is link-shared to the tenant (anyone in the org with the link can edit) so a human can open it — without sharing, app-created docs are owned by the bot and invisible in users\' drives. The doc starts empty — use feishu_docx_append to add markdown content.', {
32
+ title: z.string().optional().describe('Document title'),
33
+ folder_token: z.string().optional().describe('Drive folder token to create the doc in (root of the app space if omitted)'),
34
+ share: z.enum(['tenant_edit', 'tenant_view', 'none']).optional().describe('Link-share level (default tenant_edit). none = keep private to the app (invisible to users).'),
35
+ }, async ({ title, folder_token, share }) => guard(deps.client, async (client) => {
36
+ const res = await client.docx.v1.document.create({ data: { title, folder_token } });
37
+ const doc = unwrap(res);
38
+ const id = doc.document?.document_id ?? '';
39
+ const level = share ?? 'tenant_edit';
40
+ let shared = false;
41
+ if (level !== 'none') {
42
+ try {
43
+ shared = await setLinkShare(client, id, 'docx', level);
44
+ }
45
+ catch { /* best-effort: doc is already created; report shared:false */ }
46
+ }
47
+ const url = (await resolveDriveUrl(client, id, 'docx')) ?? docUrl(id);
48
+ return ok({ document_id: id, title: doc.document?.title ?? title, url, shared });
49
+ }));
50
+ server.tool('feishu_docx_get_content', 'Read a Feishu doc as plain text (human-readable, no block IDs). To edit specific blocks, use feishu_docx_list_blocks instead to obtain block_ids.', {
51
+ document_id: z.string().describe('The docx document_id'),
52
+ }, async ({ document_id }) => guard(deps.client, async (client) => {
53
+ const res = await client.docx.v1.document.rawContent({ path: { document_id }, params: { lang: 0 } });
54
+ const data = unwrap(res);
55
+ return ok({ document_id, content: data.content ?? '' });
56
+ }));
57
+ server.tool('feishu_docx_list_blocks', 'List a docx\'s blocks with block_id, type, parent_id and text. Call this before update_block / delete_blocks to locate the target block.', {
58
+ document_id: z.string().describe('The docx document_id'),
59
+ page_token: z.string().optional().describe('Pagination token from a previous call'),
60
+ page_size: z.number().int().min(1).max(500).optional().describe('Page size (default 500)'),
61
+ }, async ({ document_id, page_token, page_size }) => guard(deps.client, async (client) => {
62
+ const res = await client.docx.v1.documentBlock.list({
63
+ path: { document_id },
64
+ params: { page_size: page_size ?? 500, page_token, document_revision_id: REV },
65
+ });
66
+ const data = unwrap(res);
67
+ return ok({
68
+ document_id,
69
+ blocks: summarizeBlocks(data.items ?? []),
70
+ page_token: data.page_token,
71
+ has_more: data.has_more ?? false,
72
+ });
73
+ }));
74
+ server.tool('feishu_docx_append', 'Append content to the end of a docx (or under a parent block). Provide `markdown` (preferred — supports headings, lists, code, quotes, bold/italic/links) and/or raw `blocks` JSON for Feishu-only features (tables, colors, callouts) markdown cannot express.', {
75
+ document_id: z.string().describe('The docx document_id'),
76
+ markdown: z.string().optional().describe('Markdown content to convert into blocks'),
77
+ blocks: z.array(z.any()).optional().describe('Raw Feishu block descriptors (escape hatch; bypasses markdown)'),
78
+ parent_block_id: z.string().optional().describe('Append under this block (default: document root)'),
79
+ }, async ({ document_id, markdown, blocks, parent_block_id }) => guard(deps.client, async (client) => {
80
+ const children = resolveChildren(markdown, blocks);
81
+ if (children.length === 0)
82
+ return ok({ document_id, created: 0, note: 'No content provided' });
83
+ const res = await client.docx.v1.documentBlockChildren.create({
84
+ path: { document_id, block_id: parent_block_id || document_id },
85
+ data: { children: children },
86
+ params: { document_revision_id: REV },
87
+ });
88
+ const data = unwrap(res);
89
+ return ok({
90
+ document_id,
91
+ created_block_ids: (data.children ?? []).map((c) => c.block_id),
92
+ document_revision_id: data.document_revision_id,
93
+ });
94
+ }));
95
+ server.tool('feishu_docx_insert', 'Insert content at a specific position under a parent block. Same content rules as feishu_docx_append, plus a 0-based `index` among the parent\'s children.', {
96
+ document_id: z.string().describe('The docx document_id'),
97
+ index: z.number().int().min(0).describe('0-based insertion position among the parent block\'s children'),
98
+ markdown: z.string().optional().describe('Markdown content to convert into blocks'),
99
+ blocks: z.array(z.any()).optional().describe('Raw Feishu block descriptors (escape hatch)'),
100
+ parent_block_id: z.string().optional().describe('Parent block (default: document root)'),
101
+ }, async ({ document_id, index, markdown, blocks, parent_block_id }) => guard(deps.client, async (client) => {
102
+ const children = resolveChildren(markdown, blocks);
103
+ if (children.length === 0)
104
+ return ok({ document_id, created: 0, note: 'No content provided' });
105
+ const res = await client.docx.v1.documentBlockChildren.create({
106
+ path: { document_id, block_id: parent_block_id || document_id },
107
+ data: { children: children, index },
108
+ params: { document_revision_id: REV },
109
+ });
110
+ const data = unwrap(res);
111
+ return ok({
112
+ document_id,
113
+ created_block_ids: (data.children ?? []).map((c) => c.block_id),
114
+ document_revision_id: data.document_revision_id,
115
+ });
116
+ }));
117
+ server.tool('feishu_docx_update_block', 'Replace the inline text content of a single existing block (text/heading/list/quote/todo). Supply `markdown` (first block\'s inline content is used) or raw `elements` via blocks. Locate block_id with feishu_docx_list_blocks first.', {
118
+ document_id: z.string().describe('The docx document_id'),
119
+ block_id: z.string().describe('The block to update'),
120
+ markdown: z.string().optional().describe('New inline content (markdown; first line/block used)'),
121
+ blocks: z.array(z.any()).optional().describe('Raw Feishu elements[] (escape hatch; bypasses markdown)'),
122
+ }, async ({ document_id, block_id, markdown, blocks }) => guard(deps.client, async (client) => {
123
+ let elements;
124
+ if (Array.isArray(blocks) && blocks.length > 0) {
125
+ elements = blocks;
126
+ }
127
+ else {
128
+ const parsed = markdownToBlocks(markdown ?? '');
129
+ elements = parsed.length > 0 ? elementsOf(parsed[0]) : [];
130
+ }
131
+ const res = await client.docx.v1.documentBlock.patch({
132
+ path: { document_id, block_id },
133
+ data: { update_text_elements: { elements: elements } },
134
+ params: { document_revision_id: REV },
135
+ });
136
+ const data = unwrap(res);
137
+ return ok({ document_id, block_id, document_revision_id: data.document_revision_id });
138
+ }));
139
+ server.tool('feishu_docx_delete_blocks', 'Delete a contiguous range of child blocks under a parent block, by 0-based index (end_index exclusive). Use feishu_docx_list_blocks to find indices.', {
140
+ document_id: z.string().describe('The docx document_id'),
141
+ parent_block_id: z.string().describe('Parent block whose children are deleted (document_id for root)'),
142
+ start_index: z.number().int().min(0).describe('First child index to delete (inclusive)'),
143
+ end_index: z.number().int().min(0).describe('Index to stop at (exclusive)'),
144
+ }, async ({ document_id, parent_block_id, start_index, end_index }) => guard(deps.client, async (client) => {
145
+ const res = await client.docx.v1.documentBlockChildren.batchDelete({
146
+ path: { document_id, block_id: parent_block_id },
147
+ data: { start_index, end_index },
148
+ params: { document_revision_id: REV },
149
+ });
150
+ const data = unwrap(res);
151
+ return ok({ document_id, deleted: `[${start_index}, ${end_index})`, document_revision_id: data.document_revision_id });
152
+ }));
153
+ server.tool('feishu_docx_delete', 'Delete (trash) an entire Feishu doc. This removes the whole document — irreversible from the API. Use feishu_docx_delete_blocks to remove content instead.', {
154
+ document_id: z.string().describe('The docx document_id to delete'),
155
+ }, async ({ document_id }) => guard(deps.client, async (client) => {
156
+ const res = await client.drive.v1.file.delete({
157
+ path: { file_token: document_id },
158
+ params: { type: 'docx' },
159
+ });
160
+ unwrap(res);
161
+ return ok({ document_id, deleted: true });
162
+ }));
163
+ }
@@ -0,0 +1,23 @@
1
+ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ import { type FeishuToolDeps } from './types.js';
3
+ import type { LarkClient } from './client.js';
4
+ /** Drive file type token used by the meta / permission APIs. */
5
+ export type DriveFileType = 'doc' | 'docx' | 'sheet' | 'bitable' | 'file' | 'wiki' | 'slides' | 'mindnote';
6
+ /** Friendly link-share levels mapped to Feishu's link_share_entity values. */
7
+ export type LinkShareLevel = 'tenant_edit' | 'tenant_view' | 'none';
8
+ /**
9
+ * Resolve a drive file's canonical (tenant-subdomain) URL via drive.meta.batchQuery. App-created
10
+ * files live on the tenant subdomain (e.g. https://<tenant>.feishu.cn/docx/<id>), which a hand-built
11
+ * "feishu.cn/docx/<id>" URL does not match — so the create tools call this to return a link that
12
+ * actually opens. Returns null on any failure so callers fall back to a constructed URL.
13
+ */
14
+ export declare function resolveDriveUrl(client: LarkClient, token: string, docType: DriveFileType): Promise<string | null>;
15
+ /**
16
+ * Set a drive file's link-share so tenant members can open it by URL. This is how an app-created
17
+ * (bot-owned) file becomes visible to a human user: without it the file sits in the app's space,
18
+ * owned by the app identity, invisible in any person's drive. `none` is a no-op here (use the
19
+ * standalone tool to actively revoke). Throws on a non-zero API code so callers can decide whether
20
+ * to treat sharing as best-effort.
21
+ */
22
+ export declare function setLinkShare(client: LarkClient, token: string, type: DriveFileType, level: LinkShareLevel): Promise<boolean>;
23
+ export declare function registerDriveTools(server: McpServer, deps: FeishuToolDeps): void;
@@ -0,0 +1,66 @@
1
+ // input: MCP SDK, zod, types (guard/ok/unwrap), lark client
2
+ // output: drive helpers (resolveDriveUrl, setLinkShare) + registerDriveTools (feishu_drive_set_link_share)
3
+ // pos: Feishu drive sharing & canonical-URL resolution — shared by the create tools + a standalone tool
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
+ const LINK_SHARE_ENTITY = {
8
+ tenant_edit: 'tenant_editable',
9
+ tenant_view: 'tenant_readable',
10
+ };
11
+ /**
12
+ * Resolve a drive file's canonical (tenant-subdomain) URL via drive.meta.batchQuery. App-created
13
+ * files live on the tenant subdomain (e.g. https://<tenant>.feishu.cn/docx/<id>), which a hand-built
14
+ * "feishu.cn/docx/<id>" URL does not match — so the create tools call this to return a link that
15
+ * actually opens. Returns null on any failure so callers fall back to a constructed URL.
16
+ */
17
+ export async function resolveDriveUrl(client, token, docType) {
18
+ try {
19
+ const res = await client.drive.v1.meta.batchQuery({
20
+ data: { request_docs: [{ doc_token: token, doc_type: docType }], with_url: true },
21
+ });
22
+ const data = unwrap(res);
23
+ return data.metas?.[0]?.url ?? null;
24
+ }
25
+ catch {
26
+ return null;
27
+ }
28
+ }
29
+ /**
30
+ * Set a drive file's link-share so tenant members can open it by URL. This is how an app-created
31
+ * (bot-owned) file becomes visible to a human user: without it the file sits in the app's space,
32
+ * owned by the app identity, invisible in any person's drive. `none` is a no-op here (use the
33
+ * standalone tool to actively revoke). Throws on a non-zero API code so callers can decide whether
34
+ * to treat sharing as best-effort.
35
+ */
36
+ export async function setLinkShare(client, token, type, level) {
37
+ if (level === 'none')
38
+ return false;
39
+ const res = await client.drive.v1.permissionPublic.patch({
40
+ path: { token },
41
+ params: { type },
42
+ data: { link_share_entity: LINK_SHARE_ENTITY[level] },
43
+ });
44
+ unwrap(res);
45
+ return true;
46
+ }
47
+ export function registerDriveTools(server, deps) {
48
+ server.tool('feishu_drive_set_link_share', 'Control a Feishu file\'s link-share. Use this to make an app-created (bot-owned) doc/sheet/base visible: set level=tenant_edit (anyone in the org with the link can edit) or tenant_view (view only); level=none revokes link access. Returns the canonical URL to open.', {
49
+ token: z.string().describe('The file token (docx document_id, sheet spreadsheet_token, bitable app_token, …)'),
50
+ type: z.enum(['docx', 'sheet', 'bitable', 'file', 'doc', 'slides', 'mindnote']).describe('The file type'),
51
+ level: z.enum(['tenant_edit', 'tenant_view', 'none']).describe('tenant_edit | tenant_view | none (revoke)'),
52
+ }, async ({ token, type, level }) => guard(deps.client, async (client) => {
53
+ if (level === 'none') {
54
+ const res = await client.drive.v1.permissionPublic.patch({
55
+ path: { token },
56
+ params: { type },
57
+ data: { link_share_entity: 'closed' },
58
+ });
59
+ unwrap(res);
60
+ return ok({ token, type, level: 'none', shared: false });
61
+ }
62
+ await setLinkShare(client, token, type, level);
63
+ const url = await resolveDriveUrl(client, token, type);
64
+ return ok({ token, type, level, shared: true, url });
65
+ }));
66
+ }
@@ -0,0 +1,14 @@
1
+ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ import { type FeishuToolDeps } from './types.js';
3
+ import type { LarkClient } from './client.js';
4
+ export declare function uploadFileToFeishu(client: LarkClient, { channel, filePath, fileName, title }: {
5
+ channel: string;
6
+ filePath: string;
7
+ fileName?: string;
8
+ title?: string;
9
+ }): Promise<{
10
+ path: string;
11
+ fileName: string;
12
+ size: number;
13
+ }>;
14
+ export declare function registerFileTools(server: McpServer, deps: FeishuToolDeps): void;