@cortex-agent/server 2026.9.14 → 2026.9.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (259) hide show
  1. package/README.md +3 -2
  2. package/defaults/config/hooks/08-agents-md-injector-post-tool.json +10 -0
  3. package/defaults/config/hooks/{10-cortex-md-injector-session-start.json → 10-agents-md-injector-session-start.json} +3 -3
  4. package/defaults/config/hooks/{CORTEX.md → AGENTS.md} +2 -2
  5. package/defaults/hooks/{CORTEX.md → AGENTS.md} +1 -1
  6. package/defaults/hooks/{cortex-md-injector.mjs → agents-md-injector.mjs} +117 -26
  7. package/defaults/hooks/cortex-hook-api.mjs +2 -2
  8. package/defaults/hooks/new-session-hook.mjs +2 -2
  9. package/defaults/hooks/rules-loader.mjs +2 -2
  10. package/defaults/hooks/status-md-guard.mjs +8 -8
  11. package/defaults/hooks/task-status-check.mjs +18 -76
  12. package/defaults/hooks/tasks-yaml-guard.mjs +2 -2
  13. package/defaults/plugins/cortex-commission/.claude-plugin/plugin.json +2 -2
  14. package/defaults/plugins/cortex-commission/plugin.json +2 -2
  15. package/defaults/plugins/cortex-commission/skills/commission/SKILL.md +3 -3
  16. package/defaults/plugins/cortex-feishu/skills/feishu-doc/SKILL.md +1 -1
  17. package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +2 -2
  18. package/defaults/plugins/cortex-system/skills/project-init/SKILL.md +4 -4
  19. package/defaults/plugins/cortex-system/skills/task/SKILL.md +1 -1
  20. package/defaults/rules/{cortex-md.md → agents-md.md} +4 -4
  21. package/defaults/rules/decision-records.md +1 -1
  22. package/defaults/rules/meta-conventions.md +4 -4
  23. package/defaults/rules/mission-md.md +1 -1
  24. package/dist/agent-adapter/claude/adapter.d.ts +0 -6
  25. package/dist/agent-adapter/claude/adapter.js +0 -8
  26. package/dist/agent-adapter/claude/defaults.d.ts +10 -7
  27. package/dist/agent-adapter/claude/defaults.js +18 -16
  28. package/dist/agent-adapter/claude/hooks-builder.js +2 -2
  29. package/dist/agent-adapter/claude/spawn-args.d.ts +0 -3
  30. package/dist/agent-adapter/claude/spawn-args.js +20 -16
  31. package/dist/agent-adapter/claude/turn-machine.d.ts +11 -0
  32. package/dist/agent-adapter/claude/turn-machine.js +46 -5
  33. package/dist/agent-adapter/normalize/prompt-builder.d.ts +16 -1
  34. package/dist/agent-adapter/normalize/prompt-builder.js +24 -6
  35. package/dist/agent-adapter/pi/mcp-bridge-logic.d.ts +11 -2
  36. package/dist/agent-adapter/pi/mcp-bridge-logic.js +32 -1
  37. package/dist/agent-adapter/pi/mcp-bridge.js +16 -15
  38. package/dist/agent-adapter/pi/session-options.d.ts +0 -6
  39. package/dist/agent-adapter/pi/session-options.js +1 -8
  40. package/dist/agent-adapter/types.d.ts +1 -1
  41. package/dist/core/mcp-tool-gate.d.ts +3 -17
  42. package/dist/core/mcp-tool-gate.js +4 -19
  43. package/dist/core/media-types.d.ts +10 -0
  44. package/dist/core/media-types.js +34 -0
  45. package/dist/core/platform-settings-spec.js +1 -1
  46. package/dist/core/settings-spec.d.ts +22 -1
  47. package/dist/core/settings-spec.js +33 -2
  48. package/dist/core/types/agent-types.d.ts +3 -1
  49. package/dist/core/utils.d.ts +1 -1
  50. package/dist/core/utils.js +1 -1
  51. package/dist/domain/agents/config.d.ts +1 -1
  52. package/dist/domain/agents/config.js +1 -1
  53. package/dist/domain/agents/profile-switch.d.ts +1 -1
  54. package/dist/domain/agents/profile-switch.js +3 -5
  55. package/dist/domain/agents/subagent/runner.js +0 -1
  56. package/dist/domain/commissions/commission-draft.d.ts +58 -0
  57. package/dist/domain/commissions/commission-draft.js +87 -4
  58. package/dist/domain/commissions/commission-finalize.d.ts +8 -3
  59. package/dist/domain/commissions/commission-finalize.js +14 -0
  60. package/dist/domain/executions/registry.d.ts +1 -2
  61. package/dist/domain/executions/registry.js +0 -3
  62. package/dist/domain/mcp/bundled-server.js +4 -3
  63. package/dist/domain/mcp/feishu/file.js +37 -18
  64. package/dist/domain/mcp/feishu/types.d.ts +3 -0
  65. package/dist/domain/mcp/feishu-server.js +1 -1
  66. package/dist/domain/mcp/tools/{cortex-md.d.ts → agents-md.d.ts} +6 -6
  67. package/dist/domain/mcp/tools/{cortex-md.js → agents-md.js} +6 -6
  68. package/dist/domain/mcp/tools/commission-tools.d.ts +12 -1
  69. package/dist/domain/mcp/tools/commission-tools.js +68 -14
  70. package/dist/domain/mcp/tools/remote-file.d.ts +20 -0
  71. package/dist/domain/mcp/tools/remote-file.js +44 -0
  72. package/dist/domain/mcp/tools/slack.d.ts +2 -0
  73. package/dist/domain/mcp/tools/slack.js +22 -7
  74. package/dist/domain/mcp/tools/task-ops.js +5 -13
  75. package/dist/domain/mcp/tools/ui-file.js +23 -10
  76. package/dist/domain/mcp/tools/waitpoint.d.ts +3 -0
  77. package/dist/domain/mcp/tools/waitpoint.js +122 -0
  78. package/dist/domain/memory/agents-md-injector.d.ts +24 -0
  79. package/dist/domain/memory/{cortex-md-injector.js → agents-md-injector.js} +10 -7
  80. package/dist/domain/projects/project-store.d.ts +1 -1
  81. package/dist/domain/projects/project-store.js +3 -3
  82. package/dist/domain/remote/client-hot-reload.js +3 -1
  83. package/dist/domain/remote/client-manager.js +105 -126
  84. package/dist/domain/remote/client-ssh-tunnel.d.ts +16 -5
  85. package/dist/domain/remote/client-ssh-tunnel.js +12 -5
  86. package/dist/domain/remote/cortex-client-config.d.ts +1 -1
  87. package/dist/domain/remote/cortex-client-config.js +1 -1
  88. package/dist/domain/remote/device-file.d.ts +51 -0
  89. package/dist/domain/remote/device-file.js +193 -0
  90. package/dist/domain/remote/device-port.js +3 -0
  91. package/dist/domain/remote/reverse-stream.d.ts +18 -7
  92. package/dist/domain/remote/reverse-stream.js +19 -6
  93. package/dist/domain/runs/builders.js +0 -1
  94. package/dist/domain/runs/compact.js +0 -1
  95. package/dist/domain/runs/engine-spec.d.ts +11 -4
  96. package/dist/domain/runs/engine-spec.js +7 -4
  97. package/dist/domain/runs/prompt.js +16 -10
  98. package/dist/domain/runs/request.d.ts +0 -1
  99. package/dist/domain/sessions/session-hooks.d.ts +5 -12
  100. package/dist/domain/sessions/session-hooks.js +6 -13
  101. package/dist/domain/sessions/session-lifecycle.d.ts +4 -4
  102. package/dist/domain/sessions/session-lifecycle.js +5 -6
  103. package/dist/domain/sessions/session-retention.d.ts +1 -3
  104. package/dist/domain/sessions/session-retention.js +9 -26
  105. package/dist/domain/sessions/session-use.d.ts +32 -0
  106. package/dist/domain/sessions/session-use.js +63 -0
  107. package/dist/domain/sessions/session.js +6 -5
  108. package/dist/domain/system/server-update-check.js +29 -1
  109. package/dist/domain/system/update-ui-state.d.ts +32 -0
  110. package/dist/domain/system/update-ui-state.js +63 -0
  111. package/dist/domain/tasks/claim-recovery.js +2 -2
  112. package/dist/domain/tasks/dispatch-utils.d.ts +10 -1
  113. package/dist/domain/tasks/dispatch-utils.js +46 -1
  114. package/dist/domain/tasks/dispatcher.js +4 -5
  115. package/dist/domain/tasks/mutator.d.ts +2 -2
  116. package/dist/domain/tasks/mutator.js +2 -2
  117. package/dist/domain/tasks/system/task-cli.js +2 -2
  118. package/dist/domain/tasks/system/task-state.js +1 -1
  119. package/dist/domain/threads/runner.js +3 -2
  120. package/dist/domain/ui-service/app-router.d.ts +54 -3
  121. package/dist/domain/ui-service/app-router.js +12 -14
  122. package/dist/domain/ui-service/input-schemas.d.ts +49 -5
  123. package/dist/domain/ui-service/input-schemas.js +35 -9
  124. package/dist/domain/ui-service/mutate/platform-settings.js +1 -1
  125. package/dist/domain/ui-service/mutate/sessions.d.ts +17 -1
  126. package/dist/domain/ui-service/mutate/sessions.js +83 -3
  127. package/dist/domain/ui-service/mutate/system.d.ts +3 -1
  128. package/dist/domain/ui-service/mutate/system.js +13 -0
  129. package/dist/domain/ui-service/mutate/waitpoints.d.ts +2 -0
  130. package/dist/domain/ui-service/mutate/waitpoints.js +20 -0
  131. package/dist/domain/ui-service/platform-settings.js +1 -1
  132. package/dist/domain/ui-service/plugins-shared.js +1 -1
  133. package/dist/domain/ui-service/query/config.js +1 -1
  134. package/dist/domain/ui-service/query/executions.js +0 -2
  135. package/dist/domain/ui-service/query/machine-detail.js +3 -8
  136. package/dist/domain/ui-service/query/memory.js +1 -1
  137. package/dist/domain/ui-service/query/sessions.js +7 -0
  138. package/dist/domain/ui-service/query/system.d.ts +2 -1
  139. package/dist/domain/ui-service/query/system.js +4 -0
  140. package/dist/domain/ui-service/query/threads.js +1 -54
  141. package/dist/domain/ui-service/query/waitpoints.d.ts +30 -0
  142. package/dist/domain/ui-service/query/waitpoints.js +117 -0
  143. package/dist/domain/ui-service/query-input-schemas.d.ts +3 -0
  144. package/dist/domain/ui-service/query-input-schemas.js +3 -0
  145. package/dist/domain/ui-service/trpc.js +1 -1
  146. package/dist/domain/ui-service/types.d.ts +175 -50
  147. package/dist/domain/ui-service/types.js +1 -1
  148. package/dist/domain/ui-service/ui-service.js +13 -33
  149. package/dist/domain/waitpoints/notices.d.ts +21 -0
  150. package/dist/domain/waitpoints/notices.js +115 -0
  151. package/dist/domain/waitpoints/service.d.ts +91 -0
  152. package/dist/domain/waitpoints/service.js +243 -0
  153. package/dist/entry/app.js +39 -29
  154. package/dist/entry/auth-login-cli.js +1 -1
  155. package/dist/entry/auth-login-terminal.js +1 -1
  156. package/dist/entry/init-auth.js +1 -1
  157. package/dist/entry/init.js +6 -6
  158. package/dist/entry/signal-cli.d.ts +30 -0
  159. package/dist/entry/signal-cli.js +207 -0
  160. package/dist/entry/start-ui-http.d.ts +1 -1
  161. package/dist/entry/start-ui-http.js +5 -3
  162. package/dist/events/event-types.d.ts +5 -7
  163. package/dist/hooks/{cortex-md-injector.mjs → agents-md-injector.mjs} +117 -26
  164. package/dist/hooks/cortex-hook-api.mjs +2 -2
  165. package/dist/hooks/new-session-hook.mjs +2 -2
  166. package/dist/hooks/rules-loader.mjs +2 -2
  167. package/dist/hooks/status-md-guard.mjs +8 -8
  168. package/dist/hooks/task-status-check.mjs +18 -76
  169. package/dist/hooks/tasks-yaml-guard.mjs +2 -2
  170. package/dist/orchestration/agent-file-send.d.ts +9 -0
  171. package/dist/orchestration/agent-file-send.js +21 -2
  172. package/dist/orchestration/agent-runner.d.ts +4 -3
  173. package/dist/orchestration/agent-runner.js +25 -23
  174. package/dist/orchestration/attachments-store.d.ts +31 -0
  175. package/dist/orchestration/attachments-store.js +184 -0
  176. package/dist/orchestration/conversation-request.d.ts +30 -8
  177. package/dist/orchestration/conversation-request.js +62 -26
  178. package/dist/orchestration/edit-retry.js +2 -1
  179. package/dist/orchestration/interactions/ask-user-resume.js +2 -1
  180. package/dist/orchestration/interactions/plan-approvals.js +1 -1
  181. package/dist/orchestration/interactions/ui-update-prompt.d.ts +8 -0
  182. package/dist/orchestration/interactions/ui-update-prompt.js +47 -0
  183. package/dist/orchestration/outputs-store.d.ts +11 -0
  184. package/dist/orchestration/outputs-store.js +32 -6
  185. package/dist/orchestration/resume-dispatcher.js +2 -2
  186. package/dist/orchestration/routing/file-handler.d.ts +23 -2
  187. package/dist/orchestration/routing/file-handler.js +22 -5
  188. package/dist/orchestration/routing/webhook.js +240 -39
  189. package/dist/orchestration/session-compact.d.ts +3 -0
  190. package/dist/orchestration/session-compact.js +3 -2
  191. package/dist/orchestration/session-events.d.ts +6 -0
  192. package/dist/orchestration/session-events.js +5 -0
  193. package/dist/orchestration/session-gateway.d.ts +1 -1
  194. package/dist/orchestration/session-gateway.js +1 -0
  195. package/dist/orchestration/thread-executor.d.ts +2 -0
  196. package/dist/orchestration/thread-executor.js +11 -1
  197. package/dist/orchestration/thread-input.d.ts +3 -2
  198. package/dist/orchestration/thread-input.js +8 -9
  199. package/dist/orchestration/turn/turn-prep.d.ts +15 -1
  200. package/dist/orchestration/turn/turn-prep.js +21 -9
  201. package/dist/orchestration/waitpoint-ingress.d.ts +41 -0
  202. package/dist/orchestration/waitpoint-ingress.js +172 -0
  203. package/dist/orchestration/waitpoint-notifier.d.ts +21 -0
  204. package/dist/orchestration/waitpoint-notifier.js +119 -0
  205. package/dist/orchestration/waitpoint-remote-drain.d.ts +20 -0
  206. package/dist/orchestration/waitpoint-remote-drain.js +147 -0
  207. package/dist/orchestration/waitpoint-sweep.d.ts +42 -0
  208. package/dist/orchestration/waitpoint-sweep.js +87 -0
  209. package/dist/platform/adapters/feishu-image.d.ts +19 -0
  210. package/dist/platform/adapters/feishu-image.js +71 -0
  211. package/dist/platform/adapters/feishu.d.ts +2 -0
  212. package/dist/platform/adapters/feishu.js +26 -16
  213. package/dist/platform/ui-http/app-update.d.ts +11 -0
  214. package/dist/platform/ui-http/app-update.js +3 -0
  215. package/dist/platform/ui-http/listening-ports.d.ts +1 -1
  216. package/dist/platform/ui-http/listening-ports.js +1 -1
  217. package/dist/platform/ui-http/ui-session.js +1 -1
  218. package/dist/store/conversation-ledger-repo.d.ts +10 -19
  219. package/dist/store/conversation-ledger-repo.js +143 -152
  220. package/dist/store/execution-repo.d.ts +1 -19
  221. package/dist/store/execution-repo.js +1 -18
  222. package/dist/store/project-notes-repo.js +11 -2
  223. package/dist/store/prompt-migration-replacements.js +1 -1
  224. package/dist/store/session-registry-import.d.ts +34 -0
  225. package/dist/store/session-registry-import.js +182 -0
  226. package/dist/store/session-registry-journal.d.ts +107 -0
  227. package/dist/store/session-registry-journal.js +308 -19
  228. package/dist/store/session-registry-repo.d.ts +113 -28
  229. package/dist/store/session-registry-repo.js +288 -105
  230. package/dist/store/version-migrations.d.ts +29 -3
  231. package/dist/store/version-migrations.js +288 -24
  232. package/dist/store/waitpoint-repo.d.ts +108 -0
  233. package/dist/store/waitpoint-repo.js +94 -0
  234. package/package.json +2 -2
  235. package/web/dist/assets/index-CwwQNMpP.css +1 -0
  236. package/web/dist/assets/index-DLSfgq3o.js +444 -0
  237. package/web/dist/assets/{index-aHbOZSP6.js → index-DZTuqUO4.js} +1 -1
  238. package/web/dist/index.html +2 -2
  239. package/defaults/config/hooks/08-cortex-md-injector-post-tool.json +0 -10
  240. package/dist/domain/executions/log-tailer.d.ts +0 -71
  241. package/dist/domain/executions/log-tailer.js +0 -194
  242. package/dist/domain/memory/cortex-md-injector.d.ts +0 -24
  243. package/dist/domain/memory/cortex-md-scanner.d.ts +0 -10
  244. package/dist/domain/memory/cortex-md-scanner.js +0 -66
  245. package/dist/domain/remote/cortex-client.d.ts +0 -1
  246. package/dist/domain/remote/cortex-client.js +0 -662
  247. package/dist/domain/tasks/system/cortex-run.d.ts +0 -25
  248. package/dist/domain/tasks/system/cortex-run.js +0 -360
  249. package/dist/store/session-repo.d.ts +0 -65
  250. package/dist/store/session-repo.js +0 -184
  251. package/web/dist/assets/index-BuXbCsuz.js +0 -444
  252. package/web/dist/assets/index-CCPxQ94C.css +0 -1
  253. /package/defaults/{CORTEX.md → AGENTS.md} +0 -0
  254. /package/defaults/config/{CORTEX.md → AGENTS.md} +0 -0
  255. /package/defaults/context/{CORTEX.md → AGENTS.md} +0 -0
  256. /package/defaults/context/ideas/{CORTEX.md → AGENTS.md} +0 -0
  257. /package/defaults/context/projects/{CORTEX.md → AGENTS.md} +0 -0
  258. /package/defaults/context/scans/{CORTEX.md → AGENTS.md} +0 -0
  259. /package/defaults/context/user/{CORTEX.md → AGENTS.md} +0 -0
@@ -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;
@@ -27,9 +31,7 @@ export interface PrepareConversationRequestOptions {
27
31
  profileOverride?: string | null;
28
32
  /** CDP endpoint of the browser this session opted into, or null for the usual no-browser session. */
29
33
  browserCdpEndpoint?: string | null;
30
- /** Expose the commission-creation tools this turn — true only while a contract is being drafted. */
31
- commissionTools?: boolean;
32
- /** True while the session is in commission mode; loads the commission skill bundle. */
34
+ /** True once the session is bound to a landed commission; loads the commission skill bundle. */
33
35
  commissionMode?: boolean;
34
36
  /** Receives the backend-ready prompt after context and attachment paths are assembled. */
35
37
  onPromptBuilt?: ((prompt: string) => void) | null;
@@ -57,20 +59,40 @@ export declare function resolveConversationProject(args: {
57
59
  id: string;
58
60
  contextDir: string;
59
61
  } | null;
62
+ /** The delivery key for a session's current commission binding, or null outside the mode. Bound
63
+ * wins over drafting: finalize clears the draft, and the two are never both meaningful. */
64
+ export declare function commissionBindingKey(session: {
65
+ commissionId?: string | null;
66
+ commissionDraft?: string | null;
67
+ } | null): string | null;
60
68
  /**
61
- * Load the [Commission] injection payload for a fresh commission-bound session, or null for
62
- * ordinary sessions. Same first-turn-only economics as USER.md / [Session Project]: resume keeps the
63
- * block in backend history, and mid-run contract edits reach the agent through the checkpoint
64
- * protocol's mandatory re-read, not through re-injection. Best-effort: any failure injects nothing.
69
+ * Load the [Commission] injection payload for this turn, or null when nothing needs delivering.
70
+ *
71
+ * Delivery follows the STATE, not the session's age (DR-0037 v4). v3 injected on the first turn
72
+ * only, on the same economics as USER.md / [Session Project]: resume keeps the block in backend
73
+ * history, so re-sending it every turn is waste. True — but it silently assumed the binding is
74
+ * decided before the first turn, and it is not: a session can enter the mode mid-conversation (the
75
+ * agent calls `cortex_commission_start`, or the user switches it on) and it always binds its
76
+ * contract mid-conversation. Those sessions received the block never. So the marker records WHICH
77
+ * binding was delivered, and a turn injects when the current binding differs from it.
78
+ *
79
+ * `isFreshSession` still forces delivery: a spawn that died before writing history leaves the
80
+ * marker set against a conversation that does not contain the block.
81
+ *
82
+ * Best-effort throughout: any failure injects nothing rather than failing the turn.
65
83
  */
66
- export declare function resolveConversationCommission(trackSessionId: string, deps?: {
84
+ export declare function resolveConversationCommission(trackSessionId: string, args?: {
85
+ isFreshSession?: boolean;
86
+ }, deps?: {
67
87
  getSession?: (id: string) => Promise<{
68
88
  commissionId?: string | null;
69
89
  commissionDraft?: string | null;
70
90
  projectId?: string | null;
91
+ commissionBlockFor?: string | null;
71
92
  } | null>;
72
93
  load?: typeof loadCommissionPromptContext;
73
94
  loadDraft?: typeof loadCommissionDraftContext;
95
+ markDelivered?: (sessionId: string, key: string) => Promise<unknown>;
74
96
  enabled?: () => boolean;
75
97
  }): Promise<CommissionPromptContext | null>;
76
98
  /**
@@ -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
@@ -56,29 +58,59 @@ export function resolveConversationProject(args) {
56
58
  return null;
57
59
  return { id: project.id, contextDir: project.contextDir };
58
60
  }
61
+ /** The delivery key for a session's current commission binding, or null outside the mode. Bound
62
+ * wins over drafting: finalize clears the draft, and the two are never both meaningful. */
63
+ export function commissionBindingKey(session) {
64
+ if (session?.commissionId)
65
+ return `active:${session.commissionId}`;
66
+ if (session?.commissionDraft)
67
+ return `draft:${session.commissionDraft}`;
68
+ return null;
69
+ }
59
70
  /**
60
- * Load the [Commission] injection payload for a fresh commission-bound session, or null for
61
- * ordinary sessions. Same first-turn-only economics as USER.md / [Session Project]: resume keeps the
62
- * block in backend history, and mid-run contract edits reach the agent through the checkpoint
63
- * protocol's mandatory re-read, not through re-injection. Best-effort: any failure injects nothing.
71
+ * Load the [Commission] injection payload for this turn, or null when nothing needs delivering.
72
+ *
73
+ * Delivery follows the STATE, not the session's age (DR-0037 v4). v3 injected on the first turn
74
+ * only, on the same economics as USER.md / [Session Project]: resume keeps the block in backend
75
+ * history, so re-sending it every turn is waste. True — but it silently assumed the binding is
76
+ * decided before the first turn, and it is not: a session can enter the mode mid-conversation (the
77
+ * agent calls `cortex_commission_start`, or the user switches it on) and it always binds its
78
+ * contract mid-conversation. Those sessions received the block never. So the marker records WHICH
79
+ * binding was delivered, and a turn injects when the current binding differs from it.
80
+ *
81
+ * `isFreshSession` still forces delivery: a spawn that died before writing history leaves the
82
+ * marker set against a conversation that does not contain the block.
83
+ *
84
+ * Best-effort throughout: any failure injects nothing rather than failing the turn.
64
85
  */
65
- export async function resolveConversationCommission(trackSessionId, deps = {}) {
86
+ export async function resolveConversationCommission(trackSessionId, args = {}, deps = {}) {
66
87
  try {
67
- // Global feature switch (off by default while commission mode is under test). Off means no
68
- // contract block reaches any prompt, matching the tool/skill gate in agent-runner.
88
+ // Global feature switch. Off means no contract block reaches any prompt, matching the skill
89
+ // gate in agent-runner and the refusal in the commission tools.
69
90
  if (!(deps.enabled ?? (() => getSettings().commissionEnabled))())
70
91
  return null;
71
92
  const getSession = deps.getSession ?? ((id) => sessionStore.getById(id));
72
93
  const session = await getSession(trackSessionId);
73
- if (session?.commissionId) {
74
- return await (deps.load ?? loadCommissionPromptContext)(session.commissionId);
75
- }
76
- // A session still drafting its contract has no commission id yet — it is the FIRST session of
77
- // the commission, and the one that most needs to be told what it is here to do.
78
- if (session?.commissionDraft && session.projectId) {
79
- return (deps.loadDraft ?? loadCommissionDraftContext)(session.projectId, session.commissionDraft);
80
- }
81
- return null;
94
+ const key = commissionBindingKey(session ?? null);
95
+ if (!key)
96
+ return null;
97
+ if (!args.isFreshSession && key === session?.commissionBlockFor)
98
+ return null;
99
+ const context = session?.commissionId
100
+ ? await (deps.load ?? loadCommissionPromptContext)(session.commissionId)
101
+ // A session still drafting has no commission id yet — it is the FIRST session of the
102
+ // commission, and the one that most needs to be told what it is here to do.
103
+ : (session?.commissionDraft && session.projectId
104
+ ? (deps.loadDraft ?? loadCommissionDraftContext)(session.projectId, session.commissionDraft)
105
+ : null);
106
+ // Nothing loadable (contract still empty, directory gone) — leave the marker alone so the next
107
+ // turn tries again rather than recording a delivery that never happened.
108
+ if (!context)
109
+ return null;
110
+ const mark = deps.markDelivered
111
+ ?? ((id, value) => sessionStore.markCommissionBlockDelivered(id, value));
112
+ await mark(trackSessionId, key);
113
+ return context;
82
114
  }
83
115
  catch {
84
116
  return null;
@@ -104,15 +136,18 @@ export async function prepareConversationRequest(opts) {
104
136
  // A plain conversation turn is thread-free: no artifact, no previous step, no control-plane
105
137
  // preamble. Everything it does carry is a first-turn ambient block, and the two prompt-shaping
106
138
  // fields come from the very spec the run is opened with — one description of the agent, not two.
107
- const prompt = composeUserPrompt(spec, opts.userMessage, {
139
+ const composedPrompt = composeUserPrompt(spec, opts.userMessage, {
108
140
  userContext: userProfileBlock(isFreshSession),
109
141
  // Web UI direct sessions are bound to a project at create time; tell the agent which one
110
142
  // on the session's first turn (see resolveConversationProject for the exact gating).
111
143
  project: resolveConversationProject({ channel: opts.channel, projectId, isFreshSession }),
112
- // Commission-bound sessions additionally get the contract + ledger digest + protocol block
113
- // on their first turn (see resolveConversationCommission).
114
- commission: isFreshSession ? await resolveConversationCommission(sessionId) : null,
144
+ // Commission sessions additionally get the contract + ledger index + protocol block, once per
145
+ // binding rather than once per session (see resolveConversationCommission).
146
+ commission: await resolveConversationCommission(sessionId, { isFreshSession }),
115
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}`;
116
151
  const backendPrompt = buildBackendPrompt(prompt, opts.files);
117
152
  opts.onPromptBuilt?.(backendPrompt);
118
153
  // Attribute cost/execution to the session's bound project (from the registry record), NOT a
@@ -148,7 +183,9 @@ export async function prepareConversationRequest(opts) {
148
183
  spec,
149
184
  prompt: {
150
185
  text: prompt,
151
- 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
+ })),
152
189
  },
153
190
  context: {
154
191
  channel: opts.channel,
@@ -158,7 +195,6 @@ export async function prepareConversationRequest(opts) {
158
195
  executionKind: trigger === 'scheduled' ? 'scheduled' : 'local',
159
196
  isUserInitiated: true,
160
197
  commissionMode: opts.commissionMode ?? false,
161
- commissionTools: opts.commissionTools ?? false,
162
198
  scheduleTaskId: opts.scheduleTaskId ?? null,
163
199
  },
164
200
  // The three fields that differ from the shared direct-run policy; every field NOT named here
@@ -4,6 +4,7 @@ import { t } from '../core/i18n.js';
4
4
  import { trackPendingTask } from './busy-tracker.js';
5
5
  import { enqueue } from './conduit-queue.js';
6
6
  import { getSessionAsync } from '../domain/sessions/session.js';
7
+ import { acquireSessionUse } from '../domain/sessions/session-use.js';
7
8
  import { sessionStore, effectiveBackendSessionId } from '../store/session-registry-repo.js';
8
9
  import { conversationLedger } from '../store/conversation-ledger-repo.js';
9
10
  import { getActiveProfile } from '../domain/agents/index.js';
@@ -76,7 +77,7 @@ export async function runRetryAgent({ channel, text, adapter, statusMsg, startTi
76
77
  let lease = null;
77
78
  try {
78
79
  if (sessionId) {
79
- const release = await sessionStore.acquireSessionUse(sessionId);
80
+ const release = await acquireSessionUse(sessionId);
80
81
  if (!release)
81
82
  throw new Error(`Session not found or pending deletion: ${sessionId}`);
82
83
  lease = { release };
@@ -1,5 +1,6 @@
1
1
  import { createLogger } from '../../core/log.js';
2
2
  import { sessionStore, effectiveBackendSessionId } from '../../store/session-registry-repo.js';
3
+ import { acquireSessionUse } from '../../domain/sessions/session-use.js';
3
4
  import { continuationRunRequest } from '../../domain/runs/builders.js';
4
5
  import { getDefaultProfileName } from '../../domain/agents/profile-manager.js';
5
6
  import { resolveRunConfig } from '../../domain/runs/config-resolver.js';
@@ -11,7 +12,7 @@ const log = createLogger('ask-user-resume');
11
12
  export async function resumeAskUserQuestionGroup({ adapter, group, responseText }) {
12
13
  let sessionRelease = null;
13
14
  try {
14
- sessionRelease = await sessionStore.acquireSessionUse(group.sessionId);
15
+ sessionRelease = await acquireSessionUse(group.sessionId);
15
16
  if (!sessionRelease) {
16
17
  log.warn(`AskUserQuestion resume skipped for missing or deleting session: ${group.sessionId}`);
17
18
  return;
@@ -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;
@@ -0,0 +1,8 @@
1
+ import type { UpdatePrompt } from '../../domain/system/update-prompt.js';
2
+ /** How long the dialog gets the question to itself before the chat prompt is posted too. */
3
+ export declare const DEFAULT_FALLBACK_MS = 600000;
4
+ export interface UiUpdatePromptOptions {
5
+ /** Override the fallback delay (tests use a few milliseconds). */
6
+ fallbackMs?: number;
7
+ }
8
+ export declare function createUiUpdatePrompt(fallback: UpdatePrompt, opts?: UiUpdatePromptOptions): UpdatePrompt;
@@ -0,0 +1,47 @@
1
+ // input: a fallback UpdatePrompt (the chat-message one from ./update-prompt.js) + domain update state
2
+ // output: createUiUpdatePrompt(fallback, opts?) => UpdatePrompt
3
+ // pos: Dialog-first UpdatePrompt: ask() publishes `prompting` for the SPA's system.updateStatus
4
+ // query and waits for system.applyUpdate / system.skipUpdate. A fallback timer hands the
5
+ // same question to the chat-message prompt so Slack/Feishu/headless users are not stranded.
6
+ import { openServerUpdatePrompt, settleServerUpdatePrompt, } from '../../domain/system/update-ui-state.js';
7
+ import { createLogger } from '../../core/log.js';
8
+ const log = createLogger('ui-update-prompt');
9
+ /** How long the dialog gets the question to itself before the chat prompt is posted too. */
10
+ export const DEFAULT_FALLBACK_MS = 600_000; // 10 min
11
+ export function createUiUpdatePrompt(fallback, opts) {
12
+ const fallbackMs = opts?.fallbackMs ?? DEFAULT_FALLBACK_MS;
13
+ return {
14
+ ask(spec) {
15
+ return new Promise((resolve) => {
16
+ let settled = false;
17
+ let timer;
18
+ // The one place an answer becomes final, whichever side produced it. The loser's
19
+ // answer arrives later (a chat button click has no cancel API — `createUpdatePrompt`
20
+ // only clears its pending state on click or on its own 24h timeout) and is dropped here.
21
+ const finish = (choice) => {
22
+ if (settled)
23
+ return;
24
+ settled = true;
25
+ if (timer !== undefined)
26
+ clearTimeout(timer);
27
+ settleServerUpdatePrompt(choice);
28
+ resolve(choice);
29
+ };
30
+ openServerUpdatePrompt(spec.latestVersion, finish);
31
+ timer = setTimeout(() => {
32
+ if (settled)
33
+ return;
34
+ // Nobody has the SPA open (or nobody looked). Ask again over chat rather than let the
35
+ // update sit behind a dialog no one will ever see.
36
+ void fallback
37
+ .ask(spec)
38
+ .then(finish)
39
+ .catch((e) => {
40
+ log.error(`Chat-message update prompt failed: ${e.message}`);
41
+ });
42
+ }, fallbackMs);
43
+ timer.unref?.();
44
+ });
45
+ },
46
+ };
47
+ }
@@ -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. */
@@ -70,6 +70,16 @@ function outputsDir(sessionId, subdir) {
70
70
  relPrefix: `workspace/outputs/${parts.join('/')}`,
71
71
  };
72
72
  }
73
+ /** Claim a free destination inside the session's outputs area, creating the directory. Shared by
74
+ * every lander so naming, collision handling and placement cannot drift between them. */
75
+ async function reserveOutputPath(a) {
76
+ const displayName = sanitizeDisplayFilename(a.fileName);
77
+ const storageName = sanitizeStorageFilename(displayName);
78
+ const { dir, relPrefix } = outputsDir(a.sessionId, a.subdir);
79
+ await fs.mkdir(dir, { recursive: true });
80
+ const { destPath, finalName } = await resolveAvailablePath(dir, storageName);
81
+ return { destPath, relPath: `${relPrefix}/${finalName}`, displayName };
82
+ }
73
83
  /**
74
84
  * Copy an agent-produced file into the session's `workspace/outputs/…` area and return its
75
85
  * UI-relative path + final name + byte size. Copying (rather than referencing the source in
@@ -91,14 +101,30 @@ export async function copyFileIntoOutputs(a) {
91
101
  if (a.maxBytes !== undefined && stat.size > a.maxBytes) {
92
102
  throw new Error(`File is ${stat.size} bytes, over the ${a.maxBytes}-byte limit`);
93
103
  }
94
- const displayName = sanitizeDisplayFilename(a.fileName || path.basename(resolvedSrc));
95
- const storageName = sanitizeStorageFilename(displayName);
96
- const { dir, relPrefix } = outputsDir(a.sessionId, a.subdir);
97
- await fs.mkdir(dir, { recursive: true });
98
- const { destPath, finalName } = await resolveAvailablePath(dir, storageName);
104
+ const { destPath, relPath, displayName } = await reserveOutputPath({
105
+ sessionId: a.sessionId, fileName: a.fileName || path.basename(resolvedSrc), subdir: a.subdir,
106
+ });
99
107
  await fs.copyFile(resolvedSrc, destPath);
100
108
  const outStat = await fs.stat(destPath);
101
- return { relPath: `${relPrefix}/${finalName}`, name: displayName, size: outStat.size };
109
+ return { relPath, name: displayName, size: outStat.size };
110
+ }
111
+ /**
112
+ * Land a file whose bytes are produced by `receive` (a remote-device transfer) directly in the
113
+ * outputs area. Same placement and naming as `copyFileIntoOutputs`, but written once: staging to a
114
+ * temp file first and copying would double the I/O of every large transfer and leave litter behind
115
+ * when a send fails. A failing `receive` must leave nothing, so the reservation is removed here.
116
+ */
117
+ export async function receiveIntoOutputs(a, receive) {
118
+ const { destPath, relPath, displayName } = await reserveOutputPath(a);
119
+ try {
120
+ await receive(destPath);
121
+ }
122
+ catch (e) {
123
+ await fs.rm(destPath, { force: true }).catch(() => { });
124
+ throw e;
125
+ }
126
+ const outStat = await fs.stat(destPath);
127
+ return { relPath, name: displayName, size: outStat.size };
102
128
  }
103
129
  /** Write agent-authored text into the session's outputs area under `fileName`, same placement and
104
130
  * naming discipline as `copyFileIntoOutputs`. Used when the payload arrives inline rather than as
@@ -7,7 +7,7 @@ import { openThreadRun } from './thread-run/index.js';
7
7
  import { resumeThreadRunInput } from './thread-callback.js';
8
8
  import { trackPendingTask } from './busy-tracker.js';
9
9
  import { threadStore } from '../store/thread-repo.js';
10
- import { sessionStore } from '../store/session-registry-repo.js';
10
+ import { acquireSessionUse } from '../domain/sessions/session-use.js';
11
11
  import { runRegistry } from '../core/run-registry.js';
12
12
  import { createLogger } from '../core/log.js';
13
13
  const log = createLogger('resume-dispatcher');
@@ -33,7 +33,7 @@ function defaultDeps() {
33
33
  getThread: (id) => threadStore.get(id),
34
34
  channelBusy: (ch) => runRegistry.hasChannel(ch),
35
35
  directSessionBusy: (ch) => runRegistry.getByChannel(ch).some(e => !e.threadId),
36
- acquireSessionUse: (sessionId) => sessionStore.acquireSessionUse(sessionId),
36
+ acquireSessionUse: (sessionId) => acquireSessionUse(sessionId),
37
37
  track: trackPendingTask,
38
38
  delay: (ms) => new Promise((r) => setTimeout(r, ms)),
39
39
  };
@@ -1,4 +1,25 @@
1
1
  import type { PlatformAdapter } from '../../platform/adapter.js';
2
- import type { PlatformFileRef, DownloadedFile } from '../../platform/types.js';
3
- declare function downloadFiles(files: PlatformFileRef[] | undefined, adapter: PlatformAdapter, tempDir: string): Promise<DownloadedFile[]>;
2
+ import type { IncomingMessage, PlatformFileRef, DownloadedFile } from '../../platform/types.js';
3
+ export interface AttachmentFailure {
4
+ name: string;
5
+ reason: string;
6
+ }
7
+ export interface InboundFiles {
8
+ files: DownloadedFile[];
9
+ /** Attachments the platform would not hand over. Reported to the user and to the model rather
10
+ * than dropped: an answer written as if the picture had never been sent is worse than an
11
+ * answer that says the picture did not arrive. */
12
+ failures: AttachmentFailure[];
13
+ }
14
+ /**
15
+ * Download one message's attachments into that message's own directory under
16
+ * `workspace/attachments/`, then settle each one's real type and name (attachments-store).
17
+ *
18
+ * `key` identifies the inbound message (its platform message id); reusing it means a retried
19
+ * delivery reuses the directory instead of littering a new one.
20
+ */
21
+ declare function downloadFiles(files: PlatformFileRef[] | undefined, adapter: PlatformAdapter, key: string): Promise<InboundFiles>;
22
+ /** The inbound message's own attachment directory key: conduit + platform message id. Stable, so a
23
+ * redelivery of the same message reuses its directory instead of littering a new one. */
24
+ export declare function inboundAttachmentKey(message: IncomingMessage): string;
4
25
  export { downloadFiles };
@@ -1,17 +1,34 @@
1
1
  import { createLogger } from '../../core/log.js';
2
+ import { finalizeInboundFile, prepareInboundAttachmentDir } from '../attachments-store.js';
2
3
  const log = createLogger('file-handler');
3
- async function downloadFiles(files, adapter, tempDir) {
4
+ /**
5
+ * Download one message's attachments into that message's own directory under
6
+ * `workspace/attachments/`, then settle each one's real type and name (attachments-store).
7
+ *
8
+ * `key` identifies the inbound message (its platform message id); reusing it means a retried
9
+ * delivery reuses the directory instead of littering a new one.
10
+ */
11
+ async function downloadFiles(files, adapter, key) {
4
12
  if (!files?.length)
5
- return [];
13
+ return { files: [], failures: [] };
14
+ const dir = await prepareInboundAttachmentDir(key);
6
15
  const results = [];
16
+ const failures = [];
7
17
  for (const file of files) {
8
18
  try {
9
- results.push(await adapter.downloadFile(file, tempDir));
19
+ results.push(await finalizeInboundFile(await adapter.downloadFile(file, dir), dir));
10
20
  }
11
21
  catch (e) {
12
- log.error('Failed to download file:', file.name, e.message);
22
+ const reason = e.message;
23
+ log.error('Failed to download file:', file.name, reason);
24
+ failures.push({ name: file.name || file.id, reason });
13
25
  }
14
26
  }
15
- return results;
27
+ return { files: results, failures };
28
+ }
29
+ /** The inbound message's own attachment directory key: conduit + platform message id. Stable, so a
30
+ * redelivery of the same message reuses its directory instead of littering a new one. */
31
+ export function inboundAttachmentKey(message) {
32
+ return `${message.ref.conduit || 'unknown'}-${message.ref.messageId || 'nomsg'}`;
16
33
  }
17
34
  export { downloadFiles };