@cortex-agent/server 2026.9.15 → 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 (192) 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-feishu/skills/feishu-doc/SKILL.md +1 -1
  14. package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +2 -2
  15. package/defaults/plugins/cortex-system/skills/project-init/SKILL.md +4 -4
  16. package/defaults/plugins/cortex-system/skills/task/SKILL.md +1 -1
  17. package/defaults/rules/{cortex-md.md → agents-md.md} +4 -4
  18. package/defaults/rules/decision-records.md +1 -1
  19. package/defaults/rules/meta-conventions.md +4 -4
  20. package/defaults/rules/mission-md.md +1 -1
  21. package/dist/agent-adapter/claude/hooks-builder.js +2 -2
  22. package/dist/agent-adapter/claude/spawn-args.js +4 -0
  23. package/dist/agent-adapter/claude/turn-machine.d.ts +11 -0
  24. package/dist/agent-adapter/claude/turn-machine.js +46 -5
  25. package/dist/agent-adapter/normalize/prompt-builder.d.ts +16 -1
  26. package/dist/agent-adapter/normalize/prompt-builder.js +24 -6
  27. package/dist/agent-adapter/types.d.ts +1 -0
  28. package/dist/core/mcp-tool-gate.js +1 -0
  29. package/dist/core/media-types.d.ts +10 -0
  30. package/dist/core/media-types.js +34 -0
  31. package/dist/core/platform-settings-spec.js +1 -1
  32. package/dist/core/settings-spec.d.ts +21 -0
  33. package/dist/core/settings-spec.js +28 -1
  34. package/dist/core/types/agent-types.d.ts +3 -1
  35. package/dist/core/utils.d.ts +1 -1
  36. package/dist/core/utils.js +1 -1
  37. package/dist/domain/executions/registry.d.ts +1 -2
  38. package/dist/domain/executions/registry.js +0 -3
  39. package/dist/domain/mcp/bundled-server.js +4 -3
  40. package/dist/domain/mcp/feishu/file.js +37 -18
  41. package/dist/domain/mcp/feishu/types.d.ts +3 -0
  42. package/dist/domain/mcp/feishu-server.js +1 -1
  43. package/dist/domain/mcp/tools/{cortex-md.d.ts → agents-md.d.ts} +6 -6
  44. package/dist/domain/mcp/tools/{cortex-md.js → agents-md.js} +6 -6
  45. package/dist/domain/mcp/tools/remote-file.d.ts +20 -0
  46. package/dist/domain/mcp/tools/remote-file.js +44 -0
  47. package/dist/domain/mcp/tools/slack.d.ts +2 -0
  48. package/dist/domain/mcp/tools/slack.js +22 -7
  49. package/dist/domain/mcp/tools/task-ops.js +5 -13
  50. package/dist/domain/mcp/tools/ui-file.js +23 -10
  51. package/dist/domain/mcp/tools/waitpoint.d.ts +3 -0
  52. package/dist/domain/mcp/tools/waitpoint.js +122 -0
  53. package/dist/domain/memory/agents-md-injector.d.ts +24 -0
  54. package/dist/domain/memory/{cortex-md-injector.js → agents-md-injector.js} +10 -7
  55. package/dist/domain/projects/project-store.d.ts +1 -1
  56. package/dist/domain/projects/project-store.js +3 -3
  57. package/dist/domain/remote/client-hot-reload.js +3 -1
  58. package/dist/domain/remote/client-manager.js +39 -119
  59. package/dist/domain/remote/cortex-client-config.d.ts +1 -1
  60. package/dist/domain/remote/cortex-client-config.js +1 -1
  61. package/dist/domain/remote/device-file.d.ts +51 -0
  62. package/dist/domain/remote/device-file.js +193 -0
  63. package/dist/domain/remote/device-port.js +3 -0
  64. package/dist/domain/remote/reverse-stream.d.ts +18 -7
  65. package/dist/domain/remote/reverse-stream.js +19 -6
  66. package/dist/domain/tasks/claim-recovery.js +2 -2
  67. package/dist/domain/tasks/dispatch-utils.d.ts +10 -1
  68. package/dist/domain/tasks/dispatch-utils.js +46 -1
  69. package/dist/domain/tasks/dispatcher.js +4 -5
  70. package/dist/domain/tasks/mutator.d.ts +2 -2
  71. package/dist/domain/tasks/mutator.js +2 -2
  72. package/dist/domain/tasks/system/task-cli.js +2 -2
  73. package/dist/domain/tasks/system/task-state.js +1 -1
  74. package/dist/domain/threads/runner.js +3 -1
  75. package/dist/domain/ui-service/app-router.d.ts +24 -3
  76. package/dist/domain/ui-service/app-router.js +8 -14
  77. package/dist/domain/ui-service/input-schemas.d.ts +17 -5
  78. package/dist/domain/ui-service/input-schemas.js +13 -9
  79. package/dist/domain/ui-service/mutate/platform-settings.js +1 -1
  80. package/dist/domain/ui-service/mutate/sessions.d.ts +5 -1
  81. package/dist/domain/ui-service/mutate/sessions.js +14 -0
  82. package/dist/domain/ui-service/mutate/waitpoints.d.ts +2 -0
  83. package/dist/domain/ui-service/mutate/waitpoints.js +20 -0
  84. package/dist/domain/ui-service/platform-settings.js +1 -1
  85. package/dist/domain/ui-service/plugins-shared.js +1 -1
  86. package/dist/domain/ui-service/query/config.js +1 -1
  87. package/dist/domain/ui-service/query/executions.js +0 -2
  88. package/dist/domain/ui-service/query/machine-detail.js +3 -8
  89. package/dist/domain/ui-service/query/memory.js +1 -1
  90. package/dist/domain/ui-service/query/sessions.js +7 -0
  91. package/dist/domain/ui-service/query/threads.js +1 -54
  92. package/dist/domain/ui-service/query/waitpoints.d.ts +30 -0
  93. package/dist/domain/ui-service/query/waitpoints.js +117 -0
  94. package/dist/domain/ui-service/query-input-schemas.d.ts +3 -0
  95. package/dist/domain/ui-service/query-input-schemas.js +3 -0
  96. package/dist/domain/ui-service/trpc.js +1 -1
  97. package/dist/domain/ui-service/types.d.ts +133 -49
  98. package/dist/domain/ui-service/types.js +1 -1
  99. package/dist/domain/ui-service/ui-service.js +7 -31
  100. package/dist/domain/waitpoints/notices.d.ts +21 -0
  101. package/dist/domain/waitpoints/notices.js +115 -0
  102. package/dist/domain/waitpoints/service.d.ts +91 -0
  103. package/dist/domain/waitpoints/service.js +243 -0
  104. package/dist/entry/app.js +29 -7
  105. package/dist/entry/auth-login-cli.js +1 -1
  106. package/dist/entry/auth-login-terminal.js +1 -1
  107. package/dist/entry/init-auth.js +1 -1
  108. package/dist/entry/init.js +6 -6
  109. package/dist/entry/signal-cli.d.ts +30 -0
  110. package/dist/entry/signal-cli.js +207 -0
  111. package/dist/entry/start-ui-http.d.ts +1 -1
  112. package/dist/entry/start-ui-http.js +2 -2
  113. package/dist/events/event-types.d.ts +0 -7
  114. package/dist/hooks/{cortex-md-injector.mjs → agents-md-injector.mjs} +117 -26
  115. package/dist/hooks/cortex-hook-api.mjs +2 -2
  116. package/dist/hooks/new-session-hook.mjs +2 -2
  117. package/dist/hooks/rules-loader.mjs +2 -2
  118. package/dist/hooks/status-md-guard.mjs +8 -8
  119. package/dist/hooks/task-status-check.mjs +18 -76
  120. package/dist/hooks/tasks-yaml-guard.mjs +2 -2
  121. package/dist/orchestration/agent-file-send.d.ts +9 -0
  122. package/dist/orchestration/agent-file-send.js +21 -2
  123. package/dist/orchestration/agent-runner.d.ts +3 -2
  124. package/dist/orchestration/agent-runner.js +17 -12
  125. package/dist/orchestration/attachments-store.d.ts +31 -0
  126. package/dist/orchestration/attachments-store.js +184 -0
  127. package/dist/orchestration/conversation-request.d.ts +4 -0
  128. package/dist/orchestration/conversation-request.js +13 -6
  129. package/dist/orchestration/interactions/plan-approvals.js +1 -1
  130. package/dist/orchestration/outputs-store.d.ts +11 -0
  131. package/dist/orchestration/outputs-store.js +32 -6
  132. package/dist/orchestration/routing/file-handler.d.ts +23 -2
  133. package/dist/orchestration/routing/file-handler.js +22 -5
  134. package/dist/orchestration/routing/webhook.js +193 -39
  135. package/dist/orchestration/session-gateway.d.ts +1 -1
  136. package/dist/orchestration/session-gateway.js +1 -0
  137. package/dist/orchestration/thread-executor.d.ts +2 -0
  138. package/dist/orchestration/thread-executor.js +11 -1
  139. package/dist/orchestration/thread-input.d.ts +3 -2
  140. package/dist/orchestration/thread-input.js +8 -9
  141. package/dist/orchestration/turn/turn-prep.d.ts +15 -1
  142. package/dist/orchestration/turn/turn-prep.js +19 -8
  143. package/dist/orchestration/waitpoint-ingress.d.ts +41 -0
  144. package/dist/orchestration/waitpoint-ingress.js +172 -0
  145. package/dist/orchestration/waitpoint-notifier.d.ts +21 -0
  146. package/dist/orchestration/waitpoint-notifier.js +119 -0
  147. package/dist/orchestration/waitpoint-remote-drain.d.ts +20 -0
  148. package/dist/orchestration/waitpoint-remote-drain.js +147 -0
  149. package/dist/orchestration/waitpoint-sweep.d.ts +42 -0
  150. package/dist/orchestration/waitpoint-sweep.js +87 -0
  151. package/dist/platform/adapters/feishu-image.d.ts +19 -0
  152. package/dist/platform/adapters/feishu-image.js +71 -0
  153. package/dist/platform/adapters/feishu.d.ts +2 -0
  154. package/dist/platform/adapters/feishu.js +26 -16
  155. package/dist/platform/ui-http/listening-ports.d.ts +1 -1
  156. package/dist/platform/ui-http/listening-ports.js +1 -1
  157. package/dist/platform/ui-http/ui-session.js +1 -1
  158. package/dist/store/conversation-ledger-repo.js +1 -1
  159. package/dist/store/execution-repo.d.ts +1 -19
  160. package/dist/store/execution-repo.js +1 -18
  161. package/dist/store/project-notes-repo.js +11 -2
  162. package/dist/store/prompt-migration-replacements.js +1 -1
  163. package/dist/store/session-registry-import.js +1 -1
  164. package/dist/store/session-registry-journal.js +1 -1
  165. package/dist/store/session-registry-repo.js +1 -1
  166. package/dist/store/version-migrations.d.ts +13 -3
  167. package/dist/store/version-migrations.js +254 -24
  168. package/dist/store/waitpoint-repo.d.ts +108 -0
  169. package/dist/store/waitpoint-repo.js +94 -0
  170. package/package.json +2 -2
  171. package/web/dist/assets/{index-CRDJo39X.css → index-CwwQNMpP.css} +1 -1
  172. package/web/dist/assets/index-DLSfgq3o.js +444 -0
  173. package/web/dist/assets/{index-CEZ0DSei.js → index-DZTuqUO4.js} +1 -1
  174. package/web/dist/index.html +2 -2
  175. package/defaults/config/hooks/08-cortex-md-injector-post-tool.json +0 -10
  176. package/dist/domain/executions/log-tailer.d.ts +0 -71
  177. package/dist/domain/executions/log-tailer.js +0 -194
  178. package/dist/domain/memory/cortex-md-injector.d.ts +0 -24
  179. package/dist/domain/memory/cortex-md-scanner.d.ts +0 -10
  180. package/dist/domain/memory/cortex-md-scanner.js +0 -66
  181. package/dist/domain/remote/cortex-client.d.ts +0 -1
  182. package/dist/domain/remote/cortex-client.js +0 -662
  183. package/dist/domain/tasks/system/cortex-run.d.ts +0 -25
  184. package/dist/domain/tasks/system/cortex-run.js +0 -360
  185. package/web/dist/assets/index-DjuPJVZE.js +0 -444
  186. /package/defaults/{CORTEX.md → AGENTS.md} +0 -0
  187. /package/defaults/config/{CORTEX.md → AGENTS.md} +0 -0
  188. /package/defaults/context/{CORTEX.md → AGENTS.md} +0 -0
  189. /package/defaults/context/ideas/{CORTEX.md → AGENTS.md} +0 -0
  190. /package/defaults/context/projects/{CORTEX.md → AGENTS.md} +0 -0
  191. /package/defaults/context/scans/{CORTEX.md → AGENTS.md} +0 -0
  192. /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
- }