@cortex-agent/server 2026.9.14 → 2026.9.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (259) 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/hooks/{CORTEX.md → AGENTS.md} +1 -1
  6. package/defaults/hooks/{cortex-md-injector.mjs → agents-md-injector.mjs} +117 -26
  7. package/defaults/hooks/cortex-hook-api.mjs +2 -2
  8. package/defaults/hooks/new-session-hook.mjs +2 -2
  9. package/defaults/hooks/rules-loader.mjs +2 -2
  10. package/defaults/hooks/status-md-guard.mjs +8 -8
  11. package/defaults/hooks/task-status-check.mjs +18 -76
  12. package/defaults/hooks/tasks-yaml-guard.mjs +2 -2
  13. package/defaults/plugins/cortex-commission/.claude-plugin/plugin.json +2 -2
  14. package/defaults/plugins/cortex-commission/plugin.json +2 -2
  15. package/defaults/plugins/cortex-commission/skills/commission/SKILL.md +3 -3
  16. package/defaults/plugins/cortex-feishu/skills/feishu-doc/SKILL.md +1 -1
  17. package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +2 -2
  18. package/defaults/plugins/cortex-system/skills/project-init/SKILL.md +4 -4
  19. package/defaults/plugins/cortex-system/skills/task/SKILL.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 +0 -6
  25. package/dist/agent-adapter/claude/adapter.js +0 -8
  26. package/dist/agent-adapter/claude/defaults.d.ts +10 -7
  27. package/dist/agent-adapter/claude/defaults.js +18 -16
  28. package/dist/agent-adapter/claude/hooks-builder.js +2 -2
  29. package/dist/agent-adapter/claude/spawn-args.d.ts +0 -3
  30. package/dist/agent-adapter/claude/spawn-args.js +20 -16
  31. package/dist/agent-adapter/claude/turn-machine.d.ts +11 -0
  32. package/dist/agent-adapter/claude/turn-machine.js +46 -5
  33. package/dist/agent-adapter/normalize/prompt-builder.d.ts +16 -1
  34. package/dist/agent-adapter/normalize/prompt-builder.js +24 -6
  35. package/dist/agent-adapter/pi/mcp-bridge-logic.d.ts +11 -2
  36. package/dist/agent-adapter/pi/mcp-bridge-logic.js +32 -1
  37. package/dist/agent-adapter/pi/mcp-bridge.js +16 -15
  38. package/dist/agent-adapter/pi/session-options.d.ts +0 -6
  39. package/dist/agent-adapter/pi/session-options.js +1 -8
  40. package/dist/agent-adapter/types.d.ts +1 -1
  41. package/dist/core/mcp-tool-gate.d.ts +3 -17
  42. package/dist/core/mcp-tool-gate.js +4 -19
  43. package/dist/core/media-types.d.ts +10 -0
  44. package/dist/core/media-types.js +34 -0
  45. package/dist/core/platform-settings-spec.js +1 -1
  46. package/dist/core/settings-spec.d.ts +22 -1
  47. package/dist/core/settings-spec.js +33 -2
  48. package/dist/core/types/agent-types.d.ts +3 -1
  49. package/dist/core/utils.d.ts +1 -1
  50. package/dist/core/utils.js +1 -1
  51. package/dist/domain/agents/config.d.ts +1 -1
  52. package/dist/domain/agents/config.js +1 -1
  53. package/dist/domain/agents/profile-switch.d.ts +1 -1
  54. package/dist/domain/agents/profile-switch.js +3 -5
  55. package/dist/domain/agents/subagent/runner.js +0 -1
  56. package/dist/domain/commissions/commission-draft.d.ts +58 -0
  57. package/dist/domain/commissions/commission-draft.js +87 -4
  58. package/dist/domain/commissions/commission-finalize.d.ts +8 -3
  59. package/dist/domain/commissions/commission-finalize.js +14 -0
  60. package/dist/domain/executions/registry.d.ts +1 -2
  61. package/dist/domain/executions/registry.js +0 -3
  62. package/dist/domain/mcp/bundled-server.js +4 -3
  63. package/dist/domain/mcp/feishu/file.js +37 -18
  64. package/dist/domain/mcp/feishu/types.d.ts +3 -0
  65. package/dist/domain/mcp/feishu-server.js +1 -1
  66. package/dist/domain/mcp/tools/{cortex-md.d.ts → agents-md.d.ts} +6 -6
  67. package/dist/domain/mcp/tools/{cortex-md.js → agents-md.js} +6 -6
  68. package/dist/domain/mcp/tools/commission-tools.d.ts +12 -1
  69. package/dist/domain/mcp/tools/commission-tools.js +68 -14
  70. package/dist/domain/mcp/tools/remote-file.d.ts +20 -0
  71. package/dist/domain/mcp/tools/remote-file.js +44 -0
  72. package/dist/domain/mcp/tools/slack.d.ts +2 -0
  73. package/dist/domain/mcp/tools/slack.js +22 -7
  74. package/dist/domain/mcp/tools/task-ops.js +5 -13
  75. package/dist/domain/mcp/tools/ui-file.js +23 -10
  76. package/dist/domain/mcp/tools/waitpoint.d.ts +3 -0
  77. package/dist/domain/mcp/tools/waitpoint.js +122 -0
  78. package/dist/domain/memory/agents-md-injector.d.ts +24 -0
  79. package/dist/domain/memory/{cortex-md-injector.js → agents-md-injector.js} +10 -7
  80. package/dist/domain/projects/project-store.d.ts +1 -1
  81. package/dist/domain/projects/project-store.js +3 -3
  82. package/dist/domain/remote/client-hot-reload.js +3 -1
  83. package/dist/domain/remote/client-manager.js +105 -126
  84. package/dist/domain/remote/client-ssh-tunnel.d.ts +16 -5
  85. package/dist/domain/remote/client-ssh-tunnel.js +12 -5
  86. package/dist/domain/remote/cortex-client-config.d.ts +1 -1
  87. package/dist/domain/remote/cortex-client-config.js +1 -1
  88. package/dist/domain/remote/device-file.d.ts +51 -0
  89. package/dist/domain/remote/device-file.js +193 -0
  90. package/dist/domain/remote/device-port.js +3 -0
  91. package/dist/domain/remote/reverse-stream.d.ts +18 -7
  92. package/dist/domain/remote/reverse-stream.js +19 -6
  93. package/dist/domain/runs/builders.js +0 -1
  94. package/dist/domain/runs/compact.js +0 -1
  95. package/dist/domain/runs/engine-spec.d.ts +11 -4
  96. package/dist/domain/runs/engine-spec.js +7 -4
  97. package/dist/domain/runs/prompt.js +16 -10
  98. package/dist/domain/runs/request.d.ts +0 -1
  99. package/dist/domain/sessions/session-hooks.d.ts +5 -12
  100. package/dist/domain/sessions/session-hooks.js +6 -13
  101. package/dist/domain/sessions/session-lifecycle.d.ts +4 -4
  102. package/dist/domain/sessions/session-lifecycle.js +5 -6
  103. package/dist/domain/sessions/session-retention.d.ts +1 -3
  104. package/dist/domain/sessions/session-retention.js +9 -26
  105. package/dist/domain/sessions/session-use.d.ts +32 -0
  106. package/dist/domain/sessions/session-use.js +63 -0
  107. package/dist/domain/sessions/session.js +6 -5
  108. package/dist/domain/system/server-update-check.js +29 -1
  109. package/dist/domain/system/update-ui-state.d.ts +32 -0
  110. package/dist/domain/system/update-ui-state.js +63 -0
  111. package/dist/domain/tasks/claim-recovery.js +2 -2
  112. package/dist/domain/tasks/dispatch-utils.d.ts +10 -1
  113. package/dist/domain/tasks/dispatch-utils.js +46 -1
  114. package/dist/domain/tasks/dispatcher.js +4 -5
  115. package/dist/domain/tasks/mutator.d.ts +2 -2
  116. package/dist/domain/tasks/mutator.js +2 -2
  117. package/dist/domain/tasks/system/task-cli.js +2 -2
  118. package/dist/domain/tasks/system/task-state.js +1 -1
  119. package/dist/domain/threads/runner.js +3 -2
  120. package/dist/domain/ui-service/app-router.d.ts +54 -3
  121. package/dist/domain/ui-service/app-router.js +12 -14
  122. package/dist/domain/ui-service/input-schemas.d.ts +49 -5
  123. package/dist/domain/ui-service/input-schemas.js +35 -9
  124. package/dist/domain/ui-service/mutate/platform-settings.js +1 -1
  125. package/dist/domain/ui-service/mutate/sessions.d.ts +17 -1
  126. package/dist/domain/ui-service/mutate/sessions.js +83 -3
  127. package/dist/domain/ui-service/mutate/system.d.ts +3 -1
  128. package/dist/domain/ui-service/mutate/system.js +13 -0
  129. package/dist/domain/ui-service/mutate/waitpoints.d.ts +2 -0
  130. package/dist/domain/ui-service/mutate/waitpoints.js +20 -0
  131. package/dist/domain/ui-service/platform-settings.js +1 -1
  132. package/dist/domain/ui-service/plugins-shared.js +1 -1
  133. package/dist/domain/ui-service/query/config.js +1 -1
  134. package/dist/domain/ui-service/query/executions.js +0 -2
  135. package/dist/domain/ui-service/query/machine-detail.js +3 -8
  136. package/dist/domain/ui-service/query/memory.js +1 -1
  137. package/dist/domain/ui-service/query/sessions.js +7 -0
  138. package/dist/domain/ui-service/query/system.d.ts +2 -1
  139. package/dist/domain/ui-service/query/system.js +4 -0
  140. package/dist/domain/ui-service/query/threads.js +1 -54
  141. package/dist/domain/ui-service/query/waitpoints.d.ts +30 -0
  142. package/dist/domain/ui-service/query/waitpoints.js +117 -0
  143. package/dist/domain/ui-service/query-input-schemas.d.ts +3 -0
  144. package/dist/domain/ui-service/query-input-schemas.js +3 -0
  145. package/dist/domain/ui-service/trpc.js +1 -1
  146. package/dist/domain/ui-service/types.d.ts +175 -50
  147. package/dist/domain/ui-service/types.js +1 -1
  148. package/dist/domain/ui-service/ui-service.js +13 -33
  149. package/dist/domain/waitpoints/notices.d.ts +21 -0
  150. package/dist/domain/waitpoints/notices.js +115 -0
  151. package/dist/domain/waitpoints/service.d.ts +91 -0
  152. package/dist/domain/waitpoints/service.js +243 -0
  153. package/dist/entry/app.js +39 -29
  154. package/dist/entry/auth-login-cli.js +1 -1
  155. package/dist/entry/auth-login-terminal.js +1 -1
  156. package/dist/entry/init-auth.js +1 -1
  157. package/dist/entry/init.js +6 -6
  158. package/dist/entry/signal-cli.d.ts +30 -0
  159. package/dist/entry/signal-cli.js +207 -0
  160. package/dist/entry/start-ui-http.d.ts +1 -1
  161. package/dist/entry/start-ui-http.js +5 -3
  162. package/dist/events/event-types.d.ts +5 -7
  163. package/dist/hooks/{cortex-md-injector.mjs → agents-md-injector.mjs} +117 -26
  164. package/dist/hooks/cortex-hook-api.mjs +2 -2
  165. package/dist/hooks/new-session-hook.mjs +2 -2
  166. package/dist/hooks/rules-loader.mjs +2 -2
  167. package/dist/hooks/status-md-guard.mjs +8 -8
  168. package/dist/hooks/task-status-check.mjs +18 -76
  169. package/dist/hooks/tasks-yaml-guard.mjs +2 -2
  170. package/dist/orchestration/agent-file-send.d.ts +9 -0
  171. package/dist/orchestration/agent-file-send.js +21 -2
  172. package/dist/orchestration/agent-runner.d.ts +4 -3
  173. package/dist/orchestration/agent-runner.js +25 -23
  174. package/dist/orchestration/attachments-store.d.ts +31 -0
  175. package/dist/orchestration/attachments-store.js +184 -0
  176. package/dist/orchestration/conversation-request.d.ts +30 -8
  177. package/dist/orchestration/conversation-request.js +62 -26
  178. package/dist/orchestration/edit-retry.js +2 -1
  179. package/dist/orchestration/interactions/ask-user-resume.js +2 -1
  180. package/dist/orchestration/interactions/plan-approvals.js +1 -1
  181. package/dist/orchestration/interactions/ui-update-prompt.d.ts +8 -0
  182. package/dist/orchestration/interactions/ui-update-prompt.js +47 -0
  183. package/dist/orchestration/outputs-store.d.ts +11 -0
  184. package/dist/orchestration/outputs-store.js +32 -6
  185. package/dist/orchestration/resume-dispatcher.js +2 -2
  186. package/dist/orchestration/routing/file-handler.d.ts +23 -2
  187. package/dist/orchestration/routing/file-handler.js +22 -5
  188. package/dist/orchestration/routing/webhook.js +240 -39
  189. package/dist/orchestration/session-compact.d.ts +3 -0
  190. package/dist/orchestration/session-compact.js +3 -2
  191. package/dist/orchestration/session-events.d.ts +6 -0
  192. package/dist/orchestration/session-events.js +5 -0
  193. package/dist/orchestration/session-gateway.d.ts +1 -1
  194. package/dist/orchestration/session-gateway.js +1 -0
  195. package/dist/orchestration/thread-executor.d.ts +2 -0
  196. package/dist/orchestration/thread-executor.js +11 -1
  197. package/dist/orchestration/thread-input.d.ts +3 -2
  198. package/dist/orchestration/thread-input.js +8 -9
  199. package/dist/orchestration/turn/turn-prep.d.ts +15 -1
  200. package/dist/orchestration/turn/turn-prep.js +21 -9
  201. package/dist/orchestration/waitpoint-ingress.d.ts +41 -0
  202. package/dist/orchestration/waitpoint-ingress.js +172 -0
  203. package/dist/orchestration/waitpoint-notifier.d.ts +21 -0
  204. package/dist/orchestration/waitpoint-notifier.js +119 -0
  205. package/dist/orchestration/waitpoint-remote-drain.d.ts +20 -0
  206. package/dist/orchestration/waitpoint-remote-drain.js +147 -0
  207. package/dist/orchestration/waitpoint-sweep.d.ts +42 -0
  208. package/dist/orchestration/waitpoint-sweep.js +87 -0
  209. package/dist/platform/adapters/feishu-image.d.ts +19 -0
  210. package/dist/platform/adapters/feishu-image.js +71 -0
  211. package/dist/platform/adapters/feishu.d.ts +2 -0
  212. package/dist/platform/adapters/feishu.js +26 -16
  213. package/dist/platform/ui-http/app-update.d.ts +11 -0
  214. package/dist/platform/ui-http/app-update.js +3 -0
  215. package/dist/platform/ui-http/listening-ports.d.ts +1 -1
  216. package/dist/platform/ui-http/listening-ports.js +1 -1
  217. package/dist/platform/ui-http/ui-session.js +1 -1
  218. package/dist/store/conversation-ledger-repo.d.ts +10 -19
  219. package/dist/store/conversation-ledger-repo.js +143 -152
  220. package/dist/store/execution-repo.d.ts +1 -19
  221. package/dist/store/execution-repo.js +1 -18
  222. package/dist/store/project-notes-repo.js +11 -2
  223. package/dist/store/prompt-migration-replacements.js +1 -1
  224. package/dist/store/session-registry-import.d.ts +34 -0
  225. package/dist/store/session-registry-import.js +182 -0
  226. package/dist/store/session-registry-journal.d.ts +107 -0
  227. package/dist/store/session-registry-journal.js +308 -19
  228. package/dist/store/session-registry-repo.d.ts +113 -28
  229. package/dist/store/session-registry-repo.js +288 -105
  230. package/dist/store/version-migrations.d.ts +29 -3
  231. package/dist/store/version-migrations.js +288 -24
  232. package/dist/store/waitpoint-repo.d.ts +108 -0
  233. package/dist/store/waitpoint-repo.js +94 -0
  234. package/package.json +2 -2
  235. package/web/dist/assets/index-CwwQNMpP.css +1 -0
  236. package/web/dist/assets/index-DLSfgq3o.js +444 -0
  237. package/web/dist/assets/{index-aHbOZSP6.js → index-DZTuqUO4.js} +1 -1
  238. package/web/dist/index.html +2 -2
  239. package/defaults/config/hooks/08-cortex-md-injector-post-tool.json +0 -10
  240. package/dist/domain/executions/log-tailer.d.ts +0 -71
  241. package/dist/domain/executions/log-tailer.js +0 -194
  242. package/dist/domain/memory/cortex-md-injector.d.ts +0 -24
  243. package/dist/domain/memory/cortex-md-scanner.d.ts +0 -10
  244. package/dist/domain/memory/cortex-md-scanner.js +0 -66
  245. package/dist/domain/remote/cortex-client.d.ts +0 -1
  246. package/dist/domain/remote/cortex-client.js +0 -662
  247. package/dist/domain/tasks/system/cortex-run.d.ts +0 -25
  248. package/dist/domain/tasks/system/cortex-run.js +0 -360
  249. package/dist/store/session-repo.d.ts +0 -65
  250. package/dist/store/session-repo.js +0 -184
  251. package/web/dist/assets/index-BuXbCsuz.js +0 -444
  252. package/web/dist/assets/index-CCPxQ94C.css +0 -1
  253. /package/defaults/{CORTEX.md → AGENTS.md} +0 -0
  254. /package/defaults/config/{CORTEX.md → AGENTS.md} +0 -0
  255. /package/defaults/context/{CORTEX.md → AGENTS.md} +0 -0
  256. /package/defaults/context/ideas/{CORTEX.md → AGENTS.md} +0 -0
  257. /package/defaults/context/projects/{CORTEX.md → AGENTS.md} +0 -0
  258. /package/defaults/context/scans/{CORTEX.md → AGENTS.md} +0 -0
  259. /package/defaults/context/user/{CORTEX.md → AGENTS.md} +0 -0
@@ -7,11 +7,16 @@ import * as crypto from 'crypto';
7
7
  import { readFileSync } from 'fs';
8
8
  import { taskMutator } from '../../domain/tasks/mutator.js';
9
9
  import { sendCommand, isDeviceOnline, getOnlineDevices } from '../../domain/remote/client-manager.js';
10
- import { registerDispatchExecution } from '../../domain/executions/registry.js';
10
+ import { stageRemoteFile } from '../../domain/remote/device-file.js';
11
+ import { createWaitpoint, cancelWaitpoint, listWaitpointsForSession, publicView } from '../../domain/waitpoints/service.js';
12
+ import { ingestSignal, toSignalInput } from '../waitpoint-ingress.js';
13
+ import { waitpointRepo } from '../../store/waitpoint-repo.js';
11
14
  import { registerAskQuestion, registerPlanApproval } from './hook-bridge.js';
12
15
  import { normalizeAskLevel } from '../../platform/index.js';
13
16
  import { sessionStore } from '../../store/session-registry-repo.js';
14
17
  import { validateCommissionFinalize, finalizeCommission } from '../../domain/commissions/commission-finalize.js';
18
+ import { enterCommissionDraft } from '../../domain/commissions/commission-draft.js';
19
+ import { publishSessionCommission } from '../session-events.js';
15
20
  import { getCurrentPlanFilePath } from '../../agent-adapter/claude/event-parser.js';
16
21
  import { orchestrationAdapter, orchestrationBus } from '../runtime.js';
17
22
  import { createThread, cancelThread, readArtifact, listTemplates, listAgents, checkSpawnGuards, getRootThreadId, registerChildSpawn, buildThreadTree, getTreeThreads, buildContractPrompt, buildMissionChain, isArtifactUnchangedSinceStepStart } from '../../domain/threads/index.js';
@@ -42,36 +47,6 @@ function verifySignature(body, signature) {
42
47
  return false;
43
48
  }
44
49
  }
45
- /**
46
- * B2-C: a task-linked `cortex-run --name X` writes `<DATA_DIR>/tmp/cortex-run/X/output.log` on the
47
- * target device but, being a separate CLI process, cannot register an execution into the daemon's
48
- * in-memory registry. This is the daemon-side seam: on a successful launch, register (idempotent,
49
- * keyed by taskId) a `dispatch` execution carrying `runName` + `machine` so the Web UI can resolve
50
- * the run's live log by executionId (subscribeExecutionLog → resolveExecutionLogLocation). Requires
51
- * a taskId (the record key); a run without `--task-id` is not tailable through the UI. Best-effort —
52
- * never blocks or fails the launch response.
53
- */
54
- function maybeRegisterCortexRunExecution(action, params, device) {
55
- if (action !== 'cortex-run.launch')
56
- return;
57
- const name = params?.name;
58
- const taskId = params?.taskId;
59
- const taskProject = params?.taskProject;
60
- if (!name || !taskId)
61
- return;
62
- try {
63
- registerDispatchExecution({
64
- taskId,
65
- machine: device,
66
- project: taskProject || undefined,
67
- runName: name,
68
- });
69
- log.info(`B2-C: registered dispatch execution for cortex-run "${name}" (task ${taskId} on ${device})`);
70
- }
71
- catch (e) {
72
- log.warn(`B2-C: failed to register cortex-run execution for "${name}": ${e.message}`);
73
- }
74
- }
75
50
  /**
76
51
  * Bearer-token gate for every webhook route EXCEPT /webhook/github (which authenticates
77
52
  * via its own HMAC signature). Reads the call-time CORTEX_WEBHOOK_TOKEN and compares it
@@ -83,10 +58,44 @@ function isWebhookAuthorized(req) {
83
58
  const headerVal = Array.isArray(provided) ? provided[0] : provided;
84
59
  return timingSafeEqualStr(getWebhookToken(), headerVal);
85
60
  }
86
- function readJsonBody(req, callback) {
61
+ /**
62
+ * Read and parse a JSON body.
63
+ *
64
+ * `maxBytes` is opt-in so existing trusted callers keep their behaviour, but any route reachable
65
+ * without the bearer token must pass one — otherwise the concatenation below is an unbounded
66
+ * allocation driven by an unauthenticated caller. Over the cap the request is destroyed and the
67
+ * callback fires with a `tooLarge` error.
68
+ */
69
+ /**
70
+ * Routes that do NOT take the shared bearer token, because each carries a narrower credential of
71
+ * its own. Deliberately a Set of exact paths: handing `CORTEX_WEBHOOK_TOKEN` to a training script
72
+ * would give it `remote-command` on every device, which is why the signal route authenticates with
73
+ * a capability scoped to one waitpoint instead.
74
+ */
75
+ const TOKEN_EXEMPT_ROUTES = new Set(['/webhook/github', '/webhook/signal']);
76
+ /** Ceiling on an unauthenticated signal body. A signal is a summary, not a log. */
77
+ const SIGNAL_BODY_MAX_BYTES = 64 * 1024;
78
+ function readJsonBody(req, callback, maxBytes = 0) {
87
79
  let body = '';
88
- req.on('data', (chunk) => { body += chunk; });
80
+ let size = 0;
81
+ let aborted = false;
82
+ req.on('data', (chunk) => {
83
+ if (aborted)
84
+ return;
85
+ size += chunk.length;
86
+ if (maxBytes > 0 && size > maxBytes) {
87
+ aborted = true;
88
+ const error = new Error(`body exceeds ${maxBytes} bytes`);
89
+ error.tooLarge = true;
90
+ req.destroy();
91
+ callback(error);
92
+ return;
93
+ }
94
+ body += chunk;
95
+ });
89
96
  req.on('end', () => {
97
+ if (aborted)
98
+ return;
90
99
  try {
91
100
  callback(null, body, JSON.parse(body));
92
101
  }
@@ -157,9 +166,11 @@ function createWebhookHandler(_options = {}) {
157
166
  res.end('Forbidden');
158
167
  return;
159
168
  }
160
- // --- Auth gate: every route requires the webhook bearer token, except /webhook/github
161
- // which authenticates via its own HMAC signature (GitHub cannot send our header). ---
162
- if (req.url !== '/webhook/github' && !isWebhookAuthorized(req)) {
169
+ // --- Auth gate: every route requires the webhook bearer token, except the two that carry
170
+ // their own credential — /webhook/github (HMAC; GitHub cannot send our header) and
171
+ // /webhook/signal (a per-waitpoint capability in the body, checked inside the handler).
172
+ // Exact string match only: a prefix test here would open every future /webhook/signal*. ---
173
+ if (!TOKEN_EXEMPT_ROUTES.has(req.url) && !isWebhookAuthorized(req)) {
163
174
  log.warn(`webhook auth rejected: ${req.method} ${req.url}`);
164
175
  res.writeHead(401);
165
176
  res.end('Unauthorized');
@@ -194,7 +205,6 @@ function createWebhookHandler(_options = {}) {
194
205
  }
195
206
  try {
196
207
  const result = await sendCommand(device, { action, params: params || {}, timeout });
197
- maybeRegisterCortexRunExecution(action, params, device);
198
208
  res.writeHead(200, { 'Content-Type': 'application/json' });
199
209
  res.end(JSON.stringify({ success: true, data: result }));
200
210
  }
@@ -205,6 +215,36 @@ function createWebhookHandler(_options = {}) {
205
215
  });
206
216
  return;
207
217
  }
218
+ // --- Remote file staging (from MCP sidecar → client-manager reverse channel) ---
219
+ // For senders that upload from a local path themselves (Slack, Feishu): stream the device's
220
+ // file into a server-local staging area and hand back the path. The Web `send_file` does NOT
221
+ // come through here — it passes `device` to /webhook/ui-file and the daemon streams straight
222
+ // into the session's outputs, saving a full copy of every transfer.
223
+ if (req.method === 'POST' && req.url === '/webhook/remote-fetch') {
224
+ readJsonBody(req, async (error, _body, data) => {
225
+ if (error) {
226
+ res.writeHead(400);
227
+ res.end('Bad JSON');
228
+ return;
229
+ }
230
+ const { device, filePath, maxBytes } = data || {};
231
+ if (!device || !filePath) {
232
+ res.writeHead(400, { 'Content-Type': 'application/json' });
233
+ res.end(JSON.stringify({ success: false, error: 'device and filePath required' }));
234
+ return;
235
+ }
236
+ try {
237
+ const staged = await stageRemoteFile({ device, filePath, maxBytes });
238
+ res.writeHead(200, { 'Content-Type': 'application/json' });
239
+ res.end(JSON.stringify({ success: true, data: staged }));
240
+ }
241
+ catch (e) {
242
+ res.writeHead(200, { 'Content-Type': 'application/json' });
243
+ res.end(JSON.stringify({ success: false, error: e.message }));
244
+ }
245
+ });
246
+ return;
247
+ }
208
248
  // --- Remote task operation (from MCP sidecar on branch bases) ---
209
249
  if (req.method === 'POST' && req.url === '/webhook/task-op') {
210
250
  readJsonBody(req, async (error, _body, data) => {
@@ -245,14 +285,14 @@ function createWebhookHandler(_options = {}) {
245
285
  res.end('Bad JSON');
246
286
  return;
247
287
  }
248
- const { sessionId, filePath, fileName, caption } = data || {};
288
+ const { sessionId, filePath, fileName, caption, device } = data || {};
249
289
  if (!sessionId || !filePath) {
250
290
  res.writeHead(400, { 'Content-Type': 'application/json' });
251
291
  res.end(JSON.stringify({ success: false, error: 'sessionId and filePath required' }));
252
292
  return;
253
293
  }
254
294
  try {
255
- const meta = await sendAgentFile({ sessionId, filePath, fileName, caption });
295
+ const meta = await sendAgentFile({ sessionId, filePath, fileName, caption, device });
256
296
  res.writeHead(200, { 'Content-Type': 'application/json' });
257
297
  res.end(JSON.stringify({ success: true, data: meta }));
258
298
  }
@@ -653,6 +693,51 @@ function createWebhookHandler(_options = {}) {
653
693
  });
654
694
  return;
655
695
  }
696
+ // --- MCP tool: cortex_commission_start ---
697
+ //
698
+ // The tool runs in the bundled MCP process and cannot touch the registry, so entering the mode
699
+ // is a loopback call like every other state change an agent makes. Idempotent: a second call
700
+ // returns the same directory, which is what lets the [Commission] block say "call it if you
701
+ // have not already" without worrying about which entry the session came through.
702
+ if (req.method === 'POST' && req.url === '/hook/commission-start') {
703
+ readJsonBody(req, async (error, _body, data) => {
704
+ if (error) {
705
+ res.writeHead(400);
706
+ res.end('Bad JSON');
707
+ return;
708
+ }
709
+ const reply = (status, payload) => {
710
+ res.writeHead(status, { 'Content-Type': 'application/json' });
711
+ res.end(JSON.stringify(payload));
712
+ };
713
+ const sessionId = typeof data?.sessionId === 'string' ? data.sessionId : '';
714
+ if (!sessionId) {
715
+ reply(200, { error: 'no originating session id — commission start requires CORTEX_SESSION_ID' });
716
+ return;
717
+ }
718
+ // The kill switch has to bite HERE too: since v4 this tool is the entry point, not a
719
+ // capability handed only to sessions the user already opted in.
720
+ if (!getSettings().commissionEnabled) {
721
+ reply(200, { error: 'commission mode is disabled on this server (settings.commissionEnabled)' });
722
+ return;
723
+ }
724
+ try {
725
+ const result = await enterCommissionDraft(sessionId);
726
+ if (result.ok === false) {
727
+ reply(200, { error: result.error });
728
+ return;
729
+ }
730
+ if (!result.alreadyDrafting && typeof data?.channel === 'string' && data.channel) {
731
+ publishSessionCommission({ sessionId, channel: data.channel });
732
+ }
733
+ reply(200, { ok: true, dir: result.dir, draftDir: result.draftDir, alreadyDrafting: result.alreadyDrafting });
734
+ }
735
+ catch (e) {
736
+ reply(500, { error: e.message });
737
+ }
738
+ });
739
+ return;
740
+ }
656
741
  // --- PreToolUse hook: ExitPlanMode ---
657
742
  if (req.method === 'POST' && req.url === '/hook/exit-plan-mode') {
658
743
  readJsonBody(req, async (error, _body, data) => {
@@ -710,6 +795,122 @@ function createWebhookHandler(_options = {}) {
710
795
  });
711
796
  return;
712
797
  }
798
+ // --- /webhook/signal (an external process reporting that what an agent waited for is done) ---
799
+ // The only unauthenticated-by-bearer-token POST. Its credential is the per-waitpoint secret
800
+ // in the body, so a training script can be handed a capability that resolves exactly one
801
+ // waitpoint and can do nothing else.
802
+ if (req.method === 'POST' && req.url === '/webhook/signal') {
803
+ readJsonBody(req, async (error, _body, data) => {
804
+ if (error) {
805
+ if (error.tooLarge) {
806
+ res.writeHead(413, { 'Content-Type': 'application/json' });
807
+ res.end(JSON.stringify({ accepted: false, error: 'signal body too large' }));
808
+ return;
809
+ }
810
+ res.writeHead(400);
811
+ res.end('Bad JSON');
812
+ return;
813
+ }
814
+ try {
815
+ const outcome = await ingestSignal(toSignalInput(data || {}, null, 'http'));
816
+ switch (outcome.kind) {
817
+ case 'accepted':
818
+ res.writeHead(202, { 'Content-Type': 'application/json' });
819
+ res.end(JSON.stringify({ accepted: true, fired: outcome.fired, state: outcome.waitpoint.state }));
820
+ return;
821
+ case 'duplicate':
822
+ res.writeHead(202, { 'Content-Type': 'application/json' });
823
+ res.end(JSON.stringify({ accepted: true, duplicate: true, state: outcome.waitpoint.state }));
824
+ return;
825
+ case 'already-resolved':
826
+ // 410, not 404: the caller asked about something that really existed, and echoing the
827
+ // original resolution lets a script log "already reported" instead of retrying forever.
828
+ res.writeHead(410, { 'Content-Type': 'application/json' });
829
+ res.end(JSON.stringify({ accepted: false, state: outcome.state, resolved_at: outcome.resolvedAt }));
830
+ return;
831
+ case 'bad-secret':
832
+ res.writeHead(401, { 'Content-Type': 'application/json' });
833
+ res.end(JSON.stringify({ accepted: false, error: 'bad secret' }));
834
+ return;
835
+ case 'rate-limited':
836
+ res.writeHead(429, { 'Content-Type': 'application/json' });
837
+ res.end(JSON.stringify({ accepted: false, error: 'too many signals' }));
838
+ return;
839
+ default:
840
+ res.writeHead(404, { 'Content-Type': 'application/json' });
841
+ res.end(JSON.stringify({ accepted: false, error: 'unknown waitpoint' }));
842
+ return;
843
+ }
844
+ }
845
+ catch (e) {
846
+ res.writeHead(500, { 'Content-Type': 'application/json' });
847
+ res.end(JSON.stringify({ accepted: false, error: e.message }));
848
+ }
849
+ }, SIGNAL_BODY_MAX_BYTES);
850
+ return;
851
+ }
852
+ // --- /webhook/waitpoint (agent-side ops behind the normal bearer token) ---
853
+ if (req.method === 'POST' && req.url === '/webhook/waitpoint') {
854
+ readJsonBody(req, async (error, _body, data) => {
855
+ if (error) {
856
+ res.writeHead(400);
857
+ res.end('Bad JSON');
858
+ return;
859
+ }
860
+ const reply = (payload) => {
861
+ res.writeHead(200, { 'Content-Type': 'application/json' });
862
+ res.end(JSON.stringify(payload));
863
+ };
864
+ try {
865
+ const action = data?.action;
866
+ if (action === 'create') {
867
+ const channel = data.channel || await resolveSessionChannel(data.sessionId);
868
+ if (!channel)
869
+ return reply({ success: false, error: 'cannot resolve a channel for this session' });
870
+ if (!data.label || !data.intent)
871
+ return reply({ success: false, error: 'label and intent are required' });
872
+ const { waitpoint, secret } = await createWaitpoint({
873
+ label: String(data.label),
874
+ intent: String(data.intent),
875
+ owner: {
876
+ sessionId: String(data.sessionId || ''),
877
+ channel,
878
+ threadId: data.threadId || null,
879
+ project: data.project || null,
880
+ },
881
+ quorum: data.quorum,
882
+ failFast: data.failFast,
883
+ maxSignals: data.maxSignals,
884
+ coalesceMs: data.coalesceMs,
885
+ ttlMs: data.ttlMs,
886
+ emitFrom: data.device ? { kind: 'device', device: String(data.device) } : { kind: 'local' },
887
+ });
888
+ return reply({ success: true, data: { ...publicView(waitpoint), secret } });
889
+ }
890
+ if (action === 'check') {
891
+ if (data.id) {
892
+ const wp = await waitpointRepo.get(String(data.id));
893
+ if (!wp)
894
+ return reply({ success: false, error: `unknown waitpoint: ${data.id}` });
895
+ return reply({ success: true, data: publicView(wp) });
896
+ }
897
+ const mine = await listWaitpointsForSession(String(data.sessionId || ''));
898
+ return reply({ success: true, data: { waitpoints: mine.map(publicView) } });
899
+ }
900
+ if (action === 'cancel') {
901
+ if (!data.id)
902
+ return reply({ success: false, error: 'id is required' });
903
+ const result = await cancelWaitpoint(String(data.id));
904
+ return reply({ success: true, data: result });
905
+ }
906
+ return reply({ success: false, error: `unknown action: ${action}` });
907
+ }
908
+ catch (e) {
909
+ reply({ success: false, error: e.message });
910
+ }
911
+ });
912
+ return;
913
+ }
713
914
  if (req.method !== 'POST' || req.url !== '/webhook/github') {
714
915
  res.writeHead(404);
715
916
  res.end('Not found');
@@ -27,6 +27,9 @@ export interface CompactSessionDeps {
27
27
  sessions: {
28
28
  getById(sessionId: string): Promise<CompactSessionRecord | null>;
29
29
  updateContextUsage(sessionId: string, usage: SessionContextUsage | null): Promise<void>;
30
+ /** Compaction removes the already-delivered [Commission] block from backend history, so the
31
+ * delivery marker has to go with it or the block is never seen again (DR-0037 v4). */
32
+ clearCommissionBlockDelivery(sessionId: string): Promise<unknown>;
30
33
  };
31
34
  /** The registry's one answer to "may a command touch this session's pooled engine": see
32
35
  * `core/session-state.ts`'s `channelEngineBusy`. */
@@ -1,5 +1,5 @@
1
1
  import { channelEngineBusy } from '../core/session-state.js';
2
- import { sessionRepo } from '../store/session-repo.js';
2
+ import { getSessionAsync } from '../domain/sessions/session.js';
3
3
  import { effectiveBackendSessionId, sessionStore, } from '../store/session-registry-repo.js';
4
4
  import { compactAgentContext, isSessionCompactionSupported, } from '../domain/runs/compact.js';
5
5
  import { resolveBackendForChannel } from '../domain/agents/config.js';
@@ -39,6 +39,7 @@ async function applyCompactResult(session, result, deps) {
39
39
  ? { ...result.contextUsage, updatedAt: deps.now() }
40
40
  : null;
41
41
  await deps.sessions.updateContextUsage(session.sessionId, contextUsage);
42
+ await deps.sessions.clearCommissionBlockDelivery(session.sessionId);
42
43
  deps.publish({
43
44
  sessionId: session.sessionId,
44
45
  channel: session.channel,
@@ -49,7 +50,7 @@ async function applyCompactResult(session, result, deps) {
49
50
  }
50
51
  export async function compactActiveSessionContext(opts) {
51
52
  const backend = resolveBackendForChannel(opts.channel);
52
- const sessionId = await sessionRepo.getSessionAsync(opts.channel);
53
+ const sessionId = await getSessionAsync(opts.channel);
53
54
  if (!sessionId)
54
55
  return { ok: false, reason: 'no-session' };
55
56
  return compactSessionContext(sessionId);
@@ -135,6 +135,12 @@ export declare function publishSessionRewound(p: {
135
135
  * the model. The web hold (turn/background-hold.ts) keeps `running:true, backgroundRunning:true` for the
136
136
  * whole wait so the session is NOT prematurely marked idle, then publishes `running:false` once the
137
137
  * background work finishes. Omitted (undefined) on the normal turn-start / turn-end edges. */
138
+ /** The session's commission binding moved (entered drafting, left it) without any commission
139
+ * record changing, so `commission.updated` would have nothing to name. */
140
+ export declare function publishSessionCommission(p: {
141
+ sessionId: string;
142
+ channel: string;
143
+ }): void;
138
144
  export declare function publishSessionStatus(p: {
139
145
  sessionId: string;
140
146
  channel: string;
@@ -113,6 +113,11 @@ export function publishSessionRewound(p) {
113
113
  * the model. The web hold (turn/background-hold.ts) keeps `running:true, backgroundRunning:true` for the
114
114
  * whole wait so the session is NOT prematurely marked idle, then publishes `running:false` once the
115
115
  * background work finishes. Omitted (undefined) on the normal turn-start / turn-end edges. */
116
+ /** The session's commission binding moved (entered drafting, left it) without any commission
117
+ * record changing, so `commission.updated` would have nothing to name. */
118
+ export function publishSessionCommission(p) {
119
+ orchestrationBus()?.publish({ type: 'session.commission', sessionId: p.sessionId, channel: p.channel });
120
+ }
116
121
  export function publishSessionStatus(p) {
117
122
  orchestrationBus()?.publish({
118
123
  type: 'session.status',
@@ -9,7 +9,7 @@ export declare const WEB_UI_SENDER = "cortex-web-ui";
9
9
  * Why a turn is being delivered. Each origin fixes the sender id, the systemOrigin tag, the
10
10
  * messageId prefix and `raw.source` — see `ORIGINS`.
11
11
  */
12
- export type DeliveryOrigin = 'web-user' | 'agent-result' | 'ask-user-answer' | 'resume' | 'thread-callback' | 'task-callback' | 'subtask-question';
12
+ export type DeliveryOrigin = 'web-user' | 'agent-result' | 'ask-user-answer' | 'resume' | 'thread-callback' | 'task-callback' | 'subtask-question' | 'external-signal';
13
13
  export interface DeliverToSessionOptions {
14
14
  channel: string;
15
15
  text: string;
@@ -25,6 +25,7 @@ const ORIGINS = {
25
25
  'thread-callback': { senderId: SYNTHETIC_CALLBACK_SENDER, prefix: 'cb', rawSource: 'task-callback', systemOrigin: 'thread-callback' },
26
26
  'task-callback': { senderId: SYNTHETIC_CALLBACK_SENDER, prefix: 'cb', rawSource: 'task-callback', systemOrigin: 'task-callback' },
27
27
  'subtask-question': { senderId: SYNTHETIC_CALLBACK_SENDER, prefix: 'cb', rawSource: 'task-callback', systemOrigin: 'subtask-question' },
28
+ 'external-signal': { senderId: SYNTHETIC_CALLBACK_SENDER, prefix: 'cb', rawSource: 'external-signal', systemOrigin: 'external-signal' },
28
29
  };
29
30
  /** The one place a synthetic `IncomingMessage` is built. */
30
31
  export function buildDeliveryMessage(opts) {
@@ -19,5 +19,7 @@ export declare class ThreadExecutor {
19
19
  * The catch covers the VALIDATION phase only: once `openThreadRun` is entered, the failure /
20
20
  * cancellation rendering (onto the live status message, with the elapsed clock) belongs to it. */
21
21
  private _executeReal;
22
+ /** Tell the channel which attachments did not make it into the thread. */
23
+ private _reportFailedDownloads;
22
24
  }
23
25
  export declare const threadExecutor: ThreadExecutor;
@@ -54,7 +54,12 @@ export class ThreadExecutor {
54
54
  * cancellation rendering (onto the live status message, with the elapsed clock) belongs to it. */
55
55
  async _executeReal(ctx) {
56
56
  const startTime = Date.now();
57
- const downloadedFiles = await downloadFiles(ctx.message.files, ctx.hasFiles, ctx.adapter);
57
+ // A thread's first step takes the files. An attachment that would not download cannot be named
58
+ // in the step prompt (the template composes it), so the user is told in the channel instead —
59
+ // the one thing that must not happen is the whole thing passing in silence.
60
+ const { files: downloadedFiles, failures } = await downloadFiles(ctx.message, ctx.hasFiles, ctx.adapter);
61
+ if (failures.length > 0)
62
+ await this._reportFailedDownloads(ctx, failures);
58
63
  const args = { channel: ctx.channel, adapter: ctx.adapter, threadAnchorId: ctx.threadAnchorId, startTime, downloadedFiles };
59
64
  try {
60
65
  if (ctx.threadAddMatch) {
@@ -75,6 +80,11 @@ export class ThreadExecutor {
75
80
  await ctx.adapter.postMessage({ type: 'interactive-reply', conduit: ctx.channel, sessionId: '' }, { text }, ctx.threadAnchorId ? { threadId: ctx.threadAnchorId } : undefined).catch(() => { });
76
81
  }
77
82
  }
83
+ /** Tell the channel which attachments did not make it into the thread. */
84
+ async _reportFailedDownloads(ctx, failures) {
85
+ const list = failures.map((f) => `• ${f.name} — ${f.reason}`).join('\n');
86
+ await ctx.adapter.postMessage({ type: 'interactive-reply', conduit: ctx.channel, sessionId: '' }, { text: `${Icons.warning} Could not download ${failures.length} attachment(s); the thread runs without them:\n${list}` }, ctx.threadAnchorId ? { threadId: ctx.threadAnchorId } : undefined).catch(() => { });
87
+ }
78
88
  }
79
89
  export const threadExecutor = new ThreadExecutor();
80
90
  /** The shared half of all three ThreadRunInputs: an interactive surface, with buttons, that
@@ -1,4 +1,5 @@
1
- import type { PlatformAdapter, DownloadedFile, IncomingMessage, PlatformFileRef } from '../platform/index.js';
1
+ import type { PlatformAdapter, IncomingMessage } from '../platform/index.js';
2
+ import { type InboundFiles } from './routing/file-handler.js';
2
3
  export interface ThreadExecCtx {
3
4
  message: IncomingMessage;
4
5
  channel: string;
@@ -11,6 +12,6 @@ export interface ThreadExecCtx {
11
12
  existingThread: any;
12
13
  isActiveThread: boolean;
13
14
  }
14
- export declare function downloadFiles(files: PlatformFileRef[] | undefined, hasFiles: boolean, adapter: PlatformAdapter): Promise<DownloadedFile[]>;
15
+ export declare function downloadFiles(message: IncomingMessage, hasFiles: boolean, adapter: PlatformAdapter): Promise<InboundFiles>;
15
16
  /** Buffer user text plus downloaded files for the next thread step. */
16
17
  export declare function bufferUserMessage(ctx: ThreadExecCtx): Promise<void>;
@@ -7,18 +7,16 @@ import { randomUUID } from 'node:crypto';
7
7
  import { createLogger } from '../core/log.js';
8
8
  import { Icons } from '../core/icons.js';
9
9
  import { evictPendingUserInput, registerPendingUserInput } from '../domain/threads/pending-user-inputs.js';
10
- import { downloadFiles as downloadPlatformFiles } from './routing/file-handler.js';
10
+ import { downloadFiles as downloadPlatformFiles, inboundAttachmentKey, } from './routing/file-handler.js';
11
11
  import { threadStore } from '../store/thread-repo.js';
12
- import { WORKSPACE_DIR } from '../core/utils.js';
13
12
  import { buildPrompt as buildAgentPrompt } from '../agent-adapter/normalize/prompt-builder.js';
14
- const TEMP_DIR = WORKSPACE_DIR;
15
13
  // Same tag as thread-executor's logger on purpose: these lines used to be emitted from there.
16
14
  const log = createLogger('thread-executor');
17
15
  // --- Shared helper ---
18
- export async function downloadFiles(files, hasFiles, adapter) {
19
- if (!hasFiles || !files)
20
- return [];
21
- return downloadPlatformFiles(files, adapter, TEMP_DIR);
16
+ export async function downloadFiles(message, hasFiles, adapter) {
17
+ if (!hasFiles || !message.files)
18
+ return { files: [], failures: [] };
19
+ return downloadPlatformFiles(message.files, adapter, inboundAttachmentKey(message));
22
20
  }
23
21
  // --- Message buffering (Phase 6) ---
24
22
  /** Reserve user input synchronously so the runner sees it before the current step exits. */
@@ -33,7 +31,7 @@ function reserveUserInput(thread, text) {
33
31
  return { inputId, evictedInputId };
34
32
  }
35
33
  async function prepareUserInput(ctx, inputId, text) {
36
- const files = await downloadFiles(ctx.message.files, ctx.hasFiles, ctx.adapter);
34
+ const { files, failures } = await downloadFiles(ctx.message, ctx.hasFiles, ctx.adapter);
37
35
  const thread = threadStore.get(ctx.existingThread.id);
38
36
  const input = thread?.metadata?.pendingUserInputs?.find((entry) => entry.id === inputId);
39
37
  if (!thread || !input)
@@ -41,7 +39,8 @@ async function prepareUserInput(ctx, inputId, text) {
41
39
  input.text = buildAgentPrompt(text, files.map((file) => ({
42
40
  mimeType: file.mimetype,
43
41
  path: file.localPath,
44
- })));
42
+ name: file.name,
43
+ })), failures);
45
44
  await threadStore.set(thread);
46
45
  }
47
46
  /** Buffer user text plus downloaded files for the next thread step. */
@@ -1,4 +1,5 @@
1
1
  import type { DownloadedFile, IncomingMessage, PlatformAdapter } from '../../platform/index.js';
2
+ import type { AttachmentFailure, InboundFiles } from '../routing/file-handler.js';
2
3
  import { type Session } from '../../store/session-registry-repo.js';
3
4
  export interface SessionUseLease {
4
5
  session: Session;
@@ -7,6 +8,15 @@ export interface SessionUseLease {
7
8
  /** Take the session's use lease, or null when the record is gone / pending deletion. The lease is
8
9
  * what stops retention from deleting a session out from under a turn that is still opening. */
9
10
  export declare function acquireSessionUseLease(sessionId: string): Promise<SessionUseLease | null>;
11
+ export interface TurnFiles {
12
+ /** Everything the backend is told about: platform downloads first, then web uploads. */
13
+ files: DownloadedFile[];
14
+ /** Transcript cards for the platform downloads only — a web upload already has its own card,
15
+ * minted by the upload route and carried on the message. */
16
+ platformAttachments: IncomingMessage['webAttachments'];
17
+ /** Attachments the platform would not hand over (reported in the prompt, not swallowed). */
18
+ failures: AttachmentFailure[];
19
+ }
10
20
  /**
11
21
  * The files one turn carries: what the platform had to download, plus the web upload's attachments
12
22
  * which are already on disk.
@@ -15,8 +25,12 @@ export declare function acquireSessionUseLease(sessionId: string): Promise<Sessi
15
25
  * WORKSPACE_DIR's contents; resolveWorkspaceRelPath maps it to the real absolute path under
16
26
  * WORKSPACE_DIR (= <DATA_DIR>/tmp). A malformed/escaping path resolves to null and is dropped, so a
17
27
  * broken path is never handed to the agent as a bogus absolute file.
28
+ *
29
+ * A platform download also gets a transcript card here, so an image sent from Slack or Feishu is
30
+ * visible when the same session is opened in the Web UI — previously only web uploads were, and a
31
+ * Feishu-sent picture simply vanished from the transcript.
18
32
  */
19
- export declare function collectTurnFiles(message: IncomingMessage, loadPlatformFiles: () => Promise<DownloadedFile[]>): Promise<DownloadedFile[]>;
33
+ export declare function collectTurnFiles(message: IncomingMessage, loadPlatformFiles: () => Promise<InboundFiles>): Promise<TurnFiles>;
20
34
  /**
21
35
  * A browser-enabled session holds the shared Chrome for the duration of its turn. Acquiring outside
22
36
  * the adapter keeps the spawn path synchronous and gives us one obvious place to pair with a
@@ -11,12 +11,14 @@
11
11
  // because `tests/orch/agent-runner.test.ts` and
12
12
  // `tests/orch/session-lifecycle-characterization.test.ts` pin their behaviour, and both are
13
13
  // re-exported from `agent-runner.ts` so those imports still resolve.
14
+ import { inboundAttachmentMeta } from '../attachments-store.js';
14
15
  import { createLogger } from '../../core/log.js';
15
16
  import { resolveWorkspaceRelPath } from '../../core/utils.js';
16
17
  import { sessionStore } from '../../store/session-registry-repo.js';
17
18
  import { getActiveProfile, getDefaultAgent, resolveBackendForChannel } from '../../domain/agents/index.js';
18
19
  import { resolveProfileConfig } from '../../domain/agents/profile-manager.js';
19
20
  import { registerNamedSession } from '../../domain/sessions/session-lifecycle.js';
21
+ import { acquireSessionUse } from '../../domain/sessions/session-use.js';
20
22
  import { getAgent } from '../../domain/threads/index.js';
21
23
  import { acquireBrowser, releaseBrowser, backendSupportsBrowser, BROWSER_DEVICE_SERVER } from '../../platform/browser/managed-browser.js';
22
24
  import { acquireDeviceBrowser, releaseDeviceBrowser } from '../../domain/remote/device-browser.js';
@@ -27,7 +29,7 @@ export async function acquireSessionUseLease(sessionId) {
27
29
  const session = await sessionStore.getById(sessionId);
28
30
  if (!session)
29
31
  return null;
30
- const release = await sessionStore.acquireSessionUse(sessionId);
32
+ const release = await acquireSessionUse(sessionId);
31
33
  if (!release)
32
34
  return null;
33
35
  return { session, release };
@@ -40,16 +42,26 @@ export async function acquireSessionUseLease(sessionId) {
40
42
  * WORKSPACE_DIR's contents; resolveWorkspaceRelPath maps it to the real absolute path under
41
43
  * WORKSPACE_DIR (= <DATA_DIR>/tmp). A malformed/escaping path resolves to null and is dropped, so a
42
44
  * broken path is never handed to the agent as a bogus absolute file.
45
+ *
46
+ * A platform download also gets a transcript card here, so an image sent from Slack or Feishu is
47
+ * visible when the same session is opened in the Web UI — previously only web uploads were, and a
48
+ * Feishu-sent picture simply vanished from the transcript.
43
49
  */
44
50
  export async function collectTurnFiles(message, loadPlatformFiles) {
45
- const downloadedFiles = await loadPlatformFiles();
46
- return [
47
- ...downloadedFiles,
48
- ...(message.webAttachments ?? []).flatMap((a) => {
49
- const localPath = resolveWorkspaceRelPath(a.path);
50
- return localPath ? [{ localPath, mimetype: a.mimeType, name: a.name }] : [];
51
- }),
52
- ];
51
+ const { files: downloadedFiles, failures } = await loadPlatformFiles();
52
+ const metas = await Promise.all(downloadedFiles.map(inboundAttachmentMeta));
53
+ const platformAttachments = metas.filter((meta) => meta !== null);
54
+ return {
55
+ files: [
56
+ ...downloadedFiles,
57
+ ...(message.webAttachments ?? []).flatMap((a) => {
58
+ const localPath = resolveWorkspaceRelPath(a.path);
59
+ return localPath ? [{ localPath, mimetype: a.mimeType, name: a.name }] : [];
60
+ }),
61
+ ],
62
+ platformAttachments: platformAttachments.length > 0 ? platformAttachments : undefined,
63
+ failures,
64
+ };
53
65
  }
54
66
  /** The session's backend decides whether a browser can be driven at all; the profile's
55
67
  * `claudeBackend` decides whether it is the print adapter — the only one wired for it. */