@cortex-agent/server 2026.9.15 → 2026.9.25

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 (297) hide show
  1. package/README.md +3 -2
  2. package/defaults/config/hooks/08-agents-md-injector-post-tool.json +10 -0
  3. package/defaults/config/hooks/{10-cortex-md-injector-session-start.json → 10-agents-md-injector-session-start.json} +3 -3
  4. package/defaults/config/hooks/{CORTEX.md → AGENTS.md} +2 -2
  5. package/defaults/config/thread-templates/agents/creative.json +17 -0
  6. package/defaults/hooks/{CORTEX.md → AGENTS.md} +1 -1
  7. package/defaults/hooks/{cortex-md-injector.mjs → agents-md-injector.mjs} +117 -26
  8. package/defaults/hooks/cortex-hook-api.mjs +2 -2
  9. package/defaults/hooks/new-session-hook.mjs +2 -2
  10. package/defaults/hooks/rules-loader.mjs +2 -2
  11. package/defaults/hooks/status-md-guard.mjs +8 -8
  12. package/defaults/hooks/task-status-check.mjs +18 -76
  13. package/defaults/hooks/tasks-yaml-guard.mjs +2 -2
  14. package/defaults/plugins/cortex-feishu/skills/feishu-doc/SKILL.md +1 -1
  15. package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +2 -2
  16. package/defaults/plugins/cortex-system/skills/project-init/SKILL.md +4 -4
  17. package/defaults/plugins/cortex-system/skills/task/SKILL.md +1 -1
  18. package/defaults/prompts/systemPrompts/creative.md +13 -0
  19. package/defaults/prompts/systemPrompts/direct.md +1 -1
  20. package/defaults/rules/{cortex-md.md → agents-md.md} +4 -4
  21. package/defaults/rules/decision-records.md +1 -1
  22. package/defaults/rules/meta-conventions.md +4 -4
  23. package/defaults/rules/mission-md.md +1 -1
  24. package/dist/agent-adapter/claude/adapter.d.ts +12 -0
  25. package/dist/agent-adapter/claude/adapter.js +19 -1
  26. package/dist/agent-adapter/claude/hooks-builder.js +2 -2
  27. package/dist/agent-adapter/claude/spawn-args.d.ts +7 -0
  28. package/dist/agent-adapter/claude/spawn-args.js +14 -0
  29. package/dist/agent-adapter/claude/turn-machine.d.ts +11 -0
  30. package/dist/agent-adapter/claude/turn-machine.js +46 -5
  31. package/dist/agent-adapter/normalize/prompt-builder.d.ts +16 -1
  32. package/dist/agent-adapter/normalize/prompt-builder.js +24 -6
  33. package/dist/agent-adapter/pi/child-runner.d.ts +4 -2
  34. package/dist/agent-adapter/pi/child-runner.js +5 -1
  35. package/dist/agent-adapter/pi/event-parser.d.ts +3 -2
  36. package/dist/agent-adapter/pi/event-parser.js +46 -2
  37. package/dist/agent-adapter/pi/extensions.d.ts +7 -1
  38. package/dist/agent-adapter/pi/extensions.js +10 -3
  39. package/dist/agent-adapter/pi/mcp-bridge.js +8 -8
  40. package/dist/agent-adapter/pi/pi-session.js +5 -0
  41. package/dist/agent-adapter/pi/runtime.js +3 -0
  42. package/dist/agent-adapter/pi/session-options.js +5 -1
  43. package/dist/agent-adapter/pi/subagent.d.ts +15 -3
  44. package/dist/agent-adapter/pi/subagent.js +18 -0
  45. package/dist/agent-adapter/pi/tool-shims.d.ts +6 -1
  46. package/dist/agent-adapter/pi/tool-shims.js +34 -1
  47. package/dist/agent-adapter/types.d.ts +6 -0
  48. package/dist/core/agents/subagent/types.d.ts +3 -0
  49. package/dist/core/config-generator.js +17 -2
  50. package/dist/core/debug-mode.d.ts +11 -10
  51. package/dist/core/debug-mode.js +12 -18
  52. package/dist/core/exec-async.d.ts +26 -0
  53. package/dist/core/exec-async.js +47 -0
  54. package/dist/core/locales/en.d.ts +14 -1
  55. package/dist/core/locales/slices/commands.d.ts +12 -1
  56. package/dist/core/locales/slices/commands.js +24 -2
  57. package/dist/core/locales/slices/startup.d.ts +2 -0
  58. package/dist/core/locales/slices/startup.js +4 -0
  59. package/dist/core/mcp-tool-gate.js +1 -0
  60. package/dist/core/media-types.d.ts +10 -0
  61. package/dist/core/media-types.js +34 -0
  62. package/dist/core/platform-settings-spec.js +1 -1
  63. package/dist/core/rebuild-progress.d.ts +58 -0
  64. package/dist/core/rebuild-progress.js +103 -0
  65. package/dist/core/resilient-watch.js +5 -3
  66. package/dist/core/run-registry.d.ts +7 -0
  67. package/dist/core/run-registry.js +6 -0
  68. package/dist/core/settings-spec.d.ts +21 -0
  69. package/dist/core/settings-spec.js +28 -1
  70. package/dist/core/types/agent-types.d.ts +3 -1
  71. package/dist/core/types/thread-types.d.ts +23 -4
  72. package/dist/core/utils.d.ts +1 -1
  73. package/dist/core/utils.js +1 -1
  74. package/dist/domain/agents/agent-state.d.ts +7 -0
  75. package/dist/domain/agents/agent-state.js +9 -1
  76. package/dist/domain/agents/agent-switch.d.ts +38 -0
  77. package/dist/domain/agents/agent-switch.js +106 -0
  78. package/dist/domain/agents/config.d.ts +20 -2
  79. package/dist/domain/agents/config.js +58 -4
  80. package/dist/domain/agents/index.d.ts +1 -0
  81. package/dist/domain/agents/index.js +1 -0
  82. package/dist/domain/agents/profile-manager.d.ts +6 -0
  83. package/dist/domain/agents/profile-manager.js +14 -1
  84. package/dist/domain/executions/registry.d.ts +3 -2
  85. package/dist/domain/executions/registry.js +84 -10
  86. package/dist/domain/mcp/bundled-server.js +4 -3
  87. package/dist/domain/mcp/feishu/file.js +37 -18
  88. package/dist/domain/mcp/feishu/types.d.ts +3 -0
  89. package/dist/domain/mcp/feishu-server.js +1 -1
  90. package/dist/domain/mcp/tools/{cortex-md.d.ts → agents-md.d.ts} +6 -6
  91. package/dist/domain/mcp/tools/{cortex-md.js → agents-md.js} +6 -6
  92. package/dist/domain/mcp/tools/remote-file.d.ts +20 -0
  93. package/dist/domain/mcp/tools/remote-file.js +44 -0
  94. package/dist/domain/mcp/tools/slack.d.ts +2 -0
  95. package/dist/domain/mcp/tools/slack.js +22 -7
  96. package/dist/domain/mcp/tools/task-ops.js +5 -13
  97. package/dist/domain/mcp/tools/ui-file.js +23 -10
  98. package/dist/domain/mcp/tools/waitpoint.d.ts +3 -0
  99. package/dist/domain/mcp/tools/waitpoint.js +122 -0
  100. package/dist/domain/memory/agents-md-injector.d.ts +24 -0
  101. package/dist/domain/memory/{cortex-md-injector.js → agents-md-injector.js} +10 -7
  102. package/dist/domain/plugins/runtime.js +1 -1
  103. package/dist/domain/plugins/skill-projection.d.ts +8 -2
  104. package/dist/domain/plugins/skill-projection.js +76 -19
  105. package/dist/domain/projects/project-store.d.ts +1 -1
  106. package/dist/domain/projects/project-store.js +3 -3
  107. package/dist/domain/remote/client-bootstrap.js +1 -1
  108. package/dist/domain/remote/client-hot-reload.d.ts +1 -1
  109. package/dist/domain/remote/client-hot-reload.js +30 -24
  110. package/dist/domain/remote/client-manager.js +39 -119
  111. package/dist/domain/remote/cortex-client-config.d.ts +1 -1
  112. package/dist/domain/remote/cortex-client-config.js +1 -1
  113. package/dist/domain/remote/device-file.d.ts +51 -0
  114. package/dist/domain/remote/device-file.js +193 -0
  115. package/dist/domain/remote/device-port.js +3 -0
  116. package/dist/domain/remote/reverse-stream.d.ts +18 -7
  117. package/dist/domain/remote/reverse-stream.js +19 -6
  118. package/dist/domain/runs/engine-spec.js +4 -0
  119. package/dist/domain/runs/request.d.ts +6 -0
  120. package/dist/domain/runs/run.js +1 -0
  121. package/dist/domain/runs/spec-loader.d.ts +4 -3
  122. package/dist/domain/runs/spec-loader.js +4 -3
  123. package/dist/domain/scheduling/jobs/sync-public.js +6 -6
  124. package/dist/domain/scheduling/scheduler.js +14 -12
  125. package/dist/domain/sessions/session-lifecycle.d.ts +5 -0
  126. package/dist/domain/sessions/session-lifecycle.js +13 -1
  127. package/dist/domain/system/rebuild-hold.d.ts +44 -0
  128. package/dist/domain/system/rebuild-hold.js +91 -0
  129. package/dist/domain/system/server-update-check.d.ts +2 -1
  130. package/dist/domain/system/server-update-check.js +15 -13
  131. package/dist/domain/tasks/archiver.js +21 -13
  132. package/dist/domain/tasks/claim-recovery.js +2 -2
  133. package/dist/domain/tasks/dispatch-utils.d.ts +10 -1
  134. package/dist/domain/tasks/dispatch-utils.js +46 -1
  135. package/dist/domain/tasks/dispatcher.js +4 -5
  136. package/dist/domain/tasks/mutator.d.ts +2 -2
  137. package/dist/domain/tasks/mutator.js +62 -61
  138. package/dist/domain/tasks/system/task-cli.js +2 -2
  139. package/dist/domain/tasks/system/task-completion.d.ts +7 -2
  140. package/dist/domain/tasks/system/task-completion.js +69 -6
  141. package/dist/domain/tasks/system/task-lifecycle-edit.d.ts +6 -1
  142. package/dist/domain/tasks/system/task-lifecycle-edit.js +21 -2
  143. package/dist/domain/tasks/system/task-lock.d.ts +23 -0
  144. package/dist/domain/tasks/system/task-lock.js +29 -1
  145. package/dist/domain/tasks/system/task-mutations.d.ts +14 -1
  146. package/dist/domain/tasks/system/task-mutations.js +25 -2
  147. package/dist/domain/tasks/system/task-state.d.ts +12 -1
  148. package/dist/domain/tasks/system/task-state.js +20 -3
  149. package/dist/domain/threads/prompt-builder.d.ts +9 -6
  150. package/dist/domain/threads/prompt-builder.js +28 -10
  151. package/dist/domain/threads/runner.js +10 -4
  152. package/dist/domain/threads/state-machine.js +15 -11
  153. package/dist/domain/threads/template-loader.js +6 -4
  154. package/dist/domain/threads/template-validate.d.ts +43 -6
  155. package/dist/domain/threads/template-validate.js +12 -0
  156. package/dist/domain/ui-service/app-router.d.ts +34 -3
  157. package/dist/domain/ui-service/app-router.js +9 -14
  158. package/dist/domain/ui-service/input-schemas.d.ts +28 -5
  159. package/dist/domain/ui-service/input-schemas.js +24 -9
  160. package/dist/domain/ui-service/mutate/platform-settings.js +1 -1
  161. package/dist/domain/ui-service/mutate/sessions.d.ts +6 -1
  162. package/dist/domain/ui-service/mutate/sessions.js +54 -0
  163. package/dist/domain/ui-service/mutate/tasks.js +4 -3
  164. package/dist/domain/ui-service/mutate/waitpoints.d.ts +2 -0
  165. package/dist/domain/ui-service/mutate/waitpoints.js +20 -0
  166. package/dist/domain/ui-service/platform-settings.js +1 -1
  167. package/dist/domain/ui-service/plugins-shared.js +1 -1
  168. package/dist/domain/ui-service/query/config.js +20 -2
  169. package/dist/domain/ui-service/query/executions.js +0 -2
  170. package/dist/domain/ui-service/query/machine-detail.js +3 -8
  171. package/dist/domain/ui-service/query/memory.js +29 -35
  172. package/dist/domain/ui-service/query/sessions.js +96 -12
  173. package/dist/domain/ui-service/query/system.js +19 -0
  174. package/dist/domain/ui-service/query/threads.js +1 -54
  175. package/dist/domain/ui-service/query/waitpoints.d.ts +30 -0
  176. package/dist/domain/ui-service/query/waitpoints.js +117 -0
  177. package/dist/domain/ui-service/query-input-schemas.d.ts +4 -0
  178. package/dist/domain/ui-service/query-input-schemas.js +5 -0
  179. package/dist/domain/ui-service/trpc.js +1 -1
  180. package/dist/domain/ui-service/types.d.ts +229 -51
  181. package/dist/domain/ui-service/types.js +1 -1
  182. package/dist/domain/ui-service/ui-service.js +8 -31
  183. package/dist/domain/waitpoints/notices.d.ts +21 -0
  184. package/dist/domain/waitpoints/notices.js +115 -0
  185. package/dist/domain/waitpoints/service.d.ts +91 -0
  186. package/dist/domain/waitpoints/service.js +243 -0
  187. package/dist/entry/app.js +52 -11
  188. package/dist/entry/auth-login-cli.js +1 -1
  189. package/dist/entry/auth-login-terminal.js +1 -1
  190. package/dist/entry/daemon-notice.d.ts +10 -1
  191. package/dist/entry/daemon-notice.js +16 -1
  192. package/dist/entry/daemon.d.ts +43 -2
  193. package/dist/entry/daemon.js +163 -9
  194. package/dist/entry/init-auth.js +1 -1
  195. package/dist/entry/init.js +6 -6
  196. package/dist/entry/signal-cli.d.ts +30 -0
  197. package/dist/entry/signal-cli.js +207 -0
  198. package/dist/entry/start-ui-http.d.ts +1 -1
  199. package/dist/entry/start-ui-http.js +2 -2
  200. package/dist/events/event-types.d.ts +0 -7
  201. package/dist/hooks/{cortex-md-injector.mjs → agents-md-injector.mjs} +117 -26
  202. package/dist/hooks/cortex-hook-api.mjs +2 -2
  203. package/dist/hooks/new-session-hook.mjs +2 -2
  204. package/dist/hooks/rules-loader.mjs +2 -2
  205. package/dist/hooks/status-md-guard.mjs +8 -8
  206. package/dist/hooks/task-status-check.mjs +18 -76
  207. package/dist/hooks/tasks-yaml-guard.mjs +2 -2
  208. package/dist/orchestration/agent-file-send.d.ts +9 -0
  209. package/dist/orchestration/agent-file-send.js +21 -2
  210. package/dist/orchestration/agent-runner.d.ts +3 -2
  211. package/dist/orchestration/agent-runner.js +33 -12
  212. package/dist/orchestration/attachments-store.d.ts +31 -0
  213. package/dist/orchestration/attachments-store.js +184 -0
  214. package/dist/orchestration/conversation-request.d.ts +37 -0
  215. package/dist/orchestration/conversation-request.js +91 -22
  216. package/dist/orchestration/interactions/plan-approvals.js +1 -1
  217. package/dist/orchestration/mid-turn-inject.d.ts +3 -0
  218. package/dist/orchestration/mid-turn-inject.js +9 -4
  219. package/dist/orchestration/outputs-store.d.ts +11 -0
  220. package/dist/orchestration/outputs-store.js +32 -6
  221. package/dist/orchestration/resume-dispatcher.js +4 -2
  222. package/dist/orchestration/routing/commands/mode.js +114 -63
  223. package/dist/orchestration/routing/file-handler.d.ts +23 -2
  224. package/dist/orchestration/routing/file-handler.js +22 -5
  225. package/dist/orchestration/routing/webhook.js +193 -39
  226. package/dist/orchestration/session-gateway.d.ts +1 -1
  227. package/dist/orchestration/session-gateway.js +1 -0
  228. package/dist/orchestration/thread-executor.d.ts +2 -0
  229. package/dist/orchestration/thread-executor.js +24 -1
  230. package/dist/orchestration/thread-input.d.ts +3 -2
  231. package/dist/orchestration/thread-input.js +8 -9
  232. package/dist/orchestration/turn/turn-prep.d.ts +15 -1
  233. package/dist/orchestration/turn/turn-prep.js +19 -8
  234. package/dist/orchestration/turn/turn.js +1 -0
  235. package/dist/orchestration/waitpoint-ingress.d.ts +41 -0
  236. package/dist/orchestration/waitpoint-ingress.js +172 -0
  237. package/dist/orchestration/waitpoint-notifier.d.ts +21 -0
  238. package/dist/orchestration/waitpoint-notifier.js +119 -0
  239. package/dist/orchestration/waitpoint-remote-drain.d.ts +20 -0
  240. package/dist/orchestration/waitpoint-remote-drain.js +147 -0
  241. package/dist/orchestration/waitpoint-sweep.d.ts +42 -0
  242. package/dist/orchestration/waitpoint-sweep.js +87 -0
  243. package/dist/platform/adapters/feishu-image.d.ts +19 -0
  244. package/dist/platform/adapters/feishu-image.js +71 -0
  245. package/dist/platform/adapters/feishu.d.ts +2 -0
  246. package/dist/platform/adapters/feishu.js +26 -16
  247. package/dist/platform/ui-http/listening-ports.d.ts +1 -1
  248. package/dist/platform/ui-http/listening-ports.js +1 -1
  249. package/dist/platform/ui-http/ui-session.js +1 -1
  250. package/dist/store/conversation-display-projection.d.ts +9 -1
  251. package/dist/store/conversation-display-projection.js +13 -6
  252. package/dist/store/conversation-history-reader.d.ts +19 -0
  253. package/dist/store/conversation-history-reader.js +163 -44
  254. package/dist/store/conversation-history-repo.d.ts +37 -10
  255. package/dist/store/conversation-history-repo.js +161 -139
  256. package/dist/store/conversation-ledger-repo.js +1 -1
  257. package/dist/store/execution-repo.d.ts +1 -19
  258. package/dist/store/execution-repo.js +1 -18
  259. package/dist/store/project-notes-repo.js +11 -2
  260. package/dist/store/prompt-migration-replacements.js +1 -1
  261. package/dist/store/session-registry-import.js +1 -1
  262. package/dist/store/session-registry-journal.d.ts +4 -0
  263. package/dist/store/session-registry-journal.js +5 -1
  264. package/dist/store/session-registry-repo.d.ts +2 -1
  265. package/dist/store/session-registry-repo.js +3 -1
  266. package/dist/store/task-repo.d.ts +6 -3
  267. package/dist/store/task-repo.js +26 -10
  268. package/dist/store/version-migrations.d.ts +13 -3
  269. package/dist/store/version-migrations.js +254 -24
  270. package/dist/store/waitpoint-repo.d.ts +108 -0
  271. package/dist/store/waitpoint-repo.js +94 -0
  272. package/package.json +3 -2
  273. package/web/dist/AGENTS.md +10 -0
  274. package/web/dist/assets/index-B1dBi8Za.css +1 -0
  275. package/web/dist/assets/{index-CEZ0DSei.js → index-BAeLybF0.js} +1 -1
  276. package/web/dist/assets/index-BcQI8Fh5.js +445 -0
  277. package/web/dist/index.html +12 -4
  278. package/web/dist/theme.css +211 -40
  279. package/defaults/config/hooks/08-cortex-md-injector-post-tool.json +0 -10
  280. package/dist/domain/executions/log-tailer.d.ts +0 -71
  281. package/dist/domain/executions/log-tailer.js +0 -194
  282. package/dist/domain/memory/cortex-md-injector.d.ts +0 -24
  283. package/dist/domain/memory/cortex-md-scanner.d.ts +0 -10
  284. package/dist/domain/memory/cortex-md-scanner.js +0 -66
  285. package/dist/domain/remote/cortex-client.d.ts +0 -1
  286. package/dist/domain/remote/cortex-client.js +0 -662
  287. package/dist/domain/tasks/system/cortex-run.d.ts +0 -25
  288. package/dist/domain/tasks/system/cortex-run.js +0 -360
  289. package/web/dist/assets/index-CRDJo39X.css +0 -1
  290. package/web/dist/assets/index-DjuPJVZE.js +0 -444
  291. /package/defaults/{CORTEX.md → AGENTS.md} +0 -0
  292. /package/defaults/config/{CORTEX.md → AGENTS.md} +0 -0
  293. /package/defaults/context/{CORTEX.md → AGENTS.md} +0 -0
  294. /package/defaults/context/ideas/{CORTEX.md → AGENTS.md} +0 -0
  295. /package/defaults/context/projects/{CORTEX.md → AGENTS.md} +0 -0
  296. /package/defaults/context/scans/{CORTEX.md → AGENTS.md} +0 -0
  297. /package/defaults/context/user/{CORTEX.md → AGENTS.md} +0 -0
@@ -3,3 +3,37 @@
3
3
  * two sets, so they live below both rather than in either one. */
4
4
  export const IMAGE_MIMES = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp']);
5
5
  export const VIDEO_MIMES = new Set(['video/mp4', 'video/webm', 'video/quicktime', 'video/x-msvideo', 'video/x-matroska']);
6
+ /** Canonical extension per image mime, for naming a file whose declared type turned out to be a lie. */
7
+ const IMAGE_MIME_EXTENSIONS = {
8
+ 'image/png': '.png',
9
+ 'image/jpeg': '.jpg',
10
+ 'image/gif': '.gif',
11
+ 'image/webp': '.webp',
12
+ 'image/bmp': '.bmp',
13
+ };
14
+ /** The mime a file's first bytes actually declare, or null when they are not a known image.
15
+ *
16
+ * A platform's metadata is a claim, not a fact: Feishu hands every inbound image out as
17
+ * `image_key` with no type at all (Cortex called them all PNG), Slack can mislabel, and a user
18
+ * can rename anything. Backends sniff the bytes themselves, so a wrong mime never broke reading —
19
+ * it broke everything that classifies on the declared value (prompt bucket, UI attachment kind,
20
+ * the extension the file is stored under). */
21
+ export function sniffImageMime(head) {
22
+ if (head.length >= 3 && head[0] === 0xff && head[1] === 0xd8 && head[2] === 0xff)
23
+ return 'image/jpeg';
24
+ if (head.length >= 8 && head.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])))
25
+ return 'image/png';
26
+ if (head.length >= 6 && head.subarray(0, 3).toString('latin1') === 'GIF')
27
+ return 'image/gif';
28
+ if (head.length >= 12
29
+ && head.subarray(0, 4).toString('latin1') === 'RIFF'
30
+ && head.subarray(8, 12).toString('latin1') === 'WEBP')
31
+ return 'image/webp';
32
+ if (head.length >= 2 && head.subarray(0, 2).toString('latin1') === 'BM')
33
+ return 'image/bmp';
34
+ return null;
35
+ }
36
+ /** The extension an image mime should be stored under, or null for a mime with no fixed one. */
37
+ export function imageMimeExtension(mimeType) {
38
+ return IMAGE_MIME_EXTENSIONS[mimeType] ?? null;
39
+ }
@@ -1,7 +1,7 @@
1
1
  // input: zod and platform credential field definitions
2
2
  // output: platform configuration contract and safe patch schema
3
3
  // pos: Browser-safe platform settings boundary
4
- // >>> Once updated, update this header and parent CORTEX.md <<<
4
+ // >>> Once updated, update this header and parent AGENTS.md <<<
5
5
  import { z } from 'zod';
6
6
  export const PLATFORM_FIELDS = {
7
7
  feishu: ['FEISHU_APP_ID', 'FEISHU_APP_SECRET', 'FEISHU_DOMAIN', 'FEISHU_ENCRYPT_KEY', 'FEISHU_VERIFICATION_TOKEN'],
@@ -0,0 +1,58 @@
1
+ /** Where the supervisor publishes its pipeline state. */
2
+ export declare const REBUILD_PROGRESS_FILE: string;
3
+ /** The pipeline's fixed step vocabulary. `install` covers both install paths (fast sync vs
4
+ * pack + `npm install -g`); which one ran is in the step's `detail`. */
5
+ export type RebuildStepName = 'server' | 'ui-contract' | 'web' | 'install' | 'restart';
6
+ export type RebuildStepStatus = 'pending' | 'running' | 'done' | 'failed' | 'skipped';
7
+ export interface RebuildStepState {
8
+ name: RebuildStepName;
9
+ status: RebuildStepStatus;
10
+ /** Free-text qualifier for a finished step ('fast', 'pack + install -g', 'exit 1'). */
11
+ detail: string | null;
12
+ startedAt: string | null;
13
+ endedAt: string | null;
14
+ }
15
+ /** `deferred` is a pipeline that built successfully and then stopped short of touching the running
16
+ * process because app.ts was mid-turn: the install replaces the files that process loaded and the
17
+ * restart kills it, so both wait for idle. The whole pipeline runs again from the top then. */
18
+ export type RebuildStatus = 'running' | 'succeeded' | 'aborted' | 'deferred';
19
+ export interface RebuildProgress {
20
+ status: RebuildStatus;
21
+ /** What triggered the pipeline, verbatim from the watcher ('src change: core/foo.ts'). */
22
+ reason: string;
23
+ /** The step in flight, or null once terminal. */
24
+ current: RebuildStepName | null;
25
+ steps: RebuildStepState[];
26
+ startedAt: string;
27
+ updatedAt: string;
28
+ endedAt: string | null;
29
+ /** Why it ended the way it did — the operator notice's words for an abort, what is still owed for
30
+ * a deferral. Null while running and for a plain success. */
31
+ detail: string | null;
32
+ /** The supervisor that owns this record. Lets a reader discard a record left `running` by a
33
+ * daemon that is no longer alive. */
34
+ daemonPid: number;
35
+ }
36
+ /** A step list in pipeline order. `names` comes from the caller because which packages exist is
37
+ * a property of the checkout, not of this module. */
38
+ export declare function planRebuildProgress(p: {
39
+ reason: string;
40
+ names: RebuildStepName[];
41
+ daemonPid: number;
42
+ now?: () => Date;
43
+ }): RebuildProgress;
44
+ /** Mark a step as in flight. A step that is not in the plan is ignored rather than invented —
45
+ * the plan is what the reader renders a total from. */
46
+ export declare function startRebuildStep(progress: RebuildProgress, name: RebuildStepName, now?: () => Date): RebuildProgress;
47
+ /** Close a step. `status` is the step's own outcome; the pipeline's outcome is set separately,
48
+ * because a failed step and an aborted pipeline are recorded by different callers. */
49
+ export declare function finishRebuildStep(progress: RebuildProgress, name: RebuildStepName, status: Extract<RebuildStepStatus, 'done' | 'failed' | 'skipped'>, detail?: string | null, now?: () => Date): RebuildProgress;
50
+ /** Terminal state. Any step still `pending` becomes `skipped`, so a reader never shows a step as
51
+ * "waiting" for a pipeline that has stopped. */
52
+ export declare function settleRebuildProgress(progress: RebuildProgress, status: Extract<RebuildStatus, 'succeeded' | 'aborted' | 'deferred'>, detail?: string | null, now?: () => Date): RebuildProgress;
53
+ /** Read the published record, or null when there is none / it is unreadable. Never throws: a
54
+ * missing or corrupt progress file must not take the daemon-status query down with it. */
55
+ export declare function readRebuildProgress(file?: string): RebuildProgress | null;
56
+ /** Publish the record. Best-effort by design: losing a progress write must never abort a rebuild
57
+ * that is otherwise fine, so the caller gets a boolean instead of an exception. */
58
+ export declare function writeRebuildProgress(progress: RebuildProgress, file?: string): boolean;
@@ -0,0 +1,103 @@
1
+ //
2
+ // Hot-rebuild progress: the supervisor's view of its own pipeline, written where the app can read it.
3
+ //
4
+ // The daemon runs build → install → restart in its own process, and the last step kills the app
5
+ // that would otherwise hold this state in memory. So the record lives in a file: the daemon is the
6
+ // only writer, `system.daemonStatus` is the only reader, and a freshly restarted app can still say
7
+ // what the rebuild it was born from did. The same phases go down the fork IPC channel
8
+ // (`entry/daemon-notice.ts`) because the turn gate needs them without waiting for a poll.
9
+ //
10
+ // Steps are planned up front and flipped in place, so the reader always knows the total and never
11
+ // has to guess whether a missing step is pending or skipped.
12
+ //
13
+ import { existsSync, readFileSync } from 'node:fs';
14
+ import * as path from 'node:path';
15
+ import { STORE_DIR } from './paths.js';
16
+ import { atomicWriteSync } from './atomic-write.js';
17
+ /** Where the supervisor publishes its pipeline state. */
18
+ export const REBUILD_PROGRESS_FILE = path.join(STORE_DIR, 'daemon-rebuild.json');
19
+ /** A step list in pipeline order. `names` comes from the caller because which packages exist is
20
+ * a property of the checkout, not of this module. */
21
+ export function planRebuildProgress(p) {
22
+ const ts = (p.now ?? (() => new Date()))().toISOString();
23
+ return {
24
+ status: 'running',
25
+ reason: p.reason,
26
+ current: null,
27
+ steps: p.names.map((name) => ({ name, status: 'pending', detail: null, startedAt: null, endedAt: null })),
28
+ startedAt: ts,
29
+ updatedAt: ts,
30
+ endedAt: null,
31
+ detail: null,
32
+ daemonPid: p.daemonPid,
33
+ };
34
+ }
35
+ function patchStep(progress, name, patch, ts) {
36
+ return {
37
+ ...progress,
38
+ updatedAt: ts,
39
+ steps: progress.steps.map((step) => (step.name === name ? { ...step, ...patch } : step)),
40
+ };
41
+ }
42
+ /** Mark a step as in flight. A step that is not in the plan is ignored rather than invented —
43
+ * the plan is what the reader renders a total from. */
44
+ export function startRebuildStep(progress, name, now = () => new Date()) {
45
+ const ts = now().toISOString();
46
+ return { ...patchStep(progress, name, { status: 'running', startedAt: ts, endedAt: null }, ts), current: name };
47
+ }
48
+ /** Close a step. `status` is the step's own outcome; the pipeline's outcome is set separately,
49
+ * because a failed step and an aborted pipeline are recorded by different callers. */
50
+ export function finishRebuildStep(progress, name, status, detail = null, now = () => new Date()) {
51
+ const ts = now().toISOString();
52
+ const next = patchStep(progress, name, { status, detail, endedAt: ts }, ts);
53
+ return { ...next, current: next.current === name ? null : next.current };
54
+ }
55
+ /** Terminal state. Any step still `pending` becomes `skipped`, so a reader never shows a step as
56
+ * "waiting" for a pipeline that has stopped. */
57
+ export function settleRebuildProgress(progress, status, detail = null, now = () => new Date()) {
58
+ const ts = now().toISOString();
59
+ return {
60
+ ...progress,
61
+ status,
62
+ current: null,
63
+ detail,
64
+ updatedAt: ts,
65
+ endedAt: ts,
66
+ steps: progress.steps.map((step) => (step.status === 'pending' ? { ...step, status: 'skipped' } : step)),
67
+ };
68
+ }
69
+ /** Shallow structural check. The file is machine-written, so this only has to reject a truncated
70
+ * or hand-edited record rather than validate every field. */
71
+ function isRebuildProgress(value) {
72
+ if (!value || typeof value !== 'object')
73
+ return false;
74
+ const v = value;
75
+ return typeof v.status === 'string'
76
+ && typeof v.reason === 'string'
77
+ && typeof v.startedAt === 'string'
78
+ && Array.isArray(v.steps);
79
+ }
80
+ /** Read the published record, or null when there is none / it is unreadable. Never throws: a
81
+ * missing or corrupt progress file must not take the daemon-status query down with it. */
82
+ export function readRebuildProgress(file = REBUILD_PROGRESS_FILE) {
83
+ try {
84
+ if (!existsSync(file))
85
+ return null;
86
+ const parsed = JSON.parse(readFileSync(file, 'utf8'));
87
+ return isRebuildProgress(parsed) ? parsed : null;
88
+ }
89
+ catch {
90
+ return null;
91
+ }
92
+ }
93
+ /** Publish the record. Best-effort by design: losing a progress write must never abort a rebuild
94
+ * that is otherwise fine, so the caller gets a boolean instead of an exception. */
95
+ export function writeRebuildProgress(progress, file = REBUILD_PROGRESS_FILE) {
96
+ try {
97
+ atomicWriteSync(file, JSON.stringify(progress, null, 2));
98
+ return true;
99
+ }
100
+ catch {
101
+ return false;
102
+ }
103
+ }
@@ -1,5 +1,4 @@
1
- import { readFileSync, watch } from 'node:fs';
2
- import { createHash } from 'node:crypto';
1
+ import { statSync, watch } from 'node:fs';
3
2
  import path from 'node:path';
4
3
  export const WATCH_FALLBACK_MS = 5_000;
5
4
  function formatWatchError(error) {
@@ -78,9 +77,12 @@ export function createSnapshotWatchMonitor(options) {
78
77
  reconcile();
79
78
  return monitor;
80
79
  }
80
+ /** Stat stamp, not a content hash: this runs per fs event and per 5s polling tick, and the
81
+ * callers only need "did this file change" — which mtime/ctime/size/inode answer directly. */
81
82
  function fileStamp(filePath) {
82
83
  try {
83
- return createHash('sha256').update(readFileSync(filePath)).digest('hex');
84
+ const stat = statSync(filePath);
85
+ return `${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}:${stat.ino}`;
84
86
  }
85
87
  catch {
86
88
  return null;
@@ -33,6 +33,10 @@ export interface RunningExecution {
33
33
  run?: SteerableRun;
34
34
  /** Stable Cortex track session id used by registry/history/query surfaces. */
35
35
  trackSessionId?: string | null;
36
+ /** An Agent-tool child. It registers on its parent's channel so channel-wide cancel reaches it,
37
+ * and it outlives the parent's turn, but it is not the conversation: "is this channel busy"
38
+ * checks must not count it. */
39
+ subagent?: boolean;
36
40
  /** Backend resume target snapshot from spawn time. */
37
41
  backendSessionId?: string | null;
38
42
  /** Live agent-turn count of the in-flight run (adapter `turn_progress`/`turn_complete`), updated
@@ -89,6 +93,9 @@ export declare class RunRegistry {
89
93
  getForegroundBySessionId(sessionId: string): RunningExecution | null;
90
94
  /** Return all live executions registered on a channel (empty array if none). */
91
95
  getByChannel(channel: string): RunningExecution[];
96
+ /** Live executions on a channel that are the channel's own work — everything except the subagent
97
+ * children riding on it. What a busy check means by "something is running here". */
98
+ getOwnByChannel(channel: string): RunningExecution[];
92
99
  /**
93
100
  * The newest live run registered on a channel that exposes `steer()`, or null. The run itself
94
101
  * decides whether it can accept an injection; callers must not inspect the process.
@@ -50,6 +50,7 @@ export class RunRegistry {
50
50
  trackSessionId: exec.trackSessionId ?? null,
51
51
  backendSessionId: exec.backendSessionId ?? null,
52
52
  numTurns: exec.numTurns ?? null,
53
+ subagent: exec.subagent ?? false,
53
54
  };
54
55
  this.byKey.set(key, entry);
55
56
  if (entry.threadId)
@@ -133,6 +134,11 @@ export class RunRegistry {
133
134
  const set = this.byChannel.get(channel);
134
135
  return set ? Array.from(set) : [];
135
136
  }
137
+ /** Live executions on a channel that are the channel's own work — everything except the subagent
138
+ * children riding on it. What a busy check means by "something is running here". */
139
+ getOwnByChannel(channel) {
140
+ return this.getByChannel(channel).filter((entry) => !entry.subagent);
141
+ }
136
142
  /**
137
143
  * The newest live run registered on a channel that exposes `steer()`, or null. The run itself
138
144
  * decides whether it can accept an injection; callers must not inspect the process.
@@ -29,6 +29,9 @@ export interface Settings {
29
29
  feishuSkillsInWeb: boolean;
30
30
  managerRotateSteps: number;
31
31
  waitingSweepMs: number;
32
+ waitpointSweepMs: number;
33
+ waitpointTtlMs: number;
34
+ waitpointMaxWakesPerHour: number;
32
35
  injectWaitMaxS: number;
33
36
  threadMaxDepth: number;
34
37
  taskArtifactTemplates: string[];
@@ -186,6 +189,24 @@ export declare const SETTINGS_SPEC: {
186
189
  default: number;
187
190
  legacyParse: (raw: string) => number;
188
191
  };
192
+ waitpointSweepMs: {
193
+ envVar: string;
194
+ type: "number";
195
+ default: number;
196
+ legacyParse: (raw: string) => number;
197
+ };
198
+ waitpointTtlMs: {
199
+ envVar: string;
200
+ type: "number";
201
+ default: number;
202
+ legacyParse: (raw: string) => number;
203
+ };
204
+ waitpointMaxWakesPerHour: {
205
+ envVar: string;
206
+ type: "number";
207
+ default: number;
208
+ legacyParse: (raw: string) => number;
209
+ };
189
210
  injectWaitMaxS: {
190
211
  envVar: string;
191
212
  type: "number";
@@ -1,7 +1,7 @@
1
1
  // input: raw environment and runtime setting policy shapes
2
2
  // output: settings types, defaults, parsers and validators
3
3
  // pos: Browser-safe runtime settings contract
4
- // >>> Once updated, update this header and parent CORTEX.md <<<
4
+ // >>> Once updated, update this header and parent AGENTS.md <<<
5
5
  export const MAX_TIMER_DELAY_MS = 2_147_483_647;
6
6
  export const MAX_SESSION_RETENTION_DAYS = Math.floor(Number.MAX_SAFE_INTEGER / 86_400_000);
7
7
  function validateJobInterval(value) {
@@ -160,6 +160,33 @@ export const SETTINGS_SPEC = {
160
160
  return Number.isFinite(value) ? value : 60_000;
161
161
  },
162
162
  },
163
+ waitpointSweepMs: {
164
+ envVar: 'CORTEX_WAITPOINT_SWEEP_MS',
165
+ type: 'number',
166
+ default: 30_000,
167
+ legacyParse: (raw) => {
168
+ const value = Number.parseInt(raw || '', 10);
169
+ return Number.isFinite(value) ? value : 30_000;
170
+ },
171
+ },
172
+ waitpointTtlMs: {
173
+ envVar: 'CORTEX_WAITPOINT_TTL_MS',
174
+ type: 'number',
175
+ default: 7 * 24 * 60 * 60 * 1000,
176
+ legacyParse: (raw) => {
177
+ const value = Number.parseInt(raw || '', 10);
178
+ return Number.isFinite(value) && value > 0 ? value : 7 * 24 * 60 * 60 * 1000;
179
+ },
180
+ },
181
+ waitpointMaxWakesPerHour: {
182
+ envVar: 'CORTEX_WAITPOINT_MAX_WAKES_PER_HOUR',
183
+ type: 'number',
184
+ default: 12,
185
+ legacyParse: (raw) => {
186
+ const value = Number.parseInt(raw || '', 10);
187
+ return Number.isFinite(value) && value > 0 ? value : 12;
188
+ },
189
+ },
163
190
  injectWaitMaxS: {
164
191
  envVar: 'CORTEX_INJECT_WAIT_MAX_S',
165
192
  type: 'number',
@@ -31,7 +31,9 @@ export type SystemTurnOrigin =
31
31
  /** A subtask escalated a question to the manager session (`ask_manager`). */
32
32
  | 'subtask-question'
33
33
  /** A backgrounded `agent` run delivered its result. */
34
- | 'agent-result';
34
+ | 'agent-result'
35
+ /** A waitpoint an agent armed was resolved by a signal from outside the process. */
36
+ | 'external-signal';
35
37
  export interface AuthNoticeAction {
36
38
  kind: 'auth-login';
37
39
  noticeId: string;
@@ -16,7 +16,23 @@ export interface StageDefinition {
16
16
  continuesSession?: boolean;
17
17
  description?: string;
18
18
  }
19
- export interface AgentDefinition {
19
+ /** Setting files Claude Code may load beyond what Cortex passes explicitly (`--setting-sources`).
20
+ * Absent leaves the CLI's own default; `[]` loads none, which is how an agent keeps a user's
21
+ * `enabledPlugins` and ambient hooks out of its session. */
22
+ export type AgentSettingSource = 'user' | 'project' | 'local';
23
+ /** The environment fields an agent template owns. Every default equals the behaviour an agent that
24
+ * declares none of them already had, so adding the block to a definition changes nothing by itself.
25
+ * Mixed into {@link AgentDefinition}, {@link AgentSlotConfig} and the per-template override on
26
+ * {@link TemplateAgentRef}; `delegable` sits on the definition alone because it describes what the
27
+ * agent is rather than how one template runs it. */
28
+ export interface AgentEnvironment {
29
+ loadRules?: boolean;
30
+ disableHooks?: boolean;
31
+ skills?: boolean;
32
+ settingSources?: AgentSettingSource[];
33
+ projectContext?: boolean;
34
+ }
35
+ export interface AgentDefinition extends AgentEnvironment {
20
36
  name: string;
21
37
  description?: string;
22
38
  profile: string;
@@ -30,6 +46,9 @@ export interface AgentDefinition {
30
46
  pluginDirs?: string[];
31
47
  mcpComposition?: McpComposition;
32
48
  mcpToolAllowlist?: string[];
49
+ /** Whether this template may be named as a subagent delegation target. Declared now so a
50
+ * definition can carry the intent; nothing reads it yet. */
51
+ delegable?: boolean;
33
52
  /** Optional per-stage prompt map. When set, `promptTemplate` is ignored and the engine
34
53
  * selects one stage per step based on the transition target (`"agent:stage"` syntax). */
35
54
  stages?: Record<string, StageDefinition>;
@@ -39,7 +58,7 @@ export interface AgentDefinition {
39
58
  entryStage?: string;
40
59
  }
41
60
  /** Template can reference an agent by name (string) or with per-template overrides (object) */
42
- export type TemplateAgentRef = string | {
61
+ export type TemplateAgentRef = string | (AgentEnvironment & {
43
62
  ref: string;
44
63
  promptTemplate?: string;
45
64
  directive?: string;
@@ -50,8 +69,8 @@ export type TemplateAgentRef = string | {
50
69
  tools?: string;
51
70
  pluginDirs?: string[];
52
71
  mcpToolAllowlist?: string[];
53
- };
54
- export interface AgentSlotConfig {
72
+ });
73
+ export interface AgentSlotConfig extends AgentEnvironment {
55
74
  slotId: AgentSlotId;
56
75
  profile: string;
57
76
  persistSession: boolean;
@@ -16,7 +16,7 @@ declare function todayISO(): string;
16
16
  * List subdirectories of PROJECTS_DIR that look like project folders.
17
17
  *
18
18
  * Filters out:
19
- * - non-directories (e.g. top-level files like CORTEX.md, AGENTS.md that
19
+ * - non-directories (e.g. top-level files like AGENTS.md, AGENTS.md that
20
20
  * some users keep next to their projects/ tree)
21
21
  * - dotfiles (.git, .obsidian, etc.)
22
22
  *
@@ -74,7 +74,7 @@ function todayISO() {
74
74
  * List subdirectories of PROJECTS_DIR that look like project folders.
75
75
  *
76
76
  * Filters out:
77
- * - non-directories (e.g. top-level files like CORTEX.md, AGENTS.md that
77
+ * - non-directories (e.g. top-level files like AGENTS.md, AGENTS.md that
78
78
  * some users keep next to their projects/ tree)
79
79
  * - dotfiles (.git, .obsidian, etc.)
80
80
  *
@@ -26,6 +26,9 @@ export interface ChannelOverride {
26
26
  * thread is a tool for that thread, not a statement about what the next Web session should run. */
27
27
  export interface SelectionDefault extends ChannelOverride {
28
28
  profileName?: string;
29
+ /** The agent — the environment — the last composer pick ran in. Written by its own pick, never
30
+ * by a model/profile one: the two are independent axes and neither erases the other. */
31
+ agentName?: string;
29
32
  }
30
33
  export interface AgentState {
31
34
  /** Globally selected profile name. `'__active__'` is init's placeholder for "use the default". */
@@ -34,6 +37,10 @@ export interface AgentState {
34
37
  channelProfiles: Record<string, string>;
35
38
  /** Thread agent applied to plain messages when no agent is named. */
36
39
  defaultAgent: string | null;
40
+ /** Per-channel agent selection; beats `defaultAgent` for that channel. The agent is the
41
+ * conversation's ENVIRONMENT (prompt, tools, skills, rules), the twin of `channelProfiles`
42
+ * on the model axis — which is why the two maps are separate and neither writes the other. */
43
+ channelAgents: Record<string, string>;
37
44
  /** Per-channel knobs layered on top of the resolved profile. */
38
45
  channelOverrides: Record<string, ChannelOverride>;
39
46
  /** Seed for the next conversation's composer — see {@link SelectionDefault}. */
@@ -6,7 +6,9 @@ const log = createLogger('agent-state');
6
6
  const STATE_FILE = path.join(STORE_DIR, 'agent-state.json');
7
7
  const LEGACY_FILE = path.join(STORE_DIR, 'mode.json');
8
8
  function emptyState() {
9
- return { activeProfile: null, channelProfiles: {}, defaultAgent: null, channelOverrides: {} };
9
+ return {
10
+ activeProfile: null, channelProfiles: {}, defaultAgent: null, channelAgents: {}, channelOverrides: {},
11
+ };
10
12
  }
11
13
  function record(value) {
12
14
  return value && typeof value === 'object' && !Array.isArray(value)
@@ -50,6 +52,9 @@ function parseSelectionDefault(value) {
50
52
  const profileName = record(value).profileName;
51
53
  if (typeof profileName === 'string' && profileName)
52
54
  seed.profileName = profileName;
55
+ const agentName = record(value).agentName;
56
+ if (typeof agentName === 'string' && agentName)
57
+ seed.agentName = agentName;
53
58
  return Object.keys(seed).length > 0 ? seed : undefined;
54
59
  }
55
60
  /** Parse either file shape into one state. Unknown and malformed fields collapse to the empty
@@ -63,6 +68,7 @@ function parseState(raw) {
63
68
  state.channelProfiles = stringMap(data.channelProfiles);
64
69
  if (typeof data.defaultAgent === 'string' && data.defaultAgent)
65
70
  state.defaultAgent = data.defaultAgent;
71
+ state.channelAgents = stringMap(data.channelAgents);
66
72
  state.channelOverrides = overrideMap(data.channelOverrides);
67
73
  // Assigned only when there is one: an explicit `selectionDefault: undefined` key is still a key,
68
74
  // and every caller here compares whole states.
@@ -123,6 +129,8 @@ export function saveAgentState(state) {
123
129
  data.channelProfiles = state.channelProfiles;
124
130
  if (state.defaultAgent)
125
131
  data.defaultAgent = state.defaultAgent;
132
+ if (Object.keys(state.channelAgents).length > 0)
133
+ data.channelAgents = state.channelAgents;
126
134
  if (Object.keys(state.channelOverrides).length > 0)
127
135
  data.channelOverrides = state.channelOverrides;
128
136
  if (state.selectionDefault && Object.keys(state.selectionDefault).length > 0) {
@@ -0,0 +1,38 @@
1
+ export type SwitchAgentFailure = 'unknown-agent' | 'cross-backend-live-session';
2
+ export interface SwitchAgentSuccess {
3
+ ok: true;
4
+ /** The agent the channel now runs. */
5
+ agentName: string;
6
+ /** The profile that agent will actually run under — its own when it pins one, otherwise the
7
+ * channel's. FOR DISPLAY ONLY: the run path re-resolves it every turn, and this rule never
8
+ * writes `channelProfiles` (a pinned profile is already an override there). */
9
+ effectiveProfile: string;
10
+ /** True when the switch moved to a different backend (only possible on a fresh session). */
11
+ backendChanged: boolean;
12
+ }
13
+ export interface SwitchAgentRefusal {
14
+ ok: false;
15
+ reason: SwitchAgentFailure;
16
+ /** The channel's effective backend before the switch; absent when the agent was unknown. */
17
+ currentBackend?: string;
18
+ /** The backend the agent would have run on; absent when the agent was unknown. */
19
+ targetBackend?: string;
20
+ }
21
+ export type SwitchAgentResult = SwitchAgentSuccess | SwitchAgentRefusal;
22
+ /**
23
+ * Switch the agent for a channel/session under the shared switch rule.
24
+ *
25
+ * Takes effect on the NEXT turn, like `!model`: the EngineSpec changes identity, so `SessionEngines`
26
+ * restarts the process with `--resume` and the conversation keeps its history under the new prompt
27
+ * and tool surface. Nothing is reset.
28
+ *
29
+ * The cross-backend refusal is {@link decideProfileSwitch}, unchanged — an agent that pins a
30
+ * profile on the other backend is a backend move wearing a different hat, and a live conversation
31
+ * cannot be resumed there.
32
+ */
33
+ export declare function switchChannelAgent(opts: {
34
+ channel: string;
35
+ name: string;
36
+ }): Promise<SwitchAgentResult>;
37
+ /** Drop the channel's agent selection: it follows the global default again, from the next turn. */
38
+ export declare function clearChannelAgentSelection(channel: string): Promise<void>;
@@ -0,0 +1,106 @@
1
+ // input: template-loader (getAgent) + config (getDefaultAgent/setDefaultAgent/clearChannelAgent/
2
+ // resolveBackendForChannel) + profile-manager (resolveProfileConfig) + profile-switch
3
+ // (decideProfileSwitch/channelHasHistory) + session-registry-repo (record sync)
4
+ // output: switchChannelAgent / clearChannelAgentSelection — the composed "switch the agent for a
5
+ // channel/session" rule used by the `!agent` command AND the Web UI, so the rule has ONE
6
+ // source of truth.
7
+ // pos: domain/agents — the environment twin of profile-switch.ts. An agent decides the
8
+ // conversation's prompt, tools, skills and rules; a profile decides its model. The two are
9
+ // independent axes, so switching an agent writes the agent map and nothing else — but they
10
+ // meet at the backend, because an agent that pins a profile pins that profile's backend,
11
+ // and a live conversation can no more move across backends this way than through `!profile`.
12
+ import { sessionStore } from '../../store/session-registry-repo.js';
13
+ import { clearChannelAgent, getActiveProfile, resolveBackendForChannel, setDefaultAgent, setSelectionDefaultAgent, } from './config.js';
14
+ import { resolveProfileConfig } from './profile-manager.js';
15
+ import { channelHasHistory, decideProfileSwitch } from './profile-switch.js';
16
+ // The template loader, not the `@domain/threads` barrel: the barrel re-exports prompt-builder,
17
+ // which imports this domain back, and the cycle would be real at module-init time.
18
+ import { getAgent } from '../threads/template-loader.js';
19
+ /**
20
+ * The backend an agent runs on for a given channel: its own profile's when it pins one, else the
21
+ * channel's — an `__active__` agent follows whatever the channel already resolves to, so it can
22
+ * never move the backend by itself.
23
+ */
24
+ function targetBackendOf(agentProfile, currentBackend) {
25
+ if (agentProfile === '__active__')
26
+ return currentBackend;
27
+ try {
28
+ return resolveProfileConfig(agentProfile).backend;
29
+ }
30
+ catch {
31
+ // A pinned profile that no longer exists cannot state a backend; the channel's own answer is
32
+ // the honest one, and the run path reports the bad name when the turn opens.
33
+ return currentBackend;
34
+ }
35
+ }
36
+ /**
37
+ * Switch the agent for a channel/session under the shared switch rule.
38
+ *
39
+ * Takes effect on the NEXT turn, like `!model`: the EngineSpec changes identity, so `SessionEngines`
40
+ * restarts the process with `--resume` and the conversation keeps its history under the new prompt
41
+ * and tool surface. Nothing is reset.
42
+ *
43
+ * The cross-backend refusal is {@link decideProfileSwitch}, unchanged — an agent that pins a
44
+ * profile on the other backend is a backend move wearing a different hat, and a live conversation
45
+ * cannot be resumed there.
46
+ */
47
+ export async function switchChannelAgent(opts) {
48
+ const { channel, name } = opts;
49
+ const agent = getAgent(name);
50
+ if (!agent)
51
+ return { ok: false, reason: 'unknown-agent' };
52
+ const currentBackend = resolveBackendForChannel(channel);
53
+ const targetBackend = targetBackendOf(agent.profile, currentBackend);
54
+ const decision = decideProfileSwitch({
55
+ currentBackend, targetBackend, hasHistory: await channelHasHistory(channel),
56
+ });
57
+ if (!decision.allowed) {
58
+ return { ok: false, reason: 'cross-backend-live-session', currentBackend, targetBackend };
59
+ }
60
+ setDefaultAgent(name, channel);
61
+ seedNextConversation(channel, name);
62
+ await syncSessionAgent(channel, name);
63
+ return {
64
+ ok: true,
65
+ agentName: name,
66
+ effectiveProfile: agent.profile === '__active__' ? resolveChannelProfileName(channel) : agent.profile,
67
+ backendChanged: decision.backendChanged,
68
+ };
69
+ }
70
+ /** Drop the channel's agent selection: it follows the global default again, from the next turn. */
71
+ export async function clearChannelAgentSelection(channel) {
72
+ clearChannelAgent(channel);
73
+ seedNextConversation(channel, null);
74
+ await syncSessionAgent(channel, null);
75
+ }
76
+ /** A pick made in the app says how the user wants to work, so the NEXT new conversation opens in
77
+ * the same environment. Direct (`web:`) channels only, for the reason `applyChannelSelection`
78
+ * gives: an `!agent` in some Slack thread is a tool for that thread. */
79
+ function seedNextConversation(channel, agentName) {
80
+ if (channel.startsWith('web:'))
81
+ setSelectionDefaultAgent(agentName);
82
+ }
83
+ /** Keep the session-registry record in lock-step (best-effort), so the Web session list and
84
+ * `!resume` report the agent the channel is on. The channel map is the runtime source of truth;
85
+ * a failure here costs a label, not the switch. */
86
+ async function syncSessionAgent(channel, agentName) {
87
+ try {
88
+ const sessionName = await sessionStore.getActiveSessionName(channel);
89
+ if (sessionName)
90
+ await sessionStore.updateSession(sessionName, { agentName });
91
+ }
92
+ catch {
93
+ // non-fatal — see above
94
+ }
95
+ }
96
+ /** The profile name an `__active__` agent displays: whatever the channel itself resolves to. */
97
+ function resolveChannelProfileName(channel) {
98
+ try {
99
+ return resolveProfileConfig(getActiveProfile(channel)).name;
100
+ }
101
+ catch {
102
+ // No profile resolvable at all (profiles.json unreadable) — say what the agent declares rather
103
+ // than inventing a name the run would not use.
104
+ return '__active__';
105
+ }
106
+ }