@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
@@ -3,9 +3,9 @@
3
3
  // input: stdin thread lifecycle payload, argv identity fallback
4
4
  // output: HookResult for unresolved dispatch task state
5
5
  // pos: Checks task status after a dispatched thread terminates
6
- // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
6
+ // >>> If I am updated, update my header comment and the parent folder's AGENTS.md <<<
7
7
 
8
- import { readFileSync, existsSync, readdirSync } from 'fs';
8
+ import { readFileSync, existsSync } from 'fs';
9
9
  import * as path from 'path';
10
10
  import { homedir } from 'os';
11
11
 
@@ -16,8 +16,6 @@ const PROJECTS_DIR = process.env.CORTEX_PROJECTS_DIR
16
16
  ? path.resolve(process.env.CORTEX_PROJECTS_DIR)
17
17
  : path.join(DATA_DIR, 'context', 'projects');
18
18
 
19
- const CORTEX_RUN_DIR = path.join(DATA_DIR, 'tmp', 'cortex-run');
20
-
21
19
  function noop() {
22
20
  console.log(JSON.stringify({ insertAgent: false }));
23
21
  }
@@ -79,35 +77,6 @@ function findTaskById(content, taskId) {
79
77
  return task;
80
78
  }
81
79
 
82
- /** Find a cortex-run state file that references the given task. */
83
- function findStateFileForTask(project, taskId) {
84
- try {
85
- if (!existsSync(CORTEX_RUN_DIR)) return null;
86
- for (const entry of readdirSync(CORTEX_RUN_DIR, { withFileTypes: true })) {
87
- if (!entry.isDirectory()) continue;
88
- const statePath = path.join(CORTEX_RUN_DIR, entry.name, 'state.json');
89
- if (!existsSync(statePath)) continue;
90
- try {
91
- const state = JSON.parse(readFileSync(statePath, 'utf8'));
92
- if (state.task_project === project && state.task_id === taskId) {
93
- return { runName: entry.name, ...state };
94
- }
95
- } catch {}
96
- }
97
- } catch {}
98
- return null;
99
- }
100
-
101
- /** Check if a PID is still alive. */
102
- function pidAlive(pid) {
103
- try {
104
- process.kill(pid, 0);
105
- return true;
106
- } catch {
107
- return false;
108
- }
109
- }
110
-
111
80
  async function main() {
112
81
  let input = '';
113
82
  for await (const chunk of process.stdin) input += chunk;
@@ -146,27 +115,20 @@ async function main() {
146
115
  // Task is done — nothing to do.
147
116
  if (task.status === 'done') { noop(); return; }
148
117
 
149
- // Task is pending — cortex-run is handling it. No recovery; just verify.
118
+ // Task is pending — something outside this thread owns its completion (a waitpoint signal, an
119
+ // operator). No recovery is automatic; just make the limbo visible to the agent that ran.
150
120
  if (task.status === 'pending') {
151
- const stateFile = findStateFileForTask(project, taskId);
152
- if (!stateFile || stateFile.status === 'failed') {
153
- // cortex-run state file missing or run failed — but per design, do not auto-recover.
154
- // Just report so it's visible.
155
- const targetAgent = ctx.previousAgent;
156
- if (targetAgent) {
157
- const note = !stateFile
158
- ? 'no state file found (cortex-run may not have started)'
159
- : `state file shows status=${stateFile.status} (exit ${stateFile.exit_code})`;
160
- console.log(JSON.stringify({
161
- insertAgent: false,
162
- targetAgent,
163
- prompt: [
164
- `FYI: task [id: ${taskId}] in project "${project}" is still [pending] but cortex-run ${note}.`,
165
- 'Per current policy, pending→done recovery is not automatic. Check manually if needed.',
166
- ].join('\n'),
167
- }));
168
- return;
169
- }
121
+ const targetAgent = ctx.previousAgent;
122
+ if (targetAgent) {
123
+ console.log(JSON.stringify({
124
+ insertAgent: false,
125
+ targetAgent,
126
+ prompt: [
127
+ `FYI: task [id: ${taskId}] in project "${project}" is still [pending] and the thread has finished.`,
128
+ 'Per current policy, pending→done recovery is not automatic. Check manually if needed.',
129
+ ].join('\n'),
130
+ }));
131
+ return;
170
132
  }
171
133
  noop();
172
134
  return;
@@ -180,37 +142,17 @@ async function main() {
180
142
  const targetAgent = ctx.previousAgent;
181
143
  if (!targetAgent) { noop(); return; }
182
144
 
183
- // Check if there's a cortex-run process handling this task
184
- const stateFile = findStateFileForTask(project, taskId);
185
-
186
- if (stateFile && stateFile.status === 'running') {
187
- // cortex-run is running — this is a legitimate pending case.
188
- // Engineer forgot to call cortex-task pending; auto-transition.
189
- console.log(JSON.stringify({
190
- insertAgent: false,
191
- targetAgent,
192
- prompt: [
193
- `Auto-detected: task [id: ${taskId}] in project "${project}" is still claimed,`,
194
- `but a cortex-run process "(${stateFile.runName})" is running for this task (PID ${stateFile.pid}).`,
195
- `The engineer likely forgot to mark the task pending. Call:`,
196
- ` cortex-task pending --project ${project} --task-id ${taskId}`,
197
- ].join('\n'),
198
- }));
199
- return;
200
- }
201
-
202
- // No cortex-run state file — genuine orphan.
203
- // Unclaim and prompt agent to resolve.
145
+ // The thread finished without transitioning the task — prompt the agent to resolve it.
204
146
  console.log(JSON.stringify({
205
147
  insertAgent: false,
206
148
  targetAgent,
207
149
  prompt: [
208
- `Status check: task [id: ${taskId}] in project "${project}" is still marked [claimed] in TASKS.yaml, but the thread has finished. No running cortex-run process found for this task.`,
150
+ `Status check: task [id: ${taskId}] in project "${project}" is still marked [claimed] in TASKS.yaml, but the thread has finished.`,
209
151
  '',
210
152
  'Resolve the task status now — do not leave it in limbo:',
211
153
  `- If done-when conditions are satisfied: cortex-task complete --project ${project} --task-id ${taskId} --note "<what you did>"`,
212
154
  `- If blocked by external reasons: cortex-task block --project ${project} --task-id ${taskId} --reason "<reason>"`,
213
- `- If a cortex-run is still running: cortex-task pending --project ${project} --task-id ${taskId}`,
155
+ `- If something outside this thread still has to finish: cortex-task pending --project ${project} --task-id ${taskId}`,
214
156
  `- If none of the above apply: cortex-task unclaim --project ${project} --task-id ${taskId}`,
215
157
  '',
216
158
  'After updating the task, commit the TASKS.yaml change.',
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
- // @cortex-hook-version 2026.6.22-2
2
+ // @cortex-hook-version 2026.9.15-2
3
3
  // input: stdin JSON — Claude Code PreToolUse event payload
4
4
  // output: stdout JSON — { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision, permissionDecisionReason } }
5
5
  // pos: PreToolUse hook — intercepts Edit/Write on **/TASKS.yaml, checks project lock
6
6
  // allow when current process holds the lock; deny + helpful message otherwise
7
7
  // Owner identity: process.env.CORTEX_EXECUTION_ID ?? manual:<user>:<pid>
8
- // >>> If I am updated, be sure to update my header comment and the CORTEX.md in the same folder <<<
8
+ // >>> If I am updated, be sure to update my header comment and the AGENTS.md in the same folder <<<
9
9
 
10
10
  import { readFileSync, existsSync } from 'fs';
11
11
  import { basename, resolve } from 'path';
@@ -17,6 +17,8 @@ export interface SendAgentFileArgs {
17
17
  fileName?: string;
18
18
  /** Optional caption shown alongside the file card. */
19
19
  caption?: string;
20
+ /** Name of a connected cortex-client; the path is then read on THAT device, not on the server. */
21
+ device?: string;
20
22
  }
21
23
  export interface SendAgentFileDeps {
22
24
  copyIntoOutputs?: (a: {
@@ -24,6 +26,13 @@ export interface SendAgentFileDeps {
24
26
  filePath: string;
25
27
  fileName?: string;
26
28
  }) => Promise<StoredOutput>;
29
+ /** Injectable twin of `copyIntoOutputs` for the remote path. */
30
+ fetchIntoOutputs?: (a: {
31
+ sessionId: string;
32
+ device: string;
33
+ filePath: string;
34
+ fileName?: string;
35
+ }) => Promise<StoredOutput>;
27
36
  appendAssistant?: (sessionId: string, opts: {
28
37
  text: string;
29
38
  ts?: string;
@@ -1,7 +1,8 @@
1
1
  import * as path from 'path';
2
2
  import { conversationHistory } from '../store/conversation-history-repo.js';
3
3
  import { publishSessionMessage } from './session-events.js';
4
- import { copyFileIntoOutputs } from './outputs-store.js';
4
+ import { copyFileIntoOutputs, receiveIntoOutputs } from './outputs-store.js';
5
+ import { fetchRemoteFile, prepareRemoteFetch } from '../domain/remote/device-file.js';
5
6
  export { copyFileIntoOutputs };
6
7
  /** Minimal extension → MIME map for the common file kinds an agent shares. Anything unknown falls
7
8
  * back to application/octet-stream (still downloadable, just no inline preview). */
@@ -28,6 +29,19 @@ export function classifyAttachment(mimeType) {
28
29
  return 'video';
29
30
  return 'file';
30
31
  }
32
+ /** Nothing the chat can usefully show is this big, and the cap is what stops one `send_file` from
33
+ * filling the disk with a transfer nobody can cancel. */
34
+ const MAX_REMOTE_FILE_BYTES = 200 * 1024 * 1024;
35
+ /** Stream a device's file straight into the session's outputs area. */
36
+ async function defaultFetchIntoOutputs(a) {
37
+ // Stat first: it is what rejects a bad path or an oversized file before anything is reserved on
38
+ // disk, and it supplies the default display name. The device derives that name with ITS own path
39
+ // rules — basename() here would mis-split a Windows path on a Linux server.
40
+ const stat = await prepareRemoteFetch({
41
+ device: a.device, filePath: a.filePath, maxBytes: MAX_REMOTE_FILE_BYTES,
42
+ });
43
+ return receiveIntoOutputs({ sessionId: a.sessionId, fileName: a.fileName || stat.name }, destPath => fetchRemoteFile({ device: a.device, filePath: a.filePath, destPath, stat }).then(() => { }));
44
+ }
31
45
  /**
32
46
  * Deliver a file into a web chat session as an agent-sent attachment (20a). Copies the file into the
33
47
  * session's outputs area, records an assistant message carrying the attachment (persisted, so it is
@@ -37,10 +51,15 @@ export function classifyAttachment(mimeType) {
37
51
  */
38
52
  export async function sendAgentFile(args, deps = {}) {
39
53
  const copy = deps.copyIntoOutputs ?? copyFileIntoOutputs;
54
+ const fetchIn = deps.fetchIntoOutputs ?? defaultFetchIntoOutputs;
40
55
  const append = deps.appendAssistant ?? ((sid, o) => conversationHistory.appendAssistant(sid, o));
41
56
  const publish = deps.publish ?? publishSessionMessage;
42
57
  const now = deps.now ?? (() => new Date().toISOString());
43
- const { relPath, name, size } = await copy({ sessionId: args.sessionId, filePath: args.filePath, fileName: args.fileName });
58
+ // Only the source of the bytes differs. Once the file is in the outputs area, a device's file is
59
+ // an ordinary attachment — same card, same download endpoint, same transcript row.
60
+ const { relPath, name, size } = args.device
61
+ ? await fetchIn({ sessionId: args.sessionId, device: args.device, filePath: args.filePath, fileName: args.fileName })
62
+ : await copy({ sessionId: args.sessionId, filePath: args.filePath, fileName: args.fileName });
44
63
  const mimeType = extToMime(name);
45
64
  const meta = { name, path: relPath, size, mimeType, type: classifyAttachment(mimeType) };
46
65
  const ts = now();
@@ -1,9 +1,10 @@
1
- import type { PlatformAdapter, DownloadedFile, IncomingMessage } from '../platform/index.js';
1
+ import type { PlatformAdapter, IncomingMessage } from '../platform/index.js';
2
2
  import { persistSessionContextUsage, type SessionContextUsagePersistenceDeps } from './transcript-sink.js';
3
+ import { type InboundFiles } from './routing/file-handler.js';
3
4
  import { type TurnMutationRelease } from './turn-mutation-lock.js';
4
5
  type Enqueuer = (channel: string, fn: () => Promise<void>) => boolean;
5
6
  type Tracker = (delta: number) => void;
6
- type PlatformFileLoader = () => Promise<DownloadedFile[]>;
7
+ type PlatformFileLoader = () => Promise<InboundFiles>;
7
8
  type Executor = (ctx: AgentRunnerCtx, mutationRelease: TurnMutationRelease, loadPlatformFiles: PlatformFileLoader) => Promise<void>;
8
9
  /** Attempt mid-turn injection; true ⇒ the message was delivered into the live turn and must NOT
9
10
  * be queued. Injectable so the routing branch is testable without a live backend. */
@@ -20,11 +20,9 @@ import { prepareConversationRequest } from './conversation-request.js';
20
20
  import { openTurn, buildInjectDeps, recordHistory } from './turn/turn.js';
21
21
  import { acquireSessionUseLease, acquireTurnBrowser, collectTurnFiles, releaseTurnBrowser, } from './turn/turn-prep.js';
22
22
  import { tryConsume as tryHumanAnswerBackstop } from './human-answer-backstop.js';
23
- import { downloadFiles as downloadPlatformFiles } from './routing/file-handler.js';
24
- import { WORKSPACE_DIR } from '../core/utils.js';
23
+ import { downloadFiles as downloadPlatformFiles, inboundAttachmentKey, } from './routing/file-handler.js';
25
24
  import { acquireTurnMutationLock } from './turn-mutation-lock.js';
26
25
  const log = createLogger('agent-runner');
27
- const TEMP_DIR = WORKSPACE_DIR;
28
26
  export class AgentRunner {
29
27
  _enqueue;
30
28
  _track;
@@ -120,9 +118,10 @@ export class AgentRunner {
120
118
  ...(ctx.message.systemOrigin ? { systemOrigin: ctx.message.systemOrigin } : {}),
121
119
  messageId: ctx.message.ref.messageId,
122
120
  attachments: ctx.message.webAttachments,
123
- prepareBackendAttachments: async () => (await loadPlatformFiles()).map((file) => ({
121
+ prepareBackendAttachments: async () => (await loadPlatformFiles()).files.map((file) => ({
124
122
  mimeType: file.mimetype,
125
123
  path: file.localPath,
124
+ name: file.name,
126
125
  })),
127
126
  });
128
127
  }
@@ -144,7 +143,7 @@ export class AgentRunner {
144
143
  */
145
144
  async _executeReal(ctx, mutationRelease, loadPlatformFiles) {
146
145
  const { message, channel, adapter, threadAnchorId, userMessage, agentMessage } = ctx;
147
- const allFiles = await collectTurnFiles(message, loadPlatformFiles);
146
+ const turnFiles = await collectTurnFiles(message, loadPlatformFiles);
148
147
  const startTime = Date.now();
149
148
  const backend = resolveBackendForChannel(channel);
150
149
  let sessionId = await getSessionAsync(channel);
@@ -195,7 +194,7 @@ export class AgentRunner {
195
194
  session: { sessionId, sessionName, backendSessionId, projectId, lease: sessionLease },
196
195
  user: {
197
196
  text: userMessage || '',
198
- attachments: message.webAttachments,
197
+ attachments: mergeAttachments(message.webAttachments, turnFiles.platformAttachments),
199
198
  ...(message.systemOrigin ? { systemOrigin: message.systemOrigin } : {}),
200
199
  },
201
200
  ledger: { userMessageTs: message.ref.messageId },
@@ -213,7 +212,8 @@ export class AgentRunner {
213
212
  },
214
213
  channel,
215
214
  userMessage: agentMessage,
216
- files: allFiles,
215
+ files: turnFiles.files,
216
+ failedFiles: turnFiles.failures,
217
217
  trigger: 'user',
218
218
  browserCdpEndpoint: browser.cdpEndpoint,
219
219
  commissionMode: !!sessionCommissionId,
@@ -230,6 +230,11 @@ export class AgentRunner {
230
230
  }
231
231
  export const agentRunner = new AgentRunner();
232
232
  // --- Helpers ---
233
+ /** Web uploads and platform downloads share one attachment list on the user's transcript row. */
234
+ function mergeAttachments(web, platform) {
235
+ const merged = [...(web ?? []), ...(platform ?? [])];
236
+ return merged.length > 0 ? merged : undefined;
237
+ }
233
238
  // Moved to transcript-sink.ts (the one transcript observer). Re-exported here so the existing
234
239
  // agent-runner tests and importers keep their import path.
235
240
  export { persistSessionContextUsage };
@@ -241,12 +246,12 @@ export { resolveDefaultAgent, resolveSessionName } from './turn/turn-prep.js';
241
246
  function createPlatformFileLoader(ctx) {
242
247
  let pending = null;
243
248
  return () => {
244
- pending ??= downloadFiles(ctx.message.files, ctx.hasFiles, ctx.adapter);
249
+ pending ??= downloadFiles(ctx.message, ctx.hasFiles, ctx.adapter);
245
250
  return pending;
246
251
  };
247
252
  }
248
- async function downloadFiles(files, hasFiles, adapter) {
249
- if (!hasFiles || !files)
250
- return [];
251
- return downloadPlatformFiles(files, adapter, TEMP_DIR);
253
+ async function downloadFiles(message, hasFiles, adapter) {
254
+ if (!hasFiles || !message.files)
255
+ return { files: [], failures: [] };
256
+ return downloadPlatformFiles(message.files, adapter, inboundAttachmentKey(message));
252
257
  }
@@ -0,0 +1,31 @@
1
+ import type { DownloadedFile } from '../platform/types.js';
2
+ import type { AttachmentMeta } from '../domain/ui-service/types.js';
3
+ /** Physical directory backing the UI-relative `workspace/attachments/` prefix. */
4
+ export declare const ATTACHMENTS_DIR: string;
5
+ export declare function inboundAttachmentDir(key: string): string;
6
+ export declare function prepareInboundAttachmentDir(key: string): Promise<string>;
7
+ /** The UI-relative `workspace/…` alias for a path inside the workspace, or null when it is outside
8
+ * (a TUI attachment is the user's own file, referenced where it already lives). */
9
+ export declare function workspaceRelPath(absPath: string): string | null;
10
+ /**
11
+ * Settle a freshly downloaded file: believe its bytes over its metadata, and store it under the
12
+ * name the user sent it as.
13
+ *
14
+ * Only files the adapter wrote into `ownedDir` are renamed — an adapter that hands back a
15
+ * reference to a file it does not own (the TUI passes the user's own path through) keeps its
16
+ * location, and only its mimetype is corrected.
17
+ */
18
+ export declare function finalizeInboundFile(file: DownloadedFile, ownedDir: string): Promise<DownloadedFile>;
19
+ /**
20
+ * Delete inbound attachment directories older than `maxAgeDays`.
21
+ *
22
+ * Age, not liveness: an attachment is read during the turn it arrives on (the backend is handed a
23
+ * path, and it reads the file within that turn), so nothing that matters is still pending days
24
+ * later. Only the per-message directories this module creates are swept — `<sessionId>/` uploads
25
+ * from the web composer are the UI's to keep, since its file cards link to them for as long as the
26
+ * transcript lives.
27
+ */
28
+ export declare function pruneInboundAttachments(maxAgeDays: number, now?: () => number): Promise<number>;
29
+ /** The transcript card for an inbound attachment, or null for a file stored outside the workspace
30
+ * (the UI serves `workspace/…` paths only, so a TUI passthrough has nothing to link to). */
31
+ export declare function inboundAttachmentMeta(file: DownloadedFile): Promise<AttachmentMeta | null>;
@@ -0,0 +1,184 @@
1
+ // input: a file a platform adapter has just written into a directory this module owns
2
+ // output: that file under `workspace/attachments/<inbound key>/`, named after what the user sent
3
+ // it as, typed by what its bytes actually are — plus the age sweep that reclaims the space
4
+ // pos: orchestration — the inbound half of `outputs-store.ts` (which owns the agent-sent
5
+ // `workspace/outputs/` side) and the server-side twin of the web upload route, which
6
+ // stores composer uploads under `workspace/attachments/<sessionId>/`. Platform downloads
7
+ // used to land flat in WORKSPACE_DIR's root under their opaque platform id
8
+ // (`img_v3_02n4….png`), mixed in with agent scratch, never cleaned, and with the user's
9
+ // own filename dropped on the floor.
10
+ import * as path from 'path';
11
+ import { promises as fs } from 'fs';
12
+ import { WORKSPACE_DIR } from '../core/paths.js';
13
+ import { imageMimeExtension, sniffImageMime } from '../core/media-types.js';
14
+ import { createLogger } from '../core/log.js';
15
+ import { sanitizeDisplayFilename, sanitizeStorageFilename } from './outputs-store.js';
16
+ import { classifyAttachment, extToMime } from './agent-file-send.js';
17
+ const log = createLogger('attachments-store');
18
+ /** Physical directory backing the UI-relative `workspace/attachments/` prefix. */
19
+ export const ATTACHMENTS_DIR = path.join(WORKSPACE_DIR, 'attachments');
20
+ /** Bytes read to identify a file's real type. */
21
+ const SNIFF_BYTES = 16;
22
+ /** Marks the directories this module owns. A web composer upload lands under a bare `<sessionId>`
23
+ * in the same root and its files are linked from the transcript forever, so the age sweep must be
24
+ * able to tell the two apart by name alone. */
25
+ const INBOUND_PREFIX = 'in-';
26
+ /** One inbound message's own directory, so two files of the same name cannot collide across
27
+ * messages and the whole set can be reclaimed as a unit. */
28
+ function inboundDirName(key) {
29
+ const safe = key.replace(/[^A-Za-z0-9._-]/g, '-').replace(/^[.-]+/, '').slice(0, 120);
30
+ return `${INBOUND_PREFIX}${safe || 'message'}`;
31
+ }
32
+ export function inboundAttachmentDir(key) {
33
+ return path.join(ATTACHMENTS_DIR, inboundDirName(key));
34
+ }
35
+ export async function prepareInboundAttachmentDir(key) {
36
+ const dir = inboundAttachmentDir(key);
37
+ await fs.mkdir(dir, { recursive: true });
38
+ return dir;
39
+ }
40
+ /** The UI-relative `workspace/…` alias for a path inside the workspace, or null when it is outside
41
+ * (a TUI attachment is the user's own file, referenced where it already lives). */
42
+ export function workspaceRelPath(absPath) {
43
+ const root = path.resolve(WORKSPACE_DIR);
44
+ const resolved = path.resolve(absPath);
45
+ if (!resolved.startsWith(root + path.sep))
46
+ return null;
47
+ return `workspace/${path.relative(root, resolved).split(path.sep).join('/')}`;
48
+ }
49
+ /** Find an available filename in `dir`: on collision try `name_1`, `name_2`, … */
50
+ async function availablePath(dir, base) {
51
+ const extIdx = base.lastIndexOf('.');
52
+ const stem = extIdx > 0 ? base.slice(0, extIdx) : base;
53
+ const ext = extIdx > 0 ? base.slice(extIdx) : '';
54
+ let candidate = base;
55
+ let counter = 0;
56
+ for (;;) {
57
+ const p = path.join(dir, candidate);
58
+ try {
59
+ await fs.access(p);
60
+ counter++;
61
+ candidate = `${stem}_${counter}${ext}`;
62
+ }
63
+ catch {
64
+ return p;
65
+ }
66
+ }
67
+ }
68
+ /** The storage name for a download: the user's filename, ASCII-folded, re-extensioned when the
69
+ * bytes disagree with what it claimed to be. The Unicode original travels on `DownloadedFile.name`
70
+ * and reaches the model through the prompt and the UI through the attachment card. */
71
+ function storageName(displayName, sniffed) {
72
+ const base = sanitizeStorageFilename(displayName);
73
+ const wantExt = sniffed ? imageMimeExtension(sniffed) : null;
74
+ if (!wantExt)
75
+ return base;
76
+ const ext = path.extname(base).toLowerCase();
77
+ if (ext === wantExt || (wantExt === '.jpg' && ext === '.jpeg'))
78
+ return base;
79
+ const stem = ext ? base.slice(0, -ext.length) : base;
80
+ return `${stem || 'file'}${wantExt}`;
81
+ }
82
+ async function sniffFile(filePath) {
83
+ let handle;
84
+ try {
85
+ handle = await fs.open(filePath, 'r');
86
+ const buf = Buffer.alloc(SNIFF_BYTES);
87
+ const { bytesRead } = await handle.read(buf, 0, SNIFF_BYTES, 0);
88
+ return sniffImageMime(buf.subarray(0, bytesRead));
89
+ }
90
+ catch {
91
+ return null;
92
+ }
93
+ finally {
94
+ await handle?.close().catch(() => undefined);
95
+ }
96
+ }
97
+ /**
98
+ * Settle a freshly downloaded file: believe its bytes over its metadata, and store it under the
99
+ * name the user sent it as.
100
+ *
101
+ * Only files the adapter wrote into `ownedDir` are renamed — an adapter that hands back a
102
+ * reference to a file it does not own (the TUI passes the user's own path through) keeps its
103
+ * location, and only its mimetype is corrected.
104
+ */
105
+ export async function finalizeInboundFile(file, ownedDir) {
106
+ const displayName = sanitizeDisplayFilename(file.name || path.basename(file.localPath));
107
+ const sniffed = await sniffFile(file.localPath);
108
+ // Bytes first, then what the platform said, then the name — Feishu hands a `file` message over
109
+ // with no mimetype at all, and an empty string reaches the UI as an undownloadable card.
110
+ const mimetype = sniffed ?? (file.mimetype || extToMime(displayName));
111
+ const owned = path.resolve(path.dirname(file.localPath)) === path.resolve(ownedDir);
112
+ if (!owned)
113
+ return { localPath: file.localPath, mimetype, name: displayName };
114
+ const target = await availablePath(ownedDir, storageName(displayName, sniffed));
115
+ if (path.resolve(target) !== path.resolve(file.localPath)) {
116
+ try {
117
+ await fs.rename(file.localPath, target);
118
+ }
119
+ catch (error) {
120
+ log.warn(`could not rename ${file.localPath}: ${error.message}`);
121
+ return { localPath: file.localPath, mimetype, name: displayName };
122
+ }
123
+ }
124
+ return { localPath: target, mimetype, name: displayName };
125
+ }
126
+ /**
127
+ * Delete inbound attachment directories older than `maxAgeDays`.
128
+ *
129
+ * Age, not liveness: an attachment is read during the turn it arrives on (the backend is handed a
130
+ * path, and it reads the file within that turn), so nothing that matters is still pending days
131
+ * later. Only the per-message directories this module creates are swept — `<sessionId>/` uploads
132
+ * from the web composer are the UI's to keep, since its file cards link to them for as long as the
133
+ * transcript lives.
134
+ */
135
+ export async function pruneInboundAttachments(maxAgeDays, now = Date.now) {
136
+ if (!(maxAgeDays > 0))
137
+ return 0;
138
+ const cutoff = now() - maxAgeDays * 24 * 60 * 60 * 1000;
139
+ let removed = 0;
140
+ let entries;
141
+ try {
142
+ entries = await fs.readdir(ATTACHMENTS_DIR);
143
+ }
144
+ catch {
145
+ return 0;
146
+ }
147
+ for (const entry of entries) {
148
+ if (!entry.startsWith(INBOUND_PREFIX))
149
+ continue;
150
+ const dir = path.join(ATTACHMENTS_DIR, entry);
151
+ try {
152
+ const stat = await fs.stat(dir);
153
+ if (!stat.isDirectory() || stat.mtimeMs >= cutoff)
154
+ continue;
155
+ await fs.rm(dir, { recursive: true, force: true });
156
+ removed++;
157
+ }
158
+ catch (error) {
159
+ log.warn(`could not prune ${dir}: ${error.message}`);
160
+ }
161
+ }
162
+ return removed;
163
+ }
164
+ /** The transcript card for an inbound attachment, or null for a file stored outside the workspace
165
+ * (the UI serves `workspace/…` paths only, so a TUI passthrough has nothing to link to). */
166
+ export async function inboundAttachmentMeta(file) {
167
+ const relPath = workspaceRelPath(file.localPath);
168
+ if (!relPath)
169
+ return null;
170
+ let size = 0;
171
+ try {
172
+ size = (await fs.stat(file.localPath)).size;
173
+ }
174
+ catch {
175
+ return null;
176
+ }
177
+ return {
178
+ name: file.name || path.basename(file.localPath),
179
+ path: relPath,
180
+ size,
181
+ mimeType: file.mimetype,
182
+ type: classifyAttachment(file.mimetype),
183
+ };
184
+ }
@@ -1,4 +1,5 @@
1
1
  import type { DownloadedFile } from '../platform/index.js';
2
+ import type { AttachmentFailure } from './routing/file-handler.js';
2
3
  import { projectStore } from '../domain/projects/index.js';
3
4
  import { loadCommissionDraftContext, loadCommissionPromptContext, type CommissionPromptContext } from '../domain/commissions/commission-context.js';
4
5
  import type { RunRequest } from '../domain/runs/request.js';
@@ -20,6 +21,9 @@ export interface PrepareConversationRequestOptions {
20
21
  /** The raw user message (without the default agent's directive). */
21
22
  userMessage: string;
22
23
  files: DownloadedFile[];
24
+ /** Attachments the platform refused to hand over; named in the prompt so the agent cannot
25
+ * answer as though the user had sent nothing. */
26
+ failedFiles?: AttachmentFailure[];
23
27
  /** Execution trigger; defaults to 'user'. Scheduled session-target dispatch passes 'scheduled'. */
24
28
  trigger?: string;
25
29
  scheduleTaskId?: string | null;
@@ -20,10 +20,12 @@ import { projectStore } from '../domain/projects/index.js';
20
20
  import { loadCommissionDraftContext, loadCommissionPromptContext, } from '../domain/commissions/commission-context.js';
21
21
  import { sessionStore } from '../store/session-registry-repo.js';
22
22
  import { getSettings } from '../core/settings.js';
23
- import { buildPrompt as buildAgentPrompt } from '../agent-adapter/normalize/prompt-builder.js';
24
- function buildBackendPrompt(prompt, files) {
25
- const attachments = files.map((file) => ({ mimeType: file.mimetype, path: file.localPath }));
26
- return buildAgentPrompt(prompt, attachments);
23
+ import { buildPrompt as buildAgentPrompt, formatAttachmentFailures, } from '../agent-adapter/normalize/prompt-builder.js';
24
+ function buildBackendPrompt(prompt, files, failures = []) {
25
+ const attachments = files.map((file) => ({
26
+ mimeType: file.mimetype, path: file.localPath, name: file.name,
27
+ }));
28
+ return buildAgentPrompt(prompt, attachments, failures);
27
29
  }
28
30
  /**
29
31
  * Whether the surface wants a background hold. The conversation path never waits inline, so both
@@ -134,7 +136,7 @@ export async function prepareConversationRequest(opts) {
134
136
  // A plain conversation turn is thread-free: no artifact, no previous step, no control-plane
135
137
  // preamble. Everything it does carry is a first-turn ambient block, and the two prompt-shaping
136
138
  // fields come from the very spec the run is opened with — one description of the agent, not two.
137
- const prompt = composeUserPrompt(spec, opts.userMessage, {
139
+ const composedPrompt = composeUserPrompt(spec, opts.userMessage, {
138
140
  userContext: userProfileBlock(isFreshSession),
139
141
  // Web UI direct sessions are bound to a project at create time; tell the agent which one
140
142
  // on the session's first turn (see resolveConversationProject for the exact gating).
@@ -143,6 +145,9 @@ export async function prepareConversationRequest(opts) {
143
145
  // binding rather than once per session (see resolveConversationCommission).
144
146
  commission: await resolveConversationCommission(sessionId, { isFreshSession }),
145
147
  });
148
+ // The backend composes the real prompt from `prompt.text` + `prompt.attachments`, so a download
149
+ // failure has to ride the TEXT to reach the model — `backendPrompt` below is the debug echo.
150
+ const prompt = `${formatAttachmentFailures(opts.failedFiles ?? [])}${composedPrompt}`;
146
151
  const backendPrompt = buildBackendPrompt(prompt, opts.files);
147
152
  opts.onPromptBuilt?.(backendPrompt);
148
153
  // Attribute cost/execution to the session's bound project (from the registry record), NOT a
@@ -178,7 +183,9 @@ export async function prepareConversationRequest(opts) {
178
183
  spec,
179
184
  prompt: {
180
185
  text: prompt,
181
- attachments: (opts.files || []).map((file) => ({ mimeType: file.mimetype, path: file.localPath })),
186
+ attachments: (opts.files || []).map((file) => ({
187
+ mimeType: file.mimetype, path: file.localPath, name: file.name,
188
+ })),
182
189
  },
183
190
  context: {
184
191
  channel: opts.channel,
@@ -1,7 +1,7 @@
1
1
  // input: EventBus
2
2
  // output: PendingPlan type and PlanApprovals state
3
3
  // pos: Tracks request-keyed plan approvals
4
- // >>> If updated, update this header and folder CORTEX.md <<<
4
+ // >>> If updated, update this header and folder AGENTS.md <<<
5
5
  export class PlanApprovals {
6
6
  _map = new Map();
7
7
  _bus = null;
@@ -22,6 +22,17 @@ export declare function copyFileIntoOutputs(a: {
22
22
  subdir?: string;
23
23
  maxBytes?: number;
24
24
  }): Promise<StoredOutput>;
25
+ /**
26
+ * Land a file whose bytes are produced by `receive` (a remote-device transfer) directly in the
27
+ * outputs area. Same placement and naming as `copyFileIntoOutputs`, but written once: staging to a
28
+ * temp file first and copying would double the I/O of every large transfer and leave litter behind
29
+ * when a send fails. A failing `receive` must leave nothing, so the reservation is removed here.
30
+ */
31
+ export declare function receiveIntoOutputs(a: {
32
+ sessionId: string;
33
+ fileName: string;
34
+ subdir?: string;
35
+ }, receive: (destPath: string) => Promise<void>): Promise<StoredOutput>;
25
36
  /** Write agent-authored text into the session's outputs area under `fileName`, same placement and
26
37
  * naming discipline as `copyFileIntoOutputs`. Used when the payload arrives inline rather than as
27
38
  * a path on disk. */