@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
@@ -5,11 +5,16 @@ export interface CommissionFinalizeArgs {
5
5
  title?: string;
6
6
  contractPath: string;
7
7
  }
8
+ /** The session fields finalize decides on: which project owns the directory, and which commission
9
+ * state the session is in. A submit is only legal from a session that is DRAFTING (DR-0037 v4). */
10
+ export interface CommissionFinalizeSession {
11
+ projectId: string;
12
+ commissionId?: string | null;
13
+ commissionDraft?: string | null;
14
+ }
8
15
  /** Store seams only — path checks run against the real filesystem on purpose (tests use tmp dirs). */
9
16
  export interface CommissionFinalizeDeps {
10
- getSession?: (id: string) => Promise<{
11
- projectId: string;
12
- } | null>;
17
+ getSession?: (id: string) => Promise<CommissionFinalizeSession | null>;
13
18
  resolveRoot?: (projectId: string) => string | null;
14
19
  findBySlug?: (projectId: string, slug: string) => Promise<unknown | null>;
15
20
  addCommission?: (record: CommissionRecord) => Promise<void>;
@@ -42,6 +42,15 @@ export async function validateCommissionFinalize(args, deps = {}) {
42
42
  const session = await (deps.getSession ?? ((id) => sessionStore.getById(id)))(args.sessionId);
43
43
  if (!session)
44
44
  return fail(`unknown session ${args.sessionId}`);
45
+ // The state check, not tool visibility, is what makes a commission impossible to bootstrap from a
46
+ // session that never entered the mode. Visibility was the v3 lever and it never worked on the
47
+ // Claude backend: `--tools` filters the built-in set only, so the MCP tools were always callable.
48
+ if (session.commissionId) {
49
+ return fail(`this session is already bound to commission ${session.commissionId} — one commission per session`);
50
+ }
51
+ if (!session.commissionDraft) {
52
+ return fail('this session is not drafting a commission — call cortex_commission_start first');
53
+ }
45
54
  const slug = slugifyCommissionName(args.name ?? '');
46
55
  if (!slug)
47
56
  return fail(`name "${args.name}" leaves no slug-safe characters — use an ASCII name`);
@@ -51,6 +60,11 @@ export async function validateCommissionFinalize(args, deps = {}) {
51
60
  const draft = resolveDraftDir(root, args.contractPath);
52
61
  if (draft.ok === false)
53
62
  return draft; // (=== false: truthiness narrowing is off with strict:false)
63
+ // Own draft only: the shape check above accepts any `_draft-*` under this project, which would let
64
+ // one session submit another's contract and rename a directory out from under it.
65
+ if (path.basename(draft.dir) !== session.commissionDraft) {
66
+ return fail(`contract.md is in ${path.basename(draft.dir)}, but this session drafts in ${session.commissionDraft}`);
67
+ }
54
68
  const targetDir = path.join(root, slug);
55
69
  if (fs.existsSync(targetDir))
56
70
  return fail(`commissions/${slug} already exists — pick another name`);
@@ -1,6 +1,6 @@
1
1
  import { executionRepo, TERMINAL_STATUSES } from '../../store/execution-repo.js';
2
2
  import type { AgentResult } from '../../core/types/agent-types.js';
3
- export type { ExecutionRecord, DispatchInfo, ExecutionGpuInfo } from '../../store/execution-repo.js';
3
+ export type { ExecutionRecord, DispatchInfo } from '../../store/execution-repo.js';
4
4
  export { TERMINAL_STATUSES };
5
5
  /** Release any task locks owned by `executionId` WITHOUT ending the execution.
6
6
  * Used by the thread suspend path (DR-0014): a manager that acquired a project lock
@@ -18,7 +18,6 @@ export declare function findRunningDispatchMatch(opts: Parameters<typeof executi
18
18
  export declare function startLocalExecution(opts: Parameters<typeof executionRepo.startLocalExecution>[0]): import("../../store/execution-repo.js").ExecutionRecord;
19
19
  export declare function registerDispatchExecution(opts: Parameters<typeof executionRepo.registerDispatchExecution>[0]): import("../../store/execution-repo.js").ExecutionRecord;
20
20
  export declare function touchExecution(id: string, patch?: Parameters<typeof executionRepo.touchExecution>[1]): import("../../store/execution-repo.js").ExecutionRecord;
21
- export declare function setExecutionGpuByTaskId(taskId: string, gpu: Parameters<typeof executionRepo.setExecutionGpuByTaskId>[1]): import("../../store/execution-repo.js").ExecutionRecord;
22
21
  export declare function completeExecution(id: string, metrics?: Parameters<typeof executionRepo.completeExecution>[1]): import("../../store/execution-repo.js").ExecutionRecord;
23
22
  export declare function completeExecutionByTaskId(taskId: string, metrics?: Parameters<typeof executionRepo.completeExecutionByTaskId>[1]): import("../../store/execution-repo.js").ExecutionRecord;
24
23
  export declare function failExecution(id: string, metrics?: Parameters<typeof executionRepo.failExecution>[1]): import("../../store/execution-repo.js").ExecutionRecord;
@@ -82,9 +82,6 @@ export function registerDispatchExecution(opts) {
82
82
  export function touchExecution(id, patch) {
83
83
  return executionRepo.touchExecution(id, patch);
84
84
  }
85
- export function setExecutionGpuByTaskId(taskId, gpu) {
86
- return executionRepo.setExecutionGpuByTaskId(taskId, gpu);
87
- }
88
85
  export function completeExecution(id, metrics) {
89
86
  const r = executionRepo.completeExecution(id, metrics);
90
87
  if (r && TERMINAL_STATUSES.has(r.status))
@@ -32,15 +32,16 @@ const threadLoader = async (ctx) => {
32
32
  return server => { registerThreadTools(server, ctx); registerAskManagerTool(server, ctx); };
33
33
  };
34
34
  const extLoader = async (ctx) => {
35
- const [{ registerCostTools }, { registerExecutionTools }, { registerContextTools }, { registerScheduleTools }] = await Promise.all([
35
+ const [{ registerCostTools }, { registerExecutionTools }, { registerContextTools }, { registerScheduleTools }, { registerWaitpointTools }] = await Promise.all([
36
36
  import('./tools/cost.js'), import('./tools/executions.js'), import('./tools/context.js'),
37
- import('./tools/schedule.js'),
37
+ import('./tools/schedule.js'), import('./tools/waitpoint.js'),
38
38
  ]);
39
39
  return server => {
40
40
  registerCostTools(server);
41
41
  registerExecutionTools(server);
42
42
  registerContextTools(server, ctx);
43
43
  registerScheduleTools(server, ctx);
44
+ registerWaitpointTools(server, ctx);
44
45
  };
45
46
  };
46
47
  const interactionLoader = async (ctx) => {
@@ -65,7 +66,7 @@ const feishuLoader = async (ctx) => {
65
66
  ]);
66
67
  // App credentials stay process-wide (one Feishu app per daemon); only the channel is per session.
67
68
  const client = buildFeishuClientFromEnv();
68
- return server => registerFeishuTools(server, { client, fallbackChannel: ctx.channel });
69
+ return server => registerFeishuTools(server, { client, fallbackChannel: ctx.channel, ctx });
69
70
  };
70
71
  const webLoader = async (ctx) => {
71
72
  const [{ registerUiFileTools }, { registerUiViewTools }, { registerUiDecisionTools }] = await Promise.all([
@@ -2,6 +2,8 @@ import { z } from 'zod';
2
2
  import * as fs from 'fs';
3
3
  import * as path from 'path';
4
4
  import { guard, ok, unwrap } from './types.js';
5
+ import { uploadFeishuImage } from '../../../platform/adapters/feishu-image.js';
6
+ import { withStagedRemoteFile } from '../tools/remote-file.js';
5
7
  function resolveReadableFilePath(filePathInput) {
6
8
  const resolved = path.isAbsolute(filePathInput)
7
9
  ? filePathInput
@@ -43,51 +45,68 @@ function inferFeishuFileType(fileName) {
43
45
  // Use 'stream' as fallback for all unsupported types
44
46
  return typeMap[ext] || 'stream';
45
47
  }
46
- export async function uploadFileToFeishu(client, { channel, filePath, fileName, title }) {
47
- const { resolved, size } = resolveReadableFilePath(filePath);
48
- const body = fs.readFileSync(resolved);
49
- const uploadName = fileName || path.basename(resolved);
50
- // Strip 'feishu:' prefix from channel ID for Feishu API compatibility
51
- const bareChannel = stripFeishuPrefix(channel);
52
- // Upload file to get file_key
48
+ /** Upload as a chat file and return its file_key. */
49
+ async function uploadFileKey(client, resolved, uploadName) {
53
50
  const uploadRes = await client.im.v1.file.create({
54
51
  data: {
55
52
  file_type: inferFeishuFileType(uploadName),
56
53
  file_name: uploadName,
57
- file: body,
54
+ file: fs.readFileSync(resolved),
58
55
  },
59
56
  });
60
57
  const fileKey = unwrap(uploadRes).file_key;
61
58
  if (!fileKey)
62
59
  throw new Error('Feishu file upload failed: no file_key returned');
63
- // Send file message to channel
64
- const msgContent = JSON.stringify({ file_key: fileKey });
60
+ return fileKey;
61
+ }
62
+ export async function uploadFileToFeishu(client, { channel, filePath, fileName, title }) {
63
+ const { resolved, size } = resolveReadableFilePath(filePath);
64
+ const uploadName = fileName || path.basename(resolved);
65
+ // Strip 'feishu:' prefix from channel ID for Feishu API compatibility
66
+ const bareChannel = stripFeishuPrefix(channel);
67
+ // An image goes into the chat as an image, so the user sees it without opening anything. The file
68
+ // card below stays the fallback: non-images, images over 10 MB, and apps without `im:resource`.
69
+ const imageKey = await uploadFeishuImage(client, resolved, size);
70
+ const msgType = imageKey ? 'image' : 'file';
71
+ const msgContent = imageKey
72
+ ? JSON.stringify({ image_key: imageKey })
73
+ : JSON.stringify({ file_key: await uploadFileKey(client, resolved, uploadName) });
65
74
  await client.im.v1.message.create({
66
75
  params: { receive_id_type: 'chat_id' },
67
76
  data: {
68
77
  receive_id: bareChannel,
69
- msg_type: 'file',
78
+ msg_type: msgType,
70
79
  content: msgContent,
71
80
  },
72
81
  });
73
82
  return { path: resolved, fileName: uploadName, size };
74
83
  }
75
84
  export function registerFileTools(server, deps) {
76
- server.tool('feishu_send_file', 'Upload a local file to Feishu. Use this when you need to share a file (document, image, archive, etc.) with users in a Feishu chat or channel.', {
77
- file_path: z.string().describe('Local file path to upload'),
85
+ server.tool('feishu_send_file', 'Upload a file to Feishu. Use this when you need to share a file (document, image, archive, etc.) with users in a Feishu chat or channel. The file may be on this server or, with `device`, on a connected remote device.', {
86
+ file_path: z.string().describe('File path to upload. Local path, or an absolute path on `device`.'),
78
87
  file_name: z.string().optional().describe('Optional filename override shown in Feishu'),
79
88
  title: z.string().optional().describe('Optional file title shown in Feishu'),
80
89
  channel: z.string().optional().describe('Optional chat/channel ID (uses route context if not provided)'),
81
- }, async ({ file_path, file_name, title, channel: explicitChannel }) => guard(deps.client, async (client) => {
90
+ device: z.string().optional().describe('Name of a connected remote device (as used by remote_bash). Omit for files on this server.'),
91
+ }, async ({ file_path, file_name, title, channel: explicitChannel, device }) => guard(deps.client, async (client) => {
82
92
  const channel = explicitChannel || deps.fallbackChannel || '';
83
93
  if (!channel)
84
94
  throw new Error('No Feishu channel available (no session channel or channel parameter)');
85
- const uploaded = await uploadFileToFeishu(client, {
95
+ const upload = (filePath, name) => uploadFileToFeishu(client, {
86
96
  channel,
87
- filePath: file_path,
88
- fileName: file_name,
97
+ filePath,
98
+ fileName: name,
89
99
  title,
90
100
  });
91
- return ok(`File uploaded: ${uploaded.fileName} (${uploaded.size} bytes)`);
101
+ // The Feishu upload reads from a path, so a device's file is staged to disk first and
102
+ // removed again once the upload has taken its bytes.
103
+ if (!device) {
104
+ const uploaded = await upload(file_path, file_name);
105
+ return ok(`File uploaded: ${uploaded.fileName} (${uploaded.size} bytes)`);
106
+ }
107
+ if (!deps.ctx)
108
+ throw new Error('`device` is not available in this context');
109
+ const uploaded = await withStagedRemoteFile(deps.ctx, device, file_path, staged => upload(staged.localPath, file_name || staged.name));
110
+ return ok(`File uploaded from ${device}: ${uploaded.fileName} (${uploaded.size} bytes)`);
92
111
  }));
93
112
  }
@@ -1,9 +1,12 @@
1
1
  import type { LarkClient } from './client.js';
2
+ import type { CortexToolContext } from '../tools/context.js';
2
3
  /** Dependencies injected into each register*Tools function (client is mockable in tests). */
3
4
  export interface FeishuToolDeps {
4
5
  client: LarkClient | null;
5
6
  /** Session channel used when a tool call names none (may carry the `feishu:` prefix). */
6
7
  fallbackChannel?: string | null;
8
+ /** Carried so the file tool can reach the daemon to stage a remote device's file. */
9
+ ctx?: CortexToolContext;
7
10
  }
8
11
  export interface McpResult {
9
12
  content: Array<{
@@ -18,7 +18,7 @@ const client = buildFeishuClientFromEnv();
18
18
  // --- McpServer + tool registration ---
19
19
  const ctx = toolContextFromEnv();
20
20
  const server = new McpServer({ name: 'cortex-feishu', version: CORTEX_VERSION });
21
- registerGatedMcpTools(server, target => registerFeishuTools(target, { client, fallbackChannel: ctx.channel }), ctx.toolAllowlist);
21
+ registerGatedMcpTools(server, target => registerFeishuTools(target, { client, fallbackChannel: ctx.channel, ctx }), ctx.toolAllowlist);
22
22
  export async function startServer() {
23
23
  if (!client) {
24
24
  log.warn('FEISHU_APP_ID / FEISHU_APP_SECRET not set — feishu_send_file will return a not-configured error');
@@ -1,17 +1,17 @@
1
- import { type CortexMDEntry } from '../../memory/cortex-md-injector.js';
2
- export { type CortexMDEntry };
3
- /** Build text content blocks for the CORTEX.md chain returned by cortex-client.
4
- * Dedup by (device:path) mtime via CortexMDInjector — each CORTEX.md is injected
1
+ import { type AgentsMDEntry } from '../../memory/agents-md-injector.js';
2
+ export { type AgentsMDEntry };
3
+ /** Build text content blocks for the AGENTS.md chain returned by cortex-client.
4
+ * Dedup by (device:path) mtime via AgentsMDInjector — each AGENTS.md is injected
5
5
  * at most once per MCP process, and the cache is disk-backed so restarts
6
6
  * don't re-flood the agent with the same instructions.
7
7
  *
8
8
  * If `targetFilePath` is supplied and equals one of the chain entries (i.e. the
9
- * tool is reading/writing/editing a CORTEX.md itself), that entry is marked as
9
+ * tool is reading/writing/editing an AGENTS.md itself), that entry is marked as
10
10
  * seen in the cache but its block is suppressed — the agent already receives
11
11
  * the content as the primary tool response, so re-injecting would just double
12
12
  * it. Subsequent reads of sibling files in the same dir will then hit the
13
13
  * cache and also skip, matching the normal dedup behavior. */
14
- export declare function cortexMDContentBlocks(device: string, entries: CortexMDEntry[] | undefined, targetFilePath?: string): Array<{
14
+ export declare function agentsMDContentBlocks(device: string, entries: AgentsMDEntry[] | undefined, targetFilePath?: string): Array<{
15
15
  type: 'text';
16
16
  text: string;
17
17
  }>;
@@ -1,16 +1,16 @@
1
- import { getDefaultCortexInjector } from '../../memory/cortex-md-injector.js';
2
- /** Build text content blocks for the CORTEX.md chain returned by cortex-client.
3
- * Dedup by (device:path) mtime via CortexMDInjector — each CORTEX.md is injected
1
+ import { getDefaultAgentsInjector } from '../../memory/agents-md-injector.js';
2
+ /** Build text content blocks for the AGENTS.md chain returned by cortex-client.
3
+ * Dedup by (device:path) mtime via AgentsMDInjector — each AGENTS.md is injected
4
4
  * at most once per MCP process, and the cache is disk-backed so restarts
5
5
  * don't re-flood the agent with the same instructions.
6
6
  *
7
7
  * If `targetFilePath` is supplied and equals one of the chain entries (i.e. the
8
- * tool is reading/writing/editing a CORTEX.md itself), that entry is marked as
8
+ * tool is reading/writing/editing an AGENTS.md itself), that entry is marked as
9
9
  * seen in the cache but its block is suppressed — the agent already receives
10
10
  * the content as the primary tool response, so re-injecting would just double
11
11
  * it. Subsequent reads of sibling files in the same dir will then hit the
12
12
  * cache and also skip, matching the normal dedup behavior. */
13
- export function cortexMDContentBlocks(device, entries, targetFilePath) {
13
+ export function agentsMDContentBlocks(device, entries, targetFilePath) {
14
14
  if (!entries || entries.length === 0)
15
15
  return [];
16
16
  let markOnly;
@@ -19,7 +19,7 @@ export function cortexMDContentBlocks(device, entries, targetFilePath) {
19
19
  if (matched.length > 0)
20
20
  markOnly = new Set(matched.map(e => e.path));
21
21
  }
22
- return getDefaultCortexInjector().buildBlocks(device, entries, markOnly);
22
+ return getDefaultAgentsInjector().buildBlocks(device, entries, markOnly);
23
23
  }
24
24
  /** Tolerant path equality for matching tool `file_path` against scanner-produced
25
25
  * entry paths. The scanner runs on the remote device (Linux or Windows), so
@@ -6,9 +6,20 @@ export interface CommissionSubmitArgs {
6
6
  title?: string;
7
7
  summary?: string;
8
8
  }
9
+ /**
10
+ * Enter the drafting phase and hand back the creation protocol.
11
+ *
12
+ * Impure since v4: the session decides for itself whether a task is a commission, so the tool is
13
+ * the entry point rather than a briefing handed to a session the user already opted in. It creates
14
+ * the draft directory and sets `commissionDraft` through the loopback webhook (this process has no
15
+ * registry), which is also what makes `cortex_commission_submit` legal afterwards.
16
+ *
17
+ * Idempotent: a session already drafting gets the same directory and the same protocol back, so the
18
+ * [Commission] block can tell a user-initiated session to call it without risking a second draft.
19
+ */
9
20
  export declare function runCommissionStart(args: {
10
21
  reasoning?: string;
11
- }, deps: InteractionToolDeps): CallToolResultShape;
22
+ }, deps: InteractionToolDeps): Promise<CallToolResultShape>;
12
23
  /**
13
24
  * Posts the contract through the blocking /hook/exit-plan-mode approval channel (shared with
14
25
  * cortex_plan_exit, but this is a separate tool — plan mode is untouched). The
@@ -12,12 +12,24 @@ function okResult(text) {
12
12
  // commission skill covers maintenance only.
13
13
  // =====================================================================================
14
14
  const COMMISSION_START_PROTOCOL = `\
15
- You are starting a commission: a long task anchored by two files the user can read at any time.
15
+ This session is now drafting a commission: a long task anchored by two files the user can read at
16
+ any time.
16
17
 
17
18
  contract.md — the binding statement of intent. Written once, here, through the drill below.
18
19
  Changed afterwards only by appending to its Revisions section.
19
20
  ledger.md — your state record, written after the contract is approved.
20
21
 
22
+ Phase 0 — is this actually one? You may have entered on your own judgement, so check it against the
23
+ criteria before spending the user's time. A commission fits when the work spans several sessions or
24
+ days, when the goal hides decisions only the user can settle, or when "done" needs to be auditable
25
+ later. It does NOT fit a single question, a bounded edit whose shape is already agreed, or open
26
+ exploration with no commitment at the end. If it does not fit, say so and tell the user to switch
27
+ the mode off — do not drill anyway.
28
+
29
+ Announce it, once: unless the user turned this mode on themselves, your first cortex_ask_user call
30
+ must open by stating that you are treating this as a commission and why, and must offer an option
31
+ meaning "skip the contract, just do it". Having said it once, do not keep asking.
32
+
21
33
  Phase 1 — drill. Implement nothing. Investigation is read-only; the only thing you write is the
22
34
  contract draft. The goal is to surface and resolve the decisions hiding inside the user's request
23
35
  BEFORE any work starts.
@@ -62,21 +74,49 @@ Phase 3 — submit it with cortex_commission_submit. That call blocks until the
62
74
  denial the feedback comes back and the draft survives, so revise and call again. On approval the
63
75
  draft directory is renamed to the approved slug, the commission is registered, and this session is
64
76
  bound to it.`;
65
- function draftLocationLine(deps) {
66
- const dir = deps.sessionName
67
- ? `commissions/_draft-${deps.sessionName}/`
68
- : 'the commissions/_draft-* directory';
69
- return `Draft directory (already created by the server, under this project's context directory): ${dir}\n`
77
+ function draftLocationLine(dir) {
78
+ return `Draft directory (created for you): ${dir}\n`
70
79
  + 'Write contract.md there. Do not create or rename that directory yourself.';
71
80
  }
72
- export function runCommissionStart(args, deps) {
81
+ /**
82
+ * Enter the drafting phase and hand back the creation protocol.
83
+ *
84
+ * Impure since v4: the session decides for itself whether a task is a commission, so the tool is
85
+ * the entry point rather than a briefing handed to a session the user already opted in. It creates
86
+ * the draft directory and sets `commissionDraft` through the loopback webhook (this process has no
87
+ * registry), which is also what makes `cortex_commission_submit` legal afterwards.
88
+ *
89
+ * Idempotent: a session already drafting gets the same directory and the same protocol back, so the
90
+ * [Commission] block can tell a user-initiated session to call it without risking a second draft.
91
+ */
92
+ export async function runCommissionStart(args, deps) {
93
+ if (!deps.sessionId)
94
+ return errorResult('cortex_commission_start error: no session id in the MCP env');
95
+ let body;
96
+ try {
97
+ const resp = await deps.httpPost(`${deps.webhookBaseUrl}/hook/commission-start`, {
98
+ sessionId: deps.sessionId, channel: deps.channel, reasoning: args.reasoning ?? null,
99
+ });
100
+ body = resp.body;
101
+ if (resp.status !== 200) {
102
+ return errorResult(`cortex_commission_start error: webhook returned status ${resp.status}`);
103
+ }
104
+ }
105
+ catch (e) {
106
+ return errorResult(`cortex_commission_start error: webhook call failed: ${e.message}`);
107
+ }
108
+ if (typeof body?.error === 'string')
109
+ return errorResult(`cortex_commission_start error: ${body.error}`);
110
+ if (!body?.ok || typeof body.dir !== 'string') {
111
+ return errorResult('cortex_commission_start error: server did not return a draft directory');
112
+ }
73
113
  const reasoning = (args.reasoning && args.reasoning.trim()) || null;
74
- const text = [
114
+ return okResult([
75
115
  COMMISSION_START_PROTOCOL,
76
- draftLocationLine(deps),
116
+ draftLocationLine(body.dir),
117
+ body.alreadyDrafting ? '(This session was already drafting; the directory above is unchanged.)' : null,
77
118
  reasoning ? `(Reasoning recorded: ${reasoning})` : null,
78
- ].filter(Boolean).join('\n\n');
79
- return okResult(text);
119
+ ].filter(Boolean).join('\n\n'));
80
120
  }
81
121
  function validateArgs(args, deps) {
82
122
  if (!deps.channel)
@@ -111,6 +151,14 @@ function formatOutcome(body) {
111
151
  + `Commission directory: ${fin.dir}\n\n`
112
152
  + LEDGER_INIT);
113
153
  }
154
+ /** The same four rules the `[Commission]` block carries (see `domain/runs/prompt.ts`). Repeated
155
+ * here because the skill and the block both arrive on the NEXT turn — the plugin set is fixed at
156
+ * spawn and the block is a prompt prefix — while the contract lands in the MIDDLE of this one. */
157
+ const COMMISSION_EXECUTION_PROTOCOL = `\
158
+ 1. Surprises are three kinds: an obstacle you route around; a fork you align on; a discovery that invalidates a contract premise. A discovery MUST be surfaced against the contract — never silently absorbed.
159
+ 2. Completion claims need evidence pointers (file paths, command outputs, EXP ids) in ledger.md.
160
+ 3. Before this session ends, and at each stage boundary, append a checkpoint CP-N with three diffs — plan vs done, contract vs current direction, assumptions vs reality — graded ok / attention / gate. Re-read contract.md first.
161
+ 4. Contract gates are blocking: ask the user and wait.`;
114
162
  /** Written into the final directory the moment the contract lands, so the state record exists from
115
163
  * the first minute. Everything after this point is maintenance, which the commission skill covers. */
116
164
  const LEDGER_INIT = `\
@@ -130,7 +178,13 @@ Now create ledger.md in that directory, derived from the contract:
130
178
  ## Log
131
179
  (L-NNN entries, appended)
132
180
 
133
- Then start executing. The commission skill describes the checkpoint discipline from here on.`;
181
+ Then start executing.
182
+
183
+ The \`commission\` skill carries the maintenance protocol in full and loads from your NEXT turn (the
184
+ session respawns onto it, keeping this conversation). For the rest of THIS turn, these four rules
185
+ are the whole of it:
186
+
187
+ ${COMMISSION_EXECUTION_PROTOCOL}`;
134
188
  /**
135
189
  * Posts the contract through the blocking /hook/exit-plan-mode approval channel (shared with
136
190
  * cortex_plan_exit, but this is a separate tool — plan mode is untouched). The
@@ -171,8 +225,8 @@ export async function runCommissionSubmit(args, deps) {
171
225
  return formatOutcome(resp.body);
172
226
  }
173
227
  export function registerCommissionTools(server, deps) {
174
- server.tool('cortex_commission_start', 'Start creating a commission — a long task anchored by a user-approved contract. Call this FIRST, before any investigation or questions: it returns the complete creation protocol (drill rules, contract.md structure) and the draft directory to write the contract into. Unrelated to plan mode; cortex_plan_enter/exit still exist and are for ordinary implementation planning. Optional `reasoning` is recorded for the audit trail.', { reasoning: z.string().optional() }, async (args) => runCommissionStart(args ?? {}, deps));
175
- server.tool('cortex_commission_submit', 'Submit a drafted commission contract for human approval, and land the commission if approved. Reads contract.md at `contract_file_path` — it must live in a `commissions/_draft-*/` directory of this session\'s project — and BLOCKS until the human decides. On approval the draft directory is renamed to the slug of `name`, the commission is registered, this session is bound to it, and the final directory is returned. On denial the feedback comes back and the draft survives: revise and call again.', {
228
+ server.tool('cortex_commission_start', 'Put THIS session into commission mode and get the creation protocol: a commission is a long task anchored by a contract the user approves before any work begins. Call it when the work spans several sessions or days, hides decisions only the user can settle, or needs an auditable record of what "done" meant — not for a single question, an already-agreed edit, or open exploration. It creates the draft directory, returns the full drill protocol and contract structure, and is idempotent (safe to call again to re-read the protocol). Unrelated to plan mode; cortex_plan_enter/exit remain for ordinary implementation planning. Optional `reasoning` is recorded for the audit trail.', { reasoning: z.string().optional() }, async (args) => (await runCommissionStart(args ?? {}, deps)));
229
+ server.tool('cortex_commission_submit', 'Submit a drafted commission contract for human approval, and land the commission if approved. Only legal from a session that entered the mode through cortex_commission_start (or that the user switched into it); it reads contract.md at `contract_file_path`, which must be THIS session\'s own `commissions/_draft-*/` directory, and BLOCKS until the human decides. On approval the draft directory is renamed to the slug of `name`, the commission is registered, this session is bound to it, and the final directory is returned. On denial the feedback comes back and the draft survives: revise and call again.', {
176
230
  contract_file_path: z.string().describe('Absolute path of the draft contract.md to submit'),
177
231
  name: z.string().describe('Final commission name; slugified into the directory name'),
178
232
  title: z.string().optional().describe('Display title (defaults to name)'),
@@ -0,0 +1,20 @@
1
+ import { type CortexToolContext } from './context.js';
2
+ /** Cross-platform absolute-path check (the server runs on Linux but validates paths for Windows
3
+ * clients, where `D:\…` is absolute and `/foo` is not what the user means). */
4
+ export declare function isAbsoluteFilePath(p: string): boolean;
5
+ export interface StagedFile {
6
+ localPath: string;
7
+ name: string;
8
+ size: number;
9
+ }
10
+ /**
11
+ * Bring a remote device's file to this machine so a sender that uploads from disk (Slack, Feishu)
12
+ * can treat it like any local file. The transfer itself happens in the daemon — client-manager and
13
+ * the reverse channel live there — so this is only the proxy call.
14
+ */
15
+ export declare function stageRemoteFile(ctx: CortexToolContext, device: string, filePath: string): Promise<StagedFile>;
16
+ /**
17
+ * Run `use` against a device's file, then delete the staged copy. The copy is a transfer buffer,
18
+ * not a result: leaving it behind would grow the workspace by the size of every file ever sent.
19
+ */
20
+ export declare function withStagedRemoteFile<T>(ctx: CortexToolContext, device: string, filePath: string, use: (staged: StagedFile) => Promise<T>): Promise<T>;
@@ -0,0 +1,44 @@
1
+ import * as fs from 'fs';
2
+ import * as path from 'path';
3
+ import { requestLoopbackJson } from '../../../core/loopback-http.js';
4
+ import { webhookAuthHeaders } from './context.js';
5
+ /** Cross-platform absolute-path check (the server runs on Linux but validates paths for Windows
6
+ * clients, where `D:\…` is absolute and `/foo` is not what the user means). */
7
+ export function isAbsoluteFilePath(p) {
8
+ if (path.isAbsolute(p))
9
+ return true;
10
+ // Windows absolute: D:\, D:/, etc.
11
+ if (/^[A-Za-z]:[/\\]/.test(p))
12
+ return true;
13
+ return false;
14
+ }
15
+ /** How long a staged transfer may take end to end. Generous: the transfer crosses whatever tunnel
16
+ * the device is behind, and the alternative to waiting is a file the user never receives. */
17
+ const STAGE_TIMEOUT_MS = 10 * 60_000;
18
+ /**
19
+ * Bring a remote device's file to this machine so a sender that uploads from disk (Slack, Feishu)
20
+ * can treat it like any local file. The transfer itself happens in the daemon — client-manager and
21
+ * the reverse channel live there — so this is only the proxy call.
22
+ */
23
+ export async function stageRemoteFile(ctx, device, filePath) {
24
+ if (!isAbsoluteFilePath(filePath)) {
25
+ throw new Error('file_path must be absolute when `device` is set');
26
+ }
27
+ const { body } = await requestLoopbackJson('POST', `${ctx.webhookBaseUrl}/webhook/remote-fetch`, { device, filePath }, webhookAuthHeaders(ctx), STAGE_TIMEOUT_MS);
28
+ if (!body.success)
29
+ throw new Error(body.error || `Failed to fetch ${filePath} from ${device}`);
30
+ return body.data;
31
+ }
32
+ /**
33
+ * Run `use` against a device's file, then delete the staged copy. The copy is a transfer buffer,
34
+ * not a result: leaving it behind would grow the workspace by the size of every file ever sent.
35
+ */
36
+ export async function withStagedRemoteFile(ctx, device, filePath, use) {
37
+ const staged = await stageRemoteFile(ctx, device, filePath);
38
+ try {
39
+ return await use(staged);
40
+ }
41
+ finally {
42
+ await fs.promises.rm(path.dirname(staged.localPath), { recursive: true, force: true }).catch(() => { });
43
+ }
44
+ }
@@ -6,6 +6,8 @@ export interface SlackToolDeps {
6
6
  fallbackChannel: string | undefined;
7
7
  branchMachine: string | undefined;
8
8
  callbackSource: string | undefined;
9
+ /** Carried so file tools can reach the daemon to stage a remote device's file. */
10
+ ctx?: CortexToolContext;
9
11
  }
10
12
  /** Production deps for one session: a WebClient when the session carries a bot token. */
11
13
  export declare function slackDepsFor(ctx: CortexToolContext): SlackToolDeps;
@@ -4,6 +4,7 @@ import * as fs from 'fs';
4
4
  import * as path from 'path';
5
5
  import { TokenBucketRateLimiter } from '../../../platform/utils/rate-limiter.js';
6
6
  import { Icons } from '../../../core/icons.js';
7
+ import { withStagedRemoteFile } from './remote-file.js';
7
8
  /** Production deps for one session: a WebClient when the session carries a bot token. */
8
9
  export function slackDepsFor(ctx) {
9
10
  return {
@@ -11,6 +12,7 @@ export function slackDepsFor(ctx) {
11
12
  fallbackChannel: ctx.channel ?? undefined,
12
13
  branchMachine: ctx.branchMachine ?? undefined,
13
14
  callbackSource: ctx.callbackSource ?? undefined,
15
+ ctx,
14
16
  };
15
17
  }
16
18
  /** Per-process rate limiter for the MCP server's Slack API calls.
@@ -98,30 +100,43 @@ export async function uploadFileToSlack(slack, { channel, filePath, fileName, ti
98
100
  });
99
101
  return { path: resolved, fileName: uploadName, size };
100
102
  }
103
+ /** Tests construct deps without a context; only the remote path needs one, so it is demanded here
104
+ * rather than made mandatory for every Slack tool. */
105
+ function requireCtx(deps) {
106
+ if (!deps.ctx)
107
+ throw new Error('`device` is not available in this context');
108
+ return deps.ctx;
109
+ }
101
110
  export function registerSlackTools(server, deps) {
102
- server.tool('slack_send_file', 'Upload a local file to Slack. Use this when you need to share a file (image, log, data, etc.) with the user.', {
103
- file_path: z.string().describe('Local file path to upload'),
111
+ server.tool('slack_send_file', 'Upload a file to Slack. Use this when you need to share a file (image, log, data, etc.) with the user. The file may be on this server or, with `device`, on a connected remote device.', {
112
+ file_path: z.string().describe('File path to upload. Local path, or an absolute path on `device`.'),
104
113
  file_name: z.string().optional().describe('Optional filename override shown in Slack'),
105
114
  title: z.string().optional().describe('Optional file title shown in Slack'),
106
115
  comment: z.string().optional().describe('Optional comment to accompany the file'),
107
- }, async ({ file_path, file_name, title, comment }) => {
116
+ device: z.string().optional().describe('Name of a connected remote device (as used by remote_bash). Omit for files on this server.'),
117
+ }, async ({ file_path, file_name, title, comment, device }) => {
108
118
  try {
109
119
  const channel = deps.fallbackChannel;
110
120
  if (!channel)
111
121
  throw new Error('No routing channel available');
112
122
  if (!deps.slack)
113
123
  throw new Error('Missing SLACK_BOT_TOKEN');
114
- const uploaded = await uploadFileToSlack(deps.slack, {
124
+ const upload = (filePath, name) => uploadFileToSlack(deps.slack, {
115
125
  channel,
116
- filePath: file_path,
117
- fileName: file_name,
126
+ filePath,
127
+ fileName: name,
118
128
  title,
119
129
  initialComment: comment || undefined,
120
130
  });
131
+ // A device's file is fetched to disk first: the Slack SDK uploads from a path, so there is
132
+ // nothing to gain from streaming it anywhere else on the way.
133
+ const uploaded = device
134
+ ? await withStagedRemoteFile(requireCtx(deps), device, file_path, staged => upload(staged.localPath, file_name || staged.name))
135
+ : await upload(file_path, file_name);
121
136
  return {
122
137
  content: [{
123
138
  type: 'text',
124
- text: `File uploaded: ${uploaded.fileName} (${uploaded.size} bytes)`,
139
+ text: `File uploaded${device ? ` from ${device}` : ''}: ${uploaded.fileName} (${uploaded.size} bytes)`,
125
140
  }],
126
141
  };
127
142
  }