@cortex-agent/server 2026.9.14 → 2026.9.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (259) hide show
  1. package/README.md +3 -2
  2. package/defaults/config/hooks/08-agents-md-injector-post-tool.json +10 -0
  3. package/defaults/config/hooks/{10-cortex-md-injector-session-start.json → 10-agents-md-injector-session-start.json} +3 -3
  4. package/defaults/config/hooks/{CORTEX.md → AGENTS.md} +2 -2
  5. package/defaults/hooks/{CORTEX.md → AGENTS.md} +1 -1
  6. package/defaults/hooks/{cortex-md-injector.mjs → agents-md-injector.mjs} +117 -26
  7. package/defaults/hooks/cortex-hook-api.mjs +2 -2
  8. package/defaults/hooks/new-session-hook.mjs +2 -2
  9. package/defaults/hooks/rules-loader.mjs +2 -2
  10. package/defaults/hooks/status-md-guard.mjs +8 -8
  11. package/defaults/hooks/task-status-check.mjs +18 -76
  12. package/defaults/hooks/tasks-yaml-guard.mjs +2 -2
  13. package/defaults/plugins/cortex-commission/.claude-plugin/plugin.json +2 -2
  14. package/defaults/plugins/cortex-commission/plugin.json +2 -2
  15. package/defaults/plugins/cortex-commission/skills/commission/SKILL.md +3 -3
  16. package/defaults/plugins/cortex-feishu/skills/feishu-doc/SKILL.md +1 -1
  17. package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +2 -2
  18. package/defaults/plugins/cortex-system/skills/project-init/SKILL.md +4 -4
  19. package/defaults/plugins/cortex-system/skills/task/SKILL.md +1 -1
  20. package/defaults/rules/{cortex-md.md → agents-md.md} +4 -4
  21. package/defaults/rules/decision-records.md +1 -1
  22. package/defaults/rules/meta-conventions.md +4 -4
  23. package/defaults/rules/mission-md.md +1 -1
  24. package/dist/agent-adapter/claude/adapter.d.ts +0 -6
  25. package/dist/agent-adapter/claude/adapter.js +0 -8
  26. package/dist/agent-adapter/claude/defaults.d.ts +10 -7
  27. package/dist/agent-adapter/claude/defaults.js +18 -16
  28. package/dist/agent-adapter/claude/hooks-builder.js +2 -2
  29. package/dist/agent-adapter/claude/spawn-args.d.ts +0 -3
  30. package/dist/agent-adapter/claude/spawn-args.js +20 -16
  31. package/dist/agent-adapter/claude/turn-machine.d.ts +11 -0
  32. package/dist/agent-adapter/claude/turn-machine.js +46 -5
  33. package/dist/agent-adapter/normalize/prompt-builder.d.ts +16 -1
  34. package/dist/agent-adapter/normalize/prompt-builder.js +24 -6
  35. package/dist/agent-adapter/pi/mcp-bridge-logic.d.ts +11 -2
  36. package/dist/agent-adapter/pi/mcp-bridge-logic.js +32 -1
  37. package/dist/agent-adapter/pi/mcp-bridge.js +16 -15
  38. package/dist/agent-adapter/pi/session-options.d.ts +0 -6
  39. package/dist/agent-adapter/pi/session-options.js +1 -8
  40. package/dist/agent-adapter/types.d.ts +1 -1
  41. package/dist/core/mcp-tool-gate.d.ts +3 -17
  42. package/dist/core/mcp-tool-gate.js +4 -19
  43. package/dist/core/media-types.d.ts +10 -0
  44. package/dist/core/media-types.js +34 -0
  45. package/dist/core/platform-settings-spec.js +1 -1
  46. package/dist/core/settings-spec.d.ts +22 -1
  47. package/dist/core/settings-spec.js +33 -2
  48. package/dist/core/types/agent-types.d.ts +3 -1
  49. package/dist/core/utils.d.ts +1 -1
  50. package/dist/core/utils.js +1 -1
  51. package/dist/domain/agents/config.d.ts +1 -1
  52. package/dist/domain/agents/config.js +1 -1
  53. package/dist/domain/agents/profile-switch.d.ts +1 -1
  54. package/dist/domain/agents/profile-switch.js +3 -5
  55. package/dist/domain/agents/subagent/runner.js +0 -1
  56. package/dist/domain/commissions/commission-draft.d.ts +58 -0
  57. package/dist/domain/commissions/commission-draft.js +87 -4
  58. package/dist/domain/commissions/commission-finalize.d.ts +8 -3
  59. package/dist/domain/commissions/commission-finalize.js +14 -0
  60. package/dist/domain/executions/registry.d.ts +1 -2
  61. package/dist/domain/executions/registry.js +0 -3
  62. package/dist/domain/mcp/bundled-server.js +4 -3
  63. package/dist/domain/mcp/feishu/file.js +37 -18
  64. package/dist/domain/mcp/feishu/types.d.ts +3 -0
  65. package/dist/domain/mcp/feishu-server.js +1 -1
  66. package/dist/domain/mcp/tools/{cortex-md.d.ts → agents-md.d.ts} +6 -6
  67. package/dist/domain/mcp/tools/{cortex-md.js → agents-md.js} +6 -6
  68. package/dist/domain/mcp/tools/commission-tools.d.ts +12 -1
  69. package/dist/domain/mcp/tools/commission-tools.js +68 -14
  70. package/dist/domain/mcp/tools/remote-file.d.ts +20 -0
  71. package/dist/domain/mcp/tools/remote-file.js +44 -0
  72. package/dist/domain/mcp/tools/slack.d.ts +2 -0
  73. package/dist/domain/mcp/tools/slack.js +22 -7
  74. package/dist/domain/mcp/tools/task-ops.js +5 -13
  75. package/dist/domain/mcp/tools/ui-file.js +23 -10
  76. package/dist/domain/mcp/tools/waitpoint.d.ts +3 -0
  77. package/dist/domain/mcp/tools/waitpoint.js +122 -0
  78. package/dist/domain/memory/agents-md-injector.d.ts +24 -0
  79. package/dist/domain/memory/{cortex-md-injector.js → agents-md-injector.js} +10 -7
  80. package/dist/domain/projects/project-store.d.ts +1 -1
  81. package/dist/domain/projects/project-store.js +3 -3
  82. package/dist/domain/remote/client-hot-reload.js +3 -1
  83. package/dist/domain/remote/client-manager.js +105 -126
  84. package/dist/domain/remote/client-ssh-tunnel.d.ts +16 -5
  85. package/dist/domain/remote/client-ssh-tunnel.js +12 -5
  86. package/dist/domain/remote/cortex-client-config.d.ts +1 -1
  87. package/dist/domain/remote/cortex-client-config.js +1 -1
  88. package/dist/domain/remote/device-file.d.ts +51 -0
  89. package/dist/domain/remote/device-file.js +193 -0
  90. package/dist/domain/remote/device-port.js +3 -0
  91. package/dist/domain/remote/reverse-stream.d.ts +18 -7
  92. package/dist/domain/remote/reverse-stream.js +19 -6
  93. package/dist/domain/runs/builders.js +0 -1
  94. package/dist/domain/runs/compact.js +0 -1
  95. package/dist/domain/runs/engine-spec.d.ts +11 -4
  96. package/dist/domain/runs/engine-spec.js +7 -4
  97. package/dist/domain/runs/prompt.js +16 -10
  98. package/dist/domain/runs/request.d.ts +0 -1
  99. package/dist/domain/sessions/session-hooks.d.ts +5 -12
  100. package/dist/domain/sessions/session-hooks.js +6 -13
  101. package/dist/domain/sessions/session-lifecycle.d.ts +4 -4
  102. package/dist/domain/sessions/session-lifecycle.js +5 -6
  103. package/dist/domain/sessions/session-retention.d.ts +1 -3
  104. package/dist/domain/sessions/session-retention.js +9 -26
  105. package/dist/domain/sessions/session-use.d.ts +32 -0
  106. package/dist/domain/sessions/session-use.js +63 -0
  107. package/dist/domain/sessions/session.js +6 -5
  108. package/dist/domain/system/server-update-check.js +29 -1
  109. package/dist/domain/system/update-ui-state.d.ts +32 -0
  110. package/dist/domain/system/update-ui-state.js +63 -0
  111. package/dist/domain/tasks/claim-recovery.js +2 -2
  112. package/dist/domain/tasks/dispatch-utils.d.ts +10 -1
  113. package/dist/domain/tasks/dispatch-utils.js +46 -1
  114. package/dist/domain/tasks/dispatcher.js +4 -5
  115. package/dist/domain/tasks/mutator.d.ts +2 -2
  116. package/dist/domain/tasks/mutator.js +2 -2
  117. package/dist/domain/tasks/system/task-cli.js +2 -2
  118. package/dist/domain/tasks/system/task-state.js +1 -1
  119. package/dist/domain/threads/runner.js +3 -2
  120. package/dist/domain/ui-service/app-router.d.ts +54 -3
  121. package/dist/domain/ui-service/app-router.js +12 -14
  122. package/dist/domain/ui-service/input-schemas.d.ts +49 -5
  123. package/dist/domain/ui-service/input-schemas.js +35 -9
  124. package/dist/domain/ui-service/mutate/platform-settings.js +1 -1
  125. package/dist/domain/ui-service/mutate/sessions.d.ts +17 -1
  126. package/dist/domain/ui-service/mutate/sessions.js +83 -3
  127. package/dist/domain/ui-service/mutate/system.d.ts +3 -1
  128. package/dist/domain/ui-service/mutate/system.js +13 -0
  129. package/dist/domain/ui-service/mutate/waitpoints.d.ts +2 -0
  130. package/dist/domain/ui-service/mutate/waitpoints.js +20 -0
  131. package/dist/domain/ui-service/platform-settings.js +1 -1
  132. package/dist/domain/ui-service/plugins-shared.js +1 -1
  133. package/dist/domain/ui-service/query/config.js +1 -1
  134. package/dist/domain/ui-service/query/executions.js +0 -2
  135. package/dist/domain/ui-service/query/machine-detail.js +3 -8
  136. package/dist/domain/ui-service/query/memory.js +1 -1
  137. package/dist/domain/ui-service/query/sessions.js +7 -0
  138. package/dist/domain/ui-service/query/system.d.ts +2 -1
  139. package/dist/domain/ui-service/query/system.js +4 -0
  140. package/dist/domain/ui-service/query/threads.js +1 -54
  141. package/dist/domain/ui-service/query/waitpoints.d.ts +30 -0
  142. package/dist/domain/ui-service/query/waitpoints.js +117 -0
  143. package/dist/domain/ui-service/query-input-schemas.d.ts +3 -0
  144. package/dist/domain/ui-service/query-input-schemas.js +3 -0
  145. package/dist/domain/ui-service/trpc.js +1 -1
  146. package/dist/domain/ui-service/types.d.ts +175 -50
  147. package/dist/domain/ui-service/types.js +1 -1
  148. package/dist/domain/ui-service/ui-service.js +13 -33
  149. package/dist/domain/waitpoints/notices.d.ts +21 -0
  150. package/dist/domain/waitpoints/notices.js +115 -0
  151. package/dist/domain/waitpoints/service.d.ts +91 -0
  152. package/dist/domain/waitpoints/service.js +243 -0
  153. package/dist/entry/app.js +39 -29
  154. package/dist/entry/auth-login-cli.js +1 -1
  155. package/dist/entry/auth-login-terminal.js +1 -1
  156. package/dist/entry/init-auth.js +1 -1
  157. package/dist/entry/init.js +6 -6
  158. package/dist/entry/signal-cli.d.ts +30 -0
  159. package/dist/entry/signal-cli.js +207 -0
  160. package/dist/entry/start-ui-http.d.ts +1 -1
  161. package/dist/entry/start-ui-http.js +5 -3
  162. package/dist/events/event-types.d.ts +5 -7
  163. package/dist/hooks/{cortex-md-injector.mjs → agents-md-injector.mjs} +117 -26
  164. package/dist/hooks/cortex-hook-api.mjs +2 -2
  165. package/dist/hooks/new-session-hook.mjs +2 -2
  166. package/dist/hooks/rules-loader.mjs +2 -2
  167. package/dist/hooks/status-md-guard.mjs +8 -8
  168. package/dist/hooks/task-status-check.mjs +18 -76
  169. package/dist/hooks/tasks-yaml-guard.mjs +2 -2
  170. package/dist/orchestration/agent-file-send.d.ts +9 -0
  171. package/dist/orchestration/agent-file-send.js +21 -2
  172. package/dist/orchestration/agent-runner.d.ts +4 -3
  173. package/dist/orchestration/agent-runner.js +25 -23
  174. package/dist/orchestration/attachments-store.d.ts +31 -0
  175. package/dist/orchestration/attachments-store.js +184 -0
  176. package/dist/orchestration/conversation-request.d.ts +30 -8
  177. package/dist/orchestration/conversation-request.js +62 -26
  178. package/dist/orchestration/edit-retry.js +2 -1
  179. package/dist/orchestration/interactions/ask-user-resume.js +2 -1
  180. package/dist/orchestration/interactions/plan-approvals.js +1 -1
  181. package/dist/orchestration/interactions/ui-update-prompt.d.ts +8 -0
  182. package/dist/orchestration/interactions/ui-update-prompt.js +47 -0
  183. package/dist/orchestration/outputs-store.d.ts +11 -0
  184. package/dist/orchestration/outputs-store.js +32 -6
  185. package/dist/orchestration/resume-dispatcher.js +2 -2
  186. package/dist/orchestration/routing/file-handler.d.ts +23 -2
  187. package/dist/orchestration/routing/file-handler.js +22 -5
  188. package/dist/orchestration/routing/webhook.js +240 -39
  189. package/dist/orchestration/session-compact.d.ts +3 -0
  190. package/dist/orchestration/session-compact.js +3 -2
  191. package/dist/orchestration/session-events.d.ts +6 -0
  192. package/dist/orchestration/session-events.js +5 -0
  193. package/dist/orchestration/session-gateway.d.ts +1 -1
  194. package/dist/orchestration/session-gateway.js +1 -0
  195. package/dist/orchestration/thread-executor.d.ts +2 -0
  196. package/dist/orchestration/thread-executor.js +11 -1
  197. package/dist/orchestration/thread-input.d.ts +3 -2
  198. package/dist/orchestration/thread-input.js +8 -9
  199. package/dist/orchestration/turn/turn-prep.d.ts +15 -1
  200. package/dist/orchestration/turn/turn-prep.js +21 -9
  201. package/dist/orchestration/waitpoint-ingress.d.ts +41 -0
  202. package/dist/orchestration/waitpoint-ingress.js +172 -0
  203. package/dist/orchestration/waitpoint-notifier.d.ts +21 -0
  204. package/dist/orchestration/waitpoint-notifier.js +119 -0
  205. package/dist/orchestration/waitpoint-remote-drain.d.ts +20 -0
  206. package/dist/orchestration/waitpoint-remote-drain.js +147 -0
  207. package/dist/orchestration/waitpoint-sweep.d.ts +42 -0
  208. package/dist/orchestration/waitpoint-sweep.js +87 -0
  209. package/dist/platform/adapters/feishu-image.d.ts +19 -0
  210. package/dist/platform/adapters/feishu-image.js +71 -0
  211. package/dist/platform/adapters/feishu.d.ts +2 -0
  212. package/dist/platform/adapters/feishu.js +26 -16
  213. package/dist/platform/ui-http/app-update.d.ts +11 -0
  214. package/dist/platform/ui-http/app-update.js +3 -0
  215. package/dist/platform/ui-http/listening-ports.d.ts +1 -1
  216. package/dist/platform/ui-http/listening-ports.js +1 -1
  217. package/dist/platform/ui-http/ui-session.js +1 -1
  218. package/dist/store/conversation-ledger-repo.d.ts +10 -19
  219. package/dist/store/conversation-ledger-repo.js +143 -152
  220. package/dist/store/execution-repo.d.ts +1 -19
  221. package/dist/store/execution-repo.js +1 -18
  222. package/dist/store/project-notes-repo.js +11 -2
  223. package/dist/store/prompt-migration-replacements.js +1 -1
  224. package/dist/store/session-registry-import.d.ts +34 -0
  225. package/dist/store/session-registry-import.js +182 -0
  226. package/dist/store/session-registry-journal.d.ts +107 -0
  227. package/dist/store/session-registry-journal.js +308 -19
  228. package/dist/store/session-registry-repo.d.ts +113 -28
  229. package/dist/store/session-registry-repo.js +288 -105
  230. package/dist/store/version-migrations.d.ts +29 -3
  231. package/dist/store/version-migrations.js +288 -24
  232. package/dist/store/waitpoint-repo.d.ts +108 -0
  233. package/dist/store/waitpoint-repo.js +94 -0
  234. package/package.json +2 -2
  235. package/web/dist/assets/index-CwwQNMpP.css +1 -0
  236. package/web/dist/assets/index-DLSfgq3o.js +444 -0
  237. package/web/dist/assets/{index-aHbOZSP6.js → index-DZTuqUO4.js} +1 -1
  238. package/web/dist/index.html +2 -2
  239. package/defaults/config/hooks/08-cortex-md-injector-post-tool.json +0 -10
  240. package/dist/domain/executions/log-tailer.d.ts +0 -71
  241. package/dist/domain/executions/log-tailer.js +0 -194
  242. package/dist/domain/memory/cortex-md-injector.d.ts +0 -24
  243. package/dist/domain/memory/cortex-md-scanner.d.ts +0 -10
  244. package/dist/domain/memory/cortex-md-scanner.js +0 -66
  245. package/dist/domain/remote/cortex-client.d.ts +0 -1
  246. package/dist/domain/remote/cortex-client.js +0 -662
  247. package/dist/domain/tasks/system/cortex-run.d.ts +0 -25
  248. package/dist/domain/tasks/system/cortex-run.js +0 -360
  249. package/dist/store/session-repo.d.ts +0 -65
  250. package/dist/store/session-repo.js +0 -184
  251. package/web/dist/assets/index-BuXbCsuz.js +0 -444
  252. package/web/dist/assets/index-CCPxQ94C.css +0 -1
  253. /package/defaults/{CORTEX.md → AGENTS.md} +0 -0
  254. /package/defaults/config/{CORTEX.md → AGENTS.md} +0 -0
  255. /package/defaults/context/{CORTEX.md → AGENTS.md} +0 -0
  256. /package/defaults/context/ideas/{CORTEX.md → AGENTS.md} +0 -0
  257. /package/defaults/context/projects/{CORTEX.md → AGENTS.md} +0 -0
  258. /package/defaults/context/scans/{CORTEX.md → AGENTS.md} +0 -0
  259. /package/defaults/context/user/{CORTEX.md → AGENTS.md} +0 -0
@@ -1,360 +0,0 @@
1
- #!/usr/bin/env node
2
- // cortex-run CLI dispatch via sendCommand (DR-0011 §4.8 + §4.9).
3
- //
4
- // Launch:
5
- // cortex-run [--device <name>] --name <name> [--stall 10m] [--gpu auto]
6
- // [--task-project P --task-id ABCD] [--force]
7
- // [--env-passthrough VAR1,VAR2,...]
8
- // [--log-tail-bytes 5000]
9
- // -- COMMAND [ARGS...]
10
- //
11
- // Cancel:
12
- // cortex-run --cancel <name> [--device <name>] [--signal SIGTERM]
13
- //
14
- // No local spawn — all execution forwarded via sendCommand to cortex-client.
15
- import { getLocalMachine } from '../../tasks/dispatch-utils.js';
16
- import { pendingTask } from './task-state.js';
17
- import { parseArgs } from 'node:util';
18
- import { isMainModule } from '../../../core/utils.js';
19
- // --- Daemon webhook bridge (HTTP to agent-server daemon) ---
20
- // The daemon's webhook server runs at 127.0.0.1:3001 (env WEBHOOK_PORT).
21
- // When cortex-run runs standalone, the client-manager's devices Map lives in
22
- // the daemon process, so we proxy sendCommand/isDeviceOnline through HTTP.
23
- const WEBHOOK_PORT = parseInt(process.env.WEBHOOK_PORT || '3001', 10);
24
- const WEBHOOK_BASE = `http://127.0.0.1:${WEBHOOK_PORT}`;
25
- // Bearer token for the webhook auth gate. Inherited from the daemon/dispatcher env (see core/auth.ts).
26
- const webhookAuthHeader = () => ({ 'x-cortex-token': process.env.CORTEX_WEBHOOK_TOKEN || '' });
27
- async function httpIsDeviceOnline(device) {
28
- try {
29
- const res = await fetch(`${WEBHOOK_BASE}/webhook/devices`, { headers: webhookAuthHeader() });
30
- if (!res.ok)
31
- return false;
32
- const data = (await res.json());
33
- return data.devices?.includes(device) ?? false;
34
- }
35
- catch {
36
- return false;
37
- }
38
- }
39
- function isConnectionRefused(err) {
40
- if (err && typeof err === 'object') {
41
- const e = err;
42
- if (e.cause?.code === 'ECONNREFUSED' || e.code === 'ECONNREFUSED')
43
- return true;
44
- }
45
- return false;
46
- }
47
- async function httpSendCommand(device, command) {
48
- const httpTimeout = (command.timeout || 60_000) + 15_000;
49
- const controller = new AbortController();
50
- const timer = setTimeout(() => controller.abort(), httpTimeout);
51
- try {
52
- const res = await fetch(`${WEBHOOK_BASE}/webhook/remote-command`, {
53
- method: 'POST',
54
- headers: { 'Content-Type': 'application/json', ...webhookAuthHeader() },
55
- body: JSON.stringify({
56
- device,
57
- action: command.action,
58
- params: command.params,
59
- timeout: command.timeout,
60
- }),
61
- signal: controller.signal,
62
- });
63
- const data = (await res.json());
64
- if (!data.success) {
65
- const suffix = data.onlineDevices?.length
66
- ? ` Online devices: ${data.onlineDevices.join(', ')}`
67
- : '';
68
- throw new Error(`${data.error || 'Unknown error from daemon'}${suffix}`);
69
- }
70
- return data.data;
71
- }
72
- catch (e) {
73
- if (isConnectionRefused(e)) {
74
- throw new Error(`Cannot connect to cortex daemon at ${WEBHOOK_BASE}. Is the agent server running?`);
75
- }
76
- throw e;
77
- }
78
- finally {
79
- clearTimeout(timer);
80
- }
81
- }
82
- // --- Types ---
83
- function resolveTaskGeneration(project, taskId, env = process.env) {
84
- const sameTask = !!taskId && env.CORTEX_TASK_ID === taskId;
85
- const sameProject = !!project && env.CORTEX_TASK_PROJECT === project;
86
- return sameTask && sameProject ? env.CORTEX_TASK_GENERATION ?? null : null;
87
- }
88
- // --- CLI parsing ---
89
- function getCortexRunHelp() {
90
- return [
91
- 'cortex-run — dispatch a command on a remote device via the Cortex daemon',
92
- '',
93
- 'Launch:',
94
- ' cortex-run [--device <name>] --name <name> [--stall 10m] [--gpu auto]',
95
- ' [--task-project P --task-id ABCD] [--force]',
96
- ' [--env-passthrough VAR1,VAR2,...]',
97
- ' [--log-tail-bytes 5000]',
98
- ' -- COMMAND [ARGS...]',
99
- '',
100
- 'Cancel:',
101
- ' cortex-run --cancel <name> [--device <name>] [--signal SIGTERM]',
102
- '',
103
- 'Options:',
104
- ' --name <name> Required for launch — unique run name (also used as result dir)',
105
- ' --device <name> Target device (default: local machine name from machines.json)',
106
- ' --stall <duration> Stall timeout, e.g. 10m / 1h (default: 10m)',
107
- ' --gpu <slot> GPU slot: auto | none | <index> (default: auto)',
108
- ' --force Allow launch even if a same-name run state dir exists',
109
- ' --task-project <name> Link this run to a TASKS.yaml task — marks pending on launch',
110
- ' --task-id <hash> 4-char hex task id (used with --task-project)',
111
- ' --env-passthrough <list> Comma-separated env var names to forward to the remote',
112
- ' --log-tail-bytes <n> Bytes of log tail returned in callback (default: 5000)',
113
- ' --cancel <name> Cancel a previously launched run by name',
114
- ' --signal <sig> Signal to send when cancelling (default: SIGTERM)',
115
- ' --help, -h Show this help',
116
- '',
117
- 'Notes:',
118
- ' • All execution is forwarded via the daemon webhook (default 127.0.0.1:3001).',
119
- ' • Without --task-id, exit/termination is still reported but no task lifecycle is touched.',
120
- ' • --task-id must be 4-char hex; invalid IDs cause a non-zero exit before dispatch.',
121
- ].join('\n');
122
- }
123
- /**
124
- * Returns true if the user is asking for help at the top level.
125
- * `--help` / `-h` that appear AFTER the `--` separator belong to the user
126
- * command and must not be treated as cortex-run help requests.
127
- */
128
- function isHelpRequest(rawArgs) {
129
- if (rawArgs.length === 0)
130
- return true;
131
- const sepIdx = rawArgs.indexOf('--');
132
- const helpIdx = rawArgs.indexOf('--help');
133
- const shortIdx = rawArgs.indexOf('-h');
134
- const firstHelp = [helpIdx, shortIdx].filter((i) => i !== -1).sort((a, b) => a - b)[0];
135
- if (firstHelp == null)
136
- return false;
137
- return sepIdx === -1 || firstHelp < sepIdx;
138
- }
139
- function parseCliArgs() {
140
- const rawArgs = process.argv.slice(2);
141
- // Detect --cancel mode: only if no -- separator present, or --cancel is before --
142
- const sepIdx = rawArgs.indexOf('--');
143
- const cancelIdx = rawArgs.indexOf('--cancel');
144
- const isCancelMode = cancelIdx !== -1 && (sepIdx === -1 || cancelIdx < sepIdx);
145
- if (isCancelMode) {
146
- const cancelArgs = rawArgs.slice(0);
147
- const { values } = parseArgs({
148
- args: cancelArgs,
149
- options: {
150
- cancel: { type: 'string' },
151
- device: { type: 'string' },
152
- signal: { type: 'string', default: 'SIGTERM' },
153
- },
154
- strict: true,
155
- allowPositionals: true,
156
- });
157
- if (!values.cancel) {
158
- console.error('Error: --cancel requires a run name.');
159
- process.exit(2);
160
- }
161
- return {
162
- cancel: values.cancel,
163
- device: values.device || getLocalMachine(),
164
- signal: values.signal || 'SIGTERM',
165
- name: undefined,
166
- command: undefined,
167
- project: null,
168
- taskId: null,
169
- envPassthrough: [],
170
- logTailBytes: 5000,
171
- stall: '10m',
172
- gpu: 'auto',
173
- force: false,
174
- };
175
- }
176
- // Launch mode: -- separator required
177
- if (sepIdx === -1) {
178
- console.error('Error: No command specified. Use -- to separate cortex-run args from command.');
179
- process.exit(2);
180
- }
181
- const cortexArgs = rawArgs.slice(0, sepIdx);
182
- const command = rawArgs.slice(sepIdx + 1);
183
- if (command.length === 0) {
184
- console.error('Error: No command specified after --.');
185
- process.exit(2);
186
- }
187
- // --cancel inside launch mode (after --) is not cancel mode; but if --cancel
188
- // appears in cortexArgs, parseArgs will reject it since it's not in the
189
- // launch option list. That's a usage error.
190
- const { values } = parseArgs({
191
- args: cortexArgs,
192
- options: {
193
- name: { type: 'string' },
194
- device: { type: 'string' },
195
- stall: { type: 'string', default: '10m' },
196
- gpu: { type: 'string', default: 'auto' },
197
- force: { type: 'boolean', default: false },
198
- 'task-project': { type: 'string' },
199
- 'task-id': { type: 'string' },
200
- 'env-passthrough': { type: 'string' },
201
- 'log-tail-bytes': { type: 'string' },
202
- },
203
- strict: true,
204
- });
205
- if (!values.name) {
206
- console.error('Error: --name is required.');
207
- process.exit(2);
208
- }
209
- const rawTaskId = values['task-id'] || null;
210
- if (rawTaskId && !/^[0-9a-fA-F]{4}$/.test(rawTaskId)) {
211
- console.error(`[cortex-run] FATAL: --task-id='${rawTaskId}' is not a valid 4-char hex hash. ` +
212
- `Refusing to start — fix the launch command.`);
213
- process.exit(1);
214
- }
215
- // Parse env-passthrough (comma-separated key list)
216
- const envPassthrough = [];
217
- if (values['env-passthrough']) {
218
- for (const key of values['env-passthrough'].split(',').map(s => s.trim()).filter(Boolean)) {
219
- envPassthrough.push(key);
220
- }
221
- }
222
- // Parse log-tail-bytes
223
- let logTailBytes = 5000;
224
- if (values['log-tail-bytes']) {
225
- logTailBytes = parseInt(values['log-tail-bytes'], 10);
226
- if (isNaN(logTailBytes) || logTailBytes < 0) {
227
- console.error(`Error: invalid --log-tail-bytes '${values['log-tail-bytes']}'.`);
228
- process.exit(2);
229
- }
230
- }
231
- return {
232
- name: values.name,
233
- device: values.device || getLocalMachine(),
234
- command,
235
- project: values['task-project'] || null,
236
- taskId: rawTaskId,
237
- envPassthrough,
238
- logTailBytes,
239
- cancel: null,
240
- signal: 'SIGTERM',
241
- stall: values.stall,
242
- gpu: values.gpu,
243
- force: values.force,
244
- };
245
- }
246
- // --- Launch (DR-0011 §4.8) ---
247
- async function cmdLaunch(args) {
248
- const device = args.device;
249
- const hasTaskContext = !!args.project && !!args.taskId
250
- && process.env.CORTEX_TASK_PROJECT === args.project
251
- && process.env.CORTEX_TASK_ID === args.taskId;
252
- const dispatchGeneration = resolveTaskGeneration(args.project, args.taskId);
253
- const ownership = hasTaskContext ? { generation: dispatchGeneration } : undefined;
254
- if (!(await httpIsDeviceOnline(device))) {
255
- console.error(`[cortex-run] Error: device "${device}" is not online (cortex-client not connected)`);
256
- process.exit(1);
257
- }
258
- // --env-passthrough: extract values from server process.env
259
- const passthroughEnv = {};
260
- for (const key of args.envPassthrough) {
261
- if (process.env[key] !== undefined) {
262
- passthroughEnv[key] = process.env[key];
263
- }
264
- }
265
- // Task linkage: mark pending (belt-and-suspenders, non-blocking)
266
- if (args.project && args.taskId) {
267
- try {
268
- const result = pendingTask(null, args.project, args.taskId, ownership);
269
- if ('stale' in result && result.stale) {
270
- console.error(`[cortex-run] Error: ${result.message}`);
271
- process.exit(1);
272
- }
273
- else if (!result.success) {
274
- console.error(`[cortex-run] Warning: pendingTask failed: ${result.message}`);
275
- }
276
- else {
277
- console.log(`[cortex-run] Task ${args.taskId} marked pending`);
278
- }
279
- }
280
- catch (e) {
281
- console.error(`[cortex-run] Warning: pendingTask error: ${e.message}`);
282
- }
283
- }
284
- // Single pathway: all launch via sendCommand
285
- let result;
286
- try {
287
- result = await httpSendCommand(device, {
288
- action: 'cortex-run.launch',
289
- params: {
290
- name: args.name,
291
- command: args.command,
292
- stall: args.stall,
293
- gpu: args.gpu,
294
- force: args.force,
295
- cwd: process.cwd(),
296
- env: passthroughEnv,
297
- logTailBytes: args.logTailBytes,
298
- taskProject: args.project,
299
- taskId: args.taskId,
300
- dispatchGeneration,
301
- },
302
- timeout: 30_000,
303
- });
304
- }
305
- catch (e) {
306
- console.error(`[cortex-run] Error: launch failed: ${e.message}`);
307
- process.exit(1);
308
- }
309
- console.log(`[cortex-run] launched on ${device}`);
310
- console.log(`[cortex-run] pid=${result.pid}`);
311
- console.log(`[cortex-run] callbackId=${result.callbackId}`);
312
- console.log(`[cortex-run] resultDir=${result.resultDir}`);
313
- console.log(`[cortex-run] task lifecycle will be reported back via task-callback`);
314
- process.exit(0);
315
- }
316
- // --- Cancel (DR-0011 §4.9) ---
317
- async function cmdCancel(args) {
318
- const device = args.device;
319
- if (!(await httpIsDeviceOnline(device))) {
320
- console.error(`[cortex-run] Error: device "${device}" is not online (cortex-client not connected)`);
321
- process.exit(1);
322
- }
323
- let result;
324
- try {
325
- result = await httpSendCommand(device, {
326
- action: 'cortex-run.cancel',
327
- params: {
328
- name: args.cancel,
329
- signal: args.signal,
330
- },
331
- timeout: 30_000,
332
- });
333
- }
334
- catch (e) {
335
- console.error(`[cortex-run] Error: cancel failed: ${e.message}`);
336
- process.exit(1);
337
- }
338
- console.log(`[cortex-run] cancel signal sent to ${device}: ${args.cancel}`);
339
- console.log(`[cortex-run] killed=${result.killed} (pid=${result.pid})`);
340
- process.exit(0);
341
- }
342
- // --- Main entry ---
343
- export { parseCliArgs, getCortexRunHelp, isHelpRequest, resolveTaskGeneration };
344
- // Use the shared isMainModule helper so symlink invocations (e.g. via the
345
- // global `cortex-run` bin) follow through to realpath comparison. The
346
- // hand-rolled `path.resolve` variant previously here did not follow symlinks
347
- // and silently skipped main() when invoked via the npm global bin link.
348
- if (isMainModule(import.meta.url)) {
349
- if (isHelpRequest(process.argv.slice(2))) {
350
- process.stdout.write(`${getCortexRunHelp()}\n`);
351
- process.exit(0);
352
- }
353
- const args = parseCliArgs();
354
- if (args.cancel) {
355
- await cmdCancel(args);
356
- }
357
- else {
358
- await cmdLaunch(args);
359
- }
360
- }
@@ -1,65 +0,0 @@
1
- /**
2
- * A conduit provider resolves session+project info for non-file-based conduits
3
- * (e.g., TUI in-memory conduit state). Returns null for unrecognized conduitIds
4
- * so the file-based lookup is used as fallback.
5
- */
6
- export type ConduitProvider = (conduitId: string) => {
7
- sessionId: string;
8
- projectId: string;
9
- } | null;
10
- /**
11
- * Register a conduit provider callback. Called by adapters (e.g., TuiGatewayAdapter)
12
- * during start() so session lookup can resolve in-memory conduit state.
13
- */
14
- export declare function registerConduitProvider(provider: ConduitProvider): void;
15
- /** Shape of sessions.json: `{"<channel>": sessionId, ...}`. Legacy files key on
16
- * `"<backend>:<channel>"`; both are read, and `migrateSessionKeys` collapses the old form. */
17
- export type SessionsData = Record<string, string>;
18
- export interface SessionKeyMigrationDeps {
19
- /** When two backends bound the same channel, the more recently used binding wins. Returns null
20
- * for a session the registry has forgotten, which then loses to any dated candidate. */
21
- lastUsedAt?: (sessionId: string) => Promise<string | null>;
22
- log?: (message: string) => void;
23
- }
24
- export interface SessionKeyMigrationResult {
25
- /** Keys rewritten from `backend:channel` to `channel`. */
26
- migrated: number;
27
- /** Channels that held two different sessions, one of which was dropped. */
28
- conflicts: number;
29
- }
30
- export declare class SessionRepo {
31
- private _repo;
32
- constructor(filePath?: string);
33
- /**
34
- * The session bound to a channel.
35
- *
36
- * `backend` is accepted and ignored: a channel has one session. The parameter stays so the
37
- * many call sites that pass one keep compiling while they are cleaned up; it is deprecated.
38
- *
39
- * Legacy `backend:channel` keys are still read, so a file written by an older build resolves
40
- * correctly before `migrateSessionKeys` has run (and in any process that never runs it).
41
- */
42
- getSessionAsync(channel: string, _backend?: string): Promise<string | undefined>;
43
- /** Bind a channel to a session. Any legacy backend-prefixed key for the same channel is dropped,
44
- * so a write is also a migration of the one channel it touches. */
45
- setSessionAsync(channel: string, sessionId: string, _backend?: string): Promise<void>;
46
- /** Unbind a channel. Deletes every form of the key, so one call really does clear the channel —
47
- * where the old signature needed one call per backend and silently left the other behind. */
48
- deleteSessionAsync(channel: string, _backend?: string): Promise<void>;
49
- /**
50
- * Collapse `backend:channel` keys onto `channel`, once, at startup.
51
- *
52
- * A channel bound under both backends keeps the more recently used session and drops the other:
53
- * the two were never usable at the same time — only the channel's current backend was ever
54
- * consulted — so the newer one is the conversation the user actually has. Every drop is logged
55
- * with both ids, because that is the only record that the other binding existed.
56
- */
57
- migrateSessionKeys(deps?: SessionKeyMigrationDeps): Promise<SessionKeyMigrationResult>;
58
- deleteManyBySessionIds(sessionIds: Iterable<string>): Promise<number>;
59
- deleteExceptSessionIds(sessionIds: Iterable<string>): Promise<number>;
60
- /** Drop the in-memory cache so the next read() fetches from disk. Test hook. */
61
- invalidate(): void;
62
- /** Wait for any in-flight mutate() to complete. For graceful SIGTERM drain. */
63
- flush(): Promise<void>;
64
- }
65
- export declare const sessionRepo: SessionRepo;
@@ -1,184 +0,0 @@
1
- import * as path from 'path';
2
- import { JsonRepository } from '../core/json-repository.js';
3
- import { STORE_DIR } from '../core/paths.js';
4
- const SESSIONS_FILE = path.join(STORE_DIR, 'sessions.json');
5
- /** Registered conduit providers, tried in registration order before file lookup. */
6
- const conduitProviders = [];
7
- /**
8
- * Register a conduit provider callback. Called by adapters (e.g., TuiGatewayAdapter)
9
- * during start() so session lookup can resolve in-memory conduit state.
10
- */
11
- export function registerConduitProvider(provider) {
12
- conduitProviders.push(provider);
13
- }
14
- /** Try conduit providers in registration order; returns null if none match. */
15
- async function lookupViaProviders(channel) {
16
- for (const provider of conduitProviders) {
17
- const result = provider(channel);
18
- if (result)
19
- return result.sessionId;
20
- }
21
- return undefined;
22
- }
23
- /**
24
- * D5: a channel has ONE session, and which backend it runs is a property of that session's record,
25
- * not of the key it is filed under. Keying on `backend:channel` let the same channel hold two
26
- * bindings at once, so a caller that asked with the wrong backend — cancel, `!session`, the
27
- * scheduler — silently missed a session that was right there.
28
- */
29
- const LEGACY_PREFIXES = ['claude', 'pi'];
30
- function legacyKeys(channel) {
31
- return LEGACY_PREFIXES.map(prefix => `${prefix}:${channel}`);
32
- }
33
- /** Split a stored key into the channel it refers to. `web:`/`slack:`/`feishu:`/`tui:` channels
34
- * carry their own colons, so only a leading backend name is stripped, and only those two. */
35
- function channelFromKey(key) {
36
- for (const prefix of LEGACY_PREFIXES) {
37
- if (key.startsWith(`${prefix}:`))
38
- return key.slice(prefix.length + 1);
39
- }
40
- return key;
41
- }
42
- export class SessionRepo {
43
- _repo;
44
- constructor(filePath = SESSIONS_FILE) {
45
- this._repo = new JsonRepository({
46
- filePath,
47
- defaultValue: () => ({}),
48
- migrate: (raw) => (typeof raw === 'object' && raw !== null ? raw : ({})),
49
- });
50
- }
51
- /**
52
- * The session bound to a channel.
53
- *
54
- * `backend` is accepted and ignored: a channel has one session. The parameter stays so the
55
- * many call sites that pass one keep compiling while they are cleaned up; it is deprecated.
56
- *
57
- * Legacy `backend:channel` keys are still read, so a file written by an older build resolves
58
- * correctly before `migrateSessionKeys` has run (and in any process that never runs it).
59
- */
60
- async getSessionAsync(channel, _backend) {
61
- // Try conduit providers first (TUI in-memory state, etc.)
62
- const providerResult = await lookupViaProviders(channel);
63
- if (providerResult !== undefined)
64
- return providerResult;
65
- // Fall back to file storage
66
- const sessions = await this._repo.read();
67
- if (sessions[channel] !== undefined)
68
- return sessions[channel];
69
- for (const key of legacyKeys(channel)) {
70
- if (sessions[key] !== undefined)
71
- return sessions[key];
72
- }
73
- return undefined;
74
- }
75
- /** Bind a channel to a session. Any legacy backend-prefixed key for the same channel is dropped,
76
- * so a write is also a migration of the one channel it touches. */
77
- async setSessionAsync(channel, sessionId, _backend) {
78
- await this._repo.mutate((sessions) => {
79
- sessions[channel] = sessionId;
80
- for (const key of legacyKeys(channel))
81
- delete sessions[key];
82
- return { next: sessions, result: undefined };
83
- });
84
- }
85
- /** Unbind a channel. Deletes every form of the key, so one call really does clear the channel —
86
- * where the old signature needed one call per backend and silently left the other behind. */
87
- async deleteSessionAsync(channel, _backend) {
88
- await this._repo.mutate((sessions) => {
89
- delete sessions[channel];
90
- for (const key of legacyKeys(channel))
91
- delete sessions[key];
92
- return { next: sessions, result: undefined };
93
- });
94
- }
95
- /**
96
- * Collapse `backend:channel` keys onto `channel`, once, at startup.
97
- *
98
- * A channel bound under both backends keeps the more recently used session and drops the other:
99
- * the two were never usable at the same time — only the channel's current backend was ever
100
- * consulted — so the newer one is the conversation the user actually has. Every drop is logged
101
- * with both ids, because that is the only record that the other binding existed.
102
- */
103
- async migrateSessionKeys(deps = {}) {
104
- const lastUsedAt = deps.lastUsedAt ?? (async () => null);
105
- const sessions = await this._repo.read();
106
- const legacy = Object.keys(sessions).filter(key => key !== channelFromKey(key));
107
- if (legacy.length === 0)
108
- return { migrated: 0, conflicts: 0 };
109
- // Resolve timestamps before the mutate: the mutator must stay synchronous.
110
- const dated = new Map();
111
- for (const key of legacy) {
112
- const id = sessions[key];
113
- if (!dated.has(id))
114
- dated.set(id, await lastUsedAt(id).catch(() => null));
115
- }
116
- for (const key of legacy) {
117
- const bare = sessions[channelFromKey(key)];
118
- if (bare !== undefined && !dated.has(bare))
119
- dated.set(bare, await lastUsedAt(bare).catch(() => null));
120
- }
121
- return this._repo.mutate((data) => {
122
- let migrated = 0;
123
- let conflicts = 0;
124
- for (const key of legacy) {
125
- const value = data[key];
126
- if (value === undefined)
127
- continue;
128
- delete data[key];
129
- const channel = channelFromKey(key);
130
- const incumbent = data[channel];
131
- if (incumbent === undefined || incumbent === value) {
132
- data[channel] = value;
133
- migrated += 1;
134
- continue;
135
- }
136
- conflicts += 1;
137
- // An undated candidate is one the registry has forgotten; it loses to any dated one, and
138
- // to the incumbent when neither is dated (first key wins, so the result is deterministic).
139
- const keep = (dated.get(value) ?? '') > (dated.get(incumbent) ?? '') ? value : incumbent;
140
- data[channel] = keep;
141
- deps.log?.(`sessions.json: channel ${channel} was bound under two backends `
142
- + `(${incumbent}, ${value}); keeping the more recently used session ${keep}`);
143
- }
144
- return { next: data, result: { migrated, conflicts } };
145
- });
146
- }
147
- async deleteManyBySessionIds(sessionIds) {
148
- const targets = new Set(sessionIds);
149
- if (targets.size === 0)
150
- return 0;
151
- return this._repo.mutate((sessions) => {
152
- let removed = 0;
153
- for (const [key, value] of Object.entries(sessions)) {
154
- if (!targets.has(value))
155
- continue;
156
- delete sessions[key];
157
- removed += 1;
158
- }
159
- return { next: sessions, result: removed };
160
- });
161
- }
162
- async deleteExceptSessionIds(sessionIds) {
163
- const live = new Set(sessionIds);
164
- return this._repo.mutate((sessions) => {
165
- let removed = 0;
166
- for (const [key, value] of Object.entries(sessions)) {
167
- if (live.has(value))
168
- continue;
169
- delete sessions[key];
170
- removed += 1;
171
- }
172
- return { next: sessions, result: removed };
173
- });
174
- }
175
- /** Drop the in-memory cache so the next read() fetches from disk. Test hook. */
176
- invalidate() {
177
- this._repo.invalidate();
178
- }
179
- /** Wait for any in-flight mutate() to complete. For graceful SIGTERM drain. */
180
- flush() {
181
- return this._repo.flush();
182
- }
183
- }
184
- export const sessionRepo = new SessionRepo();