@cortex-agent/server 2026.9.15 → 2026.9.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (297) hide show
  1. package/README.md +3 -2
  2. package/defaults/config/hooks/08-agents-md-injector-post-tool.json +10 -0
  3. package/defaults/config/hooks/{10-cortex-md-injector-session-start.json → 10-agents-md-injector-session-start.json} +3 -3
  4. package/defaults/config/hooks/{CORTEX.md → AGENTS.md} +2 -2
  5. package/defaults/config/thread-templates/agents/creative.json +17 -0
  6. package/defaults/hooks/{CORTEX.md → AGENTS.md} +1 -1
  7. package/defaults/hooks/{cortex-md-injector.mjs → agents-md-injector.mjs} +117 -26
  8. package/defaults/hooks/cortex-hook-api.mjs +2 -2
  9. package/defaults/hooks/new-session-hook.mjs +2 -2
  10. package/defaults/hooks/rules-loader.mjs +2 -2
  11. package/defaults/hooks/status-md-guard.mjs +8 -8
  12. package/defaults/hooks/task-status-check.mjs +18 -76
  13. package/defaults/hooks/tasks-yaml-guard.mjs +2 -2
  14. package/defaults/plugins/cortex-feishu/skills/feishu-doc/SKILL.md +1 -1
  15. package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +2 -2
  16. package/defaults/plugins/cortex-system/skills/project-init/SKILL.md +4 -4
  17. package/defaults/plugins/cortex-system/skills/task/SKILL.md +1 -1
  18. package/defaults/prompts/systemPrompts/creative.md +13 -0
  19. package/defaults/prompts/systemPrompts/direct.md +1 -1
  20. package/defaults/rules/{cortex-md.md → agents-md.md} +4 -4
  21. package/defaults/rules/decision-records.md +1 -1
  22. package/defaults/rules/meta-conventions.md +4 -4
  23. package/defaults/rules/mission-md.md +1 -1
  24. package/dist/agent-adapter/claude/adapter.d.ts +12 -0
  25. package/dist/agent-adapter/claude/adapter.js +19 -1
  26. package/dist/agent-adapter/claude/hooks-builder.js +2 -2
  27. package/dist/agent-adapter/claude/spawn-args.d.ts +7 -0
  28. package/dist/agent-adapter/claude/spawn-args.js +14 -0
  29. package/dist/agent-adapter/claude/turn-machine.d.ts +11 -0
  30. package/dist/agent-adapter/claude/turn-machine.js +46 -5
  31. package/dist/agent-adapter/normalize/prompt-builder.d.ts +16 -1
  32. package/dist/agent-adapter/normalize/prompt-builder.js +24 -6
  33. package/dist/agent-adapter/pi/child-runner.d.ts +4 -2
  34. package/dist/agent-adapter/pi/child-runner.js +5 -1
  35. package/dist/agent-adapter/pi/event-parser.d.ts +3 -2
  36. package/dist/agent-adapter/pi/event-parser.js +46 -2
  37. package/dist/agent-adapter/pi/extensions.d.ts +7 -1
  38. package/dist/agent-adapter/pi/extensions.js +10 -3
  39. package/dist/agent-adapter/pi/mcp-bridge.js +8 -8
  40. package/dist/agent-adapter/pi/pi-session.js +5 -0
  41. package/dist/agent-adapter/pi/runtime.js +3 -0
  42. package/dist/agent-adapter/pi/session-options.js +5 -1
  43. package/dist/agent-adapter/pi/subagent.d.ts +15 -3
  44. package/dist/agent-adapter/pi/subagent.js +18 -0
  45. package/dist/agent-adapter/pi/tool-shims.d.ts +6 -1
  46. package/dist/agent-adapter/pi/tool-shims.js +34 -1
  47. package/dist/agent-adapter/types.d.ts +6 -0
  48. package/dist/core/agents/subagent/types.d.ts +3 -0
  49. package/dist/core/config-generator.js +17 -2
  50. package/dist/core/debug-mode.d.ts +11 -10
  51. package/dist/core/debug-mode.js +12 -18
  52. package/dist/core/exec-async.d.ts +26 -0
  53. package/dist/core/exec-async.js +47 -0
  54. package/dist/core/locales/en.d.ts +14 -1
  55. package/dist/core/locales/slices/commands.d.ts +12 -1
  56. package/dist/core/locales/slices/commands.js +24 -2
  57. package/dist/core/locales/slices/startup.d.ts +2 -0
  58. package/dist/core/locales/slices/startup.js +4 -0
  59. package/dist/core/mcp-tool-gate.js +1 -0
  60. package/dist/core/media-types.d.ts +10 -0
  61. package/dist/core/media-types.js +34 -0
  62. package/dist/core/platform-settings-spec.js +1 -1
  63. package/dist/core/rebuild-progress.d.ts +58 -0
  64. package/dist/core/rebuild-progress.js +103 -0
  65. package/dist/core/resilient-watch.js +5 -3
  66. package/dist/core/run-registry.d.ts +7 -0
  67. package/dist/core/run-registry.js +6 -0
  68. package/dist/core/settings-spec.d.ts +21 -0
  69. package/dist/core/settings-spec.js +28 -1
  70. package/dist/core/types/agent-types.d.ts +3 -1
  71. package/dist/core/types/thread-types.d.ts +23 -4
  72. package/dist/core/utils.d.ts +1 -1
  73. package/dist/core/utils.js +1 -1
  74. package/dist/domain/agents/agent-state.d.ts +7 -0
  75. package/dist/domain/agents/agent-state.js +9 -1
  76. package/dist/domain/agents/agent-switch.d.ts +38 -0
  77. package/dist/domain/agents/agent-switch.js +106 -0
  78. package/dist/domain/agents/config.d.ts +20 -2
  79. package/dist/domain/agents/config.js +58 -4
  80. package/dist/domain/agents/index.d.ts +1 -0
  81. package/dist/domain/agents/index.js +1 -0
  82. package/dist/domain/agents/profile-manager.d.ts +6 -0
  83. package/dist/domain/agents/profile-manager.js +14 -1
  84. package/dist/domain/executions/registry.d.ts +3 -2
  85. package/dist/domain/executions/registry.js +84 -10
  86. package/dist/domain/mcp/bundled-server.js +4 -3
  87. package/dist/domain/mcp/feishu/file.js +37 -18
  88. package/dist/domain/mcp/feishu/types.d.ts +3 -0
  89. package/dist/domain/mcp/feishu-server.js +1 -1
  90. package/dist/domain/mcp/tools/{cortex-md.d.ts → agents-md.d.ts} +6 -6
  91. package/dist/domain/mcp/tools/{cortex-md.js → agents-md.js} +6 -6
  92. package/dist/domain/mcp/tools/remote-file.d.ts +20 -0
  93. package/dist/domain/mcp/tools/remote-file.js +44 -0
  94. package/dist/domain/mcp/tools/slack.d.ts +2 -0
  95. package/dist/domain/mcp/tools/slack.js +22 -7
  96. package/dist/domain/mcp/tools/task-ops.js +5 -13
  97. package/dist/domain/mcp/tools/ui-file.js +23 -10
  98. package/dist/domain/mcp/tools/waitpoint.d.ts +3 -0
  99. package/dist/domain/mcp/tools/waitpoint.js +122 -0
  100. package/dist/domain/memory/agents-md-injector.d.ts +24 -0
  101. package/dist/domain/memory/{cortex-md-injector.js → agents-md-injector.js} +10 -7
  102. package/dist/domain/plugins/runtime.js +1 -1
  103. package/dist/domain/plugins/skill-projection.d.ts +8 -2
  104. package/dist/domain/plugins/skill-projection.js +76 -19
  105. package/dist/domain/projects/project-store.d.ts +1 -1
  106. package/dist/domain/projects/project-store.js +3 -3
  107. package/dist/domain/remote/client-bootstrap.js +1 -1
  108. package/dist/domain/remote/client-hot-reload.d.ts +1 -1
  109. package/dist/domain/remote/client-hot-reload.js +30 -24
  110. package/dist/domain/remote/client-manager.js +39 -119
  111. package/dist/domain/remote/cortex-client-config.d.ts +1 -1
  112. package/dist/domain/remote/cortex-client-config.js +1 -1
  113. package/dist/domain/remote/device-file.d.ts +51 -0
  114. package/dist/domain/remote/device-file.js +193 -0
  115. package/dist/domain/remote/device-port.js +3 -0
  116. package/dist/domain/remote/reverse-stream.d.ts +18 -7
  117. package/dist/domain/remote/reverse-stream.js +19 -6
  118. package/dist/domain/runs/engine-spec.js +4 -0
  119. package/dist/domain/runs/request.d.ts +6 -0
  120. package/dist/domain/runs/run.js +1 -0
  121. package/dist/domain/runs/spec-loader.d.ts +4 -3
  122. package/dist/domain/runs/spec-loader.js +4 -3
  123. package/dist/domain/scheduling/jobs/sync-public.js +6 -6
  124. package/dist/domain/scheduling/scheduler.js +14 -12
  125. package/dist/domain/sessions/session-lifecycle.d.ts +5 -0
  126. package/dist/domain/sessions/session-lifecycle.js +13 -1
  127. package/dist/domain/system/rebuild-hold.d.ts +44 -0
  128. package/dist/domain/system/rebuild-hold.js +91 -0
  129. package/dist/domain/system/server-update-check.d.ts +2 -1
  130. package/dist/domain/system/server-update-check.js +15 -13
  131. package/dist/domain/tasks/archiver.js +21 -13
  132. package/dist/domain/tasks/claim-recovery.js +2 -2
  133. package/dist/domain/tasks/dispatch-utils.d.ts +10 -1
  134. package/dist/domain/tasks/dispatch-utils.js +46 -1
  135. package/dist/domain/tasks/dispatcher.js +4 -5
  136. package/dist/domain/tasks/mutator.d.ts +2 -2
  137. package/dist/domain/tasks/mutator.js +62 -61
  138. package/dist/domain/tasks/system/task-cli.js +2 -2
  139. package/dist/domain/tasks/system/task-completion.d.ts +7 -2
  140. package/dist/domain/tasks/system/task-completion.js +69 -6
  141. package/dist/domain/tasks/system/task-lifecycle-edit.d.ts +6 -1
  142. package/dist/domain/tasks/system/task-lifecycle-edit.js +21 -2
  143. package/dist/domain/tasks/system/task-lock.d.ts +23 -0
  144. package/dist/domain/tasks/system/task-lock.js +29 -1
  145. package/dist/domain/tasks/system/task-mutations.d.ts +14 -1
  146. package/dist/domain/tasks/system/task-mutations.js +25 -2
  147. package/dist/domain/tasks/system/task-state.d.ts +12 -1
  148. package/dist/domain/tasks/system/task-state.js +20 -3
  149. package/dist/domain/threads/prompt-builder.d.ts +9 -6
  150. package/dist/domain/threads/prompt-builder.js +28 -10
  151. package/dist/domain/threads/runner.js +10 -4
  152. package/dist/domain/threads/state-machine.js +15 -11
  153. package/dist/domain/threads/template-loader.js +6 -4
  154. package/dist/domain/threads/template-validate.d.ts +43 -6
  155. package/dist/domain/threads/template-validate.js +12 -0
  156. package/dist/domain/ui-service/app-router.d.ts +34 -3
  157. package/dist/domain/ui-service/app-router.js +9 -14
  158. package/dist/domain/ui-service/input-schemas.d.ts +28 -5
  159. package/dist/domain/ui-service/input-schemas.js +24 -9
  160. package/dist/domain/ui-service/mutate/platform-settings.js +1 -1
  161. package/dist/domain/ui-service/mutate/sessions.d.ts +6 -1
  162. package/dist/domain/ui-service/mutate/sessions.js +54 -0
  163. package/dist/domain/ui-service/mutate/tasks.js +4 -3
  164. package/dist/domain/ui-service/mutate/waitpoints.d.ts +2 -0
  165. package/dist/domain/ui-service/mutate/waitpoints.js +20 -0
  166. package/dist/domain/ui-service/platform-settings.js +1 -1
  167. package/dist/domain/ui-service/plugins-shared.js +1 -1
  168. package/dist/domain/ui-service/query/config.js +20 -2
  169. package/dist/domain/ui-service/query/executions.js +0 -2
  170. package/dist/domain/ui-service/query/machine-detail.js +3 -8
  171. package/dist/domain/ui-service/query/memory.js +29 -35
  172. package/dist/domain/ui-service/query/sessions.js +96 -12
  173. package/dist/domain/ui-service/query/system.js +19 -0
  174. package/dist/domain/ui-service/query/threads.js +1 -54
  175. package/dist/domain/ui-service/query/waitpoints.d.ts +30 -0
  176. package/dist/domain/ui-service/query/waitpoints.js +117 -0
  177. package/dist/domain/ui-service/query-input-schemas.d.ts +4 -0
  178. package/dist/domain/ui-service/query-input-schemas.js +5 -0
  179. package/dist/domain/ui-service/trpc.js +1 -1
  180. package/dist/domain/ui-service/types.d.ts +229 -51
  181. package/dist/domain/ui-service/types.js +1 -1
  182. package/dist/domain/ui-service/ui-service.js +8 -31
  183. package/dist/domain/waitpoints/notices.d.ts +21 -0
  184. package/dist/domain/waitpoints/notices.js +115 -0
  185. package/dist/domain/waitpoints/service.d.ts +91 -0
  186. package/dist/domain/waitpoints/service.js +243 -0
  187. package/dist/entry/app.js +52 -11
  188. package/dist/entry/auth-login-cli.js +1 -1
  189. package/dist/entry/auth-login-terminal.js +1 -1
  190. package/dist/entry/daemon-notice.d.ts +10 -1
  191. package/dist/entry/daemon-notice.js +16 -1
  192. package/dist/entry/daemon.d.ts +43 -2
  193. package/dist/entry/daemon.js +163 -9
  194. package/dist/entry/init-auth.js +1 -1
  195. package/dist/entry/init.js +6 -6
  196. package/dist/entry/signal-cli.d.ts +30 -0
  197. package/dist/entry/signal-cli.js +207 -0
  198. package/dist/entry/start-ui-http.d.ts +1 -1
  199. package/dist/entry/start-ui-http.js +2 -2
  200. package/dist/events/event-types.d.ts +0 -7
  201. package/dist/hooks/{cortex-md-injector.mjs → agents-md-injector.mjs} +117 -26
  202. package/dist/hooks/cortex-hook-api.mjs +2 -2
  203. package/dist/hooks/new-session-hook.mjs +2 -2
  204. package/dist/hooks/rules-loader.mjs +2 -2
  205. package/dist/hooks/status-md-guard.mjs +8 -8
  206. package/dist/hooks/task-status-check.mjs +18 -76
  207. package/dist/hooks/tasks-yaml-guard.mjs +2 -2
  208. package/dist/orchestration/agent-file-send.d.ts +9 -0
  209. package/dist/orchestration/agent-file-send.js +21 -2
  210. package/dist/orchestration/agent-runner.d.ts +3 -2
  211. package/dist/orchestration/agent-runner.js +33 -12
  212. package/dist/orchestration/attachments-store.d.ts +31 -0
  213. package/dist/orchestration/attachments-store.js +184 -0
  214. package/dist/orchestration/conversation-request.d.ts +37 -0
  215. package/dist/orchestration/conversation-request.js +91 -22
  216. package/dist/orchestration/interactions/plan-approvals.js +1 -1
  217. package/dist/orchestration/mid-turn-inject.d.ts +3 -0
  218. package/dist/orchestration/mid-turn-inject.js +9 -4
  219. package/dist/orchestration/outputs-store.d.ts +11 -0
  220. package/dist/orchestration/outputs-store.js +32 -6
  221. package/dist/orchestration/resume-dispatcher.js +4 -2
  222. package/dist/orchestration/routing/commands/mode.js +114 -63
  223. package/dist/orchestration/routing/file-handler.d.ts +23 -2
  224. package/dist/orchestration/routing/file-handler.js +22 -5
  225. package/dist/orchestration/routing/webhook.js +193 -39
  226. package/dist/orchestration/session-gateway.d.ts +1 -1
  227. package/dist/orchestration/session-gateway.js +1 -0
  228. package/dist/orchestration/thread-executor.d.ts +2 -0
  229. package/dist/orchestration/thread-executor.js +24 -1
  230. package/dist/orchestration/thread-input.d.ts +3 -2
  231. package/dist/orchestration/thread-input.js +8 -9
  232. package/dist/orchestration/turn/turn-prep.d.ts +15 -1
  233. package/dist/orchestration/turn/turn-prep.js +19 -8
  234. package/dist/orchestration/turn/turn.js +1 -0
  235. package/dist/orchestration/waitpoint-ingress.d.ts +41 -0
  236. package/dist/orchestration/waitpoint-ingress.js +172 -0
  237. package/dist/orchestration/waitpoint-notifier.d.ts +21 -0
  238. package/dist/orchestration/waitpoint-notifier.js +119 -0
  239. package/dist/orchestration/waitpoint-remote-drain.d.ts +20 -0
  240. package/dist/orchestration/waitpoint-remote-drain.js +147 -0
  241. package/dist/orchestration/waitpoint-sweep.d.ts +42 -0
  242. package/dist/orchestration/waitpoint-sweep.js +87 -0
  243. package/dist/platform/adapters/feishu-image.d.ts +19 -0
  244. package/dist/platform/adapters/feishu-image.js +71 -0
  245. package/dist/platform/adapters/feishu.d.ts +2 -0
  246. package/dist/platform/adapters/feishu.js +26 -16
  247. package/dist/platform/ui-http/listening-ports.d.ts +1 -1
  248. package/dist/platform/ui-http/listening-ports.js +1 -1
  249. package/dist/platform/ui-http/ui-session.js +1 -1
  250. package/dist/store/conversation-display-projection.d.ts +9 -1
  251. package/dist/store/conversation-display-projection.js +13 -6
  252. package/dist/store/conversation-history-reader.d.ts +19 -0
  253. package/dist/store/conversation-history-reader.js +163 -44
  254. package/dist/store/conversation-history-repo.d.ts +37 -10
  255. package/dist/store/conversation-history-repo.js +161 -139
  256. package/dist/store/conversation-ledger-repo.js +1 -1
  257. package/dist/store/execution-repo.d.ts +1 -19
  258. package/dist/store/execution-repo.js +1 -18
  259. package/dist/store/project-notes-repo.js +11 -2
  260. package/dist/store/prompt-migration-replacements.js +1 -1
  261. package/dist/store/session-registry-import.js +1 -1
  262. package/dist/store/session-registry-journal.d.ts +4 -0
  263. package/dist/store/session-registry-journal.js +5 -1
  264. package/dist/store/session-registry-repo.d.ts +2 -1
  265. package/dist/store/session-registry-repo.js +3 -1
  266. package/dist/store/task-repo.d.ts +6 -3
  267. package/dist/store/task-repo.js +26 -10
  268. package/dist/store/version-migrations.d.ts +13 -3
  269. package/dist/store/version-migrations.js +254 -24
  270. package/dist/store/waitpoint-repo.d.ts +108 -0
  271. package/dist/store/waitpoint-repo.js +94 -0
  272. package/package.json +3 -2
  273. package/web/dist/AGENTS.md +10 -0
  274. package/web/dist/assets/index-B1dBi8Za.css +1 -0
  275. package/web/dist/assets/{index-CEZ0DSei.js → index-BAeLybF0.js} +1 -1
  276. package/web/dist/assets/index-BcQI8Fh5.js +445 -0
  277. package/web/dist/index.html +12 -4
  278. package/web/dist/theme.css +211 -40
  279. package/defaults/config/hooks/08-cortex-md-injector-post-tool.json +0 -10
  280. package/dist/domain/executions/log-tailer.d.ts +0 -71
  281. package/dist/domain/executions/log-tailer.js +0 -194
  282. package/dist/domain/memory/cortex-md-injector.d.ts +0 -24
  283. package/dist/domain/memory/cortex-md-scanner.d.ts +0 -10
  284. package/dist/domain/memory/cortex-md-scanner.js +0 -66
  285. package/dist/domain/remote/cortex-client.d.ts +0 -1
  286. package/dist/domain/remote/cortex-client.js +0 -662
  287. package/dist/domain/tasks/system/cortex-run.d.ts +0 -25
  288. package/dist/domain/tasks/system/cortex-run.js +0 -360
  289. package/web/dist/assets/index-CRDJo39X.css +0 -1
  290. package/web/dist/assets/index-DjuPJVZE.js +0 -444
  291. /package/defaults/{CORTEX.md → AGENTS.md} +0 -0
  292. /package/defaults/config/{CORTEX.md → AGENTS.md} +0 -0
  293. /package/defaults/context/{CORTEX.md → AGENTS.md} +0 -0
  294. /package/defaults/context/ideas/{CORTEX.md → AGENTS.md} +0 -0
  295. /package/defaults/context/projects/{CORTEX.md → AGENTS.md} +0 -0
  296. /package/defaults/context/scans/{CORTEX.md → AGENTS.md} +0 -0
  297. /package/defaults/context/user/{CORTEX.md → AGENTS.md} +0 -0
@@ -62,6 +62,9 @@ export declare function setChannelOverride(channel: string, patch: Partial<Recor
62
62
  * seed then carries a profile and no overrides.
63
63
  */
64
64
  export declare function setSelectionDefault(seed: SelectionDefault | null): void;
65
+ /** Remember the composer's AGENT pick in the same seed, leaving the engine half alone. A null name
66
+ * records "the next conversation opens on the global default", which is a choice like any other. */
67
+ export declare function setSelectionDefaultAgent(agentName: string | null): void;
65
68
  /** The seed for the next conversation, or null when nothing has been picked on this host yet. */
66
69
  export declare function getSelectionDefault(): SelectionDefault | null;
67
70
  /** Drop every override the channel carries — what an explicit "run this profile as declared"
@@ -73,8 +76,23 @@ export declare function setChannelModelOverride(channel: string, model: string |
73
76
  /** The channel-scoped thinking level `!thinking` writes — the chat twin of the composer's picker.
74
77
  * Clearing drops ONLY the level: a model chosen separately was a separate decision. */
75
78
  export declare function setChannelThinkingOverride(channel: string, thinking: string | null): void;
76
- export declare function getDefaultAgent(): string | null;
77
- export declare function setDefaultAgent(name: string | null): void;
79
+ /**
80
+ * The agent a channel runs: its own selection, else the global default. Null when neither is set
81
+ * and the caller's own fallback applies.
82
+ *
83
+ * The channel layer is what makes an agent a per-conversation choice rather than a daemon-wide
84
+ * one — the same shape `getActiveProfile` has, and deliberately so: profile and agent are two
85
+ * independent axes (which model vs which environment) and each has its own channel map.
86
+ */
87
+ export declare function getDefaultAgent(channel?: string): string | null;
88
+ /** Set the agent for one channel (`channel` given) or the global default (omitted). A null name
89
+ * clears: for a channel that means "follow the global default again", globally it means "no
90
+ * default agent at all". */
91
+ export declare function setDefaultAgent(name: string | null, channel?: string): void;
92
+ /** Drop the channel's agent selection — it follows the global default again. */
93
+ export declare function clearChannelAgent(channel: string): void;
94
+ /** Every channel that has selected an agent of its own. */
95
+ export declare function getChannelAgents(): Record<string, string>;
78
96
  export declare function isApiRateLimitError(errorMessage: string | null | undefined): boolean;
79
97
  export declare function isRetryableResult(result: {
80
98
  rateLimited?: boolean;
@@ -207,6 +207,7 @@ let agentState = loadAgentState();
207
207
  let activeProfile = agentState.activeProfile;
208
208
  let channelProfiles = agentState.channelProfiles;
209
209
  let defaultAgent = agentState.defaultAgent;
210
+ let channelAgents = agentState.channelAgents;
210
211
  // Seeded from the migrated state so a CLI process that never reaches the daemon's composition root
211
212
  // still has a value; `entry/app.ts` overwrites it at boot with the default profile's model, which
212
213
  // is the D5-correct answer. Read by PI's subagent catalog and the MCP tool context.
@@ -219,7 +220,7 @@ process.env.CORTEX_CLAUDE_MODEL = agentState.claudeModel || DEFAULT_CLAUDE_MODEL
219
220
  * which is exactly what a rollback to an older build should find, since this build never
220
221
  * acted on them either. */
221
222
  function persist() {
222
- agentState = { ...agentState, activeProfile, channelProfiles, defaultAgent };
223
+ agentState = { ...agentState, activeProfile, channelProfiles, defaultAgent, channelAgents };
223
224
  saveAgentState(agentState);
224
225
  }
225
226
  function saveModeFile(profile = activeProfile, agent = defaultAgent) {
@@ -347,7 +348,26 @@ export function setChannelOverride(channel, patch) {
347
348
  * seed then carries a profile and no overrides.
348
349
  */
349
350
  export function setSelectionDefault(seed) {
350
- agentState = { ...agentState, selectionDefault: seed ?? undefined };
351
+ // The agent is carried forward: the engine seed and the environment seed are two different picks,
352
+ // and choosing a model is not a statement about which environment the next conversation opens in.
353
+ // `setSelectionDefaultAgent` is the only writer of that half.
354
+ const agentName = agentState.selectionDefault?.agentName;
355
+ const next = seed && agentName && !seed.agentName ? { ...seed, agentName } : seed;
356
+ agentState = { ...agentState, selectionDefault: next ?? undefined };
357
+ persist();
358
+ }
359
+ /** Remember the composer's AGENT pick in the same seed, leaving the engine half alone. A null name
360
+ * records "the next conversation opens on the global default", which is a choice like any other. */
361
+ export function setSelectionDefaultAgent(agentName) {
362
+ const seed = { ...(agentState.selectionDefault ?? {}) };
363
+ if (agentName)
364
+ seed.agentName = agentName;
365
+ else
366
+ delete seed.agentName;
367
+ agentState = {
368
+ ...agentState,
369
+ selectionDefault: Object.keys(seed).length > 0 ? seed : undefined,
370
+ };
351
371
  persist();
352
372
  }
353
373
  /** The seed for the next conversation, or null when nothing has been picked on this host yet. */
@@ -374,11 +394,45 @@ export function setChannelModelOverride(channel, model) {
374
394
  export function setChannelThinkingOverride(channel, thinking) {
375
395
  setChannelOverride(channel, { thinking });
376
396
  }
377
- export function getDefaultAgent() { return defaultAgent; }
378
- export function setDefaultAgent(name) {
397
+ /**
398
+ * The agent a channel runs: its own selection, else the global default. Null when neither is set
399
+ * and the caller's own fallback applies.
400
+ *
401
+ * The channel layer is what makes an agent a per-conversation choice rather than a daemon-wide
402
+ * one — the same shape `getActiveProfile` has, and deliberately so: profile and agent are two
403
+ * independent axes (which model vs which environment) and each has its own channel map.
404
+ */
405
+ export function getDefaultAgent(channel) {
406
+ if (channel && channelAgents[channel])
407
+ return channelAgents[channel];
408
+ return defaultAgent;
409
+ }
410
+ /** Set the agent for one channel (`channel` given) or the global default (omitted). A null name
411
+ * clears: for a channel that means "follow the global default again", globally it means "no
412
+ * default agent at all". */
413
+ export function setDefaultAgent(name, channel) {
414
+ if (channel) {
415
+ if (name)
416
+ channelAgents[channel] = name;
417
+ else
418
+ delete channelAgents[channel];
419
+ persist();
420
+ return;
421
+ }
379
422
  defaultAgent = name;
380
423
  saveModeFile(activeProfile, defaultAgent);
381
424
  }
425
+ /** Drop the channel's agent selection — it follows the global default again. */
426
+ export function clearChannelAgent(channel) {
427
+ if (!channelAgents[channel])
428
+ return;
429
+ delete channelAgents[channel];
430
+ persist();
431
+ }
432
+ /** Every channel that has selected an agent of its own. */
433
+ export function getChannelAgents() {
434
+ return { ...channelAgents };
435
+ }
382
436
  export function isApiRateLimitError(errorMessage) {
383
437
  if (!errorMessage)
384
438
  return false;
@@ -1,5 +1,6 @@
1
1
  export * from './config.js';
2
2
  export * from './profile-switch.js';
3
+ export * from './agent-switch.js';
3
4
  export * from './model-selection.js';
4
5
  export { resolveRateLimitProvider } from './provider-run-lifecycle.js';
5
6
  export { buildPiGatewaySubPath, CHANNEL_SCOPED_PLUGINS, COMMISSION_SCOPED_PLUGINS, filterChannelScopedPlugins, filterScopedPlugins, } from '../runs/engine-spec.js';
@@ -9,6 +9,7 @@
9
9
  // `@domain/runs/engine-spec.js`.
10
10
  export * from './config.js';
11
11
  export * from './profile-switch.js';
12
+ export * from './agent-switch.js';
12
13
  export * from './model-selection.js';
13
14
  export { resolveRateLimitProvider } from './provider-run-lifecycle.js';
14
15
  export { buildPiGatewaySubPath, CHANNEL_SCOPED_PLUGINS, COMMISSION_SCOPED_PLUGINS, filterChannelScopedPlugins, filterScopedPlugins, } from '../runs/engine-spec.js';
@@ -68,6 +68,12 @@ export declare const THINKING_LEVELS_BY_BACKEND: Record<Backend, readonly string
68
68
  /** Is `level` a value this backend accepts? The selection path's gate, the profile validator's
69
69
  * rule — one predicate. */
70
70
  export declare function isValidThinkingLevel(backend: Backend, level: string): boolean;
71
+ /**
72
+ * Identity, not a revision counter, is what makes this safe: every path that can change the
73
+ * profiles — `save`, `mutate`, and the hot-reload watcher's `invalidate` + `readSync` — installs a
74
+ * NEW object, so a stale verdict cannot outlive a change. A file that fails validation is never
75
+ * recorded, so it keeps throwing until it is fixed.
76
+ */
71
77
  declare function loadProfilesFile(): ProfilesFile;
72
78
  /**
73
79
  * Pure resolver: maps a ProfileEntry's claudeBackend field to one of the two accepted values.
@@ -22,10 +22,23 @@ const THINKING_LEVEL_SETS = {
22
22
  export function isValidThinkingLevel(backend, level) {
23
23
  return THINKING_LEVEL_SETS[backend]?.has(level) ?? false;
24
24
  }
25
+ /** The profiles object whose validation already passed. `profileRepo` caches the PARSE; the
26
+ * validation was left to run again on every call, and every caller of this module goes through
27
+ * here — a 300-session `sessions.list` revalidated the whole file 300 times per request. */
28
+ let validatedProfiles = null;
29
+ /**
30
+ * Identity, not a revision counter, is what makes this safe: every path that can change the
31
+ * profiles — `save`, `mutate`, and the hot-reload watcher's `invalidate` + `readSync` — installs a
32
+ * NEW object, so a stale verdict cannot outlive a change. A file that fails validation is never
33
+ * recorded, so it keeps throwing until it is fixed.
34
+ */
25
35
  function loadProfilesFile() {
26
36
  try {
27
37
  const data = profileRepo.readSync();
28
- validateProfilesFile(data);
38
+ if (data !== validatedProfiles) {
39
+ validateProfilesFile(data);
40
+ validatedProfiles = data;
41
+ }
29
42
  return data;
30
43
  }
31
44
  catch (error) {
@@ -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
@@ -10,6 +10,8 @@ export { TERMINAL_STATUSES };
10
10
  * cannot recover it because re-entry completes under a NEW executionId that no longer matches
11
11
  * the original lock owner — leaking the lock until its 20-min TTL expires. Idempotent. */
12
12
  export declare function releaseExecutionLocks(executionId: string | null | undefined): void;
13
+ /** Async twin of `releaseExecutionLocks` for event-loop-sensitive callers (thread suspend path). */
14
+ export declare function releaseExecutionLocksAsync(executionId: string | null | undefined): Promise<void>;
13
15
  export declare function getExecution(id: string): import("../../store/execution-repo.js").ExecutionRecord;
14
16
  export declare function getExecutionByTaskId(taskId: string | null | undefined): import("../../store/execution-repo.js").ExecutionRecord;
15
17
  export declare function getAll(): import("../../store/execution-repo.js").ExecutionRecord[];
@@ -18,7 +20,6 @@ export declare function findRunningDispatchMatch(opts: Parameters<typeof executi
18
20
  export declare function startLocalExecution(opts: Parameters<typeof executionRepo.startLocalExecution>[0]): import("../../store/execution-repo.js").ExecutionRecord;
19
21
  export declare function registerDispatchExecution(opts: Parameters<typeof executionRepo.registerDispatchExecution>[0]): import("../../store/execution-repo.js").ExecutionRecord;
20
22
  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
23
  export declare function completeExecution(id: string, metrics?: Parameters<typeof executionRepo.completeExecution>[1]): import("../../store/execution-repo.js").ExecutionRecord;
23
24
  export declare function completeExecutionByTaskId(taskId: string, metrics?: Parameters<typeof executionRepo.completeExecutionByTaskId>[1]): import("../../store/execution-repo.js").ExecutionRecord;
24
25
  export declare function failExecution(id: string, metrics?: Parameters<typeof executionRepo.failExecution>[1]): import("../../store/execution-repo.js").ExecutionRecord;
@@ -4,30 +4,103 @@
4
4
  // Lock-release: every terminal transition (complete/fail/cancel/stale) auto-releases any task lock held by the executionId.
5
5
  // releaseExecutionLocks(id) exposes the same release for the thread SUSPEND path (thread_wait) WITHOUT ending the execution (DR-0014 lock hygiene).
6
6
  import * as fs from 'node:fs';
7
+ import * as fsp from 'node:fs/promises';
8
+ import path from 'node:path';
7
9
  import { executionRepo, TERMINAL_STATUSES } from '../../store/execution-repo.js';
8
10
  import { PROJECTS_DIR } from '../../core/utils.js';
9
- import { readLock, releaseLock } from '../tasks/system/task-lock.js';
11
+ import { releaseLock, releaseLockAsync } from '../tasks/system/task-lock.js';
12
+ import { parseTasksFileWithLock } from '../../core/task-parser.js';
10
13
  import { createLogger } from '../../core/log.js';
11
14
  import { runRegistry } from '../../core/run-registry.js';
12
15
  export { TERMINAL_STATUSES };
13
16
  const lockLog = createLogger('execution-lock-release');
17
+ /** Project directories that currently have a TASKS.yaml. One readdir, no per-project stat. */
18
+ function projectsWithTasksFile() {
19
+ let names;
20
+ try {
21
+ names = fs.readdirSync(PROJECTS_DIR, { withFileTypes: true })
22
+ .filter(d => d.isDirectory()).map(d => d.name);
23
+ }
24
+ catch {
25
+ return [];
26
+ }
27
+ const out = [];
28
+ for (const project of names) {
29
+ const tasksPath = path.join(PROJECTS_DIR, project, 'TASKS.yaml');
30
+ if (fs.existsSync(tasksPath))
31
+ out.push({ project, tasksPath });
32
+ }
33
+ return out;
34
+ }
14
35
  /** Release any task locks still owned by `executionId` after its agent finished.
15
- * Idempotent — `releaseLock` returns success on absent or non-matching locks. */
36
+ * Idempotent — `releaseLock` returns success on absent or non-matching locks.
37
+ *
38
+ * The lock lives inside TASKS.yaml, so a project whose file does not even mention the execution
39
+ * id cannot hold a matching lock. Reading + substring-scanning the ~22 task files costs ~0.4ms;
40
+ * YAML-parsing all of them costs ~20ms (measured), so the parse is deferred to the rare match.
41
+ * This function stays sync because terminal transitions (and their tests) are sync; event-loop-
42
+ * sensitive callers use `releaseLocksOwnedByAsync` instead. */
16
43
  function releaseLocksOwnedBy(executionId) {
44
+ if (!executionId)
45
+ return;
46
+ for (const { project, tasksPath } of projectsWithTasksFile()) {
47
+ let content;
48
+ try {
49
+ content = fs.readFileSync(tasksPath, 'utf8');
50
+ }
51
+ catch {
52
+ continue;
53
+ }
54
+ if (!content.includes(executionId))
55
+ continue;
56
+ let lock;
57
+ try {
58
+ lock = parseTasksFileWithLock(content, project).lock;
59
+ }
60
+ catch {
61
+ continue;
62
+ }
63
+ if (!lock || lock.owner !== executionId)
64
+ continue;
65
+ try {
66
+ const r = releaseLock(project, executionId);
67
+ if (r.released) {
68
+ lockLog.warn(`auto-released stale lock on '${project}' held by execution ${executionId} ` +
69
+ `(agent finished without calling cortex-task lock-release)`);
70
+ }
71
+ }
72
+ catch (err) {
73
+ lockLog.warn(`release attempt failed for ${project} / ${executionId}: ${err?.message || err}`);
74
+ }
75
+ }
76
+ }
77
+ /** Async twin of `releaseLocksOwnedBy`: no sync fs and no sync mutation-lock wait, so an
78
+ * event-loop-sensitive caller (thread suspend, stale reconciliation) never parks the process on a
79
+ * contended cross-process lock. Same pre-filter, same owner-match semantics, same logging. */
80
+ async function releaseLocksOwnedByAsync(executionId) {
17
81
  if (!executionId)
18
82
  return;
19
83
  let projects;
20
84
  try {
21
- projects = fs.readdirSync(PROJECTS_DIR, { withFileTypes: true })
85
+ projects = (await fsp.readdir(PROJECTS_DIR, { withFileTypes: true }))
22
86
  .filter(d => d.isDirectory()).map(d => d.name);
23
87
  }
24
88
  catch {
25
89
  return;
26
90
  }
27
91
  for (const project of projects) {
92
+ let content;
93
+ try {
94
+ content = await fsp.readFile(path.join(PROJECTS_DIR, project, 'TASKS.yaml'), 'utf8');
95
+ }
96
+ catch {
97
+ continue;
98
+ }
99
+ if (!content.includes(executionId))
100
+ continue;
28
101
  let lock;
29
102
  try {
30
- lock = readLock(project);
103
+ lock = parseTasksFileWithLock(content, project).lock;
31
104
  }
32
105
  catch {
33
106
  continue;
@@ -35,7 +108,7 @@ function releaseLocksOwnedBy(executionId) {
35
108
  if (!lock || lock.owner !== executionId)
36
109
  continue;
37
110
  try {
38
- const r = releaseLock(project, executionId);
111
+ const r = await releaseLockAsync(project, executionId);
39
112
  if (r.released) {
40
113
  lockLog.warn(`auto-released stale lock on '${project}' held by execution ${executionId} ` +
41
114
  `(agent finished without calling cortex-task lock-release)`);
@@ -56,6 +129,10 @@ function releaseLocksOwnedBy(executionId) {
56
129
  export function releaseExecutionLocks(executionId) {
57
130
  releaseLocksOwnedBy(executionId);
58
131
  }
132
+ /** Async twin of `releaseExecutionLocks` for event-loop-sensitive callers (thread suspend path). */
133
+ export async function releaseExecutionLocksAsync(executionId) {
134
+ await releaseLocksOwnedByAsync(executionId);
135
+ }
59
136
  // --- Sync reads ---
60
137
  export function getExecution(id) {
61
138
  return executionRepo.getExecution(id);
@@ -82,9 +159,6 @@ export function registerDispatchExecution(opts) {
82
159
  export function touchExecution(id, patch) {
83
160
  return executionRepo.touchExecution(id, patch);
84
161
  }
85
- export function setExecutionGpuByTaskId(taskId, gpu) {
86
- return executionRepo.setExecutionGpuByTaskId(taskId, gpu);
87
- }
88
162
  export function completeExecution(id, metrics) {
89
163
  const r = executionRepo.completeExecution(id, metrics);
90
164
  if (r && TERMINAL_STATUSES.has(r.status))
@@ -159,13 +233,13 @@ export function teardownExecution({ executionId, status, result, error, duration
159
233
  export async function markMissingRunningExecutionsStale(keepRunning) {
160
234
  const staled = await executionRepo.markMissingRunningExecutionsStale(keepRunning);
161
235
  for (const id of staled)
162
- releaseLocksOwnedBy(id);
236
+ await releaseLocksOwnedByAsync(id);
163
237
  return staled;
164
238
  }
165
239
  export async function reconcileStaleDispatches(opts) {
166
240
  const { count, staled } = await executionRepo.reconcileStaleDispatches(opts);
167
241
  for (const id of staled)
168
- releaseLocksOwnedBy(id);
242
+ await releaseLocksOwnedByAsync(id);
169
243
  return count;
170
244
  }
171
245
  // --- Deprecated ---
@@ -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
@@ -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
+ }