@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.
- 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-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/hooks-builder.js +2 -2
- package/dist/agent-adapter/claude/spawn-args.js +4 -0
- 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/types.d.ts +1 -0
- package/dist/core/mcp-tool-gate.js +1 -0
- 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 +21 -0
- package/dist/core/settings-spec.js +28 -1
- 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/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/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 +39 -119
- 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/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 -1
- package/dist/domain/ui-service/app-router.d.ts +24 -3
- package/dist/domain/ui-service/app-router.js +8 -14
- package/dist/domain/ui-service/input-schemas.d.ts +17 -5
- package/dist/domain/ui-service/input-schemas.js +13 -9
- package/dist/domain/ui-service/mutate/platform-settings.js +1 -1
- package/dist/domain/ui-service/mutate/sessions.d.ts +5 -1
- package/dist/domain/ui-service/mutate/sessions.js +14 -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/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 +133 -49
- package/dist/domain/ui-service/types.js +1 -1
- package/dist/domain/ui-service/ui-service.js +7 -31
- 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 +29 -7
- 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 +2 -2
- package/dist/events/event-types.d.ts +0 -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 +3 -2
- package/dist/orchestration/agent-runner.js +17 -12
- package/dist/orchestration/attachments-store.d.ts +31 -0
- package/dist/orchestration/attachments-store.js +184 -0
- package/dist/orchestration/conversation-request.d.ts +4 -0
- package/dist/orchestration/conversation-request.js +13 -6
- package/dist/orchestration/interactions/plan-approvals.js +1 -1
- package/dist/orchestration/outputs-store.d.ts +11 -0
- package/dist/orchestration/outputs-store.js +32 -6
- 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 +193 -39
- 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 +19 -8
- 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/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.js +1 -1
- 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.js +1 -1
- package/dist/store/session-registry-journal.js +1 -1
- package/dist/store/session-registry-repo.js +1 -1
- package/dist/store/version-migrations.d.ts +13 -3
- package/dist/store/version-migrations.js +254 -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-CRDJo39X.css → index-CwwQNMpP.css} +1 -1
- package/web/dist/assets/index-DLSfgq3o.js +444 -0
- package/web/dist/assets/{index-CEZ0DSei.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/web/dist/assets/index-DjuPJVZE.js +0 -444
- /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
|
@@ -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) {
|
|
@@ -676,87 +677,6 @@ function _testReset() {
|
|
|
676
677
|
_getRegistryImpl = getMachineRegistry;
|
|
677
678
|
tunnelSupervisor = new SshTunnelSupervisor();
|
|
678
679
|
}
|
|
679
|
-
// --- Task callback handler (DR-0011 §4.4) ---
|
|
680
|
-
function sendAck(ws, callbackId, ok, message) {
|
|
681
|
-
if (ws.readyState === WebSocket.OPEN) {
|
|
682
|
-
ws.send(JSON.stringify({ type: 'task-callback-ack', callbackId, ok, message }));
|
|
683
|
-
}
|
|
684
|
-
}
|
|
685
|
-
/** Validate an untrusted `gpu` field from a task-callback into a persistable ExecutionGpuInfo,
|
|
686
|
-
* or null if absent/malformed. Requires a non-empty numeric `indices` array. */
|
|
687
|
-
function normalizeGpuPayload(raw) {
|
|
688
|
-
if (!raw || typeof raw !== 'object')
|
|
689
|
-
return null;
|
|
690
|
-
const obj = raw;
|
|
691
|
-
const indices = Array.isArray(obj.indices)
|
|
692
|
-
? obj.indices.filter((n) => typeof n === 'number' && Number.isFinite(n))
|
|
693
|
-
: [];
|
|
694
|
-
if (indices.length === 0)
|
|
695
|
-
return null;
|
|
696
|
-
const memoryMb = typeof obj.memoryMb === 'number' && Number.isFinite(obj.memoryMb) ? obj.memoryMb : null;
|
|
697
|
-
return { indices, memoryMb };
|
|
698
|
-
}
|
|
699
|
-
async function handleTaskCallback(ws, msg) {
|
|
700
|
-
const { taskProject, taskId, dispatchGeneration, termination, exitCode, durationHuman, remoteResultPath, remoteLogPath, device, callbackId, logTail, gpu } = msg;
|
|
701
|
-
// Capture the per-execution GPU onto the dispatch execution record (DR-0018 §6.3 B2-followup).
|
|
702
|
-
// Keyed by taskId, independent of task status, and done BEFORE the idempotency short-circuits so
|
|
703
|
-
// it lands even on an "already done" callback. No-op when no execution is registered for the task
|
|
704
|
-
// (non-webhook-launched run) or the payload is absent/malformed.
|
|
705
|
-
if (taskId) {
|
|
706
|
-
const normalizedGpu = normalizeGpuPayload(gpu);
|
|
707
|
-
if (normalizedGpu) {
|
|
708
|
-
try {
|
|
709
|
-
setExecutionGpuByTaskId(taskId, normalizedGpu);
|
|
710
|
-
}
|
|
711
|
-
catch (e) {
|
|
712
|
-
log.warn(`task-callback: failed to record GPU for task ${taskId}: ${e.message}`);
|
|
713
|
-
}
|
|
714
|
-
}
|
|
715
|
-
}
|
|
716
|
-
// No task linkage: ack-true immediately (client doesn't need to retry)
|
|
717
|
-
if (!taskProject || !taskId) {
|
|
718
|
-
sendAck(ws, callbackId, true, 'no task linkage');
|
|
719
|
-
return;
|
|
720
|
-
}
|
|
721
|
-
// Read task state from TASKS.yaml for idempotency check
|
|
722
|
-
const tasks = readTasks(taskProject);
|
|
723
|
-
const found = findTask(tasks, null, taskId);
|
|
724
|
-
if ('error' in found) {
|
|
725
|
-
log.info(`Ghost callback: task ${taskId} not found in ${taskProject}`);
|
|
726
|
-
sendAck(ws, callbackId, true, 'ghost callback');
|
|
727
|
-
return;
|
|
728
|
-
}
|
|
729
|
-
const task = found.task;
|
|
730
|
-
if (task.status === 'done') {
|
|
731
|
-
sendAck(ws, callbackId, true, 'already done, idempotent');
|
|
732
|
-
return;
|
|
733
|
-
}
|
|
734
|
-
const isSuccess = termination === 'completed' && exitCode === 0;
|
|
735
|
-
const remoteRef = remoteResultPath || remoteLogPath || 'unknown';
|
|
736
|
-
const note = isSuccess
|
|
737
|
-
? `cortex-run on ${device} completed in ${durationHuman || '?'}, exit 0. Remote: ${remoteRef}`
|
|
738
|
-
: `cortex-run on ${device} ${termination || '?'} after ${durationHuman || '?'}, exit ${exitCode ?? '?'}. Remote: ${remoteRef}\n--- log tail ---\n${logTail || '(no log tail)'}`;
|
|
739
|
-
// Route through taskMutator (not the bare lifecycle functions) so task.completed /
|
|
740
|
-
// task.blocked events fire — a manager thread suspended on this task (DR-0014 §8)
|
|
741
|
-
// is woken by exactly these events, possibly days after dispatch.
|
|
742
|
-
let result;
|
|
743
|
-
if (isSuccess) {
|
|
744
|
-
result = await taskMutator.complete(taskId, note, {
|
|
745
|
-
skipVerify: true,
|
|
746
|
-
skipVerifyReason: 'remote-run',
|
|
747
|
-
ownership: { generation: dispatchGeneration ?? null },
|
|
748
|
-
});
|
|
749
|
-
}
|
|
750
|
-
else {
|
|
751
|
-
result = await taskMutator.block(taskId, note, {
|
|
752
|
-
ownership: { generation: dispatchGeneration ?? null },
|
|
753
|
-
});
|
|
754
|
-
}
|
|
755
|
-
const ackMessage = result.verify_warning
|
|
756
|
-
? `${result.message} (${result.verify_warning})`
|
|
757
|
-
: result.message;
|
|
758
|
-
sendAck(ws, callbackId, result.stale ? true : result.success, ackMessage);
|
|
759
|
-
}
|
|
760
680
|
export { startClientManager, stopClientManager, getOnlineDevices, isDeviceOnline, sendCommand, sendControlMessage, setClientUpdateHooks, startRemoteClient, launchRemoteClient, startAllRemoteClients, buildRemoteSpawnCommand, localClientEntryPath, clientPids, sshExec,
|
|
761
681
|
// Test-only hooks (prefixed with _ by convention).
|
|
762
682
|
_setSshExecForTesting, _setMachineRegistryProviderForTesting, _setTunnelSupervisorForTesting, _getRestartTimerCount, _testReset, };
|
|
@@ -10,7 +10,7 @@ export interface ClientConnectEnv {
|
|
|
10
10
|
/**
|
|
11
11
|
* Resolve the WebSocket URL the cortex-client dials.
|
|
12
12
|
*
|
|
13
|
-
* A full ``CORTEX_SERVER_URL`` (e.g. ``wss://cortex.
|
|
13
|
+
* A full ``CORTEX_SERVER_URL`` (e.g. ``wss://cortex.example.com``) takes
|
|
14
14
|
* precedence so the client can reach the agent-server through a Cloudflare
|
|
15
15
|
* Tunnel over 443/TLS. Otherwise it falls back to ``ws://<host>:<port>`` for
|
|
16
16
|
* direct/LAN reach.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Resolve the WebSocket URL the cortex-client dials.
|
|
3
3
|
*
|
|
4
|
-
* A full ``CORTEX_SERVER_URL`` (e.g. ``wss://cortex.
|
|
4
|
+
* A full ``CORTEX_SERVER_URL`` (e.g. ``wss://cortex.example.com``) takes
|
|
5
5
|
* precedence so the client can reach the agent-server through a Cloudflare
|
|
6
6
|
* Tunnel over 443/TLS. Otherwise it falls back to ``ws://<host>:<port>`` for
|
|
7
7
|
* direct/LAN reach.
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/** `file.stat` is a metadata round trip — the client-manager file-command timeout is plenty. */
|
|
2
|
+
export interface RemoteFileStat {
|
|
3
|
+
size: number;
|
|
4
|
+
name: string;
|
|
5
|
+
mtimeMs?: number;
|
|
6
|
+
}
|
|
7
|
+
/** Metadata probe: existence, regular-file-ness and size, with the device's own error text. */
|
|
8
|
+
export declare function statRemoteFile(device: string, filePath: string): Promise<RemoteFileStat>;
|
|
9
|
+
/**
|
|
10
|
+
* Everything that can be known — and refused — before a single byte moves: that the device is
|
|
11
|
+
* online and new enough, that the path is a readable file, and that it fits under the cap. Callers
|
|
12
|
+
* that need the file's NAME to choose a destination run this first and hand the result back to
|
|
13
|
+
* `fetchRemoteFile`, so the device is stat'ed once rather than twice.
|
|
14
|
+
*/
|
|
15
|
+
export declare function prepareRemoteFetch(a: {
|
|
16
|
+
device: string;
|
|
17
|
+
filePath: string;
|
|
18
|
+
maxBytes?: number;
|
|
19
|
+
}): Promise<RemoteFileStat>;
|
|
20
|
+
export interface FetchRemoteFileArgs {
|
|
21
|
+
device: string;
|
|
22
|
+
/** Absolute path ON THE DEVICE. */
|
|
23
|
+
filePath: string;
|
|
24
|
+
/** Local destination; its directory must already exist. */
|
|
25
|
+
destPath: string;
|
|
26
|
+
/** Refuse before transferring anything when the device reports a larger file. */
|
|
27
|
+
maxBytes?: number;
|
|
28
|
+
/** Result of an earlier `prepareRemoteFetch` for this exact file; skips the second stat. */
|
|
29
|
+
stat?: RemoteFileStat;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Copy `filePath` from `device` into `destPath`. Throws — leaving no partial file behind — when the
|
|
33
|
+
* device is offline, too old, the path is not a readable file, it exceeds `maxBytes`, or the
|
|
34
|
+
* transfer ends short.
|
|
35
|
+
*/
|
|
36
|
+
export declare function fetchRemoteFile(a: FetchRemoteFileArgs): Promise<RemoteFileStat>;
|
|
37
|
+
export interface StagedRemoteFile {
|
|
38
|
+
/** Server-local path the caller reads, and is expected to delete when done. */
|
|
39
|
+
localPath: string;
|
|
40
|
+
name: string;
|
|
41
|
+
size: number;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Stream a device's file into a server-local staging path. Used by senders that do their own upload
|
|
45
|
+
* from disk (Slack, Feishu); the Web sender writes into the session's outputs directly instead.
|
|
46
|
+
*/
|
|
47
|
+
export declare function stageRemoteFile(a: {
|
|
48
|
+
device: string;
|
|
49
|
+
filePath: string;
|
|
50
|
+
maxBytes?: number;
|
|
51
|
+
}): Promise<StagedRemoteFile>;
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import * as fs from 'fs';
|
|
2
|
+
import * as path from 'path';
|
|
3
|
+
import * as crypto from 'crypto';
|
|
4
|
+
import { WORKSPACE_DIR } from '../../core/paths.js';
|
|
5
|
+
import { createLogger } from '../../core/log.js';
|
|
6
|
+
import { sendCommand, sendControlMessage, getOnlineDevices } from './client-manager.js';
|
|
7
|
+
import { requestFileStream } from './reverse-stream.js';
|
|
8
|
+
const log = createLogger('device-file');
|
|
9
|
+
/**
|
|
10
|
+
* Pull a whole file off a device (`send_file device=…`). Every other remote tool answers on the
|
|
11
|
+
* control socket as one JSON message, which is fine for text but not for bytes: a file would be
|
|
12
|
+
* base64'd whole into memory on both ends and would hold the device's single command channel for
|
|
13
|
+
* the length of the transfer. So this uses the reverse channel instead — the same handshake the
|
|
14
|
+
* port forward already relies on — and streams binary frames straight to disk.
|
|
15
|
+
*
|
|
16
|
+
* The transfer is two steps on purpose. `file.stat` first, over the ordinary command path, so a
|
|
17
|
+
* missing path or an over-cap file fails with a real error message; only then is the stream opened.
|
|
18
|
+
* The stat'd size then doubles as the completeness check: a transfer that ends early is rejected
|
|
19
|
+
* rather than silently delivering a truncated file.
|
|
20
|
+
*/
|
|
21
|
+
/** The device must have dialled back AND finished within this; a stalled transfer is not a hang. */
|
|
22
|
+
const IDLE_TIMEOUT_MS = 60_000;
|
|
23
|
+
/** Capability advertised in the device's `hello`. Absent on clients older than this feature. */
|
|
24
|
+
const FILE_STREAM_CAPABILITY = 'file-stream';
|
|
25
|
+
function assertCanStreamFiles(device) {
|
|
26
|
+
const info = getOnlineDevices().find(d => d.device === device);
|
|
27
|
+
if (!info)
|
|
28
|
+
throw new Error(`Device "${device}" is not online`);
|
|
29
|
+
if (!info.capabilities?.includes(FILE_STREAM_CAPABILITY)) {
|
|
30
|
+
throw new Error(`Device "${device}" runs a client too old to stream files. It updates itself on its next `
|
|
31
|
+
+ 'reconnect; until then, copy the file to the server yourself.');
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/** Metadata probe: existence, regular-file-ness and size, with the device's own error text. */
|
|
35
|
+
export async function statRemoteFile(device, filePath) {
|
|
36
|
+
const data = await sendCommand(device, { action: 'file.stat', params: { file_path: filePath } });
|
|
37
|
+
if (typeof data?.size !== 'number')
|
|
38
|
+
throw new Error(`Device "${device}" returned no size for ${filePath}`);
|
|
39
|
+
return { size: data.size, name: data.name || filePath.split(/[/\\]/).pop() || 'file', mtimeMs: data.mtimeMs };
|
|
40
|
+
}
|
|
41
|
+
/** Receive the callback socket's frames into `destPath`, resolving with the byte count. */
|
|
42
|
+
function receiveInto(ws, destPath, expected) {
|
|
43
|
+
return new Promise((resolve, reject) => {
|
|
44
|
+
const out = fs.createWriteStream(destPath);
|
|
45
|
+
let received = 0;
|
|
46
|
+
let settled = false;
|
|
47
|
+
let idle;
|
|
48
|
+
const finish = (err) => {
|
|
49
|
+
if (settled)
|
|
50
|
+
return;
|
|
51
|
+
settled = true;
|
|
52
|
+
clearTimeout(idle);
|
|
53
|
+
// End the file either way: the caller deletes a failed destination, and leaving the handle
|
|
54
|
+
// open would keep it undeletable on Windows.
|
|
55
|
+
out.end(() => (err ? reject(err) : resolve(received)));
|
|
56
|
+
if (err) {
|
|
57
|
+
try {
|
|
58
|
+
ws.close();
|
|
59
|
+
}
|
|
60
|
+
catch { /* already closing */ }
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
const armIdle = () => {
|
|
64
|
+
clearTimeout(idle);
|
|
65
|
+
idle = setTimeout(() => finish(new Error(`transfer stalled after ${received}/${expected} bytes`)), IDLE_TIMEOUT_MS);
|
|
66
|
+
idle.unref?.();
|
|
67
|
+
};
|
|
68
|
+
armIdle();
|
|
69
|
+
ws.on('message', (data) => {
|
|
70
|
+
const buf = Array.isArray(data) ? Buffer.concat(data) : Buffer.from(data);
|
|
71
|
+
received += buf.length;
|
|
72
|
+
armIdle();
|
|
73
|
+
if (received > expected) {
|
|
74
|
+
finish(new Error(`device sent more than the ${expected} bytes it declared`));
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
// Pause the socket while the disk catches up, so a slow filesystem costs time, not memory.
|
|
78
|
+
if (!out.write(buf)) {
|
|
79
|
+
ws.pause?.();
|
|
80
|
+
out.once('drain', () => ws.resume?.());
|
|
81
|
+
}
|
|
82
|
+
});
|
|
83
|
+
ws.on('error', (e) => finish(new Error(`stream error: ${e.message}`)));
|
|
84
|
+
out.on('error', (e) => finish(new Error(`write failed: ${e.message}`)));
|
|
85
|
+
ws.on('close', (code, reason) => {
|
|
86
|
+
const why = reason?.toString() || '';
|
|
87
|
+
// The client reports a read-side failure by closing with a reason instead of by sending
|
|
88
|
+
// fewer bytes, so an explicit error is never mistaken for a short file and vice versa.
|
|
89
|
+
if (code !== 1000) {
|
|
90
|
+
finish(new Error(why || `device closed the stream (code ${code})`));
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
if (received !== expected) {
|
|
94
|
+
finish(new Error(`truncated transfer: got ${received} of ${expected} bytes${why ? ` (${why})` : ''}`));
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
finish(null);
|
|
98
|
+
});
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Everything that can be known — and refused — before a single byte moves: that the device is
|
|
103
|
+
* online and new enough, that the path is a readable file, and that it fits under the cap. Callers
|
|
104
|
+
* that need the file's NAME to choose a destination run this first and hand the result back to
|
|
105
|
+
* `fetchRemoteFile`, so the device is stat'ed once rather than twice.
|
|
106
|
+
*/
|
|
107
|
+
export async function prepareRemoteFetch(a) {
|
|
108
|
+
assertCanStreamFiles(a.device);
|
|
109
|
+
const stat = await statRemoteFile(a.device, a.filePath);
|
|
110
|
+
if (a.maxBytes !== undefined && stat.size > a.maxBytes) {
|
|
111
|
+
throw new Error(`File is ${stat.size} bytes on ${a.device}, over the ${a.maxBytes}-byte limit`);
|
|
112
|
+
}
|
|
113
|
+
return stat;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Copy `filePath` from `device` into `destPath`. Throws — leaving no partial file behind — when the
|
|
117
|
+
* device is offline, too old, the path is not a readable file, it exceeds `maxBytes`, or the
|
|
118
|
+
* transfer ends short.
|
|
119
|
+
*/
|
|
120
|
+
export async function fetchRemoteFile(a) {
|
|
121
|
+
const stat = a.stat ?? await prepareRemoteFetch(a);
|
|
122
|
+
const req = requestFileStream(a.device, a.filePath);
|
|
123
|
+
// The claim rejects on its own timer (or when the device disconnects) whether or not anyone is
|
|
124
|
+
// waiting — and if `sendControlMessage` throws we never reach the await. An unobserved rejection
|
|
125
|
+
// would take the daemon down, so mark it handled now; the await below still sees the real error.
|
|
126
|
+
req.socket.catch(() => { });
|
|
127
|
+
let ws;
|
|
128
|
+
try {
|
|
129
|
+
sendControlMessage(a.device, req.message);
|
|
130
|
+
ws = await req.socket;
|
|
131
|
+
}
|
|
132
|
+
catch (e) {
|
|
133
|
+
throw new Error(`Failed to open a file stream from "${a.device}": ${e.message}`);
|
|
134
|
+
}
|
|
135
|
+
try {
|
|
136
|
+
const received = await receiveInto(ws, a.destPath, stat.size);
|
|
137
|
+
log.info(`fetched ${a.filePath} from ${a.device} (${received} bytes)`);
|
|
138
|
+
return stat;
|
|
139
|
+
}
|
|
140
|
+
catch (e) {
|
|
141
|
+
await fs.promises.rm(a.destPath, { force: true }).catch(() => { });
|
|
142
|
+
throw new Error(`Transfer of ${a.filePath} from "${a.device}" failed: ${e.message}`);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
// --- Staging for senders that upload from a local path ---
|
|
146
|
+
/** Transfers in flight for a platform upload live here, one directory per transfer so two files of
|
|
147
|
+
* the same name never collide. */
|
|
148
|
+
const STAGING_DIR = path.join(WORKSPACE_DIR, 'remote-files');
|
|
149
|
+
/** A staged file outlives its upload only if that upload crashed; an hour is far past any transfer
|
|
150
|
+
* still worth waiting for. */
|
|
151
|
+
const STAGING_TTL_MS = 60 * 60_000;
|
|
152
|
+
/** Opportunistic sweep so a crashed uploader leaks at most one TTL window rather than forever. */
|
|
153
|
+
async function sweepStaging() {
|
|
154
|
+
const cutoff = Date.now() - STAGING_TTL_MS;
|
|
155
|
+
let entries;
|
|
156
|
+
try {
|
|
157
|
+
entries = await fs.promises.readdir(STAGING_DIR);
|
|
158
|
+
}
|
|
159
|
+
catch {
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
await Promise.all(entries.map(async (name) => {
|
|
163
|
+
const dir = path.join(STAGING_DIR, name);
|
|
164
|
+
try {
|
|
165
|
+
const st = await fs.promises.stat(dir);
|
|
166
|
+
if (st.mtimeMs < cutoff)
|
|
167
|
+
await fs.promises.rm(dir, { recursive: true, force: true });
|
|
168
|
+
}
|
|
169
|
+
catch { /* raced with another sweep or an active uploader */ }
|
|
170
|
+
}));
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Stream a device's file into a server-local staging path. Used by senders that do their own upload
|
|
174
|
+
* from disk (Slack, Feishu); the Web sender writes into the session's outputs directly instead.
|
|
175
|
+
*/
|
|
176
|
+
export async function stageRemoteFile(a) {
|
|
177
|
+
const stat = await prepareRemoteFetch(a);
|
|
178
|
+
void sweepStaging();
|
|
179
|
+
const dir = path.join(STAGING_DIR, crypto.randomBytes(8).toString('hex'));
|
|
180
|
+
await fs.promises.mkdir(dir, { recursive: true });
|
|
181
|
+
// The device's own basename, with separators stripped: it is remote input, and it must not be
|
|
182
|
+
// able to steer the write out of the staging directory.
|
|
183
|
+
const safeName = (stat.name.replace(/[/\\]/g, '_') || 'file').slice(0, 200);
|
|
184
|
+
const localPath = path.join(dir, safeName);
|
|
185
|
+
try {
|
|
186
|
+
await fetchRemoteFile({ device: a.device, filePath: a.filePath, destPath: localPath, stat });
|
|
187
|
+
}
|
|
188
|
+
catch (e) {
|
|
189
|
+
await fs.promises.rm(dir, { recursive: true, force: true }).catch(() => { });
|
|
190
|
+
throw e;
|
|
191
|
+
}
|
|
192
|
+
return { localPath, name: safeName, size: stat.size };
|
|
193
|
+
}
|
|
@@ -92,6 +92,9 @@ async function serveConnection(entry, tcp) {
|
|
|
92
92
|
tcp.destroy();
|
|
93
93
|
return;
|
|
94
94
|
}
|
|
95
|
+
// The claim rejects on its own timer even if we bail out below without awaiting it, and an
|
|
96
|
+
// unobserved rejection would take the daemon down. The await further down still sees the error.
|
|
97
|
+
req.socket.catch(() => { });
|
|
95
98
|
try {
|
|
96
99
|
sendControl(device, req.message);
|
|
97
100
|
}
|
|
@@ -13,15 +13,15 @@ import type { WebSocket } from 'ws';
|
|
|
13
13
|
export declare const REVERSE_PATH_PREFIX = "/reverse";
|
|
14
14
|
/** `/reverse?stream=<id>` → the id, or null when this is not a callback socket. */
|
|
15
15
|
export declare function parseStreamId(rawUrl: string | undefined): string | null;
|
|
16
|
-
export interface StreamRequest {
|
|
16
|
+
export interface StreamRequest<M = {
|
|
17
|
+
type: 'open-stream';
|
|
18
|
+
streamId: string;
|
|
19
|
+
host: string;
|
|
20
|
+
port: number;
|
|
21
|
+
}> {
|
|
17
22
|
id: string;
|
|
18
23
|
/** Message to hand to the device over its control socket. */
|
|
19
|
-
message:
|
|
20
|
-
type: 'open-stream';
|
|
21
|
-
streamId: string;
|
|
22
|
-
host: string;
|
|
23
|
-
port: number;
|
|
24
|
-
};
|
|
24
|
+
message: M;
|
|
25
25
|
/** Resolves with the device's callback socket, or rejects on timeout. */
|
|
26
26
|
socket: Promise<WebSocket>;
|
|
27
27
|
}
|
|
@@ -30,6 +30,17 @@ export interface StreamRequest {
|
|
|
30
30
|
* device's control socket and then awaits `socket`.
|
|
31
31
|
*/
|
|
32
32
|
export declare function requestStream(device: string, host: string, port: number): StreamRequest;
|
|
33
|
+
export type OpenFileStreamMessage = {
|
|
34
|
+
type: 'open-file-stream';
|
|
35
|
+
streamId: string;
|
|
36
|
+
path: string;
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* Same handshake as `requestStream`, but the device answers with the bytes of a FILE rather than a
|
|
40
|
+
* TCP connection. Both share the claim table, the cap and the callback path, so a file transfer
|
|
41
|
+
* needs no new port, credential or tunnel — only a different message on the control socket.
|
|
42
|
+
*/
|
|
43
|
+
export declare function requestFileStream(device: string, filePath: string): StreamRequest<OpenFileStreamMessage>;
|
|
33
44
|
/**
|
|
34
45
|
* Pair a callback socket with its request. Returns false when the id is unknown — a stale or forged
|
|
35
46
|
* callback, which the caller closes rather than trusts.
|
|
@@ -29,16 +29,12 @@ export function parseStreamId(rawUrl) {
|
|
|
29
29
|
// Ids are minted here and echoed back verbatim; anything else is not ours.
|
|
30
30
|
return id && /^[0-9a-f]{32}$/.test(id) ? id : null;
|
|
31
31
|
}
|
|
32
|
-
/**
|
|
33
|
-
|
|
34
|
-
* device's control socket and then awaits `socket`.
|
|
35
|
-
*/
|
|
36
|
-
export function requestStream(device, host, port) {
|
|
32
|
+
/** Mint a pending callback slot. `target` is for logging and the timeout message only. */
|
|
33
|
+
function mintStream(device, target) {
|
|
37
34
|
if (pending.size >= MAX_PENDING) {
|
|
38
35
|
throw new Error(`too many pending reverse streams (${pending.size})`);
|
|
39
36
|
}
|
|
40
37
|
const id = crypto.randomBytes(16).toString('hex');
|
|
41
|
-
const target = `${host}:${port}`;
|
|
42
38
|
let resolve;
|
|
43
39
|
let reject;
|
|
44
40
|
const socket = new Promise((res, rej) => { resolve = res; reject = rej; });
|
|
@@ -48,8 +44,25 @@ export function requestStream(device, host, port) {
|
|
|
48
44
|
}, CLAIM_TIMEOUT_MS);
|
|
49
45
|
timer.unref?.();
|
|
50
46
|
pending.set(id, { device, target, resolve, reject, timer });
|
|
47
|
+
return { id, socket };
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Mint a stream the device is expected to dial back for. The caller sends `message` over the
|
|
51
|
+
* device's control socket and then awaits `socket`.
|
|
52
|
+
*/
|
|
53
|
+
export function requestStream(device, host, port) {
|
|
54
|
+
const { id, socket } = mintStream(device, `${host}:${port}`);
|
|
51
55
|
return { id, message: { type: 'open-stream', streamId: id, host, port }, socket };
|
|
52
56
|
}
|
|
57
|
+
/**
|
|
58
|
+
* Same handshake as `requestStream`, but the device answers with the bytes of a FILE rather than a
|
|
59
|
+
* TCP connection. Both share the claim table, the cap and the callback path, so a file transfer
|
|
60
|
+
* needs no new port, credential or tunnel — only a different message on the control socket.
|
|
61
|
+
*/
|
|
62
|
+
export function requestFileStream(device, filePath) {
|
|
63
|
+
const { id, socket } = mintStream(device, filePath);
|
|
64
|
+
return { id, message: { type: 'open-file-stream', streamId: id, path: filePath }, socket };
|
|
65
|
+
}
|
|
53
66
|
/**
|
|
54
67
|
* Pair a callback socket with its request. Returns false when the id is unknown — a stale or forged
|
|
55
68
|
* callback, which the caller closes rather than trusts.
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
// dispatch claim whose owner died with the server would otherwise stay in-progress forever
|
|
6
6
|
// — stranding the task AND any manager thread suspended on it. Claims that legitimately
|
|
7
7
|
// survive a restart are respected: a waiting/rate_limited thread that owns the task
|
|
8
|
-
// (DR-0014 suspension, rate-limit pause), a remote
|
|
8
|
+
// (DR-0014 suspension, rate-limit pause), a remote dispatch tracked in pending-tasks.json,
|
|
9
9
|
// and manual (non-dispatcher) claims.
|
|
10
10
|
import { scanAllTasks } from '../../core/task-parser.js';
|
|
11
11
|
import { threadStore } from '../../store/thread-repo.js';
|
|
@@ -43,7 +43,7 @@ export async function recoverOrphanedClaims(deps = {}) {
|
|
|
43
43
|
if (!task.id || task.claimed_by !== DISPATCHER_AGENT)
|
|
44
44
|
continue;
|
|
45
45
|
if (task.status === 'done' || task.status === 'pending')
|
|
46
|
-
continue; // pending →
|
|
46
|
+
continue; // pending → outside work owns it
|
|
47
47
|
if (task.blocked_by)
|
|
48
48
|
continue; // blocked is already a terminal signal for the tree
|
|
49
49
|
if (ownedByLiveThread(task))
|
|
@@ -30,6 +30,15 @@ declare function loadMachinesFromFile(failOnError?: boolean): void;
|
|
|
30
30
|
* Return the current in-memory machine registry.
|
|
31
31
|
*/
|
|
32
32
|
declare function getMachineRegistry(): MachineRegistry;
|
|
33
|
+
export type GpuCountUpdate = 'updated' | 'unchanged' | 'skipped';
|
|
34
|
+
/**
|
|
35
|
+
* Reconcile a GPU count a client reported about itself into the registry and machines.json.
|
|
36
|
+
*
|
|
37
|
+
* `null` means the client could not probe (no nvidia-smi, driver down) — that is "unknown", not
|
|
38
|
+
* "zero GPUs", so the configured value stands and the machine is never silently dropped from GPU
|
|
39
|
+
* dispatch. Only machines already in the registry are touched: a client cannot register itself.
|
|
40
|
+
*/
|
|
41
|
+
declare function applyReportedGpuCount(machine: string, reported: number | null): GpuCountUpdate;
|
|
33
42
|
/**
|
|
34
43
|
* Return the first machine key in the registry as the local/default machine.
|
|
35
44
|
* Falls back to 'local' if no machines are registered.
|
|
@@ -106,4 +115,4 @@ declare function processAbortOutcome(args: {
|
|
|
106
115
|
message: string;
|
|
107
116
|
}>;
|
|
108
117
|
}): Promise<AbortOutcome>;
|
|
109
|
-
export { getMachineRegistry, getLocalMachine, loadMachinesFromFile, startMachineRegistryWatcher, stopMachineRegistryWatcher, generateTaskId, buildDispatchSessionName, processSplitOutcome, processAbortOutcome, _testSetRegistry, };
|
|
118
|
+
export { getMachineRegistry, getLocalMachine, applyReportedGpuCount, loadMachinesFromFile, startMachineRegistryWatcher, stopMachineRegistryWatcher, generateTaskId, buildDispatchSessionName, processSplitOutcome, processAbortOutcome, _testSetRegistry, };
|
|
@@ -2,6 +2,7 @@ import * as crypto from 'crypto';
|
|
|
2
2
|
import { readFileSync, existsSync } from 'fs';
|
|
3
3
|
import * as path from 'path';
|
|
4
4
|
import { CONFIG_DIR } from '../../core/utils.js';
|
|
5
|
+
import { atomicWriteSync } from '../../core/atomic-write.js';
|
|
5
6
|
import { createLogger } from '../../core/log.js';
|
|
6
7
|
import { createFileWatchMonitor } from '../../core/resilient-watch.js';
|
|
7
8
|
import { Icons } from '../../core/icons.js';
|
|
@@ -78,6 +79,50 @@ function loadMachinesFromFile(failOnError = true) {
|
|
|
78
79
|
function getMachineRegistry() {
|
|
79
80
|
return _registry;
|
|
80
81
|
}
|
|
82
|
+
// --- Client-reported GPU count ---
|
|
83
|
+
/** Above this a reported number is treated as garbage rather than a machine with that many GPUs. */
|
|
84
|
+
const MAX_PLAUSIBLE_GPUS = 64;
|
|
85
|
+
function isPlausibleGpuCount(value) {
|
|
86
|
+
return typeof value === 'number' && Number.isInteger(value)
|
|
87
|
+
&& value >= 0 && value <= MAX_PLAUSIBLE_GPUS;
|
|
88
|
+
}
|
|
89
|
+
/** Read-modify-write machines.json so every other field of every entry survives. Returns false —
|
|
90
|
+
* leaving the file untouched — when it cannot be parsed or no longer holds the machine. */
|
|
91
|
+
function persistGpuCount(machine, gpuCount) {
|
|
92
|
+
try {
|
|
93
|
+
const parsed = JSON.parse(readFileSync(MACHINES_FILE, 'utf-8'));
|
|
94
|
+
if (!parsed[machine])
|
|
95
|
+
return false;
|
|
96
|
+
parsed[machine].gpuCount = gpuCount;
|
|
97
|
+
atomicWriteSync(MACHINES_FILE, `${JSON.stringify(parsed, null, 2)}\n`);
|
|
98
|
+
return true;
|
|
99
|
+
}
|
|
100
|
+
catch (e) {
|
|
101
|
+
log.error(`Failed to persist gpuCount for ${machine}: ${e.message}`);
|
|
102
|
+
return false;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Reconcile a GPU count a client reported about itself into the registry and machines.json.
|
|
107
|
+
*
|
|
108
|
+
* `null` means the client could not probe (no nvidia-smi, driver down) — that is "unknown", not
|
|
109
|
+
* "zero GPUs", so the configured value stands and the machine is never silently dropped from GPU
|
|
110
|
+
* dispatch. Only machines already in the registry are touched: a client cannot register itself.
|
|
111
|
+
*/
|
|
112
|
+
function applyReportedGpuCount(machine, reported) {
|
|
113
|
+
const entry = _registry[machine];
|
|
114
|
+
if (!entry || !isPlausibleGpuCount(reported))
|
|
115
|
+
return 'skipped';
|
|
116
|
+
if (entry.gpuCount === reported)
|
|
117
|
+
return 'unchanged';
|
|
118
|
+
if (!persistGpuCount(machine, reported))
|
|
119
|
+
return 'skipped';
|
|
120
|
+
const previous = entry.gpuCount;
|
|
121
|
+
entry.gpuCount = reported;
|
|
122
|
+
log.info(`${machine}: gpuCount ${previous} → ${reported} (client-reported)`);
|
|
123
|
+
_adminNotifier?.(`${Icons.refresh} \`${machine}\` gpuCount ${previous} → ${reported} (reported by its client)`);
|
|
124
|
+
return 'updated';
|
|
125
|
+
}
|
|
81
126
|
/**
|
|
82
127
|
* Return the first machine key in the registry as the local/default machine.
|
|
83
128
|
* Falls back to 'local' if no machines are registered.
|
|
@@ -199,4 +244,4 @@ async function processAbortOutcome(args, deps) {
|
|
|
199
244
|
}
|
|
200
245
|
return { handled: true, note: `worker aborted — task blocked (${rawReason.slice(0, 120)})` };
|
|
201
246
|
}
|
|
202
|
-
export { getMachineRegistry, getLocalMachine, loadMachinesFromFile, startMachineRegistryWatcher, stopMachineRegistryWatcher, generateTaskId, buildDispatchSessionName, processSplitOutcome, processAbortOutcome, _testSetRegistry, };
|
|
247
|
+
export { getMachineRegistry, getLocalMachine, applyReportedGpuCount, loadMachinesFromFile, startMachineRegistryWatcher, stopMachineRegistryWatcher, generateTaskId, buildDispatchSessionName, processSplitOutcome, processAbortOutcome, _testSetRegistry, };
|