@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
@@ -1,120 +1,61 @@
1
1
  import * as crypto from 'node:crypto';
2
2
  import { setSessionAsync, deleteSessionAsync } from './session.js';
3
3
  import { conversationLedger } from '../../store/conversation-ledger-repo.js';
4
- import { applyChannelSelection, setActiveProfile, setDefaultAgent, setSelectionDefaultAgent, } from '../agents/index.js';
5
- import { resolveProfileConfig } from '../agents/profile-manager.js';
4
+ import { applyChannelSelection } from '../agents/model-selection.js';
5
+ import { setChannelSelection, setDefaultAgent, setSelectionDefaultAgent } from '../agents/config.js';
6
+ import { resolveRunSelection } from '../runs/config-resolver.js';
6
7
  import * as sessionBackup from './session-backup.js';
7
- /** Register a session by its stable ID. */
8
+ /** Register a session by its stable ID, freezing the engine choice for future resumes. */
8
9
  export async function registerSessionRecord(store, opts) {
9
- // Every caller path but a schedule's fire (inbound direct message, TUI and web fresh sessions,
10
- // team workers) is user-initiated.
11
10
  const scheduled = !!opts.scheduleId;
11
+ const selection = resolveRunSelection({ channel: opts.channel, selection: opts.selection });
12
12
  await store.registerSession({
13
- sessionId: opts.sessionId,
14
- channel: opts.channel,
15
- backend: opts.backend,
16
- kind: scheduled ? 'scheduled' : 'local',
17
- origin: scheduled ? 'scheduled' : 'direct',
18
- projectId: opts.projectId,
19
- label: opts.label ?? null,
20
- profileName: opts.profileName ?? null,
21
- agentName: opts.agentName ?? null,
22
- browser: opts.browser ?? null,
23
- boardId: opts.boardId ?? null,
13
+ sessionId: opts.sessionId, channel: opts.channel, backend: selection.backend,
14
+ kind: scheduled ? 'scheduled' : 'local', origin: scheduled ? 'scheduled' : 'direct',
15
+ projectId: opts.projectId, label: opts.label ?? null, selection,
16
+ agentName: opts.agentName ?? null, boardId: opts.boardId ?? null,
24
17
  ...(opts.teamLeadId
25
18
  ? { teamLeadId: opts.teamLeadId, workerName: opts.workerName ?? null, workerBrief: opts.workerBrief ?? null }
26
19
  : {}),
27
20
  ...(scheduled ? { scheduleId: opts.scheduleId } : {}),
28
21
  });
29
22
  }
30
- /** Create a fresh, live session for a web/UI conversation: mint a sessionId, derive its own
31
- * `web:<sessionId>` conduit channel, register by ID, bind the channel→session mapping
32
- * and conversation ledger. Returns the sessionId + channel. The session is
33
- * user-initiated (origin='direct') unless `scheduleId` names the schedule whose fire opened it.
34
- *
35
- * When `profileName` is provided, the backend is resolved directly from the profile config (not
36
- * from the channel's profile state) so the session is bound to the correct backend even before any
37
- * channel profile is set. The channel profile is then set so subsequent sends resolve correctly.
38
- *
39
- * Because the channel is bound with the same backend the send path resolves, a subsequent send
40
- * resumes THIS session rather than spawning a new one. */
41
- export async function createDirectSession(deps, opts) {
42
- const sessionId = opts.sessionId ?? crypto.randomUUID();
43
- const channel = `web:${sessionId}`;
44
- let backend;
45
- if (opts.profileName) {
46
- backend = resolveProfileConfig(opts.profileName).backend;
47
- setActiveProfile(opts.profileName, channel);
48
- }
49
- else {
50
- backend = deps.resolveBackend(channel);
51
- }
52
- // The draft composer's choice, carried onto the new channel before the first turn is routed —
53
- // through the SAME rule the picker writes with, not a direct state write. A draft has no history
54
- // to protect, but it can still name a level the backend does not take or a provider on a claude
55
- // profile: without the rule those land unchecked and the first turn dies at the CLI. The channel
56
- // is minted here, so the cross-backend guard has nothing to refuse.
57
- //
58
- // An EMPTY selection is a statement too — "run this profile as declared" — and it has to reach
59
- // the rule, because the rule is also what re-seeds `selectionDefault` (what the NEXT new
60
- // conversation opens on). Skipping it left a draft that had just been cleared back to its profile
61
- // re-opening the next one on the model it had dropped, however many times it was taken back.
62
- // `null`/`undefined` is the other thing entirely: a caller with no composer behind it
63
- // (sessions.create, an issue's session) states nothing and must not move the seed.
64
- if (opts.selection) {
65
- await applyChannelSelection({
66
- channel,
67
- model: opts.selection.model ?? null,
68
- provider: opts.selection.provider ?? null,
69
- thinking: opts.selection.thinking ?? null,
70
- mode: opts.selection.mode ?? null,
71
- });
72
- }
73
- // The environment the session opens in, written to the channel BEFORE the first turn is routed
74
- // (the run path resolves the agent per turn from the session record, then this map). No switch
75
- // rule is needed: a channel minted here has no history, so the cross-backend guard the rule
76
- // exists for has nothing to refuse.
23
+ /** A draft's explicit selection goes through the picker rule before the channel is bound. */
24
+ async function initializeSelection(channel, opts) {
25
+ const selection = resolveRunSelection({ channel, selection: opts.selection });
26
+ const seedDefault = opts.seedDefault ?? !!opts.selection;
27
+ const applied = await applyChannelSelection({ channel, ...selection, seedDefault });
28
+ if (!applied.ok)
29
+ throw new Error(applied.reason ?? 'Invalid engine selection');
77
30
  if (opts.agentName)
78
31
  setDefaultAgent(opts.agentName, channel);
79
- // Seeded on the same condition as the selection above: `selection` present is what marks a
80
- // composer behind this call, and a composer that named no agent stated the default.
81
- if (opts.selection)
32
+ if (seedDefault)
82
33
  setSelectionDefaultAgent(opts.agentName ?? null);
34
+ return selection;
35
+ }
36
+ /** Mint a session and bind its conduit, registry and ledger to one materialized engine choice. */
37
+ export async function createDirectSession(deps, opts) {
38
+ const sessionId = opts.sessionId ?? crypto.randomUUID();
39
+ const channel = `web:${sessionId}`;
40
+ const selection = await initializeSelection(channel, opts);
83
41
  await registerSessionRecord(deps.sessionStore, {
84
- sessionId,
85
- channel,
86
- backend,
87
- projectId: opts.projectId,
88
- label: opts.label ?? null,
89
- profileName: opts.profileName ?? null,
90
- agentName: opts.agentName ?? null,
91
- browser: opts.browser ?? null,
92
- boardId: opts.boardId ?? null,
93
- teamLeadId: opts.teamLeadId ?? null,
94
- workerName: opts.workerName ?? null,
95
- workerBrief: opts.workerBrief ?? null,
96
- scheduleId: opts.scheduleId ?? null,
42
+ ...opts, sessionId, channel, backend: selection.backend, selection,
97
43
  });
98
44
  await deps.setChannelSession(channel, sessionId);
99
- await deps.initConversation(channel, { sessionId, backend });
45
+ await deps.initConversation(channel, { sessionId, backend: selection.backend, selection });
100
46
  return { sessionId, channel };
101
47
  }
102
- /** Attach a channel to an existing session: restore its profile (if any), bind the channel to it in
103
- * the registry, and switch the conversation ledger. Mirrors the !resume switch sequence. */
48
+ /** Resume restores the record verbatim, not the last choice of the channel it replaces. */
104
49
  export async function attachExistingSession(channel, opts) {
105
- if (opts.profileName)
106
- setActiveProfile(opts.profileName, channel);
50
+ const selection = resolveRunSelection({ channel, selection: opts.selection });
51
+ // This restores another session rather than switching the engine of the current session.
52
+ setChannelSelection(channel, selection);
107
53
  await setSessionAsync(channel, opts.sessionId);
108
54
  await conversationLedger.switchSession(channel, {
109
- sessionId: opts.sessionId, backend: opts.backend, profileName: opts.profileName,
55
+ sessionId: opts.sessionId, backend: selection.backend, selection,
110
56
  });
111
57
  }
112
- /** Convert a scheduled run's session into a normal direct web session (replying adopts the run).
113
- * A run opened on its own `web:<sessionId>` conduit is already bound there and only needs its record
114
- * re-pointed; an older run that lived on the shared project channel first gets that conduit attached
115
- * — the same switch sequence as !resume, so a later send resumes the run's transcript. `scheduleId`
116
- * is intentionally KEPT on the record (provenance for the trigger card / schedule grouping).
117
- * Idempotent: a non-scheduled record just returns its current channel; an unknown id returns null. */
58
+ /** Re-home older shared-channel scheduled runs; preserve provenance and engine selection. */
118
59
  export async function adoptScheduledSession(store, sessionId) {
119
60
  const record = await store.getById(sessionId);
120
61
  if (!record)
@@ -122,23 +63,20 @@ export async function adoptScheduledSession(store, sessionId) {
122
63
  if (record.origin !== 'scheduled')
123
64
  return { channel: record.channel };
124
65
  const channel = `web:${sessionId}`;
125
- // Re-attaching the conduit it already runs on would switch the ledger under a turn that may be live.
126
66
  if (record.channel !== channel) {
127
67
  await attachExistingSession(channel, {
128
- sessionId, backend: record.backend, profileName: record.profileName,
68
+ sessionId, backend: record.backend, selection: record.selection,
129
69
  });
130
70
  }
131
71
  await store.convertToDirect(sessionId, { channel });
132
72
  return { channel };
133
73
  }
134
- /** Clear a channel's session state: unbind the channel in the registry, clean session
135
- * backups, and clear the conversation ledger. Mirrors the store-level half of !new. */
74
+ /** Clear the channel's binding, backups and conversation ledger. */
136
75
  export async function resetChannelSession(channel) {
137
76
  const conv = await conversationLedger.getConversation(channel);
138
77
  if (conv) {
139
78
  sessionBackup.cleanupAllBackups(conv.sessionId);
140
79
  await conversationLedger.clearConversation(channel);
141
80
  }
142
- // One channel, one binding: `deleteSessionAsync` unbinds the channel in the registry.
143
81
  await deleteSessionAsync(channel).catch(() => { });
144
82
  }
@@ -55,10 +55,10 @@ export interface DoctorDeps {
55
55
  resolvePiSdk(): PiSdkInfo | null;
56
56
  loadPiRuntime(): Promise<PiRuntimeLoadResult>;
57
57
  getAuthStatus(): Promise<AuthStatusSnapshot>;
58
- /** Backend and route of the profile a channel with no selection runs; null when unreadable. */
59
- defaultProfile(): DefaultProfileInfo | null;
58
+ /** Backend and route used by an unconfigured channel; null when unreadable. */
59
+ defaultSelection(): DefaultSelectionInfo | null;
60
60
  }
61
- export interface DefaultProfileInfo {
61
+ export interface DefaultSelectionInfo {
62
62
  backend: Backend;
63
63
  mode: string | null;
64
64
  }
@@ -10,7 +10,8 @@ import { ensureAuthTokens, CLIENT_TOKEN_ENV, WEBHOOK_TOKEN_ENV } from '../../cor
10
10
  import { generateMcpConfig } from '../../core/config-generator.js';
11
11
  import { isProcessAlive } from '../../core/singleton-lock.js';
12
12
  import { getAuthStatus as readAuthStatus, } from '../auth/auth-status.js';
13
- import { resolveRunConfig } from '../runs/config-resolver.js';
13
+ import { resolveConfiguredDefaultRun } from '../runs/config-resolver.js';
14
+ import { validateEngineSelection, validateModelRef } from '../agents/engine-selection.js';
14
15
  import { loadPiRuntime as loadInstalledPiRuntime, PI_SDK_PACKAGE, } from '../auth/pi-runtime.js';
15
16
  // ─── Helpers ──────────────────────────────────────────────────────
16
17
  const GW_HOST = '127.0.0.1';
@@ -43,10 +44,10 @@ function buildEnvReader(deps) {
43
44
  return (name) => normalize(deps.env[name] ?? fileEnv[name]);
44
45
  }
45
46
  // ─── Section: Runtime & Process ───────────────────────────────────
46
- /** The default profile's backend (D5), else claude. PI runs in-process from the SDK bundled with
47
+ /** The default selection's backend, else claude. PI runs in-process from the SDK bundled with
47
48
  * this package, so only the Claude backend still needs a CLI on PATH. */
48
49
  function backendRuntimeCheck(deps) {
49
- const backend = deps.defaultProfile()?.backend ?? 'claude';
50
+ const backend = deps.defaultSelection()?.backend ?? 'claude';
50
51
  if (backend === 'pi') {
51
52
  return { id: 'backend-runtime', label: 'Backend runtime', status: 'pass', detail: 'backend: pi runs in-process from the bundled SDK (no CLI needed)' };
52
53
  }
@@ -105,11 +106,11 @@ function pushEnvAndTokenChecks(checks, deps, getEnv) {
105
106
  ? { id: 'auth-tokens', label: 'Auth tokens', status: 'pass', detail: 'client + webhook tokens set' }
106
107
  : { id: 'auth-tokens', label: 'Auth tokens', status: 'fail', detail: `missing: ${missing.join(', ')}`, hint: 'run `cortex doctor --fix` to generate', fixable: true });
107
108
  }
108
- /** Whether the default profile runs Claude on a key-billed route. Mirrors the run path: a profile
109
+ /** Whether the default selection runs Claude on a key-billed route. Mirrors the run path: a selection
109
110
  * without a mode routes as `api` (resolveRunRoute), and every route but `plan` carries a key. */
110
111
  function usesClaudeApiMode(deps) {
111
- const profile = deps.defaultProfile();
112
- return profile?.backend === 'claude' && (profile.mode || 'api') !== 'plan';
112
+ const selection = deps.defaultSelection();
113
+ return selection?.backend === 'claude' && (selection.mode || 'api') !== 'plan';
113
114
  }
114
115
  function gatewayBacksClaudeApi(deps, getEnv, gatewayHealthy) {
115
116
  const apiKey = getEnv('ANTHROPIC_API_KEY');
@@ -134,7 +135,7 @@ function pushConfigChecks(checks, deps) {
134
135
  const statePath = path.join(store, 'agent-state.json');
135
136
  const stateLabel = deps.fileExists(statePath) ? 'agent-state.json' : 'mode.json';
136
137
  pushJsonCheck(checks, deps, deps.fileExists(statePath) ? statePath : path.join(store, 'mode.json'), 'mode-json', stateLabel, 'warn');
137
- checks.push(checkProfiles(deps, path.join(config, 'profiles.json')));
138
+ checks.push(checkModels(deps, path.join(config, 'models.json')));
138
139
  const mcpPath = path.join(config, 'mcp-config.json');
139
140
  if (!deps.fileExists(mcpPath)) {
140
141
  checks.push({ id: 'mcp-config', label: 'mcp-config.json', status: 'warn', detail: `missing (${mcpPath})`, hint: 'run `cortex doctor --fix` to regenerate', fixable: true });
@@ -243,26 +244,22 @@ function pushJsonCheck(checks, deps, p, id, label, missingStatus) {
243
244
  ? { id, label, status: 'pass', detail: 'valid' }
244
245
  : { id, label, status: missingStatus, detail: 'invalid JSON' });
245
246
  }
246
- function checkProfiles(deps, p) {
247
+ function checkModels(deps, p) {
248
+ const base = { id: 'models', label: 'models.json' };
247
249
  if (!deps.fileExists(p)) {
248
- return { id: 'profiles', label: 'profiles.json', status: 'warn', detail: `missing (${p})`, hint: 'run `cortex setup-gateway`' };
250
+ return { ...base, status: 'warn', detail: `missing (${p})`, hint: 'run `cortex setup-gateway`' };
249
251
  }
250
- const text = deps.readText(p);
251
- let parsed;
252
252
  try {
253
- parsed = JSON.parse(text ?? '');
253
+ const parsed = JSON.parse(deps.readText(p) ?? '');
254
+ validateEngineSelection(parsed?.default);
255
+ if (!Array.isArray(parsed?.favorites))
256
+ throw new Error('missing `favorites` array');
257
+ parsed.favorites.forEach(validateModelRef);
258
+ return { ...base, status: 'pass', detail: `default: ${parsed.default.model}; favorites: ${parsed.favorites.length}` };
254
259
  }
255
- catch {
256
- return { id: 'profiles', label: 'profiles.json', status: 'fail', detail: 'invalid JSON', hint: 're-run `cortex setup-gateway`' };
257
- }
258
- if (!parsed || typeof parsed !== 'object' || typeof parsed.profiles !== 'object' || parsed.profiles == null) {
259
- return { id: 'profiles', label: 'profiles.json', status: 'fail', detail: 'missing `profiles` object' };
260
- }
261
- if (parsed.defaultProfile && !(parsed.defaultProfile in parsed.profiles)) {
262
- return { id: 'profiles', label: 'profiles.json', status: 'fail', detail: `defaultProfile "${parsed.defaultProfile}" not found in profiles` };
260
+ catch (error) {
261
+ return { ...base, status: 'fail', detail: error.message, hint: 're-run `cortex setup-gateway`' };
263
262
  }
264
- const names = Object.keys(parsed.profiles).join(', ');
265
- return { id: 'profiles', label: 'profiles.json', status: 'pass', detail: `profiles: ${names || '(none)'}` };
266
263
  }
267
264
  // ─── Section: Messaging Platform ──────────────────────────────────
268
265
  function sectionPlatform(deps, getEnv) {
@@ -461,13 +458,12 @@ export function createDefaultDoctorDeps() {
461
458
  resolvePiSdk: resolveBundledPiSdk,
462
459
  loadPiRuntime: () => loadInstalledPiRuntime(),
463
460
  getAuthStatus: () => readAuthStatus(),
464
- defaultProfile: readDefaultProfile,
461
+ defaultSelection: readDefaultSelection,
465
462
  };
466
463
  }
467
- function readDefaultProfile() {
464
+ function readDefaultSelection() {
468
465
  try {
469
- const { profile } = resolveRunConfig();
470
- return { backend: profile.backend, mode: profile.mode };
466
+ return resolveConfiguredDefaultRun();
471
467
  }
472
468
  catch {
473
469
  return null;
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Directories that hold this server's own `node` and npm-linked bins (`cortex`, `cortex-signal`).
3
+ * The npm bin dir is absent for a repo checkout, which has no global prefix.
4
+ */
5
+ export declare function ownBinDirs(execPath?: string, installRoot?: string, platform?: NodeJS.Platform): string[];
6
+ /** Prepend each dir missing from `pathEnv`; entries already present keep their position. */
7
+ export declare function withDirsOnPath(pathEnv: string, dirs: string[], platform?: NodeJS.Platform): string;
8
+ /**
9
+ * Sessions inherit this process's env, and skills, waitpoint recipes and Claude hooks call bare
10
+ * `cortex`, `cortex-signal` and `node`. Make them resolve to this install however the daemon was
11
+ * started (desktop app, init-written service unit, terminal restart).
12
+ */
13
+ export declare function ensureOwnBinsOnPath(): void;
@@ -0,0 +1,36 @@
1
+ import * as path from 'path';
2
+ import { INSTALL_ROOT } from '../../core/paths.js';
3
+ import { npmPrefixFromInstallRoot } from '../../core/utils.js';
4
+ const SERVER_PACKAGE = '@cortex-agent/server';
5
+ /**
6
+ * Directories that hold this server's own `node` and npm-linked bins (`cortex`, `cortex-signal`).
7
+ * The npm bin dir is absent for a repo checkout, which has no global prefix.
8
+ */
9
+ export function ownBinDirs(execPath = process.execPath, installRoot = INSTALL_ROOT, platform = process.platform) {
10
+ const p = platform === 'win32' ? path.win32 : path.posix;
11
+ const dirs = [p.dirname(execPath)];
12
+ const prefix = npmPrefixFromInstallRoot(installRoot, SERVER_PACKAGE, platform);
13
+ if (prefix)
14
+ dirs.push(platform === 'win32' ? prefix : p.join(prefix, 'bin'));
15
+ return dirs;
16
+ }
17
+ /** Prepend each dir missing from `pathEnv`; entries already present keep their position. */
18
+ export function withDirsOnPath(pathEnv, dirs, platform = process.platform) {
19
+ const p = platform === 'win32' ? path.win32 : path.posix;
20
+ const key = (dir) => {
21
+ const normalized = p.normalize(dir).replace(/[\\/]+$/, '');
22
+ return platform === 'win32' ? normalized.toLowerCase() : normalized;
23
+ };
24
+ const entries = pathEnv.split(p.delimiter).filter(Boolean);
25
+ const present = new Set(entries.map(key));
26
+ const missing = dirs.filter((dir) => !present.has(key(dir)));
27
+ return [...missing, ...entries].join(p.delimiter);
28
+ }
29
+ /**
30
+ * Sessions inherit this process's env, and skills, waitpoint recipes and Claude hooks call bare
31
+ * `cortex`, `cortex-signal` and `node`. Make them resolve to this install however the daemon was
32
+ * started (desktop app, init-written service unit, terminal restart).
33
+ */
34
+ export function ensureOwnBinsOnPath() {
35
+ process.env.PATH = withDirsOnPath(process.env.PATH ?? '', ownBinDirs());
36
+ }
@@ -0,0 +1,58 @@
1
+ import { type PathRegistrar } from './registrar.js';
2
+ export interface TerminalCliContext {
3
+ home: string;
4
+ node: string;
5
+ installRoot: string;
6
+ platform: NodeJS.Platform;
7
+ pathEnv: string;
8
+ registrar: PathRegistrar;
9
+ }
10
+ /** Absolute paths of `names` found in `pathEnv`, skipping `excludeDirs`. */
11
+ export declare function findOnPath(names: string[], pathEnv: string, platform: NodeJS.Platform, excludeDirs?: string[]): string[];
12
+ export declare function defaultTerminalCliContext(home: string): TerminalCliContext;
13
+ export declare function installTerminalCli(ctx: TerminalCliContext, dryRun: boolean): {
14
+ ok: boolean;
15
+ action: string;
16
+ dry_run: boolean;
17
+ dir: string;
18
+ shims: string[];
19
+ written: string[];
20
+ path_targets: {
21
+ target: string;
22
+ changed: boolean;
23
+ }[];
24
+ shadowed: string[];
25
+ };
26
+ export declare function removeTerminalCli(ctx: TerminalCliContext, dryRun: boolean): {
27
+ ok: boolean;
28
+ action: string;
29
+ dry_run: boolean;
30
+ dir: string;
31
+ removed: string[];
32
+ path_targets: {
33
+ target: string;
34
+ changed: boolean;
35
+ }[];
36
+ };
37
+ export declare function terminalCliStatus(ctx: TerminalCliContext): {
38
+ ok: boolean;
39
+ dir: string;
40
+ installed: boolean;
41
+ shims: string[];
42
+ stale: string[];
43
+ path_targets: {
44
+ target: string;
45
+ registered: boolean;
46
+ }[];
47
+ on_current_path: boolean;
48
+ };
49
+ export type TerminalCliSync = {
50
+ action: 'skipped' | 'installed' | 'refreshed';
51
+ files: string[];
52
+ };
53
+ /**
54
+ * Server start. A desktop-runtime install gets the terminal command unless the user removed it,
55
+ * which also covers installs that predate it once they update. Elsewhere, existing launchers are
56
+ * only re-pointed at the node and entry running now (e.g. after a bundled Node upgrade).
57
+ */
58
+ export declare function syncTerminalCli(ctx: TerminalCliContext): TerminalCliSync;
@@ -0,0 +1,100 @@
1
+ import * as fs from 'fs';
2
+ import * as os from 'os';
3
+ import * as path from 'path';
4
+ import { INSTALL_ROOT } from '../../../core/paths.js';
5
+ import { ownBinDirs } from '../own-bin-path.js';
6
+ import { isChanged } from './registrar.js';
7
+ import { posixRegistrar } from './posix-profiles.js';
8
+ import { windowsRegistrar } from './windows-user-path.js';
9
+ import { listManagedShims, packageBins, refreshShims, removeShims, renderShims, shimDir, staleShims, writeShims, } from './shims.js';
10
+ import { isManagedRuntimeInstall, readTerminalCliState, writeTerminalCliState } from './state.js';
11
+ const pathApi = (platform) => (platform === 'win32' ? path.win32 : path.posix);
12
+ const pathKey = (dir, platform) => {
13
+ const normalized = pathApi(platform).normalize(dir).replace(/[\\/]+$/, '');
14
+ return platform === 'win32' ? normalized.toLowerCase() : normalized;
15
+ };
16
+ /** Absolute paths of `names` found in `pathEnv`, skipping `excludeDirs`. */
17
+ export function findOnPath(names, pathEnv, platform, excludeDirs = []) {
18
+ const p = pathApi(platform);
19
+ const excluded = new Set(excludeDirs.map((dir) => pathKey(dir, platform)));
20
+ const dirs = pathEnv.split(p.delimiter).filter((dir) => dir && !excluded.has(pathKey(dir, platform)));
21
+ return dirs.flatMap((dir) => names.map((name) => p.join(dir, name))).filter((file) => fs.existsSync(file));
22
+ }
23
+ function defaultRegistrar(platform, pathEnv) {
24
+ if (platform === 'win32')
25
+ return windowsRegistrar();
26
+ return posixRegistrar({
27
+ home: os.homedir(),
28
+ platform,
29
+ zdotdir: process.env.ZDOTDIR,
30
+ exists: fs.existsSync,
31
+ hasZsh: findOnPath(['zsh'], pathEnv, platform).length > 0,
32
+ });
33
+ }
34
+ export function defaultTerminalCliContext(home) {
35
+ const platform = process.platform;
36
+ const pathEnv = process.env.PATH ?? '';
37
+ return { home, node: process.execPath, installRoot: INSTALL_ROOT, platform, pathEnv, registrar: defaultRegistrar(platform, pathEnv) };
38
+ }
39
+ function renderFor(ctx) {
40
+ return renderShims({ node: ctx.node, home: ctx.home, bins: packageBins(ctx.installRoot) }, ctx.platform);
41
+ }
42
+ const summarize = (changes) => changes.map((change) => ({ target: change.target, changed: isChanged(change) }));
43
+ /** Another `cortex` that new terminals will no longer reach first. */
44
+ function shadowedCortex(ctx, dir) {
45
+ const names = ctx.platform === 'win32' ? ['cortex.cmd', 'cortex.exe', 'cortex'] : ['cortex'];
46
+ return findOnPath(names, ctx.pathEnv, ctx.platform, [dir, ...ownBinDirs(ctx.node, ctx.installRoot, ctx.platform)]);
47
+ }
48
+ /**
49
+ * PATH first, launchers second, state last: an interrupted install leaves no launchers behind, so
50
+ * the next server start sees it as not installed and runs it again.
51
+ */
52
+ function applyInstall(ctx, dir, shims, changes) {
53
+ ctx.registrar.apply(changes);
54
+ const written = writeShims(dir, shims);
55
+ writeTerminalCliState(ctx.home, 'installed');
56
+ return written;
57
+ }
58
+ export function installTerminalCli(ctx, dryRun) {
59
+ const dir = shimDir(ctx.home);
60
+ const shims = renderFor(ctx);
61
+ const changes = ctx.registrar.plan(dir, 'add');
62
+ const written = dryRun ? staleShims(dir, shims) : applyInstall(ctx, dir, shims, changes);
63
+ return {
64
+ ok: true, action: 'install', dry_run: dryRun, dir, shims: shims.map((shim) => shim.file), written,
65
+ path_targets: summarize(changes), shadowed: shadowedCortex(ctx, dir),
66
+ };
67
+ }
68
+ export function removeTerminalCli(ctx, dryRun) {
69
+ const dir = shimDir(ctx.home);
70
+ const changes = ctx.registrar.plan(dir, 'remove');
71
+ const removed = dryRun ? listManagedShims(dir) : removeShims(dir);
72
+ if (!dryRun) {
73
+ ctx.registrar.apply(changes);
74
+ writeTerminalCliState(ctx.home, 'removed');
75
+ }
76
+ return { ok: true, action: 'remove', dry_run: dryRun, dir, removed, path_targets: summarize(changes) };
77
+ }
78
+ export function terminalCliStatus(ctx) {
79
+ const dir = shimDir(ctx.home);
80
+ const installed = listManagedShims(dir);
81
+ const stale = installed.length > 0 ? staleShims(dir, renderFor(ctx)) : [];
82
+ const registered = ctx.registrar.plan(dir, 'add').map((change) => ({ target: change.target, registered: !isChanged(change) }));
83
+ const onPath = ctx.pathEnv.split(pathApi(ctx.platform).delimiter).some((entry) => entry && pathKey(entry, ctx.platform) === pathKey(dir, ctx.platform));
84
+ return { ok: true, dir, installed: installed.length > 0, shims: installed, stale, path_targets: registered, on_current_path: onPath };
85
+ }
86
+ /**
87
+ * Server start. A desktop-runtime install gets the terminal command unless the user removed it,
88
+ * which also covers installs that predate it once they update. Elsewhere, existing launchers are
89
+ * only re-pointed at the node and entry running now (e.g. after a bundled Node upgrade).
90
+ */
91
+ export function syncTerminalCli(ctx) {
92
+ if (readTerminalCliState(ctx.home) === 'removed')
93
+ return { action: 'skipped', files: [] };
94
+ const dir = shimDir(ctx.home);
95
+ const missing = listManagedShims(dir).length === 0;
96
+ if (missing && isManagedRuntimeInstall(ctx.home, ctx.installRoot, ctx.platform)) {
97
+ return { action: 'installed', files: installTerminalCli(ctx, false).written };
98
+ }
99
+ return { action: 'refreshed', files: refreshShims(dir, renderFor(ctx)) };
100
+ }
@@ -0,0 +1,23 @@
1
+ import { type PathRegistrar } from './registrar.js';
2
+ export declare function renderBlock(dir: string): string;
3
+ /**
4
+ * Insert or refresh the block. `top` serves ~/.bashrc, whose interactive guard would otherwise skip
5
+ * an appended block for non-interactive `ssh host cortex …`.
6
+ */
7
+ export declare function upsertBlock(content: string, block: string, position: 'top' | 'bottom'): string;
8
+ /** Undo `upsertBlock`, including the blank separator line it added. */
9
+ export declare function removeBlock(content: string): string;
10
+ interface ProfileEnv {
11
+ home: string;
12
+ platform: NodeJS.Platform;
13
+ zdotdir?: string;
14
+ exists: (file: string) => boolean;
15
+ hasZsh: boolean;
16
+ }
17
+ /** rustup's set: ~/.profile always; bash files that exist; ~/.zshenv where zsh is in use. */
18
+ export declare function profileTargets(env: ProfileEnv): Array<{
19
+ file: string;
20
+ position: 'top' | 'bottom';
21
+ }>;
22
+ export declare function posixRegistrar(env: ProfileEnv): PathRegistrar;
23
+ export {};
@@ -0,0 +1,74 @@
1
+ import * as fs from 'fs';
2
+ import * as path from 'path';
3
+ import { isChanged } from './registrar.js';
4
+ const BEGIN = '# >>> cortex >>>';
5
+ const END = '# <<< cortex <<<';
6
+ const BLOCK_RE = /# >>> cortex >>>\n[\s\S]*?\n# <<< cortex <<<\n?/;
7
+ const shQuote = (value) => `'${value.replace(/'/g, `'\\''`)}'`;
8
+ export function renderBlock(dir) {
9
+ const q = shQuote(dir);
10
+ return `${BEGIN}\ncase ":\${PATH}:" in *:${q}:*) ;; *) PATH=${q}:"$PATH"; export PATH ;; esac\n${END}\n`;
11
+ }
12
+ /**
13
+ * Insert or refresh the block. `top` serves ~/.bashrc, whose interactive guard would otherwise skip
14
+ * an appended block for non-interactive `ssh host cortex …`.
15
+ */
16
+ export function upsertBlock(content, block, position) {
17
+ if (BLOCK_RE.test(content))
18
+ return content.replace(BLOCK_RE, () => block);
19
+ if (!content)
20
+ return block;
21
+ if (position === 'top')
22
+ return `${block}\n${content}`;
23
+ return `${content}${content.endsWith('\n') ? '' : '\n'}\n${block}`;
24
+ }
25
+ /** Undo `upsertBlock`, including the blank separator line it added. */
26
+ export function removeBlock(content) {
27
+ const match = BLOCK_RE.exec(content);
28
+ if (!match)
29
+ return content;
30
+ const before = content.slice(0, match.index);
31
+ const after = content.slice(match.index + match[0].length);
32
+ if (before === '')
33
+ return after.replace(/^\n/, '');
34
+ return (before.endsWith('\n\n') ? before.slice(0, -1) : before) + after;
35
+ }
36
+ /** rustup's set: ~/.profile always; bash files that exist; ~/.zshenv where zsh is in use. */
37
+ export function profileTargets(env) {
38
+ const at = (name) => path.join(env.home, name);
39
+ const targets = [{ file: at('.profile'), position: 'bottom' }];
40
+ if (env.exists(at('.bashrc')))
41
+ targets.push({ file: at('.bashrc'), position: 'top' });
42
+ if (env.exists(at('.bash_profile')))
43
+ targets.push({ file: at('.bash_profile'), position: 'bottom' });
44
+ const zdot = env.zdotdir || env.home;
45
+ const usesZsh = env.platform === 'darwin' || env.hasZsh || env.exists(path.join(zdot, '.zshrc'));
46
+ if (usesZsh)
47
+ targets.push({ file: path.join(zdot, '.zshenv'), position: 'bottom' });
48
+ return targets;
49
+ }
50
+ function readOrNull(file) {
51
+ try {
52
+ return fs.readFileSync(file, 'utf8');
53
+ }
54
+ catch {
55
+ return null;
56
+ }
57
+ }
58
+ function planOne(file, position, dir, mode) {
59
+ const before = readOrNull(file);
60
+ if (mode === 'remove')
61
+ return { target: file, before, after: before === null ? null : removeBlock(before) };
62
+ return { target: file, before, after: upsertBlock(before ?? '', renderBlock(dir), position) };
63
+ }
64
+ export function posixRegistrar(env) {
65
+ return {
66
+ plan: (dir, mode) => profileTargets(env).map(({ file, position }) => planOne(file, position, dir, mode)),
67
+ apply: (changes) => {
68
+ for (const change of changes.filter(isChanged)) {
69
+ if (change.after !== null)
70
+ fs.writeFileSync(change.target, change.after);
71
+ }
72
+ },
73
+ };
74
+ }
@@ -0,0 +1,12 @@
1
+ /** One place that puts the shim dir on PATH: a shell profile file or the Windows user Path. */
2
+ export interface PathChange {
3
+ target: string;
4
+ before: string | null;
5
+ after: string | null;
6
+ }
7
+ export type PathMode = 'add' | 'remove';
8
+ export interface PathRegistrar {
9
+ plan(dir: string, mode: PathMode): PathChange[];
10
+ apply(changes: PathChange[]): void;
11
+ }
12
+ export declare const isChanged: (change: PathChange) => boolean;
@@ -0,0 +1 @@
1
+ export const isChanged = (change) => change.before !== change.after;
@@ -0,0 +1,27 @@
1
+ /** Marks files this module owns; remove and refresh never touch a file without it. */
2
+ export declare const SHIM_MARKER = "cortex-managed-shim";
3
+ export interface ShimTarget {
4
+ node: string;
5
+ home: string;
6
+ bins: Array<{
7
+ name: string;
8
+ entry: string;
9
+ }>;
10
+ }
11
+ export interface RenderedShim {
12
+ file: string;
13
+ content: string;
14
+ }
15
+ export declare function shimDir(home: string): string;
16
+ /** The package's `bin` map as absolute entry paths. */
17
+ export declare function packageBins(installRoot: string): ShimTarget['bins'];
18
+ export declare function renderShims(target: ShimTarget, platform?: NodeJS.Platform): RenderedShim[];
19
+ export declare function listManagedShims(dir: string): string[];
20
+ /** Shims whose on-disk content differs from `rendered` (missing ones included). */
21
+ export declare function staleShims(dir: string, rendered: RenderedShim[]): string[];
22
+ /** Write changed shims and drop managed ones no longer rendered; returns files written. */
23
+ export declare function writeShims(dir: string, rendered: RenderedShim[]): string[];
24
+ /** Delete managed shims, then the directory if nothing else is in it; returns files removed. */
25
+ export declare function removeShims(dir: string): string[];
26
+ /** Re-point existing shims at the running node and entry (e.g. after a bundled Node upgrade). */
27
+ export declare function refreshShims(dir: string, rendered: RenderedShim[]): string[];