@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.
- package/README.md +3 -2
- package/defaults/config/hooks/08-agents-md-injector-post-tool.json +10 -0
- package/defaults/config/hooks/{10-cortex-md-injector-session-start.json → 10-agents-md-injector-session-start.json} +3 -3
- package/defaults/config/hooks/{CORTEX.md → AGENTS.md} +2 -2
- package/defaults/hooks/{CORTEX.md → AGENTS.md} +1 -1
- package/defaults/hooks/{cortex-md-injector.mjs → agents-md-injector.mjs} +117 -26
- package/defaults/hooks/cortex-hook-api.mjs +2 -2
- package/defaults/hooks/new-session-hook.mjs +2 -2
- package/defaults/hooks/rules-loader.mjs +2 -2
- package/defaults/hooks/status-md-guard.mjs +8 -8
- package/defaults/hooks/task-status-check.mjs +18 -76
- package/defaults/hooks/tasks-yaml-guard.mjs +2 -2
- package/defaults/plugins/cortex-commission/.claude-plugin/plugin.json +2 -2
- package/defaults/plugins/cortex-commission/plugin.json +2 -2
- package/defaults/plugins/cortex-commission/skills/commission/SKILL.md +3 -3
- package/defaults/plugins/cortex-feishu/skills/feishu-doc/SKILL.md +1 -1
- package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +2 -2
- package/defaults/plugins/cortex-system/skills/project-init/SKILL.md +4 -4
- package/defaults/plugins/cortex-system/skills/task/SKILL.md +1 -1
- package/defaults/rules/{cortex-md.md → agents-md.md} +4 -4
- package/defaults/rules/decision-records.md +1 -1
- package/defaults/rules/meta-conventions.md +4 -4
- package/defaults/rules/mission-md.md +1 -1
- package/dist/agent-adapter/claude/adapter.d.ts +0 -6
- package/dist/agent-adapter/claude/adapter.js +0 -8
- package/dist/agent-adapter/claude/defaults.d.ts +10 -7
- package/dist/agent-adapter/claude/defaults.js +18 -16
- package/dist/agent-adapter/claude/hooks-builder.js +2 -2
- package/dist/agent-adapter/claude/spawn-args.d.ts +0 -3
- package/dist/agent-adapter/claude/spawn-args.js +20 -16
- package/dist/agent-adapter/claude/turn-machine.d.ts +11 -0
- package/dist/agent-adapter/claude/turn-machine.js +46 -5
- package/dist/agent-adapter/normalize/prompt-builder.d.ts +16 -1
- package/dist/agent-adapter/normalize/prompt-builder.js +24 -6
- package/dist/agent-adapter/pi/mcp-bridge-logic.d.ts +11 -2
- package/dist/agent-adapter/pi/mcp-bridge-logic.js +32 -1
- package/dist/agent-adapter/pi/mcp-bridge.js +16 -15
- package/dist/agent-adapter/pi/session-options.d.ts +0 -6
- package/dist/agent-adapter/pi/session-options.js +1 -8
- package/dist/agent-adapter/types.d.ts +1 -1
- package/dist/core/mcp-tool-gate.d.ts +3 -17
- package/dist/core/mcp-tool-gate.js +4 -19
- package/dist/core/media-types.d.ts +10 -0
- package/dist/core/media-types.js +34 -0
- package/dist/core/platform-settings-spec.js +1 -1
- package/dist/core/settings-spec.d.ts +22 -1
- package/dist/core/settings-spec.js +33 -2
- package/dist/core/types/agent-types.d.ts +3 -1
- package/dist/core/utils.d.ts +1 -1
- package/dist/core/utils.js +1 -1
- package/dist/domain/agents/config.d.ts +1 -1
- package/dist/domain/agents/config.js +1 -1
- package/dist/domain/agents/profile-switch.d.ts +1 -1
- package/dist/domain/agents/profile-switch.js +3 -5
- package/dist/domain/agents/subagent/runner.js +0 -1
- package/dist/domain/commissions/commission-draft.d.ts +58 -0
- package/dist/domain/commissions/commission-draft.js +87 -4
- package/dist/domain/commissions/commission-finalize.d.ts +8 -3
- package/dist/domain/commissions/commission-finalize.js +14 -0
- package/dist/domain/executions/registry.d.ts +1 -2
- package/dist/domain/executions/registry.js +0 -3
- package/dist/domain/mcp/bundled-server.js +4 -3
- package/dist/domain/mcp/feishu/file.js +37 -18
- package/dist/domain/mcp/feishu/types.d.ts +3 -0
- package/dist/domain/mcp/feishu-server.js +1 -1
- package/dist/domain/mcp/tools/{cortex-md.d.ts → agents-md.d.ts} +6 -6
- package/dist/domain/mcp/tools/{cortex-md.js → agents-md.js} +6 -6
- package/dist/domain/mcp/tools/commission-tools.d.ts +12 -1
- package/dist/domain/mcp/tools/commission-tools.js +68 -14
- package/dist/domain/mcp/tools/remote-file.d.ts +20 -0
- package/dist/domain/mcp/tools/remote-file.js +44 -0
- package/dist/domain/mcp/tools/slack.d.ts +2 -0
- package/dist/domain/mcp/tools/slack.js +22 -7
- package/dist/domain/mcp/tools/task-ops.js +5 -13
- package/dist/domain/mcp/tools/ui-file.js +23 -10
- package/dist/domain/mcp/tools/waitpoint.d.ts +3 -0
- package/dist/domain/mcp/tools/waitpoint.js +122 -0
- package/dist/domain/memory/agents-md-injector.d.ts +24 -0
- package/dist/domain/memory/{cortex-md-injector.js → agents-md-injector.js} +10 -7
- package/dist/domain/projects/project-store.d.ts +1 -1
- package/dist/domain/projects/project-store.js +3 -3
- package/dist/domain/remote/client-hot-reload.js +3 -1
- package/dist/domain/remote/client-manager.js +105 -126
- package/dist/domain/remote/client-ssh-tunnel.d.ts +16 -5
- package/dist/domain/remote/client-ssh-tunnel.js +12 -5
- package/dist/domain/remote/cortex-client-config.d.ts +1 -1
- package/dist/domain/remote/cortex-client-config.js +1 -1
- package/dist/domain/remote/device-file.d.ts +51 -0
- package/dist/domain/remote/device-file.js +193 -0
- package/dist/domain/remote/device-port.js +3 -0
- package/dist/domain/remote/reverse-stream.d.ts +18 -7
- package/dist/domain/remote/reverse-stream.js +19 -6
- package/dist/domain/runs/builders.js +0 -1
- package/dist/domain/runs/compact.js +0 -1
- package/dist/domain/runs/engine-spec.d.ts +11 -4
- package/dist/domain/runs/engine-spec.js +7 -4
- package/dist/domain/runs/prompt.js +16 -10
- package/dist/domain/runs/request.d.ts +0 -1
- package/dist/domain/sessions/session-hooks.d.ts +5 -12
- package/dist/domain/sessions/session-hooks.js +6 -13
- package/dist/domain/sessions/session-lifecycle.d.ts +4 -4
- package/dist/domain/sessions/session-lifecycle.js +5 -6
- package/dist/domain/sessions/session-retention.d.ts +1 -3
- package/dist/domain/sessions/session-retention.js +9 -26
- package/dist/domain/sessions/session-use.d.ts +32 -0
- package/dist/domain/sessions/session-use.js +63 -0
- package/dist/domain/sessions/session.js +6 -5
- package/dist/domain/system/server-update-check.js +29 -1
- package/dist/domain/system/update-ui-state.d.ts +32 -0
- package/dist/domain/system/update-ui-state.js +63 -0
- package/dist/domain/tasks/claim-recovery.js +2 -2
- package/dist/domain/tasks/dispatch-utils.d.ts +10 -1
- package/dist/domain/tasks/dispatch-utils.js +46 -1
- package/dist/domain/tasks/dispatcher.js +4 -5
- package/dist/domain/tasks/mutator.d.ts +2 -2
- package/dist/domain/tasks/mutator.js +2 -2
- package/dist/domain/tasks/system/task-cli.js +2 -2
- package/dist/domain/tasks/system/task-state.js +1 -1
- package/dist/domain/threads/runner.js +3 -2
- package/dist/domain/ui-service/app-router.d.ts +54 -3
- package/dist/domain/ui-service/app-router.js +12 -14
- package/dist/domain/ui-service/input-schemas.d.ts +49 -5
- package/dist/domain/ui-service/input-schemas.js +35 -9
- package/dist/domain/ui-service/mutate/platform-settings.js +1 -1
- package/dist/domain/ui-service/mutate/sessions.d.ts +17 -1
- package/dist/domain/ui-service/mutate/sessions.js +83 -3
- package/dist/domain/ui-service/mutate/system.d.ts +3 -1
- package/dist/domain/ui-service/mutate/system.js +13 -0
- package/dist/domain/ui-service/mutate/waitpoints.d.ts +2 -0
- package/dist/domain/ui-service/mutate/waitpoints.js +20 -0
- package/dist/domain/ui-service/platform-settings.js +1 -1
- package/dist/domain/ui-service/plugins-shared.js +1 -1
- package/dist/domain/ui-service/query/config.js +1 -1
- package/dist/domain/ui-service/query/executions.js +0 -2
- package/dist/domain/ui-service/query/machine-detail.js +3 -8
- package/dist/domain/ui-service/query/memory.js +1 -1
- package/dist/domain/ui-service/query/sessions.js +7 -0
- package/dist/domain/ui-service/query/system.d.ts +2 -1
- package/dist/domain/ui-service/query/system.js +4 -0
- package/dist/domain/ui-service/query/threads.js +1 -54
- package/dist/domain/ui-service/query/waitpoints.d.ts +30 -0
- package/dist/domain/ui-service/query/waitpoints.js +117 -0
- package/dist/domain/ui-service/query-input-schemas.d.ts +3 -0
- package/dist/domain/ui-service/query-input-schemas.js +3 -0
- package/dist/domain/ui-service/trpc.js +1 -1
- package/dist/domain/ui-service/types.d.ts +175 -50
- package/dist/domain/ui-service/types.js +1 -1
- package/dist/domain/ui-service/ui-service.js +13 -33
- package/dist/domain/waitpoints/notices.d.ts +21 -0
- package/dist/domain/waitpoints/notices.js +115 -0
- package/dist/domain/waitpoints/service.d.ts +91 -0
- package/dist/domain/waitpoints/service.js +243 -0
- package/dist/entry/app.js +39 -29
- package/dist/entry/auth-login-cli.js +1 -1
- package/dist/entry/auth-login-terminal.js +1 -1
- package/dist/entry/init-auth.js +1 -1
- package/dist/entry/init.js +6 -6
- package/dist/entry/signal-cli.d.ts +30 -0
- package/dist/entry/signal-cli.js +207 -0
- package/dist/entry/start-ui-http.d.ts +1 -1
- package/dist/entry/start-ui-http.js +5 -3
- package/dist/events/event-types.d.ts +5 -7
- package/dist/hooks/{cortex-md-injector.mjs → agents-md-injector.mjs} +117 -26
- package/dist/hooks/cortex-hook-api.mjs +2 -2
- package/dist/hooks/new-session-hook.mjs +2 -2
- package/dist/hooks/rules-loader.mjs +2 -2
- package/dist/hooks/status-md-guard.mjs +8 -8
- package/dist/hooks/task-status-check.mjs +18 -76
- package/dist/hooks/tasks-yaml-guard.mjs +2 -2
- package/dist/orchestration/agent-file-send.d.ts +9 -0
- package/dist/orchestration/agent-file-send.js +21 -2
- package/dist/orchestration/agent-runner.d.ts +4 -3
- package/dist/orchestration/agent-runner.js +25 -23
- package/dist/orchestration/attachments-store.d.ts +31 -0
- package/dist/orchestration/attachments-store.js +184 -0
- package/dist/orchestration/conversation-request.d.ts +30 -8
- package/dist/orchestration/conversation-request.js +62 -26
- package/dist/orchestration/edit-retry.js +2 -1
- package/dist/orchestration/interactions/ask-user-resume.js +2 -1
- package/dist/orchestration/interactions/plan-approvals.js +1 -1
- package/dist/orchestration/interactions/ui-update-prompt.d.ts +8 -0
- package/dist/orchestration/interactions/ui-update-prompt.js +47 -0
- package/dist/orchestration/outputs-store.d.ts +11 -0
- package/dist/orchestration/outputs-store.js +32 -6
- package/dist/orchestration/resume-dispatcher.js +2 -2
- package/dist/orchestration/routing/file-handler.d.ts +23 -2
- package/dist/orchestration/routing/file-handler.js +22 -5
- package/dist/orchestration/routing/webhook.js +240 -39
- package/dist/orchestration/session-compact.d.ts +3 -0
- package/dist/orchestration/session-compact.js +3 -2
- package/dist/orchestration/session-events.d.ts +6 -0
- package/dist/orchestration/session-events.js +5 -0
- package/dist/orchestration/session-gateway.d.ts +1 -1
- package/dist/orchestration/session-gateway.js +1 -0
- package/dist/orchestration/thread-executor.d.ts +2 -0
- package/dist/orchestration/thread-executor.js +11 -1
- package/dist/orchestration/thread-input.d.ts +3 -2
- package/dist/orchestration/thread-input.js +8 -9
- package/dist/orchestration/turn/turn-prep.d.ts +15 -1
- package/dist/orchestration/turn/turn-prep.js +21 -9
- package/dist/orchestration/waitpoint-ingress.d.ts +41 -0
- package/dist/orchestration/waitpoint-ingress.js +172 -0
- package/dist/orchestration/waitpoint-notifier.d.ts +21 -0
- package/dist/orchestration/waitpoint-notifier.js +119 -0
- package/dist/orchestration/waitpoint-remote-drain.d.ts +20 -0
- package/dist/orchestration/waitpoint-remote-drain.js +147 -0
- package/dist/orchestration/waitpoint-sweep.d.ts +42 -0
- package/dist/orchestration/waitpoint-sweep.js +87 -0
- package/dist/platform/adapters/feishu-image.d.ts +19 -0
- package/dist/platform/adapters/feishu-image.js +71 -0
- package/dist/platform/adapters/feishu.d.ts +2 -0
- package/dist/platform/adapters/feishu.js +26 -16
- package/dist/platform/ui-http/app-update.d.ts +11 -0
- package/dist/platform/ui-http/app-update.js +3 -0
- package/dist/platform/ui-http/listening-ports.d.ts +1 -1
- package/dist/platform/ui-http/listening-ports.js +1 -1
- package/dist/platform/ui-http/ui-session.js +1 -1
- package/dist/store/conversation-ledger-repo.d.ts +10 -19
- package/dist/store/conversation-ledger-repo.js +143 -152
- package/dist/store/execution-repo.d.ts +1 -19
- package/dist/store/execution-repo.js +1 -18
- package/dist/store/project-notes-repo.js +11 -2
- package/dist/store/prompt-migration-replacements.js +1 -1
- package/dist/store/session-registry-import.d.ts +34 -0
- package/dist/store/session-registry-import.js +182 -0
- package/dist/store/session-registry-journal.d.ts +107 -0
- package/dist/store/session-registry-journal.js +308 -19
- package/dist/store/session-registry-repo.d.ts +113 -28
- package/dist/store/session-registry-repo.js +288 -105
- package/dist/store/version-migrations.d.ts +29 -3
- package/dist/store/version-migrations.js +288 -24
- package/dist/store/waitpoint-repo.d.ts +108 -0
- package/dist/store/waitpoint-repo.js +94 -0
- package/package.json +2 -2
- package/web/dist/assets/index-CwwQNMpP.css +1 -0
- package/web/dist/assets/index-DLSfgq3o.js +444 -0
- package/web/dist/assets/{index-aHbOZSP6.js → index-DZTuqUO4.js} +1 -1
- package/web/dist/index.html +2 -2
- package/defaults/config/hooks/08-cortex-md-injector-post-tool.json +0 -10
- package/dist/domain/executions/log-tailer.d.ts +0 -71
- package/dist/domain/executions/log-tailer.js +0 -194
- package/dist/domain/memory/cortex-md-injector.d.ts +0 -24
- package/dist/domain/memory/cortex-md-scanner.d.ts +0 -10
- package/dist/domain/memory/cortex-md-scanner.js +0 -66
- package/dist/domain/remote/cortex-client.d.ts +0 -1
- package/dist/domain/remote/cortex-client.js +0 -662
- package/dist/domain/tasks/system/cortex-run.d.ts +0 -25
- package/dist/domain/tasks/system/cortex-run.js +0 -360
- package/dist/store/session-repo.d.ts +0 -65
- package/dist/store/session-repo.js +0 -184
- package/web/dist/assets/index-BuXbCsuz.js +0 -444
- package/web/dist/assets/index-CCPxQ94C.css +0 -1
- /package/defaults/{CORTEX.md → AGENTS.md} +0 -0
- /package/defaults/config/{CORTEX.md → AGENTS.md} +0 -0
- /package/defaults/context/{CORTEX.md → AGENTS.md} +0 -0
- /package/defaults/context/ideas/{CORTEX.md → AGENTS.md} +0 -0
- /package/defaults/context/projects/{CORTEX.md → AGENTS.md} +0 -0
- /package/defaults/context/scans/{CORTEX.md → AGENTS.md} +0 -0
- /package/defaults/context/user/{CORTEX.md → AGENTS.md} +0 -0
|
@@ -5,7 +5,8 @@ import * as crypto from 'crypto';
|
|
|
5
5
|
import { pathToFileURL } from 'url';
|
|
6
6
|
import { WORKSPACE_DIR } from '../../../core/utils.js';
|
|
7
7
|
import { requestLoopbackJson } from '../../../core/loopback-http.js';
|
|
8
|
-
import {
|
|
8
|
+
import { agentsMDContentBlocks } from './agents-md.js';
|
|
9
|
+
import { isAbsoluteFilePath } from './remote-file.js';
|
|
9
10
|
import { webhookAuthHeaders } from './context.js';
|
|
10
11
|
// Remote device commands are proxied through the daemon webhook: client-manager lives in the
|
|
11
12
|
// daemon and a tool must not reach into it directly.
|
|
@@ -15,15 +16,6 @@ async function proxySendCommand(ctx, device, action, params, timeout) {
|
|
|
15
16
|
throw new Error(body.error || 'Command failed');
|
|
16
17
|
return body.data;
|
|
17
18
|
}
|
|
18
|
-
/** Cross-platform absolute-path check (server runs on Linux but validates paths for Windows clients). */
|
|
19
|
-
function isAbsoluteFilePath(p) {
|
|
20
|
-
if (path.isAbsolute(p))
|
|
21
|
-
return true;
|
|
22
|
-
// Windows absolute: D:\, D:/, etc.
|
|
23
|
-
if (/^[A-Za-z]:[/\\]/.test(p))
|
|
24
|
-
return true;
|
|
25
|
-
return false;
|
|
26
|
-
}
|
|
27
19
|
// --- Tool result persistence ---
|
|
28
20
|
// When tool output exceeds a character threshold, save full output to a local
|
|
29
21
|
// file and return a pointer + preview. Prevents context window explosion while
|
|
@@ -191,7 +183,7 @@ export function registerTaskOpsTools(server, ctx) {
|
|
|
191
183
|
return { content: [{ type: 'text', text: 'file_path must be absolute' }], isError: true };
|
|
192
184
|
}
|
|
193
185
|
const result = await proxySendCommand(ctx, device, 'read', { file_path, offset, limit });
|
|
194
|
-
const cmdBlocks =
|
|
186
|
+
const cmdBlocks = agentsMDContentBlocks(device, result.cortexMDs, file_path);
|
|
195
187
|
// Image response path
|
|
196
188
|
if (result.image) {
|
|
197
189
|
const { data, mimeType, width, height, originalSize } = result.image;
|
|
@@ -264,7 +256,7 @@ export function registerTaskOpsTools(server, ctx) {
|
|
|
264
256
|
return { content: [{ type: 'text', text: 'file_path must be absolute' }], isError: true };
|
|
265
257
|
}
|
|
266
258
|
const result = await proxySendCommand(ctx, device, 'write', { file_path, content });
|
|
267
|
-
const cmdBlocks =
|
|
259
|
+
const cmdBlocks = agentsMDContentBlocks(device, result?.cortexMDs, file_path);
|
|
268
260
|
return {
|
|
269
261
|
content: [{ type: 'text', text: `File written: ${file_path}` }, ...cmdBlocks],
|
|
270
262
|
};
|
|
@@ -286,7 +278,7 @@ export function registerTaskOpsTools(server, ctx) {
|
|
|
286
278
|
return { content: [{ type: 'text', text: 'file_path must be absolute' }], isError: true };
|
|
287
279
|
}
|
|
288
280
|
const result = await proxySendCommand(ctx, device, 'edit', { file_path, old_string, new_string, replace_all: replace_all || false });
|
|
289
|
-
const cmdBlocks =
|
|
281
|
+
const cmdBlocks = agentsMDContentBlocks(device, result?.cortexMDs, file_path);
|
|
290
282
|
return {
|
|
291
283
|
content: [{ type: 'text', text: `File edited: ${file_path}` }, ...cmdBlocks],
|
|
292
284
|
};
|
|
@@ -2,27 +2,40 @@ import { z } from 'zod';
|
|
|
2
2
|
import * as fs from 'fs';
|
|
3
3
|
import * as path from 'path';
|
|
4
4
|
import { requestLoopbackJson } from '../../../core/loopback-http.js';
|
|
5
|
+
import { isAbsoluteFilePath } from './remote-file.js';
|
|
5
6
|
import { webhookAuthHeaders, webSessionId } from './context.js';
|
|
6
7
|
export function registerUiFileTools(server, ctx) {
|
|
7
|
-
server.tool('send_file', 'Send a file to the user in this chat. Use this whenever you want to share a file you produced — a report, plot, image, dataset, log, PDF, etc. The file appears as a downloadable card in the conversation (images preview inline). Pass a local path to a file you have written or that exists on disk.', {
|
|
8
|
-
file_path: z.string().describe('
|
|
8
|
+
server.tool('send_file', 'Send a file to the user in this chat. Use this whenever you want to share a file you produced — a report, plot, image, dataset, log, PDF, etc. The file appears as a downloadable card in the conversation (images preview inline). Pass a local path to a file you have written or that exists on disk, or set `device` to send a file that lives on a remote device instead.', {
|
|
9
|
+
file_path: z.string().describe('Path to the file to send. Local path (absolute, or relative to the working directory); with `device`, an absolute path on that device.'),
|
|
9
10
|
file_name: z.string().optional().describe('Optional filename override shown to the user.'),
|
|
10
11
|
caption: z.string().optional().describe('Optional short message shown alongside the file.'),
|
|
11
|
-
|
|
12
|
+
device: z.string().optional().describe('Name of a connected remote device (as used by remote_bash). The file is read there and streamed back. Omit for files on this server.'),
|
|
13
|
+
}, async ({ file_path, file_name, caption, device }) => {
|
|
12
14
|
try {
|
|
13
15
|
const sessionId = webSessionId(ctx);
|
|
14
16
|
if (!sessionId)
|
|
15
17
|
throw new Error('No web session in context — send_file is only usable inside a Web UI chat session');
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
if (
|
|
20
|
-
|
|
21
|
-
|
|
18
|
+
// With `device` the path belongs to another machine: it cannot be resolved or stat'ed here,
|
|
19
|
+
// and a relative path would be meaningless there. The daemon validates it on the device.
|
|
20
|
+
let resolved;
|
|
21
|
+
if (device) {
|
|
22
|
+
if (!isAbsoluteFilePath(file_path))
|
|
23
|
+
throw new Error('file_path must be absolute when `device` is set');
|
|
24
|
+
resolved = file_path;
|
|
25
|
+
}
|
|
26
|
+
else {
|
|
27
|
+
resolved = path.isAbsolute(file_path) ? file_path : path.resolve(process.cwd(), file_path);
|
|
28
|
+
if (!fs.existsSync(resolved))
|
|
29
|
+
throw new Error(`File not found: ${resolved}`);
|
|
30
|
+
if (!fs.statSync(resolved).isFile())
|
|
31
|
+
throw new Error(`Not a file: ${resolved}`);
|
|
32
|
+
}
|
|
33
|
+
const { body } = await requestLoopbackJson('POST', `${ctx.webhookBaseUrl}/webhook/ui-file`, { sessionId, filePath: resolved, fileName: file_name, caption, device }, webhookAuthHeaders(ctx));
|
|
22
34
|
if (!body.success)
|
|
23
35
|
throw new Error(body.error || 'send_file failed');
|
|
24
36
|
const meta = body.data;
|
|
25
|
-
|
|
37
|
+
const from = device ? ` from ${device}` : '';
|
|
38
|
+
return { content: [{ type: 'text', text: `Sent file to the user${from}: ${meta.name} (${meta.size} bytes)` }] };
|
|
26
39
|
}
|
|
27
40
|
catch (e) {
|
|
28
41
|
return { content: [{ type: 'text', text: `Failed to send file: ${e.message}` }], isError: true };
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { requestLoopbackJson } from '../../../core/loopback-http.js';
|
|
3
|
+
import { webhookAuthHeaders } from './context.js';
|
|
4
|
+
async function proxy(ctx, action, payload) {
|
|
5
|
+
const { body } = await requestLoopbackJson('POST', `${ctx.webhookBaseUrl}/webhook/waitpoint`, { action, sessionId: ctx.sessionId, channel: ctx.channel, threadId: ctx.threadId, project: ctx.taskProject || ctx.project, ...payload }, webhookAuthHeaders(ctx));
|
|
6
|
+
if (!body.success)
|
|
7
|
+
throw new Error(body.error || `waitpoint ${action} failed`);
|
|
8
|
+
return body.data;
|
|
9
|
+
}
|
|
10
|
+
function ok(payload) {
|
|
11
|
+
return { content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }] };
|
|
12
|
+
}
|
|
13
|
+
function fail(message) {
|
|
14
|
+
return { content: [{ type: 'text', text: message }], isError: true };
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* The three forms a signal can take, filled in with a real id and secret.
|
|
18
|
+
*
|
|
19
|
+
* `shell` is the one that matters for a remote machine: it needs no Cortex binary and no route
|
|
20
|
+
* back to the daemon — it drops a file the daemon comes and collects.
|
|
21
|
+
*/
|
|
22
|
+
function buildRecipe(id, secret, port, device) {
|
|
23
|
+
const env = `export CORTEX_SIGNAL_ID=${id} CORTEX_SIGNAL_SECRET=${secret}`;
|
|
24
|
+
const cli = `cortex-signal --exit-code $?`;
|
|
25
|
+
const curl = `curl -sS -XPOST http://127.0.0.1:${port}/webhook/signal `
|
|
26
|
+
+ `-H 'content-type: application/json' `
|
|
27
|
+
+ `-d '{"id":"${id}","secret":"${secret}","status":"ok","message":"done"}'`;
|
|
28
|
+
// Write-then-rename: a same-directory rename is atomic, so the drain never reads a half file.
|
|
29
|
+
const shell = [
|
|
30
|
+
`s=$?; d=~/.cortex/tmp/signals; mkdir -p "$d"`,
|
|
31
|
+
`printf '{"id":"${id}","secret":"${secret}","status":"%s","message":"exit=%s"}' `
|
|
32
|
+
+ `"$([ $s -eq 0 ] && echo ok || echo fail)" "$s" > "$d/$$.tmp" && mv "$d/$$.tmp" "$d/$$.json"`,
|
|
33
|
+
].join('\n');
|
|
34
|
+
// On a device the daemon cannot be reached over HTTP at all, so the file drop is the only
|
|
35
|
+
// form that works there; on this machine the CLI is shorter and reports failures immediately.
|
|
36
|
+
const attachToPid = `(while kill -0 <PID> 2>/dev/null; do sleep 5; done; `
|
|
37
|
+
+ `cortex-signal --status ok --message "pid <PID> exited") &`;
|
|
38
|
+
return { recommended: device ? 'shell' : 'cli', env, cli, curl, shell, attach_to_pid: attachToPid };
|
|
39
|
+
}
|
|
40
|
+
export function registerWaitpointTools(server, ctx) {
|
|
41
|
+
server.tool('wait_create', [
|
|
42
|
+
'Arm a waitpoint: a durable wake that anything outside Cortex can address. You get back an id,',
|
|
43
|
+
'a one-time secret and ready-to-paste lines; anything able to run one of them wakes this session',
|
|
44
|
+
'later, carrying a result.',
|
|
45
|
+
'',
|
|
46
|
+
'Shapes it takes:',
|
|
47
|
+
' a job that just finished python train.py; cortex-signal --exit-code $?',
|
|
48
|
+
' a job already running the reply\'s attach_to_pid line watches its pid',
|
|
49
|
+
' an alarm clock (sleep 3600; cortex-signal --message "an hour is up") &',
|
|
50
|
+
' a monitor max_signals > 1 — every report wakes you, until you cancel it',
|
|
51
|
+
' several jobs at once members + quorum — woken once, when the set is done',
|
|
52
|
+
'',
|
|
53
|
+
'Mechanism: Cortex launches nothing and watches nothing, so that callback exists only because',
|
|
54
|
+
'you put it somewhere. Arm the waitpoint before starting the job, so its line goes into the same',
|
|
55
|
+
'command; a waitpoint nobody signals just expires days later, having told you nothing.',
|
|
56
|
+
'',
|
|
57
|
+
'Then END YOUR TURN. Idle waiting is free and you never poll — when the signal lands this session',
|
|
58
|
+
'is woken with the result and the intent you recorded here.',
|
|
59
|
+
].join('\n'), {
|
|
60
|
+
label: z.string().describe('Short human name, e.g. "arm2 training". Appears in the wake message.'),
|
|
61
|
+
intent: z.string().describe('What you are waiting for and what you will do when woken, in your own words. You will read '
|
|
62
|
+
+ 'this hours later in a fresh turn with none of the current context, so write it for a stranger.'),
|
|
63
|
+
members: z.array(z.string()).optional().describe('Names of the jobs you expect to report, e.g. ["arm2","arm6","arm8"]. Each one signals with its own name.'),
|
|
64
|
+
quorum: z.union([z.number(), z.literal('all')]).optional().describe('How many terminal signals resolve this waitpoint. Defaults to "all" when members are given, else 1.'),
|
|
65
|
+
fail_fast: z.boolean().optional().describe('Wake on the first failure even if the quorum is unmet. Default true.'),
|
|
66
|
+
max_signals: z.number().optional().describe('How many times it may wake you before closing. Default 1: one job, one wake. Set it above 1 '
|
|
67
|
+
+ 'to keep the waitpoint open as a mailbox, so a job reporting every 30 minutes wakes you every '
|
|
68
|
+
+ 'time; cancel it yourself once you have what you need. A sender that should be recorded '
|
|
69
|
+
+ 'WITHOUT waking you uses `cortex-signal --status progress` instead.'),
|
|
70
|
+
expires_in_hours: z.number().optional().describe('Deadline. If nothing signals by then you are told so instead of waiting forever. Default 168h (7d), max 720h.'),
|
|
71
|
+
device: z.string().optional().describe('Name of the connected device the job runs on. Set this when the job is NOT on this machine: '
|
|
72
|
+
+ 'the daemon then collects signals from that device instead of expecting an HTTP call it cannot make.'),
|
|
73
|
+
}, async (args) => {
|
|
74
|
+
try {
|
|
75
|
+
const data = await proxy(ctx, 'create', {
|
|
76
|
+
label: args.label,
|
|
77
|
+
intent: args.intent,
|
|
78
|
+
quorum: { need: args.quorum, members: args.members },
|
|
79
|
+
failFast: args.fail_fast,
|
|
80
|
+
maxSignals: args.max_signals,
|
|
81
|
+
ttlMs: typeof args.expires_in_hours === 'number' ? args.expires_in_hours * 3600_000 : undefined,
|
|
82
|
+
device: args.device,
|
|
83
|
+
});
|
|
84
|
+
const port = Number(new URL(ctx.webhookBaseUrl).port || 3001);
|
|
85
|
+
const recipe = buildRecipe(data.id, data.secret, port, args.device ?? null);
|
|
86
|
+
return ok({
|
|
87
|
+
...data,
|
|
88
|
+
how_to_signal: recipe,
|
|
89
|
+
next: 'Nothing will signal this waitpoint unless you put one of the how_to_signal lines '
|
|
90
|
+
+ 'where the job runs it (start the job with it, or attach_to_pid if it is already '
|
|
91
|
+
+ 'running). Do that first, then end your turn — you will be woken.',
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
catch (e) {
|
|
95
|
+
return fail(`wait_create failed: ${e.message}`);
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
server.tool('wait_check', 'Inspect a waitpoint you armed: its state, which members have reported, and what they said. '
|
|
99
|
+
+ 'Pass an id, or omit it to list every waitpoint this session owns. Read-only — you do not need '
|
|
100
|
+
+ 'to poll this to be woken.', {
|
|
101
|
+
id: z.string().optional().describe('Waitpoint id (wp_…). Omit to list all of this session\'s waitpoints.'),
|
|
102
|
+
}, { readOnlyHint: true }, async (args) => {
|
|
103
|
+
try {
|
|
104
|
+
return ok(await proxy(ctx, 'check', { id: args.id }));
|
|
105
|
+
}
|
|
106
|
+
catch (e) {
|
|
107
|
+
return fail(`wait_check failed: ${e.message}`);
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
server.tool('wait_cancel', 'Disarm a waitpoint you no longer care about. Its secret stops working and you will not be woken. '
|
|
111
|
+
+ 'Use this when you gave up on the job or finished the work another way — an abandoned waitpoint '
|
|
112
|
+
+ 'otherwise wakes you days later about something nobody remembers.', {
|
|
113
|
+
id: z.string().describe('Waitpoint id (wp_…) to cancel.'),
|
|
114
|
+
}, async (args) => {
|
|
115
|
+
try {
|
|
116
|
+
return ok(await proxy(ctx, 'cancel', { id: args.id }));
|
|
117
|
+
}
|
|
118
|
+
catch (e) {
|
|
119
|
+
return fail(`wait_cancel failed: ${e.message}`);
|
|
120
|
+
}
|
|
121
|
+
});
|
|
122
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export interface AgentsMDEntry {
|
|
2
|
+
path: string;
|
|
3
|
+
content: string;
|
|
4
|
+
mtimeMs: number;
|
|
5
|
+
deviceId?: string;
|
|
6
|
+
}
|
|
7
|
+
export interface AgentsMDBlock {
|
|
8
|
+
type: 'text';
|
|
9
|
+
text: string;
|
|
10
|
+
}
|
|
11
|
+
export interface AgentsMDInjectorOptions {
|
|
12
|
+
sessionId?: string;
|
|
13
|
+
cacheDir?: string;
|
|
14
|
+
cacheFile?: string | null;
|
|
15
|
+
}
|
|
16
|
+
export declare class AgentsMDInjector {
|
|
17
|
+
private readonly memoryCache;
|
|
18
|
+
private readonly cacheFile;
|
|
19
|
+
constructor(options?: AgentsMDInjectorOptions);
|
|
20
|
+
private transact;
|
|
21
|
+
buildBlocks(device: string, entries: AgentsMDEntry[], markOnlyPaths?: Set<string>): AgentsMDBlock[];
|
|
22
|
+
private formatBlock;
|
|
23
|
+
}
|
|
24
|
+
export declare function getDefaultAgentsInjector(): AgentsMDInjector;
|
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import * as fs from 'fs';
|
|
2
2
|
import * as path from 'path';
|
|
3
3
|
import { WORKSPACE_DIR } from '../../core/utils.js';
|
|
4
|
+
// Directory name predates the AGENTS.md rename and is deliberately unchanged: it is shared
|
|
5
|
+
// with the local agents-md-injector hook, and renaming it would orphan every live session's
|
|
6
|
+
// dedup state at once, re-injecting every rule file already in context.
|
|
4
7
|
const DEFAULT_CACHE_DIR = path.join(WORKSPACE_DIR, 'cortexmd-cache');
|
|
5
8
|
const CACHE_TTL_MS = 7 * 24 * 60 * 60 * 1000;
|
|
6
9
|
const LOCK_WAIT_MS = 250;
|
|
@@ -91,7 +94,7 @@ function cacheKey(device, entry) {
|
|
|
91
94
|
const physicalDevice = entry.deviceId?.trim() || device;
|
|
92
95
|
return `${physicalDevice.toLowerCase()}:${entry.path}`;
|
|
93
96
|
}
|
|
94
|
-
export class
|
|
97
|
+
export class AgentsMDInjector {
|
|
95
98
|
memoryCache = new Map();
|
|
96
99
|
cacheFile;
|
|
97
100
|
constructor(options = {}) {
|
|
@@ -140,16 +143,16 @@ export class CortexMDInjector {
|
|
|
140
143
|
}
|
|
141
144
|
formatBlock(device, entry) {
|
|
142
145
|
return `<system-reminder>\n` +
|
|
143
|
-
`Auto-loaded
|
|
146
|
+
`Auto-loaded AGENTS.md from ${device}:${entry.path} ` +
|
|
144
147
|
`(ancestor of accessed path on remote device). ` +
|
|
145
148
|
`These instructions apply to files under this directory on that device.\n\n` +
|
|
146
149
|
entry.content +
|
|
147
150
|
`\n</system-reminder>`;
|
|
148
151
|
}
|
|
149
152
|
}
|
|
150
|
-
let
|
|
151
|
-
export function
|
|
152
|
-
if (!
|
|
153
|
-
|
|
154
|
-
return
|
|
153
|
+
let defaultAgentsInjector = null;
|
|
154
|
+
export function getDefaultAgentsInjector() {
|
|
155
|
+
if (!defaultAgentsInjector)
|
|
156
|
+
defaultAgentsInjector = new AgentsMDInjector();
|
|
157
|
+
return defaultAgentsInjector;
|
|
155
158
|
}
|
|
@@ -51,7 +51,7 @@ export declare class ProjectStore {
|
|
|
51
51
|
refresh(): void;
|
|
52
52
|
/**
|
|
53
53
|
* Create a new user project directory under PROJECTS_DIR with a standard scaffold
|
|
54
|
-
* (STATUS.md +
|
|
54
|
+
* (STATUS.md + AGENTS.md + TASKS.yaml). Validates the name (rejects path traversal, separators,
|
|
55
55
|
* empty/whitespace, leading-dot, and the reserved 'general'). Never overwrites an
|
|
56
56
|
* existing project directory — returns an `already-exists` error instead.
|
|
57
57
|
*/
|
|
@@ -115,7 +115,7 @@ export class ProjectStore {
|
|
|
115
115
|
}
|
|
116
116
|
/**
|
|
117
117
|
* Create a new user project directory under PROJECTS_DIR with a standard scaffold
|
|
118
|
-
* (STATUS.md +
|
|
118
|
+
* (STATUS.md + AGENTS.md + TASKS.yaml). Validates the name (rejects path traversal, separators,
|
|
119
119
|
* empty/whitespace, leading-dot, and the reserved 'general'). Never overwrites an
|
|
120
120
|
* existing project directory — returns an `already-exists` error instead.
|
|
121
121
|
*/
|
|
@@ -165,10 +165,10 @@ export class ProjectStore {
|
|
|
165
165
|
this.ensureTasksFile(generalDir);
|
|
166
166
|
}
|
|
167
167
|
/** Create a project directory and write the standard scaffold files. */
|
|
168
|
-
scaffoldProject(dir, statusContent,
|
|
168
|
+
scaffoldProject(dir, statusContent, indexContent) {
|
|
169
169
|
fs.mkdirSync(dir, { recursive: true });
|
|
170
170
|
fs.writeFileSync(path.join(dir, 'STATUS.md'), statusContent, 'utf8');
|
|
171
|
-
fs.writeFileSync(path.join(dir, '
|
|
171
|
+
fs.writeFileSync(path.join(dir, 'AGENTS.md'), indexContent, 'utf8');
|
|
172
172
|
this.ensureTasksFile(dir);
|
|
173
173
|
}
|
|
174
174
|
ensureTasksFile(dir) {
|
|
@@ -8,7 +8,9 @@ import { STORE_DIR } from '../../core/utils.js';
|
|
|
8
8
|
import { createLogger } from '../../core/log.js';
|
|
9
9
|
import { Icons } from '../../core/icons.js';
|
|
10
10
|
const log = createLogger('client-hot-reload');
|
|
11
|
-
/** The complete update artifact, hashed in this exact order on both ends.
|
|
11
|
+
/** The complete update artifact, hashed in this exact order on both ends.
|
|
12
|
+
* `cortex-run-watcher.mjs` is a compatibility stub (cortex-run was removed) — see the note on
|
|
13
|
+
* BUNDLE_FILES in client/src/self-update.ts. Both ends drop it in the same release or not at all. */
|
|
12
14
|
const BUNDLE_FILES = ['client.mjs', 'cortex-run-watcher.mjs'];
|
|
13
15
|
/** After a failed install, do not re-push the same bundle to that device for this long. */
|
|
14
16
|
const PUSH_RETRY_COOLDOWN_MS = 10 * 60_000;
|
|
@@ -3,15 +3,12 @@ import * as crypto from 'crypto';
|
|
|
3
3
|
import * as fs from 'fs';
|
|
4
4
|
import * as path from 'path';
|
|
5
5
|
import { execFile, spawn } from 'child_process';
|
|
6
|
-
import { getMachineRegistry } from '../tasks/dispatch-utils.js';
|
|
6
|
+
import { getMachineRegistry, applyReportedGpuCount } from '../tasks/dispatch-utils.js';
|
|
7
7
|
import { STORE_DIR, DATA_DIR } from '../../core/utils.js';
|
|
8
8
|
import { AUTH_HEADER, getClientToken, timingSafeEqualStr } from '../../core/auth.js';
|
|
9
9
|
import { createLogger } from '../../core/log.js';
|
|
10
10
|
import { claimStream, parseStreamId, cancelStreamsFor } from './reverse-stream.js';
|
|
11
11
|
import { emitCortexEvent } from '../../core/hook-bus.js';
|
|
12
|
-
import { readTasks, findTask } from '../tasks/system/task-lifecycle-edit.js';
|
|
13
|
-
import { taskMutator } from '../tasks/mutator.js';
|
|
14
|
-
import { setExecutionGpuByTaskId } from '../executions/registry.js';
|
|
15
12
|
import { SshTunnelSupervisor } from './client-ssh-tunnel.js';
|
|
16
13
|
const log = createLogger('client-manager');
|
|
17
14
|
let updateHooks = null;
|
|
@@ -31,6 +28,43 @@ function emitDisconnected(device, reason) {
|
|
|
31
28
|
const payload = reason ? { device, reason } : { device };
|
|
32
29
|
void emitCortexEvent('cortex:client.disconnected', payload).catch(() => { });
|
|
33
30
|
}
|
|
31
|
+
/**
|
|
32
|
+
* Take a device online from its hello frame. Returns the device name, or null when the frame was
|
|
33
|
+
* rejected (no name / a live connection already holds that name) — the socket is closed in that case.
|
|
34
|
+
*
|
|
35
|
+
* The frame also carries the machine's own GPU count, which is reconciled into machines.json here:
|
|
36
|
+
* a client knows its hardware, the registry only holds what someone typed. An absent or
|
|
37
|
+
* unparseable `gpuCount` is "unknown" and leaves the configured value alone.
|
|
38
|
+
*/
|
|
39
|
+
function registerHelloDevice(ws, msg) {
|
|
40
|
+
const device = msg.device;
|
|
41
|
+
if (!device) {
|
|
42
|
+
ws.close(4001, 'Missing device name');
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
const existing = devices.get(device);
|
|
46
|
+
if (existing && existing.ws !== ws) {
|
|
47
|
+
log.info(`Device ${device} already connected, rejecting new connection`);
|
|
48
|
+
ws.close(4002, 'Device already connected');
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
const bundleHash = typeof msg.bundleHash === 'string' && msg.bundleHash ? msg.bundleHash : null;
|
|
52
|
+
const platform = msg.platform || 'unknown';
|
|
53
|
+
devices.set(device, {
|
|
54
|
+
device, platform, capabilities: msg.capabilities || [],
|
|
55
|
+
connectedAt: new Date(), lastHeartbeat: new Date(), bundleHash, ws,
|
|
56
|
+
});
|
|
57
|
+
log.info(`Device connected: ${device} (${platform})`);
|
|
58
|
+
void emitCortexEvent('cortex:client.connected', { device }).catch(() => { });
|
|
59
|
+
applyReportedGpuCount(device, typeof msg.gpuCount === 'number' ? msg.gpuCount : null);
|
|
60
|
+
try {
|
|
61
|
+
updateHooks?.onHello(device, bundleHash);
|
|
62
|
+
}
|
|
63
|
+
catch (e) {
|
|
64
|
+
log.warn(`onHello hook failed for ${device}: ${e.message}`);
|
|
65
|
+
}
|
|
66
|
+
return device;
|
|
67
|
+
}
|
|
34
68
|
// --- Server lifecycle ---
|
|
35
69
|
function startClientManager(port) {
|
|
36
70
|
if (wss) {
|
|
@@ -80,36 +114,7 @@ function startClientManager(port) {
|
|
|
80
114
|
return;
|
|
81
115
|
}
|
|
82
116
|
if (msg.type === 'hello') {
|
|
83
|
-
deviceName = msg
|
|
84
|
-
if (!deviceName) {
|
|
85
|
-
ws.close(4001, 'Missing device name');
|
|
86
|
-
return;
|
|
87
|
-
}
|
|
88
|
-
// If a device with the same name is already connected, reject the new connection
|
|
89
|
-
const existing = devices.get(deviceName);
|
|
90
|
-
if (existing && existing.ws !== ws) {
|
|
91
|
-
log.info(`Device ${deviceName} already connected, rejecting new connection`);
|
|
92
|
-
ws.close(4002, 'Device already connected');
|
|
93
|
-
return;
|
|
94
|
-
}
|
|
95
|
-
const bundleHash = typeof msg.bundleHash === 'string' && msg.bundleHash ? msg.bundleHash : null;
|
|
96
|
-
devices.set(deviceName, {
|
|
97
|
-
device: deviceName,
|
|
98
|
-
platform: msg.platform || 'unknown',
|
|
99
|
-
capabilities: msg.capabilities || [],
|
|
100
|
-
connectedAt: new Date(),
|
|
101
|
-
lastHeartbeat: new Date(),
|
|
102
|
-
bundleHash,
|
|
103
|
-
ws,
|
|
104
|
-
});
|
|
105
|
-
log.info(`Device connected: ${deviceName} (${msg.platform || 'unknown'})`);
|
|
106
|
-
void emitCortexEvent('cortex:client.connected', { device: deviceName }).catch(() => { });
|
|
107
|
-
try {
|
|
108
|
-
updateHooks?.onHello(deviceName, bundleHash);
|
|
109
|
-
}
|
|
110
|
-
catch (e) {
|
|
111
|
-
log.warn(`onHello hook failed for ${deviceName}: ${e.message}`);
|
|
112
|
-
}
|
|
117
|
+
deviceName = registerHelloDevice(ws, msg);
|
|
113
118
|
return;
|
|
114
119
|
}
|
|
115
120
|
if (msg.type === 'update-result' && deviceName) {
|
|
@@ -146,10 +151,6 @@ function startClientManager(port) {
|
|
|
146
151
|
}
|
|
147
152
|
return;
|
|
148
153
|
}
|
|
149
|
-
if (msg.type === 'task-callback') {
|
|
150
|
-
void handleTaskCallback(ws, msg).catch((e) => log.error(`task-callback: ${e.message}`));
|
|
151
|
-
return;
|
|
152
|
-
}
|
|
153
154
|
});
|
|
154
155
|
ws.on('close', (_code, reason) => {
|
|
155
156
|
if (deviceName) {
|
|
@@ -426,14 +427,68 @@ function managedServerUrl(reg) {
|
|
|
426
427
|
return `ws://127.0.0.1:${reg.clientReversePort ?? clientManagerPort}`;
|
|
427
428
|
}
|
|
428
429
|
/**
|
|
429
|
-
* Kill
|
|
430
|
-
* neither tears the forward listener down with the session nor refuses a duplicate bind,
|
|
431
|
-
* dead tunnel can keep answering the cortex-client while a healthy one sits next to it
|
|
430
|
+
* Kill the sshd sessions still listening on the tunnel's loopback port on a Windows host. Windows
|
|
431
|
+
* OpenSSH neither tears the forward listener down with the session nor refuses a duplicate bind,
|
|
432
|
+
* so a dead tunnel can keep answering the cortex-client while a healthy one sits next to it
|
|
433
|
+
* unused — and several can pile up on one port.
|
|
434
|
+
*
|
|
435
|
+
* It loops because `Get-NetTCPConnection` reports a single row per endpoint no matter how many
|
|
436
|
+
* sockets are bound to it: with two listeners on the port, `netstat -ano` and .NET's
|
|
437
|
+
* `GetActiveTcpListeners()` both show two and the cmdlet shows one — the oldest. One pass would
|
|
438
|
+
* evict one listener and leave the rest, so it repeats until no sshd holds the port.
|
|
439
|
+
*
|
|
440
|
+
* The owner is checked by name because the kill is otherwise indiscriminate: whatever happens to
|
|
441
|
+
* be listening on the port gets force-stopped, which is a stray kill waiting to happen if anything
|
|
442
|
+
* else ever binds it. This is the same guard the POSIX command applies through `comm`.
|
|
432
443
|
*/
|
|
433
444
|
function windowsFreePortCommand(port) {
|
|
434
|
-
return 'powershell -NoProfile -Command "
|
|
435
|
-
+ `${port} -ErrorAction SilentlyContinue | `
|
|
436
|
-
+
|
|
445
|
+
return 'powershell -NoProfile -Command "for ($i = 0; $i -lt 8; $i++) { '
|
|
446
|
+
+ `$t = @(Get-NetTCPConnection -State Listen -LocalPort ${port} -ErrorAction SilentlyContinue | `
|
|
447
|
+
+ "Where-Object { (Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue).ProcessName -eq 'sshd' }); "
|
|
448
|
+
+ 'if (-not $t) { break }; '
|
|
449
|
+
+ '$t | ForEach-Object { Stop-Process -Id $_.OwningProcess -Force -ErrorAction SilentlyContinue }; '
|
|
450
|
+
+ 'Start-Sleep -Milliseconds 250 }"';
|
|
451
|
+
}
|
|
452
|
+
/** Tags a POSIX tunnel's remote session so a stale one can be found by name rather than by port. */
|
|
453
|
+
function posixTunnelMarker(port) {
|
|
454
|
+
return `cortex-tunnel-${port}`;
|
|
455
|
+
}
|
|
456
|
+
/**
|
|
457
|
+
* The remote end of a POSIX tunnel: a shell that parks with the marker in its own argv for as long
|
|
458
|
+
* as the sshd that spawned it lives. `ssh -N` would leave nothing on the far side but sshd, and
|
|
459
|
+
* sshd marks itself non-dumpable, so `/proc/<sshd>/fd` is root-only and an unprivileged
|
|
460
|
+
* `fuser`/`lsof`/`ss -p` reports no owner for the forward listener at all — a stale one simply
|
|
461
|
+
* cannot be located from the port. This process is an ordinary child of that sshd, which turns
|
|
462
|
+
* "who holds the port" into a `pgrep`.
|
|
463
|
+
*
|
|
464
|
+
* It has to watch its parent rather than park forever: `-T` gives the session no pty, so nothing
|
|
465
|
+
* sends SIGHUP when sshd goes away, and a plain `sleep` loop would be reparented to init and leak
|
|
466
|
+
* one process per tunnel restart. Watching the parent by pid also keeps the black-hole case right
|
|
467
|
+
* — there sshd is still alive, so the marker stays put and stays findable.
|
|
468
|
+
*/
|
|
469
|
+
function posixTunnelCommand(port) {
|
|
470
|
+
return "exec sh -c 'P=$PPID; while kill -0 $P 2>/dev/null; do sleep 30; done"
|
|
471
|
+
+ ` # ${posixTunnelMarker(port)}'`;
|
|
472
|
+
}
|
|
473
|
+
/**
|
|
474
|
+
* Evict a stale POSIX tunnel by killing the sshd session that owns its listener. When the link
|
|
475
|
+
* dies without a clean close, sshd blocks writing the session's exit status into the black hole
|
|
476
|
+
* and keeps the forward bound for a full TCP retransmission timeout (~15 min); every `ssh -R` in
|
|
477
|
+
* that window dies on ExitOnForwardFailure. Killing the marker's parent needs no privilege — that
|
|
478
|
+
* sshd runs as us — but it does need care: `/proc/<pid>/stat` is read past the last `)` because a
|
|
479
|
+
* process name may contain spaces, and the kill is gated on the parent actually being an sshd, so
|
|
480
|
+
* neither a recycled PID nor a marker already reparented to init can turn this into a stray kill.
|
|
481
|
+
* The name is matched as a prefix because OpenSSH 9.8+ renamed the per-connection process to
|
|
482
|
+
* `sshd-session`. The `[-]` keeps the pattern from matching the command's own shell, which would
|
|
483
|
+
* otherwise make this hang up on itself.
|
|
484
|
+
*/
|
|
485
|
+
function posixFreePortCommand(port) {
|
|
486
|
+
const pattern = posixTunnelMarker(port).replace('cortex-', 'cortex[-]');
|
|
487
|
+
return `for p in $(pgrep -f "${pattern}"); do `
|
|
488
|
+
+ 'pp=$(sed -e "s/^.*) //" /proc/$p/stat 2>/dev/null | cut -d" " -f2); '
|
|
489
|
+
+ '[ -n "$pp" ] || continue; '
|
|
490
|
+
+ 'case "$(cat /proc/$pp/comm 2>/dev/null)" in sshd*) kill "$pp";; esac; '
|
|
491
|
+
+ 'done; exit 0';
|
|
437
492
|
}
|
|
438
493
|
function tunnelSpec(device, reg) {
|
|
439
494
|
if (reg.clientConnection !== 'ssh-reverse')
|
|
@@ -442,8 +497,13 @@ function tunnelSpec(device, reg) {
|
|
|
442
497
|
throw new Error(`SSH reverse route is not ready for ${device}`);
|
|
443
498
|
const remotePort = reg.clientReversePort ?? clientManagerPort;
|
|
444
499
|
const spec = { device, host: reg.ssh, remotePort, serverPort: clientManagerPort };
|
|
445
|
-
if (reg.win)
|
|
500
|
+
if (reg.win) {
|
|
446
501
|
spec.freeRemotePortCommand = windowsFreePortCommand(remotePort);
|
|
502
|
+
}
|
|
503
|
+
else {
|
|
504
|
+
spec.markerCommand = posixTunnelCommand(remotePort);
|
|
505
|
+
spec.freeRemotePortCommand = posixFreePortCommand(remotePort);
|
|
506
|
+
}
|
|
447
507
|
return spec;
|
|
448
508
|
}
|
|
449
509
|
async function ensureManagedRoute(device, reg) {
|
|
@@ -617,87 +677,6 @@ function _testReset() {
|
|
|
617
677
|
_getRegistryImpl = getMachineRegistry;
|
|
618
678
|
tunnelSupervisor = new SshTunnelSupervisor();
|
|
619
679
|
}
|
|
620
|
-
// --- Task callback handler (DR-0011 §4.4) ---
|
|
621
|
-
function sendAck(ws, callbackId, ok, message) {
|
|
622
|
-
if (ws.readyState === WebSocket.OPEN) {
|
|
623
|
-
ws.send(JSON.stringify({ type: 'task-callback-ack', callbackId, ok, message }));
|
|
624
|
-
}
|
|
625
|
-
}
|
|
626
|
-
/** Validate an untrusted `gpu` field from a task-callback into a persistable ExecutionGpuInfo,
|
|
627
|
-
* or null if absent/malformed. Requires a non-empty numeric `indices` array. */
|
|
628
|
-
function normalizeGpuPayload(raw) {
|
|
629
|
-
if (!raw || typeof raw !== 'object')
|
|
630
|
-
return null;
|
|
631
|
-
const obj = raw;
|
|
632
|
-
const indices = Array.isArray(obj.indices)
|
|
633
|
-
? obj.indices.filter((n) => typeof n === 'number' && Number.isFinite(n))
|
|
634
|
-
: [];
|
|
635
|
-
if (indices.length === 0)
|
|
636
|
-
return null;
|
|
637
|
-
const memoryMb = typeof obj.memoryMb === 'number' && Number.isFinite(obj.memoryMb) ? obj.memoryMb : null;
|
|
638
|
-
return { indices, memoryMb };
|
|
639
|
-
}
|
|
640
|
-
async function handleTaskCallback(ws, msg) {
|
|
641
|
-
const { taskProject, taskId, dispatchGeneration, termination, exitCode, durationHuman, remoteResultPath, remoteLogPath, device, callbackId, logTail, gpu } = msg;
|
|
642
|
-
// Capture the per-execution GPU onto the dispatch execution record (DR-0018 §6.3 B2-followup).
|
|
643
|
-
// Keyed by taskId, independent of task status, and done BEFORE the idempotency short-circuits so
|
|
644
|
-
// it lands even on an "already done" callback. No-op when no execution is registered for the task
|
|
645
|
-
// (non-webhook-launched run) or the payload is absent/malformed.
|
|
646
|
-
if (taskId) {
|
|
647
|
-
const normalizedGpu = normalizeGpuPayload(gpu);
|
|
648
|
-
if (normalizedGpu) {
|
|
649
|
-
try {
|
|
650
|
-
setExecutionGpuByTaskId(taskId, normalizedGpu);
|
|
651
|
-
}
|
|
652
|
-
catch (e) {
|
|
653
|
-
log.warn(`task-callback: failed to record GPU for task ${taskId}: ${e.message}`);
|
|
654
|
-
}
|
|
655
|
-
}
|
|
656
|
-
}
|
|
657
|
-
// No task linkage: ack-true immediately (client doesn't need to retry)
|
|
658
|
-
if (!taskProject || !taskId) {
|
|
659
|
-
sendAck(ws, callbackId, true, 'no task linkage');
|
|
660
|
-
return;
|
|
661
|
-
}
|
|
662
|
-
// Read task state from TASKS.yaml for idempotency check
|
|
663
|
-
const tasks = readTasks(taskProject);
|
|
664
|
-
const found = findTask(tasks, null, taskId);
|
|
665
|
-
if ('error' in found) {
|
|
666
|
-
log.info(`Ghost callback: task ${taskId} not found in ${taskProject}`);
|
|
667
|
-
sendAck(ws, callbackId, true, 'ghost callback');
|
|
668
|
-
return;
|
|
669
|
-
}
|
|
670
|
-
const task = found.task;
|
|
671
|
-
if (task.status === 'done') {
|
|
672
|
-
sendAck(ws, callbackId, true, 'already done, idempotent');
|
|
673
|
-
return;
|
|
674
|
-
}
|
|
675
|
-
const isSuccess = termination === 'completed' && exitCode === 0;
|
|
676
|
-
const remoteRef = remoteResultPath || remoteLogPath || 'unknown';
|
|
677
|
-
const note = isSuccess
|
|
678
|
-
? `cortex-run on ${device} completed in ${durationHuman || '?'}, exit 0. Remote: ${remoteRef}`
|
|
679
|
-
: `cortex-run on ${device} ${termination || '?'} after ${durationHuman || '?'}, exit ${exitCode ?? '?'}. Remote: ${remoteRef}\n--- log tail ---\n${logTail || '(no log tail)'}`;
|
|
680
|
-
// Route through taskMutator (not the bare lifecycle functions) so task.completed /
|
|
681
|
-
// task.blocked events fire — a manager thread suspended on this task (DR-0014 §8)
|
|
682
|
-
// is woken by exactly these events, possibly days after dispatch.
|
|
683
|
-
let result;
|
|
684
|
-
if (isSuccess) {
|
|
685
|
-
result = await taskMutator.complete(taskId, note, {
|
|
686
|
-
skipVerify: true,
|
|
687
|
-
skipVerifyReason: 'remote-run',
|
|
688
|
-
ownership: { generation: dispatchGeneration ?? null },
|
|
689
|
-
});
|
|
690
|
-
}
|
|
691
|
-
else {
|
|
692
|
-
result = await taskMutator.block(taskId, note, {
|
|
693
|
-
ownership: { generation: dispatchGeneration ?? null },
|
|
694
|
-
});
|
|
695
|
-
}
|
|
696
|
-
const ackMessage = result.verify_warning
|
|
697
|
-
? `${result.message} (${result.verify_warning})`
|
|
698
|
-
: result.message;
|
|
699
|
-
sendAck(ws, callbackId, result.stale ? true : result.success, ackMessage);
|
|
700
|
-
}
|
|
701
680
|
export { startClientManager, stopClientManager, getOnlineDevices, isDeviceOnline, sendCommand, sendControlMessage, setClientUpdateHooks, startRemoteClient, launchRemoteClient, startAllRemoteClients, buildRemoteSpawnCommand, localClientEntryPath, clientPids, sshExec,
|
|
702
681
|
// Test-only hooks (prefixed with _ by convention).
|
|
703
682
|
_setSshExecForTesting, _setMachineRegistryProviderForTesting, _setTunnelSupervisorForTesting, _getRestartTimerCount, _testReset, };
|