@cortex-agent/server 2026.10.15 → 2026.10.21

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 (333) hide show
  1. package/README.md +76 -50
  2. package/defaults/board/board.css +140 -62
  3. package/defaults/board/scaffold.html +36 -13
  4. package/defaults/config/environments/creative.json +0 -1
  5. package/defaults/config/environments/main.json +1 -2
  6. package/defaults/plugins/cortex-board/skills/board/SKILL.md +30 -22
  7. package/defaults/plugins/cortex-system/plugin.json +2 -2
  8. package/defaults/plugins/cortex-system/skills/browser/SKILL.md +56 -0
  9. package/dist/agent-adapter/claude/adapter.d.ts +2 -5
  10. package/dist/agent-adapter/claude/adapter.js +6 -5
  11. package/dist/agent-adapter/claude/assistant-blocks.d.ts +5 -0
  12. package/dist/agent-adapter/claude/assistant-blocks.js +61 -0
  13. package/dist/agent-adapter/claude/cache-refresh.d.ts +58 -0
  14. package/dist/agent-adapter/claude/cache-refresh.js +145 -0
  15. package/dist/agent-adapter/claude/cache-touch.d.ts +12 -0
  16. package/dist/agent-adapter/claude/cache-touch.js +75 -0
  17. package/dist/agent-adapter/claude/event-parser.d.ts +8 -3
  18. package/dist/agent-adapter/claude/event-parser.js +33 -17
  19. package/dist/agent-adapter/claude/event-translator.d.ts +2 -0
  20. package/dist/agent-adapter/claude/event-translator.js +2 -0
  21. package/dist/agent-adapter/claude/session-options.d.ts +6 -13
  22. package/dist/agent-adapter/claude/session-options.js +2 -13
  23. package/dist/agent-adapter/claude/spawn-args.d.ts +4 -21
  24. package/dist/agent-adapter/claude/spawn-args.js +17 -24
  25. package/dist/agent-adapter/claude/transcript-clear.d.ts +42 -0
  26. package/dist/agent-adapter/claude/transcript-clear.js +217 -0
  27. package/dist/agent-adapter/claude/turn-machine.d.ts +3 -2
  28. package/dist/agent-adapter/claude/turn-machine.js +21 -68
  29. package/dist/agent-adapter/claude/window-warmup.d.ts +13 -0
  30. package/dist/agent-adapter/claude/window-warmup.js +38 -0
  31. package/dist/agent-adapter/continuation-phase.js +3 -0
  32. package/dist/agent-adapter/normalize/event-types.d.ts +8 -0
  33. package/dist/agent-adapter/pi/adapter.d.ts +0 -1
  34. package/dist/agent-adapter/pi/adapter.js +5 -13
  35. package/dist/agent-adapter/pi/event-parser.d.ts +1 -1
  36. package/dist/agent-adapter/pi/event-parser.js +43 -27
  37. package/dist/agent-adapter/pi/mcp-bridge.d.ts +1 -1
  38. package/dist/agent-adapter/pi/pi-session.d.ts +2 -0
  39. package/dist/agent-adapter/pi/pi-session.js +15 -0
  40. package/dist/agent-adapter/pi/providers-config.d.ts +2 -2
  41. package/dist/agent-adapter/pi/providers-config.js +1 -1
  42. package/dist/agent-adapter/pi/quota-sink.d.ts +3 -3
  43. package/dist/agent-adapter/pi/quota-sink.js +3 -3
  44. package/dist/agent-adapter/pi/runtime.js +6 -1
  45. package/dist/agent-adapter/pi/session-options.d.ts +9 -13
  46. package/dist/agent-adapter/pi/session-options.js +12 -25
  47. package/dist/agent-adapter/run-events.d.ts +11 -10
  48. package/dist/agent-adapter/run-events.js +2 -0
  49. package/dist/agent-adapter/types.d.ts +5 -4
  50. package/dist/client-bundle/manifest.json +2 -2
  51. package/dist/core/codex-quota.d.ts +1 -1
  52. package/dist/core/codex-quota.js +1 -1
  53. package/dist/core/gateway-generator.d.ts +9 -11
  54. package/dist/core/gateway-generator.js +31 -58
  55. package/dist/core/locales/en.d.ts +51 -77
  56. package/dist/core/locales/slices/commands.d.ts +26 -31
  57. package/dist/core/locales/slices/commands.js +54 -64
  58. package/dist/core/locales/slices/init.d.ts +8 -19
  59. package/dist/core/locales/slices/init.js +17 -53
  60. package/dist/core/locales/slices/interactions.d.ts +3 -3
  61. package/dist/core/locales/slices/interactions.js +6 -6
  62. package/dist/core/locales/slices/notices.d.ts +1 -3
  63. package/dist/core/locales/slices/notices.js +2 -6
  64. package/dist/core/locales/slices/scheduling.d.ts +9 -9
  65. package/dist/core/locales/slices/scheduling.js +18 -18
  66. package/dist/core/locales/slices/status.d.ts +0 -4
  67. package/dist/core/locales/slices/status.js +0 -8
  68. package/dist/core/locales/slices/tui.d.ts +0 -1
  69. package/dist/core/locales/slices/tui.js +0 -2
  70. package/dist/core/locales/slices/uimsg.d.ts +4 -7
  71. package/dist/core/locales/slices/uimsg.js +9 -15
  72. package/dist/core/models-generator.d.ts +29 -0
  73. package/dist/core/models-generator.js +82 -0
  74. package/dist/core/paths.d.ts +1 -1
  75. package/dist/core/paths.js +1 -1
  76. package/dist/core/settings-spec.d.ts +25 -0
  77. package/dist/core/settings-spec.js +34 -0
  78. package/dist/core/status-format.d.ts +3 -2
  79. package/dist/core/status-format.js +2 -2
  80. package/dist/core/types/environment-types.d.ts +0 -2
  81. package/dist/domain/agents/agent-state.d.ts +11 -56
  82. package/dist/domain/agents/agent-state.js +48 -115
  83. package/dist/domain/agents/agent-switch.d.ts +2 -24
  84. package/dist/domain/agents/agent-switch.js +9 -72
  85. package/dist/domain/agents/config.d.ts +11 -61
  86. package/dist/domain/agents/config.js +47 -154
  87. package/dist/domain/agents/engine-selection.d.ts +21 -0
  88. package/dist/domain/agents/engine-selection.js +37 -0
  89. package/dist/domain/agents/environments/registry.js +2 -1
  90. package/dist/domain/agents/environments/resolve.js +0 -1
  91. package/dist/domain/agents/environments/schema.d.ts +0 -1
  92. package/dist/domain/agents/environments/schema.js +0 -1
  93. package/dist/domain/agents/index.d.ts +2 -1
  94. package/dist/domain/agents/index.js +3 -7
  95. package/dist/domain/agents/model-selection.d.ts +18 -70
  96. package/dist/domain/agents/model-selection.js +100 -150
  97. package/dist/domain/agents/models.d.ts +12 -0
  98. package/dist/domain/agents/models.js +94 -0
  99. package/dist/domain/agents/subagent/registry.d.ts +2 -0
  100. package/dist/domain/agents/subagent/registry.js +8 -0
  101. package/dist/domain/agents/subagent/runner.d.ts +5 -5
  102. package/dist/domain/agents/subagent/runner.js +12 -35
  103. package/dist/domain/auth/auth-status.d.ts +4 -4
  104. package/dist/domain/auth/auth-status.js +17 -28
  105. package/dist/domain/auth/gateway-sync.d.ts +6 -26
  106. package/dist/domain/auth/gateway-sync.js +31 -75
  107. package/dist/domain/benchmark/identity.d.ts +3 -5
  108. package/dist/domain/benchmark/identity.js +0 -1
  109. package/dist/domain/benchmark/production-attempt-identity.d.ts +6 -5
  110. package/dist/domain/benchmark/production-attempt-identity.js +32 -35
  111. package/dist/domain/benchmark/session-evidence.d.ts +2 -1
  112. package/dist/domain/benchmark/session-evidence.js +8 -1
  113. package/dist/domain/browser/broker.d.ts +99 -0
  114. package/dist/domain/browser/broker.js +487 -0
  115. package/dist/domain/costs/claude-account.js +21 -0
  116. package/dist/domain/costs/rate-limit-throttle.js +3 -1
  117. package/dist/domain/costs/reset-account.d.ts +2 -0
  118. package/dist/domain/costs/usage-service.d.ts +1 -1
  119. package/dist/domain/costs/usage-service.js +20 -7
  120. package/dist/domain/mcp/tools/context.d.ts +5 -6
  121. package/dist/domain/mcp/tools/context.js +17 -3
  122. package/dist/domain/mcp/tools/subagent.js +1 -1
  123. package/dist/domain/mcp/tools/ui-file.js +1 -1
  124. package/dist/domain/pi-providers/custom-provider-model.d.ts +1 -1
  125. package/dist/domain/pi-providers/custom-provider-model.js +1 -1
  126. package/dist/domain/remote/device-browser.js +1 -1
  127. package/dist/domain/remote/device-chrome-commands.js +2 -0
  128. package/dist/domain/remote/device-port.js +2 -2
  129. package/dist/domain/runs/attempt.d.ts +3 -3
  130. package/dist/domain/runs/attempt.js +2 -3
  131. package/dist/domain/runs/builders.d.ts +4 -4
  132. package/dist/domain/runs/builders.js +4 -5
  133. package/dist/domain/runs/compact.d.ts +4 -17
  134. package/dist/domain/runs/compact.js +14 -56
  135. package/dist/domain/runs/config-resolver.d.ts +15 -83
  136. package/dist/domain/runs/config-resolver.js +24 -150
  137. package/dist/domain/runs/engine-spec.d.ts +8 -8
  138. package/dist/domain/runs/engine-spec.js +15 -31
  139. package/dist/domain/runs/events.d.ts +1 -1
  140. package/dist/domain/runs/fallback.d.ts +6 -38
  141. package/dist/domain/runs/fallback.js +10 -72
  142. package/dist/domain/runs/notices.d.ts +1 -11
  143. package/dist/domain/runs/notices.js +3 -30
  144. package/dist/domain/runs/request.d.ts +4 -3
  145. package/dist/domain/runs/retryable-errors.d.ts +0 -13
  146. package/dist/domain/runs/retryable-errors.js +0 -17
  147. package/dist/domain/runs/run.d.ts +12 -42
  148. package/dist/domain/runs/run.js +40 -147
  149. package/dist/domain/runs/service.d.ts +1 -1
  150. package/dist/domain/runs/service.js +8 -3
  151. package/dist/domain/runs/spec-loader.d.ts +1 -1
  152. package/dist/domain/runs/spend.d.ts +1 -1
  153. package/dist/domain/runs/spend.js +1 -1
  154. package/dist/domain/scheduling/jobs/scheduled-task.d.ts +3 -2
  155. package/dist/domain/scheduling/jobs/scheduled-task.js +25 -19
  156. package/dist/domain/scheduling/schedule-ops.d.ts +0 -1
  157. package/dist/domain/scheduling/schedule-ops.js +2 -5
  158. package/dist/domain/scheduling/schedule-selection.d.ts +3 -0
  159. package/dist/domain/scheduling/schedule-selection.js +16 -0
  160. package/dist/domain/scheduling/schedule-spec.d.ts +6 -5
  161. package/dist/domain/scheduling/schedule-spec.js +6 -6
  162. package/dist/domain/scheduling/scheduler.d.ts +3 -1
  163. package/dist/domain/scheduling/scheduler.js +22 -21
  164. package/dist/domain/sessions/session-hooks.d.ts +5 -4
  165. package/dist/domain/sessions/session-hooks.js +15 -33
  166. package/dist/domain/sessions/session-lifecycle.d.ts +19 -51
  167. package/dist/domain/sessions/session-lifecycle.js +34 -96
  168. package/dist/domain/system/doctor.d.ts +3 -3
  169. package/dist/domain/system/doctor.js +22 -26
  170. package/dist/domain/system/own-bin-path.d.ts +13 -0
  171. package/dist/domain/system/own-bin-path.js +36 -0
  172. package/dist/domain/system/terminal-cli/index.d.ts +58 -0
  173. package/dist/domain/system/terminal-cli/index.js +100 -0
  174. package/dist/domain/system/terminal-cli/posix-profiles.d.ts +23 -0
  175. package/dist/domain/system/terminal-cli/posix-profiles.js +74 -0
  176. package/dist/domain/system/terminal-cli/registrar.d.ts +12 -0
  177. package/dist/domain/system/terminal-cli/registrar.js +1 -0
  178. package/dist/domain/system/terminal-cli/shims.d.ts +27 -0
  179. package/dist/domain/system/terminal-cli/shims.js +108 -0
  180. package/dist/domain/system/terminal-cli/state.d.ts +7 -0
  181. package/dist/domain/system/terminal-cli/state.js +36 -0
  182. package/dist/domain/system/terminal-cli/windows-user-path.d.ts +13 -0
  183. package/dist/domain/system/terminal-cli/windows-user-path.js +67 -0
  184. package/dist/domain/tui-session/tui-session-service.js +1 -1
  185. package/dist/domain/tui-session/types.d.ts +2 -2
  186. package/dist/domain/ui-service/app-router.d.ts +49 -71
  187. package/dist/domain/ui-service/app-router.js +9 -13
  188. package/dist/domain/ui-service/assistant-snapshots.js +2 -0
  189. package/dist/domain/ui-service/contract.parity.d.ts +19 -0
  190. package/dist/domain/ui-service/contract.parity.js +1 -0
  191. package/dist/domain/ui-service/inline-media-types.d.ts +18 -0
  192. package/dist/domain/ui-service/inline-media-types.js +1 -0
  193. package/dist/domain/ui-service/input-schemas.d.ts +52 -115
  194. package/dist/domain/ui-service/input-schemas.js +38 -84
  195. package/dist/domain/ui-service/mutate/auth.d.ts +1 -1
  196. package/dist/domain/ui-service/mutate/auth.js +3 -2
  197. package/dist/domain/ui-service/mutate/config.d.ts +0 -8
  198. package/dist/domain/ui-service/mutate/config.js +0 -22
  199. package/dist/domain/ui-service/mutate/models.d.ts +13 -0
  200. package/dist/domain/ui-service/mutate/models.js +137 -0
  201. package/dist/domain/ui-service/mutate/resolve-media.d.ts +4 -0
  202. package/dist/domain/ui-service/mutate/resolve-media.js +17 -0
  203. package/dist/domain/ui-service/mutate/sessions.d.ts +2 -2
  204. package/dist/domain/ui-service/mutate/sessions.js +29 -126
  205. package/dist/domain/ui-service/query/config.js +22 -42
  206. package/dist/domain/ui-service/query/models.js +2 -2
  207. package/dist/domain/ui-service/query/schedules.js +1 -1
  208. package/dist/domain/ui-service/query/sessions.js +7 -13
  209. package/dist/domain/ui-service/types.d.ts +51 -177
  210. package/dist/domain/ui-service/ui-service.d.ts +23 -49
  211. package/dist/domain/ui-service/ui-service.js +8 -6
  212. package/dist/entry/app.js +42 -19
  213. package/dist/entry/browser-cli.d.ts +39 -0
  214. package/dist/entry/browser-cli.js +317 -0
  215. package/dist/entry/cli-help.d.ts +1 -0
  216. package/dist/entry/cli-help.js +37 -6
  217. package/dist/entry/cli.js +16 -14
  218. package/dist/entry/daemon.js +2 -0
  219. package/dist/entry/init-auth.js +1 -1
  220. package/dist/entry/init.d.ts +7 -8
  221. package/dist/entry/init.js +89 -249
  222. package/dist/entry/path-cli.d.ts +4 -0
  223. package/dist/entry/path-cli.js +65 -0
  224. package/dist/entry/schedule-cli.js +13 -6
  225. package/dist/entry/shutdown.d.ts +1 -1
  226. package/dist/entry/shutdown.js +8 -1
  227. package/dist/entry/start-ui-http.js +8 -0
  228. package/dist/entry/ui-service-wiring.js +8 -10
  229. package/dist/events/event-types.d.ts +3 -2
  230. package/dist/orchestration/agent-runner.d.ts +2 -2
  231. package/dist/orchestration/agent-runner.js +10 -9
  232. package/dist/orchestration/benchmark-session-webhook.js +13 -1
  233. package/dist/orchestration/browser-webhook.d.ts +11 -0
  234. package/dist/orchestration/browser-webhook.js +28 -0
  235. package/dist/orchestration/cache-keep-warm.d.ts +77 -0
  236. package/dist/orchestration/cache-keep-warm.js +213 -0
  237. package/dist/orchestration/claude-window-warmup.d.ts +40 -0
  238. package/dist/orchestration/claude-window-warmup.js +126 -0
  239. package/dist/orchestration/conversation-request.d.ts +6 -10
  240. package/dist/orchestration/conversation-request.js +5 -23
  241. package/dist/orchestration/delta-coalescer.d.ts +4 -2
  242. package/dist/orchestration/delta-coalescer.js +5 -5
  243. package/dist/orchestration/edit-retry.js +9 -11
  244. package/dist/orchestration/inline-media-eager.d.ts +13 -0
  245. package/dist/orchestration/inline-media-eager.js +58 -0
  246. package/dist/orchestration/inline-media.d.ts +22 -0
  247. package/dist/orchestration/inline-media.js +151 -0
  248. package/dist/orchestration/interactions/ask-user-resume.js +3 -7
  249. package/dist/orchestration/interactions/interaction-handlers.js +6 -6
  250. package/dist/orchestration/mid-turn-inject.d.ts +2 -1
  251. package/dist/orchestration/mid-turn-inject.js +1 -1
  252. package/dist/orchestration/pending-injection-recovery.d.ts +2 -1
  253. package/dist/orchestration/pending-injection-recovery.js +1 -1
  254. package/dist/orchestration/routing/commands/index.js +4 -4
  255. package/dist/orchestration/routing/commands/mode.d.ts +5 -44
  256. package/dist/orchestration/routing/commands/mode.js +98 -272
  257. package/dist/orchestration/routing/commands/schedule.js +29 -18
  258. package/dist/orchestration/routing/commands/session.js +9 -9
  259. package/dist/orchestration/routing/commands/status.js +1 -1
  260. package/dist/orchestration/routing/commands/usage-format.js +3 -0
  261. package/dist/orchestration/routing/webhook.js +4 -0
  262. package/dist/orchestration/session-compact.d.ts +0 -1
  263. package/dist/orchestration/session-compact.js +5 -7
  264. package/dist/orchestration/session-events.d.ts +2 -1
  265. package/dist/orchestration/session-events.js +1 -0
  266. package/dist/orchestration/status-helpers.d.ts +0 -4
  267. package/dist/orchestration/status-helpers.js +0 -18
  268. package/dist/orchestration/subagent-webhook.js +9 -34
  269. package/dist/orchestration/team-webhook.d.ts +8 -9
  270. package/dist/orchestration/team-webhook.js +16 -42
  271. package/dist/orchestration/transcript-sink.d.ts +6 -0
  272. package/dist/orchestration/transcript-sink.js +21 -2
  273. package/dist/orchestration/turn/terminal.js +7 -7
  274. package/dist/orchestration/turn/turn-prep.d.ts +0 -8
  275. package/dist/orchestration/turn/turn-prep.js +0 -51
  276. package/dist/orchestration/turn/turn-tracking.d.ts +2 -2
  277. package/dist/orchestration/turn/turn-tracking.js +8 -5
  278. package/dist/orchestration/turn/turn.d.ts +0 -2
  279. package/dist/orchestration/turn/turn.js +13 -15
  280. package/dist/platform/adapters/tui/ports.d.ts +1 -1
  281. package/dist/platform/adapters/tui/tui-transcript.js +2 -0
  282. package/dist/platform/browser/agent-browser.d.ts +50 -0
  283. package/dist/platform/browser/agent-browser.js +165 -0
  284. package/dist/platform/browser/managed-browser.d.ts +1 -11
  285. package/dist/platform/browser/managed-browser.js +4 -12
  286. package/dist/platform/ui-http/browser-stream.d.ts +110 -0
  287. package/dist/platform/ui-http/browser-stream.js +447 -0
  288. package/dist/platform/ui-http/ui-http-server.d.ts +12 -0
  289. package/dist/platform/ui-http/ui-http-server.js +23 -6
  290. package/dist/store/conversation-history-reader.js +8 -0
  291. package/dist/store/conversation-history-repo.d.ts +8 -1
  292. package/dist/store/conversation-history-repo.js +5 -0
  293. package/dist/store/conversation-ledger-repo.d.ts +6 -6
  294. package/dist/store/conversation-ledger-repo.js +4 -4
  295. package/dist/store/models-repo.d.ts +18 -0
  296. package/dist/store/models-repo.js +74 -0
  297. package/dist/store/pending-injection-repo.d.ts +2 -1
  298. package/dist/store/pending-injection-repo.js +3 -1
  299. package/dist/store/retire-profiles-migration.d.ts +28 -0
  300. package/dist/store/retire-profiles-migration.js +335 -0
  301. package/dist/store/schedule-repo.d.ts +2 -1
  302. package/dist/store/session-registry-import.js +3 -2
  303. package/dist/store/session-registry-journal.d.ts +10 -13
  304. package/dist/store/session-registry-journal.js +48 -25
  305. package/dist/store/session-registry-repo.d.ts +4 -4
  306. package/dist/store/session-registry-repo.js +4 -5
  307. package/dist/store/version-migrations.d.ts +2 -3
  308. package/dist/store/version-migrations.js +19 -3
  309. package/dist/tui/slash-commands.js +2 -2
  310. package/dist/tui/turn-status.js +1 -1
  311. package/package.json +6 -4
  312. package/web/dist/assets/board-math-css-CB4GJ6qO.js +2 -0
  313. package/web/dist/assets/index-CaSZPg_H.css +1 -0
  314. package/web/dist/assets/index-CzOR7Edh.js +522 -0
  315. package/web/dist/assets/{index-CndZZ1IQ.js → index-cIGFv27z.js} +1 -1
  316. package/web/dist/index.html +3 -2
  317. package/web/dist/theme.css +6 -0
  318. package/dist/agent-adapter/browser-mcp-server.d.ts +0 -13
  319. package/dist/agent-adapter/browser-mcp-server.js +0 -28
  320. package/dist/agent-adapter/claude/browser-mcp.d.ts +0 -9
  321. package/dist/agent-adapter/claude/browser-mcp.js +0 -10
  322. package/dist/core/profile-generator.d.ts +0 -79
  323. package/dist/core/profile-generator.js +0 -215
  324. package/dist/domain/agents/profile-manager.d.ts +0 -103
  325. package/dist/domain/agents/profile-manager.js +0 -286
  326. package/dist/domain/agents/profile-switch.d.ts +0 -49
  327. package/dist/domain/agents/profile-switch.js +0 -62
  328. package/dist/domain/ui-service/mutate/profiles.d.ts +0 -36
  329. package/dist/domain/ui-service/mutate/profiles.js +0 -151
  330. package/dist/store/profile-repo.d.ts +0 -20
  331. package/dist/store/profile-repo.js +0 -97
  332. package/web/dist/assets/index-B76ueW3q.js +0 -494
  333. package/web/dist/assets/index-C8O0yxg8.css +0 -1
package/dist/entry/cli.js CHANGED
@@ -11,8 +11,8 @@ import { createLogger } from '../core/log.js';
11
11
  import { getResolvedPaths, formatConfigOutput, runInit, parseInitAnswersJson, } from './init.js';
12
12
  import { cmdFeishu } from './feishu-login.js';
13
13
  import { cmdDoctor } from './doctor-cli.js';
14
- import { discoverEndpoints, writeMergedGatewayYaml, validateProfilesAgainstGateway, dryRunGatewayYaml } from '../core/gateway-generator.js';
15
- import { generateProfiles, writeProfilesJson } from '../core/profile-generator.js';
14
+ import { discoverEndpoints, writeMergedGatewayYaml, validateModelsAgainstGateway, dryRunGatewayYaml } from '../core/gateway-generator.js';
15
+ import { readExistingModels, writeModelsJson } from '../core/models-generator.js';
16
16
  import { CORTEX_VERSION } from '../core/version.js';
17
17
  import { getAuthStatus } from '../domain/auth/auth-status.js';
18
18
  import { defaultCustomProviderStores } from '../domain/pi-providers/index.js';
@@ -20,6 +20,7 @@ import { runAuthCli } from './auth-cli.js';
20
20
  import { getCliHelp, getInitHelp, getSetupGatewayHelp, getTuiHelp, } from './cli-help.js';
21
21
  import { runUiCli } from './ui-cli.js';
22
22
  import { runClientCli } from './client-cli.js';
23
+ import { runPathCli } from './path-cli.js';
23
24
  import { LoginCliError } from './auth-login-cli.js';
24
25
  import { t } from '../core/i18n.js';
25
26
  // ─── Paths ──────────────────────────────────────────────────────
@@ -355,37 +356,37 @@ function appendDroppedWarnings(lines, result) {
355
356
  lines.push(`WARNING: preserved ${result.droppedFromDiscovery.length} existing gateway mode(s) not reported by discovery: ${list}`);
356
357
  lines.push(' (if these should auto-detect, check `cortex auth status` and log the provider in)');
357
358
  }
358
- function appendProfileIssues(lines, issues) {
359
+ function appendModelIssues(lines, issues) {
359
360
  if (issues.length === 0)
360
361
  return;
361
- lines.push(`WARNING: ${issues.length} profile(s) reference an unconfigured gateway mode (would fail with "Unknown mode"):`);
362
+ lines.push(`WARNING: ${issues.length} model selection(s) reference an unconfigured gateway route:`);
362
363
  for (const issue of issues)
363
- lines.push(` - ${issue.profile}: ${issue.reason}`);
364
+ lines.push(` - ${issue.model}: ${issue.reason}`);
364
365
  }
365
- function gatewayOutput(endpoints, outputDir, gatewayPath, profilesPath, mergeResult) {
366
- const profiles = generateProfiles(endpoints);
367
- const profileNames = Object.keys(profiles.profiles).join(', ');
366
+ function gatewayOutput(endpoints, outputDir, gatewayPath, modelsPath, mergeResult) {
367
+ const models = readExistingModels(path.dirname(modelsPath));
368
+ const favorites = models.favorites.map(ref => ref.model).join(', ');
368
369
  const lines = [
369
370
  outputDir ? `[TEST MODE] Output directory: ${outputDir}` : '',
370
371
  `Gateway config: ${gatewayPath}`,
371
- `Profiles: ${profilesPath}`,
372
+ `Models: ${modelsPath}`,
372
373
  `Discovered ${endpoints.length} endpoint modes`,
373
- `Generated profiles: ${profileNames} (default: ${profiles.defaultProfile})`,
374
+ `Favorites: ${favorites} (default: ${models.default.model})`,
374
375
  ];
375
376
  appendDroppedWarnings(lines, mergeResult);
376
- appendProfileIssues(lines, validateProfilesAgainstGateway(mergeResult.endpoints, outputDir));
377
+ appendModelIssues(lines, validateModelsAgainstGateway(mergeResult.endpoints, outputDir));
377
378
  return lines.filter(Boolean).join('\n');
378
379
  }
379
380
  async function writeGatewayConfiguration(outputDir) {
380
381
  const endpoints = await discoverEndpoints();
381
- if (endpoints.length === 0) {
382
+ if (!endpoints.some(endpoint => endpoint.models.length > 0)) {
382
383
  return { exitCode: 0, stdout: 'No backends discovered. Log into Claude Code and/or PI first.\n', stderr: '' };
383
384
  }
384
385
  const { path: gatewayPath, result } = writeMergedGatewayYaml(endpoints, outputDir);
385
- const profilesPath = writeProfilesJson(endpoints, { outputDir });
386
+ const modelsPath = writeModelsJson(endpoints, { outputDir });
386
387
  return {
387
388
  exitCode: 0,
388
- stdout: gatewayOutput(endpoints, outputDir, gatewayPath, profilesPath, result),
389
+ stdout: gatewayOutput(endpoints, outputDir, gatewayPath, modelsPath, result),
389
390
  stderr: '',
390
391
  };
391
392
  }
@@ -448,6 +449,7 @@ const CLI_HANDLERS = {
448
449
  'setup-gateway': (args) => runSetupGatewayCli(args),
449
450
  ui: (args) => runUiCli(args),
450
451
  client: (args) => runClientCli(args),
452
+ path: (args) => runPathCli(args),
451
453
  install: (args) => runInstallCli(args),
452
454
  schedule: async (args) => (await import('./schedule-cli.js')).runScheduleCli(args),
453
455
  memory: async (args) => (await import('./memory-cli.js')).runMemoryCli(args),
@@ -79,6 +79,7 @@ import { isMainModule, moduleDir, withServerNpmPrefix } from '../core/utils.js';
79
79
  import { DATA_DIR, CONFIG_DIR, INSTALL_ROOT, DAEMON_PID_FILE, DAEMON_CHILD_PID_FILE, RESTART_TRIGGER_FILE, } from '../core/paths.js';
80
80
  import { planFastInstall, applyFastInstall } from './fast-install.js';
81
81
  import { tryAcquireSingletonLock, releaseSingletonLock as releaseLock } from '../core/singleton-lock.js';
82
+ import { ensureOwnBinsOnPath } from '../domain/system/own-bin-path.js';
82
83
  import { finishRebuildStep, planRebuildProgress, settleRebuildProgress, startRebuildStep, writeRebuildProgress, } from '../core/rebuild-progress.js';
83
84
  // Load .env BEFORE reading any CORTEX_* env vars below. Mirrors app.ts §61 — the
84
85
  // daemon needs CORTEX_REPO (and potentially other vars) from .env, not just from
@@ -884,6 +885,7 @@ function main() {
884
885
  acquireSingletonLock();
885
886
  process.on('exit', releaseSingletonLock);
886
887
  log.info('Cortex Daemon starting...');
888
+ ensureOwnBinsOnPath();
887
889
  setupShutdown();
888
890
  startChild();
889
891
  watchMonitors = setupWatchers();
@@ -32,7 +32,7 @@ export async function onboardInitAuth(interactive, emit, deps = defaultLoginDeps
32
32
  if (action === 'continue')
33
33
  return available;
34
34
  if (action === 'login') {
35
- const result = await runAuthLoginCli([], { ...deps, sync: async () => ({ configured: false, endpoints: 0, profiles: [], reason: 'deferred-to-init' }) });
35
+ const result = await runAuthLoginCli([], { ...deps, sync: async () => ({ configured: false, endpoints: 0, defaultSet: false, favorites: [], reason: 'deferred-to-init' }) });
36
36
  if (result.exitCode === 130)
37
37
  throw new LoginCliError(t('init.cancel'), 130);
38
38
  deps.ui.notify({ kind: 'info', message: result.stderr || t('init.auth.saved') });
@@ -1,5 +1,5 @@
1
1
  export { isGitInstalled, ensureGitInstalled, getGitInstallHint } from './init-git.js';
2
- import type { ModelChoice } from '../core/profile-generator.js';
2
+ import type { ModelChoice } from '../core/models-generator.js';
3
3
  import { type UsageSharingUpdate } from '../domain/costs/aistatus-config.js';
4
4
  import { type Locale } from '../core/i18n.js';
5
5
  import { cmdFeishu } from './feishu-login.js';
@@ -44,13 +44,10 @@ export interface InitAnswers {
44
44
  /** Omitted when a scripted caller did not make an upload choice. */
45
45
  gatewayUsage?: GatewayUsageConfig;
46
46
  installService: boolean;
47
- /** Explicit (mode, model) for the `plan` profile. Non-interactive only; interactive picks
48
- * inside runGatewaySetup once endpoints are discovered. Undefined → auto-infer. */
49
- planChoice?: ModelChoice;
50
- /** Explicit (mode, model) for the `execute` profile. Same semantics as planChoice. */
51
- executeChoice?: ModelChoice;
52
- /** Additional models to register as standalone named profiles. Non-interactive only. */
53
- extraProfiles?: ModelChoice[];
47
+ /** Default model; omitted uses the discovery recommendation. */
48
+ defaultChoice?: ModelChoice;
49
+ /** Favorite models; the default model is always included. */
50
+ favorites?: ModelChoice[];
54
51
  /**
55
52
  * Enable the loopback Web UI endpoint the native desktop app connects to. Set by the desktop
56
53
  * setup wizard (`--answers`); the terminal wizard leaves it undefined, so a normal `cortex init`
@@ -129,6 +126,8 @@ export declare function runFeishuUserLogin(config: FeishuInitConfig, configDir:
129
126
  cmdFeishuImpl?: typeof cmdFeishu;
130
127
  stdout?: (s: string) => void;
131
128
  }): Promise<CliResult>;
129
+ /** Seven setup lines, platform token blocks, then defaultChoice and comma-separated favorites. */
130
+ export declare function parseInitAnswersLines(lines: string[]): InitAnswers;
132
131
  export declare function safeCopy(src: string, dst: string, force: boolean): boolean;
133
132
  export declare function generateConfigs(paths: InitPaths, answers: InitAnswers, force: boolean): void;
134
133
  export declare function writeDotEnv(paths: InitPaths, answers: InitAnswers, force: boolean): void;
@@ -11,8 +11,8 @@ export { isGitInstalled, ensureGitInstalled, getGitInstallHint } from './init-gi
11
11
  import { onboardInitAuth } from './init-auth.js';
12
12
  import * as clack from '@clack/prompts';
13
13
  import { buildCoreConfig, buildEmptyConfig, buildFullConfig, buildInteractionConfig, } from '../core/config-generator.js';
14
- import { discoverEndpoints, writeMergedGatewayYaml, validateProfilesAgainstGateway } from '../core/gateway-generator.js';
15
- import { generateProfiles, writeProfilesJson, listChoices, recommendedChoice } from '../core/profile-generator.js';
14
+ import { discoverEndpoints, writeMergedGatewayYaml, validateModelsAgainstGateway } from '../core/gateway-generator.js';
15
+ import { readExistingModels, writeModelsJson, listChoices, recommendedChoice } from '../core/models-generator.js';
16
16
  import { ENVIRONMENTS_DIRNAME, mergeDefaultEnvironments } from '../domain/agents/environments/index.js';
17
17
  import { createLogger } from '../core/log.js';
18
18
  import { INSTALL_ROOT, DEFAULTS_DIR } from '../core/paths.js';
@@ -120,10 +120,9 @@ export function parseInitAnswersJson(raw) {
120
120
  feishuConfig: input.feishuConfig,
121
121
  gatewayUsage,
122
122
  installService: input.installService === true,
123
- planChoice: parseChoiceValue(input.planChoice),
124
- executeChoice: parseChoiceValue(input.executeChoice),
125
- extraProfiles: Array.isArray(input.extraProfiles)
126
- ? input.extraProfiles.map(parseChoiceValue).filter((c) => !!c)
123
+ defaultChoice: parseChoiceValue(input.defaultChoice),
124
+ favorites: Array.isArray(input.favorites)
125
+ ? input.favorites.map(parseChoiceValue).filter((c) => !!c)
127
126
  : undefined,
128
127
  localUi: parseLocalUi(input.localUi),
129
128
  localClient: parseLocalClientAnswer(input.localClient),
@@ -145,8 +144,8 @@ function parseChoiceLine(raw) {
145
144
  model: trimmed.substring(colonIdx + 1).trim(),
146
145
  };
147
146
  }
148
- /** Parse comma-separated "mode:model" pairs for extra profiles. Returns undefined for empty. */
149
- function parseExtraProfilesLine(raw) {
147
+ /** Parse comma-separated "mode:model" favorites. Returns undefined for empty. */
148
+ function parseFavoritesLine(raw) {
150
149
  if (!raw)
151
150
  return undefined;
152
151
  const trimmed = raw.trim();
@@ -209,7 +208,6 @@ export function generateDotEnvContent(answers) {
209
208
  /** Generate default agent-state.json content (compact JSON, single line). */
210
209
  export function generateDefaultModeJson() {
211
210
  return JSON.stringify({
212
- activeProfile: '__active__',
213
211
  defaultAgent: 'main',
214
212
  });
215
213
  }
@@ -870,73 +868,48 @@ async function collectAnswersNonInteractive() {
870
868
  for await (const line of rl) {
871
869
  lines.push(line);
872
870
  }
873
- // Line format:
874
- // backends, platform, gatewayEnabled, name, org, email, installService
875
- // [+ platform-specific token blocks, concatenated in fixed order: slack first, then feishu]
876
- // `platform` is a comma-separated list (e.g. "slack,feishu"); single values are back-compat.
877
- const [backendsRaw, platformRaw, gatewayEnabledRaw, name, org, email, installServiceRaw] = lines;
878
- const backends = (backendsRaw || 'pi')
879
- .split(',')
880
- .map(s => s.trim())
881
- .filter((s) => s === 'claude' || s === 'pi');
882
- // Parse the platform list, keeping valid values in order and de-duplicating.
883
- const platforms = [];
884
- const seenPlatforms = new Set();
885
- for (const raw of (platformRaw || '').split(',')) {
886
- const p = raw.trim().toLowerCase();
887
- if ((p === 'slack' || p === 'feishu') && !seenPlatforms.has(p)) {
888
- seenPlatforms.add(p);
889
- platforms.push(p);
890
- }
891
- }
892
- const gatewayChoice = gatewayEnabledRaw?.trim().toLowerCase();
893
871
  log.info('Cortex Initialization (non-interactive)');
894
- // Parse platform token blocks from remaining lines (starting at index 7). Blocks are
895
- // concatenated in fixed order — slack (3 lines), then feishu (3 lines) — regardless of the
896
- // order given in the platform list. The profile-choice lines (optional "mode:model"; empty
897
- // → auto-infer) follow whatever token lines were consumed. Single-platform layouts are
898
- // back-compatible: slack-only → choices at 10; feishu-only → choices at 10.
872
+ return parseInitAnswersLines(lines);
873
+ }
874
+ function stdinPlatforms(raw = '') {
875
+ const values = raw.split(',').map(value => value.trim().toLowerCase());
876
+ return [...new Set(values.filter((value) => value === 'slack' || value === 'feishu'))];
877
+ }
878
+ /** Token blocks always use Slack then Feishu order, regardless of platform display order. */
879
+ function stdinPlatformTokens(lines, platforms) {
899
880
  let slackConfig;
900
881
  let feishuConfig;
901
882
  let cursor = 7;
902
883
  if (platforms.includes('slack') && lines.length >= cursor + 3) {
903
- slackConfig = {
904
- signingSecret: lines[cursor] || '',
905
- appToken: lines[cursor + 1] || '',
906
- botToken: lines[cursor + 2] || '',
907
- };
884
+ slackConfig = { signingSecret: lines[cursor] || '', appToken: lines[cursor + 1] || '', botToken: lines[cursor + 2] || '' };
908
885
  cursor += 3;
909
886
  }
910
887
  if (platforms.includes('feishu') && lines.length >= cursor + 3) {
911
- const domainVal = (lines[cursor + 2] || '').trim().toLowerCase();
912
- feishuConfig = {
913
- appId: lines[cursor] || '',
914
- appSecret: lines[cursor + 1] || '',
915
- domain: (domainVal === 'feishu' || domainVal === 'lark')
916
- ? domainVal
917
- : undefined,
918
- };
888
+ const domain = (lines[cursor + 2] || '').trim().toLowerCase();
889
+ feishuConfig = { appId: lines[cursor] || '', appSecret: lines[cursor + 1] || '',
890
+ domain: domain === 'feishu' || domain === 'lark' ? domain : undefined };
919
891
  cursor += 3;
920
892
  }
921
- const profileChoiceStart = cursor;
922
- const planChoice = parseChoiceLine(lines[profileChoiceStart]);
923
- const executeChoice = parseChoiceLine(lines[profileChoiceStart + 1]);
924
- const extraProfiles = parseExtraProfilesLine(lines[profileChoiceStart + 2]);
893
+ return { slackConfig, feishuConfig, cursor };
894
+ }
895
+ /** Seven setup lines, platform token blocks, then defaultChoice and comma-separated favorites. */
896
+ export function parseInitAnswersLines(lines) {
897
+ const [backendsRaw, platformRaw, gatewayEnabledRaw, name, org, email, installServiceRaw] = lines;
898
+ const backends = (backendsRaw || 'pi').split(',').map(s => s.trim())
899
+ .filter((s) => s === 'claude' || s === 'pi');
900
+ const platforms = stdinPlatforms(platformRaw);
901
+ const { slackConfig, feishuConfig, cursor } = stdinPlatformTokens(lines, platforms);
902
+ const gatewayChoice = gatewayEnabledRaw?.trim().toLowerCase();
925
903
  return {
926
904
  lang: process.env.CORTEX_LANG ? normalizeLocale(process.env.CORTEX_LANG) : detectSystemLocale(),
927
905
  backends: backends.length > 0 ? backends : ['claude'],
928
- machineName: os.hostname(),
929
- gpuCount: detectGpuCount(),
930
- platforms,
931
- slackConfig,
932
- feishuConfig,
906
+ machineName: os.hostname(), gpuCount: detectGpuCount(), platforms, slackConfig, feishuConfig,
933
907
  gatewayUsage: gatewayChoice === 'y'
934
908
  ? { enabled: true, name: name || '', org: org || '', email: email || '' }
935
909
  : gatewayChoice === 'n' ? { enabled: false } : undefined,
936
910
  installService: installServiceRaw?.toLowerCase() === 'y',
937
- planChoice,
938
- executeChoice,
939
- extraProfiles,
911
+ defaultChoice: parseChoiceLine(lines[cursor]),
912
+ favorites: parseFavoritesLine(lines[cursor + 1]),
940
913
  };
941
914
  }
942
915
  // ─── Directory creation ─────────────────────────────────────────
@@ -1112,190 +1085,75 @@ export function writeDotEnv(paths, answers, force) {
1112
1085
  }
1113
1086
  writeFileSync(envPath, content);
1114
1087
  }
1115
- // ─── Gateway & profile auto-setup ──────────────────────────────
1116
- /** Detect whether a profiles.json at <configDir>/profiles.json already has `plan` or `execute`. */
1117
- function detectExistingPlanOrExecute(configDir) {
1118
- const profilesPath = path.join(configDir, 'profiles.json');
1119
- if (!existsSync(profilesPath))
1120
- return false;
1121
- try {
1122
- const data = JSON.parse(readFileSync(profilesPath, 'utf-8'));
1123
- return !!(data?.profiles?.plan || data?.profiles?.execute);
1124
- }
1125
- catch {
1126
- return false;
1127
- }
1088
+ // ─── Gateway & model auto-setup ──────────────────────────────
1089
+ async function confirmDefaultOverwrite(configDir) {
1090
+ if (!readExistingModels(configDir)?.default)
1091
+ return true;
1092
+ const confirm = await clack.confirm({ message: t('init.gatewaySetup.overwritePrompt'), initialValue: false });
1093
+ handleCancel(confirm);
1094
+ return confirm;
1128
1095
  }
1129
- /**
1130
- * Interactively pick plan / execute (mode, model) from discovered endpoints, plus optional
1131
- * fallback chains. Lists are sorted lexicographically; the recommended choice is pre-selected.
1132
- *
1133
- * Returns `overwrite: false` if the user declined to overwrite an existing profile — in that
1134
- * case all *Choice / *Fallback fields are undefined.
1135
- */
1136
- async function pickPlanExecuteInteractive(endpoints, configDir) {
1137
- // If existing profiles.json has plan/execute, ask before overwriting
1138
- if (detectExistingPlanOrExecute(configDir)) {
1139
- const confirm = await clack.confirm({
1140
- message: t('init.gatewaySetup.overwritePrompt'),
1141
- initialValue: false,
1142
- });
1143
- handleCancel(confirm);
1144
- if (!confirm) {
1145
- return { overwrite: false };
1146
- }
1147
- }
1096
+ /** Pick a recommended default and favorites. The default is included even if untoggled. */
1097
+ async function pickModelsInteractive(endpoints, configDir) {
1098
+ if (!await confirmDefaultOverwrite(configDir))
1099
+ return { overwrite: false };
1148
1100
  const choices = listChoices(endpoints);
1149
- if (choices.length === 0)
1101
+ if (!choices.length)
1150
1102
  return { overwrite: true };
1151
- const formatValue = (c) => `${c.mode}:${c.model}`;
1152
- const parseValue = (v) => {
1153
- const colonIdx = v.indexOf(':');
1154
- return { mode: v.substring(0, colonIdx), model: v.substring(colonIdx + 1) };
1155
- };
1156
- const options = choices.map(c => ({
1157
- value: formatValue(c),
1158
- label: `${c.mode} / ${c.model}`,
1159
- }));
1160
- // Pre-select the same model a non-interactive setup would pick.
1161
- const firstChoiceValue = formatValue(recommendedChoice(endpoints) ?? choices[0]);
1162
- const planSel = await clack.select({
1163
- message: t('init.gatewaySetup.planPrompt'),
1164
- options,
1165
- initialValue: firstChoiceValue,
1103
+ const format = (choice) => `${choice.mode}:${choice.model}`;
1104
+ const options = choices.map(choice => ({ value: format(choice), label: `${choice.mode} / ${choice.model}` }));
1105
+ const selected = await clack.select({
1106
+ message: t('init.gatewaySetup.defaultPrompt'), options,
1107
+ initialValue: format(recommendedChoice(endpoints) ?? choices[0]),
1166
1108
  });
1167
- handleCancel(planSel);
1168
- const execSel = await clack.select({
1169
- message: t('init.gatewaySetup.executePrompt'),
1170
- options,
1171
- initialValue: firstChoiceValue,
1109
+ handleCancel(selected);
1110
+ const favorites = await clack.multiselect({
1111
+ message: t('init.gatewaySetup.favoritesPrompt'), options,
1112
+ required: false, initialValues: [selected],
1172
1113
  });
1173
- handleCancel(execSel);
1174
- const planChoice = parseValue(planSel);
1175
- const execChoice = parseValue(execSel);
1176
- // ── Fallback selection (multi-select, ordered) ──
1177
- // Build fallback options excluding the primary choice. If no candidates remain (e.g. only
1178
- // one discovered model), skip the prompt entirely.
1179
- const planFallbackOptions = options.filter(o => o.value !== planSel);
1180
- const execFallbackOptions = options.filter(o => o.value !== execSel);
1181
- let planFallback;
1182
- if (planFallbackOptions.length > 0) {
1183
- const sel = await clack.multiselect({
1184
- message: t('init.gatewaySetup.planFallbackPrompt'),
1185
- options: planFallbackOptions,
1186
- required: false,
1187
- initialValues: [],
1188
- });
1189
- handleCancel(sel);
1190
- const arr = sel;
1191
- if (arr.length > 0)
1192
- planFallback = arr.map(parseValue);
1193
- }
1194
- let executeFallback;
1195
- if (execFallbackOptions.length > 0) {
1196
- const sel = await clack.multiselect({
1197
- message: t('init.gatewaySetup.executeFallbackPrompt'),
1198
- options: execFallbackOptions,
1199
- required: false,
1200
- initialValues: [],
1201
- });
1202
- handleCancel(sel);
1203
- const arr = sel;
1204
- if (arr.length > 0)
1205
- executeFallback = arr.map(parseValue);
1206
- }
1207
- // ── Extra profiles: additional models to register as standalone named profiles ──
1208
- let extraProfiles;
1209
- if (options.length > 0) {
1210
- const sel = await clack.multiselect({
1211
- message: t('init.gatewaySetup.extraProfilesPrompt'),
1212
- options,
1213
- required: false,
1214
- initialValues: [],
1215
- });
1216
- handleCancel(sel);
1217
- const arr = sel;
1218
- if (arr.length > 0)
1219
- extraProfiles = arr.map(parseValue);
1114
+ handleCancel(favorites);
1115
+ const values = new Set([selected, ...favorites]);
1116
+ return { defaultChoice: parseChoiceLine(selected), favorites: [...values].map(v => parseChoiceLine(v)), overwrite: true };
1117
+ }
1118
+ function writeDiscoveredGateway(endpoints, configDir) {
1119
+ 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');
1120
+ clack.log.success(t('init.gatewaySetup.discovered', { count: endpoints.length, summary }));
1121
+ const { path: gatewayPath, result } = writeMergedGatewayYaml(endpoints, configDir);
1122
+ clack.log.success(t('init.gatewaySetup.gatewayWritten', { path: gatewayPath }));
1123
+ if (result.droppedFromDiscovery.length > 0) {
1124
+ const list = result.droppedFromDiscovery.map(p => `${p.mode}/${p.endpoint}`).join(', ');
1125
+ clack.log.warn(t('init.gatewaySetup.preservedModes', { count: result.droppedFromDiscovery.length, list }));
1126
+ clack.log.info(t('init.gatewaySetup.preservedModesHint'));
1220
1127
  }
1221
- return {
1222
- planChoice,
1223
- executeChoice: execChoice,
1224
- planFallback,
1225
- executeFallback,
1226
- extraProfiles,
1227
- overwrite: true,
1228
- };
1128
+ return result.endpoints;
1129
+ }
1130
+ function reportModelsSetup(configDir, endpoints) {
1131
+ const models = readExistingModels(configDir);
1132
+ clack.log.info(t('init.gatewaySetup.generatedModels', {
1133
+ names: models.favorites.map(ref => ref.model).join(', '), default: models.default.model,
1134
+ }));
1135
+ const issues = validateModelsAgainstGateway(endpoints, configDir);
1136
+ if (!issues.length)
1137
+ return;
1138
+ const lines = issues.map(i => ` - ${i.model}: ${i.reason}`).join('\n');
1139
+ clack.log.warn(t('init.gatewaySetup.modelIssues', { count: issues.length, lines }));
1140
+ clack.log.info(t('init.gatewaySetup.modelIssuesHint'));
1229
1141
  }
1230
1142
  /** Returns false when no backend is logged in yet, so nothing could be generated. */
1231
1143
  async function runGatewaySetup(backends, paths, gatewayConfigDir, answers, interactive = false) {
1232
- // Discover endpoints from Claude/PI local configs — filtered by user-selected backends
1233
1144
  const endpoints = await discoverEndpoints(backends);
1234
- if (endpoints.length === 0) {
1145
+ if (!endpoints.some(endpoint => endpoint.models.length > 0)) {
1235
1146
  clack.log.warn(t('init.gatewaySetup.noBackends'));
1236
1147
  clack.log.info(t('init.gatewaySetup.rerunHint'));
1237
1148
  return false;
1238
1149
  }
1239
- // Show discovered summary
1240
- 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');
1241
- clack.log.success(t('init.gatewaySetup.discovered', { count: endpoints.length, summary }));
1242
- // Generate gateway.yaml — scoped to gatewayConfigDir when provided (test/alt env),
1243
- // otherwise defaults to ~/.aistatus/gateway.yaml (production). Merge-aware: preserves
1244
- // hand-maintained modes/keys and never drops previously-configured modes if discovery
1245
- // under-reports (e.g. a transient PI model scan failure).
1246
- const { path: gatewayPath, result: mergeResult } = writeMergedGatewayYaml(endpoints, gatewayConfigDir);
1247
- clack.log.success(t('init.gatewaySetup.gatewayWritten', { path: gatewayPath }));
1248
- if (mergeResult.droppedFromDiscovery.length > 0) {
1249
- const list = mergeResult.droppedFromDiscovery.map(p => `${p.mode}/${p.endpoint}`).join(', ');
1250
- clack.log.warn(t('init.gatewaySetup.preservedModes', { count: mergeResult.droppedFromDiscovery.length, list }));
1251
- clack.log.info(t('init.gatewaySetup.preservedModesHint'));
1252
- }
1253
- // Resolve plan/execute choices + fallback chains + extra profiles + overwrite intent.
1254
- let planChoice = answers?.planChoice;
1255
- let executeChoice = answers?.executeChoice;
1256
- let planFallback;
1257
- let executeFallback;
1258
- let extraProfiles = answers?.extraProfiles;
1259
- let overwrite;
1260
- if (interactive) {
1261
- // Interactive: prompt for selection (with overwrite confirmation if needed)
1262
- const picked = await pickPlanExecuteInteractive(endpoints, paths.CONFIG_DIR);
1263
- planChoice = picked.planChoice ?? planChoice;
1264
- executeChoice = picked.executeChoice ?? executeChoice;
1265
- planFallback = picked.planFallback;
1266
- executeFallback = picked.executeFallback;
1267
- extraProfiles = picked.extraProfiles ?? extraProfiles;
1268
- overwrite = picked.overwrite;
1269
- }
1270
- else {
1271
- // Non-interactive: stdin already provided choices (or empty → lex-first default).
1272
- // Fallback chains are not configurable via stdin in this iteration — extend the stdin
1273
- // protocol if scripted installs need fallback.
1274
- overwrite = !!(answers?.planChoice || answers?.executeChoice || answers?.extraProfiles);
1275
- }
1276
- // Generate profiles.json
1277
- const profilesPath = writeProfilesJson(endpoints, {
1278
- outputDir: paths.CONFIG_DIR,
1279
- planChoice,
1280
- executeChoice,
1281
- planFallback,
1282
- executeFallback,
1283
- extraProfiles,
1284
- overwrite,
1285
- });
1286
- clack.log.success(t('init.gatewaySetup.profilesWritten', { path: profilesPath }));
1287
- // Show profile summary (reflects what was actually generated, not what was merged)
1288
- const profiles = generateProfiles(endpoints, { planChoice, executeChoice, planFallback, executeFallback, extraProfiles });
1289
- const profileNames = Object.keys(profiles.profiles).join(', ');
1290
- clack.log.info(t('init.gatewaySetup.generatedProfiles', { names: profileNames, default: profiles.defaultProfile }));
1291
- // Validate profile ↔ gateway mode coupling. A profile referencing a non-existent gateway mode is
1292
- // exactly what produces a silent `400 Unknown mode: <x>` at runtime. Non-fatal — warn only.
1293
- const issues = validateProfilesAgainstGateway(mergeResult.endpoints, paths.CONFIG_DIR);
1294
- if (issues.length > 0) {
1295
- const lines = issues.map(i => ` - ${i.profile}: ${i.reason}`).join('\n');
1296
- clack.log.warn(t('init.gatewaySetup.profileIssues', { count: issues.length, lines }));
1297
- clack.log.info(t('init.gatewaySetup.profileIssuesHint'));
1298
- }
1150
+ const mergedEndpoints = writeDiscoveredGateway(endpoints, gatewayConfigDir);
1151
+ const options = interactive
1152
+ ? await pickModelsInteractive(endpoints, paths.CONFIG_DIR)
1153
+ : { ...answers, overwrite: !!answers?.defaultChoice };
1154
+ const modelsPath = writeModelsJson(endpoints, { ...options, outputDir: paths.CONFIG_DIR });
1155
+ clack.log.success(t('init.gatewaySetup.modelsWritten', { path: modelsPath }));
1156
+ reportModelsSetup(paths.CONFIG_DIR, mergedEndpoints);
1299
1157
  return true;
1300
1158
  }
1301
1159
  /**
@@ -1387,7 +1245,7 @@ async function runInitSteps(paths, force, options, emitter) {
1387
1245
  else {
1388
1246
  // Non-interactive: auto-detect silently, passing caller-supplied choices. A machine with no
1389
1247
  // backend logged in yet yields no endpoints — expected on a fresh desktop install, where the
1390
- // user logs in from the workbench afterwards and the server syncs profiles from that login.
1248
+ // user logs in from the workbench afterwards and the server syncs models from that login.
1391
1249
  try {
1392
1250
  const configured = await runGatewaySetup(answers.backends, paths, options.gatewayConfigDir, answers);
1393
1251
  emit({ step: 'gateway', state: configured ? 'ok' : 'skip', reason: configured ? undefined : 'no-backend-login' });
@@ -1397,25 +1255,7 @@ async function runInitSteps(paths, force, options, emitter) {
1397
1255
  emit({ step: 'gateway', state: 'skip', reason: e.message });
1398
1256
  }
1399
1257
  }
1400
- // 8. Patch the stored activeProfile to match profiles.json defaultProfile
1401
- try {
1402
- const profilesJsonPath = path.join(paths.CONFIG_DIR, 'profiles.json');
1403
- const statePath = path.join(paths.STORE_DIR, 'agent-state.json');
1404
- const modeJsonPath = existsSync(statePath) ? statePath : path.join(paths.STORE_DIR, 'mode.json');
1405
- if (existsSync(profilesJsonPath) && existsSync(modeJsonPath)) {
1406
- const profilesData = JSON.parse(readFileSync(profilesJsonPath, 'utf8'));
1407
- const modeData = JSON.parse(readFileSync(modeJsonPath, 'utf8'));
1408
- if (modeData.activeProfile === '__active__' && profilesData.defaultProfile) {
1409
- modeData.activeProfile = profilesData.defaultProfile;
1410
- writeFileSync(modeJsonPath, JSON.stringify(modeData));
1411
- log.info(`${path.basename(modeJsonPath)} activeProfile set to "${profilesData.defaultProfile}"`);
1412
- }
1413
- }
1414
- }
1415
- catch (e) {
1416
- log.warn(`Failed to update the stored activeProfile: ${e.message}`);
1417
- }
1418
- // 9. Done
1258
+ // 8. Done
1419
1259
  clack.outro(t('init.outro', { dataDir: paths.DATA_DIR }));
1420
1260
  emit({
1421
1261
  step: 'result',
@@ -0,0 +1,4 @@
1
+ import { type CliResult } from '../core/cli-utils.js';
2
+ import { defaultTerminalCliContext } from '../domain/system/terminal-cli/index.js';
3
+ /** `cortex path install|remove|status` — make this install's commands reachable from terminals. */
4
+ export declare function runPathCli(args: string[], makeContext?: typeof defaultTerminalCliContext): CliResult;
@@ -0,0 +1,65 @@
1
+ import { formatError } from '../core/cli-utils.js';
2
+ import { getResolvedPaths } from './init.js';
3
+ import { getPathHelp } from './cli-help.js';
4
+ import { defaultTerminalCliContext, installTerminalCli, removeTerminalCli, terminalCliStatus, } from '../domain/system/terminal-cli/index.js';
5
+ const SUBCOMMANDS = ['install', 'remove', 'status'];
6
+ function optionValue(args, flag) {
7
+ const index = args.indexOf(flag);
8
+ return index !== -1 && args[index + 1] ? args[index + 1] : undefined;
9
+ }
10
+ const fail = (message) => ({
11
+ exitCode: 1, stdout: '', stderr: formatError(message, { validValues: SUBCOMMANDS, hint: 'cortex path --help' }),
12
+ });
13
+ function targetsLine(report, key, label) {
14
+ const hits = report.path_targets.filter((t) => t[key]).map((t) => t.target);
15
+ return `${label}: ${hits.length ? hits.join(', ') : 'none'}`;
16
+ }
17
+ function installText(report) {
18
+ const lines = [
19
+ `${report.dry_run ? 'Would install' : 'Installed'} terminal commands in ${report.dir}`,
20
+ targetsLine(report, 'changed', report.dry_run ? 'PATH would change in' : 'PATH updated in'),
21
+ 'Open a new terminal to use `cortex`.',
22
+ ];
23
+ if (report.shadowed.length)
24
+ lines.push(`New terminals will use this install instead of: ${report.shadowed.join(', ')}`);
25
+ if (process.env.SHELL?.endsWith('fish'))
26
+ lines.push(`fish is not configured automatically; run: fish_add_path ${report.dir}`);
27
+ return lines;
28
+ }
29
+ function removeText(report) {
30
+ return [
31
+ `${report.dry_run ? 'Would remove' : 'Removed'} ${report.removed.length} command file(s) from ${report.dir}`,
32
+ targetsLine(report, 'changed', report.dry_run ? 'PATH would change in' : 'PATH restored in'),
33
+ ];
34
+ }
35
+ function statusText(report) {
36
+ return [
37
+ `Terminal commands: ${report.installed ? 'installed' : 'not installed'} (${report.dir})`,
38
+ ...(report.stale.length ? [`Out of date: ${report.stale.join(', ')} — rerun cortex path install`] : []),
39
+ targetsLine(report, 'registered', 'On PATH via'),
40
+ ];
41
+ }
42
+ const ACTIONS = {
43
+ install: (ctx, dryRun) => { const report = installTerminalCli(ctx, dryRun); return { report, text: installText(report) }; },
44
+ remove: (ctx, dryRun) => { const report = removeTerminalCli(ctx, dryRun); return { report, text: removeText(report) }; },
45
+ status: (ctx) => { const report = terminalCliStatus(ctx); return { report, text: statusText(report) }; },
46
+ };
47
+ /** `cortex path install|remove|status` — make this install's commands reachable from terminals. */
48
+ export function runPathCli(args, makeContext = defaultTerminalCliContext) {
49
+ if (args.includes('--help') || args.includes('-h'))
50
+ return { exitCode: 0, stdout: getPathHelp(), stderr: '' };
51
+ if (args.length === 0)
52
+ return fail("Missing subcommand for 'path'.");
53
+ const action = ACTIONS[args[0]];
54
+ if (!action)
55
+ return fail(`Unknown subcommand: '${args[0]}'.`);
56
+ try {
57
+ const ctx = makeContext(getResolvedPaths(optionValue(args, '--home')).DATA_DIR);
58
+ const { report, text } = action(ctx, args.includes('--dry-run'));
59
+ const stdout = args.includes('--json') ? `${JSON.stringify(report, null, 2)}\n` : `${text.join('\n')}\n`;
60
+ return { exitCode: 0, stdout, stderr: '' };
61
+ }
62
+ catch (error) {
63
+ return { exitCode: 1, stdout: '', stderr: `cortex path ${args[0]} failed: ${error?.message ?? String(error)}\n` };
64
+ }
65
+ }