dsh-remote-go 0.2.0 → 0.3.1

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 (135) hide show
  1. package/README.md +11 -3
  2. package/{client.js → dist/client.js} +7144 -8367
  3. package/dist/index.js +4 -0
  4. package/dist/src/admission.js +21 -0
  5. package/dist/src/api.js +380 -0
  6. package/dist/src/atomic-json.js +201 -0
  7. package/dist/src/bootstrap.js +96 -0
  8. package/dist/src/connect/attach.js +21 -0
  9. package/dist/src/connect/bootstrap.js +8 -0
  10. package/dist/src/connect/failures.js +29 -0
  11. package/dist/src/connect/guards.js +36 -0
  12. package/dist/src/connect/launch.js +70 -0
  13. package/dist/src/connect/links.js +54 -0
  14. package/dist/src/connect/ownership.js +139 -0
  15. package/dist/src/connect/pipeline.js +376 -0
  16. package/dist/src/connect/reattach.js +191 -0
  17. package/dist/src/connect/registry.js +10 -0
  18. package/dist/src/connect/repair.js +97 -0
  19. package/dist/src/connect/restart.js +255 -0
  20. package/dist/src/connect/stop.js +164 -0
  21. package/dist/src/connect/transport.js +101 -0
  22. package/dist/src/connect/verify.js +30 -0
  23. package/dist/src/connect/watchdog.js +44 -0
  24. package/dist/src/connect-log.js +137 -0
  25. package/dist/src/connect-progress.js +110 -0
  26. package/dist/src/constants.js +29 -0
  27. package/dist/src/context.js +96 -0
  28. package/dist/src/diagnostics.js +133 -0
  29. package/dist/src/download-jobs.js +221 -0
  30. package/dist/src/errors.js +228 -0
  31. package/dist/src/events.js +326 -0
  32. package/dist/src/host-lifecycle.js +368 -0
  33. package/dist/src/host-registry.js +181 -0
  34. package/dist/src/host-runtime.js +77 -0
  35. package/dist/src/host-view.js +52 -0
  36. package/dist/src/index.js +196 -0
  37. package/dist/src/kernel-adapter.js +388 -0
  38. package/dist/src/key-files.js +39 -0
  39. package/dist/src/known-hosts.js +104 -0
  40. package/dist/src/layout.js +26 -0
  41. package/dist/src/local-download.js +311 -0
  42. package/dist/src/local-ssh.js +23 -0
  43. package/dist/src/local-version.js +87 -0
  44. package/dist/src/node/download.js +157 -0
  45. package/dist/src/node-runtime.js +327 -0
  46. package/dist/src/probe.js +95 -0
  47. package/dist/src/prompts.js +198 -0
  48. package/dist/src/proxy/cookies.js +102 -0
  49. package/dist/src/proxy/headers.js +167 -0
  50. package/dist/src/proxy/http.js +134 -0
  51. package/dist/src/proxy/index.js +121 -0
  52. package/dist/src/proxy/limits.js +6 -0
  53. package/dist/src/proxy/routes.js +32 -0
  54. package/dist/src/proxy/upgrade.js +160 -0
  55. package/dist/src/redact.js +85 -0
  56. package/dist/src/remote-files.js +60 -0
  57. package/dist/src/remote-path.js +82 -0
  58. package/dist/src/remote-proc.js +271 -0
  59. package/dist/src/remote-web/registry.js +107 -0
  60. package/dist/src/remote-web/resolve.js +229 -0
  61. package/dist/src/remote-web/start.js +190 -0
  62. package/dist/src/remote-web/stop.js +74 -0
  63. package/dist/src/request-trust.js +70 -0
  64. package/dist/src/runtime/dispatch.js +200 -0
  65. package/dist/src/runtime/effects.js +81 -0
  66. package/dist/src/runtime/events.js +35 -0
  67. package/dist/src/runtime/fsm.js +70 -0
  68. package/dist/src/runtime/rules.js +480 -0
  69. package/dist/src/secrets.js +119 -0
  70. package/dist/src/service.js +300 -0
  71. package/dist/src/settings.js +143 -0
  72. package/dist/src/ssh-config.js +257 -0
  73. package/dist/src/ssh-failures.js +71 -0
  74. package/dist/src/ssh-port.js +4 -0
  75. package/dist/src/ssh-sftp.js +258 -0
  76. package/dist/src/ssh.js +395 -0
  77. package/dist/src/store.js +174 -0
  78. package/dist/src/tool-shared.js +146 -0
  79. package/dist/src/tools-exec-policy.js +121 -0
  80. package/dist/src/tools-exec.js +307 -0
  81. package/dist/src/tools-report.js +357 -0
  82. package/dist/src/tools.js +337 -0
  83. package/dist/src/tunnel.js +111 -0
  84. package/dist/src/util.js +112 -0
  85. package/dist/src/version.js +108 -0
  86. package/dist/src/watchdog-bus.js +21 -0
  87. package/dist/src/watchdog.js +116 -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/constants.js +0 -93
  100. package/src/diagnostics.js +0 -160
  101. package/src/download-jobs.js +0 -234
  102. package/src/errors.js +0 -412
  103. package/src/host-lifecycle.js +0 -604
  104. package/src/host-registry.js +0 -217
  105. package/src/host-runtime.js +0 -127
  106. package/src/host-view.js +0 -75
  107. package/src/index.js +0 -206
  108. package/src/key-files.js +0 -54
  109. package/src/known-hosts.js +0 -133
  110. package/src/layout.js +0 -53
  111. package/src/local-download.js +0 -381
  112. package/src/local-ssh.js +0 -27
  113. package/src/local-version.js +0 -88
  114. package/src/node-runtime.js +0 -521
  115. package/src/probe.js +0 -101
  116. package/src/prompts.js +0 -229
  117. package/src/redact.js +0 -68
  118. package/src/remote-files.js +0 -71
  119. package/src/remote-path.js +0 -137
  120. package/src/remote-proc.js +0 -343
  121. package/src/remote-proxy.js +0 -815
  122. package/src/remote-web.js +0 -751
  123. package/src/request-trust.js +0 -89
  124. package/src/secrets.js +0 -109
  125. package/src/service.js +0 -459
  126. package/src/settings.js +0 -163
  127. package/src/ssh-config.js +0 -271
  128. package/src/ssh.js +0 -731
  129. package/src/store.js +0 -193
  130. package/src/tools.js +0 -386
  131. package/src/tunnel.js +0 -132
  132. package/src/util.js +0 -153
  133. package/src/version.js +0 -103
  134. package/src/webapp.js +0 -43
  135. /package/{vendor → dist/vendor}/ssh2.bundle.cjs +0 -0
@@ -0,0 +1,44 @@
1
+ import { messageOf } from '../util.js';
2
+ import { watchable } from '../watchdog.js';
3
+ /** A liveness episode recovered: the remote answers the SSH probe again, so the local listener is what may still be broken. Probe the listener first — one failed upstream connection is not a broken tunnel, and rebuilding drops live WebSockets — then rebuild it when it really is down. */
4
+ async function onRecovered(ctx, entries, runtime, source) {
5
+ if (source === 'proxy' || source === 'tunnel') {
6
+ let healthy = false;
7
+ try {
8
+ healthy = (await ctx.deps.tunnelProbe?.(runtime.tunnel?.localPort ?? null)) === true;
9
+ }
10
+ catch {
11
+ // swallow-ok: a probe error means "not healthy"; the rebuild path reports its own failure
12
+ }
13
+ if (healthy) {
14
+ ctx.progress.log(runtime, 'debug', 'the local tunnel still answers; keeping the listener');
15
+ }
16
+ else {
17
+ try {
18
+ const repaired = await entries.repair(runtime);
19
+ if (repaired && repaired.ok !== true)
20
+ ctx.progress.log(runtime, 'debug', `tunnel rebuild skipped (${repaired.reason ?? 'unknown'})`);
21
+ }
22
+ catch (error) {
23
+ // swallow-ok: a failed repair is reported by the helper; the episode still recovers
24
+ ctx.progress.log(runtime, 'warn', 'tunnel rebuild failed:', messageOf(error));
25
+ }
26
+ }
27
+ }
28
+ ctx.progress.log(runtime, 'info', `remote heartbeat: the remote UI answers again (${source})`);
29
+ if (!watchable(ctx, runtime))
30
+ return;
31
+ ctx.onRemoteUnreachable?.(runtime, { phase: 'recovered', source });
32
+ }
33
+ function runWatchdogEvent(ctx, entries, event) {
34
+ const runtime = ctx.state.runtimes.get(event.hostId);
35
+ if (!runtime)
36
+ return;
37
+ if (event.kind === 'confirmed')
38
+ void entries.reattach(runtime, { reason: event.reason, source: event.source });
39
+ else
40
+ void onRecovered(ctx, entries, runtime, event.source);
41
+ }
42
+ export function installWatchdog(ctx, entries) {
43
+ return ctx.bus.subscribe((event) => runWatchdogEvent(ctx, entries, event));
44
+ }
@@ -0,0 +1,137 @@
1
+ /** The connect log behind `HostView.logs`: the per-host ring, the per-connection reset, the structured failure lines,
2
+ * its bounded `/state` tail and which statuses print it. */
3
+ import { redactText } from './redact.js';
4
+ import { headTail, isPlainObject } from './util.js';
5
+ export const CONNECT_LOG_STATUSES = Object.freeze(['connecting', 'fingerprint-pending', 'error']);
6
+ export const LOG_RING_LIMIT = 200;
7
+ export const LOG_TAIL_LIMIT = 120;
8
+ export const LOG_TECHNICAL_LIMIT = 1200;
9
+ export const LOG_LINE_LIMIT = 400;
10
+ export const LOG_TAIL_LINES = 60;
11
+ export function connectLogVisible(status) {
12
+ return typeof status === 'string' && CONNECT_LOG_STATUSES.includes(status);
13
+ }
14
+ function normalizeText(value) {
15
+ if (!isPlainObject(value))
16
+ return null;
17
+ const zh = typeof value.zh === 'string' ? value.zh : '';
18
+ const en = typeof value.en === 'string' ? value.en : '';
19
+ if (zh === '' || en === '')
20
+ return null;
21
+ return { zh, en };
22
+ }
23
+ export function appendConnectLog(runtime, input) {
24
+ const raw = typeof input.message === 'string' ? input.message : String(input.message ?? '');
25
+ // The remote's own stdout lands here (the first launch line carries its session token) and this
26
+ // ring is the second exit of that text, so it is redacted at write time, not only in the view.
27
+ const message = headTail(redactText(raw), LOG_TECHNICAL_LIMIT);
28
+ const entry = {
29
+ seq: (typeof runtime.logSeq === 'number' ? runtime.logSeq : 0) + 1,
30
+ at: typeof input.at === 'string' ? input.at : '',
31
+ level: typeof input.level === 'string' ? input.level : 'info',
32
+ phase: typeof input.phase === 'string' && input.phase !== '' ? input.phase : null,
33
+ message,
34
+ line: `[dsh-remote-go:${runtime.id}] ${message}`,
35
+ };
36
+ const text = normalizeText(input.text);
37
+ if (text !== null)
38
+ entry.text = text;
39
+ if (input.boundary === true)
40
+ entry.boundary = true;
41
+ if (!Array.isArray(runtime.logs))
42
+ runtime.logs = [];
43
+ if (runtime.logs.length >= LOG_RING_LIMIT)
44
+ runtime.logs.shift();
45
+ runtime.logSeq = entry.seq;
46
+ runtime.logs.push(entry);
47
+ return entry;
48
+ }
49
+ export function resetConnectLog(runtime) {
50
+ runtime.logs = [];
51
+ runtime.logSeq = 0;
52
+ return runtime;
53
+ }
54
+ function localClock(date) {
55
+ const pad = (value) => String(value).padStart(2, '0');
56
+ return (`${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` +
57
+ `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`);
58
+ }
59
+ /** Start one connection's log: drop the previous attempt and write its boundary line, so the panel opens on this
60
+ * attempt only and a copied log says which attempt it belongs to. */
61
+ export function beginConnectLog(runtime, options = {}) {
62
+ const at = typeof options.at === 'string' && options.at !== '' ? options.at : new Date().toISOString();
63
+ const when = new Date(at);
64
+ const attempt = (typeof runtime.connectCount === 'number' ? runtime.connectCount : 0) + 1;
65
+ runtime.connectCount = attempt;
66
+ resetConnectLog(runtime);
67
+ const clock = Number.isNaN(when.getTime()) ? at : localClock(when);
68
+ const text = { zh: `— 第 ${attempt} 次连接 · ${clock} —`, en: `— Connection ${attempt} · ${clock} —` };
69
+ return appendConnectLog(runtime, { at, level: 'info', message: text.en, text, boundary: true });
70
+ }
71
+ function say(value) {
72
+ if (typeof value === 'string')
73
+ return value === '' ? null : { zh: value, en: value };
74
+ if (!isPlainObject(value))
75
+ return null;
76
+ const zh = typeof value.zh === 'string' ? value.zh : '';
77
+ const en = typeof value.en === 'string' ? value.en : '';
78
+ if (zh === '' && en === '')
79
+ return null;
80
+ return { zh: zh === '' ? en : zh, en: en === '' ? zh : en };
81
+ }
82
+ /** The lines the log prints for a failed connection: phase/code, the localized reason, every hint, then the redacted
83
+ * head-tail-truncated technical detail. `options.label` replaces the first line for a one-shot action (remote stop). */
84
+ export function connectFailureLines(view, options = {}) {
85
+ const code = typeof view?.code === 'string' && view.code !== '' ? view.code : 'internal';
86
+ const phase = typeof options.phase === 'string' && options.phase !== '' ? options.phase : null;
87
+ const lines = [];
88
+ const push = (text) => lines.push({ level: 'error', phase, message: text.en, text });
89
+ const raw = (message) => lines.push({ level: 'error', phase, message });
90
+ const label = normalizeText(options.label);
91
+ push(label ??
92
+ (phase === null
93
+ ? { zh: `连接失败:${code}`, en: `Connect failed: ${code}` }
94
+ : { zh: `连接失败于 ${phase} 阶段:${code}`, en: `Connect failed in phase ${phase}: ${code}` }));
95
+ const reason = say(view?.detail) ?? say(view?.title);
96
+ if (reason !== null)
97
+ push({ zh: `原因:${reason.zh}`, en: `Reason: ${reason.en}` });
98
+ const hints = Array.isArray(view?.nextSteps) ? view.nextSteps : [];
99
+ for (const hint of hints) {
100
+ const step = say(hint);
101
+ if (step !== null)
102
+ push({ zh: `建议:${step.zh}`, en: `Next: ${step.en}` });
103
+ }
104
+ const technical = typeof view?.technical === 'string' ? view.technical : '';
105
+ if (technical.trim() !== '') {
106
+ const tail = code === 'remote-dsh-start-failed';
107
+ push(tail ? { zh: '远端日志尾部:', en: 'Remote log tail:' } : { zh: '技术细节:', en: 'Details:' });
108
+ let printed = 0;
109
+ for (const line of headTail(redactText(technical), LOG_TECHNICAL_LIMIT).split(/\r?\n/)) {
110
+ if (printed >= LOG_TAIL_LINES)
111
+ break;
112
+ if (line.trim() === '')
113
+ continue;
114
+ raw(headTail(line, LOG_LINE_LIMIT));
115
+ printed += 1;
116
+ }
117
+ }
118
+ return lines;
119
+ }
120
+ export function connectLogTail(runtime) {
121
+ const entries = runtime && Array.isArray(runtime.logs) ? runtime.logs : [];
122
+ return entries.slice(-LOG_TAIL_LIMIT).map((entry) => {
123
+ const item = {
124
+ seq: typeof entry.seq === 'number' ? entry.seq : 0,
125
+ at: typeof entry.at === 'string' ? entry.at : '',
126
+ level: typeof entry.level === 'string' ? entry.level : 'info',
127
+ phase: typeof entry.phase === 'string' && entry.phase !== '' ? entry.phase : null,
128
+ message: typeof entry.message === 'string' ? entry.message : String(entry.line ?? ''),
129
+ };
130
+ const text = normalizeText(entry.text);
131
+ if (text !== null)
132
+ item.text = text;
133
+ if (entry.boundary === true)
134
+ item.boundary = true;
135
+ return item;
136
+ });
137
+ }
@@ -0,0 +1,110 @@
1
+ /** Connect progress: the staged progress line (published on the state channel) and the log rows (published on the log
2
+ * channel); it never sets a host status. */
3
+ import { appendConnectLog, connectFailureLines, connectLogVisible } from './connect-log.js';
4
+ import { logVisible, nowIso } from './util.js';
5
+ const REPORT_MIN_INTERVAL_MS = 700;
6
+ function stripAnsi(text) {
7
+ return String(text ?? '').replace(/\u001B\[[0-9;]*m/g, '');
8
+ }
9
+ /** Turn one npm/npx output line into a progress event: known shapes get a localized code (the package's own `--version`
10
+ * output is the success signal, not progress), anything else is kept truncated as a detail. */
11
+ export function describePreflightEvent(line, version) {
12
+ const text = stripAnsi(line).trim();
13
+ if (text === '')
14
+ return null;
15
+ if (/^v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(text))
16
+ return null;
17
+ if (/The following package was not found and will be installed/i.test(text)) {
18
+ return { code: 'bootstrap-first-run', params: { version } };
19
+ }
20
+ if (/^npm (http fetch|http request)/i.test(text))
21
+ return { code: 'bootstrap-fetching' };
22
+ if (/added \d+ packages? in/i.test(text))
23
+ return { code: 'bootstrap-installed' };
24
+ return { code: 'bootstrap-progress', params: { detail: text.slice(0, 160) } };
25
+ }
26
+ export function createConnectProgress(options) {
27
+ function write(runtime, input) {
28
+ const entry = appendConnectLog(runtime, { at: nowIso(), ...input });
29
+ // Verbosity is a runtime decision: `options.logLevel` (tests, diagnostics) or settings.
30
+ const threshold = options.logLevel ?? options.getSettings()?.logLevel ?? 'info';
31
+ if (!logVisible(entry.level, threshold))
32
+ return entry;
33
+ const method = options.logger[entry.level] ?? options.logger.info;
34
+ method?.(entry.line);
35
+ return entry;
36
+ }
37
+ /** Hand the appended rows to the log channel; a log line is not a state change (docs/api.md v2.12). */
38
+ function publish(runtime) {
39
+ if (!connectLogVisible(runtime.status))
40
+ return;
41
+ options.emitLogs?.(runtime);
42
+ }
43
+ function log(runtime, level, ...args) {
44
+ const message = args.map((value) => (typeof value === 'string' ? value : JSON.stringify(value))).join(' ');
45
+ const entry = write(runtime, { level, message, phase: runtime.phase });
46
+ publish(runtime);
47
+ return entry;
48
+ }
49
+ /** Print a failed connection as the lines that explain it; `context.label` replaces the leading line for a stop. */
50
+ function logFailure(runtime, view, context = {}) {
51
+ const phase = typeof context.phase === 'string' && context.phase !== '' ? context.phase : null;
52
+ for (const line of connectFailureLines(view, { phase, label: context.label })) {
53
+ write(runtime, { level: line.level, message: line.message, text: line.text, phase: line.phase });
54
+ }
55
+ publish(runtime);
56
+ }
57
+ function phase(runtime, phaseName, code, params) {
58
+ runtime.phase = phaseName;
59
+ runtime.progress = { code, ...(params ? { params } : {}) };
60
+ options.emitState();
61
+ }
62
+ function nodeProgress(runtime, event) {
63
+ if (event.step === 'check')
64
+ return;
65
+ if (event.step === 'download') {
66
+ const mb = Math.max(0, Math.round(Number(event.bytes ?? 0) / (1024 * 1024)));
67
+ log(runtime, 'info', `downloading managed Node v${event.version} (${mb} MB so far)`);
68
+ phase(runtime, 'bootstrap', 'downloading-node', { version: event.version, mb });
69
+ return;
70
+ }
71
+ if (event.step === 'ready') {
72
+ log(runtime, 'info', `managed Node v${event.version} is ready`);
73
+ return;
74
+ }
75
+ log(runtime, 'info', `installing managed Node v${event.version}`);
76
+ phase(runtime, 'bootstrap', 'installing-node', { version: event.version });
77
+ }
78
+ /** Stream one channel of the npx preflight into the progress line: each line becomes a short detail, throttled so the
79
+ * SSE stream is not flooded (npm has no TTY over SSH). */
80
+ function bootstrapReporter(runtime, version) {
81
+ let buffer = '';
82
+ let lastAt = 0;
83
+ let lastKey = '';
84
+ return (chunk) => {
85
+ buffer += String(chunk ?? '');
86
+ const lines = buffer.split(/\r?\n/);
87
+ buffer = lines.pop() ?? '';
88
+ for (const rawLine of lines) {
89
+ const text = stripAnsi(rawLine).trim();
90
+ // npx is the slowest step on a cold cache: print what it says at debug level.
91
+ if (text !== '')
92
+ log(runtime, 'debug', `npx: ${text}`);
93
+ const event = describePreflightEvent(rawLine, version);
94
+ if (!event)
95
+ continue;
96
+ const key = `${event.code}:${event.params?.detail ?? ''}`;
97
+ if (key === lastKey)
98
+ continue;
99
+ const now = Date.now();
100
+ if (now - lastAt < REPORT_MIN_INTERVAL_MS)
101
+ continue;
102
+ lastAt = now;
103
+ lastKey = key;
104
+ phase(runtime, 'bootstrap', event.code, event.params);
105
+ }
106
+ };
107
+ }
108
+ function dispose() { }
109
+ return { log, logFailure, phase, nodeProgress, bootstrapReporter, dispose };
110
+ }
@@ -0,0 +1,29 @@
1
+ /** Shared constants for the remote npx runtime and the plugin surface. */
2
+ export const DEFAULT_REMOTE_PROFILE = 'web';
3
+ export const REMOTE_DSH_DIR = '.dsh';
4
+ export const REMOTE_STATE_DIR = 'remote-go';
5
+ export const API_PREFIX = '/dsh-remote-go/api';
6
+ export const REMOTE_VIEW_PREFIX = '/dsh-remote-go/remote/';
7
+ export const API_HEADER = 'x-dsh-remote-go';
8
+ export const PLUGIN_ID = 'dsh-remote-go';
9
+ export const PLUGIN_VERSION = '0.3.1';
10
+ export const MIN_DSH_VERSION = '0.2.2-rc.3';
11
+ export const API_VERSION = '2.12';
12
+ export const DEFAULT_KEY_PATH = '~/.ssh/id_rsa';
13
+ export const REMOTE_START_TIMEOUT_MS = 300_000;
14
+ export const REMOTE_CONFLICT_TIMEOUT_MS = 120_000;
15
+ export const SSH_READY_TIMEOUT_MS = 20_000;
16
+ export const DEFAULT_IDLE_MINUTES = 15;
17
+ export const TUNNEL_PROBE_TIMEOUT_MS = 10_000;
18
+ export const REMOTE_HEARTBEAT_DEFAULT_SEC = 30;
19
+ export const REMOTE_HEARTBEAT_MIN_SEC = 5;
20
+ export const REMOTE_HEARTBEAT_MAX_SEC = 600;
21
+ export const REMOTE_UNREACHABLE_FAILURES = 2;
22
+ export const REMOTE_UNREACHABLE_CONFIRM_DELAY_MS = 750;
23
+ export const REMOTE_UNREACHABLE_RECHECK_DELAY_MS = 1200;
24
+ export const REMOTE_EPISODE_COOLDOWN_MS = 15_000;
25
+ export const REMOTE_REPAIR_BACKOFF_MS = 30_000;
26
+ export const REMOTE_REPAIR_BACKOFF_MAX_MS = 120_000;
27
+ export const REMOTE_TUNNEL_REPAIR_SETTLE_MS = 5_000;
28
+ export const REMOTE_REATTACH_ATTEMPTS = 6;
29
+ export const REMOTE_REATTACH_INTERVAL_MS = 2_000;
@@ -0,0 +1,96 @@
1
+ /** The assembled service context: the one file that knows every injected leaf. Six narrow slices replaced the old
2
+ * 47-key god-`ctx`, so a module reaches only the capability it declares; the assembled object keeps the same keys and
3
+ * paths because tests use `service.ctx` as public API. Narrowing is in the parameter types, never a rename. */
4
+ import { planNpx, verifyNpxVersion } from './bootstrap.js';
5
+ import { REMOTE_CONFLICT_TIMEOUT_MS, REMOTE_REATTACH_ATTEMPTS, REMOTE_REATTACH_INTERVAL_MS, REMOTE_TUNNEL_REPAIR_SETTLE_MS, REMOTE_UNREACHABLE_CONFIRM_DELAY_MS, REMOTE_UNREACHABLE_RECHECK_DELAY_MS, } from './constants.js';
6
+ import { createConnectProgress } from './connect-progress.js';
7
+ import { loadLocalSshMaterial } from './local-ssh.js';
8
+ import { ensureRemoteNode } from './node-runtime.js';
9
+ import { probeRemote } from './probe.js';
10
+ import { exchangeTokenOverTunnel, findForeignDshProcesses, remoteHttpStatus, remoteProcessIdentity, stopForeignDshProcesses, waitForRemoteUi, } from './remote-proc.js';
11
+ import { clearRunRegistry, readRunRegistry, writeRunRegistry } from './remote-web/registry.js';
12
+ import { adoptRemoteWeb, resolveRemoteWeb } from './remote-web/resolve.js';
13
+ import { startRemoteWeb } from './remote-web/start.js';
14
+ import { stopRemoteWeb } from './remote-web/stop.js';
15
+ import { createSsh2Port } from './ssh.js';
16
+ import { createTunnel, probeLoopback } from './tunnel.js';
17
+ import { createWatchdogBus } from './watchdog-bus.js';
18
+ const HOST_KEY_CONFIRM_TIMEOUT_MS = 120_000;
19
+ /** Build the one context object: every leaf written out explicitly (no spread), so a missing or misspelled field is a
20
+ * compile error instead of an `undefined` a connection trips over. Nothing here reads the object being built —
21
+ * publishing and loading go through `hooks`, so the literal is complete before the first callback fires, which is why
22
+ * `satisfies Ctx` proves the shape without an `as` assertion. */
23
+ export function createCtx(options, hooks) {
24
+ const logger = options.logger ?? console;
25
+ const logLevel = typeof options.logLevel === 'string' ? options.logLevel : null;
26
+ const timers = {
27
+ hostKeyConfirmMs: options.hostKeyConfirmTimeoutMs ?? HOST_KEY_CONFIRM_TIMEOUT_MS,
28
+ conflictConfirmMs: options.conflictConfirmTimeoutMs ?? REMOTE_CONFLICT_TIMEOUT_MS,
29
+ remoteConfirmDelayMs: options.remoteConfirmDelayMs ?? REMOTE_UNREACHABLE_CONFIRM_DELAY_MS,
30
+ remoteRecheckMs: options.remoteRecheckMs ?? REMOTE_UNREACHABLE_RECHECK_DELAY_MS,
31
+ reattachAttempts: options.reattachAttempts ?? REMOTE_REATTACH_ATTEMPTS,
32
+ reattachIntervalMs: options.reattachIntervalMs ?? REMOTE_REATTACH_INTERVAL_MS,
33
+ tunnelRepairSettleMs: options.tunnelRepairSettleMs ?? REMOTE_TUNNEL_REPAIR_SETTLE_MS,
34
+ };
35
+ const deps = {
36
+ sshFactory: options.sshFactory ?? ((sshOptions) => createSsh2Port(sshOptions)),
37
+ tunnelFactory: options.tunnelFactory ?? createTunnel,
38
+ tunnelProbe: options.tunnelProbe ?? probeLoopback,
39
+ probe: options.probe ?? probeRemote,
40
+ plan: options.plan ?? planNpx,
41
+ ensureNode: options.ensureNode ?? ensureRemoteNode,
42
+ preflight: options.preflight ?? verifyNpxVersion,
43
+ startWeb: options.startWeb ?? startRemoteWeb,
44
+ stopWeb: options.stopWeb ?? stopRemoteWeb,
45
+ waitUi: options.waitUi ?? waitForRemoteUi,
46
+ exchange: options.exchange ?? exchangeTokenOverTunnel,
47
+ adopt: options.adopt ?? adoptRemoteWeb,
48
+ resolveRemote: options.resolveRemote ?? resolveRemoteWeb,
49
+ writeRegistry: options.writeRegistry ?? writeRunRegistry,
50
+ clearRegistry: options.clearRegistry ?? clearRunRegistry,
51
+ remoteStatus: options.remoteStatus ?? remoteHttpStatus,
52
+ processIdentity: options.processIdentity ?? remoteProcessIdentity,
53
+ findForeign: options.findForeign ?? findForeignDshProcesses,
54
+ stopForeign: options.stopForeign ?? stopForeignDshProcesses,
55
+ readRegistry: options.readRegistry ?? readRunRegistry,
56
+ loadSshMaterial: options.loadSshMaterial ?? loadLocalSshMaterial,
57
+ };
58
+ const progress = createConnectProgress({
59
+ logger,
60
+ logLevel,
61
+ getSettings: () => options.store.getSettings(),
62
+ emitState: () => hooks.publish(),
63
+ emitLogs: (runtime) => hooks.publishLogs(runtime.id),
64
+ });
65
+ // One bus per service instance: a test (or a plugin reload) that builds a second service must not
66
+ // inherit the first one's subscriber.
67
+ const bus = createWatchdogBus({ warn: logger.warn });
68
+ const state = {
69
+ runtimes: new Map(),
70
+ activeHostId: null,
71
+ initialized: false,
72
+ disposed: false,
73
+ };
74
+ const ctx = {
75
+ state,
76
+ home: options.home,
77
+ timers,
78
+ // Live readers, never cached: a setting or a detected version can change mid-connect.
79
+ settings: () => options.store.getSettings(),
80
+ localVersion: () => hooks.localVersion(),
81
+ engineNodeRange: () => hooks.engineNodeRange(),
82
+ userHome: () => process.env.USERPROFILE || process.env.HOME || options.home,
83
+ deps,
84
+ store: options.store,
85
+ secrets: options.secrets ?? null,
86
+ init: () => hooks.load(),
87
+ logger,
88
+ progress,
89
+ emitState: () => hooks.publish(),
90
+ bus,
91
+ onRemoteUnreachable: (runtime, info) => {
92
+ hooks.onEpisode(runtime, info);
93
+ },
94
+ };
95
+ return ctx;
96
+ }
@@ -0,0 +1,133 @@
1
+ /** The diagnostic checklist: read-only, opens no new connections, and redacts the exported report. */
2
+ import { isNodeVersionSupported, versionParity } from './version.js';
3
+ import { nowIso } from './util.js';
4
+ import { redactObject } from './redact.js';
5
+ /** Check labels, so each `push` below is only about status and detail. */
6
+ const TITLES = {
7
+ 'ssh-reachable': { zh: 'SSH 可达性', en: 'SSH reachability' },
8
+ auth: { zh: '认证方式', en: 'Authentication' },
9
+ 'host-key': { zh: '主机指纹', en: 'Host key' },
10
+ tunnel: { zh: '本地回环隧道', en: 'Loopback tunnel' },
11
+ 'remote-service': { zh: '远端 DSH 服务', en: 'Remote DSH service' },
12
+ 'remote-ui': { zh: '远端界面可达性', en: 'Remote UI reachability' },
13
+ 'remote-node': { zh: '远端 Node 运行时', en: 'Remote Node runtime' },
14
+ 'remote-version': { zh: '远端 DSH 版本', en: 'Remote DSH version' },
15
+ 'model-credentials': { zh: '模型凭据', en: 'Model credentials' },
16
+ 'desktop-guard': { zh: '远端桌面功能检查', en: 'Remote desktop guard' },
17
+ };
18
+ const NOT_PROBED = { zh: '未探测远端环境。', en: 'Remote environment has not been probed.' };
19
+ const t = (zh, en) => ({ zh, en });
20
+ export async function diagnoseHost(runtime, ctx) {
21
+ const checks = [];
22
+ const push = (id, status, detail) => {
23
+ checks.push({ id, title: TITLES[id], status, detail });
24
+ };
25
+ const entry = runtime.entry;
26
+ const facts = runtime.facts;
27
+ const sshLive = Boolean(runtime.ssh?.connected);
28
+ let sshStatus = 'unknown';
29
+ if (sshLive)
30
+ sshStatus = 'pass';
31
+ else if (runtime.error)
32
+ sshStatus = 'fail';
33
+ push('ssh-reachable', sshStatus, sshLive
34
+ ? t(`已连接 ${entry.address}`, `Connected to ${entry.address}`)
35
+ : (runtime.error?.detail ?? t('尚未连接,请先连接一次。', 'Not connected yet; connect once first.')));
36
+ const authType = entry.auth?.type ?? 'agent';
37
+ push('auth', sshLive ? 'pass' : 'unknown', sshLive
38
+ ? t(`认证方式:${authType}(凭据不会保存在本机)`, `Method: ${authType} (no credentials are stored locally)`)
39
+ : t('连接后检查', 'Checked after connecting'));
40
+ // The pinned fingerprint is compared with the one this session proved, never with the address.
41
+ const pinned = entry.pinnedFingerprint;
42
+ const liveFingerprint = runtime.fingerprint?.sha256 ?? null;
43
+ let keyStatus = 'unknown';
44
+ if (pinned && liveFingerprint)
45
+ keyStatus = pinned === liveFingerprint ? 'pass' : 'fail';
46
+ let keyDetail = t('尚未记录指纹,首次连接时会询问。', 'No host key recorded yet; it is asked on first connect.');
47
+ if (pinned) {
48
+ const session = liveFingerprint ? `,本次 ${liveFingerprint}` : '';
49
+ keyDetail = t(`已记录 ${pinned}${session}`, `Pinned ${pinned}${liveFingerprint ? `, this session ${liveFingerprint}` : ''}`);
50
+ }
51
+ else if (liveFingerprint) {
52
+ keyDetail = t(`本次会话 ${liveFingerprint}(尚未记录)`, `This session ${liveFingerprint} (not pinned yet)`);
53
+ }
54
+ push('host-key', keyStatus, keyDetail);
55
+ const tunnel = runtime.tunnel;
56
+ push('tunnel', tunnel ? 'pass' : 'fail', tunnel
57
+ ? t(`127.0.0.1:${tunnel.localPort} → 远端 127.0.0.1:${runtime.remote.port ?? '未知'}`, `127.0.0.1:${tunnel.localPort} → remote 127.0.0.1:${runtime.remote.port ?? 'unknown'}`)
58
+ : t('隧道未建立(连接断开或尚未连接)。', 'The tunnel is not established (disconnected or not connected yet).'));
59
+ // The token exchange is what proves the managed remote is the instance this connection started.
60
+ const remoteAlive = sshLive && runtime.exchange?.status === 200;
61
+ let serviceStatus = 'unknown';
62
+ if (remoteAlive)
63
+ serviceStatus = 'pass';
64
+ else if (sshLive)
65
+ serviceStatus = 'fail';
66
+ push('remote-service', serviceStatus, remoteAlive
67
+ ? t(`远端进程 pid=${runtime.remote.pid ?? '未知'},本地端口 ${runtime.remote.localPort ?? '未知'}`, `Remote pid ${runtime.remote.pid ?? 'unknown'}, local port ${runtime.remote.localPort ?? 'unknown'}`)
68
+ : t('远端服务未确认在运行。', 'The remote service is not confirmed running.'));
69
+ let uiStatus = 'unknown';
70
+ if (runtime.exchange?.ok)
71
+ uiStatus = 'pass';
72
+ else if (sshLive)
73
+ uiStatus = 'fail';
74
+ push('remote-ui', uiStatus, runtime.exchange?.ok
75
+ ? t(`页面标题:${runtime.exchange.title ?? '(无)'}`, `Page title: ${runtime.exchange.title ?? '(none)'}`)
76
+ : t('尚未完成远端界面的鉴权握手。', 'The remote UI authentication handshake has not completed.'));
77
+ const nodeVersion = facts?.nodeVersion ?? null;
78
+ const nodeOk = isNodeVersionSupported(nodeVersion) && Boolean(facts?.npxPath);
79
+ let nodeStatus = 'unknown';
80
+ let nodeDetail = NOT_PROBED;
81
+ if (facts) {
82
+ nodeStatus = nodeOk ? 'pass' : 'fail';
83
+ nodeDetail = nodeOk
84
+ ? t(`Node ${nodeVersion}(插件托管),npx 可用`, `Node ${nodeVersion} (plugin-managed) with npx available`)
85
+ : t(`Node ${nodeVersion ?? '未检测到'}${facts.npxPath ? '' : ',缺少 npx'},不满足 ≥ 24.9。`, `Node ${nodeVersion ?? 'not detected'}${facts.npxPath ? '' : ' (npx missing)'} does not meet >= 24.9.`);
86
+ }
87
+ push('remote-node', nodeStatus, nodeDetail);
88
+ const parity = versionParity(ctx.targetVersion, runtime.remote.version ?? null);
89
+ let versionStatus = 'unknown';
90
+ if (parity.status === 'same')
91
+ versionStatus = 'pass';
92
+ else if (parity.status === 'different')
93
+ versionStatus = 'fail';
94
+ push('remote-version', versionStatus, { zh: parity.message.zh, en: parity.message.en });
95
+ const credentials = facts
96
+ ? Boolean(facts.credentialsFile || facts.deepseekKeyEnv || facts.providerEnvKeys.length > 0)
97
+ : false;
98
+ let credentialStatus = 'unknown';
99
+ let credentialDetail = NOT_PROBED;
100
+ if (facts) {
101
+ credentialStatus = credentials ? 'pass' : 'unknown';
102
+ credentialDetail = credentials
103
+ ? t('远端已检测到模型凭据配置。', 'Remote model credentials were detected.')
104
+ : t('未检测到模型凭据;请在远端界面里配置。', 'No model credentials detected; configure them in the remote UI.');
105
+ }
106
+ push('model-credentials', credentialStatus, credentialDetail);
107
+ let desktopStatus = 'unknown';
108
+ let desktopDetail = NOT_PROBED;
109
+ if (facts) {
110
+ desktopStatus = facts.sshConnection ? 'pass' : 'unknown';
111
+ desktopDetail = facts.sshConnection
112
+ ? t('远端 DSH 经 SSH 会话启动,宿主桌面功能已关闭。', 'The remote DSH runs inside an SSH session, so host desktop features stay off.')
113
+ : t('远端未检测到 SSH 会话标记,目录对话框可能弹在远端屏幕上。', 'No SSH session marker on the remote; directory dialogs may appear on the remote screen.');
114
+ }
115
+ push('desktop-guard', desktopStatus, desktopDetail);
116
+ const failed = checks.filter((check) => check.status === 'fail').length;
117
+ const unknown = checks.filter((check) => check.status === 'unknown').length;
118
+ let summary = 'ok';
119
+ if (failed > 0)
120
+ summary = 'error';
121
+ else if (unknown > 0)
122
+ summary = 'warning';
123
+ // Redaction is the contract of the exported report: tokens, passwords, private keys and home
124
+ // directories never leave the machine.
125
+ return redactObject({
126
+ summary,
127
+ checks,
128
+ redacted: true,
129
+ generatedAt: nowIso(),
130
+ restarts: (Array.isArray(runtime.restarts) ? runtime.restarts : []).slice(-10),
131
+ logs: runtime.logs.slice(-40).map((entry) => entry.line),
132
+ });
133
+ }