@cortex-agent/server 2026.9.14 → 2026.9.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (259) hide show
  1. package/README.md +3 -2
  2. package/defaults/config/hooks/08-agents-md-injector-post-tool.json +10 -0
  3. package/defaults/config/hooks/{10-cortex-md-injector-session-start.json → 10-agents-md-injector-session-start.json} +3 -3
  4. package/defaults/config/hooks/{CORTEX.md → AGENTS.md} +2 -2
  5. package/defaults/hooks/{CORTEX.md → AGENTS.md} +1 -1
  6. package/defaults/hooks/{cortex-md-injector.mjs → agents-md-injector.mjs} +117 -26
  7. package/defaults/hooks/cortex-hook-api.mjs +2 -2
  8. package/defaults/hooks/new-session-hook.mjs +2 -2
  9. package/defaults/hooks/rules-loader.mjs +2 -2
  10. package/defaults/hooks/status-md-guard.mjs +8 -8
  11. package/defaults/hooks/task-status-check.mjs +18 -76
  12. package/defaults/hooks/tasks-yaml-guard.mjs +2 -2
  13. package/defaults/plugins/cortex-commission/.claude-plugin/plugin.json +2 -2
  14. package/defaults/plugins/cortex-commission/plugin.json +2 -2
  15. package/defaults/plugins/cortex-commission/skills/commission/SKILL.md +3 -3
  16. package/defaults/plugins/cortex-feishu/skills/feishu-doc/SKILL.md +1 -1
  17. package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +2 -2
  18. package/defaults/plugins/cortex-system/skills/project-init/SKILL.md +4 -4
  19. package/defaults/plugins/cortex-system/skills/task/SKILL.md +1 -1
  20. package/defaults/rules/{cortex-md.md → agents-md.md} +4 -4
  21. package/defaults/rules/decision-records.md +1 -1
  22. package/defaults/rules/meta-conventions.md +4 -4
  23. package/defaults/rules/mission-md.md +1 -1
  24. package/dist/agent-adapter/claude/adapter.d.ts +0 -6
  25. package/dist/agent-adapter/claude/adapter.js +0 -8
  26. package/dist/agent-adapter/claude/defaults.d.ts +10 -7
  27. package/dist/agent-adapter/claude/defaults.js +18 -16
  28. package/dist/agent-adapter/claude/hooks-builder.js +2 -2
  29. package/dist/agent-adapter/claude/spawn-args.d.ts +0 -3
  30. package/dist/agent-adapter/claude/spawn-args.js +20 -16
  31. package/dist/agent-adapter/claude/turn-machine.d.ts +11 -0
  32. package/dist/agent-adapter/claude/turn-machine.js +46 -5
  33. package/dist/agent-adapter/normalize/prompt-builder.d.ts +16 -1
  34. package/dist/agent-adapter/normalize/prompt-builder.js +24 -6
  35. package/dist/agent-adapter/pi/mcp-bridge-logic.d.ts +11 -2
  36. package/dist/agent-adapter/pi/mcp-bridge-logic.js +32 -1
  37. package/dist/agent-adapter/pi/mcp-bridge.js +16 -15
  38. package/dist/agent-adapter/pi/session-options.d.ts +0 -6
  39. package/dist/agent-adapter/pi/session-options.js +1 -8
  40. package/dist/agent-adapter/types.d.ts +1 -1
  41. package/dist/core/mcp-tool-gate.d.ts +3 -17
  42. package/dist/core/mcp-tool-gate.js +4 -19
  43. package/dist/core/media-types.d.ts +10 -0
  44. package/dist/core/media-types.js +34 -0
  45. package/dist/core/platform-settings-spec.js +1 -1
  46. package/dist/core/settings-spec.d.ts +22 -1
  47. package/dist/core/settings-spec.js +33 -2
  48. package/dist/core/types/agent-types.d.ts +3 -1
  49. package/dist/core/utils.d.ts +1 -1
  50. package/dist/core/utils.js +1 -1
  51. package/dist/domain/agents/config.d.ts +1 -1
  52. package/dist/domain/agents/config.js +1 -1
  53. package/dist/domain/agents/profile-switch.d.ts +1 -1
  54. package/dist/domain/agents/profile-switch.js +3 -5
  55. package/dist/domain/agents/subagent/runner.js +0 -1
  56. package/dist/domain/commissions/commission-draft.d.ts +58 -0
  57. package/dist/domain/commissions/commission-draft.js +87 -4
  58. package/dist/domain/commissions/commission-finalize.d.ts +8 -3
  59. package/dist/domain/commissions/commission-finalize.js +14 -0
  60. package/dist/domain/executions/registry.d.ts +1 -2
  61. package/dist/domain/executions/registry.js +0 -3
  62. package/dist/domain/mcp/bundled-server.js +4 -3
  63. package/dist/domain/mcp/feishu/file.js +37 -18
  64. package/dist/domain/mcp/feishu/types.d.ts +3 -0
  65. package/dist/domain/mcp/feishu-server.js +1 -1
  66. package/dist/domain/mcp/tools/{cortex-md.d.ts → agents-md.d.ts} +6 -6
  67. package/dist/domain/mcp/tools/{cortex-md.js → agents-md.js} +6 -6
  68. package/dist/domain/mcp/tools/commission-tools.d.ts +12 -1
  69. package/dist/domain/mcp/tools/commission-tools.js +68 -14
  70. package/dist/domain/mcp/tools/remote-file.d.ts +20 -0
  71. package/dist/domain/mcp/tools/remote-file.js +44 -0
  72. package/dist/domain/mcp/tools/slack.d.ts +2 -0
  73. package/dist/domain/mcp/tools/slack.js +22 -7
  74. package/dist/domain/mcp/tools/task-ops.js +5 -13
  75. package/dist/domain/mcp/tools/ui-file.js +23 -10
  76. package/dist/domain/mcp/tools/waitpoint.d.ts +3 -0
  77. package/dist/domain/mcp/tools/waitpoint.js +122 -0
  78. package/dist/domain/memory/agents-md-injector.d.ts +24 -0
  79. package/dist/domain/memory/{cortex-md-injector.js → agents-md-injector.js} +10 -7
  80. package/dist/domain/projects/project-store.d.ts +1 -1
  81. package/dist/domain/projects/project-store.js +3 -3
  82. package/dist/domain/remote/client-hot-reload.js +3 -1
  83. package/dist/domain/remote/client-manager.js +105 -126
  84. package/dist/domain/remote/client-ssh-tunnel.d.ts +16 -5
  85. package/dist/domain/remote/client-ssh-tunnel.js +12 -5
  86. package/dist/domain/remote/cortex-client-config.d.ts +1 -1
  87. package/dist/domain/remote/cortex-client-config.js +1 -1
  88. package/dist/domain/remote/device-file.d.ts +51 -0
  89. package/dist/domain/remote/device-file.js +193 -0
  90. package/dist/domain/remote/device-port.js +3 -0
  91. package/dist/domain/remote/reverse-stream.d.ts +18 -7
  92. package/dist/domain/remote/reverse-stream.js +19 -6
  93. package/dist/domain/runs/builders.js +0 -1
  94. package/dist/domain/runs/compact.js +0 -1
  95. package/dist/domain/runs/engine-spec.d.ts +11 -4
  96. package/dist/domain/runs/engine-spec.js +7 -4
  97. package/dist/domain/runs/prompt.js +16 -10
  98. package/dist/domain/runs/request.d.ts +0 -1
  99. package/dist/domain/sessions/session-hooks.d.ts +5 -12
  100. package/dist/domain/sessions/session-hooks.js +6 -13
  101. package/dist/domain/sessions/session-lifecycle.d.ts +4 -4
  102. package/dist/domain/sessions/session-lifecycle.js +5 -6
  103. package/dist/domain/sessions/session-retention.d.ts +1 -3
  104. package/dist/domain/sessions/session-retention.js +9 -26
  105. package/dist/domain/sessions/session-use.d.ts +32 -0
  106. package/dist/domain/sessions/session-use.js +63 -0
  107. package/dist/domain/sessions/session.js +6 -5
  108. package/dist/domain/system/server-update-check.js +29 -1
  109. package/dist/domain/system/update-ui-state.d.ts +32 -0
  110. package/dist/domain/system/update-ui-state.js +63 -0
  111. package/dist/domain/tasks/claim-recovery.js +2 -2
  112. package/dist/domain/tasks/dispatch-utils.d.ts +10 -1
  113. package/dist/domain/tasks/dispatch-utils.js +46 -1
  114. package/dist/domain/tasks/dispatcher.js +4 -5
  115. package/dist/domain/tasks/mutator.d.ts +2 -2
  116. package/dist/domain/tasks/mutator.js +2 -2
  117. package/dist/domain/tasks/system/task-cli.js +2 -2
  118. package/dist/domain/tasks/system/task-state.js +1 -1
  119. package/dist/domain/threads/runner.js +3 -2
  120. package/dist/domain/ui-service/app-router.d.ts +54 -3
  121. package/dist/domain/ui-service/app-router.js +12 -14
  122. package/dist/domain/ui-service/input-schemas.d.ts +49 -5
  123. package/dist/domain/ui-service/input-schemas.js +35 -9
  124. package/dist/domain/ui-service/mutate/platform-settings.js +1 -1
  125. package/dist/domain/ui-service/mutate/sessions.d.ts +17 -1
  126. package/dist/domain/ui-service/mutate/sessions.js +83 -3
  127. package/dist/domain/ui-service/mutate/system.d.ts +3 -1
  128. package/dist/domain/ui-service/mutate/system.js +13 -0
  129. package/dist/domain/ui-service/mutate/waitpoints.d.ts +2 -0
  130. package/dist/domain/ui-service/mutate/waitpoints.js +20 -0
  131. package/dist/domain/ui-service/platform-settings.js +1 -1
  132. package/dist/domain/ui-service/plugins-shared.js +1 -1
  133. package/dist/domain/ui-service/query/config.js +1 -1
  134. package/dist/domain/ui-service/query/executions.js +0 -2
  135. package/dist/domain/ui-service/query/machine-detail.js +3 -8
  136. package/dist/domain/ui-service/query/memory.js +1 -1
  137. package/dist/domain/ui-service/query/sessions.js +7 -0
  138. package/dist/domain/ui-service/query/system.d.ts +2 -1
  139. package/dist/domain/ui-service/query/system.js +4 -0
  140. package/dist/domain/ui-service/query/threads.js +1 -54
  141. package/dist/domain/ui-service/query/waitpoints.d.ts +30 -0
  142. package/dist/domain/ui-service/query/waitpoints.js +117 -0
  143. package/dist/domain/ui-service/query-input-schemas.d.ts +3 -0
  144. package/dist/domain/ui-service/query-input-schemas.js +3 -0
  145. package/dist/domain/ui-service/trpc.js +1 -1
  146. package/dist/domain/ui-service/types.d.ts +175 -50
  147. package/dist/domain/ui-service/types.js +1 -1
  148. package/dist/domain/ui-service/ui-service.js +13 -33
  149. package/dist/domain/waitpoints/notices.d.ts +21 -0
  150. package/dist/domain/waitpoints/notices.js +115 -0
  151. package/dist/domain/waitpoints/service.d.ts +91 -0
  152. package/dist/domain/waitpoints/service.js +243 -0
  153. package/dist/entry/app.js +39 -29
  154. package/dist/entry/auth-login-cli.js +1 -1
  155. package/dist/entry/auth-login-terminal.js +1 -1
  156. package/dist/entry/init-auth.js +1 -1
  157. package/dist/entry/init.js +6 -6
  158. package/dist/entry/signal-cli.d.ts +30 -0
  159. package/dist/entry/signal-cli.js +207 -0
  160. package/dist/entry/start-ui-http.d.ts +1 -1
  161. package/dist/entry/start-ui-http.js +5 -3
  162. package/dist/events/event-types.d.ts +5 -7
  163. package/dist/hooks/{cortex-md-injector.mjs → agents-md-injector.mjs} +117 -26
  164. package/dist/hooks/cortex-hook-api.mjs +2 -2
  165. package/dist/hooks/new-session-hook.mjs +2 -2
  166. package/dist/hooks/rules-loader.mjs +2 -2
  167. package/dist/hooks/status-md-guard.mjs +8 -8
  168. package/dist/hooks/task-status-check.mjs +18 -76
  169. package/dist/hooks/tasks-yaml-guard.mjs +2 -2
  170. package/dist/orchestration/agent-file-send.d.ts +9 -0
  171. package/dist/orchestration/agent-file-send.js +21 -2
  172. package/dist/orchestration/agent-runner.d.ts +4 -3
  173. package/dist/orchestration/agent-runner.js +25 -23
  174. package/dist/orchestration/attachments-store.d.ts +31 -0
  175. package/dist/orchestration/attachments-store.js +184 -0
  176. package/dist/orchestration/conversation-request.d.ts +30 -8
  177. package/dist/orchestration/conversation-request.js +62 -26
  178. package/dist/orchestration/edit-retry.js +2 -1
  179. package/dist/orchestration/interactions/ask-user-resume.js +2 -1
  180. package/dist/orchestration/interactions/plan-approvals.js +1 -1
  181. package/dist/orchestration/interactions/ui-update-prompt.d.ts +8 -0
  182. package/dist/orchestration/interactions/ui-update-prompt.js +47 -0
  183. package/dist/orchestration/outputs-store.d.ts +11 -0
  184. package/dist/orchestration/outputs-store.js +32 -6
  185. package/dist/orchestration/resume-dispatcher.js +2 -2
  186. package/dist/orchestration/routing/file-handler.d.ts +23 -2
  187. package/dist/orchestration/routing/file-handler.js +22 -5
  188. package/dist/orchestration/routing/webhook.js +240 -39
  189. package/dist/orchestration/session-compact.d.ts +3 -0
  190. package/dist/orchestration/session-compact.js +3 -2
  191. package/dist/orchestration/session-events.d.ts +6 -0
  192. package/dist/orchestration/session-events.js +5 -0
  193. package/dist/orchestration/session-gateway.d.ts +1 -1
  194. package/dist/orchestration/session-gateway.js +1 -0
  195. package/dist/orchestration/thread-executor.d.ts +2 -0
  196. package/dist/orchestration/thread-executor.js +11 -1
  197. package/dist/orchestration/thread-input.d.ts +3 -2
  198. package/dist/orchestration/thread-input.js +8 -9
  199. package/dist/orchestration/turn/turn-prep.d.ts +15 -1
  200. package/dist/orchestration/turn/turn-prep.js +21 -9
  201. package/dist/orchestration/waitpoint-ingress.d.ts +41 -0
  202. package/dist/orchestration/waitpoint-ingress.js +172 -0
  203. package/dist/orchestration/waitpoint-notifier.d.ts +21 -0
  204. package/dist/orchestration/waitpoint-notifier.js +119 -0
  205. package/dist/orchestration/waitpoint-remote-drain.d.ts +20 -0
  206. package/dist/orchestration/waitpoint-remote-drain.js +147 -0
  207. package/dist/orchestration/waitpoint-sweep.d.ts +42 -0
  208. package/dist/orchestration/waitpoint-sweep.js +87 -0
  209. package/dist/platform/adapters/feishu-image.d.ts +19 -0
  210. package/dist/platform/adapters/feishu-image.js +71 -0
  211. package/dist/platform/adapters/feishu.d.ts +2 -0
  212. package/dist/platform/adapters/feishu.js +26 -16
  213. package/dist/platform/ui-http/app-update.d.ts +11 -0
  214. package/dist/platform/ui-http/app-update.js +3 -0
  215. package/dist/platform/ui-http/listening-ports.d.ts +1 -1
  216. package/dist/platform/ui-http/listening-ports.js +1 -1
  217. package/dist/platform/ui-http/ui-session.js +1 -1
  218. package/dist/store/conversation-ledger-repo.d.ts +10 -19
  219. package/dist/store/conversation-ledger-repo.js +143 -152
  220. package/dist/store/execution-repo.d.ts +1 -19
  221. package/dist/store/execution-repo.js +1 -18
  222. package/dist/store/project-notes-repo.js +11 -2
  223. package/dist/store/prompt-migration-replacements.js +1 -1
  224. package/dist/store/session-registry-import.d.ts +34 -0
  225. package/dist/store/session-registry-import.js +182 -0
  226. package/dist/store/session-registry-journal.d.ts +107 -0
  227. package/dist/store/session-registry-journal.js +308 -19
  228. package/dist/store/session-registry-repo.d.ts +113 -28
  229. package/dist/store/session-registry-repo.js +288 -105
  230. package/dist/store/version-migrations.d.ts +29 -3
  231. package/dist/store/version-migrations.js +288 -24
  232. package/dist/store/waitpoint-repo.d.ts +108 -0
  233. package/dist/store/waitpoint-repo.js +94 -0
  234. package/package.json +2 -2
  235. package/web/dist/assets/index-CwwQNMpP.css +1 -0
  236. package/web/dist/assets/index-DLSfgq3o.js +444 -0
  237. package/web/dist/assets/{index-aHbOZSP6.js → index-DZTuqUO4.js} +1 -1
  238. package/web/dist/index.html +2 -2
  239. package/defaults/config/hooks/08-cortex-md-injector-post-tool.json +0 -10
  240. package/dist/domain/executions/log-tailer.d.ts +0 -71
  241. package/dist/domain/executions/log-tailer.js +0 -194
  242. package/dist/domain/memory/cortex-md-injector.d.ts +0 -24
  243. package/dist/domain/memory/cortex-md-scanner.d.ts +0 -10
  244. package/dist/domain/memory/cortex-md-scanner.js +0 -66
  245. package/dist/domain/remote/cortex-client.d.ts +0 -1
  246. package/dist/domain/remote/cortex-client.js +0 -662
  247. package/dist/domain/tasks/system/cortex-run.d.ts +0 -25
  248. package/dist/domain/tasks/system/cortex-run.js +0 -360
  249. package/dist/store/session-repo.d.ts +0 -65
  250. package/dist/store/session-repo.js +0 -184
  251. package/web/dist/assets/index-BuXbCsuz.js +0 -444
  252. package/web/dist/assets/index-CCPxQ94C.css +0 -1
  253. /package/defaults/{CORTEX.md → AGENTS.md} +0 -0
  254. /package/defaults/config/{CORTEX.md → AGENTS.md} +0 -0
  255. /package/defaults/context/{CORTEX.md → AGENTS.md} +0 -0
  256. /package/defaults/context/ideas/{CORTEX.md → AGENTS.md} +0 -0
  257. /package/defaults/context/projects/{CORTEX.md → AGENTS.md} +0 -0
  258. /package/defaults/context/scans/{CORTEX.md → AGENTS.md} +0 -0
  259. /package/defaults/context/user/{CORTEX.md → AGENTS.md} +0 -0
@@ -46,7 +46,7 @@ export interface RegisterNamedSessionOpts {
46
46
  export declare function registerNamedSession(store: SessionRegistryWriter, opts: RegisterNamedSessionOpts): Promise<string>;
47
47
  export interface CreateDirectSessionDeps {
48
48
  sessionStore: SessionRegistryWriter;
49
- /** Point the channel's sessions.json entry at the new session (so a later send resumes it). */
49
+ /** Bind the channel to the new session in the registry (so a later send resumes it). */
50
50
  setChannelSession(channel: string, sessionId: string, backend: string): Promise<void>;
51
51
  /** Initialize the conversation ledger for the new channel/session. */
52
52
  initConversation(channel: string, opts: {
@@ -90,8 +90,8 @@ export interface AttachExistingSessionOpts {
90
90
  backend: string;
91
91
  profileName?: string | null;
92
92
  }
93
- /** Attach a channel to an existing session: restore its profile (if any), point sessions.json at it,
94
- * and switch the conversation ledger. Mirrors the !resume switch sequence. */
93
+ /** Attach a channel to an existing session: restore its profile (if any), bind the channel to it in
94
+ * the registry, and switch the conversation ledger. Mirrors the !resume switch sequence. */
95
95
  export declare function attachExistingSession(channel: string, opts: AttachExistingSessionOpts): Promise<void>;
96
96
  export interface AdoptScheduledSessionStore {
97
97
  getById(sessionId: string): Promise<{
@@ -115,6 +115,6 @@ export interface AdoptScheduledSessionStore {
115
115
  export declare function adoptScheduledSession(store: AdoptScheduledSessionStore, sessionId: string): Promise<{
116
116
  channel: string;
117
117
  } | null>;
118
- /** Clear a channel's session state: drop sessions.json keys for every backend, clean session
118
+ /** Clear a channel's session state: unbind the channel in the registry, clean session
119
119
  * backups, and clear the conversation ledger. Mirrors the store-level half of !new. */
120
120
  export declare function resetChannelSession(channel: string): Promise<void>;
@@ -71,7 +71,7 @@ export async function createDirectSession(deps, opts) {
71
71
  mode: opts.selection.mode ?? null,
72
72
  });
73
73
  }
74
- // Commission mode is off by default while the feature is under test (settings.commissionEnabled).
74
+ // settings.commissionEnabled is the feature's kill switch (on by default since DR-0037 v4).
75
75
  // Refuse here rather than downgrade: a caller that asked for a commission and silently got an
76
76
  // ordinary session would only discover it much later. This is the server-side backstop for every
77
77
  // create path; the UI hides the opt-in and the ui-service handlers reject earlier with a 400.
@@ -94,8 +94,8 @@ export async function createDirectSession(deps, opts) {
94
94
  await deps.initConversation(channel, { sessionId, sessionName, backend });
95
95
  return { sessionId, sessionName, channel };
96
96
  }
97
- /** Attach a channel to an existing session: restore its profile (if any), point sessions.json at it,
98
- * and switch the conversation ledger. Mirrors the !resume switch sequence. */
97
+ /** Attach a channel to an existing session: restore its profile (if any), bind the channel to it in
98
+ * the registry, and switch the conversation ledger. Mirrors the !resume switch sequence. */
99
99
  export async function attachExistingSession(channel, opts) {
100
100
  if (opts.profileName)
101
101
  setActiveProfile(opts.profileName, channel);
@@ -123,7 +123,7 @@ export async function adoptScheduledSession(store, sessionId) {
123
123
  await store.convertToDirect(sessionId, { channel });
124
124
  return { channel };
125
125
  }
126
- /** Clear a channel's session state: drop sessions.json keys for every backend, clean session
126
+ /** Clear a channel's session state: unbind the channel in the registry, clean session
127
127
  * backups, and clear the conversation ledger. Mirrors the store-level half of !new. */
128
128
  export async function resetChannelSession(channel) {
129
129
  const conv = await conversationLedger.getConversation(channel);
@@ -131,7 +131,6 @@ export async function resetChannelSession(channel) {
131
131
  sessionBackup.cleanupAllBackups(conv.sessionId);
132
132
  await conversationLedger.clearConversation(channel);
133
133
  }
134
- // One channel, one binding: `deleteSessionAsync` clears the key and every legacy
135
- // backend-prefixed form of it, so the per-backend fan-out is gone.
134
+ // One channel, one binding: `deleteSessionAsync` unbinds the channel in the registry.
136
135
  await deleteSessionAsync(channel).catch(() => { });
137
136
  }
@@ -1,5 +1,4 @@
1
1
  import { type SessionRegistryRepo } from '../../store/session-registry-repo.js';
2
- import type { SessionRepo } from '../../store/session-repo.js';
3
2
  import type { ConversationLedgerRepo } from '../../store/conversation-ledger-repo.js';
4
3
  import type { ConversationHistoryRepo } from '../../store/conversation-history-repo.js';
5
4
  import type { RetentionCandidateRepo } from '../../store/retention-candidate-repo.js';
@@ -21,8 +20,7 @@ export interface SessionRetentionDeps {
21
20
  retentionDays: number;
22
21
  now?: () => number;
23
22
  registry: SessionRegistryRepo;
24
- sessionRepo: Pick<SessionRepo, 'deleteManyBySessionIds' | 'deleteExceptSessionIds'>;
25
- ledgerRepo: Pick<ConversationLedgerRepo, 'listBySessionIds' | 'clearBySessionIds' | 'deleteExceptSessionIds'>;
23
+ ledgerRepo: Pick<ConversationLedgerRepo, 'clearBySessionIds'>;
26
24
  historyRepo: Pick<ConversationHistoryRepo, 'clearBySessionIds'>;
27
25
  /** Per-session cumulative stats carried over from archived executions. Optional so existing
28
26
  * callers and fixtures keep working; absent ⇒ the carry is simply not pruned. */
@@ -4,6 +4,7 @@ import { createLogger } from '../../core/log.js';
4
4
  import { parsePISessionFilename } from '../../core/pi-session-filename.js';
5
5
  import { effectiveBackendSessionId } from '../../store/session-registry-repo.js';
6
6
  import { sessionTotalsCarry } from '../../store/session-totals-repo.js';
7
+ import { activeSessionUseIds } from '../sessions/session-use.js';
7
8
  const DAY_MS = 24 * 60 * 60 * 1000;
8
9
  const CAPTURE_PREFIX = 'claude-output-';
9
10
  const log = createLogger('session-retention');
@@ -13,16 +14,16 @@ export async function runSessionRetentionSweep(deps) {
13
14
  const cutoffMs = now() - deps.retentionDays * DAY_MS;
14
15
  const helper = await safeClaudeSync(deps, errors);
15
16
  const committed = await retryPendingDeletes(deps, errors);
16
- const protectedTracks = new Set(deps.liveness.protectedTrackSessionIds);
17
+ // This is the ONE place that must protect in-use sessions: the store's `beginDeleteExpired` no
18
+ // longer keeps a use counter, so the runtime lease set (`@domain/sessions/session-use.ts`) is
19
+ // unioned into the protected ids here before any delete-intent is written.
20
+ const protectedTracks = new Set([...deps.liveness.protectedTrackSessionIds, ...activeSessionUseIds()]);
17
21
  const pending = await safeRegistryBeginDeleteExpired(deps, cutoffMs, protectedTracks, errors);
18
22
  const newlyCommitted = await commitDeletes(deps, pending, errors);
19
23
  const registryCommitted = committed + newlyCommitted;
20
24
  const live = await safeRegistryListRecentSessions(deps, errors);
21
25
  const stillPending = await safeRegistryListPendingDeletions(deps, errors);
22
26
  const registryReadable = live.ok && stillPending.ok;
23
- if (registryReadable) {
24
- await repairDanglingReferences(deps, live.value, stillPending.value, errors);
25
- }
26
27
  const protectedBackendIds = new Set(deps.liveness.protectedBackendSessionIds);
27
28
  const historyOrphanDeleted = registryReadable
28
29
  ? await deleteHistoryOrphans(deps, live.value, stillPending.value, cutoffMs, errors)
@@ -56,7 +57,7 @@ async function safeClaudeSync(deps, errors) {
56
57
  }
57
58
  async function safeRegistryBeginDeleteExpired(deps, cutoffMs, protectedTracks, errors) {
58
59
  try {
59
- return await deps.registry.beginDeleteExpired(cutoffMs, protectedTracks, session => prepareDeleteCleanup(deps, session));
60
+ return await deps.registry.beginDeleteExpired(cutoffMs, protectedTracks, (session, turns) => prepareDeleteCleanup(deps, session, turns));
60
61
  }
61
62
  catch (error) {
62
63
  errors.push(`registry.beginDeleteExpired: ${error.message}`);
@@ -95,14 +96,13 @@ async function commitDeletes(deps, entries, errors) {
95
96
  }
96
97
  return committed;
97
98
  }
98
- async function prepareDeleteCleanup(deps, session) {
99
+ async function prepareDeleteCleanup(deps, session, turns) {
99
100
  if (session.backend !== 'claude')
100
101
  return { claudeBackupPaths: [] };
101
102
  const backendId = effectiveBackendSessionId(session);
102
103
  if (!backendId)
103
104
  return { claudeBackupPaths: [] };
104
- const ledgerRows = await deps.ledgerRepo.listBySessionIds([session.sessionId]);
105
- const candidates = ledgerRows.flatMap(row => row.turns.map(turn => turn.backupPath));
105
+ const candidates = turns.map(turn => turn.backupPath);
106
106
  return {
107
107
  claudeBackupPaths: await trustedClaudeBackupPaths(deps.paths.claudeProjectDir, backendId, candidates),
108
108
  };
@@ -110,7 +110,7 @@ async function prepareDeleteCleanup(deps, session) {
110
110
  async function cleanupPendingDelete(deps, entry) {
111
111
  const session = entry.session;
112
112
  const backendId = effectiveBackendSessionId(session);
113
- await deps.sessionRepo.deleteManyBySessionIds([session.sessionId]);
113
+ await deps.registry.unbindBySessionIds([session.sessionId]);
114
114
  await deps.ledgerRepo.clearBySessionIds([session.sessionId]);
115
115
  await deps.historyRepo.clearBySessionIds([session.sessionId]);
116
116
  // Otherwise the carry would outlive every session it describes and grow without bound.
@@ -155,23 +155,6 @@ async function realpathOrNull(filePath) {
155
155
  throw error;
156
156
  }
157
157
  }
158
- async function repairDanglingReferences(deps, live, pending, errors) {
159
- const liveIds = new Set(live.map((session) => session.sessionId));
160
- for (const entry of pending)
161
- liveIds.add(entry.session.sessionId);
162
- try {
163
- await deps.sessionRepo.deleteExceptSessionIds(liveIds);
164
- }
165
- catch (error) {
166
- errors.push(`bindings-repair: ${error.message}`);
167
- }
168
- try {
169
- await deps.ledgerRepo.deleteExceptSessionIds(liveIds);
170
- }
171
- catch (error) {
172
- errors.push(`ledger-repair: ${error.message}`);
173
- }
174
- }
175
158
  async function deleteHistoryOrphans(deps, live, pending, cutoffMs, errors) {
176
159
  const protectedIds = new Set([
177
160
  ...live.map(session => session.sessionId),
@@ -0,0 +1,32 @@
1
+ /** The one storage call this tracker needs: patch `lastUsedAt=now` iff the session is live and not
2
+ * pending deletion, returning whether the touch landed. Narrowed so tests can inject a fake. */
3
+ export interface UseCountStore {
4
+ touchSessionUse(sessionId: string): Promise<boolean>;
5
+ }
6
+ /**
7
+ * In-memory use counter for live sessions. `acquireSessionUse` asks the store to touch the session
8
+ * (which fails for unknown / pending-deletion ids); on success it bumps a per-session count and
9
+ * returns an idempotent `release()` that decrements it. While a session's count is > 0 it appears in
10
+ * {@link activeSessionUseIds}, which the retention sweep unions into its protected set so a session
11
+ * cannot be deleted out from under a turn that is still opening.
12
+ */
13
+ export declare class SessionUseTracker {
14
+ private readonly store;
15
+ private readonly activeUses;
16
+ constructor(store: UseCountStore);
17
+ /** Take a use lease, or null when the record is gone / pending deletion. Nested acquires stack;
18
+ * each returns its own idempotent release. */
19
+ acquireSessionUse(sessionId: string): Promise<(() => void) | null>;
20
+ /** Run `fn` while holding a use lease; returns null (without running `fn`) when the lease is
21
+ * refused. The lease is always released, even if `fn` throws. */
22
+ withSessionUse<T>(sessionId: string, fn: () => Promise<T>): Promise<T | null>;
23
+ /** The sessionIds with at least one live use lease — a snapshot the caller may keep. */
24
+ activeSessionUseIds(): ReadonlySet<string>;
25
+ /** Drop all counts. Tests only — production leases are balanced by their releases. */
26
+ _resetForTests(): void;
27
+ }
28
+ /** Process-wide tracker bound to the real registry singleton. */
29
+ export declare const sessionUse: SessionUseTracker;
30
+ export declare const acquireSessionUse: (sessionId: string) => Promise<(() => void) | null>;
31
+ export declare const withSessionUse: <T>(sessionId: string, fn: () => Promise<T>) => Promise<T | null>;
32
+ export declare const activeSessionUseIds: () => ReadonlySet<string>;
@@ -0,0 +1,63 @@
1
+ // input: the store's `touchSessionUse` storage primitive (patch lastUsedAt iff live && !pending)
2
+ // output: the runtime use-count lease that keeps retention off a session while a turn holds it
3
+ // pos: domain/sessions — the use-count bookkeeping that used to live inside
4
+ // `store/session-registry-repo.ts`. The store now owns only storage; this owns policy.
5
+ import { sessionStore } from '../../store/session-registry-repo.js';
6
+ /**
7
+ * In-memory use counter for live sessions. `acquireSessionUse` asks the store to touch the session
8
+ * (which fails for unknown / pending-deletion ids); on success it bumps a per-session count and
9
+ * returns an idempotent `release()` that decrements it. While a session's count is > 0 it appears in
10
+ * {@link activeSessionUseIds}, which the retention sweep unions into its protected set so a session
11
+ * cannot be deleted out from under a turn that is still opening.
12
+ */
13
+ export class SessionUseTracker {
14
+ store;
15
+ activeUses = new Map();
16
+ constructor(store) {
17
+ this.store = store;
18
+ }
19
+ /** Take a use lease, or null when the record is gone / pending deletion. Nested acquires stack;
20
+ * each returns its own idempotent release. */
21
+ async acquireSessionUse(sessionId) {
22
+ if (!(await this.store.touchSessionUse(sessionId)))
23
+ return null;
24
+ this.activeUses.set(sessionId, (this.activeUses.get(sessionId) ?? 0) + 1);
25
+ let released = false;
26
+ return () => {
27
+ if (released)
28
+ return;
29
+ released = true;
30
+ const next = (this.activeUses.get(sessionId) ?? 1) - 1;
31
+ if (next <= 0)
32
+ this.activeUses.delete(sessionId);
33
+ else
34
+ this.activeUses.set(sessionId, next);
35
+ };
36
+ }
37
+ /** Run `fn` while holding a use lease; returns null (without running `fn`) when the lease is
38
+ * refused. The lease is always released, even if `fn` throws. */
39
+ async withSessionUse(sessionId, fn) {
40
+ const release = await this.acquireSessionUse(sessionId);
41
+ if (!release)
42
+ return null;
43
+ try {
44
+ return await fn();
45
+ }
46
+ finally {
47
+ release();
48
+ }
49
+ }
50
+ /** The sessionIds with at least one live use lease — a snapshot the caller may keep. */
51
+ activeSessionUseIds() {
52
+ return new Set(this.activeUses.keys());
53
+ }
54
+ /** Drop all counts. Tests only — production leases are balanced by their releases. */
55
+ _resetForTests() {
56
+ this.activeUses.clear();
57
+ }
58
+ }
59
+ /** Process-wide tracker bound to the real registry singleton. */
60
+ export const sessionUse = new SessionUseTracker(sessionStore);
61
+ export const acquireSessionUse = (sessionId) => sessionUse.acquireSessionUse(sessionId);
62
+ export const withSessionUse = (sessionId, fn) => sessionUse.withSessionUse(sessionId, fn);
63
+ export const activeSessionUseIds = () => sessionUse.activeSessionUseIds();
@@ -1,12 +1,13 @@
1
- import { sessionRepo } from '../../store/session-repo.js';
1
+ import { sessionStore } from '../../store/session-registry-repo.js';
2
2
  // A channel has ONE session; the backend it runs is on the session record. `backend` is
3
- // accepted and ignored here so call sites migrate one at a time.
3
+ // accepted and ignored here so call sites migrate one at a time. These are thin wrappers over the
4
+ // session registry's channel bindings — the registry is the single owner of channel→session identity.
4
5
  export async function getSessionAsync(channel, backend) {
5
- return sessionRepo.getSessionAsync(channel, backend);
6
+ return (await sessionStore.getBoundSessionId(channel)) ?? undefined;
6
7
  }
7
8
  export async function setSessionAsync(channel, sessionId, backend) {
8
- return sessionRepo.setSessionAsync(channel, sessionId, backend);
9
+ await sessionStore.bindChannel(channel, sessionId);
9
10
  }
10
11
  export async function deleteSessionAsync(channel, backend) {
11
- return sessionRepo.deleteSessionAsync(channel, backend);
12
+ await sessionStore.unbindChannel(channel);
12
13
  }
@@ -3,6 +3,7 @@ import { execSync, spawn } from 'node:child_process';
3
3
  import { getSettings } from '../../core/settings.js';
4
4
  import { CORTEX_VERSION } from '../../core/version.js';
5
5
  import { loadUpdateState, saveUpdateState } from './update-state.js';
6
+ import { reportServerUpdateFailed, reportServerUpdateInstalled } from './update-ui-state.js';
6
7
  // ── CalVer comparison ────────────────────────────────────────────
7
8
  // Lives in @core/calver.js (platform/ui-http/app-update.ts needs it too and the platform layer may
8
9
  // not depend on domain). Re-exported here so existing importers keep working.
@@ -36,12 +37,39 @@ function defaultGetLatest() {
36
37
  return null;
37
38
  }
38
39
  }
40
+ /** Keep the reported stderr small enough to sit in a dialog and in the status snapshot. */
41
+ const INSTALL_STDERR_CAP = 2000;
42
+ function describeInstallFailure(code, signal, stderr) {
43
+ const how = signal !== null ? `killed by ${signal}` : `exited with code ${code}`;
44
+ const tail = stderr.trim().split('\n').slice(-6).join('\n').trim();
45
+ return tail ? `npm install -g ${how}\n${tail}` : `npm install -g ${how}`;
46
+ }
39
47
  function defaultSpawnInstall() {
40
48
  const child = spawn('npm', ['install', '-g', '@cortex-agent/server@latest'], {
49
+ // Detached + unref'd as before: the package's postinstall touches $STORE_DIR/.restart and the
50
+ // daemon respawns app.js, so the install has to outlive this process. Only stderr changes —
51
+ // piping it is what lets the SPA dialog report a real failure instead of pretending success.
41
52
  detached: true,
42
- stdio: 'ignore',
53
+ stdio: ['ignore', 'ignore', 'pipe'],
43
54
  cwd: '/tmp',
44
55
  });
56
+ let stderr = '';
57
+ child.stderr?.on('data', (chunk) => {
58
+ if (stderr.length < INSTALL_STDERR_CAP)
59
+ stderr += String(chunk);
60
+ });
61
+ // The pipe is a separate libuv handle from the child; unref it too so a still-running install
62
+ // cannot hold this event loop open. Typed as Readable, but a spawned pipe is a net.Socket.
63
+ child.stderr?.unref?.();
64
+ child.on('error', (err) => {
65
+ reportServerUpdateFailed(`npm install -g could not start: ${err.message}`);
66
+ });
67
+ child.on('exit', (code, signal) => {
68
+ if (code === 0)
69
+ reportServerUpdateInstalled();
70
+ else
71
+ reportServerUpdateFailed(describeInstallFailure(code, signal, stderr));
72
+ });
45
73
  child.unref();
46
74
  }
47
75
  function defaultNow() {
@@ -0,0 +1,32 @@
1
+ import type { UpdateChoice } from './update-prompt.js';
2
+ export type ServerUpdateState = 'idle' | 'prompting' | 'installing' | 'restarting' | 'failed';
3
+ export interface ServerUpdateStatus {
4
+ /** Version the server could move to, or null when there is nothing pending. */
5
+ available: string | null;
6
+ state: ServerUpdateState;
7
+ /** Set only in the `failed` state — the npm exit code / stderr tail. */
8
+ error?: string;
9
+ }
10
+ export declare function getServerUpdateStatus(): ServerUpdateStatus;
11
+ /**
12
+ * Publish a prompt for `version` and register the sink that resolves the waiting `ask()`.
13
+ * The sink is owned by the prompt, not by this module: it is what enforces first-answer-wins
14
+ * between the SPA dialog and the chat-message fallback.
15
+ */
16
+ export declare function openServerUpdatePrompt(version: string, settle: (choice: UpdateChoice | null) => void): void;
17
+ /** Answer from the SPA. Returns false when nothing was pending — a stale button. */
18
+ export declare function answerServerUpdatePrompt(choice: UpdateChoice): boolean;
19
+ /**
20
+ * Called by the prompt once EITHER side has answered. `apply` hands over to the install
21
+ * reporters below; anything else (skip / cancel / dismissed) drops back to idle.
22
+ */
23
+ export declare function settleServerUpdatePrompt(choice: UpdateChoice | null): void;
24
+ /**
25
+ * The npm install exited 0. That means "install finished", NOT "the server is already new":
26
+ * the package's postinstall touches $STORE_DIR/.restart and the daemon respawns app.js when it
27
+ * is idle, so `restarting` is the honest label for the window the SPA has to wait through.
28
+ */
29
+ export declare function reportServerUpdateInstalled(): void;
30
+ export declare function reportServerUpdateFailed(error: string): void;
31
+ /** Test-only: drop the prompt and the status back to their process-start values. */
32
+ export declare function _resetServerUpdateStatus(): void;
@@ -0,0 +1,63 @@
1
+ // input: UpdateChoice from the UpdatePrompt contract
2
+ // output: the single in-memory server-update status the SPA dialog renders, plus the sink that
3
+ // lets a tRPC mutation answer a pending prompt
4
+ // pos: Shared between orchestration/interactions/ui-update-prompt.ts (writes `prompting`),
5
+ // domain/system/server-update-check.ts (writes the install outcome) and
6
+ // domain/ui-service/{query,mutate}/system.ts (reads / answers). Process-local by design:
7
+ // the npm install restarts app.js, so anything durable here would be stale on the way back.
8
+ const IDLE = { available: null, state: 'idle' };
9
+ let status = IDLE;
10
+ let settleSink = null;
11
+ export function getServerUpdateStatus() {
12
+ return status;
13
+ }
14
+ /**
15
+ * Publish a prompt for `version` and register the sink that resolves the waiting `ask()`.
16
+ * The sink is owned by the prompt, not by this module: it is what enforces first-answer-wins
17
+ * between the SPA dialog and the chat-message fallback.
18
+ */
19
+ export function openServerUpdatePrompt(version, settle) {
20
+ // A later check (the 24h timer) while a dialog is still up supersedes the earlier one. Resolve
21
+ // the old ask() with null first, or its checkServerUpdate call would wait forever on a promise
22
+ // no button can reach any more.
23
+ const superseded = settleSink;
24
+ settleSink = null;
25
+ superseded?.(null);
26
+ settleSink = settle;
27
+ status = { available: version, state: 'prompting' };
28
+ }
29
+ /** Answer from the SPA. Returns false when nothing was pending — a stale button. */
30
+ export function answerServerUpdatePrompt(choice) {
31
+ const settle = settleSink;
32
+ if (!settle)
33
+ return false;
34
+ settleSink = null;
35
+ settle(choice);
36
+ return true;
37
+ }
38
+ /**
39
+ * Called by the prompt once EITHER side has answered. `apply` hands over to the install
40
+ * reporters below; anything else (skip / cancel / dismissed) drops back to idle.
41
+ */
42
+ export function settleServerUpdatePrompt(choice) {
43
+ settleSink = null;
44
+ status = choice === 'apply'
45
+ ? { available: status.available, state: 'installing' }
46
+ : IDLE;
47
+ }
48
+ /**
49
+ * The npm install exited 0. That means "install finished", NOT "the server is already new":
50
+ * the package's postinstall touches $STORE_DIR/.restart and the daemon respawns app.js when it
51
+ * is idle, so `restarting` is the honest label for the window the SPA has to wait through.
52
+ */
53
+ export function reportServerUpdateInstalled() {
54
+ status = { available: status.available, state: 'restarting' };
55
+ }
56
+ export function reportServerUpdateFailed(error) {
57
+ status = { available: status.available, state: 'failed', error };
58
+ }
59
+ /** Test-only: drop the prompt and the status back to their process-start values. */
60
+ export function _resetServerUpdateStatus() {
61
+ status = IDLE;
62
+ settleSink = null;
63
+ }
@@ -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>;
@@ -39,8 +39,8 @@ export class TaskMutator {
39
39
  this.bus = bus;
40
40
  }
41
41
  /** getById with a one-shot refresh on miss: tasks created out-of-process (CLI, manager
42
- * threads) reach the in-memory cache only on refresh — callers like the cortex-run
43
- * callback may fire before any dispatch cycle has reloaded TASKS.yaml. */
42
+ * threads) reach the in-memory cache only on refresh — a caller may fire before any
43
+ * dispatch cycle has reloaded TASKS.yaml. */
44
44
  getByIdFresh(taskId) {
45
45
  let task = this.store.getById(taskId);
46
46
  if (!task) {
@@ -108,8 +108,8 @@ const HELP_CONFIG = {
108
108
  { name: 'unclaim', description: 'Remove in-progress status' },
109
109
  { name: 'pause', description: 'Pause' },
110
110
  { name: 'resume', description: 'Resume a paused task' },
111
- { name: 'pending', description: 'Mark pending (waiting for cortex-run)' },
112
- { name: 'reopen', description: 'Restore a stuck pending task back to open (e.g. after a lost cortex-run callback)' },
111
+ { name: 'pending', description: 'Mark pending (waiting on work outside this turn)' },
112
+ { name: 'reopen', description: 'Restore a stuck pending task back to open (e.g. the awaited work never reported)' },
113
113
  { name: 'complete', description: 'Mark complete (--note)' },
114
114
  { name: 'uncomplete', description: 'Reverse a completed task' },
115
115
  ],
@@ -173,7 +173,7 @@ function blockTaskUnlocked(taskText, project, reason, taskId = null, ownership)
173
173
  task.dispatch_generation = ownership?.generation ?? null;
174
174
  task.pending_at = null;
175
175
  task.blocked_by = reason;
176
- // Normalize a 'pending' (mid cortex-run) task back to 'open'. `status === 'pending'`
176
+ // Normalize a 'pending' (waiting on outside work) task back to 'open'. `status === 'pending'`
177
177
  // is an independent dispatch-exclusion gate (task-parser isActionable), so leaving it
178
178
  // here would make the task invisible to the dispatcher even after it is unblocked.
179
179
  // blocked_by still gates dispatch, so this is safe. Never resurrect a done task.
@@ -285,7 +285,9 @@ export function buildThreadRunRequest(threadId, stepCtx, ctx, opts) {
285
285
  text: stepCtx.prompt,
286
286
  // First-step files only (never re-attached on an interrupted-session resume).
287
287
  attachments: stepCtx.isFirstStep && !stepCtx.interruptedResume
288
- ? (opts.files || []).map((file) => ({ mimeType: file.mimetype, path: file.localPath }))
288
+ ? (opts.files || []).map((file) => ({
289
+ mimeType: file.mimetype, path: file.localPath, name: file.name,
290
+ }))
289
291
  : [],
290
292
  },
291
293
  context: {
@@ -304,7 +306,6 @@ export function buildThreadRunRequest(threadId, stepCtx, ctx, opts) {
304
306
  executionKind,
305
307
  isUserInitiated: false,
306
308
  commissionMode: false,
307
- commissionTools: false,
308
309
  },
309
310
  policy: {
310
311
  background: stepBackgroundPolicy(),