@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
@@ -20,10 +20,12 @@ import { projectStore } from '../domain/projects/index.js';
20
20
  import { loadCommissionDraftContext, loadCommissionPromptContext, } from '../domain/commissions/commission-context.js';
21
21
  import { sessionStore } from '../store/session-registry-repo.js';
22
22
  import { getSettings } from '../core/settings.js';
23
- import { buildPrompt as buildAgentPrompt } from '../agent-adapter/normalize/prompt-builder.js';
24
- function buildBackendPrompt(prompt, files) {
25
- const attachments = files.map((file) => ({ mimeType: file.mimetype, path: file.localPath }));
26
- return buildAgentPrompt(prompt, attachments);
23
+ import { buildPrompt as buildAgentPrompt, formatAttachmentFailures, } from '../agent-adapter/normalize/prompt-builder.js';
24
+ function buildBackendPrompt(prompt, files, failures = []) {
25
+ const attachments = files.map((file) => ({
26
+ mimeType: file.mimetype, path: file.localPath, name: file.name,
27
+ }));
28
+ return buildAgentPrompt(prompt, attachments, failures);
27
29
  }
28
30
  /**
29
31
  * Whether the surface wants a background hold. The conversation path never waits inline, so both
@@ -44,9 +46,13 @@ function conversationBackgroundPolicy(channel) {
44
46
  * in history) of a Web UI direct session (`web:` channel — the only path where the user explicitly
45
47
  * binds the session to a project at create time), and only for real user projects (the `general`
46
48
  * umbrella carries no signal). Unknown/deleted project ids inject nothing rather than a dead path.
49
+ * An agent with `projectContext: false` opts out of the block entirely — "record your findings in
50
+ * the project" is operational noise in an environment built for something else.
47
51
  */
48
52
  export function resolveConversationProject(args) {
49
53
  const store = args.store ?? projectStore;
54
+ if (args.projectContext === false)
55
+ return null;
50
56
  if (!args.isFreshSession)
51
57
  return null;
52
58
  if (!args.channel.startsWith('web:'))
@@ -56,6 +62,63 @@ export function resolveConversationProject(args) {
56
62
  return null;
57
63
  return { id: project.id, contextDir: project.contextDir };
58
64
  }
65
+ /**
66
+ * The policy one conversation turn opens under: the shared direct-run policy, the surface's own
67
+ * background intent, and the execution-environment fields the agent template declares.
68
+ *
69
+ * Every environment default equals what {@link DIRECT_RUN_POLICY} already said, so an agent that
70
+ * declares none of them produces that constant field for field — which is why adding the fields
71
+ * changed no existing session. `skills` and `settingSources` stay `undefined` rather than being
72
+ * defaulted here: absent means "whatever the backend loads on its own", and only the agent that
73
+ * opts out has an opinion.
74
+ */
75
+ export function conversationRunPolicy(agentConfig, opts) {
76
+ return {
77
+ ...DIRECT_RUN_POLICY,
78
+ background: conversationBackgroundPolicy(opts.channel),
79
+ hooks: agentConfig.disableHooks !== true,
80
+ loadRules: agentConfig.loadRules !== false,
81
+ skills: agentConfig.skills,
82
+ settingSources: agentConfig.settingSources,
83
+ mcpComposition: agentConfig.mcpComposition ?? 'direct',
84
+ mcpToolAllowlist: agentConfig.mcpToolAllowlist,
85
+ browserCdpEndpoint: opts.browserCdpEndpoint ?? null,
86
+ };
87
+ }
88
+ /** The agent a conversation falls back to when nothing anywhere names one. */
89
+ const FALLBACK_AGENT = 'main';
90
+ /**
91
+ * Which agent — which execution environment — a conversation turn opens under.
92
+ *
93
+ * The chain is the profile chain's twin: the session's own choice (what the composer set, or what
94
+ * `!agent` recorded on the session), then the channel's selection, then the global default, then
95
+ * `main`. `getDefaultAgent(channel)` already folds the middle two together.
96
+ *
97
+ * A candidate that no longer resolves is SKIPPED rather than fatal: an agent renamed or deleted
98
+ * since it was persisted must not kill every turn of the session that named it, exactly as an
99
+ * unknown channel profile falls back instead of throwing (see the run-config resolution below).
100
+ */
101
+ export function resolveConversationAgent(candidates, resolve = resolveAgentSlotConfigByName) {
102
+ for (const name of [...candidates, FALLBACK_AGENT]) {
103
+ if (!name)
104
+ continue;
105
+ const agentConfig = resolve(name);
106
+ if (agentConfig)
107
+ return { agentName: name, agentConfig };
108
+ }
109
+ throw new Error(`Unknown default agent: ${FALLBACK_AGENT}`);
110
+ }
111
+ /** The agent recorded on the session record, if any. Best-effort: a registry read that fails leaves
112
+ * the channel's selection to answer, which is the same thing a session with no choice of its own
113
+ * would produce. */
114
+ async function sessionAgentName(sessionId) {
115
+ try {
116
+ return (await sessionStore.getById(sessionId))?.agentName ?? null;
117
+ }
118
+ catch {
119
+ return null;
120
+ }
121
+ }
59
122
  /** The delivery key for a session's current commission binding, or null outside the mode. Bound
60
123
  * wins over drafting: finalize clears the draft, and the two are never both meaningful. */
61
124
  export function commissionBindingKey(session) {
@@ -122,27 +185,39 @@ export async function resolveConversationCommission(trackSessionId, args = {}, d
122
185
  */
123
186
  export async function prepareConversationRequest(opts) {
124
187
  const { sessionId, backendSessionId, sessionName, projectId } = opts.ids;
125
- const defaultAgentName = getDefaultAgent() || 'main';
126
- const agentConfig = resolveAgentSlotConfigByName(defaultAgentName);
127
- if (!agentConfig)
128
- throw new Error(`Unknown default agent: ${defaultAgentName}`);
188
+ const { agentConfig } = resolveConversationAgent([
189
+ await sessionAgentName(sessionId),
190
+ getDefaultAgent(opts.channel),
191
+ ]);
129
192
  // USER.md profile is injected only on a session's FIRST turn (no backend session yet).
130
193
  // Session resume keeps it in history thereafter, so re-sending it every turn just wastes tokens.
131
194
  const isFreshSession = backendSessionId === null;
132
- // A thread-free conversation runs on the direct MCP surface — there is no thread to control.
133
- const spec = fromAgentSlot(agentConfig, { mcpComposition: 'direct' });
195
+ // A thread-free conversation runs on the direct MCP surface — there is no thread to control —
196
+ // unless the agent declared a narrower one, which it owns on every path it runs.
197
+ const policy = conversationRunPolicy(agentConfig, {
198
+ channel: opts.channel, browserCdpEndpoint: opts.browserCdpEndpoint,
199
+ });
200
+ const spec = fromAgentSlot(agentConfig, { mcpComposition: policy.mcpComposition });
134
201
  // A plain conversation turn is thread-free: no artifact, no previous step, no control-plane
135
202
  // preamble. Everything it does carry is a first-turn ambient block, and the two prompt-shaping
136
203
  // fields come from the very spec the run is opened with — one description of the agent, not two.
137
- const prompt = composeUserPrompt(spec, opts.userMessage, {
204
+ const composedPrompt = composeUserPrompt(spec, opts.userMessage, {
138
205
  userContext: userProfileBlock(isFreshSession),
139
206
  // Web UI direct sessions are bound to a project at create time; tell the agent which one
140
207
  // on the session's first turn (see resolveConversationProject for the exact gating).
141
- project: resolveConversationProject({ channel: opts.channel, projectId, isFreshSession }),
208
+ project: resolveConversationProject({
209
+ channel: opts.channel,
210
+ projectId,
211
+ isFreshSession,
212
+ projectContext: agentConfig.projectContext,
213
+ }),
142
214
  // Commission sessions additionally get the contract + ledger index + protocol block, once per
143
215
  // binding rather than once per session (see resolveConversationCommission).
144
216
  commission: await resolveConversationCommission(sessionId, { isFreshSession }),
145
217
  });
218
+ // The backend composes the real prompt from `prompt.text` + `prompt.attachments`, so a download
219
+ // failure has to ride the TEXT to reach the model — `backendPrompt` below is the debug echo.
220
+ const prompt = `${formatAttachmentFailures(opts.failedFiles ?? [])}${composedPrompt}`;
146
221
  const backendPrompt = buildBackendPrompt(prompt, opts.files);
147
222
  opts.onPromptBuilt?.(backendPrompt);
148
223
  // Attribute cost/execution to the session's bound project (from the registry record), NOT a
@@ -178,7 +253,9 @@ export async function prepareConversationRequest(opts) {
178
253
  spec,
179
254
  prompt: {
180
255
  text: prompt,
181
- attachments: (opts.files || []).map((file) => ({ mimeType: file.mimetype, path: file.localPath })),
256
+ attachments: (opts.files || []).map((file) => ({
257
+ mimeType: file.mimetype, path: file.localPath, name: file.name,
258
+ })),
182
259
  },
183
260
  context: {
184
261
  channel: opts.channel,
@@ -190,15 +267,7 @@ export async function prepareConversationRequest(opts) {
190
267
  commissionMode: opts.commissionMode ?? false,
191
268
  scheduleTaskId: opts.scheduleTaskId ?? null,
192
269
  },
193
- // The three fields that differ from the shared direct-run policy; every field NOT named here
194
- // is provably the `DIRECT_RUN_POLICY` value (background:'none' → this path's surface intent,
195
- // and browserCdpEndpoint:null → the session's opted-in Chrome, are the two it overrides).
196
- policy: {
197
- ...DIRECT_RUN_POLICY,
198
- background: conversationBackgroundPolicy(opts.channel),
199
- mcpToolAllowlist: agentConfig.mcpToolAllowlist,
200
- browserCdpEndpoint: opts.browserCdpEndpoint ?? null,
201
- },
270
+ policy,
202
271
  };
203
272
  return { request, backendPrompt };
204
273
  }
@@ -1,7 +1,7 @@
1
1
  // input: EventBus
2
2
  // output: PendingPlan type and PlanApprovals state
3
3
  // pos: Tracks request-keyed plan approvals
4
- // >>> If updated, update this header and folder CORTEX.md <<<
4
+ // >>> If updated, update this header and folder AGENTS.md <<<
5
5
  export class PlanApprovals {
6
6
  _map = new Map();
7
7
  _bus = null;
@@ -17,6 +17,9 @@ import { type InjectionLedgerDeps } from './transcript-sink.js';
17
17
  export interface LiveExecutionLike {
18
18
  backend: string;
19
19
  run?: AgentRun;
20
+ /** Stable Cortex session the run belongs to. A subagent child registers on its parent's channel
21
+ * with a null session, so this is what tells the conversation's own run apart from it. */
22
+ trackSessionId?: string | null;
20
23
  }
21
24
  /** Everything the injection ledger and the router need, bound by `buildInjectDeps`. */
22
25
  export interface MidTurnInjectDeps extends InjectionLedgerDeps {
@@ -30,11 +30,16 @@ export function isInjectableMessage(opts) {
30
30
  export function backendSupportsInject(backend) {
31
31
  return !!CAPABILITIES_BY_BACKEND[backend]?.has(Capability.MidTurnInject);
32
32
  }
33
- /** The newest live run on the channel. Capability is enforced by `run.steer()`, not inspected here. */
34
- function selectInjectRun(execs) {
33
+ /**
34
+ * The newest live run on the channel that belongs to the channel's own session. Background subagent
35
+ * children share the parent's channel and outlive the parent's turn; picking one of them sent the
36
+ * user's message into the child's stdin, where it was swallowed and the conversation never answered.
37
+ * Capability is enforced by `run.steer()`, not inspected here.
38
+ */
39
+ function selectInjectRun(execs, sessionId) {
35
40
  let best = null;
36
41
  for (const exec of execs) {
37
- if (exec.run)
42
+ if (exec.run && exec.trackSessionId === sessionId)
38
43
  best = { run: exec.run, backend: exec.backend };
39
44
  }
40
45
  return best;
@@ -65,7 +70,7 @@ function buildPendingRecord(deps, ctx, message, sessionId, backend, ts) {
65
70
  export async function tryInjectIntoLiveTurn(deps, ctx) {
66
71
  if (!isInjectableMessage(ctx) || !ctx.sessionId)
67
72
  return false;
68
- const target = selectInjectRun(deps.getLiveExecutions(ctx.channel));
73
+ const target = selectInjectRun(deps.getLiveExecutions(ctx.channel), ctx.sessionId);
69
74
  if (!target)
70
75
  return false;
71
76
  const platformAttachments = ctx.prepareBackendAttachments
@@ -22,6 +22,17 @@ export declare function copyFileIntoOutputs(a: {
22
22
  subdir?: string;
23
23
  maxBytes?: number;
24
24
  }): Promise<StoredOutput>;
25
+ /**
26
+ * Land a file whose bytes are produced by `receive` (a remote-device transfer) directly in the
27
+ * outputs area. Same placement and naming as `copyFileIntoOutputs`, but written once: staging to a
28
+ * temp file first and copying would double the I/O of every large transfer and leave litter behind
29
+ * when a send fails. A failing `receive` must leave nothing, so the reservation is removed here.
30
+ */
31
+ export declare function receiveIntoOutputs(a: {
32
+ sessionId: string;
33
+ fileName: string;
34
+ subdir?: string;
35
+ }, receive: (destPath: string) => Promise<void>): Promise<StoredOutput>;
25
36
  /** Write agent-authored text into the session's outputs area under `fileName`, same placement and
26
37
  * naming discipline as `copyFileIntoOutputs`. Used when the payload arrives inline rather than as
27
38
  * a path on disk. */
@@ -70,6 +70,16 @@ function outputsDir(sessionId, subdir) {
70
70
  relPrefix: `workspace/outputs/${parts.join('/')}`,
71
71
  };
72
72
  }
73
+ /** Claim a free destination inside the session's outputs area, creating the directory. Shared by
74
+ * every lander so naming, collision handling and placement cannot drift between them. */
75
+ async function reserveOutputPath(a) {
76
+ const displayName = sanitizeDisplayFilename(a.fileName);
77
+ const storageName = sanitizeStorageFilename(displayName);
78
+ const { dir, relPrefix } = outputsDir(a.sessionId, a.subdir);
79
+ await fs.mkdir(dir, { recursive: true });
80
+ const { destPath, finalName } = await resolveAvailablePath(dir, storageName);
81
+ return { destPath, relPath: `${relPrefix}/${finalName}`, displayName };
82
+ }
73
83
  /**
74
84
  * Copy an agent-produced file into the session's `workspace/outputs/…` area and return its
75
85
  * UI-relative path + final name + byte size. Copying (rather than referencing the source in
@@ -91,14 +101,30 @@ export async function copyFileIntoOutputs(a) {
91
101
  if (a.maxBytes !== undefined && stat.size > a.maxBytes) {
92
102
  throw new Error(`File is ${stat.size} bytes, over the ${a.maxBytes}-byte limit`);
93
103
  }
94
- const displayName = sanitizeDisplayFilename(a.fileName || path.basename(resolvedSrc));
95
- const storageName = sanitizeStorageFilename(displayName);
96
- const { dir, relPrefix } = outputsDir(a.sessionId, a.subdir);
97
- await fs.mkdir(dir, { recursive: true });
98
- const { destPath, finalName } = await resolveAvailablePath(dir, storageName);
104
+ const { destPath, relPath, displayName } = await reserveOutputPath({
105
+ sessionId: a.sessionId, fileName: a.fileName || path.basename(resolvedSrc), subdir: a.subdir,
106
+ });
99
107
  await fs.copyFile(resolvedSrc, destPath);
100
108
  const outStat = await fs.stat(destPath);
101
- return { relPath: `${relPrefix}/${finalName}`, name: displayName, size: outStat.size };
109
+ return { relPath, name: displayName, size: outStat.size };
110
+ }
111
+ /**
112
+ * Land a file whose bytes are produced by `receive` (a remote-device transfer) directly in the
113
+ * outputs area. Same placement and naming as `copyFileIntoOutputs`, but written once: staging to a
114
+ * temp file first and copying would double the I/O of every large transfer and leave litter behind
115
+ * when a send fails. A failing `receive` must leave nothing, so the reservation is removed here.
116
+ */
117
+ export async function receiveIntoOutputs(a, receive) {
118
+ const { destPath, relPath, displayName } = await reserveOutputPath(a);
119
+ try {
120
+ await receive(destPath);
121
+ }
122
+ catch (e) {
123
+ await fs.rm(destPath, { force: true }).catch(() => { });
124
+ throw e;
125
+ }
126
+ const outStat = await fs.stat(destPath);
127
+ return { relPath, name: displayName, size: outStat.size };
102
128
  }
103
129
  /** Write agent-authored text into the session's outputs area under `fileName`, same placement and
104
130
  * naming discipline as `copyFileIntoOutputs`. Used when the payload arrives inline rather than as
@@ -31,8 +31,10 @@ function defaultDeps() {
31
31
  requeue: recordResume,
32
32
  buildResumeInput: (thread) => resumeThreadRunInput(thread, 'resume-rate-limited'),
33
33
  getThread: (id) => threadStore.get(id),
34
- channelBusy: (ch) => runRegistry.hasChannel(ch),
35
- directSessionBusy: (ch) => runRegistry.getByChannel(ch).some(e => !e.threadId),
34
+ // Subagent children ride on their parent's channel and outlive its turn; counting them read an
35
+ // idle conversation as busy, which dropped its direct resume and stalled threads behind it.
36
+ channelBusy: (ch) => runRegistry.getOwnByChannel(ch).length > 0,
37
+ directSessionBusy: (ch) => runRegistry.getOwnByChannel(ch).some(e => !e.threadId),
36
38
  acquireSessionUse: (sessionId) => acquireSessionUse(sessionId),
37
39
  track: trackPendingTask,
38
40
  delay: (ms) => new Promise((r) => setTimeout(r, ms)),
@@ -1,6 +1,6 @@
1
1
  import { Icons } from '../../../core/icons.js';
2
2
  import { t } from '../../../core/i18n.js';
3
- import { setChannelModelOverride, setChannelThinkingOverride, getActiveProfile, setActiveProfile, clearChannelProfile, getDefaultAgent, setDefaultAgent, switchChannelProfile } from '../../../domain/agents/index.js';
3
+ import { setChannelModelOverride, setChannelThinkingOverride, getActiveProfile, setActiveProfile, clearChannelProfile, getChannelAgents, getDefaultAgent, setDefaultAgent, switchChannelAgent, clearChannelAgentSelection, switchChannelProfile } from '../../../domain/agents/index.js';
4
4
  import { getDefaultProfileForBackend, getDefaultProfileName, isValidThinkingLevel, listProfiles, resolveProfile, THINKING_LEVELS_BY_BACKEND } from '../../../domain/agents/profile-manager.js';
5
5
  import { resolveRunConfig } from '../../../domain/runs/config-resolver.js';
6
6
  import { getDisplaySkillGroups } from '../../../domain/memory/skill-scanner.js';
@@ -305,71 +305,108 @@ export async function handleSkillsCmd(channel, adapter) {
305
305
  await adapter.postMessage(dest, { text: lines.join('\n') });
306
306
  }
307
307
  const MAX_AGENT_BUTTONS = 10;
308
- function buildAgentText() {
309
- const current = getDefaultAgent();
310
- const agents = listAgents();
311
- if (current) {
312
- const agentDef = getAgent(current);
313
- const profile = agentDef?.profile || '?';
314
- const claudeAgentStr = agentDef?.claudeAgent ? ` · agent:${agentDef.claudeAgent}` : '';
315
- return t('cmd.agent.current', { name: current, detail: `${profile}${claudeAgentStr}` });
316
- }
317
- return t('cmd.agent.none', { agents: agents.map(a => `\`${a.name}\``).join(', ') });
308
+ /** `profile · agent:<claude agent>` — what an agent runs under, in one line. */
309
+ function agentDetail(name) {
310
+ const agentDef = getAgent(name);
311
+ const claudeAgentStr = agentDef?.claudeAgent ? ` · agent:${agentDef.claudeAgent}` : '';
312
+ return `${agentDef?.profile || '?'}${claudeAgentStr}`;
318
313
  }
319
- function buildAgentButtons() {
314
+ /**
315
+ * What `!agent` reports: this conversation's agent, the global default it would fall back to, and
316
+ * the list to pick from. The two layers are always both named — "this channel runs creative" and
317
+ * "everything else runs main" are different facts, and a reader who sees only one cannot tell which
318
+ * of them a later `!agent reset` would leave behind.
319
+ */
320
+ function buildAgentText(channel) {
321
+ const channelAgent = getChannelAgents()[channel] ?? null;
322
+ const globalAgent = getDefaultAgent();
323
+ const header = channelAgent
324
+ ? t('cmd.agent.channelHeader', { name: channelAgent, detail: agentDetail(channelAgent) })
325
+ : globalAgent
326
+ ? t('cmd.agent.followingGlobal', { name: globalAgent })
327
+ : t('cmd.agent.followingGlobalNone');
328
+ const globalLine = globalAgent
329
+ ? t('cmd.agent.globalLine', { name: globalAgent })
330
+ : t('cmd.agent.globalNone');
331
+ const available = t('cmd.agent.available', {
332
+ agents: listAgents().map(a => `\`${a.name}\``).join(', '),
333
+ });
334
+ return `${header}\n${globalLine}\n${available}`;
335
+ }
336
+ /** The buttons set the CHANNEL's agent (the common move); the last one hands the channel back to
337
+ * the global default. Changing the global is a typed command (`!agent global <name>`) — a button
338
+ * that silently re-points every other conversation is not a button anyone wants to mis-tap. */
339
+ function buildAgentButtons(channel) {
320
340
  const agents = listAgents();
321
341
  const buttons = agents.slice(0, MAX_AGENT_BUTTONS - 1).map((a, i) => ({
322
342
  type: 'button',
323
343
  text: a.name,
324
344
  actionId: `cmd:agent:set-${i}`,
325
- value: a.name,
345
+ value: JSON.stringify({ name: a.name, channel }),
326
346
  }));
327
347
  buttons.push({
328
348
  type: 'button',
329
- text: t('cmd.agent.disableButton'),
330
- actionId: 'cmd:agent:disable',
331
- value: 'off',
332
- style: 'danger',
349
+ text: t('cmd.agent.followGlobalButton'),
350
+ actionId: 'cmd:agent:reset',
351
+ value: JSON.stringify({ channel }),
333
352
  });
334
353
  return buttons;
335
354
  }
355
+ /** Apply the shared per-channel agent-switch rule and build the reply text. Used by both
356
+ * `!agent <name>` and the interactive buttons, so Slack + Feishu share ONE code path — the same
357
+ * `switchChannelAgent` the Web UI's `sessions.setAgent` calls. */
358
+ async function switchChannelAgentReply(channel, name) {
359
+ const res = await switchChannelAgent({ channel, name });
360
+ // `res.ok === false` rather than `!res.ok`: this project compiles non-strict, where a boolean
361
+ // discriminant narrows only through an explicit comparison.
362
+ if (res.ok === false) {
363
+ if (res.reason === 'cross-backend-live-session') {
364
+ return `${Icons.error} ${t('cmd.agent.crossBackendBlocked', {
365
+ name, target: res.targetBackend ?? '?', current: res.currentBackend ?? '?',
366
+ })}`;
367
+ }
368
+ const available = listAgents().map(a => `\`${a.name}\``).join(', ');
369
+ return `${Icons.error} ${t('cmd.agent.unknown', { name, available })}`;
370
+ }
371
+ return `${Icons.ok} ${t('cmd.agent.channelSet', { name, detail: agentDetail(name) })}`;
372
+ }
373
+ /** Hand this conversation back to the global default. */
374
+ async function resetChannelAgentReply(channel) {
375
+ await clearChannelAgentSelection(channel);
376
+ const globalAgent = getDefaultAgent();
377
+ return `${Icons.ok} ${globalAgent
378
+ ? t('cmd.agent.cleared', { name: globalAgent })
379
+ : t('cmd.agent.clearedNoGlobal')}`;
380
+ }
381
+ /** `!agent reset` and its aliases: every bare form of the command is channel-scoped now, so "off"
382
+ * means "this conversation stops overriding", not "nobody has a default agent". The global is
383
+ * reached through `!agent global off`. */
384
+ const AGENT_RESET_WORDS = new Set(['reset', 'clear', 'off', 'none', 'disable']);
336
385
  export function createAgentHandler(router) {
337
386
  if (router) {
338
- const setHandler = async (ctx) => {
387
+ const rerender = async (ctx, channel, text) => {
339
388
  const adapter = router.getAdapter();
340
- if (!adapter)
389
+ if (!adapter || !ctx.messageRef)
341
390
  return;
342
- const name = ctx.value;
343
- const agentDef = getAgent(name);
344
- if (!agentDef)
391
+ await adapter.updateMessage(ctx.messageRef, {
392
+ text,
393
+ richBlocks: [
394
+ { type: 'section', text },
395
+ { type: 'actions', elements: buildAgentButtons(channel) },
396
+ ],
397
+ }).catch(() => { });
398
+ };
399
+ const setHandler = async (ctx) => {
400
+ if (!router.getAdapter())
345
401
  return;
346
- setDefaultAgent(name);
347
- const claudeAgentStr = agentDef.claudeAgent ? ` · agent:${agentDef.claudeAgent}` : '';
348
- const text = `${Icons.ok} ${t('cmd.agent.defaultSet', { name, detail: `${agentDef.profile}${claudeAgentStr}` })}`;
349
- if (ctx.messageRef) {
350
- await adapter.updateMessage(ctx.messageRef, {
351
- text,
352
- richBlocks: [
353
- { type: 'section', text },
354
- { type: 'actions', elements: buildAgentButtons() },
355
- ],
356
- }).catch(() => { });
357
- }
402
+ const { name, channel } = JSON.parse(ctx.value);
403
+ await rerender(ctx, channel, await switchChannelAgentReply(channel, name));
358
404
  };
359
- const disableHandler = async (ctx) => {
360
- const adapter = router.getAdapter();
361
- if (!adapter)
405
+ const resetHandler = async (ctx) => {
406
+ if (!router.getAdapter())
362
407
  return;
363
- setDefaultAgent(null);
364
- if (ctx.messageRef) {
365
- await adapter.updateMessage(ctx.messageRef, {
366
- text: `${Icons.ok} ${t('cmd.agent.disabled')}`,
367
- richBlocks: [
368
- { type: 'section', text: `${Icons.ok} ${t('cmd.agent.disabled')}` },
369
- { type: 'actions', elements: buildAgentButtons() },
370
- ],
371
- }).catch(() => { });
372
- }
408
+ const { channel } = JSON.parse(ctx.value);
409
+ await rerender(ctx, channel, await resetChannelAgentReply(channel));
373
410
  };
374
411
  router.registerCommand('agent', {
375
412
  actions: [
@@ -377,32 +414,46 @@ export function createAgentHandler(router) {
377
414
  actionId: `set-${i}`,
378
415
  handler: setHandler,
379
416
  })),
380
- { actionId: 'disable', handler: disableHandler },
417
+ { actionId: 'reset', handler: resetHandler },
381
418
  ],
382
419
  });
383
420
  }
384
421
  return async function handleAgentCmdInteractive(channel, adapter, trimmedMessage) {
385
- const args = trimmedMessage.replace(/^!agent\s*/, '').trim();
422
+ const args = trimmedMessage.replace(/^!agent\s*/, '').trim().split(/\s+/).filter(Boolean);
386
423
  const dest = { type: 'interactive-reply', conduit: channel, sessionId: '' };
387
- if (args) {
388
- const name = args.split(/\s+/)[0];
389
- if (name === 'off' || name === 'none' || name === 'disable') {
390
- setDefaultAgent(null);
391
- await adapter.postMessage(dest, { text: `${Icons.ok} ${t('cmd.agent.disabled')}` });
424
+ if (args.length > 0) {
425
+ if (AGENT_RESET_WORDS.has(args[0])) {
426
+ await adapter.postMessage(dest, { text: await resetChannelAgentReply(channel) });
392
427
  return;
393
428
  }
394
- const agentDef = getAgent(name);
395
- if (!agentDef) {
396
- const available = listAgents().map(a => `\`${a.name}\``).join(', ');
397
- await adapter.postMessage(dest, { text: `${Icons.error} ${t('cmd.agent.unknown', { name, available })}` });
429
+ // The old daemon-wide semantics, kept under an explicit prefix: an agent set here is what
430
+ // every conversation WITHOUT one of its own runs.
431
+ if (args[0] === 'global') {
432
+ const name = args[1];
433
+ if (!name) {
434
+ await adapter.postMessage(dest, { text: `${Icons.error} ${t('cmd.agent.globalUsage')}` });
435
+ return;
436
+ }
437
+ if (name === 'off' || name === 'none' || name === 'disable') {
438
+ setDefaultAgent(null);
439
+ await adapter.postMessage(dest, { text: `${Icons.ok} ${t('cmd.agent.disabled')}` });
440
+ return;
441
+ }
442
+ if (!getAgent(name)) {
443
+ const available = listAgents().map(a => `\`${a.name}\``).join(', ');
444
+ await adapter.postMessage(dest, { text: `${Icons.error} ${t('cmd.agent.unknown', { name, available })}` });
445
+ return;
446
+ }
447
+ setDefaultAgent(name);
448
+ await adapter.postMessage(dest, {
449
+ text: `${Icons.ok} ${t('cmd.agent.defaultSet', { name, detail: agentDetail(name) })}`,
450
+ });
398
451
  return;
399
452
  }
400
- setDefaultAgent(name);
401
- const claudeAgentStr = agentDef.claudeAgent ? ` · agent:${agentDef.claudeAgent}` : '';
402
- await adapter.postMessage(dest, { text: `${Icons.ok} ${t('cmd.agent.defaultSet', { name, detail: `${agentDef.profile}${claudeAgentStr}` })}` });
453
+ await adapter.postMessage(dest, { text: await switchChannelAgentReply(channel, args[0]) });
403
454
  return;
404
455
  }
405
- const text = buildAgentText();
456
+ const text = buildAgentText(channel);
406
457
  if (!router) {
407
458
  await adapter.postMessage(dest, { text });
408
459
  return;
@@ -410,7 +461,7 @@ export function createAgentHandler(router) {
410
461
  return {
411
462
  text,
412
463
  richBlocks: [{ type: 'section', text }],
413
- actions: buildAgentButtons(),
464
+ actions: buildAgentButtons(channel),
414
465
  };
415
466
  };
416
467
  }
@@ -1,4 +1,25 @@
1
1
  import type { PlatformAdapter } from '../../platform/adapter.js';
2
- import type { PlatformFileRef, DownloadedFile } from '../../platform/types.js';
3
- declare function downloadFiles(files: PlatformFileRef[] | undefined, adapter: PlatformAdapter, tempDir: string): Promise<DownloadedFile[]>;
2
+ import type { IncomingMessage, PlatformFileRef, DownloadedFile } from '../../platform/types.js';
3
+ export interface AttachmentFailure {
4
+ name: string;
5
+ reason: string;
6
+ }
7
+ export interface InboundFiles {
8
+ files: DownloadedFile[];
9
+ /** Attachments the platform would not hand over. Reported to the user and to the model rather
10
+ * than dropped: an answer written as if the picture had never been sent is worse than an
11
+ * answer that says the picture did not arrive. */
12
+ failures: AttachmentFailure[];
13
+ }
14
+ /**
15
+ * Download one message's attachments into that message's own directory under
16
+ * `workspace/attachments/`, then settle each one's real type and name (attachments-store).
17
+ *
18
+ * `key` identifies the inbound message (its platform message id); reusing it means a retried
19
+ * delivery reuses the directory instead of littering a new one.
20
+ */
21
+ declare function downloadFiles(files: PlatformFileRef[] | undefined, adapter: PlatformAdapter, key: string): Promise<InboundFiles>;
22
+ /** The inbound message's own attachment directory key: conduit + platform message id. Stable, so a
23
+ * redelivery of the same message reuses its directory instead of littering a new one. */
24
+ export declare function inboundAttachmentKey(message: IncomingMessage): string;
4
25
  export { downloadFiles };
@@ -1,17 +1,34 @@
1
1
  import { createLogger } from '../../core/log.js';
2
+ import { finalizeInboundFile, prepareInboundAttachmentDir } from '../attachments-store.js';
2
3
  const log = createLogger('file-handler');
3
- async function downloadFiles(files, adapter, tempDir) {
4
+ /**
5
+ * Download one message's attachments into that message's own directory under
6
+ * `workspace/attachments/`, then settle each one's real type and name (attachments-store).
7
+ *
8
+ * `key` identifies the inbound message (its platform message id); reusing it means a retried
9
+ * delivery reuses the directory instead of littering a new one.
10
+ */
11
+ async function downloadFiles(files, adapter, key) {
4
12
  if (!files?.length)
5
- return [];
13
+ return { files: [], failures: [] };
14
+ const dir = await prepareInboundAttachmentDir(key);
6
15
  const results = [];
16
+ const failures = [];
7
17
  for (const file of files) {
8
18
  try {
9
- results.push(await adapter.downloadFile(file, tempDir));
19
+ results.push(await finalizeInboundFile(await adapter.downloadFile(file, dir), dir));
10
20
  }
11
21
  catch (e) {
12
- log.error('Failed to download file:', file.name, e.message);
22
+ const reason = e.message;
23
+ log.error('Failed to download file:', file.name, reason);
24
+ failures.push({ name: file.name || file.id, reason });
13
25
  }
14
26
  }
15
- return results;
27
+ return { files: results, failures };
28
+ }
29
+ /** The inbound message's own attachment directory key: conduit + platform message id. Stable, so a
30
+ * redelivery of the same message reuses its directory instead of littering a new one. */
31
+ export function inboundAttachmentKey(message) {
32
+ return `${message.ref.conduit || 'unknown'}-${message.ref.messageId || 'nomsg'}`;
16
33
  }
17
34
  export { downloadFiles };