@cortex-agent/server 2026.5.25 → 2026.6.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (355) hide show
  1. package/defaults/config/thread-templates.json +28 -1
  2. package/defaults/hooks/cortex-md-injector.mjs +47 -31
  3. package/defaults/hooks/post-task-hook.mjs +6 -0
  4. package/defaults/hooks/task-status-check.mjs +8 -0
  5. package/defaults/mcp-config-slack.json +11 -0
  6. package/defaults/plugins/cortex-stage-gate/skills/task/SKILL.md +18 -0
  7. package/defaults/plugins/cortex-system/skills/schedule/SKILL.md +5 -6
  8. package/defaults/prompts/directives/manager.md +67 -0
  9. package/dist/agent-adapter/claude/adapter-tui.d.ts +35 -3
  10. package/dist/agent-adapter/claude/adapter-tui.js +91 -12
  11. package/dist/agent-adapter/claude/adapter.js +11 -0
  12. package/dist/agent-adapter/claude/defaults.d.ts +30 -0
  13. package/dist/agent-adapter/claude/defaults.js +30 -0
  14. package/dist/agent-adapter/claude/jsonl-tail.d.ts +2 -2
  15. package/dist/agent-adapter/claude/jsonl-tail.js +25 -20
  16. package/dist/agent-adapter/claude/spawn-args.d.ts +11 -0
  17. package/dist/agent-adapter/claude/spawn-args.js +49 -7
  18. package/dist/agent-adapter/claude/tmux-control.d.ts +20 -0
  19. package/dist/agent-adapter/claude/tmux-control.js +54 -8
  20. package/dist/agent-adapter/codex/adapter.js +1 -1
  21. package/dist/agent-adapter/normalize/event-types.d.ts +1 -0
  22. package/dist/agent-adapter/pi/adapter.js +46 -19
  23. package/dist/agent-adapter/pi/agent-dir.d.ts +21 -0
  24. package/dist/agent-adapter/pi/agent-dir.js +53 -2
  25. package/dist/agent-adapter/pi/event-parser.js +13 -1
  26. package/dist/agent-adapter/pi/mcp-bridge.d.ts +12 -0
  27. package/dist/agent-adapter/pi/mcp-bridge.js +47 -9
  28. package/dist/agent-adapter/pi/tool-shims.d.ts +14 -0
  29. package/dist/agent-adapter/pi/tool-shims.js +167 -140
  30. package/dist/agent-adapter/types.d.ts +7 -2
  31. package/dist/core/atomic-write.js +21 -0
  32. package/dist/core/config-generator.d.ts +10 -0
  33. package/dist/core/config-generator.js +28 -0
  34. package/dist/core/gateway-generator.d.ts +77 -7
  35. package/dist/core/gateway-generator.js +301 -29
  36. package/dist/core/icons.d.ts +68 -0
  37. package/dist/core/icons.js +67 -0
  38. package/dist/core/profile-generator.d.ts +6 -0
  39. package/dist/core/profile-generator.js +35 -7
  40. package/dist/core/running-executions.d.ts +51 -41
  41. package/dist/core/running-executions.js +120 -73
  42. package/dist/core/status-format.js +3 -2
  43. package/dist/core/task-parser.d.ts +3 -0
  44. package/dist/core/task-parser.js +3 -1
  45. package/dist/core/types/thread-types.d.ts +54 -8
  46. package/dist/domain/agents/facade.d.ts +18 -0
  47. package/dist/domain/agents/facade.js +26 -3
  48. package/dist/domain/agents/profile-manager.d.ts +11 -0
  49. package/dist/domain/agents/profile-manager.js +21 -2
  50. package/dist/domain/costs/codex-usage-monitor.js +2 -1
  51. package/dist/domain/costs/rate-limit-throttle.js +14 -2
  52. package/dist/domain/executions/registry.d.ts +24 -0
  53. package/dist/domain/executions/registry.js +38 -0
  54. package/dist/domain/mcp/core-server.js +15 -3
  55. package/dist/domain/mcp/feishu/bitable.d.ts +3 -0
  56. package/dist/domain/mcp/feishu/bitable.js +168 -0
  57. package/dist/domain/mcp/feishu/block-types.d.ts +44 -0
  58. package/dist/domain/mcp/feishu/block-types.js +127 -0
  59. package/dist/domain/mcp/feishu/blocks-to-text.d.ts +19 -0
  60. package/dist/domain/mcp/feishu/blocks-to-text.js +43 -0
  61. package/dist/domain/mcp/feishu/client.d.ts +46 -0
  62. package/dist/domain/mcp/feishu/client.js +87 -0
  63. package/dist/domain/mcp/feishu/docx.d.ts +3 -0
  64. package/dist/domain/mcp/feishu/docx.js +163 -0
  65. package/dist/domain/mcp/feishu/drive.d.ts +23 -0
  66. package/dist/domain/mcp/feishu/drive.js +66 -0
  67. package/dist/domain/mcp/feishu/file.d.ts +14 -0
  68. package/dist/domain/mcp/feishu/file.js +107 -0
  69. package/dist/domain/mcp/feishu/index.d.ts +6 -0
  70. package/dist/domain/mcp/feishu/index.js +61 -0
  71. package/dist/domain/mcp/feishu/markdown-to-blocks.d.ts +40 -0
  72. package/dist/domain/mcp/feishu/markdown-to-blocks.js +191 -0
  73. package/dist/domain/mcp/feishu/sheets.d.ts +3 -0
  74. package/dist/domain/mcp/feishu/sheets.js +119 -0
  75. package/dist/domain/mcp/feishu/types.d.ts +26 -0
  76. package/dist/domain/mcp/feishu/types.js +38 -0
  77. package/dist/domain/mcp/feishu/user-auth.d.ts +140 -0
  78. package/dist/domain/mcp/feishu/user-auth.js +286 -0
  79. package/dist/domain/mcp/feishu/wiki.d.ts +3 -0
  80. package/dist/domain/mcp/feishu/wiki.js +77 -0
  81. package/dist/domain/mcp/feishu-server.d.ts +2 -0
  82. package/dist/domain/mcp/feishu-server.js +33 -0
  83. package/dist/domain/mcp/server.d.ts +0 -1
  84. package/dist/domain/mcp/server.js +6 -25
  85. package/dist/domain/mcp/slack-server.d.ts +3 -0
  86. package/dist/domain/mcp/slack-server.js +46 -0
  87. package/dist/domain/mcp/tools/context.js +1 -1
  88. package/dist/domain/mcp/tools/schedule.d.ts +1 -1
  89. package/dist/domain/mcp/tools/schedule.js +6 -20
  90. package/dist/domain/mcp/tools/slack.js +20 -7
  91. package/dist/domain/mcp/tools/thread-ops.d.ts +2 -0
  92. package/dist/domain/mcp/tools/thread-ops.js +121 -0
  93. package/dist/domain/mcp/tools/time.d.ts +2 -0
  94. package/dist/domain/mcp/tools/time.js +66 -0
  95. package/dist/domain/mcp/tools/tui-ask.js +1 -1
  96. package/dist/domain/mcp/tools/tui-plan.js +2 -2
  97. package/dist/domain/mcp/tui-server.js +1 -0
  98. package/dist/domain/monitor/disk-monitor.js +2 -1
  99. package/dist/domain/monitor/gpu-monitor.js +2 -1
  100. package/dist/domain/remote/client-hot-reload.js +3 -2
  101. package/dist/domain/remote/client-manager.js +8 -6
  102. package/dist/domain/scheduling/job-registry.d.ts +4 -0
  103. package/dist/domain/scheduling/job-registry.js +1 -0
  104. package/dist/domain/scheduling/jobs/_shared.js +2 -1
  105. package/dist/domain/scheduling/jobs/memory-index-regen.js +3 -2
  106. package/dist/domain/scheduling/jobs/scheduled-task.js +9 -23
  107. package/dist/domain/scheduling/jobs/sync-public.js +4 -3
  108. package/dist/domain/scheduling/jobs/target-dispatch.d.ts +1 -8
  109. package/dist/domain/scheduling/jobs/target-dispatch.js +0 -7
  110. package/dist/domain/scheduling/jobs/task-archive.js +3 -2
  111. package/dist/domain/scheduling/jobs/task-dispatch.js +120 -10
  112. package/dist/domain/scheduling/schedule-command.js +16 -15
  113. package/dist/domain/scheduling/scheduler.d.ts +1 -1
  114. package/dist/domain/scheduling/scheduler.js +2 -1
  115. package/dist/domain/sessions/session-hooks.d.ts +2 -2
  116. package/dist/domain/sessions/session-hooks.js +19 -18
  117. package/dist/domain/sessions/session-lifecycle.d.ts +38 -0
  118. package/dist/domain/sessions/session-lifecycle.js +44 -0
  119. package/dist/domain/system/install-cli.d.ts +7 -0
  120. package/dist/domain/system/install-cli.js +106 -0
  121. package/dist/domain/system/server-update-check.js +2 -2
  122. package/dist/domain/tasks/dispatch-utils.d.ts +58 -1
  123. package/dist/domain/tasks/dispatch-utils.js +53 -4
  124. package/dist/domain/tasks/dispatcher.js +26 -0
  125. package/dist/domain/tasks/lint.js +28 -0
  126. package/dist/domain/tasks/mutator.d.ts +16 -3
  127. package/dist/domain/tasks/mutator.js +41 -12
  128. package/dist/domain/tasks/pending-tracker.js +6 -5
  129. package/dist/domain/tasks/system/task-cli.d.ts +2 -0
  130. package/dist/domain/tasks/system/task-cli.js +37 -6
  131. package/dist/domain/tasks/system/task-lifecycle-edit.js +6 -1
  132. package/dist/domain/tasks/system/task-mutations.d.ts +41 -3
  133. package/dist/domain/tasks/system/task-mutations.js +166 -8
  134. package/dist/domain/threads/contract.d.ts +17 -0
  135. package/dist/domain/threads/contract.js +59 -0
  136. package/dist/domain/threads/hook-runner.js +7 -6
  137. package/dist/domain/threads/index.d.ts +2 -0
  138. package/dist/domain/threads/index.js +3 -1
  139. package/dist/domain/threads/prompt-builder.d.ts +15 -1
  140. package/dist/domain/threads/prompt-builder.js +41 -2
  141. package/dist/domain/threads/runner.d.ts +6 -5
  142. package/dist/domain/threads/runner.js +128 -79
  143. package/dist/domain/threads/state-machine.d.ts +23 -21
  144. package/dist/domain/threads/state-machine.js +113 -54
  145. package/dist/domain/threads/template-loader.js +3 -2
  146. package/dist/domain/threads/tree.d.ts +45 -0
  147. package/dist/domain/threads/tree.js +171 -0
  148. package/dist/domain/tui-session/index.d.ts +2 -0
  149. package/dist/domain/tui-session/index.js +3 -0
  150. package/dist/domain/tui-session/tui-session-service.d.ts +2 -0
  151. package/dist/domain/tui-session/tui-session-service.js +103 -0
  152. package/dist/domain/tui-session/types.d.ts +67 -0
  153. package/dist/domain/tui-session/types.js +4 -0
  154. package/dist/domain/ui-service/index.d.ts +5 -0
  155. package/dist/domain/ui-service/index.js +3 -0
  156. package/dist/domain/ui-service/mutate/executions.d.ts +4 -0
  157. package/dist/domain/ui-service/mutate/executions.js +15 -0
  158. package/dist/domain/ui-service/mutate/schedules.d.ts +10 -0
  159. package/dist/domain/ui-service/mutate/schedules.js +39 -0
  160. package/dist/domain/ui-service/mutate/tasks.d.ts +23 -0
  161. package/dist/domain/ui-service/mutate/tasks.js +59 -0
  162. package/dist/domain/ui-service/mutate/threads.d.ts +4 -0
  163. package/dist/domain/ui-service/mutate/threads.js +21 -0
  164. package/dist/domain/ui-service/query/cost.d.ts +3 -0
  165. package/dist/domain/ui-service/query/cost.js +6 -0
  166. package/dist/domain/ui-service/query/executions.d.ts +2 -0
  167. package/dist/domain/ui-service/query/executions.js +35 -0
  168. package/dist/domain/ui-service/query/projects.d.ts +2 -0
  169. package/dist/domain/ui-service/query/projects.js +30 -0
  170. package/dist/domain/ui-service/query/schedules.d.ts +2 -0
  171. package/dist/domain/ui-service/query/schedules.js +23 -0
  172. package/dist/domain/ui-service/query/sessions.d.ts +2 -0
  173. package/dist/domain/ui-service/query/sessions.js +35 -0
  174. package/dist/domain/ui-service/query/tasks.d.ts +2 -0
  175. package/dist/domain/ui-service/query/tasks.js +30 -0
  176. package/dist/domain/ui-service/query/threads.d.ts +2 -0
  177. package/dist/domain/ui-service/query/threads.js +27 -0
  178. package/dist/domain/ui-service/subscribe.d.ts +5 -0
  179. package/dist/domain/ui-service/subscribe.js +118 -0
  180. package/dist/domain/ui-service/types.d.ts +237 -0
  181. package/dist/domain/ui-service/types.js +5 -0
  182. package/dist/domain/ui-service/ui-service.d.ts +2 -0
  183. package/dist/domain/ui-service/ui-service.js +83 -0
  184. package/dist/entry/app.js +94 -5
  185. package/dist/entry/cli.d.ts +12 -0
  186. package/dist/entry/cli.js +122 -12
  187. package/dist/entry/feishu-login.d.ts +28 -0
  188. package/dist/entry/feishu-login.js +218 -0
  189. package/dist/entry/init.d.ts +25 -2
  190. package/dist/entry/init.js +211 -64
  191. package/dist/events/event-types.d.ts +14 -0
  192. package/dist/hooks/cortex-md-injector.mjs +47 -31
  193. package/dist/hooks/post-task-hook.mjs +6 -0
  194. package/dist/hooks/task-status-check.mjs +8 -0
  195. package/dist/orchestration/agent-runner.d.ts +2 -1
  196. package/dist/orchestration/agent-runner.js +55 -55
  197. package/dist/orchestration/conduit-queue.d.ts +18 -0
  198. package/dist/orchestration/conduit-queue.js +32 -0
  199. package/dist/orchestration/conversation-runner.d.ts +48 -0
  200. package/dist/orchestration/conversation-runner.js +109 -0
  201. package/dist/orchestration/dispatch-reconciler.js +8 -1
  202. package/dist/orchestration/interactions/ask-user-question.d.ts +1 -1
  203. package/dist/orchestration/interactions/ask-user-question.js +3 -3
  204. package/dist/orchestration/interactions/interaction-handlers.js +48 -17
  205. package/dist/orchestration/interactions/plan-handler.d.ts +2 -2
  206. package/dist/orchestration/interactions/plan-handler.js +4 -3
  207. package/dist/orchestration/interactions/update-prompt.d.ts +6 -0
  208. package/dist/orchestration/interactions/update-prompt.js +100 -0
  209. package/dist/orchestration/lifecycle.d.ts +4 -4
  210. package/dist/orchestration/lifecycle.js +24 -22
  211. package/dist/orchestration/orchestrator.d.ts +1 -1
  212. package/dist/orchestration/routing/commands/cancel.js +39 -47
  213. package/dist/orchestration/routing/commands/channel.js +24 -11
  214. package/dist/orchestration/routing/commands/cost.js +2 -1
  215. package/dist/orchestration/routing/commands/device.js +3 -2
  216. package/dist/orchestration/routing/commands/dispatch.js +6 -5
  217. package/dist/orchestration/routing/commands/index.d.ts +1 -1
  218. package/dist/orchestration/routing/commands/index.js +11 -10
  219. package/dist/orchestration/routing/commands/mode.js +19 -18
  220. package/dist/orchestration/routing/commands/nvtop.js +10 -9
  221. package/dist/orchestration/routing/commands/sendfile.js +7 -6
  222. package/dist/orchestration/routing/commands/session.d.ts +1 -1
  223. package/dist/orchestration/routing/commands/session.js +17 -33
  224. package/dist/orchestration/routing/commands/tail.js +4 -3
  225. package/dist/orchestration/routing/commands/task.js +4 -3
  226. package/dist/orchestration/routing/commands/thread-handlers.js +16 -6
  227. package/dist/orchestration/routing/edit-handler.js +8 -7
  228. package/dist/orchestration/routing/hook-bridge-subscribers.js +17 -1
  229. package/dist/orchestration/routing/message-router.d.ts +1 -1
  230. package/dist/orchestration/routing/message-router.js +9 -9
  231. package/dist/orchestration/routing/webhook.js +233 -2
  232. package/dist/orchestration/status-helpers.d.ts +5 -1
  233. package/dist/orchestration/status-helpers.js +7 -6
  234. package/dist/orchestration/thread-callback.d.ts +67 -0
  235. package/dist/orchestration/thread-callback.js +465 -0
  236. package/dist/orchestration/thread-executor.d.ts +22 -1
  237. package/dist/orchestration/thread-executor.js +85 -36
  238. package/dist/platform/adapter.d.ts +6 -2
  239. package/dist/platform/adapters/composite-adapter.d.ts +89 -0
  240. package/dist/platform/adapters/composite-adapter.js +318 -0
  241. package/dist/platform/adapters/feishu-output-stream.d.ts +26 -4
  242. package/dist/platform/adapters/feishu-output-stream.js +274 -36
  243. package/dist/platform/adapters/feishu.d.ts +50 -5
  244. package/dist/platform/adapters/feishu.js +370 -116
  245. package/dist/platform/adapters/index.d.ts +24 -3
  246. package/dist/platform/adapters/index.js +89 -11
  247. package/dist/platform/adapters/project-conduits.d.ts +9 -0
  248. package/dist/platform/adapters/project-conduits.js +42 -0
  249. package/dist/platform/adapters/slack-project-conduits.d.ts +1 -9
  250. package/dist/platform/adapters/slack-project-conduits.js +6 -40
  251. package/dist/platform/adapters/slack.d.ts +9 -2
  252. package/dist/platform/adapters/slack.js +83 -39
  253. package/dist/platform/adapters/tui/index.d.ts +9 -0
  254. package/dist/platform/adapters/tui/index.js +10 -0
  255. package/dist/platform/adapters/tui/ports.d.ts +20 -0
  256. package/dist/platform/adapters/tui/ports.js +4 -0
  257. package/dist/platform/adapters/tui/tui-conduit-state.d.ts +10 -0
  258. package/dist/platform/adapters/tui/tui-conduit-state.js +17 -0
  259. package/dist/platform/adapters/tui/tui-connection.d.ts +30 -0
  260. package/dist/platform/adapters/tui/tui-connection.js +53 -0
  261. package/dist/platform/adapters/tui/tui-gateway.d.ts +120 -0
  262. package/dist/platform/adapters/tui/tui-gateway.js +919 -0
  263. package/dist/platform/adapters/tui/tui-notifications.d.ts +12 -0
  264. package/dist/platform/adapters/tui/tui-notifications.js +60 -0
  265. package/dist/platform/adapters/tui/tui-output-stream.d.ts +36 -0
  266. package/dist/platform/adapters/tui/tui-output-stream.js +99 -0
  267. package/dist/platform/adapters/tui/tui-transcript.d.ts +8 -0
  268. package/dist/platform/adapters/tui/tui-transcript.js +56 -0
  269. package/dist/platform/index.d.ts +1 -0
  270. package/dist/platform/index.js +2 -1
  271. package/dist/platform/interactive-builder.js +3 -2
  272. package/dist/platform/output-stream.d.ts +5 -0
  273. package/dist/platform/testing.d.ts +7 -11
  274. package/dist/platform/testing.js +18 -15
  275. package/dist/platform/tool-trace.js +15 -5
  276. package/dist/platform/tui/protocol.d.ts +355 -0
  277. package/dist/platform/tui/protocol.js +199 -0
  278. package/dist/platform/types.d.ts +12 -3
  279. package/dist/store/execution-repo.d.ts +6 -1
  280. package/dist/store/execution-repo.js +13 -3
  281. package/dist/store/hook-sync.d.ts +18 -0
  282. package/dist/store/hook-sync.js +92 -0
  283. package/dist/store/outbound-queue.js +2 -2
  284. package/dist/store/profile-repo.js +3 -2
  285. package/dist/store/schedule-repo.d.ts +1 -8
  286. package/dist/store/session-registry-repo.d.ts +9 -1
  287. package/dist/store/session-registry-repo.js +19 -3
  288. package/dist/store/session-repo.d.ts +14 -0
  289. package/dist/store/session-repo.js +23 -0
  290. package/dist/store/thread-repo.d.ts +3 -0
  291. package/dist/store/thread-repo.js +49 -2
  292. package/dist/store/version-migrations.js +95 -0
  293. package/dist/tui/App.d.ts +27 -0
  294. package/dist/tui/App.js +219 -0
  295. package/dist/tui/components/AskUserModal.d.ts +11 -0
  296. package/dist/tui/components/AskUserModal.js +364 -0
  297. package/dist/tui/components/ConfirmModal.d.ts +12 -0
  298. package/dist/tui/components/ConfirmModal.js +31 -0
  299. package/dist/tui/components/Dashboard.d.ts +23 -0
  300. package/dist/tui/components/Dashboard.js +80 -0
  301. package/dist/tui/components/DashboardCostTab.d.ts +7 -0
  302. package/dist/tui/components/DashboardCostTab.js +16 -0
  303. package/dist/tui/components/DashboardExecutionsTab.d.ts +11 -0
  304. package/dist/tui/components/DashboardExecutionsTab.js +94 -0
  305. package/dist/tui/components/DashboardSchedulesTab.d.ts +11 -0
  306. package/dist/tui/components/DashboardSchedulesTab.js +124 -0
  307. package/dist/tui/components/DashboardTasksTab.d.ts +12 -0
  308. package/dist/tui/components/DashboardTasksTab.js +200 -0
  309. package/dist/tui/components/DashboardThreadsTab.d.ts +11 -0
  310. package/dist/tui/components/DashboardThreadsTab.js +81 -0
  311. package/dist/tui/components/Header.d.ts +11 -0
  312. package/dist/tui/components/Header.js +5 -0
  313. package/dist/tui/components/InputBox.d.ts +10 -0
  314. package/dist/tui/components/InputBox.js +19 -0
  315. package/dist/tui/components/MessageRow.d.ts +7 -0
  316. package/dist/tui/components/MessageRow.js +10 -0
  317. package/dist/tui/components/Notifications.d.ts +19 -0
  318. package/dist/tui/components/Notifications.js +72 -0
  319. package/dist/tui/components/PlanFeedbackModal.d.ts +11 -0
  320. package/dist/tui/components/PlanFeedbackModal.js +161 -0
  321. package/dist/tui/components/ProjectSwitcher.d.ts +18 -0
  322. package/dist/tui/components/ProjectSwitcher.js +43 -0
  323. package/dist/tui/components/SessionPicker.d.ts +14 -0
  324. package/dist/tui/components/SessionPicker.js +34 -0
  325. package/dist/tui/components/SidePanel.d.ts +19 -0
  326. package/dist/tui/components/SidePanel.js +8 -0
  327. package/dist/tui/components/StatusLine.d.ts +10 -0
  328. package/dist/tui/components/StatusLine.js +29 -0
  329. package/dist/tui/components/Transcript.d.ts +13 -0
  330. package/dist/tui/components/Transcript.js +56 -0
  331. package/dist/tui/hooks/useDashboardData.d.ts +32 -0
  332. package/dist/tui/hooks/useDashboardData.js +104 -0
  333. package/dist/tui/hooks/useKeybindings.d.ts +19 -0
  334. package/dist/tui/hooks/useKeybindings.js +87 -0
  335. package/dist/tui/hooks/useMutate.d.ts +22 -0
  336. package/dist/tui/hooks/useMutate.js +56 -0
  337. package/dist/tui/hooks/useNotifications.d.ts +28 -0
  338. package/dist/tui/hooks/useNotifications.js +70 -0
  339. package/dist/tui/hooks/useTranscript.d.ts +39 -0
  340. package/dist/tui/hooks/useTranscript.js +265 -0
  341. package/dist/tui/hooks/useWsClient.d.ts +29 -0
  342. package/dist/tui/hooks/useWsClient.js +69 -0
  343. package/dist/tui/index.d.ts +2 -0
  344. package/dist/tui/index.js +210 -0
  345. package/dist/tui/logic.d.ts +16 -0
  346. package/dist/tui/logic.js +49 -0
  347. package/dist/tui/render/markdown.d.ts +10 -0
  348. package/dist/tui/render/markdown.js +38 -0
  349. package/dist/tui/render/rich-blocks.d.ts +11 -0
  350. package/dist/tui/render/rich-blocks.js +24 -0
  351. package/dist/tui/ws-client.d.ts +44 -0
  352. package/dist/tui/ws-client.js +157 -0
  353. package/package.json +11 -3
  354. package/dist/orchestration/channel-queue.d.ts +0 -18
  355. package/dist/orchestration/channel-queue.js +0 -32
@@ -1,15 +1,25 @@
1
- // input: fs, path, os, `pi --list-models` output
2
- // output: discoverEndpoints / generateGatewayYaml / writeGatewayYaml / parsePiListModelsOutput
3
- // — spawns pi --list-models, produces gateway.yaml content
1
+ // input: fs, path, os, yaml, `pi --list-models` output
2
+ // output: discoverEndpoints / generateGatewayYaml / parsePiListModelsOutput
3
+ // + merge-aware: readGatewayYaml / discoveredToEndpointMap / mergeGatewayConfig /
4
+ // serializeGatewayYaml / writeMergedGatewayYaml / validateProfilesAgainstGateway
5
+ // — spawns pi --list-models, produces & merges gateway.yaml (add-only: never clobbers
6
+ // hand-maintained modes/keys), validates profile↔gateway mode coupling
4
7
  // pos: init-time gateway config auto-generation. PI model metadata is owned by the PI agent
5
8
  // (we shell out to `pi --list-models` rather than maintain provider/model whitelists).
6
- // Claude plan mode is always assumed (user must have claude login), no credential scanning.
7
- import { writeFileSync, copyFileSync, mkdirSync, existsSync } from 'fs';
9
+ // Claude plan mode is included when the backends filter includes 'claude' (or is omitted).
10
+ import { writeFileSync, copyFileSync, mkdirSync, existsSync, readFileSync } from 'fs';
8
11
  import { execSync } from 'child_process';
9
12
  import * as path from 'path';
10
13
  import * as os from 'os';
14
+ import { parse as yamlParse, stringify as yamlStringify } from 'yaml';
11
15
  import { createLogger } from './log.js';
12
16
  const log = createLogger('gateway-generator');
17
+ /** aistatus reserved top-level keys (mirror of node_modules/aistatus fromDict RESERVED_KEYS). */
18
+ const GATEWAY_RESERVED_KEYS = new Set(['host', 'port', 'mode', 'auth', 'status_check', 'endpoint_modes', 'endpoints']);
19
+ /** Keys that, when present directly on an endpoint value, mark it as a "flat" (single-mode) config. */
20
+ const FLAT_ENDPOINT_KEYS = ['keys', 'base_url', 'auth_style', 'passthrough', 'fallbacks', 'model_fallbacks'];
21
+ /** Synthetic mode name used to hold a flat endpoint config (aistatus assigns these to mode "default"). */
22
+ const FLAT_MODE = 'default';
13
23
  // ─── Anthropic models (default tier) ─────────────────────────────
14
24
  const ANTHROPIC_MODELS = ['claude-opus-4-7', 'claude-sonnet-4-6', 'claude-haiku-4-5'];
15
25
  // ─── PI provider → upstream URL lookup (manually maintained) ────────────────
@@ -115,41 +125,49 @@ function scanPIViaListModels() {
115
125
  /**
116
126
  * Scan Claude Code and PI configurations and return discovered endpoints.
117
127
  *
118
- * - Claude Code plan mode: always generated if logged in (OAuth bearer passthrough).
119
- * - Claude Code api mode: generated only if ANTHROPIC_API_KEY env var is set.
120
- * - PI providers: discovered via `pi --list-models`. Each provider becomes one endpoint with
121
- * `mode = endpoint = provider name`. `gatewayManaged` is true only if the provider has a known
122
- * upstream URL in PI_PROVIDER_UPSTREAM (otherwise profile is generated but gateway.yaml entry
123
- * is skipped).
128
+ * @param backends - Optional filter: when provided, only discover endpoints for the listed backends
129
+ * (e.g. `['claude']`, `['pi']`, `['claude', 'pi']`). When omitted, all backends are discovered.
130
+ *
131
+ * - Claude Code plan mode: generated when 'claude' is in backends (or backends is omitted).
132
+ * - Claude Code api mode: generated only if ANTHROPIC_API_KEY env var is set and 'claude' is included.
133
+ * - PI providers: discovered via `pi --list-models` when 'pi' is in backends (or backends is omitted).
134
+ * Each provider becomes one endpoint with `mode = endpoint = provider name`. `gatewayManaged`
135
+ * is true only if the provider has a known upstream URL in PI_PROVIDER_UPSTREAM (otherwise profile
136
+ * is generated but gateway.yaml entry is skipped).
124
137
  */
125
- export function discoverEndpoints() {
138
+ export function discoverEndpoints(backends) {
126
139
  const endpoints = [];
127
- // ── Claude Code → Anthropic plan mode (always on) ──
128
- endpoints.push({
129
- mode: 'plan',
130
- endpoint: 'anthropic',
131
- base_url: 'https://api.anthropic.com',
132
- auth_style: 'bearer',
133
- keys: [],
134
- passthrough: true,
135
- models: ANTHROPIC_MODELS,
136
- gatewayManaged: true,
137
- });
138
- // api mode — only if ANTHROPIC_API_KEY is set
139
- if (process.env.ANTHROPIC_API_KEY) {
140
+ // ── Claude Code → Anthropic plan mode ──
141
+ // Skip if backends filter is provided and 'claude' is not included.
142
+ const includeClaude = !backends || backends.includes('claude');
143
+ if (includeClaude) {
140
144
  endpoints.push({
141
- mode: 'api',
145
+ mode: 'plan',
142
146
  endpoint: 'anthropic',
143
147
  base_url: 'https://api.anthropic.com',
144
- auth_style: 'anthropic',
145
- keys: ['$ANTHROPIC_API_KEY'],
148
+ auth_style: 'bearer',
149
+ keys: [],
146
150
  passthrough: true,
147
151
  models: ANTHROPIC_MODELS,
148
152
  gatewayManaged: true,
149
153
  });
154
+ // api mode — only if ANTHROPIC_API_KEY is set
155
+ if (process.env.ANTHROPIC_API_KEY) {
156
+ endpoints.push({
157
+ mode: 'api',
158
+ endpoint: 'anthropic',
159
+ base_url: 'https://api.anthropic.com',
160
+ auth_style: 'anthropic',
161
+ keys: ['$ANTHROPIC_API_KEY'],
162
+ passthrough: true,
163
+ models: ANTHROPIC_MODELS,
164
+ gatewayManaged: true,
165
+ });
166
+ }
150
167
  }
151
168
  // ── PI → per-provider endpoints (one mode per provider) ──
152
- const piModels = scanPIViaListModels();
169
+ const includePi = !backends || backends.includes('pi');
170
+ const piModels = includePi ? scanPIViaListModels() : [];
153
171
  // Group models by provider name
154
172
  const byProvider = new Map();
155
173
  for (const { provider, model } of piModels) {
@@ -254,6 +272,8 @@ export function generateGatewayYaml(endpoints, defaultMode) {
254
272
  * Write gateway.yaml to the specified path or ~/.aistatus/gateway.yaml.
255
273
  * If file already exists and outputDir is not specified, backs it up as gateway.yaml.bak before overwriting.
256
274
  * When outputDir is provided, writes to <outputDir>/gateway.yaml without backup.
275
+ *
276
+ * @deprecated Use writeMergedGatewayYaml — full overwrite drops hand-maintained custom modes.
257
277
  */
258
278
  export function writeGatewayYaml(yamlContent, outputDir) {
259
279
  const configDir = outputDir || path.join(os.homedir(), '.aistatus');
@@ -274,6 +294,258 @@ export function writeGatewayYaml(yamlContent, outputDir) {
274
294
  log.info(`Written gateway.yaml to ${configPath}`);
275
295
  return configPath;
276
296
  }
297
+ // ─── Merge-aware generation (preserve hand-maintained modes) ──────────────────
298
+ function isPlainObject(v) {
299
+ return !!v && typeof v === 'object' && !Array.isArray(v);
300
+ }
301
+ function isFlatEndpointConfig(v) {
302
+ return FLAT_ENDPOINT_KEYS.some((k) => k in v);
303
+ }
304
+ function deepCopy(v) {
305
+ return JSON.parse(JSON.stringify(v));
306
+ }
307
+ /**
308
+ * Parse an existing gateway.yaml into reserved top-level fields + the endpoint/mode tree.
309
+ * Returns null if the file is absent or unparseable (caller degrades to full generation).
310
+ */
311
+ export function readGatewayYaml(filePath) {
312
+ if (!existsSync(filePath))
313
+ return null;
314
+ let raw;
315
+ try {
316
+ raw = yamlParse(readFileSync(filePath, 'utf-8'));
317
+ }
318
+ catch (e) {
319
+ log.warn(`Failed to parse existing gateway.yaml (${filePath}): ${e.message} — regenerating from scratch`);
320
+ return null;
321
+ }
322
+ if (!isPlainObject(raw))
323
+ return null;
324
+ const top = {};
325
+ const endpoints = {};
326
+ for (const [key, val] of Object.entries(raw)) {
327
+ if (GATEWAY_RESERVED_KEYS.has(key)) {
328
+ top[key] = val;
329
+ continue;
330
+ }
331
+ if (!isPlainObject(val))
332
+ continue; // ignore stray scalars
333
+ if (isFlatEndpointConfig(val)) {
334
+ endpoints[key] ??= {};
335
+ endpoints[key][FLAT_MODE] = val;
336
+ continue;
337
+ }
338
+ for (const [modeName, modeVal] of Object.entries(val)) {
339
+ if (!isPlainObject(modeVal))
340
+ continue;
341
+ endpoints[key] ??= {};
342
+ endpoints[key][modeName] = modeVal;
343
+ }
344
+ }
345
+ return { top, endpoints };
346
+ }
347
+ /** Build an endpoint/mode tree from freshly discovered endpoints (gatewayManaged only). */
348
+ export function discoveredToEndpointMap(endpoints) {
349
+ const map = {};
350
+ for (const ep of endpoints) {
351
+ if (ep.gatewayManaged === false)
352
+ continue;
353
+ const cfg = { base_url: ep.base_url, auth_style: ep.auth_style };
354
+ if (ep.keys.length > 0) {
355
+ cfg.keys = [...ep.keys];
356
+ if (ep.passthrough)
357
+ cfg.passthrough = true;
358
+ }
359
+ map[ep.endpoint] ??= {};
360
+ map[ep.endpoint][ep.mode] = cfg;
361
+ }
362
+ return map;
363
+ }
364
+ /**
365
+ * Merge freshly discovered endpoints over an existing gateway config.
366
+ *
367
+ * Add-only at the (endpoint, mode) PAIR level (mirrors mergeProfilesJson overwrite=false): a pair
368
+ * absent from the existing file is added from discovery; any pair that already exists is preserved
369
+ * verbatim — its base_url, auth_style and (critically) managed keys are never clobbered. This both
370
+ * fixes the original bug (a missing mode gets added) and protects hand-customized routes, e.g. a
371
+ * `deepseek` mode pointed at a private relay with a secret key, even though `pi --list-models`
372
+ * reports the canonical upstream for that provider. A failed/empty discovery therefore can never
373
+ * drop or alter previously-configured modes. To intentionally update an existing route's URL/keys,
374
+ * edit gateway.yaml directly.
375
+ */
376
+ export function mergeGatewayConfig(discovered, existing, defaultMode) {
377
+ const disc = discoveredToEndpointMap(discovered);
378
+ const merged = existing ? deepCopy(existing.endpoints) : {};
379
+ const preservedCustom = [];
380
+ const droppedFromDiscovery = [];
381
+ // Classify existing pairs against the fresh discovery set (for reporting only — nothing is
382
+ // overwritten). A pair not present in this discovery is "custom"; if it also isn't a Claude
383
+ // builtin (anthropic/plan|api), surface it as droppedFromDiscovery so a failed/under-reporting
384
+ // `pi --list-models` is visible rather than silently keeping stale routes.
385
+ for (const [endpoint, modes] of Object.entries(merged)) {
386
+ for (const mode of Object.keys(modes)) {
387
+ const isDiscoveryOwned = !!disc[endpoint]?.[mode];
388
+ if (!isDiscoveryOwned) {
389
+ preservedCustom.push({ endpoint, mode });
390
+ const isClaudeBuiltin = endpoint === 'anthropic' && (mode === 'plan' || mode === 'api');
391
+ if (!isClaudeBuiltin)
392
+ droppedFromDiscovery.push({ endpoint, mode });
393
+ }
394
+ }
395
+ }
396
+ // Add-only: fill in pairs discovery found that aren't already present. Existing pairs (incl. their
397
+ // keys/base_url) are left untouched.
398
+ for (const [endpoint, modes] of Object.entries(disc)) {
399
+ merged[endpoint] ??= {};
400
+ for (const [mode, cfg] of Object.entries(modes)) {
401
+ if (!merged[endpoint][mode])
402
+ merged[endpoint][mode] = cfg;
403
+ }
404
+ }
405
+ // Resolve active billing mode: explicit override → existing-still-valid → first discovered → 'api'.
406
+ const availableModes = new Set();
407
+ for (const modes of Object.values(merged))
408
+ for (const m of Object.keys(modes))
409
+ availableModes.add(m);
410
+ const existingMode = typeof existing?.top.mode === 'string' ? existing.top.mode : undefined;
411
+ const firstDiscovered = discovered.find((e) => e.gatewayManaged !== false)?.mode;
412
+ const activeMode = defaultMode && availableModes.has(defaultMode)
413
+ ? defaultMode
414
+ : existingMode && availableModes.has(existingMode)
415
+ ? existingMode
416
+ : firstDiscovered && availableModes.has(firstDiscovered)
417
+ ? firstDiscovered
418
+ : (availableModes.values().next().value ?? 'api');
419
+ const top = existing ? deepCopy(existing.top) : {};
420
+ top.port = top.port ?? 9880;
421
+ top.mode = activeMode;
422
+ top.status_check = top.status_check ?? true;
423
+ return { endpoints: merged, top, preservedCustom, droppedFromDiscovery };
424
+ }
425
+ /** Serialize a merged gateway config back to YAML (re-serializes; inline comments in custom blocks are not retained). */
426
+ export function serializeGatewayYaml(result) {
427
+ const obj = {};
428
+ // Ordered, well-known top-level fields first.
429
+ obj.port = result.top.port ?? 9880;
430
+ obj.mode = result.top.mode;
431
+ obj.status_check = result.top.status_check ?? true;
432
+ if (result.top.host !== undefined)
433
+ obj.host = result.top.host;
434
+ if (result.top.auth !== undefined)
435
+ obj.auth = result.top.auth;
436
+ if (result.top.endpoint_modes !== undefined)
437
+ obj.endpoint_modes = result.top.endpoint_modes;
438
+ if (result.top.endpoints !== undefined)
439
+ obj.endpoints = result.top.endpoints;
440
+ for (const [endpoint, modes] of Object.entries(result.endpoints)) {
441
+ const modeNames = Object.keys(modes);
442
+ // Flat endpoint: only the synthetic `default` mode → emit config directly under the endpoint.
443
+ if (modeNames.length === 1 && modeNames[0] === FLAT_MODE) {
444
+ obj[endpoint] = modes[FLAT_MODE];
445
+ }
446
+ else {
447
+ obj[endpoint] = modes;
448
+ }
449
+ }
450
+ const header = [
451
+ '# aistatus gateway — managed by cortex (merge mode).',
452
+ `# Generated: ${new Date().toISOString()}`,
453
+ '#',
454
+ '# `cortex init` / `cortex setup-gateway` ADD newly discovered modes; existing modes and their',
455
+ '# keys are preserved as-is (never overwritten). Edit a route here to change its URL/keys.',
456
+ '# NOTE: inline comments inside existing blocks are not retained across regeneration.',
457
+ '#',
458
+ '# Docs: https://aistatus.cc/docs',
459
+ '',
460
+ ].join('\n');
461
+ return header + yamlStringify(obj, { lineWidth: 0 });
462
+ }
463
+ /**
464
+ * Read existing gateway.yaml, merge discovery over it, and write the result. Always backs up an
465
+ * existing file to .bak first (including when outputDir is given, since merge now touches real data).
466
+ */
467
+ export function writeMergedGatewayYaml(discovered, outputDir, defaultMode) {
468
+ const configDir = outputDir || path.join(os.homedir(), '.aistatus');
469
+ const configPath = path.join(configDir, 'gateway.yaml');
470
+ const existing = readGatewayYaml(configPath);
471
+ const result = mergeGatewayConfig(discovered, existing, defaultMode);
472
+ const content = serializeGatewayYaml(result);
473
+ if (existsSync(configPath)) {
474
+ try {
475
+ copyFileSync(configPath, configPath + '.bak');
476
+ log.info(`Backed up existing gateway.yaml to ${configPath}.bak`);
477
+ }
478
+ catch (e) {
479
+ log.warn(`Failed to backup existing gateway.yaml: ${e.message}`);
480
+ }
481
+ }
482
+ mkdirSync(configDir, { recursive: true });
483
+ writeFileSync(configPath, content, 'utf-8');
484
+ log.info(`Written merged gateway.yaml to ${configPath}`);
485
+ return { path: configPath, result };
486
+ }
487
+ /**
488
+ * Validate that every profile (and its fallback chain) in profiles.json references a gateway mode
489
+ * that actually exists in the merged endpoint map. Pure + non-fatal — returns the list of problems
490
+ * so the caller can warn loudly. This is what catches the `400 Unknown mode: <x>` class of bug.
491
+ */
492
+ export function validateProfilesAgainstGateway(mergedEndpoints, profilesConfigDir) {
493
+ const profilesPath = profilesConfigDir
494
+ ? path.join(profilesConfigDir, 'profiles.json')
495
+ : path.join(os.homedir(), '.cortex', 'config', 'profiles.json');
496
+ let parsed;
497
+ try {
498
+ if (!existsSync(profilesPath))
499
+ return [];
500
+ parsed = JSON.parse(readFileSync(profilesPath, 'utf-8'));
501
+ }
502
+ catch (e) {
503
+ log.warn(`Failed to read profiles.json for validation: ${e.message}`);
504
+ return [];
505
+ }
506
+ if (!isPlainObject(parsed) || !isPlainObject(parsed.profiles))
507
+ return [];
508
+ const modeExistsAnywhere = (mode) => Object.values(mergedEndpoints).some((modes) => mode in modes);
509
+ const issues = [];
510
+ const checkEntry = (entry, label) => {
511
+ const backend = typeof entry.backend === 'string' ? entry.backend : undefined;
512
+ const mode = typeof entry.mode === 'string' ? entry.mode : undefined;
513
+ const provider = typeof entry.provider === 'string' ? entry.provider : undefined;
514
+ // No mode → PI uses direct /<provider> routing (no gateway mode indirection); nothing to check.
515
+ if (!mode)
516
+ return;
517
+ let endpoint;
518
+ if (backend === 'claude')
519
+ endpoint = 'anthropic';
520
+ else if (backend === 'pi')
521
+ endpoint = provider;
522
+ else
523
+ return; // codex / unknown backends don't route through gateway modes here
524
+ if (backend === 'pi' && !provider) {
525
+ issues.push({ profile: label, mode, reason: `pi profile is missing a provider (cannot resolve gateway endpoint)` });
526
+ return;
527
+ }
528
+ if (!endpoint || !mergedEndpoints[endpoint]?.[mode]) {
529
+ const reason = !modeExistsAnywhere(mode)
530
+ ? `mode "${mode}" is not configured in gateway.yaml`
531
+ : `endpoint "${endpoint}" is not configured under mode "${mode}"`;
532
+ issues.push({ profile: label, mode, provider, reason });
533
+ }
534
+ };
535
+ for (const [name, profileVal] of Object.entries(parsed.profiles)) {
536
+ if (!isPlainObject(profileVal))
537
+ continue;
538
+ checkEntry(profileVal, name);
539
+ const fallback = profileVal.fallback;
540
+ if (Array.isArray(fallback)) {
541
+ fallback.forEach((fb, i) => {
542
+ if (isPlainObject(fb))
543
+ checkEntry(fb, `${name} (fallback #${i + 1})`);
544
+ });
545
+ }
546
+ }
547
+ return issues;
548
+ }
277
549
  /**
278
550
  * Run discovery and return the YAML string (without writing to disk).
279
551
  * Useful for dry-run / preview.
@@ -0,0 +1,68 @@
1
+ /** Semantic icon constants — replaces Slack `:shortcode:` literals.
2
+ * All values are raw Unicode so they render correctly on any platform
3
+ * (Slack, Feishu, TUI). Slack renders Unicode emoji identically to shortcodes. */
4
+ export declare const Icons: {
5
+ /** :warning: */
6
+ readonly warning: "⚠️";
7
+ /** :white_check_mark: */
8
+ readonly ok: "✅";
9
+ /** :x: */
10
+ readonly error: "❌";
11
+ /** :arrows_counterclockwise: */
12
+ readonly refresh: "🔄";
13
+ /** :hourglass_flowing_sand: */
14
+ readonly processing: "⏳";
15
+ /** :stopwatch: */
16
+ readonly stopwatch: "⏱️";
17
+ /** :repeat: */
18
+ readonly repeat: "🔁";
19
+ /** :satellite: */
20
+ readonly satellite: "🛰️";
21
+ /** :leftwards_arrow_with_hook: */
22
+ readonly reply: "↩️";
23
+ /** :hook: */
24
+ readonly hook: "🪝";
25
+ /** :speech_balloon: */
26
+ readonly waiting: "💬";
27
+ /** :fast_forward: */
28
+ readonly superseded: "⏩";
29
+ /** :octagonal_sign: */
30
+ readonly stopped: "🛑";
31
+ /** :memo: */
32
+ readonly memo: "📝";
33
+ /** :brain: */
34
+ readonly brain: "🧠";
35
+ /** :file_folder: */
36
+ readonly folder: "📁";
37
+ /** :desktop_computer: */
38
+ readonly desktop: "🖥️";
39
+ /** :scroll: */
40
+ readonly scroll: "📜";
41
+ /** :wave: */
42
+ readonly wave: "👋";
43
+ /** :no_entry: / :no_entry_sign: */
44
+ readonly blocked: "🚫";
45
+ /** :no_entry_sign: (alias for blocked — identical rendering) */
46
+ readonly noEntry: "🚫";
47
+ /** :heavy_plus_sign: */
48
+ readonly add: "➕";
49
+ /** :inbox_tray: */
50
+ readonly inbox: "📥";
51
+ /** :pencil2: */
52
+ readonly edit: "✏️";
53
+ /** :wrench: */
54
+ readonly tools: "🔧";
55
+ /** :arrow_right: */
56
+ readonly arrowRight: "➡️";
57
+ /** :arrow_left: */
58
+ readonly arrowLeft: "⬅️";
59
+ /** :arrow_forward: */
60
+ readonly resume: "▶️";
61
+ /** :double_vertical_bar: */
62
+ readonly paused: "⏸️";
63
+ /** :clock1: */
64
+ readonly scheduled: "🕐";
65
+ /** :radio_button: */
66
+ readonly pending: "🔘";
67
+ };
68
+ export type IconName = keyof typeof Icons;
@@ -0,0 +1,67 @@
1
+ /** Semantic icon constants — replaces Slack `:shortcode:` literals.
2
+ * All values are raw Unicode so they render correctly on any platform
3
+ * (Slack, Feishu, TUI). Slack renders Unicode emoji identically to shortcodes. */
4
+ export const Icons = {
5
+ /** :warning: */
6
+ warning: '⚠️',
7
+ /** :white_check_mark: */
8
+ ok: '✅',
9
+ /** :x: */
10
+ error: '❌',
11
+ /** :arrows_counterclockwise: */
12
+ refresh: '🔄',
13
+ /** :hourglass_flowing_sand: */
14
+ processing: '⏳',
15
+ /** :stopwatch: */
16
+ stopwatch: '⏱️',
17
+ /** :repeat: */
18
+ repeat: '🔁',
19
+ /** :satellite: */
20
+ satellite: '🛰️',
21
+ /** :leftwards_arrow_with_hook: */
22
+ reply: '↩️',
23
+ /** :hook: */
24
+ hook: '🪝',
25
+ /** :speech_balloon: */
26
+ waiting: '💬',
27
+ /** :fast_forward: */
28
+ superseded: '⏩',
29
+ /** :octagonal_sign: */
30
+ stopped: '🛑',
31
+ /** :memo: */
32
+ memo: '📝',
33
+ /** :brain: */
34
+ brain: '🧠',
35
+ /** :file_folder: */
36
+ folder: '📁',
37
+ /** :desktop_computer: */
38
+ desktop: '🖥️',
39
+ /** :scroll: */
40
+ scroll: '📜',
41
+ /** :wave: */
42
+ wave: '👋',
43
+ /** :no_entry: / :no_entry_sign: */
44
+ blocked: '🚫',
45
+ /** :no_entry_sign: (alias for blocked — identical rendering) */
46
+ noEntry: '🚫',
47
+ /** :heavy_plus_sign: */
48
+ add: '➕',
49
+ /** :inbox_tray: */
50
+ inbox: '📥',
51
+ /** :pencil2: */
52
+ edit: '✏️',
53
+ /** :wrench: */
54
+ tools: '🔧',
55
+ /** :arrow_right: */
56
+ arrowRight: '➡️',
57
+ /** :arrow_left: */
58
+ arrowLeft: '⬅️',
59
+ /** :arrow_forward: */
60
+ resume: '▶️',
61
+ /** :double_vertical_bar: */
62
+ paused: '⏸️',
63
+ /** :clock1: */
64
+ scheduled: '🕐',
65
+ /** :radio_button: */
66
+ pending: '🔘',
67
+ };
@@ -3,6 +3,8 @@ interface ProfileEntry {
3
3
  model: string;
4
4
  backend: string;
5
5
  mode: string;
6
+ /** PI `--provider` (= gateway endpoint group). Required for backend='pi'; omitted for claude/codex. */
7
+ provider?: string;
6
8
  fallback?: ProfileEntry[];
7
9
  extraEnv?: Record<string, string>;
8
10
  extraOption?: Record<string, string>;
@@ -25,6 +27,8 @@ export interface GenerateOpts {
25
27
  planFallback?: ModelChoice[];
26
28
  /** Ordered fallback chain for the `execute` profile. */
27
29
  executeFallback?: ModelChoice[];
30
+ /** Additional models to register as standalone named profiles (profile name = model name). */
31
+ extraProfiles?: ModelChoice[];
28
32
  }
29
33
  /**
30
34
  * Flatten endpoints to a list of (mode, model) choices the user can pick from.
@@ -55,6 +59,8 @@ export interface WriteProfilesOpts extends GenerateOpts {
55
59
  outputDir?: string;
56
60
  /** Force overwrite of existing `plan` / `execute` profiles. Default false. */
57
61
  overwrite?: boolean;
62
+ /** Additional models to register as standalone named profiles. */
63
+ extraProfiles?: ModelChoice[];
58
64
  }
59
65
  /**
60
66
  * Write profiles.json to ~/.cortex/config/profiles.json (or outputDir/profiles.json).
@@ -48,11 +48,19 @@ function findModelEntry(models, choice, label) {
48
48
  }
49
49
  /** Build a ProfileEntry from a ModelEntry (no fallback chain attached yet). */
50
50
  function makeProfileEntry(m) {
51
- return {
51
+ const entry = {
52
52
  model: m.model,
53
53
  backend: m.backend,
54
54
  mode: m.mode,
55
55
  };
56
+ // PI backends require an explicit `provider` (the PI `--provider` / gateway endpoint group).
57
+ // For discovered PI providers, endpoint === provider name (discoverEndpoints sets mode = endpoint
58
+ // = provider), so the gateway URL `/m/<mode>/<provider>` lands on the generated `<endpoint>:
59
+ // { <mode>: ... }` route. claude/codex backends carry no provider.
60
+ if (m.backend === 'pi') {
61
+ entry.provider = m.endpoint;
62
+ }
63
+ return entry;
56
64
  }
57
65
  /** Build fallback entries from explicit user choices. Throws if any choice can't be resolved. */
58
66
  function resolveFallbackChain(models, fallback, label) {
@@ -111,13 +119,32 @@ export function generateProfiles(endpoints, opts = {}) {
111
119
  const executeProfile = makeProfileEntry(executeEntry);
112
120
  if (executeFallback)
113
121
  executeProfile.fallback = executeFallback;
114
- return {
115
- defaultProfile: 'plan',
116
- profiles: {
117
- plan: planProfile,
118
- execute: executeProfile,
119
- },
122
+ const profiles = {
123
+ plan: planProfile,
124
+ execute: executeProfile,
120
125
  };
126
+ // Extra profiles: user-picked additional models to register as standalone named profiles.
127
+ // Profile name = model name (e.g., selecting deepseek-v4-pro → profile "deepseek-v4-pro").
128
+ if (opts.extraProfiles && opts.extraProfiles.length > 0) {
129
+ for (const choice of opts.extraProfiles) {
130
+ // Profile names must match /^[a-zA-Z0-9_-]+$/. Model ids may contain dots (e.g. "gpt-5.4"),
131
+ // which are invalid in a profile name — sanitize dots → dashes. The model id stored in the
132
+ // entry stays verbatim (makeProfileEntry uses choice.model) so the API call is unaffected.
133
+ const name = choice.model.replace(/\./g, '-');
134
+ if (name === 'plan' || name === 'execute') {
135
+ log.warn(`Skipping extra profile "${name}": name conflicts with managed profile`);
136
+ continue;
137
+ }
138
+ if (profiles[name]) {
139
+ log.warn(`Skipping extra profile "${name}": already exists`);
140
+ continue;
141
+ }
142
+ const entry = findModelEntry(models, choice, `extraProfiles[${name}]`);
143
+ profiles[name] = makeProfileEntry(entry);
144
+ log.info(`Added extra profile: ${name} (mode=${entry.mode}, backend=${entry.backend})`);
145
+ }
146
+ }
147
+ return { defaultProfile: 'plan', profiles };
121
148
  }
122
149
  // ─── File I/O ─────────────────────────────────────────────────────
123
150
  /**
@@ -177,6 +204,7 @@ export function writeProfilesJson(endpoints, optsOrOutputDir) {
177
204
  executeChoice: opts.executeChoice,
178
205
  planFallback: opts.planFallback,
179
206
  executeFallback: opts.executeFallback,
207
+ extraProfiles: opts.extraProfiles,
180
208
  });
181
209
  const merged = mergeProfilesJson(generated, opts.outputDir, opts.overwrite ?? false);
182
210
  const configDir = opts.outputDir || path.join(os.homedir(), '.cortex', 'config');