@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
@@ -107,6 +107,10 @@ function spawnPolicy(request) {
107
107
  // and `disableHooks` are the same fact with opposite polarity, and `undefined` must survive
108
108
  // as `undefined` so an unset policy keeps the adapter's own default.
109
109
  disableHooks: request.policy.hooks === undefined ? undefined : !request.policy.hooks,
110
+ // Same polarity rule for skills, and the same reason to keep `undefined` alive: only an
111
+ // agent that opted out states anything here.
112
+ disableSkills: request.policy.skills === false ? true : undefined,
113
+ settingSources: request.policy.settingSources,
110
114
  streamDeltas: request.policy.streamDeltas,
111
115
  captureTranscripts: request.policy.captureTranscripts,
112
116
  preserveUnreportedAccounting: request.benchmark?.preserveUnreportedAccounting,
@@ -55,6 +55,12 @@ export interface RunRequest {
55
55
  hooks: boolean;
56
56
  streamDeltas?: boolean;
57
57
  loadRules: boolean;
58
+ /** Whether the backend loads its skill layer. Absent keeps the backend's own default (every
59
+ * skill it can see); false is how an agent runs with none. */
60
+ skills?: boolean;
61
+ /** Which setting files the backend may load beyond what Cortex passes. Absent keeps its
62
+ * default; `[]` loads none. */
63
+ settingSources?: string[];
58
64
  mcpComposition: McpComposition;
59
65
  /** Legacy thread-surface selector: only consulted when `mcpComposition` is undefined (the
60
66
  * thread path always resolves an explicit value). */
@@ -332,6 +332,7 @@ export class AgentRunImpl {
332
332
  run: this,
333
333
  trackSessionId: this.request.session.sessionId,
334
334
  backendSessionId: attempt.backendSessionId ?? this.request.session.backendSessionId,
335
+ subagent: this.request.context.trigger === 'subagent',
335
336
  });
336
337
  // The engine's spawn-time backend id is authoritative even when it never emits a
337
338
  // `session_started` event (an interrupted first turn). Surfaces that persist the resume target
@@ -56,9 +56,10 @@ export declare function bareSpec(): AgentSpec;
56
56
  * `fromAgentDefinition`): `AgentDefinition` merged with any per-template ref overrides, which
57
57
  * `threads/template-loader.resolveAgentSlotConfig` already produced and both callers hold.
58
58
  *
59
- * `mcpComposition` is the caller's, not the slot's: a thread step gets the thread-control surface
60
- * and a plain conversation gets the direct one, and that is a property of the surface the run is
61
- * opened on rather than of the agent.
59
+ * `mcpComposition` is the surface's default, which the agent may override: the caller passes what
60
+ * the surface would otherwise run on (thread-control for a thread step, direct for a plain
61
+ * conversation) and resolves `config.mcpComposition` over it before calling, so an agent that
62
+ * declares a narrower surface keeps it on every path.
62
63
  */
63
64
  export declare function fromAgentSlot(config: AgentSlotConfig, opts: {
64
65
  mcpComposition: McpComposition;
@@ -17,9 +17,10 @@ export function bareSpec() {
17
17
  * `fromAgentDefinition`): `AgentDefinition` merged with any per-template ref overrides, which
18
18
  * `threads/template-loader.resolveAgentSlotConfig` already produced and both callers hold.
19
19
  *
20
- * `mcpComposition` is the caller's, not the slot's: a thread step gets the thread-control surface
21
- * and a plain conversation gets the direct one, and that is a property of the surface the run is
22
- * opened on rather than of the agent.
20
+ * `mcpComposition` is the surface's default, which the agent may override: the caller passes what
21
+ * the surface would otherwise run on (thread-control for a thread step, direct for a plain
22
+ * conversation) and resolves `config.mcpComposition` over it before calling, so an agent that
23
+ * declares a narrower surface keeps it on every path.
23
24
  */
24
25
  export function fromAgentSlot(config, opts) {
25
26
  return {
@@ -1,4 +1,4 @@
1
- import { execFileSync } from 'child_process';
1
+ import { runFile } from '../../../core/exec-async.js';
2
2
  import * as path from 'path';
3
3
  import { register, ctx } from '../job-registry.js';
4
4
  import { Icons } from '../../../core/icons.js';
@@ -16,11 +16,11 @@ register('sync-public', async (payload) => {
16
16
  const syncScript = resolveSyncPublicScript();
17
17
  if (!syncScript)
18
18
  throw new Error('CORTEX_REPO is unset; public sync requires a source checkout');
19
- const output = execFileSync('bash', [syncScript], {
20
- timeout: 30_000,
21
- encoding: 'utf-8',
22
- stdio: ['pipe', 'pipe', 'pipe'],
23
- });
19
+ // Async: this is a scheduled job inside the long-lived server process.
20
+ const synced = await runFile('bash', [syncScript], { timeoutMs: 30_000 });
21
+ if (!synced.ok)
22
+ throw new Error((synced.stderr || synced.error || 'sync script failed').trim());
23
+ const output = synced.stdout;
24
24
  const lines = output.trim().split('\n');
25
25
  const lastLine = lines[lines.length - 1] || '';
26
26
  if (lastLine.includes('0 failed') || lastLine.includes('everything in sync') || lastLine.includes('OK:') || lastLine.includes('SKIP:')) {
@@ -1,6 +1,6 @@
1
1
  import { watch } from 'fs';
2
- import { execSync } from 'child_process';
3
2
  import { randomBytes } from 'crypto';
3
+ import { runShell } from '../../core/exec-async.js';
4
4
  import { Icons } from '../../core/icons.js';
5
5
  import { DATA_DIR } from '../../core/utils.js';
6
6
  import { createLogger } from '../../core/log.js';
@@ -453,17 +453,19 @@ class Scheduler {
453
453
  if (task.preCheck) {
454
454
  const freshTask = await this._repo.findTask(task.id);
455
455
  if (freshTask?.preCheck) {
456
- try {
457
- execSync(freshTask.preCheck, {
458
- timeout: 15000,
459
- env: { ...process.env, PRECHECK_LAST_RUN: String(freshTask.lastRun || 0) },
460
- stdio: 'pipe',
461
- cwd: DATA_DIR,
462
- });
463
- }
464
- catch (e) {
465
- const output = (e.stdout || e.stderr || '').toString().trim();
466
- log.info(`Pre-check skip for ${task.id}: ${output || 'exit ' + e.status}`);
456
+ // Async: a preCheck is arbitrary user shell, so it must never block the event loop
457
+ // (execSync here stalled every session, socket and timer for up to the timeout).
458
+ const precheck = await runShell(freshTask.preCheck, {
459
+ timeoutMs: 15000,
460
+ env: { ...process.env, PRECHECK_LAST_RUN: String(freshTask.lastRun || 0) },
461
+ cwd: DATA_DIR,
462
+ });
463
+ if (!precheck.ok) {
464
+ const output = (precheck.stdout || precheck.stderr || '').trim();
465
+ const outcome = precheck.timedOut
466
+ ? 'timeout'
467
+ : `exit ${precheck.code ?? precheck.signal ?? 'unknown'}`;
468
+ log.info(`Pre-check skip for ${task.id}: ${output || outcome}`);
467
469
  await this._withWriteGuard(() => this._repo.updateTask(task.id, (t) => {
468
470
  const nextDelayMs = getNextDelay(t);
469
471
  t.nextRun = Date.now() + nextDelayMs;
@@ -12,6 +12,7 @@ export interface SessionRegistryWriter {
12
12
  projectId: string;
13
13
  label?: string | null;
14
14
  profileName?: string | null;
15
+ agentName?: string | null;
15
16
  browser?: SessionBrowserOption | null;
16
17
  commissionId?: string | null;
17
18
  commissionDraft?: string | null;
@@ -28,6 +29,9 @@ export interface RegisterNamedSessionOpts {
28
29
  origin?: SessionOrigin;
29
30
  label?: string | null;
30
31
  profileName?: string | null;
32
+ /** The agent template the session runs as; null/absent means it follows the channel's selection
33
+ * and, beneath that, the global default. */
34
+ agentName?: string | null;
31
35
  /** Opt-in browser access for this session; null/absent means no browser tools at all. */
32
36
  browser?: SessionBrowserOption | null;
33
37
  /** Commission membership, fixed at creation (DR-0037 v2). */
@@ -71,6 +75,7 @@ export declare function createDirectSession(deps: CreateDirectSessionDeps, opts:
71
75
  projectId: string;
72
76
  sessionId?: string;
73
77
  profileName?: string | null;
78
+ agentName?: string | null;
74
79
  selection?: {
75
80
  model?: string;
76
81
  provider?: string;
@@ -1,7 +1,7 @@
1
1
  import * as crypto from 'node:crypto';
2
2
  import { setSessionAsync, deleteSessionAsync } from './session.js';
3
3
  import { conversationLedger } from '../../store/conversation-ledger-repo.js';
4
- import { applyChannelSelection, setActiveProfile } from '../agents/index.js';
4
+ import { applyChannelSelection, setActiveProfile, setDefaultAgent, setSelectionDefaultAgent, } from '../agents/index.js';
5
5
  import { resolveProfileConfig } from '../agents/profile-manager.js';
6
6
  import * as sessionBackup from './session-backup.js';
7
7
  import { resolveCommissionCreate } from '../commissions/commission-draft.js';
@@ -23,6 +23,7 @@ export async function registerNamedSession(store, opts) {
23
23
  projectId: opts.projectId,
24
24
  label: opts.label ?? null,
25
25
  profileName: opts.profileName ?? null,
26
+ agentName: opts.agentName ?? null,
26
27
  browser: opts.browser ?? null,
27
28
  commissionId: commission?.commissionId ?? opts.commissionId ?? null,
28
29
  commissionDraft: commission?.commissionDraft ?? opts.commissionDraft ?? null,
@@ -71,6 +72,16 @@ export async function createDirectSession(deps, opts) {
71
72
  mode: opts.selection.mode ?? null,
72
73
  });
73
74
  }
75
+ // The environment the session opens in, written to the channel BEFORE the first turn is routed
76
+ // (the run path resolves the agent per turn from the session record, then this map). No switch
77
+ // rule is needed: a channel minted here has no history, so the cross-backend guard the rule
78
+ // exists for has nothing to refuse.
79
+ if (opts.agentName)
80
+ setDefaultAgent(opts.agentName, channel);
81
+ // Seeded on the same condition as the selection above: `selection` present is what marks a
82
+ // composer behind this call, and a composer that named no agent stated the default.
83
+ if (opts.selection)
84
+ setSelectionDefaultAgent(opts.agentName ?? null);
74
85
  // settings.commissionEnabled is the feature's kill switch (on by default since DR-0037 v4).
75
86
  // Refuse here rather than downgrade: a caller that asked for a commission and silently got an
76
87
  // ordinary session would only discover it much later. This is the server-side backstop for every
@@ -85,6 +96,7 @@ export async function createDirectSession(deps, opts) {
85
96
  projectId: opts.projectId,
86
97
  origin: 'direct',
87
98
  profileName: opts.profileName ?? null,
99
+ agentName: opts.agentName ?? null,
88
100
  browser: opts.browser ?? null,
89
101
  commissionFor: opts.commission
90
102
  ? (name) => resolveCommissionCreate(opts.projectId, name, opts.commission)
@@ -0,0 +1,44 @@
1
+ import type { PlatformAdapter } from '../../platform/index.js';
2
+ export interface RebuildHold {
3
+ /** The pipeline step in flight ('web', 'install', 'restart'), when the supervisor named one. */
4
+ phase: string | null;
5
+ /** What triggered the rebuild, verbatim ('src change: core/foo.ts'). */
6
+ reason: string | null;
7
+ /** When this process first started holding, in epoch ms. */
8
+ since: number;
9
+ }
10
+ /** Apply a supervisor hold message. Renews the lease and keeps the original `since`, so the UI and
11
+ * the refusal text can say how long the app has been closed for business. */
12
+ export declare function holdNewTurns(p: {
13
+ phase?: string | null;
14
+ reason?: string | null;
15
+ now?: number;
16
+ }): void;
17
+ /** Lift the hold (pipeline aborted, or finished without replacing this process). */
18
+ export declare function releaseNewTurnHold(): void;
19
+ /** The active hold, or null. Reading it is what expires a stale lease. */
20
+ export declare function rebuildHold(now?: number): RebuildHold | null;
21
+ /** True while new turns must be refused. */
22
+ export declare function isRebuildHeld(now?: number): boolean;
23
+ /**
24
+ * Tell whoever sent this message that it was not processed. Never throws — a refusal that fails to
25
+ * be delivered must still leave the turn un-started.
26
+ *
27
+ * Two audiences, two channels. A person who just typed gets the answer where they typed it, and
28
+ * nothing else: they are looking at that conversation. A callback (a finished background agent, a
29
+ * woken thread, a resume) has no reader, so it becomes a warning-level system notice instead — that
30
+ * is the difference between "the restart ate my subagent's report" and knowing which message to
31
+ * re-drive. Either way the work itself is NOT re-queued: nothing here survives the restart.
32
+ */
33
+ export declare function refuseTurnForRebuild(p: {
34
+ adapter: PlatformAdapter;
35
+ channel: string;
36
+ /** The refused message's text, for the notice. */
37
+ text: string;
38
+ /** True when a human is waiting on this message in `channel`. */
39
+ interactive: boolean;
40
+ }): Promise<void>;
41
+ /** Test hook: drop the hold between cases. */
42
+ export declare const _test: {
43
+ reset(): void;
44
+ };
@@ -0,0 +1,91 @@
1
+ // input: entry/daemon-notice.ts (the supervisor's 'rebuild-hold' IPC message)
2
+ // output: isRebuildHeld() / rebuildHold() — the admission answer every turn starter asks —
3
+ // plus refuseTurnForRebuild(), the one wording for a turn that was not admitted
4
+ // pos: the one piece of supervisor-pushed state this process keeps. The daemon knows it is about
5
+ // to rebuild and replace us; nothing inside the app can work that out on its own.
6
+ //
7
+ // Why a turn must not start under a hold: the app spawns the backend CLI as its own child and owns
8
+ // its stdout. When the supervisor SIGTERMs the app, that CLI keeps running (it is past the point of
9
+ // caring) and writes its answer into a pipe with no reader — a turn that is never delivered, never
10
+ // completes, and leaves the session showing "processing" forever. Refusing the turn up front turns
11
+ // a silent orphan into a message the person can resend.
12
+ //
13
+ // The hold EXPIRES. A daemon that dies mid-pipeline must not leave this process refusing work for
14
+ // the rest of its life, so every phase change renews a short lease and the absence of news
15
+ // eventually means "carry on".
16
+ import { Icons } from '../../core/icons.js';
17
+ import { t } from '../../core/i18n.js';
18
+ import { emitSystemNotice } from './system-notice.js';
19
+ /** How long a single 'hold' message is trusted. The supervisor re-sends on every phase change, and
20
+ * the longest single phase (web build, or `npm install -g` rewriting the vendored closure) runs
21
+ * well inside this. Fails open by design. */
22
+ const HOLD_LEASE_MS = 5 * 60_000;
23
+ let held = null;
24
+ /** Apply a supervisor hold message. Renews the lease and keeps the original `since`, so the UI and
25
+ * the refusal text can say how long the app has been closed for business. */
26
+ export function holdNewTurns(p) {
27
+ const now = p.now ?? Date.now();
28
+ held = {
29
+ phase: p.phase ?? null,
30
+ reason: p.reason ?? null,
31
+ since: held?.since ?? now,
32
+ expiresAt: now + HOLD_LEASE_MS,
33
+ };
34
+ }
35
+ /** Lift the hold (pipeline aborted, or finished without replacing this process). */
36
+ export function releaseNewTurnHold() {
37
+ held = null;
38
+ }
39
+ /** The active hold, or null. Reading it is what expires a stale lease. */
40
+ export function rebuildHold(now = Date.now()) {
41
+ if (!held)
42
+ return null;
43
+ if (now >= held.expiresAt) {
44
+ held = null;
45
+ return null;
46
+ }
47
+ const { phase, reason, since } = held;
48
+ return { phase, reason, since };
49
+ }
50
+ /** True while new turns must be refused. */
51
+ export function isRebuildHeld(now = Date.now()) {
52
+ return rebuildHold(now) !== null;
53
+ }
54
+ /** Longest message excerpt carried into the dropped-message notice. Enough to recognise which
55
+ * message it was, short enough for a toast. */
56
+ const PREVIEW_CHARS = 160;
57
+ function preview(text) {
58
+ const flat = text.replace(/\s+/g, ' ').trim();
59
+ if (!flat)
60
+ return '(no text)';
61
+ return flat.length > PREVIEW_CHARS ? `${flat.slice(0, PREVIEW_CHARS)}…` : flat;
62
+ }
63
+ /**
64
+ * Tell whoever sent this message that it was not processed. Never throws — a refusal that fails to
65
+ * be delivered must still leave the turn un-started.
66
+ *
67
+ * Two audiences, two channels. A person who just typed gets the answer where they typed it, and
68
+ * nothing else: they are looking at that conversation. A callback (a finished background agent, a
69
+ * woken thread, a resume) has no reader, so it becomes a warning-level system notice instead — that
70
+ * is the difference between "the restart ate my subagent's report" and knowing which message to
71
+ * re-drive. Either way the work itself is NOT re-queued: nothing here survives the restart.
72
+ */
73
+ export async function refuseTurnForRebuild(p) {
74
+ const phase = rebuildHold()?.phase ?? 'restart';
75
+ if (p.interactive) {
76
+ const destination = { type: 'interactive-reply', conduit: p.channel, sessionId: '' };
77
+ await p.adapter
78
+ .postMessage(destination, { text: `${Icons.warning} ${t('startup.rebuildHold', { phase })}` })
79
+ .catch(() => { });
80
+ return;
81
+ }
82
+ await emitSystemNotice(p.adapter, {
83
+ level: 'warning',
84
+ title: 'Rebuild',
85
+ text: t('startup.rebuildHoldDropped', { phase, channel: p.channel, preview: preview(p.text) }),
86
+ }).catch(() => { });
87
+ }
88
+ /** Test hook: drop the hold between cases. */
89
+ export const _test = {
90
+ reset() { held = null; },
91
+ };
@@ -5,7 +5,8 @@ export { compareCalVer };
5
5
  export declare function isUpdateDevMode(): boolean;
6
6
  export interface CheckServerUpdateDeps {
7
7
  prompt: UpdatePrompt;
8
- getLatest?: () => string | null;
8
+ /** May be async: the default implementation shells out to `npm view` without blocking. */
9
+ getLatest?: () => string | null | Promise<string | null>;
9
10
  spawnInstall?: () => void;
10
11
  loadState?: () => UpdateState | null;
11
12
  saveState?: (s: UpdateState) => void;
@@ -1,6 +1,8 @@
1
1
  import * as fs from 'node:fs';
2
- import { execSync, spawn } from 'node:child_process';
2
+ import * as os from 'node:os';
3
+ import { spawn } from 'node:child_process';
3
4
  import { getSettings } from '../../core/settings.js';
5
+ import { runFile } from '../../core/exec-async.js';
4
6
  import { CORTEX_VERSION } from '../../core/version.js';
5
7
  import { loadUpdateState, saveUpdateState } from './update-state.js';
6
8
  import { reportServerUpdateFailed, reportServerUpdateInstalled } from './update-ui-state.js';
@@ -24,18 +26,18 @@ export function isUpdateDevMode() {
24
26
  }
25
27
  }
26
28
  // ── Default implementations ─────────────────────────────────────
27
- function defaultGetLatest() {
28
- try {
29
- const result = execSync('npm view @cortex-agent/server version', {
30
- encoding: 'utf8',
31
- timeout: 15000,
32
- stdio: 'pipe',
33
- }).trim();
34
- return result || null;
35
- }
36
- catch {
29
+ /** Async: `npm view` is a network round trip and must not stall the event loop (it used to run
30
+ * via execSync with a 15s timeout, on a timer that fires 60s after boot). */
31
+ async function defaultGetLatest() {
32
+ const result = await runFile('npm', ['view', '@cortex-agent/server', 'version'], {
33
+ timeoutMs: 15000,
34
+ // Outside any project checkout, so a local .npmrc cannot redirect the registry lookup.
35
+ cwd: os.tmpdir(),
36
+ });
37
+ if (!result.ok)
37
38
  return null;
38
- }
39
+ const version = result.stdout.trim();
40
+ return version || null;
39
41
  }
40
42
  /** Keep the reported stderr small enough to sit in a dialog and in the status snapshot. */
41
43
  const INSTALL_STDERR_CAP = 2000;
@@ -91,7 +93,7 @@ export async function checkServerUpdate(deps) {
91
93
  const saveState = deps.saveState ?? saveUpdateState;
92
94
  const now = deps.now ?? defaultNow;
93
95
  // 2. Fetch latest version
94
- const latestVersion = getLatest();
96
+ const latestVersion = await getLatest();
95
97
  if (latestVersion === null) {
96
98
  return { action: null, latestVersion: null };
97
99
  }
@@ -1,9 +1,9 @@
1
1
  import * as fs from 'fs';
2
2
  import * as path from 'path';
3
- import { execSync } from 'child_process';
3
+ import { runFile } from '../../core/exec-async.js';
4
4
  import { PROJECTS_DIR, DATA_DIR } from '../../core/utils.js';
5
5
  import { createLogger } from '../../core/log.js';
6
- import { readTasks, withTaskFileMutationLock, writeTasks, } from './system/task-lifecycle-edit.js';
6
+ import { readTasks, withTaskFileMutationLockAsync, writeTasks, } from './system/task-lifecycle-edit.js';
7
7
  import { taskStore } from './store.js';
8
8
  const log = createLogger('task-archiver');
9
9
  const ARCHIVE_AGE_DAYS = 3;
@@ -60,10 +60,10 @@ function processProjectUnlocked(projectName) {
60
60
  fs.writeFileSync(archivePath, archiveContent);
61
61
  return { project: projectName, ids: archivedIds };
62
62
  }
63
- function processProject(projectName) {
64
- return withTaskFileMutationLock(projectName, () => processProjectUnlocked(projectName));
63
+ async function processProject(projectName) {
64
+ return withTaskFileMutationLockAsync(projectName, async () => processProjectUnlocked(projectName));
65
65
  }
66
- function gitCommit(results) {
66
+ async function gitCommit(results) {
67
67
  const files = [];
68
68
  for (const r of results) {
69
69
  const projectDir = path.join(PROJECTS_DIR, r.project);
@@ -71,16 +71,24 @@ function gitCommit(results) {
71
71
  files.push(path.join(projectDir, 'tasks-archive.md'));
72
72
  }
73
73
  try {
74
- const gitArgs = files.map((f) => `"${f}"`).join(' ');
75
- execSync(`git add ${gitArgs}`, { cwd: DATA_DIR, stdio: 'pipe' });
76
- const status = execSync('git diff --cached --stat', { cwd: DATA_DIR, encoding: 'utf8' });
77
- if (!status.trim()) {
74
+ // Async git (was execSync): this job runs inside the shared server process.
75
+ const added = await runFile('git', ['add', ...files], { cwd: DATA_DIR, timeoutMs: 10000 });
76
+ if (!added.ok) {
77
+ log.error('Git add failed:', (added.stderr || added.error || '').trim());
78
+ return;
79
+ }
80
+ const status = await runFile('git', ['diff', '--cached', '--stat'], { cwd: DATA_DIR, timeoutMs: 5000 });
81
+ if (!status.ok || !status.stdout.trim()) {
78
82
  log.info('No changes to commit');
79
83
  return;
80
84
  }
81
85
  const summary = results.map((r) => `${r.project}: ${r.ids.length} tasks`).join('; ');
82
86
  const msg = `auto-archive: completed tasks (${summary})`;
83
- execSync(`git commit -m "${msg}"`, { cwd: DATA_DIR, stdio: 'pipe' });
87
+ const committed = await runFile('git', ['commit', '-m', msg], { cwd: DATA_DIR, timeoutMs: 10000 });
88
+ if (!committed.ok) {
89
+ log.error('Git commit failed:', (committed.stderr || committed.stdout || '').trim());
90
+ return;
91
+ }
84
92
  log.info(`Committed: ${msg}`);
85
93
  }
86
94
  catch (e) {
@@ -88,7 +96,7 @@ function gitCommit(results) {
88
96
  }
89
97
  }
90
98
  async function runTaskArchiver() {
91
- return taskStore.runExclusive(() => {
99
+ return taskStore.runExclusive(async () => {
92
100
  log.info('Starting scan...');
93
101
  const results = {
94
102
  archived: [], skipped: [], errors: [],
@@ -104,7 +112,7 @@ async function runTaskArchiver() {
104
112
  }
105
113
  for (const name of projectNames) {
106
114
  try {
107
- const result = processProject(name);
115
+ const result = await processProject(name);
108
116
  if (result)
109
117
  results.archived.push(result);
110
118
  else
@@ -116,7 +124,7 @@ async function runTaskArchiver() {
116
124
  }
117
125
  }
118
126
  if (results.archived.length > 0)
119
- gitCommit(results.archived);
127
+ await gitCommit(results.archived);
120
128
  const archivedCount = results.archived.reduce((sum, r) => sum + r.ids.length, 0);
121
129
  log.info(`Done. Archived ${archivedCount} tasks from ${results.archived.length} project(s)`);
122
130
  return results;
@@ -5,7 +5,7 @@
5
5
  // dispatch claim whose owner died with the server would otherwise stay in-progress forever
6
6
  // — stranding the task AND any manager thread suspended on it. Claims that legitimately
7
7
  // survive a restart are respected: a waiting/rate_limited thread that owns the task
8
- // (DR-0014 suspension, rate-limit pause), a remote cortex-run tracked in pending-tasks.json,
8
+ // (DR-0014 suspension, rate-limit pause), a remote dispatch tracked in pending-tasks.json,
9
9
  // and manual (non-dispatcher) claims.
10
10
  import { scanAllTasks } from '../../core/task-parser.js';
11
11
  import { threadStore } from '../../store/thread-repo.js';
@@ -43,7 +43,7 @@ export async function recoverOrphanedClaims(deps = {}) {
43
43
  if (!task.id || task.claimed_by !== DISPATCHER_AGENT)
44
44
  continue;
45
45
  if (task.status === 'done' || task.status === 'pending')
46
- continue; // pending → cortex-run owns it
46
+ continue; // pending → outside work owns it
47
47
  if (task.blocked_by)
48
48
  continue; // blocked is already a terminal signal for the tree
49
49
  if (ownedByLiveThread(task))
@@ -30,6 +30,15 @@ declare function loadMachinesFromFile(failOnError?: boolean): void;
30
30
  * Return the current in-memory machine registry.
31
31
  */
32
32
  declare function getMachineRegistry(): MachineRegistry;
33
+ export type GpuCountUpdate = 'updated' | 'unchanged' | 'skipped';
34
+ /**
35
+ * Reconcile a GPU count a client reported about itself into the registry and machines.json.
36
+ *
37
+ * `null` means the client could not probe (no nvidia-smi, driver down) — that is "unknown", not
38
+ * "zero GPUs", so the configured value stands and the machine is never silently dropped from GPU
39
+ * dispatch. Only machines already in the registry are touched: a client cannot register itself.
40
+ */
41
+ declare function applyReportedGpuCount(machine: string, reported: number | null): GpuCountUpdate;
33
42
  /**
34
43
  * Return the first machine key in the registry as the local/default machine.
35
44
  * Falls back to 'local' if no machines are registered.
@@ -106,4 +115,4 @@ declare function processAbortOutcome(args: {
106
115
  message: string;
107
116
  }>;
108
117
  }): Promise<AbortOutcome>;
109
- export { getMachineRegistry, getLocalMachine, loadMachinesFromFile, startMachineRegistryWatcher, stopMachineRegistryWatcher, generateTaskId, buildDispatchSessionName, processSplitOutcome, processAbortOutcome, _testSetRegistry, };
118
+ export { getMachineRegistry, getLocalMachine, applyReportedGpuCount, loadMachinesFromFile, startMachineRegistryWatcher, stopMachineRegistryWatcher, generateTaskId, buildDispatchSessionName, processSplitOutcome, processAbortOutcome, _testSetRegistry, };
@@ -2,6 +2,7 @@ import * as crypto from 'crypto';
2
2
  import { readFileSync, existsSync } from 'fs';
3
3
  import * as path from 'path';
4
4
  import { CONFIG_DIR } from '../../core/utils.js';
5
+ import { atomicWriteSync } from '../../core/atomic-write.js';
5
6
  import { createLogger } from '../../core/log.js';
6
7
  import { createFileWatchMonitor } from '../../core/resilient-watch.js';
7
8
  import { Icons } from '../../core/icons.js';
@@ -78,6 +79,50 @@ function loadMachinesFromFile(failOnError = true) {
78
79
  function getMachineRegistry() {
79
80
  return _registry;
80
81
  }
82
+ // --- Client-reported GPU count ---
83
+ /** Above this a reported number is treated as garbage rather than a machine with that many GPUs. */
84
+ const MAX_PLAUSIBLE_GPUS = 64;
85
+ function isPlausibleGpuCount(value) {
86
+ return typeof value === 'number' && Number.isInteger(value)
87
+ && value >= 0 && value <= MAX_PLAUSIBLE_GPUS;
88
+ }
89
+ /** Read-modify-write machines.json so every other field of every entry survives. Returns false —
90
+ * leaving the file untouched — when it cannot be parsed or no longer holds the machine. */
91
+ function persistGpuCount(machine, gpuCount) {
92
+ try {
93
+ const parsed = JSON.parse(readFileSync(MACHINES_FILE, 'utf-8'));
94
+ if (!parsed[machine])
95
+ return false;
96
+ parsed[machine].gpuCount = gpuCount;
97
+ atomicWriteSync(MACHINES_FILE, `${JSON.stringify(parsed, null, 2)}\n`);
98
+ return true;
99
+ }
100
+ catch (e) {
101
+ log.error(`Failed to persist gpuCount for ${machine}: ${e.message}`);
102
+ return false;
103
+ }
104
+ }
105
+ /**
106
+ * Reconcile a GPU count a client reported about itself into the registry and machines.json.
107
+ *
108
+ * `null` means the client could not probe (no nvidia-smi, driver down) — that is "unknown", not
109
+ * "zero GPUs", so the configured value stands and the machine is never silently dropped from GPU
110
+ * dispatch. Only machines already in the registry are touched: a client cannot register itself.
111
+ */
112
+ function applyReportedGpuCount(machine, reported) {
113
+ const entry = _registry[machine];
114
+ if (!entry || !isPlausibleGpuCount(reported))
115
+ return 'skipped';
116
+ if (entry.gpuCount === reported)
117
+ return 'unchanged';
118
+ if (!persistGpuCount(machine, reported))
119
+ return 'skipped';
120
+ const previous = entry.gpuCount;
121
+ entry.gpuCount = reported;
122
+ log.info(`${machine}: gpuCount ${previous} → ${reported} (client-reported)`);
123
+ _adminNotifier?.(`${Icons.refresh} \`${machine}\` gpuCount ${previous} → ${reported} (reported by its client)`);
124
+ return 'updated';
125
+ }
81
126
  /**
82
127
  * Return the first machine key in the registry as the local/default machine.
83
128
  * Falls back to 'local' if no machines are registered.
@@ -199,4 +244,4 @@ async function processAbortOutcome(args, deps) {
199
244
  }
200
245
  return { handled: true, note: `worker aborted — task blocked (${rawReason.slice(0, 120)})` };
201
246
  }
202
- export { getMachineRegistry, getLocalMachine, loadMachinesFromFile, startMachineRegistryWatcher, stopMachineRegistryWatcher, generateTaskId, buildDispatchSessionName, processSplitOutcome, processAbortOutcome, _testSetRegistry, };
247
+ export { getMachineRegistry, getLocalMachine, applyReportedGpuCount, loadMachinesFromFile, startMachineRegistryWatcher, stopMachineRegistryWatcher, generateTaskId, buildDispatchSessionName, processSplitOutcome, processAbortOutcome, _testSetRegistry, };
@@ -244,13 +244,12 @@ function buildDispatchPrompt(task) {
244
244
  '',
245
245
  '**CRITICAL: Before marking any task complete, verify ALL done_when conditions are actually satisfied.**',
246
246
  '',
247
- `If launching experiments via cortex-run, ALWAYS pass task info so cortex-run can manage task status:`,
248
- ` cortex-run --name NAME --task-project ${task.project} --task-id ${task.id} -- COMMAND`,
249
- `cortex-run will auto-mark the task pending on start, then complete on success / block on failure.`,
250
- '',
251
- `If NOT using cortex-run, verify done_when conditions, then run:`,
247
+ `Verify done_when conditions, then run:`,
252
248
  ` cortex-task complete --project ${task.project} --task-id ${task.id} --note "your completion note"`,
253
249
  '',
250
+ `If something outside this turn has to finish first (a long run, a build), arm a waitpoint with`,
251
+ `wait_create, mark the task pending, and complete it when the signal wakes you.`,
252
+ '',
254
253
  '- Update the project STATUS.md if the work changed project state',
255
254
  ];
256
255
  sections.push(completion.join('\n'));
@@ -26,8 +26,8 @@ export declare class TaskMutator {
26
26
  constructor(store?: TaskRepo, bus?: EventBus);
27
27
  setBus(bus: EventBus): void;
28
28
  /** getById with a one-shot refresh on miss: tasks created out-of-process (CLI, manager
29
- * threads) reach the in-memory cache only on refresh — callers like the cortex-run
30
- * callback may fire before any dispatch cycle has reloaded TASKS.yaml. */
29
+ * threads) reach the in-memory cache only on refresh — a caller may fire before any
30
+ * dispatch cycle has reloaded TASKS.yaml. */
31
31
  private getByIdFresh;
32
32
  claim(taskId: string, agent: string, options?: ClaimTaskOptions): Promise<any>;
33
33
  unclaim(taskId: string, options?: OwnedMutationOptions): Promise<any>;