@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
@@ -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,10 @@ 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';
25
+ import { isRebuildHeld, refuseTurnForRebuild } from '../domain/system/rebuild-hold.js';
26
26
  const log = createLogger('agent-runner');
27
- const TEMP_DIR = WORKSPACE_DIR;
28
27
  export class AgentRunner {
29
28
  _enqueue;
30
29
  _track;
@@ -51,6 +50,21 @@ export class AgentRunner {
51
50
  }
52
51
  async _routeWithAdmission(ctx, mutationRelease, loadPlatformFiles) {
53
52
  const { message, channel, adapter } = ctx;
53
+ // The supervisor is rebuilding or replacing this process (entry/daemon-notice.ts pushes the
54
+ // hold). A turn admitted now spawns a backend CLI whose stdout owner is about to be SIGTERMed:
55
+ // the CLI finishes, writes into a pipe nobody reads, and the turn hangs at "processing" forever
56
+ // (2026-09-21). Refused first, before anything is tracked, marked, leased or injected — a
57
+ // message folded into a turn that is about to die is lost just as thoroughly.
58
+ if (isRebuildHeld()) {
59
+ log.info(`Refusing turn on ${channel}: supervisor rebuild in progress`);
60
+ await refuseTurnForRebuild({
61
+ adapter,
62
+ channel,
63
+ text: ctx.userMessage || '',
64
+ interactive: message.senderId !== SYNTHETIC_CALLBACK_SENDER && !message.systemOrigin,
65
+ });
66
+ return false;
67
+ }
54
68
  // DR-0016 top-level fallback: if this channel has a pending human-escalated subtask question,
55
69
  // consume this message as the answer and short-circuit normal turn handling. Scope is narrow —
56
70
  // the backstop is disarmed unless this exact channel is awaiting a human reply, and it is armed
@@ -120,9 +134,10 @@ export class AgentRunner {
120
134
  ...(ctx.message.systemOrigin ? { systemOrigin: ctx.message.systemOrigin } : {}),
121
135
  messageId: ctx.message.ref.messageId,
122
136
  attachments: ctx.message.webAttachments,
123
- prepareBackendAttachments: async () => (await loadPlatformFiles()).map((file) => ({
137
+ prepareBackendAttachments: async () => (await loadPlatformFiles()).files.map((file) => ({
124
138
  mimeType: file.mimetype,
125
139
  path: file.localPath,
140
+ name: file.name,
126
141
  })),
127
142
  });
128
143
  }
@@ -144,7 +159,7 @@ export class AgentRunner {
144
159
  */
145
160
  async _executeReal(ctx, mutationRelease, loadPlatformFiles) {
146
161
  const { message, channel, adapter, threadAnchorId, userMessage, agentMessage } = ctx;
147
- const allFiles = await collectTurnFiles(message, loadPlatformFiles);
162
+ const turnFiles = await collectTurnFiles(message, loadPlatformFiles);
148
163
  const startTime = Date.now();
149
164
  const backend = resolveBackendForChannel(channel);
150
165
  let sessionId = await getSessionAsync(channel);
@@ -195,7 +210,7 @@ export class AgentRunner {
195
210
  session: { sessionId, sessionName, backendSessionId, projectId, lease: sessionLease },
196
211
  user: {
197
212
  text: userMessage || '',
198
- attachments: message.webAttachments,
213
+ attachments: mergeAttachments(message.webAttachments, turnFiles.platformAttachments),
199
214
  ...(message.systemOrigin ? { systemOrigin: message.systemOrigin } : {}),
200
215
  },
201
216
  ledger: { userMessageTs: message.ref.messageId },
@@ -213,7 +228,8 @@ export class AgentRunner {
213
228
  },
214
229
  channel,
215
230
  userMessage: agentMessage,
216
- files: allFiles,
231
+ files: turnFiles.files,
232
+ failedFiles: turnFiles.failures,
217
233
  trigger: 'user',
218
234
  browserCdpEndpoint: browser.cdpEndpoint,
219
235
  commissionMode: !!sessionCommissionId,
@@ -230,6 +246,11 @@ export class AgentRunner {
230
246
  }
231
247
  export const agentRunner = new AgentRunner();
232
248
  // --- Helpers ---
249
+ /** Web uploads and platform downloads share one attachment list on the user's transcript row. */
250
+ function mergeAttachments(web, platform) {
251
+ const merged = [...(web ?? []), ...(platform ?? [])];
252
+ return merged.length > 0 ? merged : undefined;
253
+ }
233
254
  // Moved to transcript-sink.ts (the one transcript observer). Re-exported here so the existing
234
255
  // agent-runner tests and importers keep their import path.
235
256
  export { persistSessionContextUsage };
@@ -241,12 +262,12 @@ export { resolveDefaultAgent, resolveSessionName } from './turn/turn-prep.js';
241
262
  function createPlatformFileLoader(ctx) {
242
263
  let pending = null;
243
264
  return () => {
244
- pending ??= downloadFiles(ctx.message.files, ctx.hasFiles, ctx.adapter);
265
+ pending ??= downloadFiles(ctx.message, ctx.hasFiles, ctx.adapter);
245
266
  return pending;
246
267
  };
247
268
  }
248
- async function downloadFiles(files, hasFiles, adapter) {
249
- if (!hasFiles || !files)
250
- return [];
251
- return downloadPlatformFiles(files, adapter, TEMP_DIR);
269
+ async function downloadFiles(message, hasFiles, adapter) {
270
+ if (!hasFiles || !message.files)
271
+ return { files: [], failures: [] };
272
+ return downloadPlatformFiles(message.files, adapter, inboundAttachmentKey(message));
252
273
  }
@@ -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,7 +1,9 @@
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';
6
+ import type { AgentSlotConfig } from '../core/types/thread-types.js';
5
7
  /** The ids the caller has already resolved for this turn. Mirrors the plan's `prepareRequest(ids)`
6
8
  * shape: everything else on {@link PrepareConversationRequestOptions} is per-surface turn input. */
7
9
  export interface ConversationSessionIds {
@@ -20,6 +22,9 @@ export interface PrepareConversationRequestOptions {
20
22
  /** The raw user message (without the default agent's directive). */
21
23
  userMessage: string;
22
24
  files: DownloadedFile[];
25
+ /** Attachments the platform refused to hand over; named in the prompt so the agent cannot
26
+ * answer as though the user had sent nothing. */
27
+ failedFiles?: AttachmentFailure[];
23
28
  /** Execution trigger; defaults to 'user'. Scheduled session-target dispatch passes 'scheduled'. */
24
29
  trigger?: string;
25
30
  scheduleTaskId?: string | null;
@@ -45,16 +50,48 @@ export interface PreparedRequest {
45
50
  * in history) of a Web UI direct session (`web:` channel — the only path where the user explicitly
46
51
  * binds the session to a project at create time), and only for real user projects (the `general`
47
52
  * umbrella carries no signal). Unknown/deleted project ids inject nothing rather than a dead path.
53
+ * An agent with `projectContext: false` opts out of the block entirely — "record your findings in
54
+ * the project" is operational noise in an environment built for something else.
48
55
  */
49
56
  export declare function resolveConversationProject(args: {
50
57
  channel: string;
51
58
  projectId: string;
52
59
  isFreshSession: boolean;
60
+ projectContext?: boolean;
53
61
  store?: Pick<typeof projectStore, 'get'>;
54
62
  }): {
55
63
  id: string;
56
64
  contextDir: string;
57
65
  } | null;
66
+ /**
67
+ * The policy one conversation turn opens under: the shared direct-run policy, the surface's own
68
+ * background intent, and the execution-environment fields the agent template declares.
69
+ *
70
+ * Every environment default equals what {@link DIRECT_RUN_POLICY} already said, so an agent that
71
+ * declares none of them produces that constant field for field — which is why adding the fields
72
+ * changed no existing session. `skills` and `settingSources` stay `undefined` rather than being
73
+ * defaulted here: absent means "whatever the backend loads on its own", and only the agent that
74
+ * opts out has an opinion.
75
+ */
76
+ export declare function conversationRunPolicy(agentConfig: AgentSlotConfig, opts: {
77
+ channel: string;
78
+ browserCdpEndpoint?: string | null;
79
+ }): RunRequest['policy'];
80
+ /**
81
+ * Which agent — which execution environment — a conversation turn opens under.
82
+ *
83
+ * The chain is the profile chain's twin: the session's own choice (what the composer set, or what
84
+ * `!agent` recorded on the session), then the channel's selection, then the global default, then
85
+ * `main`. `getDefaultAgent(channel)` already folds the middle two together.
86
+ *
87
+ * A candidate that no longer resolves is SKIPPED rather than fatal: an agent renamed or deleted
88
+ * since it was persisted must not kill every turn of the session that named it, exactly as an
89
+ * unknown channel profile falls back instead of throwing (see the run-config resolution below).
90
+ */
91
+ export declare function resolveConversationAgent(candidates: ReadonlyArray<string | null | undefined>, resolve?: (name: string) => AgentSlotConfig | null): {
92
+ agentName: string;
93
+ agentConfig: AgentSlotConfig;
94
+ };
58
95
  /** The delivery key for a session's current commission binding, or null outside the mode. Bound
59
96
  * wins over drafting: finalize clears the draft, and the two are never both meaningful. */
60
97
  export declare function commissionBindingKey(session: {