@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
@@ -7,7 +7,10 @@ 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';
@@ -44,36 +47,6 @@ function verifySignature(body, signature) {
44
47
  return false;
45
48
  }
46
49
  }
47
- /**
48
- * B2-C: a task-linked `cortex-run --name X` writes `<DATA_DIR>/tmp/cortex-run/X/output.log` on the
49
- * target device but, being a separate CLI process, cannot register an execution into the daemon's
50
- * in-memory registry. This is the daemon-side seam: on a successful launch, register (idempotent,
51
- * keyed by taskId) a `dispatch` execution carrying `runName` + `machine` so the Web UI can resolve
52
- * the run's live log by executionId (subscribeExecutionLog → resolveExecutionLogLocation). Requires
53
- * a taskId (the record key); a run without `--task-id` is not tailable through the UI. Best-effort —
54
- * never blocks or fails the launch response.
55
- */
56
- function maybeRegisterCortexRunExecution(action, params, device) {
57
- if (action !== 'cortex-run.launch')
58
- return;
59
- const name = params?.name;
60
- const taskId = params?.taskId;
61
- const taskProject = params?.taskProject;
62
- if (!name || !taskId)
63
- return;
64
- try {
65
- registerDispatchExecution({
66
- taskId,
67
- machine: device,
68
- project: taskProject || undefined,
69
- runName: name,
70
- });
71
- log.info(`B2-C: registered dispatch execution for cortex-run "${name}" (task ${taskId} on ${device})`);
72
- }
73
- catch (e) {
74
- log.warn(`B2-C: failed to register cortex-run execution for "${name}": ${e.message}`);
75
- }
76
- }
77
50
  /**
78
51
  * Bearer-token gate for every webhook route EXCEPT /webhook/github (which authenticates
79
52
  * via its own HMAC signature). Reads the call-time CORTEX_WEBHOOK_TOKEN and compares it
@@ -85,10 +58,44 @@ function isWebhookAuthorized(req) {
85
58
  const headerVal = Array.isArray(provided) ? provided[0] : provided;
86
59
  return timingSafeEqualStr(getWebhookToken(), headerVal);
87
60
  }
88
- 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) {
89
79
  let body = '';
90
- 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
+ });
91
96
  req.on('end', () => {
97
+ if (aborted)
98
+ return;
92
99
  try {
93
100
  callback(null, body, JSON.parse(body));
94
101
  }
@@ -159,9 +166,11 @@ function createWebhookHandler(_options = {}) {
159
166
  res.end('Forbidden');
160
167
  return;
161
168
  }
162
- // --- Auth gate: every route requires the webhook bearer token, except /webhook/github
163
- // which authenticates via its own HMAC signature (GitHub cannot send our header). ---
164
- 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)) {
165
174
  log.warn(`webhook auth rejected: ${req.method} ${req.url}`);
166
175
  res.writeHead(401);
167
176
  res.end('Unauthorized');
@@ -196,7 +205,6 @@ function createWebhookHandler(_options = {}) {
196
205
  }
197
206
  try {
198
207
  const result = await sendCommand(device, { action, params: params || {}, timeout });
199
- maybeRegisterCortexRunExecution(action, params, device);
200
208
  res.writeHead(200, { 'Content-Type': 'application/json' });
201
209
  res.end(JSON.stringify({ success: true, data: result }));
202
210
  }
@@ -207,6 +215,36 @@ function createWebhookHandler(_options = {}) {
207
215
  });
208
216
  return;
209
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
+ }
210
248
  // --- Remote task operation (from MCP sidecar on branch bases) ---
211
249
  if (req.method === 'POST' && req.url === '/webhook/task-op') {
212
250
  readJsonBody(req, async (error, _body, data) => {
@@ -247,14 +285,14 @@ function createWebhookHandler(_options = {}) {
247
285
  res.end('Bad JSON');
248
286
  return;
249
287
  }
250
- const { sessionId, filePath, fileName, caption } = data || {};
288
+ const { sessionId, filePath, fileName, caption, device } = data || {};
251
289
  if (!sessionId || !filePath) {
252
290
  res.writeHead(400, { 'Content-Type': 'application/json' });
253
291
  res.end(JSON.stringify({ success: false, error: 'sessionId and filePath required' }));
254
292
  return;
255
293
  }
256
294
  try {
257
- const meta = await sendAgentFile({ sessionId, filePath, fileName, caption });
295
+ const meta = await sendAgentFile({ sessionId, filePath, fileName, caption, device });
258
296
  res.writeHead(200, { 'Content-Type': 'application/json' });
259
297
  res.end(JSON.stringify({ success: true, data: meta }));
260
298
  }
@@ -757,6 +795,122 @@ function createWebhookHandler(_options = {}) {
757
795
  });
758
796
  return;
759
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
+ }
760
914
  if (req.method !== 'POST' || req.url !== '/webhook/github') {
761
915
  res.writeHead(404);
762
916
  res.end('Not found');
@@ -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;
@@ -6,6 +6,9 @@ import { getActiveHandle } from '../domain/threads/runner.js';
6
6
  import { openThreadRun } from './thread-run/index.js';
7
7
  import { threadStore } from '../store/thread-repo.js';
8
8
  import { downloadFiles, bufferUserMessage } from './thread-input.js';
9
+ import { isRebuildHeld, refuseTurnForRebuild } from '../domain/system/rebuild-hold.js';
10
+ import { createLogger } from '../core/log.js';
11
+ const log = createLogger('thread-executor');
9
12
  export class ThreadExecutor {
10
13
  _enqueue;
11
14
  _track;
@@ -18,6 +21,16 @@ export class ThreadExecutor {
18
21
  }
19
22
  async route(ctx) {
20
23
  const { message, channel, adapter } = ctx;
24
+ // Same admission rule as the direct path (agent-runner): while the supervisor is rebuilding or
25
+ // replacing this process, starting a thread step only produces a step that the SIGTERM marks
26
+ // `failed` a moment later. Refuse it where the person can see why.
27
+ if (isRebuildHeld()) {
28
+ log.info(`Refusing thread routing on ${channel}: supervisor rebuild in progress`);
29
+ await refuseTurnForRebuild({
30
+ adapter, channel, text: ctx.agentMessage || '', interactive: true,
31
+ });
32
+ return;
33
+ }
21
34
  // Phase 6: buffer user messages when the thread is running a step,
22
35
  // so they're included in the next step's prompt instead of being lost.
23
36
  // DR-0014: also buffer for a parent suspended on child threads — routing such a
@@ -54,7 +67,12 @@ export class ThreadExecutor {
54
67
  * cancellation rendering (onto the live status message, with the elapsed clock) belongs to it. */
55
68
  async _executeReal(ctx) {
56
69
  const startTime = Date.now();
57
- const downloadedFiles = await downloadFiles(ctx.message.files, ctx.hasFiles, ctx.adapter);
70
+ // A thread's first step takes the files. An attachment that would not download cannot be named
71
+ // in the step prompt (the template composes it), so the user is told in the channel instead —
72
+ // the one thing that must not happen is the whole thing passing in silence.
73
+ const { files: downloadedFiles, failures } = await downloadFiles(ctx.message, ctx.hasFiles, ctx.adapter);
74
+ if (failures.length > 0)
75
+ await this._reportFailedDownloads(ctx, failures);
58
76
  const args = { channel: ctx.channel, adapter: ctx.adapter, threadAnchorId: ctx.threadAnchorId, startTime, downloadedFiles };
59
77
  try {
60
78
  if (ctx.threadAddMatch) {
@@ -75,6 +93,11 @@ export class ThreadExecutor {
75
93
  await ctx.adapter.postMessage({ type: 'interactive-reply', conduit: ctx.channel, sessionId: '' }, { text }, ctx.threadAnchorId ? { threadId: ctx.threadAnchorId } : undefined).catch(() => { });
76
94
  }
77
95
  }
96
+ /** Tell the channel which attachments did not make it into the thread. */
97
+ async _reportFailedDownloads(ctx, failures) {
98
+ const list = failures.map((f) => `• ${f.name} — ${f.reason}`).join('\n');
99
+ 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(() => { });
100
+ }
78
101
  }
79
102
  export const threadExecutor = new ThreadExecutor();
80
103
  /** 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,6 +11,7 @@
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';
@@ -41,16 +42,26 @@ export async function acquireSessionUseLease(sessionId) {
41
42
  * WORKSPACE_DIR's contents; resolveWorkspaceRelPath maps it to the real absolute path under
42
43
  * WORKSPACE_DIR (= <DATA_DIR>/tmp). A malformed/escaping path resolves to null and is dropped, so a
43
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.
44
49
  */
45
50
  export async function collectTurnFiles(message, loadPlatformFiles) {
46
- const downloadedFiles = await loadPlatformFiles();
47
- return [
48
- ...downloadedFiles,
49
- ...(message.webAttachments ?? []).flatMap((a) => {
50
- const localPath = resolveWorkspaceRelPath(a.path);
51
- return localPath ? [{ localPath, mimetype: a.mimeType, name: a.name }] : [];
52
- }),
53
- ];
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
+ };
54
65
  }
55
66
  /** The session's backend decides whether a browser can be driven at all; the profile's
56
67
  * `claudeBackend` decides whether it is the print adapter — the only one wired for it. */
@@ -586,6 +586,7 @@ export function buildInjectDeps(sessionName, channel, adapter) {
586
586
  getLiveExecutions: (channel) => runRegistry.getByChannel(channel).map((entry) => ({
587
587
  backend: entry.backend,
588
588
  run: entry.run,
589
+ trackSessionId: entry.trackSessionId ?? null,
589
590
  })),
590
591
  getStreamingCallback: (channel) => activeTurns.streamingCallback(channel),
591
592
  appendAssistant: (sessionId, o) => recordHistory(conversationHistory.appendAssistant(sessionId, o)),
@@ -0,0 +1,41 @@
1
+ import { type ApplySignalOutcome, type SignalInput, type WaitpointServiceDeps } from '../domain/waitpoints/service.js';
2
+ import { type WaitpointNotifierDeps } from './waitpoint-notifier.js';
3
+ /** Any process that can write a file can signal: drop `<anything>.json` here. */
4
+ export declare const SIGNAL_SPOOL_DIR: string;
5
+ /** Files that could never be applied (unparseable, unknown id) are parked here, not deleted. */
6
+ export declare const SIGNAL_SPOOL_BAD_DIR: string;
7
+ /** A spool entry larger than this is refused outright — signals are summaries, not logs. */
8
+ export declare const SPOOL_FILE_MAX_BYTES: number;
9
+ export interface SignalRejection {
10
+ at: number;
11
+ reason: 'not-found' | 'bad-secret' | 'rate-limited';
12
+ id: string;
13
+ source: string;
14
+ }
15
+ /** Recent rejected signals, newest last. Diagnostic surface for "my script says 404". */
16
+ export declare function recentSignalRejections(): SignalRejection[];
17
+ /** Test hook. */
18
+ export declare function resetSignalIngressState(): void;
19
+ export interface IngestDeps {
20
+ service: WaitpointServiceDeps;
21
+ notifier: WaitpointNotifierDeps;
22
+ now: () => number;
23
+ }
24
+ export declare const productionIngestDeps: IngestDeps;
25
+ /**
26
+ * Apply one signal and schedule the wake it earned.
27
+ *
28
+ * Returns the raw outcome; mapping it onto HTTP status codes is the route's job, because the spool
29
+ * path has no status codes to map onto.
30
+ */
31
+ export declare function ingestSignal(input: SignalInput, deps?: IngestDeps): Promise<ApplySignalOutcome>;
32
+ /**
33
+ * Apply every spool file on this machine and delete the ones that landed.
34
+ *
35
+ * A file is removed only after its signal was accepted or was already resolved; anything still
36
+ * addressable to a live waitpoint is left for the next tick. The filename doubles as the dedupe
37
+ * key, so re-reading a file whose delete was lost is harmless.
38
+ */
39
+ export declare function drainLocalSpool(deps?: IngestDeps, dir?: string): Promise<number>;
40
+ /** Normalise an untrusted payload (HTTP body or spool file) into a SignalInput. */
41
+ export declare function toSignalInput(payload: Record<string, unknown>, dedupeKey: string | null, source: string): SignalInput;