@cortex-agent/server 2026.9.15 → 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 (192) 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-feishu/skills/feishu-doc/SKILL.md +1 -1
  14. package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +2 -2
  15. package/defaults/plugins/cortex-system/skills/project-init/SKILL.md +4 -4
  16. package/defaults/plugins/cortex-system/skills/task/SKILL.md +1 -1
  17. package/defaults/rules/{cortex-md.md → agents-md.md} +4 -4
  18. package/defaults/rules/decision-records.md +1 -1
  19. package/defaults/rules/meta-conventions.md +4 -4
  20. package/defaults/rules/mission-md.md +1 -1
  21. package/dist/agent-adapter/claude/hooks-builder.js +2 -2
  22. package/dist/agent-adapter/claude/spawn-args.js +4 -0
  23. package/dist/agent-adapter/claude/turn-machine.d.ts +11 -0
  24. package/dist/agent-adapter/claude/turn-machine.js +46 -5
  25. package/dist/agent-adapter/normalize/prompt-builder.d.ts +16 -1
  26. package/dist/agent-adapter/normalize/prompt-builder.js +24 -6
  27. package/dist/agent-adapter/types.d.ts +1 -0
  28. package/dist/core/mcp-tool-gate.js +1 -0
  29. package/dist/core/media-types.d.ts +10 -0
  30. package/dist/core/media-types.js +34 -0
  31. package/dist/core/platform-settings-spec.js +1 -1
  32. package/dist/core/settings-spec.d.ts +21 -0
  33. package/dist/core/settings-spec.js +28 -1
  34. package/dist/core/types/agent-types.d.ts +3 -1
  35. package/dist/core/utils.d.ts +1 -1
  36. package/dist/core/utils.js +1 -1
  37. package/dist/domain/executions/registry.d.ts +1 -2
  38. package/dist/domain/executions/registry.js +0 -3
  39. package/dist/domain/mcp/bundled-server.js +4 -3
  40. package/dist/domain/mcp/feishu/file.js +37 -18
  41. package/dist/domain/mcp/feishu/types.d.ts +3 -0
  42. package/dist/domain/mcp/feishu-server.js +1 -1
  43. package/dist/domain/mcp/tools/{cortex-md.d.ts → agents-md.d.ts} +6 -6
  44. package/dist/domain/mcp/tools/{cortex-md.js → agents-md.js} +6 -6
  45. package/dist/domain/mcp/tools/remote-file.d.ts +20 -0
  46. package/dist/domain/mcp/tools/remote-file.js +44 -0
  47. package/dist/domain/mcp/tools/slack.d.ts +2 -0
  48. package/dist/domain/mcp/tools/slack.js +22 -7
  49. package/dist/domain/mcp/tools/task-ops.js +5 -13
  50. package/dist/domain/mcp/tools/ui-file.js +23 -10
  51. package/dist/domain/mcp/tools/waitpoint.d.ts +3 -0
  52. package/dist/domain/mcp/tools/waitpoint.js +122 -0
  53. package/dist/domain/memory/agents-md-injector.d.ts +24 -0
  54. package/dist/domain/memory/{cortex-md-injector.js → agents-md-injector.js} +10 -7
  55. package/dist/domain/projects/project-store.d.ts +1 -1
  56. package/dist/domain/projects/project-store.js +3 -3
  57. package/dist/domain/remote/client-hot-reload.js +3 -1
  58. package/dist/domain/remote/client-manager.js +39 -119
  59. package/dist/domain/remote/cortex-client-config.d.ts +1 -1
  60. package/dist/domain/remote/cortex-client-config.js +1 -1
  61. package/dist/domain/remote/device-file.d.ts +51 -0
  62. package/dist/domain/remote/device-file.js +193 -0
  63. package/dist/domain/remote/device-port.js +3 -0
  64. package/dist/domain/remote/reverse-stream.d.ts +18 -7
  65. package/dist/domain/remote/reverse-stream.js +19 -6
  66. package/dist/domain/tasks/claim-recovery.js +2 -2
  67. package/dist/domain/tasks/dispatch-utils.d.ts +10 -1
  68. package/dist/domain/tasks/dispatch-utils.js +46 -1
  69. package/dist/domain/tasks/dispatcher.js +4 -5
  70. package/dist/domain/tasks/mutator.d.ts +2 -2
  71. package/dist/domain/tasks/mutator.js +2 -2
  72. package/dist/domain/tasks/system/task-cli.js +2 -2
  73. package/dist/domain/tasks/system/task-state.js +1 -1
  74. package/dist/domain/threads/runner.js +3 -1
  75. package/dist/domain/ui-service/app-router.d.ts +24 -3
  76. package/dist/domain/ui-service/app-router.js +8 -14
  77. package/dist/domain/ui-service/input-schemas.d.ts +17 -5
  78. package/dist/domain/ui-service/input-schemas.js +13 -9
  79. package/dist/domain/ui-service/mutate/platform-settings.js +1 -1
  80. package/dist/domain/ui-service/mutate/sessions.d.ts +5 -1
  81. package/dist/domain/ui-service/mutate/sessions.js +14 -0
  82. package/dist/domain/ui-service/mutate/waitpoints.d.ts +2 -0
  83. package/dist/domain/ui-service/mutate/waitpoints.js +20 -0
  84. package/dist/domain/ui-service/platform-settings.js +1 -1
  85. package/dist/domain/ui-service/plugins-shared.js +1 -1
  86. package/dist/domain/ui-service/query/config.js +1 -1
  87. package/dist/domain/ui-service/query/executions.js +0 -2
  88. package/dist/domain/ui-service/query/machine-detail.js +3 -8
  89. package/dist/domain/ui-service/query/memory.js +1 -1
  90. package/dist/domain/ui-service/query/sessions.js +7 -0
  91. package/dist/domain/ui-service/query/threads.js +1 -54
  92. package/dist/domain/ui-service/query/waitpoints.d.ts +30 -0
  93. package/dist/domain/ui-service/query/waitpoints.js +117 -0
  94. package/dist/domain/ui-service/query-input-schemas.d.ts +3 -0
  95. package/dist/domain/ui-service/query-input-schemas.js +3 -0
  96. package/dist/domain/ui-service/trpc.js +1 -1
  97. package/dist/domain/ui-service/types.d.ts +133 -49
  98. package/dist/domain/ui-service/types.js +1 -1
  99. package/dist/domain/ui-service/ui-service.js +7 -31
  100. package/dist/domain/waitpoints/notices.d.ts +21 -0
  101. package/dist/domain/waitpoints/notices.js +115 -0
  102. package/dist/domain/waitpoints/service.d.ts +91 -0
  103. package/dist/domain/waitpoints/service.js +243 -0
  104. package/dist/entry/app.js +29 -7
  105. package/dist/entry/auth-login-cli.js +1 -1
  106. package/dist/entry/auth-login-terminal.js +1 -1
  107. package/dist/entry/init-auth.js +1 -1
  108. package/dist/entry/init.js +6 -6
  109. package/dist/entry/signal-cli.d.ts +30 -0
  110. package/dist/entry/signal-cli.js +207 -0
  111. package/dist/entry/start-ui-http.d.ts +1 -1
  112. package/dist/entry/start-ui-http.js +2 -2
  113. package/dist/events/event-types.d.ts +0 -7
  114. package/dist/hooks/{cortex-md-injector.mjs → agents-md-injector.mjs} +117 -26
  115. package/dist/hooks/cortex-hook-api.mjs +2 -2
  116. package/dist/hooks/new-session-hook.mjs +2 -2
  117. package/dist/hooks/rules-loader.mjs +2 -2
  118. package/dist/hooks/status-md-guard.mjs +8 -8
  119. package/dist/hooks/task-status-check.mjs +18 -76
  120. package/dist/hooks/tasks-yaml-guard.mjs +2 -2
  121. package/dist/orchestration/agent-file-send.d.ts +9 -0
  122. package/dist/orchestration/agent-file-send.js +21 -2
  123. package/dist/orchestration/agent-runner.d.ts +3 -2
  124. package/dist/orchestration/agent-runner.js +17 -12
  125. package/dist/orchestration/attachments-store.d.ts +31 -0
  126. package/dist/orchestration/attachments-store.js +184 -0
  127. package/dist/orchestration/conversation-request.d.ts +4 -0
  128. package/dist/orchestration/conversation-request.js +13 -6
  129. package/dist/orchestration/interactions/plan-approvals.js +1 -1
  130. package/dist/orchestration/outputs-store.d.ts +11 -0
  131. package/dist/orchestration/outputs-store.js +32 -6
  132. package/dist/orchestration/routing/file-handler.d.ts +23 -2
  133. package/dist/orchestration/routing/file-handler.js +22 -5
  134. package/dist/orchestration/routing/webhook.js +193 -39
  135. package/dist/orchestration/session-gateway.d.ts +1 -1
  136. package/dist/orchestration/session-gateway.js +1 -0
  137. package/dist/orchestration/thread-executor.d.ts +2 -0
  138. package/dist/orchestration/thread-executor.js +11 -1
  139. package/dist/orchestration/thread-input.d.ts +3 -2
  140. package/dist/orchestration/thread-input.js +8 -9
  141. package/dist/orchestration/turn/turn-prep.d.ts +15 -1
  142. package/dist/orchestration/turn/turn-prep.js +19 -8
  143. package/dist/orchestration/waitpoint-ingress.d.ts +41 -0
  144. package/dist/orchestration/waitpoint-ingress.js +172 -0
  145. package/dist/orchestration/waitpoint-notifier.d.ts +21 -0
  146. package/dist/orchestration/waitpoint-notifier.js +119 -0
  147. package/dist/orchestration/waitpoint-remote-drain.d.ts +20 -0
  148. package/dist/orchestration/waitpoint-remote-drain.js +147 -0
  149. package/dist/orchestration/waitpoint-sweep.d.ts +42 -0
  150. package/dist/orchestration/waitpoint-sweep.js +87 -0
  151. package/dist/platform/adapters/feishu-image.d.ts +19 -0
  152. package/dist/platform/adapters/feishu-image.js +71 -0
  153. package/dist/platform/adapters/feishu.d.ts +2 -0
  154. package/dist/platform/adapters/feishu.js +26 -16
  155. package/dist/platform/ui-http/listening-ports.d.ts +1 -1
  156. package/dist/platform/ui-http/listening-ports.js +1 -1
  157. package/dist/platform/ui-http/ui-session.js +1 -1
  158. package/dist/store/conversation-ledger-repo.js +1 -1
  159. package/dist/store/execution-repo.d.ts +1 -19
  160. package/dist/store/execution-repo.js +1 -18
  161. package/dist/store/project-notes-repo.js +11 -2
  162. package/dist/store/prompt-migration-replacements.js +1 -1
  163. package/dist/store/session-registry-import.js +1 -1
  164. package/dist/store/session-registry-journal.js +1 -1
  165. package/dist/store/session-registry-repo.js +1 -1
  166. package/dist/store/version-migrations.d.ts +13 -3
  167. package/dist/store/version-migrations.js +254 -24
  168. package/dist/store/waitpoint-repo.d.ts +108 -0
  169. package/dist/store/waitpoint-repo.js +94 -0
  170. package/package.json +2 -2
  171. package/web/dist/assets/{index-CRDJo39X.css → index-CwwQNMpP.css} +1 -1
  172. package/web/dist/assets/index-DLSfgq3o.js +444 -0
  173. package/web/dist/assets/{index-CEZ0DSei.js → index-DZTuqUO4.js} +1 -1
  174. package/web/dist/index.html +2 -2
  175. package/defaults/config/hooks/08-cortex-md-injector-post-tool.json +0 -10
  176. package/dist/domain/executions/log-tailer.d.ts +0 -71
  177. package/dist/domain/executions/log-tailer.js +0 -194
  178. package/dist/domain/memory/cortex-md-injector.d.ts +0 -24
  179. package/dist/domain/memory/cortex-md-scanner.d.ts +0 -10
  180. package/dist/domain/memory/cortex-md-scanner.js +0 -66
  181. package/dist/domain/remote/cortex-client.d.ts +0 -1
  182. package/dist/domain/remote/cortex-client.js +0 -662
  183. package/dist/domain/tasks/system/cortex-run.d.ts +0 -25
  184. package/dist/domain/tasks/system/cortex-run.js +0 -360
  185. package/web/dist/assets/index-DjuPJVZE.js +0 -444
  186. /package/defaults/{CORTEX.md → AGENTS.md} +0 -0
  187. /package/defaults/config/{CORTEX.md → AGENTS.md} +0 -0
  188. /package/defaults/context/{CORTEX.md → AGENTS.md} +0 -0
  189. /package/defaults/context/ideas/{CORTEX.md → AGENTS.md} +0 -0
  190. /package/defaults/context/projects/{CORTEX.md → AGENTS.md} +0 -0
  191. /package/defaults/context/scans/{CORTEX.md → AGENTS.md} +0 -0
  192. /package/defaults/context/user/{CORTEX.md → AGENTS.md} +0 -0
@@ -70,6 +70,16 @@ function outputsDir(sessionId, subdir) {
70
70
  relPrefix: `workspace/outputs/${parts.join('/')}`,
71
71
  };
72
72
  }
73
+ /** Claim a free destination inside the session's outputs area, creating the directory. Shared by
74
+ * every lander so naming, collision handling and placement cannot drift between them. */
75
+ async function reserveOutputPath(a) {
76
+ const displayName = sanitizeDisplayFilename(a.fileName);
77
+ const storageName = sanitizeStorageFilename(displayName);
78
+ const { dir, relPrefix } = outputsDir(a.sessionId, a.subdir);
79
+ await fs.mkdir(dir, { recursive: true });
80
+ const { destPath, finalName } = await resolveAvailablePath(dir, storageName);
81
+ return { destPath, relPath: `${relPrefix}/${finalName}`, displayName };
82
+ }
73
83
  /**
74
84
  * Copy an agent-produced file into the session's `workspace/outputs/…` area and return its
75
85
  * UI-relative path + final name + byte size. Copying (rather than referencing the source in
@@ -91,14 +101,30 @@ export async function copyFileIntoOutputs(a) {
91
101
  if (a.maxBytes !== undefined && stat.size > a.maxBytes) {
92
102
  throw new Error(`File is ${stat.size} bytes, over the ${a.maxBytes}-byte limit`);
93
103
  }
94
- const displayName = sanitizeDisplayFilename(a.fileName || path.basename(resolvedSrc));
95
- const storageName = sanitizeStorageFilename(displayName);
96
- const { dir, relPrefix } = outputsDir(a.sessionId, a.subdir);
97
- await fs.mkdir(dir, { recursive: true });
98
- const { destPath, finalName } = await resolveAvailablePath(dir, storageName);
104
+ const { destPath, relPath, displayName } = await reserveOutputPath({
105
+ sessionId: a.sessionId, fileName: a.fileName || path.basename(resolvedSrc), subdir: a.subdir,
106
+ });
99
107
  await fs.copyFile(resolvedSrc, destPath);
100
108
  const outStat = await fs.stat(destPath);
101
- return { relPath: `${relPrefix}/${finalName}`, name: displayName, size: outStat.size };
109
+ return { relPath, name: displayName, size: outStat.size };
110
+ }
111
+ /**
112
+ * Land a file whose bytes are produced by `receive` (a remote-device transfer) directly in the
113
+ * outputs area. Same placement and naming as `copyFileIntoOutputs`, but written once: staging to a
114
+ * temp file first and copying would double the I/O of every large transfer and leave litter behind
115
+ * when a send fails. A failing `receive` must leave nothing, so the reservation is removed here.
116
+ */
117
+ export async function receiveIntoOutputs(a, receive) {
118
+ const { destPath, relPath, displayName } = await reserveOutputPath(a);
119
+ try {
120
+ await receive(destPath);
121
+ }
122
+ catch (e) {
123
+ await fs.rm(destPath, { force: true }).catch(() => { });
124
+ throw e;
125
+ }
126
+ const outStat = await fs.stat(destPath);
127
+ return { relPath, name: displayName, size: outStat.size };
102
128
  }
103
129
  /** Write agent-authored text into the session's outputs area under `fileName`, same placement and
104
130
  * naming discipline as `copyFileIntoOutputs`. Used when the payload arrives inline rather than as
@@ -1,4 +1,25 @@
1
1
  import type { PlatformAdapter } from '../../platform/adapter.js';
2
- import type { PlatformFileRef, DownloadedFile } from '../../platform/types.js';
3
- declare function downloadFiles(files: PlatformFileRef[] | undefined, adapter: PlatformAdapter, tempDir: string): Promise<DownloadedFile[]>;
2
+ import type { IncomingMessage, PlatformFileRef, DownloadedFile } from '../../platform/types.js';
3
+ export interface AttachmentFailure {
4
+ name: string;
5
+ reason: string;
6
+ }
7
+ export interface InboundFiles {
8
+ files: DownloadedFile[];
9
+ /** Attachments the platform would not hand over. Reported to the user and to the model rather
10
+ * than dropped: an answer written as if the picture had never been sent is worse than an
11
+ * answer that says the picture did not arrive. */
12
+ failures: AttachmentFailure[];
13
+ }
14
+ /**
15
+ * Download one message's attachments into that message's own directory under
16
+ * `workspace/attachments/`, then settle each one's real type and name (attachments-store).
17
+ *
18
+ * `key` identifies the inbound message (its platform message id); reusing it means a retried
19
+ * delivery reuses the directory instead of littering a new one.
20
+ */
21
+ declare function downloadFiles(files: PlatformFileRef[] | undefined, adapter: PlatformAdapter, key: string): Promise<InboundFiles>;
22
+ /** The inbound message's own attachment directory key: conduit + platform message id. Stable, so a
23
+ * redelivery of the same message reuses its directory instead of littering a new one. */
24
+ export declare function inboundAttachmentKey(message: IncomingMessage): string;
4
25
  export { downloadFiles };
@@ -1,17 +1,34 @@
1
1
  import { createLogger } from '../../core/log.js';
2
+ import { finalizeInboundFile, prepareInboundAttachmentDir } from '../attachments-store.js';
2
3
  const log = createLogger('file-handler');
3
- async function downloadFiles(files, adapter, tempDir) {
4
+ /**
5
+ * Download one message's attachments into that message's own directory under
6
+ * `workspace/attachments/`, then settle each one's real type and name (attachments-store).
7
+ *
8
+ * `key` identifies the inbound message (its platform message id); reusing it means a retried
9
+ * delivery reuses the directory instead of littering a new one.
10
+ */
11
+ async function downloadFiles(files, adapter, key) {
4
12
  if (!files?.length)
5
- return [];
13
+ return { files: [], failures: [] };
14
+ const dir = await prepareInboundAttachmentDir(key);
6
15
  const results = [];
16
+ const failures = [];
7
17
  for (const file of files) {
8
18
  try {
9
- results.push(await adapter.downloadFile(file, tempDir));
19
+ results.push(await finalizeInboundFile(await adapter.downloadFile(file, dir), dir));
10
20
  }
11
21
  catch (e) {
12
- log.error('Failed to download file:', file.name, e.message);
22
+ const reason = e.message;
23
+ log.error('Failed to download file:', file.name, reason);
24
+ failures.push({ name: file.name || file.id, reason });
13
25
  }
14
26
  }
15
- return results;
27
+ return { files: results, failures };
28
+ }
29
+ /** The inbound message's own attachment directory key: conduit + platform message id. Stable, so a
30
+ * redelivery of the same message reuses its directory instead of littering a new one. */
31
+ export function inboundAttachmentKey(message) {
32
+ return `${message.ref.conduit || 'unknown'}-${message.ref.messageId || 'nomsg'}`;
16
33
  }
17
34
  export { downloadFiles };
@@ -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;
@@ -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,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. */