@ran-sh/dsh-crew 1.9.0 → 1.10.0
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/.claude-plugin/marketplace.json +16 -16
- package/.claude-plugin/plugin.json +14 -14
- package/LICENSE +21 -21
- package/README.de.md +359 -359
- package/README.es.md +359 -359
- package/README.fr.md +359 -359
- package/README.hi.md +359 -359
- package/README.id.md +359 -359
- package/README.ja.md +359 -359
- package/README.ko.md +359 -359
- package/README.md +126 -126
- package/README.pt.md +359 -359
- package/README.ru.md +359 -359
- package/README.th.md +359 -359
- package/README.tr.md +359 -359
- package/README.vi.md +359 -359
- package/README.zh-TW.md +359 -359
- package/README.zh.md +116 -116
- package/agents/ds-flash.md +24 -24
- package/agents/ds-pro.md +24 -24
- package/agents/ds-reviewer.md +23 -23
- package/agents/ds-worker.md +23 -23
- package/bin/dsh-crew.mjs +16 -16
- package/codex/agents/ds-flash.toml +34 -34
- package/codex/agents/ds-pro.toml +34 -34
- package/codex/agents/ds-reviewer.toml +32 -32
- package/codex/agents/ds-worker.toml +32 -32
- package/codex/prompts/dsh-config.md +19 -19
- package/codex/prompts/dsh-status.md +5 -5
- package/commands/config.md +23 -23
- package/commands/off.md +5 -5
- package/commands/on.md +5 -5
- package/commands/status.md +9 -9
- package/cordis.patch.yml +4 -4
- package/docs/gpt-relay-extension.md +103 -103
- package/docs/installation.md +138 -138
- package/docs/job-contracts.md +103 -103
- package/docs/readiness-matrix.md +85 -85
- package/docs/ui-surfaces.md +107 -107
- package/official-web-bridge/cordis.patch.yml +4 -4
- package/official-web-bridge/entry.mjs +1 -1
- package/official-web-bridge/overlay-entry.mjs +59 -59
- package/official-web-bridge/package.json +25 -25
- package/package.json +3 -2
- package/scripts/build-client.mjs +49 -49
- package/scripts/live-crew-smoke.mjs +39 -39
- package/scripts/live-policy-matrix.mjs +177 -177
- package/scripts/policy-probe.mjs +101 -101
- package/scripts/remove-legacy-official-bridge.ps1 +89 -89
- package/scripts/setup.mjs +393 -393
- package/scripts/smoke-real.mjs +110 -110
- package/scripts/smoke.mjs +78 -78
- package/scripts/verify-crew-ui-polish.mjs +145 -145
- package/scripts/verify-history-ui.mjs +97 -97
- package/scripts/verify-installer-fix.mjs +26 -26
- package/scripts/verify-npm-install.mjs +311 -311
- package/scripts/verify-official-bridge-e2e.mjs +192 -192
- package/src/adaptive-routing.mjs +260 -260
- package/src/client/activation-summary.tsx +64 -64
- package/src/client/collapsible-sections.mjs +55 -55
- package/src/client/history-panel.tsx +108 -108
- package/src/client/host-readiness.mjs +71 -71
- package/src/client/index.tsx +1711 -1711
- package/src/client/model-callability-view.mjs +17 -17
- package/src/client/panel-chrome.tsx +40 -40
- package/src/client/quick-entry.tsx +10 -10
- package/src/client/quick-panel.tsx +275 -275
- package/src/client/readiness-envelope.mjs +34 -34
- package/src/client/surface-detection.mjs +43 -43
- package/src/config-readiness.mjs +226 -226
- package/src/credential-reference.mjs +38 -38
- package/src/delivery.mjs +205 -205
- package/src/dsh-cli-runtime.mjs +1021 -1021
- package/src/dsh-cohort.mjs +20 -20
- package/src/extension-contract.mjs +104 -104
- package/src/failure-classification.mjs +201 -201
- package/src/history/admission-gate.mjs +67 -67
- package/src/history/archive-store.mjs +272 -272
- package/src/history/cleanup-plan.mjs +89 -89
- package/src/history/http.mjs +32 -32
- package/src/history/operation.mjs +86 -86
- package/src/history/runner-detach.mjs +34 -34
- package/src/history/runner.mjs +52 -52
- package/src/history/runtime.mjs +36 -36
- package/src/history/service.mjs +177 -177
- package/src/history/state.mjs +27 -27
- package/src/hub/entry.mjs +104 -104
- package/src/hub/index.mjs +2694 -2694
- package/src/hub-client.mjs +154 -154
- package/src/hub-compatibility.mjs +42 -42
- package/src/i18n.mjs +19 -19
- package/src/information-flow.mjs +67 -67
- package/src/install/cli.mjs +28 -28
- package/src/install/install-legacy.mjs +711 -711
- package/src/install/install.mjs +483 -483
- package/src/install/npx-lifecycle.mjs +3456 -3456
- package/src/install/official-frontend-assets.mjs +78 -78
- package/src/install/official-web.mjs +95 -95
- package/src/install/payload-content.mjs +88 -88
- package/src/install/windows-startup.mjs +236 -236
- package/src/install/windows-supervisor-adapter.mjs +443 -443
- package/src/install/windows-supervisor-lifecycle.mjs +782 -782
- package/src/install/zcode.mjs +397 -397
- package/src/job-contracts.mjs +255 -255
- package/src/local-request-guard.mjs +60 -60
- package/src/mcp-runtime.mjs +340 -340
- package/src/model-callability-contract.mjs +79 -79
- package/src/model-catalog.mjs +180 -180
- package/src/model-routing.mjs +586 -586
- package/src/model-schedule.mjs +207 -207
- package/src/official-web-bridge.mjs +447 -447
- package/src/policy.mjs +235 -235
- package/src/provider-delete-adapters.mjs +1934 -1934
- package/src/provider-health.mjs +130 -130
- package/src/provider-inventory.mjs +182 -182
- package/src/provider-layer-migration-adapters.mjs +759 -759
- package/src/provider-layer-migration.mjs +198 -198
- package/src/provider-lifecycle-state.mjs +103 -103
- package/src/provider-lifecycle.mjs +252 -252
- package/src/provider-profile-store.mjs +390 -390
- package/src/provider-settings-store.mjs +633 -633
- package/src/provider-store-lock.mjs +67 -67
- package/src/readiness-matrix.mjs +181 -181
- package/src/removable-waiter.mjs +29 -29
- package/src/role-profiles.mjs +107 -107
- package/src/runtime-controls.mjs +84 -84
- package/src/runtime-identity-contract.mjs +34 -34
- package/src/runtime-identity.mjs +235 -235
- package/src/runtime-readiness-snapshot.mjs +285 -285
- package/src/server.mjs +581 -581
- package/src/session-origins.mjs +60 -60
- package/src/standalone-sdk.mjs +23 -23
- package/src/status-shard.mjs +63 -63
- package/src/structured-error-code.mjs +38 -38
- package/src/supervisor/restart-request.mjs +256 -256
- package/src/workflow-runtime.mjs +739 -739
- package/src/workflow.mjs +155 -155
- package/src/workspace-audit.mjs +231 -231
- package/src/workspace-context.mjs +146 -146
- package/src/workspace-isolation.mjs +463 -455
- package/src/workspace-readiness.mjs +32 -32
- package/statusline/statusline.sh +14 -14
- package/statusline/worker-segment.sh +35 -35
- package/windows/start-dsh-crew.cmd +57 -57
- package/windows/start-dsh-crew.ps1 +1302 -1302
- package/windows/supervisor-control.ps1 +467 -467
- package/worker.cordis.yml +67 -67
- package/zcode/agents/ds-reviewer.md +31 -31
- package/zcode/agents/ds-worker.md +31 -31
- package/zcode/commands/dsh-config.md +17 -17
- package/zcode/commands/dsh-status.md +5 -5
|
@@ -1,443 +1,443 @@
|
|
|
1
|
-
import { spawn } from 'node:child_process';
|
|
2
|
-
import { createHash } from 'node:crypto';
|
|
3
|
-
import { createServer } from 'node:net';
|
|
4
|
-
import { existsSync, readFileSync } from 'node:fs';
|
|
5
|
-
import { join, win32 } from 'node:path';
|
|
6
|
-
import { homedir } from 'node:os';
|
|
7
|
-
|
|
8
|
-
import {
|
|
9
|
-
readMaintenanceSession,
|
|
10
|
-
readSupervisorHeartbeat,
|
|
11
|
-
readSupervisorHeartbeatRecord,
|
|
12
|
-
} from '../supervisor/restart-request.mjs';
|
|
13
|
-
import {
|
|
14
|
-
acquireWindowsSupervisorHandoffLock,
|
|
15
|
-
releaseWindowsSupervisorHandoffLock,
|
|
16
|
-
runWindowsSupervisorHandoff,
|
|
17
|
-
windowsSupervisorHandoffJournalPath,
|
|
18
|
-
windowsSupervisorHandoffLockPath,
|
|
19
|
-
} from './windows-supervisor-lifecycle.mjs';
|
|
20
|
-
import { readWindowsSupervisorAssets } from './windows-startup.mjs';
|
|
21
|
-
|
|
22
|
-
const HASH_RE = /^[a-f0-9]{64}$/u;
|
|
23
|
-
export const PENDING_RUNTIME_ACTIVATION = 'runtime-activation-pending';
|
|
24
|
-
const EXACT_VERSION_RE = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u;
|
|
25
|
-
|
|
26
|
-
function text(value) {
|
|
27
|
-
return typeof value === 'string' && value.trim() ? value.trim() : null;
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
function sameHash(left, right) {
|
|
31
|
-
return typeof left === 'string' && typeof right === 'string' && left.toLowerCase() === right.toLowerCase();
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
export function validateSupervisorRuntime(runtime, { expectedCrewVersion = null, expectedDshVersion = null } = {}) {
|
|
35
|
-
return !!runtime
|
|
36
|
-
&& text(runtime.runtime_id) !== null
|
|
37
|
-
&& runtime.service === 'dsh-crew-hub'
|
|
38
|
-
&& runtime.execution_plane === 'hub-3210'
|
|
39
|
-
&& runtime.profile === 'dsh-crew'
|
|
40
|
-
&& Number(runtime.listen_port) === 3210
|
|
41
|
-
&& Number(runtime.protocol_version) === 1
|
|
42
|
-
&& (!expectedCrewVersion || runtime.runtime_version === expectedCrewVersion)
|
|
43
|
-
&& (!expectedDshVersion || runtime.dsh_version === expectedDshVersion);
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
export function hashSupervisorHelper(file) {
|
|
47
|
-
try { return createHash('sha256').update(readFileSync(file)).digest('hex'); } catch { return null; }
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
export function canonicalWindowsPowerShellPath({
|
|
51
|
-
environment = process.env,
|
|
52
|
-
exists = existsSync,
|
|
53
|
-
} = {}) {
|
|
54
|
-
const systemRoot = text(environment.SystemRoot ?? environment.SYSTEMROOT ?? environment.WINDIR ?? environment.windir);
|
|
55
|
-
if (!systemRoot || !win32.isAbsolute(systemRoot)) return null;
|
|
56
|
-
const candidate = win32.join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
|
|
57
|
-
return exists(candidate) ? candidate : null;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
function samePath(left, right) {
|
|
61
|
-
return typeof left === 'string'
|
|
62
|
-
&& typeof right === 'string'
|
|
63
|
-
&& left.replaceAll('/', '\\').toLowerCase() === right.replaceAll('/', '\\').toLowerCase();
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
export function runWindowsSupervisorControl(request, {
|
|
67
|
-
controlScript,
|
|
68
|
-
timeoutMs = 60_000,
|
|
69
|
-
maxOutputBytes = 64 * 1024,
|
|
70
|
-
spawnImpl = spawn,
|
|
71
|
-
environment = process.env,
|
|
72
|
-
exists = existsSync,
|
|
73
|
-
} = {}) {
|
|
74
|
-
return new Promise((resolve) => {
|
|
75
|
-
if (!text(controlScript)) {
|
|
76
|
-
resolve({ ok: false, code: 'SUPERVISOR_CONTROL_SCRIPT_MISSING' });
|
|
77
|
-
return;
|
|
78
|
-
}
|
|
79
|
-
const powerShell = canonicalWindowsPowerShellPath({ environment, exists });
|
|
80
|
-
if (!powerShell) {
|
|
81
|
-
resolve({ ok: false, code: 'SUPERVISOR_CONTROL_POWERSHELL_UNAVAILABLE' });
|
|
82
|
-
return;
|
|
83
|
-
}
|
|
84
|
-
let child;
|
|
85
|
-
try {
|
|
86
|
-
child = spawnImpl(powerShell, [
|
|
87
|
-
'-NoLogo', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass',
|
|
88
|
-
'-File', controlScript,
|
|
89
|
-
], { windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
90
|
-
} catch {
|
|
91
|
-
resolve({ ok: false, code: 'SUPERVISOR_CONTROL_START_FAILED' });
|
|
92
|
-
return;
|
|
93
|
-
}
|
|
94
|
-
let stdout = '';
|
|
95
|
-
let stderr = '';
|
|
96
|
-
let settled = false;
|
|
97
|
-
let timer = null;
|
|
98
|
-
const finish = (result) => {
|
|
99
|
-
if (settled) return;
|
|
100
|
-
settled = true;
|
|
101
|
-
clearTimeout(timer);
|
|
102
|
-
resolve(result);
|
|
103
|
-
};
|
|
104
|
-
const append = (current, chunk) => {
|
|
105
|
-
const next = current + String(chunk);
|
|
106
|
-
if (Buffer.byteLength(next, 'utf8') > maxOutputBytes) {
|
|
107
|
-
try { child.kill(); } catch {}
|
|
108
|
-
finish({ ok: false, code: 'SUPERVISOR_CONTROL_OUTPUT_LIMIT' });
|
|
109
|
-
return current;
|
|
110
|
-
}
|
|
111
|
-
return next;
|
|
112
|
-
};
|
|
113
|
-
child.stdout?.setEncoding('utf8');
|
|
114
|
-
child.stderr?.setEncoding('utf8');
|
|
115
|
-
child.stdout?.on('data', (chunk) => { stdout = append(stdout, chunk); });
|
|
116
|
-
child.stderr?.on('data', (chunk) => { stderr = append(stderr, chunk); });
|
|
117
|
-
child.on('error', () => finish({ ok: false, code: 'SUPERVISOR_CONTROL_START_FAILED' }));
|
|
118
|
-
child.on('close', (code) => {
|
|
119
|
-
if (settled) return;
|
|
120
|
-
let parsed = null;
|
|
121
|
-
try { parsed = JSON.parse(stdout.trim()); } catch {}
|
|
122
|
-
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
123
|
-
finish({ ok: false, code: 'SUPERVISOR_CONTROL_RESPONSE_INVALID', detail: stderr.trim().slice(-300) || null });
|
|
124
|
-
return;
|
|
125
|
-
}
|
|
126
|
-
finish(code === 0 && parsed.ok === true
|
|
127
|
-
? parsed
|
|
128
|
-
: { ok: false, code: text(parsed.code) ?? 'SUPERVISOR_CONTROL_FAILED', error: text(parsed.error) ?? null });
|
|
129
|
-
});
|
|
130
|
-
timer = setTimeout(() => {
|
|
131
|
-
try { child.kill(); } catch {}
|
|
132
|
-
finish({ ok: false, code: 'SUPERVISOR_CONTROL_TIMEOUT' });
|
|
133
|
-
}, timeoutMs);
|
|
134
|
-
timer.unref?.();
|
|
135
|
-
try { child.stdin.end(JSON.stringify(request)); } catch { finish({ ok: false, code: 'SUPERVISOR_CONTROL_STDIN_FAILED' }); }
|
|
136
|
-
});
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
function portFree(port = 3210) {
|
|
140
|
-
return new Promise((resolve) => {
|
|
141
|
-
const server = createServer();
|
|
142
|
-
server.unref();
|
|
143
|
-
server.once('error', () => resolve({ ok: true, free: false }));
|
|
144
|
-
server.listen({ host: '127.0.0.1', port, exclusive: true }, () => {
|
|
145
|
-
server.close(() => resolve({ ok: true, free: true }));
|
|
146
|
-
});
|
|
147
|
-
});
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
async function runtimeFromHub(fetchImpl = globalThis.fetch, timeoutMs = 3_000) {
|
|
151
|
-
try {
|
|
152
|
-
const response = await fetchImpl('http://127.0.0.1:3210/_dsh/dsh-crew/extension', {
|
|
153
|
-
headers: { accept: 'application/json' },
|
|
154
|
-
signal: AbortSignal.timeout(Math.max(1, Math.min(3_000, timeoutMs))),
|
|
155
|
-
});
|
|
156
|
-
if (!response.ok) return null;
|
|
157
|
-
const body = await response.json();
|
|
158
|
-
return body?.ok === true ? body.extension?.runtime ?? null : null;
|
|
159
|
-
} catch { return null; }
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
function watcherRequest(operation, target, expected = null, { allowHelperDrift = false } = {}) {
|
|
163
|
-
return {
|
|
164
|
-
operation,
|
|
165
|
-
helper_path: target.helper_path,
|
|
166
|
-
...(expected ? { expected } : {}),
|
|
167
|
-
...(allowHelperDrift ? { allow_helper_drift: true } : {}),
|
|
168
|
-
...(operation === 'start' ? { helper_hash: target.helper_hash } : {}),
|
|
169
|
-
};
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
export function createWindowsSupervisorHandoffHooks({
|
|
173
|
-
appRoot = null,
|
|
174
|
-
target,
|
|
175
|
-
maintenanceClient,
|
|
176
|
-
expectedCrewVersion = null,
|
|
177
|
-
expectedDshVersion = null,
|
|
178
|
-
readHeartbeatRecord = () => readSupervisorHeartbeatRecord(appRoot, { staleAfterMs: 30_000 }),
|
|
179
|
-
readAuthoritativeHeartbeat = () => readSupervisorHeartbeat(appRoot, { staleAfterMs: 30_000 }),
|
|
180
|
-
runControl,
|
|
181
|
-
controlScript,
|
|
182
|
-
fetchRuntime = ({ timeoutMs = 3_000 } = {}) => runtimeFromHub(globalThis.fetch, timeoutMs),
|
|
183
|
-
verifyPortFree = ({ port }) => portFree(port),
|
|
184
|
-
sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
|
185
|
-
readyTimeoutMs = 90_000,
|
|
186
|
-
heartbeatRecoveryAttempts = 180,
|
|
187
|
-
heartbeatRecoveryPollMs = 500,
|
|
188
|
-
now = Date.now,
|
|
189
|
-
} = {}) {
|
|
190
|
-
const control = runControl ?? ((request) => runWindowsSupervisorControl(request, { controlScript }));
|
|
191
|
-
|
|
192
|
-
const inspect = async (expected, { allowHelperDrift = false } = {}) => control(watcherRequest(
|
|
193
|
-
'inspect', target, expected, { allowHelperDrift },
|
|
194
|
-
));
|
|
195
|
-
const classifyHeartbeat = async ({
|
|
196
|
-
expect_target: expectTarget = false,
|
|
197
|
-
attempt = 0,
|
|
198
|
-
deadline = null,
|
|
199
|
-
live_runtime_seen: liveRuntimeSeen = false,
|
|
200
|
-
} = {}) => {
|
|
201
|
-
const cutoff = Number.isFinite(deadline) ? deadline : now() + readyTimeoutMs;
|
|
202
|
-
const remaining = () => Math.max(0, cutoff - now());
|
|
203
|
-
const fetchWithinBudget = async () => {
|
|
204
|
-
const budget = remaining();
|
|
205
|
-
return budget > 0 ? fetchRuntime({ timeoutMs: Math.min(3_000, budget) }) : null;
|
|
206
|
-
};
|
|
207
|
-
const retry = async (sawLive) => {
|
|
208
|
-
const budget = remaining();
|
|
209
|
-
if (attempt >= heartbeatRecoveryAttempts || budget <= 0) return null;
|
|
210
|
-
await sleep(Math.min(heartbeatRecoveryPollMs, budget));
|
|
211
|
-
return classifyHeartbeat({
|
|
212
|
-
expect_target: expectTarget,
|
|
213
|
-
attempt: attempt + 1,
|
|
214
|
-
deadline: cutoff,
|
|
215
|
-
live_runtime_seen: sawLive,
|
|
216
|
-
});
|
|
217
|
-
};
|
|
218
|
-
const observed = readHeartbeatRecord();
|
|
219
|
-
let runtime = null;
|
|
220
|
-
if (!observed) {
|
|
221
|
-
runtime = await fetchWithinBudget();
|
|
222
|
-
const sawLive = liveRuntimeSeen || !!runtime?.runtime_id;
|
|
223
|
-
if (sawLive || expectTarget) {
|
|
224
|
-
const retried = await retry(sawLive);
|
|
225
|
-
if (retried) return retried;
|
|
226
|
-
}
|
|
227
|
-
if (sawLive) return { ok: false, code: 'SUPERVISOR_HEARTBEAT_MISSING_WITH_LIVE_RUNTIME' };
|
|
228
|
-
if (expectTarget) return { ok: false, code: 'SUPERVISOR_TARGET_HEARTBEAT_TIMEOUT' };
|
|
229
|
-
return { ok: true, classification: 'absent', watcher: null, runtime_id: null };
|
|
230
|
-
}
|
|
231
|
-
const record = observed.record ?? {};
|
|
232
|
-
const expected = {
|
|
233
|
-
pid: record.pid,
|
|
234
|
-
...(record.process_started_at_utc_ticks ? { process_started_at_utc_ticks: String(record.process_started_at_utc_ticks) } : {}),
|
|
235
|
-
...(record.helper_hash ? { helper_hash: record.helper_hash } : {}),
|
|
236
|
-
};
|
|
237
|
-
const fullyAttestedStale = observed.state !== 'legacy-v1'
|
|
238
|
-
&& expected.process_started_at_utc_ticks
|
|
239
|
-
&& expected.helper_hash
|
|
240
|
-
&& !sameHash(expected.helper_hash, target.helper_hash);
|
|
241
|
-
const inspected = await inspect(expected, { allowHelperDrift: fullyAttestedStale });
|
|
242
|
-
if (inspected?.ok === false && inspected.code === 'PROCESS_NOT_FOUND') {
|
|
243
|
-
if (expectTarget) {
|
|
244
|
-
const retried = await retry(liveRuntimeSeen);
|
|
245
|
-
if (retried) return retried;
|
|
246
|
-
}
|
|
247
|
-
runtime ??= await fetchWithinBudget();
|
|
248
|
-
if (runtime?.runtime_id) {
|
|
249
|
-
return { ok: false, code: 'SUPERVISOR_HEARTBEAT_PROCESS_MISSING_WITH_LIVE_RUNTIME' };
|
|
250
|
-
}
|
|
251
|
-
if (expectTarget) {
|
|
252
|
-
return {
|
|
253
|
-
ok: false,
|
|
254
|
-
code: liveRuntimeSeen
|
|
255
|
-
? 'SUPERVISOR_HEARTBEAT_PROCESS_MISSING_WITH_LIVE_RUNTIME'
|
|
256
|
-
: 'SUPERVISOR_TARGET_HEARTBEAT_TIMEOUT',
|
|
257
|
-
};
|
|
258
|
-
}
|
|
259
|
-
return { ok: true, classification: 'absent', watcher: null, runtime_id: null };
|
|
260
|
-
}
|
|
261
|
-
if (inspected?.ok !== true || !inspected.watcher) return inspected ?? { ok: false, code: 'SUPERVISOR_WATCHER_UNVERIFIED' };
|
|
262
|
-
runtime ??= await fetchWithinBudget();
|
|
263
|
-
if (observed.state === 'legacy-v1') {
|
|
264
|
-
return runtime?.runtime_id
|
|
265
|
-
? { ok: true, classification: 'legacy', watcher: inspected.watcher, runtime_id: runtime.runtime_id }
|
|
266
|
-
: { ok: false, code: 'SUPERVISOR_RUNTIME_IDENTITY_UNAVAILABLE' };
|
|
267
|
-
}
|
|
268
|
-
const targetHash = sameHash(record.helper_hash, target.helper_hash);
|
|
269
|
-
if (targetHash && observed.state === 'ready') {
|
|
270
|
-
return runtime?.runtime_id
|
|
271
|
-
? { ok: true, classification: 'target-ready', watcher: inspected.watcher, runtime_id: runtime.runtime_id }
|
|
272
|
-
: { ok: false, code: 'SUPERVISOR_RUNTIME_IDENTITY_UNAVAILABLE' };
|
|
273
|
-
}
|
|
274
|
-
if (targetHash) return { ok: true, classification: 'target-starting', watcher: inspected.watcher, runtime_id: runtime?.runtime_id ?? null };
|
|
275
|
-
return runtime?.runtime_id
|
|
276
|
-
? { ok: true, classification: 'stale', watcher: inspected.watcher, runtime_id: runtime.runtime_id }
|
|
277
|
-
: { ok: false, code: 'SUPERVISOR_RUNTIME_IDENTITY_UNAVAILABLE' };
|
|
278
|
-
};
|
|
279
|
-
return {
|
|
280
|
-
classifyHeartbeat,
|
|
281
|
-
verifyExactWatcher: async ({ expected, role }) => inspect(expected, {
|
|
282
|
-
allowHelperDrift: role === 'old' && !sameHash(expected?.helper_hash, target.helper_hash),
|
|
283
|
-
}),
|
|
284
|
-
maintenanceStop: async ({ lease, runtime_id: runtimeId }) => maintenanceClient?.stopOwnedBackend?.({ lease, runtimeId })
|
|
285
|
-
?? { ok: false, code: 'SUPERVISOR_MAINTENANCE_UNAVAILABLE' },
|
|
286
|
-
maintenanceStatus: async ({ lease, runtime_id: runtimeId }) => {
|
|
287
|
-
const durable = readMaintenanceSession(appRoot);
|
|
288
|
-
if (!durable.ok) return durable;
|
|
289
|
-
if (durable.state === 'absent') return { ok: true, state: 'absent' };
|
|
290
|
-
const session = durable.session;
|
|
291
|
-
return session.lease === lease && session.runtime_id === runtimeId
|
|
292
|
-
? { ok: true, state: 'matching', lease, runtime_id: runtimeId, request_id: session.request_id }
|
|
293
|
-
: { ok: true, state: 'conflict', lease: session.lease, runtime_id: session.runtime_id };
|
|
294
|
-
},
|
|
295
|
-
verifyPortFree,
|
|
296
|
-
stopExactWatcher: async ({ expected }) => control(watcherRequest('stop', target, expected, {
|
|
297
|
-
allowHelperDrift: !sameHash(expected?.helper_hash, target.helper_hash),
|
|
298
|
-
})),
|
|
299
|
-
launchTargetWatcher: async () => control(watcherRequest('start', target)),
|
|
300
|
-
maintenanceStart: async ({ lease, runtime_id: runtimeId }) => maintenanceClient?.startOwnedBackend?.({
|
|
301
|
-
lease,
|
|
302
|
-
runtimeId,
|
|
303
|
-
expectedCrewVersion,
|
|
304
|
-
expectedDshVersion,
|
|
305
|
-
}) ?? { ok: false, code: 'SUPERVISOR_MAINTENANCE_UNAVAILABLE' },
|
|
306
|
-
verifyReady: async ({ previous_runtime_id: previousRuntimeId }) => {
|
|
307
|
-
const deadline = now() + readyTimeoutMs;
|
|
308
|
-
while (now() <= deadline) {
|
|
309
|
-
const heartbeat = readAuthoritativeHeartbeat();
|
|
310
|
-
if (heartbeat && sameHash(heartbeat.helper_hash, target.helper_hash)) {
|
|
311
|
-
const exact = await inspect({
|
|
312
|
-
pid: heartbeat.pid,
|
|
313
|
-
process_started_at_utc_ticks: String(heartbeat.process_started_at_utc_ticks),
|
|
314
|
-
helper_hash: heartbeat.helper_hash,
|
|
315
|
-
});
|
|
316
|
-
const runtime = await fetchRuntime({ timeoutMs: Math.max(1, Math.min(3_000, deadline - now())) });
|
|
317
|
-
if (exact?.ok === true
|
|
318
|
-
&& exact.watcher
|
|
319
|
-
&& validateSupervisorRuntime(runtime, { expectedCrewVersion, expectedDshVersion })
|
|
320
|
-
&& (!previousRuntimeId || runtime.runtime_id !== previousRuntimeId)) {
|
|
321
|
-
return { ok: true, watcher: exact.watcher, runtime };
|
|
322
|
-
}
|
|
323
|
-
}
|
|
324
|
-
await sleep(500);
|
|
325
|
-
}
|
|
326
|
-
return { ok: false, code: 'SUPERVISOR_READY_TIMEOUT' };
|
|
327
|
-
},
|
|
328
|
-
};
|
|
329
|
-
}
|
|
330
|
-
|
|
331
|
-
function prepareWindowsSupervisorConvergence({ home, root, platform }) {
|
|
332
|
-
if (platform !== 'win32') return { ok: true, skipped: true, reason: 'unsupported-platform' };
|
|
333
|
-
const appRoot = join(home, '.config', 'dsh-crew');
|
|
334
|
-
const assets = readWindowsSupervisorAssets({ home });
|
|
335
|
-
if (!assets.ok || !HASH_RE.test(assets.helper_hash) || !HASH_RE.test(assets.control_hash)) {
|
|
336
|
-
return { ok: false, code: 'SUPERVISOR_TARGET_UNAVAILABLE' };
|
|
337
|
-
}
|
|
338
|
-
let manifest = null;
|
|
339
|
-
try { manifest = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')); } catch {}
|
|
340
|
-
const expectedCrewVersion = text(manifest?.version);
|
|
341
|
-
let expectedDshVersion = text(manifest?.dependencies?.['@deepseek-ai/dsh'] ?? manifest?.peerDependencies?.['@deepseek-ai/dsh']);
|
|
342
|
-
if (!EXACT_VERSION_RE.test(expectedDshVersion ?? '')) {
|
|
343
|
-
try {
|
|
344
|
-
const cohort = JSON.parse(readFileSync(join(root, 'release-cohort.json'), 'utf8'));
|
|
345
|
-
expectedDshVersion = text(cohort?.dsh_version);
|
|
346
|
-
} catch { expectedDshVersion = null; }
|
|
347
|
-
}
|
|
348
|
-
if (manifest?.name !== '@ran-sh/dsh-crew'
|
|
349
|
-
|| !EXACT_VERSION_RE.test(expectedCrewVersion ?? '')
|
|
350
|
-
|| !EXACT_VERSION_RE.test(expectedDshVersion ?? '')) {
|
|
351
|
-
return { ok: false, code: 'SUPERVISOR_TARGET_UNAVAILABLE' };
|
|
352
|
-
}
|
|
353
|
-
return {
|
|
354
|
-
ok: true,
|
|
355
|
-
home,
|
|
356
|
-
root,
|
|
357
|
-
appRoot,
|
|
358
|
-
target: {
|
|
359
|
-
helper_path: assets.helper_path,
|
|
360
|
-
helper_hash: assets.helper_hash,
|
|
361
|
-
control_path: assets.control_path,
|
|
362
|
-
control_hash: assets.control_hash,
|
|
363
|
-
},
|
|
364
|
-
controlScript: assets.control_path,
|
|
365
|
-
controlHash: assets.control_hash,
|
|
366
|
-
expectedCrewVersion,
|
|
367
|
-
expectedDshVersion,
|
|
368
|
-
};
|
|
369
|
-
}
|
|
370
|
-
|
|
371
|
-
export function windowsSupervisorConvergencePending({ home = homedir() } = {}) {
|
|
372
|
-
const appRoot = join(home, '.config', 'dsh-crew');
|
|
373
|
-
return existsSync(windowsSupervisorHandoffJournalPath(appRoot))
|
|
374
|
-
|| existsSync(windowsSupervisorHandoffLockPath(appRoot));
|
|
375
|
-
}
|
|
376
|
-
|
|
377
|
-
export function reserveWindowsSupervisorConvergence({
|
|
378
|
-
home = homedir(),
|
|
379
|
-
root,
|
|
380
|
-
platform = process.platform,
|
|
381
|
-
} = {}) {
|
|
382
|
-
const prepared = prepareWindowsSupervisorConvergence({ home, root, platform });
|
|
383
|
-
if (!prepared.ok || prepared.skipped) return prepared;
|
|
384
|
-
const lock = acquireWindowsSupervisorHandoffLock({ appRoot: prepared.appRoot });
|
|
385
|
-
return lock.ok ? { ...prepared, lock } : { ok: false, code: lock.code, error: lock.error ?? null };
|
|
386
|
-
}
|
|
387
|
-
|
|
388
|
-
export function releaseWindowsSupervisorConvergenceReservation(reservation) {
|
|
389
|
-
if (!reservation?.lock) return { ok: false, code: 'SUPERVISOR_RESERVATION_INVALID' };
|
|
390
|
-
return releaseWindowsSupervisorHandoffLock(reservation.lock);
|
|
391
|
-
}
|
|
392
|
-
|
|
393
|
-
export async function convergeWindowsSupervisor({
|
|
394
|
-
home = homedir(),
|
|
395
|
-
root,
|
|
396
|
-
maintenanceClient,
|
|
397
|
-
platform = process.platform,
|
|
398
|
-
runControl,
|
|
399
|
-
fetchRuntime,
|
|
400
|
-
readHeartbeatRecord,
|
|
401
|
-
readAuthoritativeHeartbeat,
|
|
402
|
-
verifyPortFree,
|
|
403
|
-
sleep,
|
|
404
|
-
reservation = null,
|
|
405
|
-
} = {}) {
|
|
406
|
-
const prepared = prepareWindowsSupervisorConvergence({ home, root, platform });
|
|
407
|
-
if (!prepared.ok || prepared.skipped) {
|
|
408
|
-
if (reservation?.lock) releaseWindowsSupervisorHandoffLock(reservation.lock);
|
|
409
|
-
return prepared;
|
|
410
|
-
}
|
|
411
|
-
if (reservation && (!reservation.ok
|
|
412
|
-
|| !samePath(reservation.root, prepared.root)
|
|
413
|
-
|| !samePath(reservation.target?.helper_path, prepared.target.helper_path)
|
|
414
|
-
|| !sameHash(reservation.target?.helper_hash, prepared.target.helper_hash)
|
|
415
|
-
|| !samePath(reservation.target?.control_path, prepared.target.control_path)
|
|
416
|
-
|| !sameHash(reservation.target?.control_hash, prepared.target.control_hash)
|
|
417
|
-
|| reservation.expectedCrewVersion !== prepared.expectedCrewVersion
|
|
418
|
-
|| reservation.expectedDshVersion !== prepared.expectedDshVersion)) {
|
|
419
|
-
if (reservation?.lock) releaseWindowsSupervisorHandoffLock(reservation.lock);
|
|
420
|
-
return { ok: false, code: 'SUPERVISOR_RESERVATION_MISMATCH' };
|
|
421
|
-
}
|
|
422
|
-
const hooks = createWindowsSupervisorHandoffHooks({
|
|
423
|
-
appRoot: prepared.appRoot,
|
|
424
|
-
target: prepared.target,
|
|
425
|
-
maintenanceClient,
|
|
426
|
-
expectedCrewVersion: prepared.expectedCrewVersion,
|
|
427
|
-
expectedDshVersion: prepared.expectedDshVersion,
|
|
428
|
-
controlScript: prepared.controlScript,
|
|
429
|
-
runControl,
|
|
430
|
-
fetchRuntime,
|
|
431
|
-
readHeartbeatRecord,
|
|
432
|
-
readAuthoritativeHeartbeat,
|
|
433
|
-
verifyPortFree,
|
|
434
|
-
sleep,
|
|
435
|
-
});
|
|
436
|
-
return runWindowsSupervisorHandoff({
|
|
437
|
-
appRoot: prepared.appRoot,
|
|
438
|
-
target: prepared.target,
|
|
439
|
-
hooks,
|
|
440
|
-
preAcquiredLock: reservation?.lock ?? null,
|
|
441
|
-
forceRestart: existsSync(join(root, PENDING_RUNTIME_ACTIVATION)),
|
|
442
|
-
});
|
|
443
|
-
}
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { createServer } from 'node:net';
|
|
4
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
5
|
+
import { join, win32 } from 'node:path';
|
|
6
|
+
import { homedir } from 'node:os';
|
|
7
|
+
|
|
8
|
+
import {
|
|
9
|
+
readMaintenanceSession,
|
|
10
|
+
readSupervisorHeartbeat,
|
|
11
|
+
readSupervisorHeartbeatRecord,
|
|
12
|
+
} from '../supervisor/restart-request.mjs';
|
|
13
|
+
import {
|
|
14
|
+
acquireWindowsSupervisorHandoffLock,
|
|
15
|
+
releaseWindowsSupervisorHandoffLock,
|
|
16
|
+
runWindowsSupervisorHandoff,
|
|
17
|
+
windowsSupervisorHandoffJournalPath,
|
|
18
|
+
windowsSupervisorHandoffLockPath,
|
|
19
|
+
} from './windows-supervisor-lifecycle.mjs';
|
|
20
|
+
import { readWindowsSupervisorAssets } from './windows-startup.mjs';
|
|
21
|
+
|
|
22
|
+
const HASH_RE = /^[a-f0-9]{64}$/u;
|
|
23
|
+
export const PENDING_RUNTIME_ACTIVATION = 'runtime-activation-pending';
|
|
24
|
+
const EXACT_VERSION_RE = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u;
|
|
25
|
+
|
|
26
|
+
function text(value) {
|
|
27
|
+
return typeof value === 'string' && value.trim() ? value.trim() : null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function sameHash(left, right) {
|
|
31
|
+
return typeof left === 'string' && typeof right === 'string' && left.toLowerCase() === right.toLowerCase();
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function validateSupervisorRuntime(runtime, { expectedCrewVersion = null, expectedDshVersion = null } = {}) {
|
|
35
|
+
return !!runtime
|
|
36
|
+
&& text(runtime.runtime_id) !== null
|
|
37
|
+
&& runtime.service === 'dsh-crew-hub'
|
|
38
|
+
&& runtime.execution_plane === 'hub-3210'
|
|
39
|
+
&& runtime.profile === 'dsh-crew'
|
|
40
|
+
&& Number(runtime.listen_port) === 3210
|
|
41
|
+
&& Number(runtime.protocol_version) === 1
|
|
42
|
+
&& (!expectedCrewVersion || runtime.runtime_version === expectedCrewVersion)
|
|
43
|
+
&& (!expectedDshVersion || runtime.dsh_version === expectedDshVersion);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function hashSupervisorHelper(file) {
|
|
47
|
+
try { return createHash('sha256').update(readFileSync(file)).digest('hex'); } catch { return null; }
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function canonicalWindowsPowerShellPath({
|
|
51
|
+
environment = process.env,
|
|
52
|
+
exists = existsSync,
|
|
53
|
+
} = {}) {
|
|
54
|
+
const systemRoot = text(environment.SystemRoot ?? environment.SYSTEMROOT ?? environment.WINDIR ?? environment.windir);
|
|
55
|
+
if (!systemRoot || !win32.isAbsolute(systemRoot)) return null;
|
|
56
|
+
const candidate = win32.join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
|
|
57
|
+
return exists(candidate) ? candidate : null;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function samePath(left, right) {
|
|
61
|
+
return typeof left === 'string'
|
|
62
|
+
&& typeof right === 'string'
|
|
63
|
+
&& left.replaceAll('/', '\\').toLowerCase() === right.replaceAll('/', '\\').toLowerCase();
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function runWindowsSupervisorControl(request, {
|
|
67
|
+
controlScript,
|
|
68
|
+
timeoutMs = 60_000,
|
|
69
|
+
maxOutputBytes = 64 * 1024,
|
|
70
|
+
spawnImpl = spawn,
|
|
71
|
+
environment = process.env,
|
|
72
|
+
exists = existsSync,
|
|
73
|
+
} = {}) {
|
|
74
|
+
return new Promise((resolve) => {
|
|
75
|
+
if (!text(controlScript)) {
|
|
76
|
+
resolve({ ok: false, code: 'SUPERVISOR_CONTROL_SCRIPT_MISSING' });
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
const powerShell = canonicalWindowsPowerShellPath({ environment, exists });
|
|
80
|
+
if (!powerShell) {
|
|
81
|
+
resolve({ ok: false, code: 'SUPERVISOR_CONTROL_POWERSHELL_UNAVAILABLE' });
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
let child;
|
|
85
|
+
try {
|
|
86
|
+
child = spawnImpl(powerShell, [
|
|
87
|
+
'-NoLogo', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass',
|
|
88
|
+
'-File', controlScript,
|
|
89
|
+
], { windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
90
|
+
} catch {
|
|
91
|
+
resolve({ ok: false, code: 'SUPERVISOR_CONTROL_START_FAILED' });
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
let stdout = '';
|
|
95
|
+
let stderr = '';
|
|
96
|
+
let settled = false;
|
|
97
|
+
let timer = null;
|
|
98
|
+
const finish = (result) => {
|
|
99
|
+
if (settled) return;
|
|
100
|
+
settled = true;
|
|
101
|
+
clearTimeout(timer);
|
|
102
|
+
resolve(result);
|
|
103
|
+
};
|
|
104
|
+
const append = (current, chunk) => {
|
|
105
|
+
const next = current + String(chunk);
|
|
106
|
+
if (Buffer.byteLength(next, 'utf8') > maxOutputBytes) {
|
|
107
|
+
try { child.kill(); } catch {}
|
|
108
|
+
finish({ ok: false, code: 'SUPERVISOR_CONTROL_OUTPUT_LIMIT' });
|
|
109
|
+
return current;
|
|
110
|
+
}
|
|
111
|
+
return next;
|
|
112
|
+
};
|
|
113
|
+
child.stdout?.setEncoding('utf8');
|
|
114
|
+
child.stderr?.setEncoding('utf8');
|
|
115
|
+
child.stdout?.on('data', (chunk) => { stdout = append(stdout, chunk); });
|
|
116
|
+
child.stderr?.on('data', (chunk) => { stderr = append(stderr, chunk); });
|
|
117
|
+
child.on('error', () => finish({ ok: false, code: 'SUPERVISOR_CONTROL_START_FAILED' }));
|
|
118
|
+
child.on('close', (code) => {
|
|
119
|
+
if (settled) return;
|
|
120
|
+
let parsed = null;
|
|
121
|
+
try { parsed = JSON.parse(stdout.trim()); } catch {}
|
|
122
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
123
|
+
finish({ ok: false, code: 'SUPERVISOR_CONTROL_RESPONSE_INVALID', detail: stderr.trim().slice(-300) || null });
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
finish(code === 0 && parsed.ok === true
|
|
127
|
+
? parsed
|
|
128
|
+
: { ok: false, code: text(parsed.code) ?? 'SUPERVISOR_CONTROL_FAILED', error: text(parsed.error) ?? null });
|
|
129
|
+
});
|
|
130
|
+
timer = setTimeout(() => {
|
|
131
|
+
try { child.kill(); } catch {}
|
|
132
|
+
finish({ ok: false, code: 'SUPERVISOR_CONTROL_TIMEOUT' });
|
|
133
|
+
}, timeoutMs);
|
|
134
|
+
timer.unref?.();
|
|
135
|
+
try { child.stdin.end(JSON.stringify(request)); } catch { finish({ ok: false, code: 'SUPERVISOR_CONTROL_STDIN_FAILED' }); }
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function portFree(port = 3210) {
|
|
140
|
+
return new Promise((resolve) => {
|
|
141
|
+
const server = createServer();
|
|
142
|
+
server.unref();
|
|
143
|
+
server.once('error', () => resolve({ ok: true, free: false }));
|
|
144
|
+
server.listen({ host: '127.0.0.1', port, exclusive: true }, () => {
|
|
145
|
+
server.close(() => resolve({ ok: true, free: true }));
|
|
146
|
+
});
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
async function runtimeFromHub(fetchImpl = globalThis.fetch, timeoutMs = 3_000) {
|
|
151
|
+
try {
|
|
152
|
+
const response = await fetchImpl('http://127.0.0.1:3210/_dsh/dsh-crew/extension', {
|
|
153
|
+
headers: { accept: 'application/json' },
|
|
154
|
+
signal: AbortSignal.timeout(Math.max(1, Math.min(3_000, timeoutMs))),
|
|
155
|
+
});
|
|
156
|
+
if (!response.ok) return null;
|
|
157
|
+
const body = await response.json();
|
|
158
|
+
return body?.ok === true ? body.extension?.runtime ?? null : null;
|
|
159
|
+
} catch { return null; }
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function watcherRequest(operation, target, expected = null, { allowHelperDrift = false } = {}) {
|
|
163
|
+
return {
|
|
164
|
+
operation,
|
|
165
|
+
helper_path: target.helper_path,
|
|
166
|
+
...(expected ? { expected } : {}),
|
|
167
|
+
...(allowHelperDrift ? { allow_helper_drift: true } : {}),
|
|
168
|
+
...(operation === 'start' ? { helper_hash: target.helper_hash } : {}),
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export function createWindowsSupervisorHandoffHooks({
|
|
173
|
+
appRoot = null,
|
|
174
|
+
target,
|
|
175
|
+
maintenanceClient,
|
|
176
|
+
expectedCrewVersion = null,
|
|
177
|
+
expectedDshVersion = null,
|
|
178
|
+
readHeartbeatRecord = () => readSupervisorHeartbeatRecord(appRoot, { staleAfterMs: 30_000 }),
|
|
179
|
+
readAuthoritativeHeartbeat = () => readSupervisorHeartbeat(appRoot, { staleAfterMs: 30_000 }),
|
|
180
|
+
runControl,
|
|
181
|
+
controlScript,
|
|
182
|
+
fetchRuntime = ({ timeoutMs = 3_000 } = {}) => runtimeFromHub(globalThis.fetch, timeoutMs),
|
|
183
|
+
verifyPortFree = ({ port }) => portFree(port),
|
|
184
|
+
sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
|
185
|
+
readyTimeoutMs = 90_000,
|
|
186
|
+
heartbeatRecoveryAttempts = 180,
|
|
187
|
+
heartbeatRecoveryPollMs = 500,
|
|
188
|
+
now = Date.now,
|
|
189
|
+
} = {}) {
|
|
190
|
+
const control = runControl ?? ((request) => runWindowsSupervisorControl(request, { controlScript }));
|
|
191
|
+
|
|
192
|
+
const inspect = async (expected, { allowHelperDrift = false } = {}) => control(watcherRequest(
|
|
193
|
+
'inspect', target, expected, { allowHelperDrift },
|
|
194
|
+
));
|
|
195
|
+
const classifyHeartbeat = async ({
|
|
196
|
+
expect_target: expectTarget = false,
|
|
197
|
+
attempt = 0,
|
|
198
|
+
deadline = null,
|
|
199
|
+
live_runtime_seen: liveRuntimeSeen = false,
|
|
200
|
+
} = {}) => {
|
|
201
|
+
const cutoff = Number.isFinite(deadline) ? deadline : now() + readyTimeoutMs;
|
|
202
|
+
const remaining = () => Math.max(0, cutoff - now());
|
|
203
|
+
const fetchWithinBudget = async () => {
|
|
204
|
+
const budget = remaining();
|
|
205
|
+
return budget > 0 ? fetchRuntime({ timeoutMs: Math.min(3_000, budget) }) : null;
|
|
206
|
+
};
|
|
207
|
+
const retry = async (sawLive) => {
|
|
208
|
+
const budget = remaining();
|
|
209
|
+
if (attempt >= heartbeatRecoveryAttempts || budget <= 0) return null;
|
|
210
|
+
await sleep(Math.min(heartbeatRecoveryPollMs, budget));
|
|
211
|
+
return classifyHeartbeat({
|
|
212
|
+
expect_target: expectTarget,
|
|
213
|
+
attempt: attempt + 1,
|
|
214
|
+
deadline: cutoff,
|
|
215
|
+
live_runtime_seen: sawLive,
|
|
216
|
+
});
|
|
217
|
+
};
|
|
218
|
+
const observed = readHeartbeatRecord();
|
|
219
|
+
let runtime = null;
|
|
220
|
+
if (!observed) {
|
|
221
|
+
runtime = await fetchWithinBudget();
|
|
222
|
+
const sawLive = liveRuntimeSeen || !!runtime?.runtime_id;
|
|
223
|
+
if (sawLive || expectTarget) {
|
|
224
|
+
const retried = await retry(sawLive);
|
|
225
|
+
if (retried) return retried;
|
|
226
|
+
}
|
|
227
|
+
if (sawLive) return { ok: false, code: 'SUPERVISOR_HEARTBEAT_MISSING_WITH_LIVE_RUNTIME' };
|
|
228
|
+
if (expectTarget) return { ok: false, code: 'SUPERVISOR_TARGET_HEARTBEAT_TIMEOUT' };
|
|
229
|
+
return { ok: true, classification: 'absent', watcher: null, runtime_id: null };
|
|
230
|
+
}
|
|
231
|
+
const record = observed.record ?? {};
|
|
232
|
+
const expected = {
|
|
233
|
+
pid: record.pid,
|
|
234
|
+
...(record.process_started_at_utc_ticks ? { process_started_at_utc_ticks: String(record.process_started_at_utc_ticks) } : {}),
|
|
235
|
+
...(record.helper_hash ? { helper_hash: record.helper_hash } : {}),
|
|
236
|
+
};
|
|
237
|
+
const fullyAttestedStale = observed.state !== 'legacy-v1'
|
|
238
|
+
&& expected.process_started_at_utc_ticks
|
|
239
|
+
&& expected.helper_hash
|
|
240
|
+
&& !sameHash(expected.helper_hash, target.helper_hash);
|
|
241
|
+
const inspected = await inspect(expected, { allowHelperDrift: fullyAttestedStale });
|
|
242
|
+
if (inspected?.ok === false && inspected.code === 'PROCESS_NOT_FOUND') {
|
|
243
|
+
if (expectTarget) {
|
|
244
|
+
const retried = await retry(liveRuntimeSeen);
|
|
245
|
+
if (retried) return retried;
|
|
246
|
+
}
|
|
247
|
+
runtime ??= await fetchWithinBudget();
|
|
248
|
+
if (runtime?.runtime_id) {
|
|
249
|
+
return { ok: false, code: 'SUPERVISOR_HEARTBEAT_PROCESS_MISSING_WITH_LIVE_RUNTIME' };
|
|
250
|
+
}
|
|
251
|
+
if (expectTarget) {
|
|
252
|
+
return {
|
|
253
|
+
ok: false,
|
|
254
|
+
code: liveRuntimeSeen
|
|
255
|
+
? 'SUPERVISOR_HEARTBEAT_PROCESS_MISSING_WITH_LIVE_RUNTIME'
|
|
256
|
+
: 'SUPERVISOR_TARGET_HEARTBEAT_TIMEOUT',
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
return { ok: true, classification: 'absent', watcher: null, runtime_id: null };
|
|
260
|
+
}
|
|
261
|
+
if (inspected?.ok !== true || !inspected.watcher) return inspected ?? { ok: false, code: 'SUPERVISOR_WATCHER_UNVERIFIED' };
|
|
262
|
+
runtime ??= await fetchWithinBudget();
|
|
263
|
+
if (observed.state === 'legacy-v1') {
|
|
264
|
+
return runtime?.runtime_id
|
|
265
|
+
? { ok: true, classification: 'legacy', watcher: inspected.watcher, runtime_id: runtime.runtime_id }
|
|
266
|
+
: { ok: false, code: 'SUPERVISOR_RUNTIME_IDENTITY_UNAVAILABLE' };
|
|
267
|
+
}
|
|
268
|
+
const targetHash = sameHash(record.helper_hash, target.helper_hash);
|
|
269
|
+
if (targetHash && observed.state === 'ready') {
|
|
270
|
+
return runtime?.runtime_id
|
|
271
|
+
? { ok: true, classification: 'target-ready', watcher: inspected.watcher, runtime_id: runtime.runtime_id }
|
|
272
|
+
: { ok: false, code: 'SUPERVISOR_RUNTIME_IDENTITY_UNAVAILABLE' };
|
|
273
|
+
}
|
|
274
|
+
if (targetHash) return { ok: true, classification: 'target-starting', watcher: inspected.watcher, runtime_id: runtime?.runtime_id ?? null };
|
|
275
|
+
return runtime?.runtime_id
|
|
276
|
+
? { ok: true, classification: 'stale', watcher: inspected.watcher, runtime_id: runtime.runtime_id }
|
|
277
|
+
: { ok: false, code: 'SUPERVISOR_RUNTIME_IDENTITY_UNAVAILABLE' };
|
|
278
|
+
};
|
|
279
|
+
return {
|
|
280
|
+
classifyHeartbeat,
|
|
281
|
+
verifyExactWatcher: async ({ expected, role }) => inspect(expected, {
|
|
282
|
+
allowHelperDrift: role === 'old' && !sameHash(expected?.helper_hash, target.helper_hash),
|
|
283
|
+
}),
|
|
284
|
+
maintenanceStop: async ({ lease, runtime_id: runtimeId }) => maintenanceClient?.stopOwnedBackend?.({ lease, runtimeId })
|
|
285
|
+
?? { ok: false, code: 'SUPERVISOR_MAINTENANCE_UNAVAILABLE' },
|
|
286
|
+
maintenanceStatus: async ({ lease, runtime_id: runtimeId }) => {
|
|
287
|
+
const durable = readMaintenanceSession(appRoot);
|
|
288
|
+
if (!durable.ok) return durable;
|
|
289
|
+
if (durable.state === 'absent') return { ok: true, state: 'absent' };
|
|
290
|
+
const session = durable.session;
|
|
291
|
+
return session.lease === lease && session.runtime_id === runtimeId
|
|
292
|
+
? { ok: true, state: 'matching', lease, runtime_id: runtimeId, request_id: session.request_id }
|
|
293
|
+
: { ok: true, state: 'conflict', lease: session.lease, runtime_id: session.runtime_id };
|
|
294
|
+
},
|
|
295
|
+
verifyPortFree,
|
|
296
|
+
stopExactWatcher: async ({ expected }) => control(watcherRequest('stop', target, expected, {
|
|
297
|
+
allowHelperDrift: !sameHash(expected?.helper_hash, target.helper_hash),
|
|
298
|
+
})),
|
|
299
|
+
launchTargetWatcher: async () => control(watcherRequest('start', target)),
|
|
300
|
+
maintenanceStart: async ({ lease, runtime_id: runtimeId }) => maintenanceClient?.startOwnedBackend?.({
|
|
301
|
+
lease,
|
|
302
|
+
runtimeId,
|
|
303
|
+
expectedCrewVersion,
|
|
304
|
+
expectedDshVersion,
|
|
305
|
+
}) ?? { ok: false, code: 'SUPERVISOR_MAINTENANCE_UNAVAILABLE' },
|
|
306
|
+
verifyReady: async ({ previous_runtime_id: previousRuntimeId }) => {
|
|
307
|
+
const deadline = now() + readyTimeoutMs;
|
|
308
|
+
while (now() <= deadline) {
|
|
309
|
+
const heartbeat = readAuthoritativeHeartbeat();
|
|
310
|
+
if (heartbeat && sameHash(heartbeat.helper_hash, target.helper_hash)) {
|
|
311
|
+
const exact = await inspect({
|
|
312
|
+
pid: heartbeat.pid,
|
|
313
|
+
process_started_at_utc_ticks: String(heartbeat.process_started_at_utc_ticks),
|
|
314
|
+
helper_hash: heartbeat.helper_hash,
|
|
315
|
+
});
|
|
316
|
+
const runtime = await fetchRuntime({ timeoutMs: Math.max(1, Math.min(3_000, deadline - now())) });
|
|
317
|
+
if (exact?.ok === true
|
|
318
|
+
&& exact.watcher
|
|
319
|
+
&& validateSupervisorRuntime(runtime, { expectedCrewVersion, expectedDshVersion })
|
|
320
|
+
&& (!previousRuntimeId || runtime.runtime_id !== previousRuntimeId)) {
|
|
321
|
+
return { ok: true, watcher: exact.watcher, runtime };
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
await sleep(500);
|
|
325
|
+
}
|
|
326
|
+
return { ok: false, code: 'SUPERVISOR_READY_TIMEOUT' };
|
|
327
|
+
},
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
function prepareWindowsSupervisorConvergence({ home, root, platform }) {
|
|
332
|
+
if (platform !== 'win32') return { ok: true, skipped: true, reason: 'unsupported-platform' };
|
|
333
|
+
const appRoot = join(home, '.config', 'dsh-crew');
|
|
334
|
+
const assets = readWindowsSupervisorAssets({ home });
|
|
335
|
+
if (!assets.ok || !HASH_RE.test(assets.helper_hash) || !HASH_RE.test(assets.control_hash)) {
|
|
336
|
+
return { ok: false, code: 'SUPERVISOR_TARGET_UNAVAILABLE' };
|
|
337
|
+
}
|
|
338
|
+
let manifest = null;
|
|
339
|
+
try { manifest = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')); } catch {}
|
|
340
|
+
const expectedCrewVersion = text(manifest?.version);
|
|
341
|
+
let expectedDshVersion = text(manifest?.dependencies?.['@deepseek-ai/dsh'] ?? manifest?.peerDependencies?.['@deepseek-ai/dsh']);
|
|
342
|
+
if (!EXACT_VERSION_RE.test(expectedDshVersion ?? '')) {
|
|
343
|
+
try {
|
|
344
|
+
const cohort = JSON.parse(readFileSync(join(root, 'release-cohort.json'), 'utf8'));
|
|
345
|
+
expectedDshVersion = text(cohort?.dsh_version);
|
|
346
|
+
} catch { expectedDshVersion = null; }
|
|
347
|
+
}
|
|
348
|
+
if (manifest?.name !== '@ran-sh/dsh-crew'
|
|
349
|
+
|| !EXACT_VERSION_RE.test(expectedCrewVersion ?? '')
|
|
350
|
+
|| !EXACT_VERSION_RE.test(expectedDshVersion ?? '')) {
|
|
351
|
+
return { ok: false, code: 'SUPERVISOR_TARGET_UNAVAILABLE' };
|
|
352
|
+
}
|
|
353
|
+
return {
|
|
354
|
+
ok: true,
|
|
355
|
+
home,
|
|
356
|
+
root,
|
|
357
|
+
appRoot,
|
|
358
|
+
target: {
|
|
359
|
+
helper_path: assets.helper_path,
|
|
360
|
+
helper_hash: assets.helper_hash,
|
|
361
|
+
control_path: assets.control_path,
|
|
362
|
+
control_hash: assets.control_hash,
|
|
363
|
+
},
|
|
364
|
+
controlScript: assets.control_path,
|
|
365
|
+
controlHash: assets.control_hash,
|
|
366
|
+
expectedCrewVersion,
|
|
367
|
+
expectedDshVersion,
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
export function windowsSupervisorConvergencePending({ home = homedir() } = {}) {
|
|
372
|
+
const appRoot = join(home, '.config', 'dsh-crew');
|
|
373
|
+
return existsSync(windowsSupervisorHandoffJournalPath(appRoot))
|
|
374
|
+
|| existsSync(windowsSupervisorHandoffLockPath(appRoot));
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
export function reserveWindowsSupervisorConvergence({
|
|
378
|
+
home = homedir(),
|
|
379
|
+
root,
|
|
380
|
+
platform = process.platform,
|
|
381
|
+
} = {}) {
|
|
382
|
+
const prepared = prepareWindowsSupervisorConvergence({ home, root, platform });
|
|
383
|
+
if (!prepared.ok || prepared.skipped) return prepared;
|
|
384
|
+
const lock = acquireWindowsSupervisorHandoffLock({ appRoot: prepared.appRoot });
|
|
385
|
+
return lock.ok ? { ...prepared, lock } : { ok: false, code: lock.code, error: lock.error ?? null };
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
export function releaseWindowsSupervisorConvergenceReservation(reservation) {
|
|
389
|
+
if (!reservation?.lock) return { ok: false, code: 'SUPERVISOR_RESERVATION_INVALID' };
|
|
390
|
+
return releaseWindowsSupervisorHandoffLock(reservation.lock);
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
export async function convergeWindowsSupervisor({
|
|
394
|
+
home = homedir(),
|
|
395
|
+
root,
|
|
396
|
+
maintenanceClient,
|
|
397
|
+
platform = process.platform,
|
|
398
|
+
runControl,
|
|
399
|
+
fetchRuntime,
|
|
400
|
+
readHeartbeatRecord,
|
|
401
|
+
readAuthoritativeHeartbeat,
|
|
402
|
+
verifyPortFree,
|
|
403
|
+
sleep,
|
|
404
|
+
reservation = null,
|
|
405
|
+
} = {}) {
|
|
406
|
+
const prepared = prepareWindowsSupervisorConvergence({ home, root, platform });
|
|
407
|
+
if (!prepared.ok || prepared.skipped) {
|
|
408
|
+
if (reservation?.lock) releaseWindowsSupervisorHandoffLock(reservation.lock);
|
|
409
|
+
return prepared;
|
|
410
|
+
}
|
|
411
|
+
if (reservation && (!reservation.ok
|
|
412
|
+
|| !samePath(reservation.root, prepared.root)
|
|
413
|
+
|| !samePath(reservation.target?.helper_path, prepared.target.helper_path)
|
|
414
|
+
|| !sameHash(reservation.target?.helper_hash, prepared.target.helper_hash)
|
|
415
|
+
|| !samePath(reservation.target?.control_path, prepared.target.control_path)
|
|
416
|
+
|| !sameHash(reservation.target?.control_hash, prepared.target.control_hash)
|
|
417
|
+
|| reservation.expectedCrewVersion !== prepared.expectedCrewVersion
|
|
418
|
+
|| reservation.expectedDshVersion !== prepared.expectedDshVersion)) {
|
|
419
|
+
if (reservation?.lock) releaseWindowsSupervisorHandoffLock(reservation.lock);
|
|
420
|
+
return { ok: false, code: 'SUPERVISOR_RESERVATION_MISMATCH' };
|
|
421
|
+
}
|
|
422
|
+
const hooks = createWindowsSupervisorHandoffHooks({
|
|
423
|
+
appRoot: prepared.appRoot,
|
|
424
|
+
target: prepared.target,
|
|
425
|
+
maintenanceClient,
|
|
426
|
+
expectedCrewVersion: prepared.expectedCrewVersion,
|
|
427
|
+
expectedDshVersion: prepared.expectedDshVersion,
|
|
428
|
+
controlScript: prepared.controlScript,
|
|
429
|
+
runControl,
|
|
430
|
+
fetchRuntime,
|
|
431
|
+
readHeartbeatRecord,
|
|
432
|
+
readAuthoritativeHeartbeat,
|
|
433
|
+
verifyPortFree,
|
|
434
|
+
sleep,
|
|
435
|
+
});
|
|
436
|
+
return runWindowsSupervisorHandoff({
|
|
437
|
+
appRoot: prepared.appRoot,
|
|
438
|
+
target: prepared.target,
|
|
439
|
+
hooks,
|
|
440
|
+
preAcquiredLock: reservation?.lock ?? null,
|
|
441
|
+
forceRestart: existsSync(join(root, PENDING_RUNTIME_ACTIVATION)),
|
|
442
|
+
});
|
|
443
|
+
}
|