@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
@@ -1,8 +1,9 @@
1
1
  // input: @clack/prompts, fs, path, os, yaml, @core/config-generator
2
2
  // output: runInit — interactive CORTEX_HOME initialization
3
- // pos: cortex init subcommand — backend selection & install, gateway usage opt-in,
4
- // creates directory structure, generates .env, copies default configs,
5
- // auto-generates mcp-config.json and mode.json
3
+ // pos: cortex init subcommand — backend selection & install, multi-select interaction
4
+ // platforms (Slack/Feishu, walked one-by-one), gateway usage opt-in,
5
+ // creates directory structure, generates .env (CORTEX_PLATFORM as a comma list),
6
+ // copies default configs, auto-generates mcp-config.json and mode.json
6
7
  //
7
8
  // INSTALL_ROOT is computed from import.meta.url (agent-server dir, 2 levels up from dist/entry/).
8
9
  // DATA_DIR is resolved via the --home arg, $CORTEX_HOME env, or ~/.cortex/ default.
@@ -17,11 +18,13 @@ import { stdin as processStdin } from 'process';
17
18
  import * as clack from '@clack/prompts';
18
19
  import * as yaml from 'yaml';
19
20
  import { buildFullConfig, buildCoreConfig, buildTuiConfig } from '../core/config-generator.js';
20
- import { discoverEndpoints, generateGatewayYaml, writeGatewayYaml } from '../core/gateway-generator.js';
21
+ import { discoverEndpoints, writeMergedGatewayYaml, validateProfilesAgainstGateway } from '../core/gateway-generator.js';
21
22
  import { generateProfiles, writeProfilesJson, listChoices } from '../core/profile-generator.js';
22
23
  import { mergeThreadTemplates } from '../domain/threads/index.js';
23
24
  import { createLogger } from '../core/log.js';
24
25
  import { INSTALL_ROOT, DEFAULTS_DIR } from '../core/utils.js';
26
+ import { t, setLocale, normalizeLocale, detectSystemLocale } from '../core/i18n.js';
27
+ import { cmdFeishu } from './feishu-login.js';
25
28
  // ─── Path computation (DATA_DIR resolved locally to support --home override) ──
26
29
  const log = createLogger('init');
27
30
  // MODULE_DIR kept for any consumers that still derive paths locally; the canonical roots
@@ -61,6 +64,21 @@ function parseChoiceLine(raw) {
61
64
  model: trimmed.substring(colonIdx + 1).trim(),
62
65
  };
63
66
  }
67
+ /** Parse comma-separated "mode:model" pairs for extra profiles. Returns undefined for empty. */
68
+ function parseExtraProfilesLine(raw) {
69
+ if (!raw)
70
+ return undefined;
71
+ const trimmed = raw.trim();
72
+ if (!trimmed)
73
+ return undefined;
74
+ const choices = [];
75
+ for (const part of trimmed.split(',')) {
76
+ const choice = parseChoiceLine(part.trim());
77
+ if (choice)
78
+ choices.push(choice);
79
+ }
80
+ return choices.length > 0 ? choices : undefined;
81
+ }
64
82
  // ─── Dot env generation ──────────────────────────────────────────
65
83
  /** Generate .env content — includes CORTEX_MACHINE, CORTEX_PLATFORM, and platform-specific tokens. */
66
84
  export function generateDotEnvContent(answers) {
@@ -70,31 +88,29 @@ export function generateDotEnvContent(answers) {
70
88
  '',
71
89
  `CORTEX_MACHINE=${answers.machineName}`,
72
90
  ];
73
- if (answers.platform && answers.platform !== 'none') {
74
- lines.push(`CORTEX_PLATFORM=${answers.platform}`);
91
+ // CORTEX_PLATFORM is a comma-separated list (runtime composes adapters via CompositeAdapter).
92
+ // Each platform's token block is emitted independently when its config is present, so a
93
+ // multi-select (e.g. slack + feishu) produces both blocks.
94
+ if (answers.platforms.length > 0) {
95
+ lines.push(`CORTEX_PLATFORM=${answers.platforms.join(',')}`);
75
96
  lines.push('');
76
- if (answers.platform === 'slack' && answers.slackConfig) {
97
+ if (answers.slackConfig) {
77
98
  lines.push('# Slack configuration');
78
99
  lines.push(`SLACK_BOT_TOKEN=${answers.slackConfig.botToken}`);
79
100
  lines.push(`SLACK_SIGNING_SECRET=${answers.slackConfig.signingSecret}`);
80
101
  lines.push(`SLACK_APP_TOKEN=${answers.slackConfig.appToken}`);
81
- if (answers.slackConfig.adminChannel) {
82
- lines.push(`CORTEX_ADMIN_CHANNEL=${answers.slackConfig.adminChannel}`);
83
- }
102
+ lines.push('');
84
103
  }
85
- else if (answers.platform === 'feishu' && answers.feishuConfig) {
104
+ if (answers.feishuConfig) {
86
105
  lines.push('# Feishu configuration');
87
106
  lines.push(`FEISHU_APP_ID=${answers.feishuConfig.appId}`);
88
107
  lines.push(`FEISHU_APP_SECRET=${answers.feishuConfig.appSecret}`);
89
- if (answers.feishuConfig.encryptKey) {
90
- lines.push(`FEISHU_ENCRYPT_KEY=${answers.feishuConfig.encryptKey}`);
91
- }
92
- if (answers.feishuConfig.verificationToken) {
93
- lines.push(`FEISHU_VERIFICATION_TOKEN=${answers.feishuConfig.verificationToken}`);
94
- }
95
108
  if (answers.feishuConfig.domain) {
96
109
  lines.push(`FEISHU_DOMAIN=${answers.feishuConfig.domain}`);
97
110
  }
111
+ // Identity for MCP doc operations (binary, no fallback). Messaging is always bot.
112
+ // user mode authorizes via `cortex feishu login` (OAuth device flow) — no redirect URI.
113
+ lines.push(`FEISHU_AUTH_MODE=${answers.feishuConfig.authMode ?? 'bot'}`);
98
114
  }
99
115
  }
100
116
  lines.push('');
@@ -113,8 +129,10 @@ export function generateDefaultModeJson(primaryBackend = 'claude') {
113
129
  }
114
130
  /** Format resolved paths and initialization status for `cortex config` output. */
115
131
  export function formatConfigOutput(paths, status) {
132
+ const found = t('init.config.found');
133
+ const missing = t('init.config.missing');
116
134
  const lines = [
117
- 'Cortex configuration:',
135
+ t('init.config.title'),
118
136
  ` INSTALL_ROOT: ${paths.INSTALL_ROOT}`,
119
137
  ` DATA_DIR: ${paths.DATA_DIR}`,
120
138
  ` CONFIG_DIR: ${paths.CONFIG_DIR}`,
@@ -123,11 +141,11 @@ export function formatConfigOutput(paths, status) {
123
141
  ` PROJECTS_DIR: ${paths.PROJECTS_DIR}`,
124
142
  ` WORKSPACE_DIR: ${paths.WORKSPACE_DIR}`,
125
143
  '',
126
- 'Status:',
127
- ` DATA_DIR: ${status.dataDirExists ? 'initialized' : 'not initialized'}`,
128
- ` .env: ${status.dotEnvExists ? 'found' : 'missing'}`,
129
- ` mcp-config.json: ${status.mcpConfigExists ? 'found' : 'missing'}`,
130
- ` mode.json: ${status.modeJsonExists ? 'found' : 'missing'}`,
144
+ t('init.config.statusTitle'),
145
+ ` DATA_DIR: ${status.dataDirExists ? t('init.config.initialized') : t('init.config.notInitialized')}`,
146
+ ` .env: ${status.dotEnvExists ? found : missing}`,
147
+ ` mcp-config.json: ${status.mcpConfigExists ? found : missing}`,
148
+ ` mode.json: ${status.modeJsonExists ? found : missing}`,
131
149
  ];
132
150
  return lines.join('\n');
133
151
  }
@@ -136,14 +154,14 @@ const BACKEND_INFO = {
136
154
  claude: {
137
155
  bin: 'claude',
138
156
  npmPackage: '@anthropic-ai/claude-code',
139
- label: 'Claude Code',
140
- loginHint: 'Run `claude login` to authenticate.',
157
+ labelKey: 'init.backend.label.claude',
158
+ loginHintKey: 'init.backend.loginHint.claude',
141
159
  },
142
160
  pi: {
143
161
  bin: 'pi',
144
162
  npmPackage: '@mariozechner/pi-coding-agent',
145
- label: 'PI',
146
- loginHint: 'Configure your provider in PI settings.',
163
+ labelKey: 'init.backend.label.pi',
164
+ loginHintKey: 'init.backend.loginHint.pi',
147
165
  },
148
166
  };
149
167
  // ─── Slack App Manifest ──────────────────────────────────────────
@@ -242,7 +260,7 @@ function copyToClipboard(text) {
242
260
  async function promptCopyManifestToClipboard(manifest) {
243
261
  if (!process.stdin.isTTY)
244
262
  return; // Non-interactive mode, skip
245
- process.stdout.write('\nPress "c" to copy manifest to clipboard (any other key to skip)...');
263
+ process.stdout.write(t('init.clipboard.prompt'));
246
264
  return new Promise((resolve) => {
247
265
  const wasRaw = process.stdin.isRaw ?? false;
248
266
  try {
@@ -270,11 +288,11 @@ async function promptCopyManifestToClipboard(manifest) {
270
288
  if (ch.toLowerCase() === 'c') {
271
289
  const ok = copyToClipboard(manifest);
272
290
  if (ok) {
273
- clack.log.success('Manifest copied to clipboard!');
291
+ clack.log.success(t('init.clipboard.copied'));
274
292
  }
275
293
  else {
276
- clack.log.warn('Could not copy. If running in a terminal, ensure OSC 52 is enabled.');
277
- clack.log.info('The manifest text is shown above — please copy it manually.');
294
+ clack.log.warn(t('init.clipboard.failed'));
295
+ clack.log.info(t('init.clipboard.manual'));
278
296
  }
279
297
  }
280
298
  resolve();
@@ -304,8 +322,6 @@ function parseExistingEnvSlackConfig(envPath) {
304
322
  result.appToken = value;
305
323
  else if (key === 'SLACK_BOT_TOKEN')
306
324
  result.botToken = value;
307
- else if (key === 'CORTEX_ADMIN_CHANNEL')
308
- result.adminChannel = value;
309
325
  }
310
326
  if (!result.signingSecret && !result.appToken && !result.botToken)
311
327
  return null;
@@ -350,23 +366,24 @@ function detectGpuCount() {
350
366
  async function checkAndInstallBackends(backends) {
351
367
  for (const backend of backends) {
352
368
  const info = BACKEND_INFO[backend];
369
+ const label = t(info.labelKey);
353
370
  const installed = isBackendInstalled(backend);
354
371
  if (installed) {
355
- clack.log.success(`${info.label} is already installed.`);
372
+ clack.log.success(t('init.backend.alreadyInstalled', { label }));
356
373
  }
357
374
  else {
358
375
  const s = clack.spinner();
359
- s.start(`Installing ${info.label}...`);
376
+ s.start(t('init.backend.installing', { label }));
360
377
  try {
361
378
  execSync(getInstallCommand(backend), { stdio: 'pipe', timeout: 120_000 });
362
- s.stop(`${info.label} installed successfully.`);
379
+ s.stop(t('init.backend.installed', { label }));
363
380
  }
364
381
  catch (err) {
365
- s.stop(`Failed to install ${info.label}.`);
366
- clack.log.error(`Installation failed. Install manually: ${getInstallCommand(backend)}`);
382
+ s.stop(t('init.backend.installFailed', { label }));
383
+ clack.log.error(t('init.backend.installFailedHint', { command: getInstallCommand(backend) }));
367
384
  }
368
385
  }
369
- clack.log.info(info.loginHint);
386
+ clack.log.info(t(info.loginHintKey));
370
387
  }
371
388
  }
372
389
  // ─── Gateway usage config ────────────────────────────────────────
@@ -384,7 +401,7 @@ export function generateGatewayUsageYaml(config) {
384
401
  }
385
402
  return yaml.stringify(doc);
386
403
  }
387
- /** Write gateway usage config to ~/.aistatus/config.yaml, or <configDir>/config.yaml if configDir is given. */
404
+ /** Write gateway usage config to ~/.aistatus/config.yaml, or <configDir>/config.yaml if configDir is given (for testing). */
388
405
  function writeGatewayUsageConfig(config, configDir) {
389
406
  const configPath = configDir
390
407
  ? path.join(configDir, 'config.yaml')
@@ -494,8 +511,8 @@ function installService(dataDir) {
494
511
  const plistContent = generateLaunchdPlist(user, cortexBin, dataDir);
495
512
  const plistPath = path.join(os.homedir(), 'Library', 'LaunchAgents', plistName);
496
513
  writeFileSync(plistPath, plistContent);
497
- clack.log.success(`launchd plist written to ${plistPath}`);
498
- clack.log.info('To start now: launchctl load ' + plistPath);
514
+ clack.log.success(t('init.service.launchdWritten', { path: plistPath }));
515
+ clack.log.info(t('init.service.launchdStartHint', { path: plistPath }));
499
516
  }
500
517
  else if (platform === 'linux') {
501
518
  const unitContent = generateSystemdUnit(user, cortexBin, dataDir);
@@ -507,8 +524,8 @@ function installService(dataDir) {
507
524
  mkdirSync(userUnitDir, { recursive: true });
508
525
  const userUnitPath = path.join(userUnitDir, unitName);
509
526
  writeFileSync(userUnitPath, unitContent);
510
- clack.log.success(`systemd unit written to ${userUnitPath}`);
511
- clack.log.info('To enable: sudo systemctl --user enable --now cortex');
527
+ clack.log.success(t('init.service.systemdUserWritten', { path: userUnitPath }));
528
+ clack.log.info(t('init.service.systemdUserEnableHint'));
512
529
  return;
513
530
  }
514
531
  catch {
@@ -520,69 +537,45 @@ function installService(dataDir) {
520
537
  const tmpPath = path.join(os.tmpdir(), unitName);
521
538
  writeFileSync(tmpPath, unitContent);
522
539
  execSync(`sudo cp ${tmpPath} ${systemPath} && sudo systemctl daemon-reload`, { stdio: 'pipe' });
523
- clack.log.success(`systemd unit installed to ${systemPath}`);
524
- clack.log.info('To enable: sudo systemctl enable --now cortex');
540
+ clack.log.success(t('init.service.systemdInstalled', { path: systemPath }));
541
+ clack.log.info(t('init.service.systemdEnableHint'));
525
542
  }
526
543
  catch (err) {
527
- clack.log.warn(`Failed to install system service: ${err.message}`);
544
+ clack.log.warn(t('init.service.systemInstallFailed', { message: err.message }));
528
545
  }
529
546
  }
530
547
  else {
531
548
  // No sudo — write to config dir and show instructions
532
549
  const localPath = path.join(dataDir, 'config', unitName);
533
550
  writeFileSync(localPath, unitContent);
534
- clack.log.warn('No sudo access. Service file saved locally.');
535
- clack.log.info(`To install manually:\n sudo cp ${localPath} ${systemPath}\n sudo systemctl daemon-reload\n sudo systemctl enable --now cortex`);
551
+ clack.log.warn(t('init.service.noSudo'));
552
+ clack.log.info(t('init.service.manualInstallHint', { localPath, systemPath }));
536
553
  }
537
554
  }
538
555
  else {
539
- clack.log.warn(`Service registration is not supported on ${platform}. Start Cortex manually with \`cortex daemon\`.`);
556
+ clack.log.warn(t('init.service.unsupported', { platform }));
540
557
  }
541
558
  }
542
559
  // ─── Interactive prompts (TTY) ───────────────────────────────────
543
560
  function handleCancel(value) {
544
561
  if (clack.isCancel(value)) {
545
- clack.cancel('Init cancelled.');
562
+ clack.cancel(t('init.cancel'));
546
563
  process.exit(0);
547
564
  }
548
565
  }
549
566
  async function collectSlackConfig(prefill) {
550
- clack.note(SLACK_APP_MANIFEST, 'Slack App Manifest — copy and paste when creating the app');
551
- clack.note([
552
- 'To set up Slack, you need a Slack App:',
553
- '',
554
- '1. Go to https://api.slack.com/apps',
555
- '2. Click "Create New App" → "From a manifest"',
556
- '3. Select your workspace, then paste the manifest (shown above)',
557
- '4. Go to "Basic Information" → copy the Signing Secret',
558
- '5. Under Basic Information, generate an App-Level Token',
559
- ' (scope: connections:write, name it "cortex-socket")',
560
- '6. Go to "OAuth & Permissions" → Install to Workspace',
561
- ' Copy the *Bot User OAuth Token* after installing',
562
- '7. Go to "App Home" → Show Tabs → enable *Messages Tab*',
563
- ' and check "Allow users to send messages from the messages tab"',
564
- ' (required for DM support)',
565
- '',
566
- 'The manifest includes socket_mode_enabled, so Socket Mode',
567
- 'is automatically enabled when you import it.',
568
- '',
569
- 'Required Bot Token Scopes (included in manifest):',
570
- ' chat:write, im:history, im:write, reactions:read, reactions:write,',
571
- ' users:read, commands, app_mentions:read,',
572
- ' channels:history, channels:read, groups:history,',
573
- ' files:read, files:write, emoji:read, pins:read, pins:write',
574
- ].join('\n'), 'Slack App Setup Guide');
567
+ clack.note(SLACK_APP_MANIFEST, t('init.slack.manifestTitle'));
568
+ clack.note(t('init.slack.guide'), t('init.slack.guideTitle'));
575
569
  await promptCopyManifestToClipboard(SLACK_APP_MANIFEST);
576
570
  const hasPrefill = prefill && (prefill.signingSecret || prefill.appToken || prefill.botToken);
577
571
  let signingSecret;
578
572
  let appToken;
579
573
  let botToken;
580
- let adminChannelRaw;
581
574
  if (hasPrefill) {
582
- clack.log.info('Found existing Slack configuration. Press Enter to skip, or type anything to re-enter.');
575
+ clack.log.info(t('init.slack.prefillFound'));
583
576
  const skip = await clack.text({
584
- message: 'Skip Slack configuration? (Enter = skip, any key + Enter = re-enter)',
585
- placeholder: 'Press Enter to skip',
577
+ message: t('init.slack.skipPrompt'),
578
+ placeholder: t('init.slack.skipPlaceholder'),
586
579
  defaultValue: '',
587
580
  });
588
581
  handleCancel(skip);
@@ -591,200 +584,234 @@ async function collectSlackConfig(prefill) {
591
584
  signingSecret = prefill.signingSecret;
592
585
  appToken = prefill.appToken;
593
586
  botToken = prefill.botToken;
594
- adminChannelRaw = prefill.adminChannel ?? '';
595
587
  }
596
588
  }
597
589
  if (!signingSecret) {
598
590
  signingSecret = await clack.password({
599
- message: 'Step 1/4: SLACK_SIGNING_SECRET (from Basic Information):',
591
+ message: t('init.slack.signingSecretPrompt'),
600
592
  validate(value) {
601
593
  if (!value)
602
- return 'Signing secret is required.';
594
+ return t('init.slack.signingSecretRequired');
603
595
  },
604
596
  });
605
597
  handleCancel(signingSecret);
606
598
  appToken = await clack.password({
607
- message: 'Step 2/4: SLACK_APP_TOKEN (App-Level Token, starts with xapp-):',
599
+ message: t('init.slack.appTokenPrompt'),
608
600
  validate(value) {
609
601
  if (!value)
610
- return 'App token is required.';
602
+ return t('init.slack.appTokenRequired');
611
603
  if (!value.startsWith('xapp-'))
612
- return 'Token should start with xapp-';
604
+ return t('init.slack.appTokenPrefix');
613
605
  },
614
606
  });
615
607
  handleCancel(appToken);
616
608
  botToken = await clack.password({
617
- message: 'Step 3/4: SLACK_BOT_TOKEN (Bot User OAuth Token, starts with xoxb-):',
609
+ message: t('init.slack.botTokenPrompt'),
618
610
  validate(value) {
619
611
  if (!value)
620
- return 'Bot token is required.';
612
+ return t('init.slack.botTokenRequired');
621
613
  if (!value.startsWith('xoxb-'))
622
- return 'Token should start with xoxb-';
614
+ return t('init.slack.botTokenPrefix');
623
615
  },
624
616
  });
625
617
  handleCancel(botToken);
626
- adminChannelRaw = await clack.text({
627
- message: 'Step 4/4: CORTEX_ADMIN_CHANNEL (optional — Slack channel ID for admin notifications):',
628
- placeholder: 'e.g. C0123456789 or D0123456789 (leave blank to configure later)',
629
- initialValue: prefill?.adminChannel,
630
- });
631
- handleCancel(adminChannelRaw);
632
618
  }
633
619
  return {
634
620
  signingSecret: signingSecret,
635
621
  appToken: appToken,
636
622
  botToken: botToken,
637
- adminChannel: adminChannelRaw.trim() || undefined,
638
623
  };
639
624
  }
640
625
  async function collectFeishuConfig() {
641
- clack.note([
642
- 'To set up Feishu (飞书), create a Feishu app:',
643
- '',
644
- '1. Go to https://open.feishu.cn/app',
645
- '2. Create a new app with bot capability enabled',
646
- '3. Get App ID and App Secret from "Credentials & Basic Info"',
647
- '4. Enable bot events and subscribe to: im.message.receive_v1',
648
- '5. Publish the app and get it approved by your admin',
649
- ].join('\n'), 'Feishu App Setup Guide');
626
+ clack.note(t('init.feishu.guide'), t('init.feishu.guideTitle'));
650
627
  const appId = await clack.text({
651
- message: 'FEISHU_APP_ID:',
628
+ message: t('init.feishu.appIdPrompt'),
652
629
  validate(value) {
653
630
  if (!value)
654
- return 'App ID is required.';
631
+ return t('init.feishu.appIdRequired');
655
632
  },
656
633
  });
657
634
  handleCancel(appId);
658
635
  const appSecret = await clack.password({
659
- message: 'FEISHU_APP_SECRET:',
636
+ message: t('init.feishu.appSecretPrompt'),
660
637
  validate(value) {
661
638
  if (!value)
662
- return 'App secret is required.';
639
+ return t('init.feishu.appSecretRequired');
663
640
  },
664
641
  });
665
642
  handleCancel(appSecret);
666
- const encryptKeyRaw = await clack.text({
667
- message: 'FEISHU_ENCRYPT_KEY (optional):',
668
- placeholder: 'leave blank to skip',
669
- });
670
- handleCancel(encryptKeyRaw);
671
- const verificationTokenRaw = await clack.text({
672
- message: 'FEISHU_VERIFICATION_TOKEN (optional):',
673
- placeholder: 'leave blank to skip',
674
- });
675
- handleCancel(verificationTokenRaw);
676
643
  const domainRaw = await clack.text({
677
- message: 'FEISHU_DOMAIN (optional, "feishu" or "lark"):',
678
- placeholder: 'feishu (leave blank to use default)',
644
+ message: t('init.feishu.domainPrompt'),
645
+ placeholder: t('init.feishu.domainPlaceholder'),
679
646
  });
680
647
  handleCancel(domainRaw);
681
648
  const domainVal = domainRaw.trim().toLowerCase();
682
649
  const domain = (domainVal === 'feishu' || domainVal === 'lark')
683
650
  ? domainVal
684
651
  : undefined;
652
+ const authMode = await clack.select({
653
+ message: t('init.feishu.authModePrompt'),
654
+ options: [
655
+ { value: 'bot', label: t('init.feishu.authModeBotLabel'), hint: t('init.feishu.authModeBotHint') },
656
+ { value: 'user', label: t('init.feishu.authModeUserLabel'), hint: t('init.feishu.authModeUserHint') },
657
+ ],
658
+ initialValue: 'user',
659
+ });
660
+ handleCancel(authMode);
685
661
  return {
686
662
  appId: appId,
687
663
  appSecret: appSecret,
688
- encryptKey: encryptKeyRaw.trim() || undefined,
689
- verificationToken: verificationTokenRaw.trim() || undefined,
690
664
  domain,
665
+ authMode: authMode,
691
666
  };
692
667
  }
668
+ /**
669
+ * Run the Feishu user-identity login inline during init (OAuth device-authorization flow).
670
+ * Invoked right after the operator selects authMode='user' so they authorize in one sitting
671
+ * instead of having to run `cortex feishu login` afterwards.
672
+ *
673
+ * Credentials are passed via deps.env (no .env on disk yet at questionnaire time), and the token
674
+ * is written next to the .env (CONFIG_DIR/feishu-user-token.json) so it matches the --home target
675
+ * even when that differs from the module-level CONFIG_DIR. Best-effort: returns the CliResult and
676
+ * never throws, so a failed/abandoned login does not abort init — the operator can retry later.
677
+ */
678
+ export async function runFeishuUserLogin(config, configDir, deps = {}) {
679
+ const cmd = deps.cmdFeishuImpl ?? cmdFeishu;
680
+ const out = deps.stdout ?? ((s) => process.stdout.write(s));
681
+ const env = {
682
+ ...process.env,
683
+ FEISHU_APP_ID: config.appId,
684
+ FEISHU_APP_SECRET: config.appSecret,
685
+ };
686
+ if (config.domain)
687
+ env.FEISHU_DOMAIN = config.domain;
688
+ const tokenFile = path.join(configDir, 'feishu-user-token.json');
689
+ const result = await cmd(['login'], { env, tokenFile, loadDotenv: false });
690
+ if (result.stdout)
691
+ out(result.stdout);
692
+ if (result.exitCode !== 0 && result.stderr)
693
+ out(result.stderr);
694
+ return result;
695
+ }
693
696
  async function collectAnswersInteractive(paths) {
694
- clack.intro('Cortex Setup');
697
+ // Step 0: Language selection — shown first and bilingually (the prompt itself is always
698
+ // bilingual since no choice has been made yet). The option pre-selected as the default is
699
+ // inferred from the system locale (Chinese system → 中文 highlighted, otherwise English), so a
700
+ // Chinese user can just press Enter. The choice is applied immediately via setLocale() so every
701
+ // subsequent prompt renders in that language, and persisted to config/preferences.json.
702
+ const detected = detectSystemLocale();
703
+ const langSel = await clack.select({
704
+ message: 'Select language / 选择语言',
705
+ options: [
706
+ { value: 'en', label: 'English' },
707
+ { value: 'zh', label: '中文 (Simplified Chinese)' },
708
+ ],
709
+ initialValue: detected,
710
+ });
711
+ handleCancel(langSel);
712
+ const lang = langSel;
713
+ setLocale(lang);
714
+ clack.intro(t('init.intro'));
695
715
  // Step 1: Backend selection
696
- clack.note('Both Claude Code and PI support API key access to any model.', 'Backend info');
716
+ clack.note(t('init.backend.noteBody'), t('init.backend.noteTitle'));
697
717
  const backends = await clack.multiselect({
698
- message: 'Which backends would you like to use?',
718
+ message: t('init.backend.prompt'),
699
719
  options: [
700
- { value: 'claude', label: 'Claude Code', hint: 'recommended, for Claude subscription' },
701
- { value: 'pi', label: 'PI', hint: 'for other subscription' },
720
+ { value: 'claude', label: t('init.backend.claudeLabel'), hint: t('init.backend.claudeHint') },
721
+ { value: 'pi', label: t('init.backend.piLabel'), hint: t('init.backend.piHint') },
702
722
  ],
703
723
  required: true,
704
724
  });
705
725
  handleCancel(backends);
706
- // Step 2: Platform selection
707
- const platform = await clack.select({
708
- message: 'Which interaction platform would you like to use?',
726
+ // Step 2: Platform selection (multi-select — Slack and Feishu can run simultaneously).
727
+ // Leave empty to skip and configure platforms later by editing .env manually.
728
+ const platformsSel = await clack.multiselect({
729
+ message: t('init.platform.prompt'),
709
730
  options: [
710
- { value: 'slack', label: 'Slack', hint: 'recommended' },
711
- { value: 'none', label: 'Skip — configure later manually' },
731
+ { value: 'slack', label: t('init.platform.slackLabel'), hint: t('init.platform.slackHint') },
732
+ { value: 'feishu', label: t('init.platform.feishuLabel') },
712
733
  ],
734
+ required: false,
713
735
  });
714
- handleCancel(platform);
715
- // Step 2b: Platform-specific token input
736
+ handleCancel(platformsSel);
737
+ const platforms = platformsSel;
738
+ // Step 2b: Platform-specific setup & token input — walk each selected platform in turn,
739
+ // showing its creation guide and collecting its credentials one at a time.
716
740
  let slackConfig;
717
741
  let feishuConfig;
718
- if (platform === 'slack') {
742
+ if (platforms.includes('slack')) {
719
743
  const envPath = path.join(paths.CONFIG_DIR, '.env');
720
744
  const existingSlackConfig = parseExistingEnvSlackConfig(envPath);
721
745
  slackConfig = await collectSlackConfig(existingSlackConfig ?? undefined);
722
746
  }
723
- else if (platform === 'feishu') {
747
+ if (platforms.includes('feishu')) {
724
748
  feishuConfig = await collectFeishuConfig();
749
+ // user identity → continue straight into the device-flow login (rather than only printing a
750
+ // hint to run `cortex feishu login` later). Best-effort: a failed/abandoned login won't abort
751
+ // init — credentials are already captured in feishuConfig and the operator can retry.
752
+ if (feishuConfig.authMode === 'user') {
753
+ clack.log.info(t('init.feishu.loginStarting'));
754
+ const res = await runFeishuUserLogin(feishuConfig, paths.CONFIG_DIR);
755
+ if (res.exitCode === 0) {
756
+ clack.log.success(t('init.feishu.loginComplete'));
757
+ }
758
+ else {
759
+ clack.log.warn(t('init.feishu.loginIncomplete'));
760
+ }
761
+ }
725
762
  }
726
763
  // Step 3: Machine identity
727
764
  const hostname = os.hostname();
728
765
  const machineName = await clack.text({
729
- message: 'Machine name for this device:',
766
+ message: t('init.machine.prompt'),
730
767
  placeholder: hostname,
731
768
  defaultValue: hostname,
732
769
  validate(value) {
733
770
  if (!value)
734
- return 'Machine name is required.';
771
+ return t('init.machine.required');
735
772
  },
736
773
  });
737
774
  handleCancel(machineName);
738
775
  // GPU detection
739
776
  const gpuCount = detectGpuCount();
740
777
  if (gpuCount > 0) {
741
- clack.log.success(`Detected ${gpuCount} NVIDIA GPU(s)`);
778
+ clack.log.success(t('init.machine.gpuDetected', { count: gpuCount }));
742
779
  }
743
780
  else {
744
- clack.log.info('No NVIDIA GPU detected (gpuCount=0)');
781
+ clack.log.info(t('init.machine.gpuNone'));
745
782
  }
746
783
  // Step 4: Gateway usage
747
- clack.note([
748
- 'Cortex includes an open-source local gateway that proxies all',
749
- 'LLM calls, providing multi-key rotation, automatic failover,',
750
- 'and per-request cost tracking.',
751
- '',
752
- 'You can optionally share anonymous token usage with aistatus.cc,',
753
- 'an AI model status monitoring site. Your token usage will appear',
754
- 'on the public leaderboard (name + org + token counts). Email is',
755
- 'used only as an identity key and is never displayed.',
756
- '',
757
- 'Learn more: https://aistatus.cc',
758
- ].join('\n'), 'Gateway & aistatus');
784
+ clack.note(t('init.gateway.note'), t('init.gateway.noteTitle'));
759
785
  const enableGateway = await clack.confirm({
760
- message: 'Enable token usage reporting to aistatus?',
786
+ message: t('init.gateway.enablePrompt'),
761
787
  initialValue: true,
762
788
  });
763
789
  handleCancel(enableGateway);
764
790
  let gatewayUsage = { enabled: false };
765
791
  if (enableGateway) {
766
- const name = await clack.text({ message: 'Name:', placeholder: 'your name' });
792
+ const name = await clack.text({ message: t('init.gateway.namePrompt'), placeholder: t('init.gateway.namePlaceholder') });
767
793
  handleCancel(name);
768
- const org = await clack.text({ message: 'Organization:', placeholder: 'your organization' });
794
+ const org = await clack.text({ message: t('init.gateway.orgPrompt'), placeholder: t('init.gateway.orgPlaceholder') });
769
795
  handleCancel(org);
770
796
  const email = await clack.text({
771
- message: 'Email (identity only, not displayed):',
772
- placeholder: 'you@example.com',
797
+ message: t('init.gateway.emailPrompt'),
798
+ placeholder: t('init.gateway.emailPlaceholder'),
773
799
  });
774
800
  handleCancel(email);
775
801
  gatewayUsage = { enabled: true, name: name, org: org, email: email };
776
802
  }
777
803
  // Step 5: Service registration
778
804
  const wantService = await clack.confirm({
779
- message: 'Register Cortex as a system service (auto-start on boot)?',
805
+ message: t('init.serviceRegister.prompt'),
780
806
  initialValue: true,
781
807
  });
782
808
  handleCancel(wantService);
783
809
  return {
810
+ lang,
784
811
  backends: backends,
785
812
  machineName: machineName,
786
813
  gpuCount,
787
- platform: platform,
814
+ platforms,
788
815
  slackConfig,
789
816
  feishuConfig,
790
817
  gatewayUsage,
@@ -800,55 +827,62 @@ async function collectAnswersNonInteractive() {
800
827
  }
801
828
  // Line format:
802
829
  // backends, platform, gatewayEnabled, name, org, email, installService
803
- // [+ platform-specific tokens: signingSecret, appToken, botToken, adminChannel (slack)]
830
+ // [+ platform-specific token blocks, concatenated in fixed order: slack first, then feishu]
831
+ // `platform` is a comma-separated list (e.g. "slack,feishu"); single values are back-compat.
804
832
  const [backendsRaw, platformRaw, gatewayEnabledRaw, name, org, email, installServiceRaw] = lines;
805
833
  const backends = (backendsRaw || 'claude')
806
834
  .split(',')
807
835
  .map(s => s.trim())
808
836
  .filter((s) => s === 'claude' || s === 'pi');
809
- const platform = (platformRaw && ['slack', 'feishu'].includes(platformRaw))
810
- ? platformRaw
811
- : 'none';
837
+ // Parse the platform list, keeping valid values in order and de-duplicating.
838
+ const platforms = [];
839
+ const seenPlatforms = new Set();
840
+ for (const raw of (platformRaw || '').split(',')) {
841
+ const p = raw.trim().toLowerCase();
842
+ if ((p === 'slack' || p === 'feishu') && !seenPlatforms.has(p)) {
843
+ seenPlatforms.add(p);
844
+ platforms.push(p);
845
+ }
846
+ }
812
847
  const gatewayEnabled = gatewayEnabledRaw?.toLowerCase() === 'y';
813
848
  log.info('Cortex Initialization (non-interactive)');
814
- // Parse platform-specific tokens from remaining lines (starting at index 7).
815
- // After platform tokens, optional planChoice and executeChoice lines (format "mode:model";
816
- // empty string → auto-infer). Index varies by platform:
817
- // none → planChoice at 7, executeChoice at 8
818
- // slack → planChoice at 11, executeChoice at 12
819
- // feishu → planChoice at 12, executeChoice at 13
849
+ // Parse platform token blocks from remaining lines (starting at index 7). Blocks are
850
+ // concatenated in fixed order — slack (3 lines), then feishu (3 lines) — regardless of the
851
+ // order given in the platform list. The profile-choice lines (optional "mode:model"; empty
852
+ // → auto-infer) follow whatever token lines were consumed. Single-platform layouts are
853
+ // back-compatible: slack-only → choices at 10; feishu-only → choices at 10.
820
854
  let slackConfig;
821
855
  let feishuConfig;
822
- let profileChoiceStart = 7;
823
- if (platform === 'slack' && lines.length >= 11) {
856
+ let cursor = 7;
857
+ if (platforms.includes('slack') && lines.length >= cursor + 3) {
824
858
  slackConfig = {
825
- signingSecret: lines[7] || '',
826
- appToken: lines[8] || '',
827
- botToken: lines[9] || '',
828
- adminChannel: lines[10]?.trim() || undefined,
859
+ signingSecret: lines[cursor] || '',
860
+ appToken: lines[cursor + 1] || '',
861
+ botToken: lines[cursor + 2] || '',
829
862
  };
830
- profileChoiceStart = 11;
863
+ cursor += 3;
831
864
  }
832
- else if (platform === 'feishu' && lines.length >= 12) {
833
- const domainVal = (lines[11] || '').trim().toLowerCase();
865
+ if (platforms.includes('feishu') && lines.length >= cursor + 3) {
866
+ const domainVal = (lines[cursor + 2] || '').trim().toLowerCase();
834
867
  feishuConfig = {
835
- appId: lines[7] || '',
836
- appSecret: lines[8] || '',
837
- encryptKey: lines[9]?.trim() || undefined,
838
- verificationToken: lines[10]?.trim() || undefined,
868
+ appId: lines[cursor] || '',
869
+ appSecret: lines[cursor + 1] || '',
839
870
  domain: (domainVal === 'feishu' || domainVal === 'lark')
840
871
  ? domainVal
841
872
  : undefined,
842
873
  };
843
- profileChoiceStart = 12;
874
+ cursor += 3;
844
875
  }
876
+ const profileChoiceStart = cursor;
845
877
  const planChoice = parseChoiceLine(lines[profileChoiceStart]);
846
878
  const executeChoice = parseChoiceLine(lines[profileChoiceStart + 1]);
879
+ const extraProfiles = parseExtraProfilesLine(lines[profileChoiceStart + 2]);
847
880
  return {
881
+ lang: process.env.CORTEX_LANG ? normalizeLocale(process.env.CORTEX_LANG) : detectSystemLocale(),
848
882
  backends: backends.length > 0 ? backends : ['claude'],
849
883
  machineName: os.hostname(),
850
884
  gpuCount: detectGpuCount(),
851
- platform,
885
+ platforms,
852
886
  slackConfig,
853
887
  feishuConfig,
854
888
  gatewayUsage: gatewayEnabled
@@ -857,6 +891,7 @@ async function collectAnswersNonInteractive() {
857
891
  installService: installServiceRaw?.toLowerCase() === 'y',
858
892
  planChoice,
859
893
  executeChoice,
894
+ extraProfiles,
860
895
  };
861
896
  }
862
897
  // ─── Directory creation ─────────────────────────────────────────
@@ -945,7 +980,7 @@ export function getGitInstallHint() {
945
980
  export function ensureGitInstalled() {
946
981
  if (isGitInstalled())
947
982
  return true;
948
- clack.log.warn('Git is required but was not found on your system.');
983
+ clack.log.warn(t('init.git.required'));
949
984
  // Build the auto-install command for the current platform
950
985
  let installCmd = null;
951
986
  if (process.platform === 'linux') {
@@ -968,22 +1003,22 @@ export function ensureGitInstalled() {
968
1003
  }
969
1004
  if (installCmd) {
970
1005
  const s = clack.spinner();
971
- s.start('Attempting automatic git installation...');
1006
+ s.start(t('init.git.autoInstalling'));
972
1007
  try {
973
1008
  execSync(installCmd, { stdio: 'pipe', timeout: 120_000 });
974
- s.stop('Git installed successfully.');
1009
+ s.stop(t('init.git.installed'));
975
1010
  // Verify the install actually put git on PATH
976
1011
  if (isGitInstalled())
977
1012
  return true;
978
- clack.log.warn('Git was installed but is not on PATH. You may need to restart your shell.');
1013
+ clack.log.warn(t('init.git.notOnPath'));
979
1014
  }
980
1015
  catch (err) {
981
- s.stop('Automatic installation failed.');
1016
+ s.stop(t('init.git.autoInstallFailed'));
982
1017
  clack.log.warn(err.message);
983
1018
  }
984
1019
  }
985
1020
  const hint = getGitInstallHint();
986
- clack.log.info(`Please install git manually: ${hint}`);
1021
+ clack.log.info(t('init.git.manualHint', { hint }));
987
1022
  return false;
988
1023
  }
989
1024
  // ─── Git repo initialization ────────────────────────────────────
@@ -994,7 +1029,7 @@ function ensureGitRepo(dataDir) {
994
1029
  execSync('git init', { cwd: dataDir, stdio: 'pipe' });
995
1030
  }
996
1031
  catch (err) {
997
- clack.log.warn(`git init failed: ${err.message}`);
1032
+ clack.log.warn(t('init.git.initFailed', { message: err.message }));
998
1033
  }
999
1034
  }
1000
1035
  // ─── Safe copy helpers ──────────────────────────────────────────
@@ -1076,7 +1111,7 @@ function deployHooks(paths, force) {
1076
1111
  safeCopy(src, dst, force, `hooks/${file}`);
1077
1112
  }
1078
1113
  }
1079
- function generateConfigs(paths, answers, force) {
1114
+ export function generateConfigs(paths, answers, force) {
1080
1115
  // MCP configs — always regenerate (machine-specific, in .gitignore)
1081
1116
  writeFileSync(path.join(paths.CONFIG_DIR, 'mcp-config.json'), JSON.stringify(buildFullConfig(INSTALL_ROOT), null, 2));
1082
1117
  writeFileSync(path.join(paths.CONFIG_DIR, 'mcp-config-core.json'), JSON.stringify(buildCoreConfig(INSTALL_ROOT), null, 2));
@@ -1087,6 +1122,12 @@ function generateConfigs(paths, answers, force) {
1087
1122
  const primaryBackend = answers.backends[0] || 'claude';
1088
1123
  writeFileSync(modeJsonPath, generateDefaultModeJson(primaryBackend));
1089
1124
  }
1125
+ // preferences.json — operator UI language (read at startup by domain/system/preferences.ts).
1126
+ // Skip if exists (user may have changed it via !lang) unless --force.
1127
+ const prefsJsonPath = path.join(paths.CONFIG_DIR, 'preferences.json');
1128
+ if (!existsSync(prefsJsonPath) || force) {
1129
+ writeFileSync(prefsJsonPath, JSON.stringify({ lang: answers.lang }, null, 2) + '\n');
1130
+ }
1090
1131
  // machines.json — runtime machine registry, server won't start without it
1091
1132
  const machinesJsonPath = path.join(paths.CONFIG_DIR, 'machines.json');
1092
1133
  if (!existsSync(machinesJsonPath) || force) {
@@ -1100,8 +1141,9 @@ function generateConfigs(paths, answers, force) {
1100
1141
  }
1101
1142
  /**
1102
1143
  * Seed schedules.json from defaults/data/schedules.json into STORE_DIR.
1103
- * Replaces __ADMIN_CHANNEL__ placeholder with the configured admin channel,
1104
- * and stamps createdAt with the current timestamp. Never overwrites existing file.
1144
+ * The __ADMIN_CHANNEL__ placeholder resolves to an empty channel: the admin channel is
1145
+ * auto-detected at runtime (first DM to the bot) rather than collected during init.
1146
+ * Stamps createdAt with the current timestamp. Never overwrites existing file.
1105
1147
  */
1106
1148
  function seedSchedules(paths, answers, force) {
1107
1149
  const dstPath = path.join(paths.STORE_DIR, 'schedules.json');
@@ -1110,7 +1152,7 @@ function seedSchedules(paths, answers, force) {
1110
1152
  const srcPath = path.join(DEFAULTS_DIR, 'data', 'schedules.json');
1111
1153
  if (!existsSync(srcPath))
1112
1154
  return;
1113
- const adminChannel = answers.slackConfig?.adminChannel || '';
1155
+ const adminChannel = '';
1114
1156
  const now = Date.now();
1115
1157
  let content = readFileSync(srcPath, 'utf-8');
1116
1158
  content = content.replace(/__ADMIN_CHANNEL__/g, adminChannel);
@@ -1155,7 +1197,7 @@ async function pickPlanExecuteInteractive(endpoints, configDir) {
1155
1197
  // If existing profiles.json has plan/execute, ask before overwriting
1156
1198
  if (detectExistingPlanOrExecute(configDir)) {
1157
1199
  const confirm = await clack.confirm({
1158
- message: 'Existing `plan` or `execute` profile detected. Overwrite with a new selection?',
1200
+ message: t('init.gatewaySetup.overwritePrompt'),
1159
1201
  initialValue: false,
1160
1202
  });
1161
1203
  handleCancel(confirm);
@@ -1178,13 +1220,13 @@ async function pickPlanExecuteInteractive(endpoints, configDir) {
1178
1220
  // Default = first lexicographic entry (no tier inference).
1179
1221
  const firstChoiceValue = formatValue(choices[0]);
1180
1222
  const planSel = await clack.select({
1181
- message: 'Pick model for the `plan` profile (used by executor agents — planner, doc-writer, coder, etc.):',
1223
+ message: t('init.gatewaySetup.planPrompt'),
1182
1224
  options,
1183
1225
  initialValue: firstChoiceValue,
1184
1226
  });
1185
1227
  handleCancel(planSel);
1186
1228
  const execSel = await clack.select({
1187
- message: 'Pick model for the `execute` profile (used by reviewer agents — reviewer, doc-reviewer, coder-reviewer, etc.):',
1229
+ message: t('init.gatewaySetup.executePrompt'),
1188
1230
  options,
1189
1231
  initialValue: firstChoiceValue,
1190
1232
  });
@@ -1199,7 +1241,7 @@ async function pickPlanExecuteInteractive(endpoints, configDir) {
1199
1241
  let planFallback;
1200
1242
  if (planFallbackOptions.length > 0) {
1201
1243
  const sel = await clack.multiselect({
1202
- message: 'Pick fallback models for `plan` (in order, space to toggle, enter to confirm, leave empty for no fallback):',
1244
+ message: t('init.gatewaySetup.planFallbackPrompt'),
1203
1245
  options: planFallbackOptions,
1204
1246
  required: false,
1205
1247
  initialValues: [],
@@ -1212,7 +1254,7 @@ async function pickPlanExecuteInteractive(endpoints, configDir) {
1212
1254
  let executeFallback;
1213
1255
  if (execFallbackOptions.length > 0) {
1214
1256
  const sel = await clack.multiselect({
1215
- message: 'Pick fallback models for `execute` (in order, space to toggle, enter to confirm, leave empty for no fallback):',
1257
+ message: t('init.gatewaySetup.executeFallbackPrompt'),
1216
1258
  options: execFallbackOptions,
1217
1259
  required: false,
1218
1260
  initialValues: [],
@@ -1222,35 +1264,57 @@ async function pickPlanExecuteInteractive(endpoints, configDir) {
1222
1264
  if (arr.length > 0)
1223
1265
  executeFallback = arr.map(parseValue);
1224
1266
  }
1267
+ // ── Extra profiles: additional models to register as standalone named profiles ──
1268
+ let extraProfiles;
1269
+ if (options.length > 0) {
1270
+ const sel = await clack.multiselect({
1271
+ message: t('init.gatewaySetup.extraProfilesPrompt'),
1272
+ options,
1273
+ required: false,
1274
+ initialValues: [],
1275
+ });
1276
+ handleCancel(sel);
1277
+ const arr = sel;
1278
+ if (arr.length > 0)
1279
+ extraProfiles = arr.map(parseValue);
1280
+ }
1225
1281
  return {
1226
1282
  planChoice,
1227
1283
  executeChoice: execChoice,
1228
1284
  planFallback,
1229
1285
  executeFallback,
1286
+ extraProfiles,
1230
1287
  overwrite: true,
1231
1288
  };
1232
1289
  }
1233
1290
  async function runGatewaySetup(backends, paths, gatewayConfigDir, answers) {
1234
- // Discover endpoints from Claude/PI local configs
1235
- const endpoints = discoverEndpoints();
1291
+ // Discover endpoints from Claude/PI local configs — filtered by user-selected backends
1292
+ const endpoints = discoverEndpoints(backends);
1236
1293
  if (endpoints.length === 0) {
1237
- clack.log.warn('No backends discovered. Make sure you have logged into Claude Code and/or PI first.');
1238
- clack.log.info('You can re-run detection later with: cortex setup-gateway');
1294
+ clack.log.warn(t('init.gatewaySetup.noBackends'));
1295
+ clack.log.info(t('init.gatewaySetup.rerunHint'));
1239
1296
  return;
1240
1297
  }
1241
1298
  // Show discovered summary
1242
1299
  const summary = endpoints.map(ep => ` ${ep.mode}/${ep.endpoint}: ${ep.models.slice(0, 3).join(', ')}${ep.models.length > 3 ? ', ...' : ''} (${ep.keys.length > 0 ? 'with key' : 'passthrough'})`).join('\n');
1243
- clack.log.success(`Discovered ${endpoints.length} endpoint modes:\n${summary}`);
1300
+ clack.log.success(t('init.gatewaySetup.discovered', { count: endpoints.length, summary }));
1244
1301
  // Generate gateway.yaml — scoped to gatewayConfigDir when provided (test/alt env),
1245
- // otherwise defaults to ~/.aistatus/gateway.yaml (production).
1246
- const yamlContent = generateGatewayYaml(endpoints);
1247
- const gatewayPath = writeGatewayYaml(yamlContent, gatewayConfigDir);
1248
- clack.log.success(`Gateway config written to ${gatewayPath}`);
1249
- // Resolve plan/execute choices + fallback chains + overwrite intent.
1302
+ // otherwise defaults to ~/.aistatus/gateway.yaml (production). Merge-aware: preserves
1303
+ // hand-maintained modes/keys and never drops previously-configured modes if discovery
1304
+ // under-reports (e.g. a transient `pi --list-models` failure).
1305
+ const { path: gatewayPath, result: mergeResult } = writeMergedGatewayYaml(endpoints, gatewayConfigDir);
1306
+ clack.log.success(t('init.gatewaySetup.gatewayWritten', { path: gatewayPath }));
1307
+ if (mergeResult.droppedFromDiscovery.length > 0) {
1308
+ const list = mergeResult.droppedFromDiscovery.map(p => `${p.mode}/${p.endpoint}`).join(', ');
1309
+ clack.log.warn(t('init.gatewaySetup.preservedModes', { count: mergeResult.droppedFromDiscovery.length, list }));
1310
+ clack.log.info(t('init.gatewaySetup.preservedModesHint'));
1311
+ }
1312
+ // Resolve plan/execute choices + fallback chains + extra profiles + overwrite intent.
1250
1313
  let planChoice = answers?.planChoice;
1251
1314
  let executeChoice = answers?.executeChoice;
1252
1315
  let planFallback;
1253
1316
  let executeFallback;
1317
+ let extraProfiles = answers?.extraProfiles;
1254
1318
  let overwrite;
1255
1319
  if (processStdin.isTTY) {
1256
1320
  // Interactive: prompt for selection (with overwrite confirmation if needed)
@@ -1259,6 +1323,7 @@ async function runGatewaySetup(backends, paths, gatewayConfigDir, answers) {
1259
1323
  executeChoice = picked.executeChoice ?? executeChoice;
1260
1324
  planFallback = picked.planFallback;
1261
1325
  executeFallback = picked.executeFallback;
1326
+ extraProfiles = picked.extraProfiles ?? extraProfiles;
1262
1327
  overwrite = picked.overwrite;
1263
1328
  }
1264
1329
  else {
@@ -1274,13 +1339,22 @@ async function runGatewaySetup(backends, paths, gatewayConfigDir, answers) {
1274
1339
  executeChoice,
1275
1340
  planFallback,
1276
1341
  executeFallback,
1342
+ extraProfiles,
1277
1343
  overwrite,
1278
1344
  });
1279
- clack.log.success(`Profiles written to ${profilesPath}`);
1345
+ clack.log.success(t('init.gatewaySetup.profilesWritten', { path: profilesPath }));
1280
1346
  // Show profile summary (reflects what was actually generated, not what was merged)
1281
- const profiles = generateProfiles(endpoints, { planChoice, executeChoice, planFallback, executeFallback });
1347
+ const profiles = generateProfiles(endpoints, { planChoice, executeChoice, planFallback, executeFallback, extraProfiles });
1282
1348
  const profileNames = Object.keys(profiles.profiles).join(', ');
1283
- clack.log.info(`Generated profiles: ${profileNames} (default: ${profiles.defaultProfile})`);
1349
+ clack.log.info(t('init.gatewaySetup.generatedProfiles', { names: profileNames, default: profiles.defaultProfile }));
1350
+ // Validate profile ↔ gateway mode coupling. A profile referencing a non-existent gateway mode is
1351
+ // exactly what produces a silent `400 Unknown mode: <x>` at runtime. Non-fatal — warn only.
1352
+ const issues = validateProfilesAgainstGateway(mergeResult.endpoints, paths.CONFIG_DIR);
1353
+ if (issues.length > 0) {
1354
+ const lines = issues.map(i => ` - ${i.profile}: ${i.reason}`).join('\n');
1355
+ clack.log.warn(t('init.gatewaySetup.profileIssues', { count: issues.length, lines }));
1356
+ clack.log.info(t('init.gatewaySetup.profileIssuesHint'));
1357
+ }
1284
1358
  }
1285
1359
  export async function runInit(options = {}) {
1286
1360
  const paths = getResolvedPaths(options.homeDir);
@@ -1302,30 +1376,46 @@ export async function runInit(options = {}) {
1302
1376
  generateConfigs(paths, answers, force);
1303
1377
  seedSchedules(paths, answers, force);
1304
1378
  // 5. Gateway usage
1305
- writeGatewayUsageConfig(answers.gatewayUsage, paths.CONFIG_DIR);
1379
+ writeGatewayUsageConfig(answers.gatewayUsage, options.gatewayConfigDir);
1306
1380
  // 6. Service registration
1307
1381
  if (answers.installService) {
1308
1382
  installService(paths.DATA_DIR);
1309
1383
  }
1310
1384
  // 7. Gateway & profile auto-setup (detect from Claude/PI local configs)
1311
1385
  if (processStdin.isTTY) {
1312
- clack.note([
1313
- 'Cortex can auto-detect your Claude Code and PI configurations',
1314
- 'to generate gateway.yaml and profiles.json automatically.',
1315
- '',
1316
- 'Make sure you have logged into:',
1317
- ' • Claude Code: claude login',
1318
- ' • PI: pi login (if using PI)',
1319
- ].join('\n'), 'Gateway & Profile Setup');
1320
- const ready = await clack.confirm({
1321
- message: 'Have you logged into Claude Code and/or PI? Ready to auto-detect?',
1322
- initialValue: true,
1323
- });
1324
- if (!clack.isCancel(ready) && ready) {
1325
- await runGatewaySetup(answers.backends, paths, options.gatewayConfigDir, answers);
1326
- }
1327
- else {
1328
- clack.log.info('Skipped. Run `cortex setup-gateway` later to auto-configure.');
1386
+ const loginHints = answers.backends.map(b => {
1387
+ const info = BACKEND_INFO[b];
1388
+ return ` • ${t(info.labelKey)}: ${t(info.loginHintKey).replace(/^Run /, '').replace(/\.$/, '')}`;
1389
+ }).join('\n');
1390
+ clack.note(t('init.gatewayProfile.note', { loginHints }), t('init.gatewayProfile.noteTitle'));
1391
+ let gatewayDone = false;
1392
+ while (!gatewayDone) {
1393
+ const ready = await clack.confirm({
1394
+ message: t('init.gatewayProfile.readyPrompt'),
1395
+ initialValue: true,
1396
+ });
1397
+ handleCancel(ready);
1398
+ if (ready) {
1399
+ await runGatewaySetup(answers.backends, paths, options.gatewayConfigDir, answers);
1400
+ gatewayDone = true;
1401
+ }
1402
+ else {
1403
+ // User hasn't logged in yet — let them choose to go log in or skip entirely
1404
+ clack.log.info(t('init.gatewayProfile.loginNow', { loginHints }));
1405
+ const action = await clack.select({
1406
+ message: t('init.gatewayProfile.actionPrompt'),
1407
+ options: [
1408
+ { value: 'retry', label: t('init.gatewayProfile.retryLabel') },
1409
+ { value: 'skip', label: t('init.gatewayProfile.skipLabel') },
1410
+ ],
1411
+ });
1412
+ handleCancel(action);
1413
+ if (action === 'skip') {
1414
+ clack.log.info(t('init.gatewayProfile.skipped'));
1415
+ gatewayDone = true;
1416
+ }
1417
+ // action === 'retry' → loop continues, re-prompt the confirm
1418
+ }
1329
1419
  }
1330
1420
  }
1331
1421
  else {
@@ -1355,5 +1445,5 @@ export async function runInit(options = {}) {
1355
1445
  log.warn(`Failed to update activeProfile in mode.json: ${e.message}`);
1356
1446
  }
1357
1447
  // 9. Done
1358
- clack.outro(`Cortex initialized at ${paths.DATA_DIR}. Run \`cortex start\` to launch.`);
1448
+ clack.outro(t('init.outro', { dataDir: paths.DATA_DIR }));
1359
1449
  }