dsh-remote-go 0.2.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.
Files changed (134) hide show
  1. package/README.md +11 -3
  2. package/{client.js → dist/client.js} +7710 -8182
  3. package/dist/index.js +4 -0
  4. package/dist/src/admission.js +46 -0
  5. package/dist/src/api.js +442 -0
  6. package/dist/src/atomic-json.js +235 -0
  7. package/dist/src/bootstrap.js +106 -0
  8. package/dist/src/connect/attach.js +43 -0
  9. package/dist/src/connect/bootstrap.js +14 -0
  10. package/dist/src/connect/failures.js +44 -0
  11. package/dist/src/connect/guards.js +31 -0
  12. package/dist/src/connect/launch.js +80 -0
  13. package/dist/src/connect/links.js +70 -0
  14. package/dist/src/connect/ownership.js +220 -0
  15. package/dist/src/connect/pipeline.js +473 -0
  16. package/dist/src/connect/reattach.js +215 -0
  17. package/dist/src/connect/registry.js +11 -0
  18. package/dist/src/connect/repair.js +126 -0
  19. package/dist/src/connect/restart.js +316 -0
  20. package/dist/src/connect/stop.js +198 -0
  21. package/dist/src/connect/transport.js +109 -0
  22. package/dist/src/connect/verify.js +39 -0
  23. package/dist/src/connect/watchdog.js +76 -0
  24. package/dist/src/connect-log.js +162 -0
  25. package/dist/src/connect-progress.js +142 -0
  26. package/{src → dist/src}/constants.js +30 -56
  27. package/dist/src/context.js +117 -0
  28. package/dist/src/diagnostics.js +102 -0
  29. package/dist/src/download-jobs.js +230 -0
  30. package/dist/src/errors.js +243 -0
  31. package/dist/src/events.js +390 -0
  32. package/dist/src/host-lifecycle.js +504 -0
  33. package/dist/src/host-registry.js +232 -0
  34. package/dist/src/host-runtime.js +86 -0
  35. package/dist/src/host-view.js +75 -0
  36. package/dist/src/index.js +216 -0
  37. package/dist/src/kernel-adapter.js +434 -0
  38. package/dist/src/key-files.js +52 -0
  39. package/dist/src/known-hosts.js +125 -0
  40. package/dist/src/layout.js +43 -0
  41. package/dist/src/local-download.js +380 -0
  42. package/dist/src/local-ssh.js +30 -0
  43. package/dist/src/local-version.js +101 -0
  44. package/dist/src/node/download.js +160 -0
  45. package/dist/src/node-runtime.js +346 -0
  46. package/dist/src/probe.js +96 -0
  47. package/dist/src/prompts.js +270 -0
  48. package/dist/src/proxy/cookies.js +136 -0
  49. package/dist/src/proxy/headers.js +262 -0
  50. package/dist/src/proxy/http.js +142 -0
  51. package/dist/src/proxy/index.js +135 -0
  52. package/dist/src/proxy/limits.js +8 -0
  53. package/dist/src/proxy/routes.js +39 -0
  54. package/dist/src/proxy/upgrade.js +175 -0
  55. package/dist/src/redact.js +104 -0
  56. package/dist/src/remote-files.js +72 -0
  57. package/dist/src/remote-path.js +123 -0
  58. package/dist/src/remote-proc.js +339 -0
  59. package/dist/src/remote-web/registry.js +147 -0
  60. package/dist/src/remote-web/resolve.js +310 -0
  61. package/dist/src/remote-web/start.js +227 -0
  62. package/dist/src/remote-web/stop.js +93 -0
  63. package/dist/src/request-trust.js +87 -0
  64. package/dist/src/runtime/dispatch.js +310 -0
  65. package/dist/src/runtime/effects.js +91 -0
  66. package/dist/src/runtime/events.js +35 -0
  67. package/dist/src/runtime/fsm.js +120 -0
  68. package/dist/src/runtime/rules.js +565 -0
  69. package/dist/src/secrets.js +142 -0
  70. package/dist/src/service.js +406 -0
  71. package/dist/src/settings.js +144 -0
  72. package/dist/src/ssh-config.js +276 -0
  73. package/dist/src/ssh-failures.js +122 -0
  74. package/dist/src/ssh-port.js +4 -0
  75. package/dist/src/ssh-sftp.js +297 -0
  76. package/dist/src/ssh.js +477 -0
  77. package/dist/src/store.js +191 -0
  78. package/dist/src/tool-shared.js +181 -0
  79. package/dist/src/tools-exec-policy.js +167 -0
  80. package/dist/src/tools-exec.js +371 -0
  81. package/dist/src/tools-report.js +424 -0
  82. package/dist/src/tools.js +411 -0
  83. package/dist/src/tunnel.js +129 -0
  84. package/dist/src/util.js +149 -0
  85. package/dist/src/version.js +114 -0
  86. package/dist/src/watchdog-bus.js +29 -0
  87. package/dist/src/watchdog.js +156 -0
  88. package/index.js +5 -4
  89. package/locale/en.json +1 -1
  90. package/locale/zh.json +1 -1
  91. package/package.json +37 -19
  92. package/src/admission.js +0 -43
  93. package/src/api.js +0 -536
  94. package/src/atomic-json.js +0 -225
  95. package/src/bootstrap.js +0 -113
  96. package/src/connect-log.js +0 -176
  97. package/src/connect-pipeline.js +0 -1900
  98. package/src/connect-progress.js +0 -155
  99. package/src/diagnostics.js +0 -160
  100. package/src/download-jobs.js +0 -234
  101. package/src/errors.js +0 -412
  102. package/src/host-lifecycle.js +0 -604
  103. package/src/host-registry.js +0 -217
  104. package/src/host-runtime.js +0 -127
  105. package/src/host-view.js +0 -75
  106. package/src/index.js +0 -206
  107. package/src/key-files.js +0 -54
  108. package/src/known-hosts.js +0 -133
  109. package/src/layout.js +0 -53
  110. package/src/local-download.js +0 -381
  111. package/src/local-ssh.js +0 -27
  112. package/src/local-version.js +0 -88
  113. package/src/node-runtime.js +0 -521
  114. package/src/probe.js +0 -101
  115. package/src/prompts.js +0 -229
  116. package/src/redact.js +0 -68
  117. package/src/remote-files.js +0 -71
  118. package/src/remote-path.js +0 -137
  119. package/src/remote-proc.js +0 -343
  120. package/src/remote-proxy.js +0 -815
  121. package/src/remote-web.js +0 -751
  122. package/src/request-trust.js +0 -89
  123. package/src/secrets.js +0 -109
  124. package/src/service.js +0 -459
  125. package/src/settings.js +0 -163
  126. package/src/ssh-config.js +0 -271
  127. package/src/ssh.js +0 -731
  128. package/src/store.js +0 -193
  129. package/src/tools.js +0 -386
  130. package/src/tunnel.js +0 -132
  131. package/src/util.js +0 -153
  132. package/src/version.js +0 -103
  133. package/src/webapp.js +0 -43
  134. /package/{vendor → dist/vendor}/ssh2.bundle.cjs +0 -0
@@ -0,0 +1,346 @@
1
+ /**
2
+ * The plugin's own Node.js runtime on the remote: an official build, SHA-256 verified, under `$DSH_HOME/remote-go/node`; commands are fixed templates, never user-composed.
3
+ *
4
+ * The artifact scripts themselves — checksum discovery, verified download and unpack — live in
5
+ * `node/download.ts`; this module decides what can be reused and runs the install.
6
+ */
7
+ import { errors } from './errors.js';
8
+ import { headTail, messageOf, shellQuote } from './util.js';
9
+ import { MIN_NODE_VERSION, normalizeVersion, parseVersion } from './version.js';
10
+ import { buildNodeChecksumScript, buildNodeInstallScript, parseNodeChecksumOutput } from './node/download.js';
11
+ export const MANAGED_NODE_VERSION_FALLBACK = MIN_NODE_VERSION;
12
+ export function managedNodeVersionFromEngine(range, fallback = MANAGED_NODE_VERSION_FALLBACK) {
13
+ const text = String(range ?? '').trim();
14
+ if (text === '')
15
+ return normalizeVersion(fallback);
16
+ const first = text.split('||')[0].trim();
17
+ if (first === '' || first === '*' || first === 'latest')
18
+ return normalizeVersion(fallback);
19
+ // A strict `>` needs the next patch; `>=`, `^`, `~`, `=` and a bare version all
20
+ // mean that version itself.
21
+ const strict = /^>\s*v?(\d+)(?:\.(\d+))?(?:\.(\d+))?/.exec(first);
22
+ if (strict && !first.startsWith('>=')) {
23
+ return normalizeVersion(`${Number(strict[1])}.${Number(strict[2] ?? 0)}.${Number(strict[3] ?? 0) + 1}`);
24
+ }
25
+ const match = /(?:>=|\^|~|=)?\s*v?(\d+)(?:\.(\d+))?(?:\.(\d+))?/.exec(first);
26
+ if (!match)
27
+ return normalizeVersion(fallback);
28
+ return normalizeVersion(`${Number(match[1])}.${Number(match[2] ?? 0)}.${Number(match[3] ?? 0)}`);
29
+ }
30
+ const NODE_SCAN_TIMEOUT_MS = 30_000;
31
+ const NODE_CHECKSUM_TIMEOUT_MS = 240_000;
32
+ const NODE_INSTALL_TIMEOUT_MS = 30 * 60_000;
33
+ const NODE_MIN_FREE_KB = 400 * 1024;
34
+ const NODE_MIN_GLIBC = '2.28';
35
+ const DIST_ARCH = new Map([
36
+ ['x86_64', 'x64'],
37
+ ['amd64', 'x64'],
38
+ ['aarch64', 'arm64'],
39
+ ['arm64', 'arm64'],
40
+ ['armv7l', 'armv7l'],
41
+ ['armv7', 'armv7l'],
42
+ ['ppc64le', 'ppc64le'],
43
+ ['s390x', 's390x'],
44
+ ]);
45
+ export function nodeDistArch(arch) {
46
+ return DIST_ARCH.get(String(arch ?? '').toLowerCase()) ?? null;
47
+ }
48
+ function compareGlibc(left, right) {
49
+ const a = String(left ?? '').split('.');
50
+ const b = String(right ?? '').split('.');
51
+ const length = Math.max(a.length, b.length);
52
+ for (let index = 0; index < length; index += 1) {
53
+ const x = Number.parseInt(a[index] ?? '0', 10);
54
+ const y = Number.parseInt(b[index] ?? '0', 10);
55
+ const leftValue = Number.isFinite(x) ? x : 0;
56
+ const rightValue = Number.isFinite(y) ? y : 0;
57
+ if (leftValue !== rightValue)
58
+ return leftValue < rightValue ? -1 : 1;
59
+ }
60
+ return 0;
61
+ }
62
+ export function buildNodeScanScript(layout) {
63
+ return `set -u
64
+ NODE_DIR=${shellQuote(layout.nodeDir)}
65
+ if [ -d "$NODE_DIR" ]; then
66
+ for DIR in "$NODE_DIR"/*; do
67
+ [ -d "$DIR" ] || continue
68
+ [ -x "$DIR/bin/node" ] || continue
69
+ [ -x "$DIR/bin/npx" ] || continue
70
+ VER=$("$DIR/bin/node" -v 2>/dev/null || true)
71
+ case "$VER" in
72
+ v[0-9]*) printf 'NODE\\t%s\\t%s\\n' "\${VER#v}" "$DIR" ;;
73
+ esac
74
+ done
75
+ fi
76
+ `;
77
+ }
78
+ export function parseNodeScanOutput(stdout) {
79
+ const versions = [];
80
+ for (const rawLine of String(stdout ?? '').split(/\r?\n/)) {
81
+ const parts = rawLine.split('\t');
82
+ if (parts[0] !== 'NODE' || parts.length < 3)
83
+ continue;
84
+ const version = normalizeVersion(parts[1]);
85
+ if (!parseVersion(version))
86
+ continue;
87
+ if (versions.some((entry) => entry.version === version))
88
+ continue;
89
+ versions.push({ version, dir: parts[2] });
90
+ }
91
+ return versions;
92
+ }
93
+ function technicalOf(error) {
94
+ return messageOf(error ?? '');
95
+ }
96
+ function nodeError(detail, technical) {
97
+ return errors.nodeInstallFailed(detail, technical ? { technical } : undefined);
98
+ }
99
+ /** Run one remote command and normalize whatever shape the transport returned. */
100
+ async function runRemote(ssh, command, options) {
101
+ const result = await ssh.exec(command, options);
102
+ return {
103
+ code: typeof result?.code === 'number' ? result.code : 0,
104
+ stdout: String(result?.stdout ?? ''),
105
+ stderr: String(result?.stderr ?? ''),
106
+ };
107
+ }
108
+ async function scanManagedNode(ssh, layout) {
109
+ let result;
110
+ try {
111
+ result = await runRemote(ssh, buildNodeScanScript(layout), {
112
+ timeoutMs: NODE_SCAN_TIMEOUT_MS,
113
+ maxBytes: 200_000,
114
+ });
115
+ }
116
+ catch (error) {
117
+ throw nodeError({ zh: '无法检查远端托管的 Node。', en: 'Could not inspect the managed Node on the remote.' }, technicalOf(error));
118
+ }
119
+ if (result.code !== 0) {
120
+ throw nodeError({
121
+ zh: `无法检查远端托管的 Node(退出码 ${result.code})。`,
122
+ en: `Could not inspect the managed Node on the remote (exit ${result.code}).`,
123
+ }, headTail(result.stderr || result.stdout, 800));
124
+ }
125
+ return parseNodeScanOutput(result.stdout);
126
+ }
127
+ async function resolveNodeRelease(ssh, input) {
128
+ let result;
129
+ try {
130
+ result = await runRemote(ssh, buildNodeChecksumScript({
131
+ downloadDir: input.layout.downloadDir,
132
+ version: input.version,
133
+ arch: input.arch,
134
+ bases: input.bases,
135
+ }), { timeoutMs: NODE_CHECKSUM_TIMEOUT_MS, maxBytes: 200_000 });
136
+ }
137
+ catch (error) {
138
+ // swallow-ok: unreachable — a transport failure is reported as a typed resolution
139
+ // reason; the caller turns it into the install error.
140
+ return { ok: false, reason: 'unreachable', technical: technicalOf(error) };
141
+ }
142
+ if (result.code === 0) {
143
+ const release = parseNodeChecksumOutput(result.stdout, {
144
+ version: input.version,
145
+ arch: input.arch,
146
+ bases: input.bases,
147
+ });
148
+ if (release)
149
+ return { ok: true, release };
150
+ return { ok: false, reason: 'no-checksum', technical: headTail(result.stdout, 600) };
151
+ }
152
+ if (result.code === 9 || result.stdout.includes('FAILED\tno-fetch')) {
153
+ return { ok: false, reason: 'no-fetch' };
154
+ }
155
+ if (result.code === 5) {
156
+ return { ok: false, reason: 'unreachable', technical: headTail(result.stderr || result.stdout, 600) };
157
+ }
158
+ return { ok: false, reason: 'unreachable', technical: headTail(`${result.stdout}\n${result.stderr}`, 600) };
159
+ }
160
+ async function installNodeRelease(ssh, input) {
161
+ const expectedDir = `${input.layout.nodeDir}/v${input.release.version}`;
162
+ let buffered = '';
163
+ let dir = null;
164
+ let failure = null;
165
+ let lastBytes = -1;
166
+ let lastEmit = 0;
167
+ const handleLine = (line) => {
168
+ if (line === '')
169
+ return;
170
+ const parts = line.split('\t');
171
+ if (parts[0] === 'BYTES') {
172
+ const bytes = Number(parts[1]);
173
+ if (!Number.isFinite(bytes) || bytes < 0)
174
+ return;
175
+ const now = Date.now();
176
+ if (bytes - lastBytes < 8 * 1024 * 1024 && now - lastEmit < 5000 && bytes !== 0)
177
+ return;
178
+ lastBytes = bytes;
179
+ lastEmit = now;
180
+ input.onProgress({ step: 'download', version: input.release.version, bytes });
181
+ return;
182
+ }
183
+ if (parts[0] === 'STEP' && parts[1] === 'download') {
184
+ input.onProgress({ step: 'download', version: input.release.version, bytes: 0, source: parts[2] });
185
+ return;
186
+ }
187
+ if (parts[0] === 'STEP' && parts[1] === 'extract') {
188
+ input.onProgress({ step: 'extract', version: input.release.version });
189
+ return;
190
+ }
191
+ if (parts[0] === 'READY') {
192
+ dir = parts[1] ?? null;
193
+ return;
194
+ }
195
+ if (parts[0] === 'FAILED') {
196
+ failure = parts.slice(1).filter(Boolean).join(' ') || 'failed';
197
+ }
198
+ };
199
+ let result;
200
+ try {
201
+ result = await runRemote(ssh, buildNodeInstallScript({ layout: input.layout, release: input.release, bases: input.bases }), {
202
+ timeoutMs: NODE_INSTALL_TIMEOUT_MS,
203
+ maxBytes: 400_000,
204
+ onStdout: (chunk) => {
205
+ buffered += String(chunk ?? '');
206
+ const lines = buffered.split('\n');
207
+ buffered = lines.pop() ?? '';
208
+ for (const piece of lines)
209
+ handleLine(piece.replace(/\r$/, ''));
210
+ },
211
+ });
212
+ }
213
+ catch (error) {
214
+ // swallow-ok: unreachable — same contract as the checksum step: the caller turns
215
+ // it into the install error with the technical detail.
216
+ return { ok: false, reason: 'unreachable', technical: technicalOf(error) };
217
+ }
218
+ if (result.code !== 0 || !dir) {
219
+ return {
220
+ ok: false,
221
+ reason: failure ?? `exit ${result.code}`,
222
+ technical: headTail(`${result.stdout}\n${result.stderr}`, 800),
223
+ };
224
+ }
225
+ if (dir !== expectedDir) {
226
+ return { ok: false, reason: 'unexpected-location', technical: dir };
227
+ }
228
+ return { ok: true, dir };
229
+ }
230
+ export async function ensureRemoteNode(ssh, options) {
231
+ const facts = options.facts ?? {};
232
+ const layout = options.layout;
233
+ const version = normalizeVersion(options.version ?? MANAGED_NODE_VERSION_FALLBACK);
234
+ const onProgress = typeof options.onProgress === 'function' ? options.onProgress : () => { };
235
+ if (!layout?.nodeDir || !layout?.downloadDir) {
236
+ throw errors.internal('remote layout is missing the managed Node directories');
237
+ }
238
+ if (!parseVersion(version))
239
+ throw errors.internal(`invalid managed Node version: ${version}`);
240
+ if (!facts.home || !String(layout.nodeDir).startsWith('/')) {
241
+ throw nodeError({
242
+ zh: '远端主目录未知,无法准备托管的 Node。',
243
+ en: 'The remote home directory is unknown, so the managed Node cannot be prepared.',
244
+ });
245
+ }
246
+ if (String(facts.os ?? '') !== 'Linux') {
247
+ // The official builds this module installs are Linux-only; refusing here keeps a
248
+ // Darwin/Windows remote from downloading a binary that could never run.
249
+ throw errors.unsupportedOs(`${facts.os ?? 'unknown'} ${facts.arch ?? ''}`.trim());
250
+ }
251
+ if (facts.libc === 'glibc' && facts.glibcVersion && compareGlibc(facts.glibcVersion, NODE_MIN_GLIBC) < 0) {
252
+ throw nodeError({
253
+ zh: `远端 glibc ${facts.glibcVersion} 过低,Node 官方 Linux 构建需要 ≥ ${NODE_MIN_GLIBC}。请升级系统后重试。`,
254
+ en: `The remote glibc is ${facts.glibcVersion}, but the official Node Linux build needs >= ${NODE_MIN_GLIBC}. Upgrade the system and retry.`,
255
+ });
256
+ }
257
+ if (facts.libc === 'musl') {
258
+ throw nodeError({
259
+ zh: '远端使用 musl libc(如 Alpine),Node 官方构建无法运行;插件只使用自己的 Node,请换用 glibc 系统(如 Ubuntu/Debian)。',
260
+ en: 'The remote uses musl libc (for example Alpine), where the official Node build cannot run; the plugin only uses its own Node, so use a glibc system (such as Ubuntu/Debian).',
261
+ });
262
+ }
263
+ const arch = nodeDistArch(facts.arch);
264
+ if (!arch) {
265
+ throw nodeError({
266
+ zh: `远端架构「${facts.arch}」没有对应的 Node 官方构建。插件只使用自己的 Node,请换一台受支持的架构。`,
267
+ en: `No official Node build exists for the remote architecture "${facts.arch}". The plugin only uses its own Node, so use a supported architecture.`,
268
+ });
269
+ }
270
+ if (typeof facts.diskFreeKb === 'number' && facts.diskFreeKb > 0 && facts.diskFreeKb < NODE_MIN_FREE_KB) {
271
+ throw nodeError({
272
+ zh: `远端磁盘空间不足(可用约 ${Math.round(facts.diskFreeKb / 1024)} MB,至少需要 ${Math.round(NODE_MIN_FREE_KB / 1024)} MB)。`,
273
+ en: `The remote has too little free space (about ${Math.round(facts.diskFreeKb / 1024)} MB; at least ${Math.round(NODE_MIN_FREE_KB / 1024)} MB is required).`,
274
+ });
275
+ }
276
+ onProgress({ step: 'check', version });
277
+ const installed = await scanManagedNode(ssh, layout);
278
+ let current = installed.find((entry) => entry.version === version) ?? null;
279
+ let installedNow = false;
280
+ if (!current) {
281
+ onProgress({ step: 'checksum', version });
282
+ const resolved = await resolveNodeRelease(ssh, {
283
+ layout,
284
+ version,
285
+ arch,
286
+ bases: options.bases,
287
+ });
288
+ if (resolved.ok === false) {
289
+ throw nodeError(resolveFailureDetail(resolved.reason, version), resolved.technical ?? `reason=${resolved.reason}`);
290
+ }
291
+ onProgress({ step: 'install', version });
292
+ const install = await installNodeRelease(ssh, {
293
+ layout,
294
+ release: resolved.release,
295
+ bases: options.bases,
296
+ onProgress,
297
+ });
298
+ if (install.ok === false) {
299
+ throw nodeError({
300
+ zh: `自动安装 Node ${version} 失败(${install.reason})。`,
301
+ en: `Automatically installing Node ${version} failed (${install.reason}).`,
302
+ }, install.technical);
303
+ }
304
+ current = { version, dir: install.dir };
305
+ installedNow = true;
306
+ }
307
+ onProgress({ step: 'ready', version });
308
+ const nodeBinDir = `${current.dir}/bin`;
309
+ return {
310
+ managed: true,
311
+ version: current.version,
312
+ nodePath: `${nodeBinDir}/node`,
313
+ npmPath: `${nodeBinDir}/npm`,
314
+ npxPath: `${nodeBinDir}/npx`,
315
+ nodeBinDir,
316
+ installed: installedNow,
317
+ };
318
+ }
319
+ function resolveFailureDetail(reason, version) {
320
+ if (reason === 'no-fetch') {
321
+ return {
322
+ zh: '远端既没有 curl 也没有 wget,无法下载 Node。请安装其中一个后重试。',
323
+ en: 'The remote has neither curl nor wget, so Node cannot be downloaded. Install one of them and retry.',
324
+ };
325
+ }
326
+ if (reason === 'no-checksum') {
327
+ return {
328
+ zh: `没有在 Node 官方索引里找到 v${version} 的 linux 构建校验和。`,
329
+ en: `No linux build checksum was found in the official Node index for v${version}.`,
330
+ };
331
+ }
332
+ return {
333
+ zh: '无法从 nodejs.org / npmmirror.com 下载 Node(远端网络不可达或被拦截)。',
334
+ en: 'Node could not be downloaded from nodejs.org / npmmirror.com (the remote network is unreachable or blocked).',
335
+ };
336
+ }
337
+ export function applyManagedNodeFacts(facts, managed) {
338
+ return {
339
+ ...facts,
340
+ nodePath: managed.nodePath,
341
+ nodeBinDir: managed.nodeBinDir,
342
+ nodeVersion: normalizeVersion(managed.version),
343
+ npmPath: managed.npmPath ?? facts.npmPath,
344
+ npxPath: managed.npxPath,
345
+ };
346
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * One read-only remote probe: a single POSIX `sh` script prints `key<TAB>value` lines that become the facts used by the planner, the Node installer and diagnostics.
3
+ */
4
+ import { headTail } from './util.js';
5
+ import { errors } from './errors.js';
6
+ import { normalizeVersion } from './version.js';
7
+ export function buildProbeScript() {
8
+ return `set -u
9
+ echo "os\t$(uname -s 2>/dev/null || echo unknown)"
10
+ echo "arch\t$(uname -m 2>/dev/null || echo unknown)"
11
+ echo "os_name\t$(sed -n 's/^PRETTY_NAME="\\(.*\\)"$/\\1/p' /etc/os-release 2>/dev/null | head -n 1)"
12
+ echo "user\t$(id -un 2>/dev/null || echo unknown)"
13
+ echo "home\t$HOME"
14
+ echo "shell\t\${SHELL:-unknown}"
15
+ NODE_PATH_1="$(command -v node 2>/dev/null || true)"
16
+ echo "node_path\t$NODE_PATH_1"
17
+ if [ -n "$NODE_PATH_1" ]; then echo "node_version\t$(timeout 10 "$NODE_PATH_1" -v 2>/dev/null || true)"; else echo "node_version\t"; fi
18
+ echo "npm_path\t$(command -v npm 2>/dev/null || true)"
19
+ echo "npx_path\t$(command -v npx 2>/dev/null || true)"
20
+ echo "curl_path\t$(command -v curl 2>/dev/null || true)"
21
+ echo "wget_path\t$(command -v wget 2>/dev/null || true)"
22
+ if [ -f /etc/alpine-release ]; then
23
+ echo "libc\tmusl"
24
+ elif command -v ldd >/dev/null 2>&1 && ldd --version 2>&1 | head -n 1 | grep -qi musl; then
25
+ echo "libc\tmusl"
26
+ else
27
+ echo "libc\tglibc"
28
+ fi
29
+ echo "glibc_version\t$(getconf GNU_LIBC_VERSION 2>/dev/null | awk '{print $2}' || true)"
30
+ echo "disk_free_kb\t$(df -Pk "$HOME" 2>/dev/null | awk 'NR==2 {print $4}' || true)"
31
+ if [ -n "\${SSH_CONNECTION:-}" ] || [ -n "\${SSH_TTY:-}" ]; then echo "ssh_connection\tyes"; else echo "ssh_connection\tno"; fi
32
+ [ -f "$HOME/.dsh/.credentials.yaml" ] && echo "credentials_file\tyes" || echo "credentials_file\tno"
33
+ if [ -n "\${DEEPSEEK_API_KEY:-}" ]; then echo "deepseek_key_env\tyes"; else echo "deepseek_key_env\tno"; fi
34
+ echo "provider_env_keys\t$(env 2>/dev/null | sed -n 's/^\\([A-Z0-9_]*\\)_API_KEY=.*/\\1/p' | tr '\\n' ',' | sed 's/,$//')"
35
+ `;
36
+ }
37
+ export function parseProbeOutput(stdout) {
38
+ const values = {};
39
+ for (const rawLine of String(stdout ?? '').split(/\r?\n/)) {
40
+ const tab = rawLine.indexOf('\t');
41
+ if (tab < 0)
42
+ continue;
43
+ const key = rawLine.slice(0, tab).trim();
44
+ const value = rawLine.slice(tab + 1).trim();
45
+ if (key !== '')
46
+ values[key] = value;
47
+ }
48
+ return values;
49
+ }
50
+ export function toProbeFacts(values) {
51
+ const num = (value) => {
52
+ const n = Number(value);
53
+ return Number.isFinite(n) ? n : null;
54
+ };
55
+ return {
56
+ os: values.os || 'unknown',
57
+ arch: values.arch || 'unknown',
58
+ osName: values.os_name || '',
59
+ user: values.user || '',
60
+ home: values.home || '',
61
+ shell: values.shell || '',
62
+ nodePath: values.node_path || null,
63
+ nodeVersion: values.node_version ? normalizeVersion(values.node_version) : null,
64
+ npmPath: values.npm_path || null,
65
+ npxPath: values.npx_path || null,
66
+ curlPath: values.curl_path || null,
67
+ wgetPath: values.wget_path || null,
68
+ libc: values.libc === 'musl' ? 'musl' : values.libc === 'glibc' ? 'glibc' : 'unknown',
69
+ glibcVersion: values.glibc_version ? String(values.glibc_version).trim() : null,
70
+ diskFreeKb: num(values.disk_free_kb),
71
+ sshConnection: values.ssh_connection === 'yes',
72
+ credentialsFile: values.credentials_file === 'yes',
73
+ deepseekKeyEnv: values.deepseek_key_env === 'yes',
74
+ providerEnvKeys: values.provider_env_keys ? values.provider_env_keys.split(',').filter(Boolean) : [],
75
+ };
76
+ }
77
+ export async function probeRemote(ssh, options = {}) {
78
+ const script = buildProbeScript();
79
+ const timeoutMs = options.timeoutMs ?? 60_000;
80
+ const result = await ssh.exec(script, { timeoutMs });
81
+ // A probe that ran out of time says nothing about the remote's DSH: report a timeout
82
+ // (retryable network), not a missing remote runtime (L).
83
+ if (result.timedOut === true) {
84
+ throw errors.network({
85
+ zh: `远端环境探测超过 ${Math.round(timeoutMs / 1000)} 秒没有完成,可能是链路很慢或远端负载过高。`,
86
+ en: `The remote environment probe did not finish within ${Math.round(timeoutMs / 1000)}s; the link may be slow or the remote overloaded.`,
87
+ }, { technical: `reason=probe-timeout timeoutMs=${timeoutMs}` });
88
+ }
89
+ if (result.code !== 0) {
90
+ throw errors.remoteDshMissing({
91
+ zh: `远端环境探测失败(退出码 ${result.code}):${headTail(result.stderr || result.stdout, 400)}`,
92
+ en: `Remote probe failed (exit ${result.code}): ${headTail(result.stderr || result.stdout, 400)}`,
93
+ });
94
+ }
95
+ return toProbeFacts(parseProbeOutput(result.stdout));
96
+ }