dsh-remote-go 0.1.0 → 0.3.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/README.md +64 -95
- package/{client.js → dist/client.js} +7805 -5486
- package/dist/index.js +4 -0
- package/dist/src/admission.js +46 -0
- package/dist/src/api.js +442 -0
- package/dist/src/atomic-json.js +235 -0
- package/dist/src/bootstrap.js +106 -0
- package/dist/src/connect/attach.js +43 -0
- package/dist/src/connect/bootstrap.js +14 -0
- package/dist/src/connect/failures.js +44 -0
- package/dist/src/connect/guards.js +31 -0
- package/dist/src/connect/launch.js +80 -0
- package/dist/src/connect/links.js +70 -0
- package/dist/src/connect/ownership.js +220 -0
- package/dist/src/connect/pipeline.js +473 -0
- package/dist/src/connect/reattach.js +215 -0
- package/dist/src/connect/registry.js +11 -0
- package/dist/src/connect/repair.js +126 -0
- package/dist/src/connect/restart.js +316 -0
- package/dist/src/connect/stop.js +198 -0
- package/dist/src/connect/transport.js +109 -0
- package/dist/src/connect/verify.js +39 -0
- package/dist/src/connect/watchdog.js +76 -0
- package/dist/src/connect-log.js +162 -0
- package/dist/src/connect-progress.js +142 -0
- package/dist/src/constants.js +67 -0
- package/dist/src/context.js +117 -0
- package/dist/src/diagnostics.js +102 -0
- package/dist/src/download-jobs.js +230 -0
- package/dist/src/errors.js +243 -0
- package/dist/src/events.js +390 -0
- package/dist/src/host-lifecycle.js +504 -0
- package/dist/src/host-registry.js +232 -0
- package/dist/src/host-runtime.js +86 -0
- package/dist/src/host-view.js +75 -0
- package/dist/src/index.js +216 -0
- package/dist/src/kernel-adapter.js +434 -0
- package/dist/src/key-files.js +52 -0
- package/dist/src/known-hosts.js +125 -0
- package/dist/src/layout.js +43 -0
- package/dist/src/local-download.js +380 -0
- package/dist/src/local-ssh.js +30 -0
- package/dist/src/local-version.js +101 -0
- package/dist/src/node/download.js +160 -0
- package/dist/src/node-runtime.js +346 -0
- package/dist/src/probe.js +96 -0
- package/dist/src/prompts.js +270 -0
- package/dist/src/proxy/cookies.js +136 -0
- package/dist/src/proxy/headers.js +262 -0
- package/dist/src/proxy/http.js +142 -0
- package/dist/src/proxy/index.js +135 -0
- package/dist/src/proxy/limits.js +8 -0
- package/dist/src/proxy/routes.js +39 -0
- package/dist/src/proxy/upgrade.js +175 -0
- package/dist/src/redact.js +104 -0
- package/dist/src/remote-files.js +72 -0
- package/dist/src/remote-path.js +123 -0
- package/dist/src/remote-proc.js +339 -0
- package/dist/src/remote-web/registry.js +147 -0
- package/dist/src/remote-web/resolve.js +310 -0
- package/dist/src/remote-web/start.js +227 -0
- package/dist/src/remote-web/stop.js +93 -0
- package/dist/src/request-trust.js +87 -0
- package/dist/src/runtime/dispatch.js +310 -0
- package/dist/src/runtime/effects.js +91 -0
- package/dist/src/runtime/events.js +35 -0
- package/dist/src/runtime/fsm.js +120 -0
- package/dist/src/runtime/rules.js +565 -0
- package/dist/src/secrets.js +142 -0
- package/dist/src/service.js +406 -0
- package/dist/src/settings.js +144 -0
- package/dist/src/ssh-config.js +276 -0
- package/dist/src/ssh-failures.js +122 -0
- package/dist/src/ssh-port.js +4 -0
- package/dist/src/ssh-sftp.js +297 -0
- package/dist/src/ssh.js +477 -0
- package/dist/src/store.js +191 -0
- package/dist/src/tool-shared.js +181 -0
- package/dist/src/tools-exec-policy.js +167 -0
- package/dist/src/tools-exec.js +371 -0
- package/dist/src/tools-report.js +424 -0
- package/dist/src/tools.js +411 -0
- package/dist/src/tunnel.js +129 -0
- package/dist/src/util.js +149 -0
- package/dist/src/version.js +114 -0
- package/dist/src/watchdog-bus.js +29 -0
- package/dist/src/watchdog.js +156 -0
- package/index.js +5 -4
- package/locale/en.json +2 -2
- package/locale/zh.json +2 -2
- package/package.json +40 -21
- package/vendor/THIRD_PARTY_NOTICES.md +27 -1
- package/src/api.js +0 -340
- package/src/atomic-json.js +0 -208
- package/src/bootstrap.js +0 -100
- package/src/connect-log.js +0 -39
- package/src/connect-pipeline.js +0 -463
- package/src/connect-progress.js +0 -135
- package/src/constants.js +0 -31
- package/src/diagnostics.js +0 -157
- package/src/download-jobs.js +0 -217
- package/src/errors.js +0 -316
- package/src/host-lifecycle.js +0 -187
- package/src/host-registry.js +0 -145
- package/src/host-runtime.js +0 -53
- package/src/host-view.js +0 -51
- package/src/index.js +0 -162
- package/src/key-files.js +0 -49
- package/src/known-hosts.js +0 -94
- package/src/layout.js +0 -35
- package/src/local-download.js +0 -162
- package/src/local-ssh.js +0 -27
- package/src/local-version.js +0 -88
- package/src/node-runtime.js +0 -521
- package/src/probe.js +0 -89
- package/src/prompts.js +0 -132
- package/src/redact.js +0 -54
- package/src/remote-files.js +0 -71
- package/src/remote-path.js +0 -73
- package/src/remote-proc.js +0 -208
- package/src/remote-web.js +0 -300
- package/src/secrets.js +0 -79
- package/src/service.js +0 -250
- package/src/settings.js +0 -135
- package/src/ssh-config.js +0 -271
- package/src/ssh.js +0 -652
- package/src/store.js +0 -143
- package/src/tunnel.js +0 -73
- package/src/util.js +0 -153
- package/src/version.js +0 -103
- package/src/webapp.js +0 -28
- package/vendor/ssh2-entry.mjs +0 -12
- /package/{vendor → dist/vendor}/ssh2.bundle.cjs +0 -0
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Atomic JSON persistence: 0700 dir, 0600 file, fsynced temp, rename retry and a cross-process lock; a bad file is reported, never thrown.
|
|
3
|
+
*/
|
|
4
|
+
import { promises as fs } from 'node:fs';
|
|
5
|
+
import { existsSync } from 'node:fs';
|
|
6
|
+
import { randomUUID } from 'node:crypto';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { sleep } from './util.js';
|
|
9
|
+
const RENAME_RETRY_ATTEMPTS = 5;
|
|
10
|
+
const RENAME_RETRY_BASE_MS = 20;
|
|
11
|
+
const LOCK_STALE_MS = 10_000;
|
|
12
|
+
const LOCK_WAIT_MS = 20_000;
|
|
13
|
+
const LOCK_RETRY_MS = 10;
|
|
14
|
+
/**
|
|
15
|
+
* How long a non-`EEXIST` lock error counts as contention without the lock present.
|
|
16
|
+
* Windows reports mid-create/mid-delete races as EPERM/EACCES, but those codes also
|
|
17
|
+
* mean a lock that can never be created (ACL denial, read-only mount); past this
|
|
18
|
+
* window the original error is surfaced instead of a misleading timeout.
|
|
19
|
+
*/
|
|
20
|
+
const LOCK_TRANSIENT_MS = 250;
|
|
21
|
+
const LOCK_UNLINK_ATTEMPTS = 3;
|
|
22
|
+
/**
|
|
23
|
+
* In-process chains keyed by lock path; the value is the always-settled tail so a
|
|
24
|
+
* rejected write never poisons the next waiter.
|
|
25
|
+
*/
|
|
26
|
+
const LOCAL_CHAINS = new Map();
|
|
27
|
+
/**
|
|
28
|
+
* Run `task` under the cross-process lock, serialized with every in-process holder
|
|
29
|
+
* of the same lock path.
|
|
30
|
+
*/
|
|
31
|
+
export function withProcessLock(lockFile, options, task) {
|
|
32
|
+
const previous = LOCAL_CHAINS.get(lockFile) ?? Promise.resolve();
|
|
33
|
+
const run = previous.then(() => runExclusive(lockFile, options ?? {}, task), () => runExclusive(lockFile, options ?? {}, task));
|
|
34
|
+
LOCAL_CHAINS.set(lockFile, run.catch(() => undefined));
|
|
35
|
+
return run;
|
|
36
|
+
}
|
|
37
|
+
async function runExclusive(lockFile, options, task) {
|
|
38
|
+
const release = await acquireLock(lockFile, options);
|
|
39
|
+
try {
|
|
40
|
+
return await task();
|
|
41
|
+
}
|
|
42
|
+
finally {
|
|
43
|
+
await release();
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
async function acquireLock(lockFile, options) {
|
|
47
|
+
const fsImpl = options.fs ?? fs;
|
|
48
|
+
const staleMs = options.staleMs ?? LOCK_STALE_MS;
|
|
49
|
+
const waitMs = options.waitMs ?? LOCK_WAIT_MS;
|
|
50
|
+
const retryMs = options.retryMs ?? LOCK_RETRY_MS;
|
|
51
|
+
const started = Date.now();
|
|
52
|
+
// Only a lock we never once observed can be a permanent permission error: under
|
|
53
|
+
// real contention the lock is created and unlinked constantly.
|
|
54
|
+
let sawLock = false;
|
|
55
|
+
while (true) {
|
|
56
|
+
try {
|
|
57
|
+
const handle = await fsImpl.open(lockFile, 'wx', 0o600);
|
|
58
|
+
return async () => {
|
|
59
|
+
try {
|
|
60
|
+
await handle.close();
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
// swallow-ok: a failed close on a released lock handle is not actionable here
|
|
64
|
+
}
|
|
65
|
+
// A leaked lock costs the next writer a full stale wait, so retry the unlink
|
|
66
|
+
// (Windows can hold it briefly after close).
|
|
67
|
+
for (let attempt = 0; attempt < LOCK_UNLINK_ATTEMPTS; attempt += 1) {
|
|
68
|
+
try {
|
|
69
|
+
await fsImpl.unlink(lockFile);
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
catch (unlinkError) {
|
|
73
|
+
const unlinkCode = unlinkError?.code;
|
|
74
|
+
if (unlinkCode === 'ENOENT')
|
|
75
|
+
return;
|
|
76
|
+
if (attempt === LOCK_UNLINK_ATTEMPTS - 1)
|
|
77
|
+
return;
|
|
78
|
+
await sleep(retryMs);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
catch (error) {
|
|
84
|
+
// Windows reports contention on an exclusive create as EPERM/EACCES/EBUSY
|
|
85
|
+
// rather than EEXIST when the other process is mid-create or mid-delete.
|
|
86
|
+
const code = error?.code;
|
|
87
|
+
if (code !== 'EEXIST' && code !== 'EPERM' && code !== 'EACCES' && code !== 'EBUSY')
|
|
88
|
+
throw error;
|
|
89
|
+
if (code !== 'EEXIST' && !sawLock && Date.now() - started > LOCK_TRANSIENT_MS) {
|
|
90
|
+
if (!(await lockExists(fsImpl, lockFile)))
|
|
91
|
+
throw error;
|
|
92
|
+
}
|
|
93
|
+
if (code === 'EEXIST' || (await lockExists(fsImpl, lockFile)))
|
|
94
|
+
sawLock = true;
|
|
95
|
+
await breakStaleLock(fsImpl, lockFile, staleMs);
|
|
96
|
+
if (Date.now() - started > waitMs) {
|
|
97
|
+
const timeout = new Error('timed out waiting for another process to release the store lock');
|
|
98
|
+
timeout.code = 'ELOCKTIMEOUT';
|
|
99
|
+
throw timeout;
|
|
100
|
+
}
|
|
101
|
+
await sleep(retryMs);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
async function breakStaleLock(fsImpl, lockFile, staleMs) {
|
|
106
|
+
try {
|
|
107
|
+
const info = await fsImpl.stat(lockFile);
|
|
108
|
+
if (Date.now() - info.mtimeMs > staleMs)
|
|
109
|
+
await removeQuietly(fsImpl, lockFile);
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
// swallow-ok: the lock disappeared or cannot be inspected; the create retries
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
export async function writeJsonAtomic(file, value, options = {}) {
|
|
116
|
+
const fsImpl = options.fs ?? fs;
|
|
117
|
+
const logger = options.logger ?? console;
|
|
118
|
+
const dir = options.dir ?? path.dirname(file);
|
|
119
|
+
const dirMode = options.dirMode ?? 0o700;
|
|
120
|
+
const fileMode = options.fileMode ?? 0o600;
|
|
121
|
+
try {
|
|
122
|
+
await fsImpl.mkdir(dir, { recursive: true, mode: dirMode });
|
|
123
|
+
}
|
|
124
|
+
catch (error) {
|
|
125
|
+
logger.warn?.(`[dsh-remote-go] cannot create ${dir}:`, error);
|
|
126
|
+
}
|
|
127
|
+
const tmp = `${file}.${randomUUID()}.tmp`;
|
|
128
|
+
const text = `${JSON.stringify(value, null, 2)}\n`;
|
|
129
|
+
let handle = null;
|
|
130
|
+
try {
|
|
131
|
+
handle = await fsImpl.open(tmp, 'wx', fileMode);
|
|
132
|
+
await handle.writeFile(text, 'utf8');
|
|
133
|
+
await handle.sync();
|
|
134
|
+
await handle.close();
|
|
135
|
+
handle = null;
|
|
136
|
+
}
|
|
137
|
+
catch (error) {
|
|
138
|
+
if (handle) {
|
|
139
|
+
try {
|
|
140
|
+
await handle.close();
|
|
141
|
+
}
|
|
142
|
+
catch {
|
|
143
|
+
// swallow-ok: the temp file is removed right below; a close error is not fixable
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
await removeQuietly(fsImpl, tmp);
|
|
147
|
+
throw error;
|
|
148
|
+
}
|
|
149
|
+
await renameWithRetry(fsImpl, tmp, file);
|
|
150
|
+
await syncDir(fsImpl, dir);
|
|
151
|
+
}
|
|
152
|
+
async function renameWithRetry(fsImpl, tmp, file) {
|
|
153
|
+
for (let attempt = 1; attempt <= RENAME_RETRY_ATTEMPTS; attempt += 1) {
|
|
154
|
+
try {
|
|
155
|
+
await fsImpl.rename(tmp, file);
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
catch (error) {
|
|
159
|
+
const code = error?.code;
|
|
160
|
+
const retryable = code === 'EPERM' || code === 'EBUSY' || code === 'EACCES';
|
|
161
|
+
if (retryable && attempt < RENAME_RETRY_ATTEMPTS) {
|
|
162
|
+
await sleep(RENAME_RETRY_BASE_MS * attempt);
|
|
163
|
+
continue;
|
|
164
|
+
}
|
|
165
|
+
await removeQuietly(fsImpl, tmp);
|
|
166
|
+
throw error;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
async function syncDir(fsImpl, dir) {
|
|
171
|
+
let handle = null;
|
|
172
|
+
try {
|
|
173
|
+
handle = await fsImpl.open(dir, 'r');
|
|
174
|
+
await handle.sync();
|
|
175
|
+
}
|
|
176
|
+
catch {
|
|
177
|
+
// swallow-ok: directory fsync is not supported on every platform or filesystem
|
|
178
|
+
}
|
|
179
|
+
finally {
|
|
180
|
+
if (handle) {
|
|
181
|
+
try {
|
|
182
|
+
await handle.close();
|
|
183
|
+
}
|
|
184
|
+
catch {
|
|
185
|
+
// swallow-ok: the directory handle is best effort, like the fsync above
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Read one JSON state file.
|
|
192
|
+
*
|
|
193
|
+
* The three outcomes are deliberately distinct: `missing` (never written), `corrupt` (the bytes
|
|
194
|
+
* are not JSON — the caller may quarantine them and recover) and `unreadable` (the file exists
|
|
195
|
+
* but could not be read: EACCES/EPERM/EISDIR/IO). A merely unreadable file must not be renamed
|
|
196
|
+
* away: that would turn a transient permission problem into a lost host list.
|
|
197
|
+
*/
|
|
198
|
+
export async function readJsonFile(file, options = {}) {
|
|
199
|
+
const fsImpl = options.fs ?? fs;
|
|
200
|
+
const logger = options.logger ?? console;
|
|
201
|
+
let text;
|
|
202
|
+
try {
|
|
203
|
+
if (!existsSync(file))
|
|
204
|
+
return { status: 'missing', value: null };
|
|
205
|
+
text = await fsImpl.readFile(file, 'utf8');
|
|
206
|
+
}
|
|
207
|
+
catch (error) {
|
|
208
|
+
logger.warn?.(`[dsh-remote-go] cannot read ${path.basename(file)}:`, error);
|
|
209
|
+
return { status: 'unreadable', value: null };
|
|
210
|
+
}
|
|
211
|
+
try {
|
|
212
|
+
return { status: 'ok', value: JSON.parse(text) };
|
|
213
|
+
}
|
|
214
|
+
catch (error) {
|
|
215
|
+
logger.warn?.(`[dsh-remote-go] ${path.basename(file)} is not valid JSON:`, error);
|
|
216
|
+
return { status: 'corrupt', value: null };
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
async function removeQuietly(fsImpl, target) {
|
|
220
|
+
try {
|
|
221
|
+
await fsImpl.unlink(target);
|
|
222
|
+
}
|
|
223
|
+
catch {
|
|
224
|
+
// swallow-ok: a missing temp file is the success case for this cleanup
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
async function lockExists(fsImpl, lockFile) {
|
|
228
|
+
try {
|
|
229
|
+
await fsImpl.stat(lockFile);
|
|
230
|
+
return true;
|
|
231
|
+
}
|
|
232
|
+
catch {
|
|
233
|
+
return false;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Remote runtime preparation: `npx` pinned to the local DSH version against the remote's real `$DSH_HOME`; the executor runs only fixed templates.
|
|
3
|
+
*/
|
|
4
|
+
import { errors } from './errors.js';
|
|
5
|
+
import { headTail, shellQuote } from './util.js';
|
|
6
|
+
import { isNodeVersionSupported, normalizeVersion, parseVersion, versionsEqual } from './version.js';
|
|
7
|
+
export function assertSupportedRemote(facts) {
|
|
8
|
+
if (facts.os !== 'Linux') {
|
|
9
|
+
throw errors.unsupportedOs(`${facts.os} ${facts.arch}`.trim());
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
export function planNpx(input) {
|
|
13
|
+
const targetVersion = normalizeVersion(input.targetVersion);
|
|
14
|
+
if (!parseVersion(targetVersion)) {
|
|
15
|
+
throw errors.invalidInput('targetVersion', {
|
|
16
|
+
zh: `目标版本「${input.targetVersion}」不是合法版本号。`,
|
|
17
|
+
en: `Target version "${input.targetVersion}" is not a valid version.`,
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
assertSupportedRemote(input.facts);
|
|
21
|
+
if (!isNodeVersionSupported(input.facts.nodeVersion)) {
|
|
22
|
+
throw errors.remoteDshMissing({
|
|
23
|
+
zh: `远端 Node 不可用或版本过低(需要 ≥ 24.9.0,检测到 ${input.facts.nodeVersion ?? '无'}),自动准备也没有完成。请检查远端网络,或在远端安装 Node 后重试。`,
|
|
24
|
+
en: `The remote Node is missing or too old (>= 24.9.0 required, detected ${input.facts.nodeVersion ?? 'none'}) and automatic preparation did not finish. Check the remote network, or install Node on the remote and retry.`,
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
if (!input.facts.npxPath) {
|
|
28
|
+
throw errors.remoteDshMissing({
|
|
29
|
+
zh: '远端没有找到 npx。请安装 npm(随 Node 一起提供),或把 npm 的 bin 目录加入远程 shell 的 PATH。',
|
|
30
|
+
en: 'npx was not found on the remote. Install npm (shipped with Node) or add its bin directory to the remote shell PATH.',
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
if (!input.facts.curlPath && !input.facts.wgetPath) {
|
|
34
|
+
throw errors.remoteDshMissing({
|
|
35
|
+
zh: '远端既没有 curl 也没有 wget,无法在启动后探活远端界面。请安装其中之一。',
|
|
36
|
+
en: 'The remote has neither curl nor wget, so the remote UI cannot be health-checked after start. Install one of them.',
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
const nodeBinDir = input.facts.nodePath ? input.facts.nodePath.replace(/\/node$/, '') : undefined;
|
|
40
|
+
return {
|
|
41
|
+
level: 'npx',
|
|
42
|
+
profile: input.profile,
|
|
43
|
+
targetVersion,
|
|
44
|
+
reason: {
|
|
45
|
+
zh: `用 npx 精确版本 ${targetVersion} 启动远端 DSH(Node 运行时由插件准备)`,
|
|
46
|
+
en: `Launch the remote DSH with npx pinned to ${targetVersion} (Node runtime prepared by the plugin)`,
|
|
47
|
+
},
|
|
48
|
+
start: {
|
|
49
|
+
kind: 'npx',
|
|
50
|
+
npxPath: input.facts.npxPath,
|
|
51
|
+
nodePath: input.facts.nodePath ?? undefined,
|
|
52
|
+
nodeBinDir,
|
|
53
|
+
targetVersion,
|
|
54
|
+
},
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* The npx preflight: resolve and run the exact package once, so a first-run
|
|
59
|
+
* download happens in the foreground (and fails with a readable error) instead
|
|
60
|
+
* of inside the detached start script.
|
|
61
|
+
*
|
|
62
|
+
* `npm_config_loglevel=http` is deliberate: over an SSH channel npm has no TTY and
|
|
63
|
+
* would otherwise print nothing until it finishes. At `http` it reports fetches
|
|
64
|
+
* on stderr, which the caller turns into progress.
|
|
65
|
+
*/
|
|
66
|
+
export function buildPreflightCommand(plan) {
|
|
67
|
+
const pathPrefix = plan.start.nodeBinDir ? `PATH=${shellQuote(plan.start.nodeBinDir)}:"$PATH" ` : '';
|
|
68
|
+
return `set -eu
|
|
69
|
+
${pathPrefix}npm_config_loglevel=http ${shellQuote(plan.start.npxPath)} -y @deepseek-ai/dsh@${normalizeVersion(plan.start.targetVersion)} --version`;
|
|
70
|
+
}
|
|
71
|
+
export async function verifyNpxVersion(ssh, plan, options = {}) {
|
|
72
|
+
const timeoutMs = options.timeoutMs ?? 0;
|
|
73
|
+
const result = await ssh.exec(buildPreflightCommand(plan), {
|
|
74
|
+
timeoutMs,
|
|
75
|
+
maxBytes: options.maxBytes ?? 4 * 1024 * 1024,
|
|
76
|
+
onStdout: options.onStdout,
|
|
77
|
+
onStderr: options.onStderr,
|
|
78
|
+
});
|
|
79
|
+
// `timeoutMs: 0` means "no timeout" (a cold npx download is unbounded by design); only a
|
|
80
|
+
// caller-supplied deadline can time out, and that is a network condition, not a missing
|
|
81
|
+
// remote runtime (L).
|
|
82
|
+
if (result.timedOut === true) {
|
|
83
|
+
throw errors.network({
|
|
84
|
+
zh: `远端 npx 预检超过 ${Math.round(timeoutMs / 1000)} 秒没有完成,可能是下载很慢或远端负载过高。`,
|
|
85
|
+
en: `The remote npx preflight did not finish within ${Math.round(timeoutMs / 1000)}s; the download may be slow or the remote overloaded.`,
|
|
86
|
+
}, { technical: `reason=preflight-timeout timeoutMs=${timeoutMs}` });
|
|
87
|
+
}
|
|
88
|
+
const combined = `${result.stdout}\n${result.stderr}`;
|
|
89
|
+
if (result.code !== 0) {
|
|
90
|
+
const failure = errors.remoteDshMissing({
|
|
91
|
+
zh: `无法通过 npx 运行 @deepseek-ai/dsh@${plan.start.targetVersion}(退出码 ${result.code})。请确认远端能访问 npm registry,且 Node/npm 版本满足要求。`,
|
|
92
|
+
en: `Could not run @deepseek-ai/dsh@${plan.start.targetVersion} through npx (exit ${result.code}). Make sure the remote can reach the npm registry and Node/npm meet the requirements.`,
|
|
93
|
+
});
|
|
94
|
+
failure.technical = headTail(combined, 1500);
|
|
95
|
+
throw failure;
|
|
96
|
+
}
|
|
97
|
+
const lines = String(result.stdout ?? '')
|
|
98
|
+
.split(/\r?\n/)
|
|
99
|
+
.map((line) => line.trim())
|
|
100
|
+
.filter(Boolean);
|
|
101
|
+
const reported = normalizeVersion(lines[lines.length - 1] ?? '');
|
|
102
|
+
if (!versionsEqual(reported, plan.targetVersion)) {
|
|
103
|
+
throw errors.versionMismatch(plan.targetVersion, reported || 'unknown');
|
|
104
|
+
}
|
|
105
|
+
return reported;
|
|
106
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { dispatch, scopeFactsFor } from '../runtime/dispatch.js';
|
|
2
|
+
import { createRuntimeEffects } from '../runtime/effects.js';
|
|
3
|
+
import { nowIso } from '../util.js';
|
|
4
|
+
/**
|
|
5
|
+
* Publish the connected state and start watching the remote for its own restarts.
|
|
6
|
+
*
|
|
7
|
+
* The whole attach is one `connect.succeeded` transition: status/phase/progress/error, the
|
|
8
|
+
* retry-budget reset, the stale "stop not confirmed" warning, the idle disarm, the heartbeat arm,
|
|
9
|
+
* `uiReady`/`viewRev`, the link-block repair-budget reset and `activeHostId`.
|
|
10
|
+
* @param ctx - service context.
|
|
11
|
+
* @param runtime - the runtime that just reached `ready`.
|
|
12
|
+
*/
|
|
13
|
+
export async function markConnected(ctx, runtime) {
|
|
14
|
+
const event = { type: 'connect.succeeded' };
|
|
15
|
+
await dispatch(createRuntimeEffects(ctx), runtime, event, scopeFactsFor(ctx, runtime, event), {
|
|
16
|
+
caller: 'script',
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
/** Bounded diagnostics trail of restarts and re-attached ports (never sent to the client). */
|
|
20
|
+
export function recordRestart(runtime, entry) {
|
|
21
|
+
const history = Array.isArray(runtime.restarts) ? runtime.restarts : [];
|
|
22
|
+
history.push({ at: nowIso(), ...entry });
|
|
23
|
+
runtime.restarts = history.slice(-10);
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Put a host back into its connected state without pretending the launch URL changed.
|
|
27
|
+
*
|
|
28
|
+
* One `restart.resumed` transition (`keptInstance` when the managed stop was not confirmed, which
|
|
29
|
+
* is what puts the "no new instance was started" warning back on the card).
|
|
30
|
+
* @param ctx - service context.
|
|
31
|
+
* @param runtime - the runtime the restart action owns.
|
|
32
|
+
* @param keptInstance - whether the old remote instance was kept on purpose.
|
|
33
|
+
* @returns whether the link was still there to resume.
|
|
34
|
+
*/
|
|
35
|
+
export async function resumeConnected(ctx, runtime, keptInstance = false) {
|
|
36
|
+
// A late action must never resurrect a link that was torn down or replaced while it waited:
|
|
37
|
+
// the token is checked by callers, and these are the other three proofs that it still exists.
|
|
38
|
+
if (runtime.desired !== 'connected' || runtime.ssh?.connected !== true || runtime.tunnel === null)
|
|
39
|
+
return false;
|
|
40
|
+
const event = { type: 'restart.resumed', ...(keptInstance ? { keptInstance: true } : {}) };
|
|
41
|
+
await dispatch(createRuntimeEffects(ctx), runtime, event, scopeFactsFor(ctx, runtime, event), { caller: 'script' });
|
|
42
|
+
return true;
|
|
43
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { errors } from '../errors.js';
|
|
2
|
+
/**
|
|
3
|
+
* Recompute the launch plan from the probe facts the connection already recorded. A
|
|
4
|
+
* restart reuses the same managed Node, profile and pinned version, so `[ssh]`,
|
|
5
|
+
* `[probe]` and `[bootstrap]` are deliberately not run again.
|
|
6
|
+
*/
|
|
7
|
+
export function planForRuntime(ctx, runtime, profile) {
|
|
8
|
+
const facts = runtime.facts;
|
|
9
|
+
const targetVersion = ctx.localVersion();
|
|
10
|
+
if (!facts || !targetVersion) {
|
|
11
|
+
throw errors.internal(new Error('the connected host has no recorded probe facts or local version'));
|
|
12
|
+
}
|
|
13
|
+
return { plan: ctx.deps.plan({ facts, targetVersion, profile }), targetVersion, facts };
|
|
14
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One classification for a failed connect step (design-arch §3.3, single implementation): a step
|
|
3
|
+
* that raced the transport going away must read as a dropped connection (network, retryable),
|
|
4
|
+
* never as a bare internal error or as a key decision the user never made (H3).
|
|
5
|
+
*/
|
|
6
|
+
import { errors, RemoteGoError, toErrorView } from '../errors.js';
|
|
7
|
+
/** The bilingual detail of "the transport this step needed is gone". */
|
|
8
|
+
export const SSH_CLOSED_DETAIL = {
|
|
9
|
+
zh: 'SSH 连接已断开,本次操作没有完成;如果主机仍在线,重连即可继续。',
|
|
10
|
+
en: 'SSH connection is not open; the transport closed before this step finished. Reconnect to continue.',
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* Classify a pipeline failure. A step that raced the transport going away must read as a
|
|
14
|
+
* dropped connection (`network`, retryable), never as a bare `internal` error or as a key
|
|
15
|
+
* decision the user never made (H3).
|
|
16
|
+
* @param runtime - host runtime.
|
|
17
|
+
* @param error - the thrown value.
|
|
18
|
+
* @returns the Client-facing error view.
|
|
19
|
+
*/
|
|
20
|
+
export function normalizeConnectFailure(runtime, error) {
|
|
21
|
+
const view = toErrorView(error);
|
|
22
|
+
if (runtime.transportLost === true && runtime.ssh?.connected !== true) {
|
|
23
|
+
// A prompt parked on the transport was resolved by the close itself: the user made no
|
|
24
|
+
// decision, so this must not read as "confirm the host key" / "a manual DSH is running".
|
|
25
|
+
if (view.code === 'host-key-unknown' || view.code === 'remote-dsh-running') {
|
|
26
|
+
return toErrorView(errors.network(SSH_CLOSED_DETAIL, {
|
|
27
|
+
technical: `reason=ssh-closed phase-code=${view.code}`,
|
|
28
|
+
}));
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
if (runtime.ssh?.connected === true) {
|
|
32
|
+
if (!(error instanceof RemoteGoError) &&
|
|
33
|
+
/\b(?:not open|closed|ECONNRESET|EPIPE|Channel closed)\b/i.test(String(error?.message ?? ''))) {
|
|
34
|
+
return toErrorView(errors.network(SSH_CLOSED_DETAIL, { technical: `reason=ssh-closed cause=${error?.message ?? error}` }));
|
|
35
|
+
}
|
|
36
|
+
return view;
|
|
37
|
+
}
|
|
38
|
+
if (view.code === 'internal' || view.code === 'remote-dsh-missing' || view.code === 'remote-node-install-failed') {
|
|
39
|
+
return toErrorView(errors.network(SSH_CLOSED_DETAIL, {
|
|
40
|
+
technical: `reason=ssh-closed phase-code=${view.code} cause=${error instanceof Error ? error.message : String(error ?? '')}`,
|
|
41
|
+
}));
|
|
42
|
+
}
|
|
43
|
+
return view;
|
|
44
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { errors } from '../errors.js';
|
|
2
|
+
import { SSH_CLOSED_DETAIL } from './failures.js';
|
|
3
|
+
/**
|
|
4
|
+
* Internal marker: a pipeline step ran after the user (or the host process) took the link
|
|
5
|
+
* away. It is not a connection failure, so it never reaches the Client as an error.
|
|
6
|
+
*/
|
|
7
|
+
export class LinkCancelled extends Error {
|
|
8
|
+
constructor(reason) {
|
|
9
|
+
super(`connect aborted: ${reason}`);
|
|
10
|
+
this.name = 'LinkCancelled';
|
|
11
|
+
this.code = 'link-cancelled';
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/** Whether the link is no longer wanted: disconnect, host removal, teardown or shutdown. */
|
|
15
|
+
export function linkTaken(ctx, runtime) {
|
|
16
|
+
return (ctx.state.disposed === true ||
|
|
17
|
+
runtime.closing === true ||
|
|
18
|
+
runtime.desired !== 'connected' ||
|
|
19
|
+
!ctx.state.runtimes.has(runtime.id));
|
|
20
|
+
}
|
|
21
|
+
/** Throw unless this attempt may still write state (H4). */
|
|
22
|
+
export function assertStillWanted(ctx, runtime) {
|
|
23
|
+
if (linkTaken(ctx, runtime))
|
|
24
|
+
throw new LinkCancelled('the link is no longer wanted');
|
|
25
|
+
}
|
|
26
|
+
/** Throw a typed transport error unless the SSH transport is still open (H3). */
|
|
27
|
+
export function assertTransportOpen(runtime) {
|
|
28
|
+
if (runtime.ssh?.connected !== true) {
|
|
29
|
+
throw errors.network(SSH_CLOSED_DETAIL, { technical: 'reason=ssh-closed' });
|
|
30
|
+
}
|
|
31
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { errors } from '../errors.js';
|
|
2
|
+
import { askConflict } from '../prompts.js';
|
|
3
|
+
import { isPid, messageOf } from '../util.js';
|
|
4
|
+
/**
|
|
5
|
+
* Warn when the remote already runs a DSH this plugin did not start, and let the
|
|
6
|
+
* user decide: stop it, keep it alongside, or cancel.
|
|
7
|
+
* @returns the decision, or null when no prompt was needed.
|
|
8
|
+
*/
|
|
9
|
+
export async function resolveForeignConflict(ctx, runtime, layout, profile, options = {}) {
|
|
10
|
+
// Processes the user already chose to keep alongside this connection are not asked
|
|
11
|
+
// about again (a local restart must not turn that choice into a prompt every time).
|
|
12
|
+
const ignorePids = (Array.isArray(options.ignoredPids) ? options.ignoredPids : []).filter((pid) => isPid(pid));
|
|
13
|
+
try {
|
|
14
|
+
const registry = await ctx.deps.readRegistry(runtime.ssh, layout);
|
|
15
|
+
const pid = Number(registry?.pid);
|
|
16
|
+
if (isPid(pid) && registry?.dshHome === layout.dshHome && registry?.profile === profile)
|
|
17
|
+
ignorePids.push(pid);
|
|
18
|
+
}
|
|
19
|
+
catch (error) {
|
|
20
|
+
// swallow-ok: registry absence is normal; the scan below still finds foreign processes
|
|
21
|
+
ctx.progress.log(runtime, 'debug', 'foreign DSH: registry read failed:', messageOf(error));
|
|
22
|
+
}
|
|
23
|
+
const found = await ctx.deps.findForeign(runtime.ssh, { ignorePids });
|
|
24
|
+
const processes = found.ok === true && Array.isArray(found.processes) ? [...found.processes] : [];
|
|
25
|
+
// The registry-named instance is normally ignored by the scan (it is this connection's own
|
|
26
|
+
// process). When the caller cannot stop it - a pid a re-attach discovered - it still must be
|
|
27
|
+
// put in front of the user: a second instance must never start silently next to it. Merge it
|
|
28
|
+
// before failing open on a scan error: its identity came from /proc, not from the scan.
|
|
29
|
+
const known = options.knownProcess;
|
|
30
|
+
const knownPid = Number(known?.pid);
|
|
31
|
+
// A pid the user already chose to keep alongside is never asked about again; the
|
|
32
|
+
// registry-named pid, however, must be shown when it could not be stopped.
|
|
33
|
+
const keptAlongside = (Array.isArray(options.ignoredPids) ? options.ignoredPids : []).map(Number);
|
|
34
|
+
if (isPid(knownPid) &&
|
|
35
|
+
!keptAlongside.includes(knownPid) &&
|
|
36
|
+
!processes.some((entry) => Number(entry?.pid) === knownPid)) {
|
|
37
|
+
processes.push({
|
|
38
|
+
pid: knownPid,
|
|
39
|
+
command: typeof known.command === 'string' && known.command !== '' ? known.command : `dsh --profile ${profile}`,
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
if (found.ok !== true) {
|
|
43
|
+
ctx.progress.log(runtime, 'debug', 'foreign DSH: scan failed:', found.reason ?? found.technical ?? 'unknown');
|
|
44
|
+
// A broken scan must never allow a silent second instance: with a known live process we
|
|
45
|
+
// still ask; with nothing known there is nothing to conflict with (the old behavior).
|
|
46
|
+
if (processes.length === 0)
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
if (processes.length === 0)
|
|
50
|
+
return null;
|
|
51
|
+
const pidList = processes.map((entry) => `pid ${entry.pid}`).join(', ');
|
|
52
|
+
ctx.progress.log(runtime, 'warn', `foreign DSH on the remote: ${processes.length} process(es) sharing this ~/.dsh (${pidList})`);
|
|
53
|
+
const decision = await askConflict(ctx, runtime, processes);
|
|
54
|
+
if (decision.action === 'cancel') {
|
|
55
|
+
// The user said no: retrying would ask the same question again. The `conflict.answered`
|
|
56
|
+
// transition already recorded that (its rule owns `connectCancelled`); this is only the throw.
|
|
57
|
+
throw errors.remoteDshRunning();
|
|
58
|
+
}
|
|
59
|
+
if (decision.action === 'alongside') {
|
|
60
|
+
runtime.alongsidePids = processes.map((entry) => entry.pid).filter((pid) => isPid(pid));
|
|
61
|
+
runtime.warning = {
|
|
62
|
+
zh: '远端已有手工启动的 DSH;已按你的选择并存运行,两者共享 ~/.dsh,请避免同时操作同一会话。',
|
|
63
|
+
en: 'A manually started DSH is already running; it was kept as you chose. Both share ~/.dsh, so avoid editing the same session in both.',
|
|
64
|
+
};
|
|
65
|
+
runtime.warningSource = 'alongside';
|
|
66
|
+
return 'alongside';
|
|
67
|
+
}
|
|
68
|
+
const stopped = await ctx.deps.stopForeign(runtime.ssh, processes);
|
|
69
|
+
if (stopped.ok !== true) {
|
|
70
|
+
throw errors.remoteDshRunning({
|
|
71
|
+
zh: '远端的手工 DSH 进程没有停下来,连接已中止。',
|
|
72
|
+
en: 'The manual remote DSH process did not stop, so the connection was aborted.',
|
|
73
|
+
}, {
|
|
74
|
+
technical: `alive=${stopped.alive.join(',') || 'unknown'} output=${String(stopped.output ?? '').slice(0, 800)}`,
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
runtime.alongsidePids = [];
|
|
78
|
+
ctx.progress.log(runtime, 'info', `stopped ${processes.length} manual remote DSH process(es)`);
|
|
79
|
+
return 'stop';
|
|
80
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The two connect entries: a user connect (which owns the one-time inputs, the retry budget and
|
|
3
|
+
* the log boundary) and the "Reconnect" button's drop-and-redial.
|
|
4
|
+
*/
|
|
5
|
+
import { beginConnectLog } from '../connect-log.js';
|
|
6
|
+
import { runtimeOf } from '../host-registry.js';
|
|
7
|
+
import { cancelIdleStop, disconnectHost, disposeSsh } from '../host-lifecycle.js';
|
|
8
|
+
import { dispatch, scopeFactsFor } from '../runtime/dispatch.js';
|
|
9
|
+
import { createRuntimeEffects } from '../runtime/effects.js';
|
|
10
|
+
import { isRefusal } from '../runtime/fsm.js';
|
|
11
|
+
import { startConnectPromise } from './pipeline.js';
|
|
12
|
+
function describeTarget(entry) {
|
|
13
|
+
const user = entry.username ? `${entry.username}@` : '';
|
|
14
|
+
const port = entry.port && entry.port !== 22 ? `:${entry.port}` : '';
|
|
15
|
+
return `${user}${entry.address || '?'}${port}`;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Accept a connect request: apply the one-time inputs, stop any pending retry,
|
|
19
|
+
* and start the pipeline in the background. Progress travels on `state`.
|
|
20
|
+
*/
|
|
21
|
+
export async function startConnect(ctx, id, options = {}) {
|
|
22
|
+
await ctx.init();
|
|
23
|
+
const runtime = runtimeOf(ctx, id);
|
|
24
|
+
if (runtime.connectPromise)
|
|
25
|
+
return { accepted: false, reason: 'already-connecting' };
|
|
26
|
+
if (runtime.linkBusy !== null)
|
|
27
|
+
return { accepted: false, reason: 'already-restarting' };
|
|
28
|
+
if (runtime.status === 'connected' && runtime.ssh?.connected)
|
|
29
|
+
return { accepted: false, reason: 'already-connected' };
|
|
30
|
+
runtime.alongsidePids = [];
|
|
31
|
+
const typedPassword = typeof options.password === 'string' && options.password !== '' ? options.password : null;
|
|
32
|
+
if (typedPassword !== null)
|
|
33
|
+
runtime.password = typedPassword;
|
|
34
|
+
// Remembering is the default for a password the user just typed (`POST /hosts/:id/connect`
|
|
35
|
+
// treats an absent `rememberPassword` as true). An explicit false means "this connection
|
|
36
|
+
// only" and also forgets a previously saved record, so an unchecked box cannot leave a stale
|
|
37
|
+
// secret behind. A retry or auto-reconnect carries no password of its own and must not
|
|
38
|
+
// re-save what the store already holds.
|
|
39
|
+
runtime.savePassword = typedPassword !== null && options.rememberPassword !== false;
|
|
40
|
+
runtime.forgetPassword = typedPassword !== null && options.rememberPassword === false;
|
|
41
|
+
// This connection starts its own log: the previous attempt's lines are gone before the
|
|
42
|
+
// first line of this one, so the panel and a copied log only ever show the live attempt.
|
|
43
|
+
// The line keeps the previous attempt's `phase`, exactly as it did before the FSM owned it.
|
|
44
|
+
beginConnectLog(runtime);
|
|
45
|
+
ctx.progress.log(runtime, 'info', `connect: ${describeTarget(runtime.entry)} (auth=${runtime.entry.auth?.type ?? 'key'}${runtime.entry.jumpHost ? `, jump=${runtime.entry.jumpHost}` : ''})`);
|
|
46
|
+
// One transition owns the whole entry: the retry budget and prompt history reset (a *user*
|
|
47
|
+
// connect), the timer disarms, the desired flag and the pipeline start (`run`). The token
|
|
48
|
+
// invalidates any older one-shot action, the same way the old `cancelLinkWork` did.
|
|
49
|
+
const token = (Number(runtime.linkToken) || 0) + 1;
|
|
50
|
+
const event = { type: 'connect.requested', token };
|
|
51
|
+
const result = await dispatch(createRuntimeEffects(ctx), runtime, event, scopeFactsFor(ctx, runtime, event), {
|
|
52
|
+
run: () => startConnectPromise(ctx, runtime),
|
|
53
|
+
});
|
|
54
|
+
if (isRefusal(result)) {
|
|
55
|
+
// The guards above are the API-visible ones; the machine refusing here means the two disagreed.
|
|
56
|
+
ctx.progress.log(runtime, 'warn', `connect refused: ${result.reason}`);
|
|
57
|
+
return { accepted: false, reason: result.reason === 'already-connecting' ? 'already-connecting' : 'busy' };
|
|
58
|
+
}
|
|
59
|
+
return { accepted: true };
|
|
60
|
+
}
|
|
61
|
+
/** Drop the current link and connect again from scratch (the "Reconnect" button). */
|
|
62
|
+
export async function reconnectHost(ctx, runtime) {
|
|
63
|
+
await disconnectHost(ctx, runtime, { stopRemote: false });
|
|
64
|
+
cancelIdleStop(runtime);
|
|
65
|
+
await disposeSsh(runtime);
|
|
66
|
+
// A one-shot action cancelled by the disconnect resolves after its transport is gone; it
|
|
67
|
+
// can no longer write state, but letting it settle keeps the old code out of the new run.
|
|
68
|
+
await Promise.allSettled([runtime.restartPromise, runtime.reattachPromise].filter((promise) => promise && typeof promise.then === 'function'));
|
|
69
|
+
return startConnect(ctx, runtime.id, {});
|
|
70
|
+
}
|