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,142 @@
1
+ /**
2
+ * Connect progress: the staged progress line (published on the state channel) and the log rows
3
+ * (published on the log channel); it never sets a status.
4
+ */
5
+ import { appendConnectLog, connectFailureLines, connectLogVisible } from './connect-log.js';
6
+ import { logVisible, nowIso } from './util.js';
7
+ /** Throttle for the npx reporter: one progress frame per 700 ms at most. */
8
+ const REPORT_MIN_INTERVAL_MS = 700;
9
+ function stripAnsi(text) {
10
+ return String(text ?? '').replace(/\u001B\[[0-9;]*m/g, '');
11
+ }
12
+ /**
13
+ * Turn one npm/npx output line into a progress event for the connect line.
14
+ * `npm_config_loglevel=http` makes npm report fetches without a TTY; known shapes
15
+ * get a localized progress code, anything else is kept (truncated) as a detail.
16
+ */
17
+ export function describePreflightEvent(line, version) {
18
+ const text = stripAnsi(line).trim();
19
+ if (text === '')
20
+ return null;
21
+ // The package's own `--version` output is the success signal, not progress.
22
+ if (/^v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(text))
23
+ return null;
24
+ if (/The following package was not found and will be installed/i.test(text)) {
25
+ return { code: 'bootstrap-first-run', params: { version } };
26
+ }
27
+ if (/^npm (http fetch|http request)/i.test(text))
28
+ return { code: 'bootstrap-fetching' };
29
+ if (/added \d+ packages? in/i.test(text))
30
+ return { code: 'bootstrap-installed' };
31
+ return { code: 'bootstrap-progress', params: { detail: text.slice(0, 160) } };
32
+ }
33
+ export function createConnectProgress(options) {
34
+ /** Append one line and echo it to the Host logger at the same level. */
35
+ function write(runtime, input) {
36
+ const entry = appendConnectLog(runtime, { at: nowIso(), ...input });
37
+ // Verbosity is a runtime decision: `options.logLevel` (tests, diagnostics) or settings.
38
+ const threshold = options.logLevel ?? options.getSettings()?.logLevel ?? 'info';
39
+ if (!logVisible(entry.level, threshold))
40
+ return entry;
41
+ const method = options.logger[entry.level] ?? options.logger.info;
42
+ method?.(entry.line);
43
+ return entry;
44
+ }
45
+ function log(runtime, level, ...args) {
46
+ const message = args.map((value) => (typeof value === 'string' ? value : JSON.stringify(value))).join(' ');
47
+ const entry = write(runtime, { level, message, phase: runtime.phase });
48
+ publish(runtime);
49
+ return entry;
50
+ }
51
+ /**
52
+ * Print a failed connection as the lines that explain it (phase, code, localized reason,
53
+ * hints, redacted details), instead of one line of code plus a raw message. `context.label`
54
+ * replaces the leading line for a one-shot action that is not a connect (the remote stop).
55
+ */
56
+ function logFailure(runtime, view, context = {}) {
57
+ const phase = typeof context.phase === 'string' && context.phase !== '' ? context.phase : null;
58
+ for (const line of connectFailureLines(view, { phase, label: context.label })) {
59
+ write(runtime, { level: line.level, message: line.message, text: line.text, phase: line.phase });
60
+ }
61
+ publish(runtime);
62
+ }
63
+ /**
64
+ * Hand the appended rows to the log channel. The state channel is not touched: a log line is
65
+ * not a state change (docs/api.md v2.12). Coalescing (150 ms) belongs to the event hub, so this
66
+ * is one cheap notification per row and the hub decides how many frames leave the process.
67
+ */
68
+ function publish(runtime) {
69
+ if (!connectLogVisible(runtime.status))
70
+ return;
71
+ options.emitLogs?.(runtime);
72
+ }
73
+ /**
74
+ * The staged progress line (pure UI): it never changes the host status, which is why it is not a
75
+ * transition. The connect pipeline is its only caller.
76
+ */
77
+ function phase(runtime, phaseName, code, params) {
78
+ runtime.phase = phaseName;
79
+ runtime.progress = { code, ...(params ? { params } : {}) };
80
+ options.emitState();
81
+ }
82
+ /**
83
+ * Managed-Node provisioning reports coarse steps; surface them in the same
84
+ * progress line the rest of the pipeline uses (the installer already bundles
85
+ * byte progress into ~5s/8 MB events).
86
+ */
87
+ function nodeProgress(runtime, event) {
88
+ if (event.step === 'check')
89
+ return;
90
+ if (event.step === 'download') {
91
+ const mb = Math.max(0, Math.round(Number(event.bytes ?? 0) / (1024 * 1024)));
92
+ log(runtime, 'info', `downloading managed Node v${event.version} (${mb} MB so far)`);
93
+ phase(runtime, 'bootstrap', 'downloading-node', { version: event.version, mb });
94
+ return;
95
+ }
96
+ if (event.step === 'ready') {
97
+ log(runtime, 'info', `managed Node v${event.version} is ready`);
98
+ return;
99
+ }
100
+ log(runtime, 'info', `installing managed Node v${event.version}`);
101
+ phase(runtime, 'bootstrap', 'installing-node', { version: event.version });
102
+ }
103
+ /**
104
+ * Stream one channel of the npx preflight into the connect progress line. npm
105
+ * has no TTY over SSH, so the command enables `npm_config_loglevel=http`; each
106
+ * line becomes a short detail, throttled so the SSE stream is not flooded.
107
+ */
108
+ function bootstrapReporter(runtime, version) {
109
+ let buffer = '';
110
+ let lastAt = 0;
111
+ let lastKey = '';
112
+ return (chunk) => {
113
+ buffer += String(chunk ?? '');
114
+ const lines = buffer.split(/\r?\n/);
115
+ buffer = lines.pop() ?? '';
116
+ for (const rawLine of lines) {
117
+ const text = stripAnsi(rawLine).trim();
118
+ // npx is the slowest step on a cold cache: print what it says at debug level.
119
+ if (text !== '')
120
+ log(runtime, 'debug', `npx: ${text}`);
121
+ const event = describePreflightEvent(rawLine, version);
122
+ if (!event)
123
+ continue;
124
+ const key = `${event.code}:${event.params?.detail ?? ''}`;
125
+ if (key === lastKey)
126
+ continue;
127
+ const now = Date.now();
128
+ if (now - lastAt < REPORT_MIN_INTERVAL_MS)
129
+ continue;
130
+ lastAt = now;
131
+ lastKey = key;
132
+ phase(runtime, 'bootstrap', event.code, event.params);
133
+ }
134
+ };
135
+ }
136
+ /**
137
+ * Nothing to release: the 150 ms window moved into the event hub with the channel itself. The
138
+ * call stays because `service.shutdown()` has always made it (docs/api.md v2.12).
139
+ */
140
+ function dispose() { }
141
+ return { log, logFailure, phase, nodeProgress, bootstrapReporter, dispose };
142
+ }
@@ -1,93 +1,67 @@
1
1
  /**
2
2
  * Shared constants for the remote npx runtime and the plugin surface.
3
3
  */
4
-
5
- export const DEFAULT_REMOTE_PROFILE = 'web'
6
-
7
- export const REMOTE_DSH_DIR = '.dsh'
8
-
9
- export const REMOTE_STATE_DIR = 'remote-go'
10
-
11
- export const API_PREFIX = '/dsh-remote-go/api'
12
-
4
+ export const DEFAULT_REMOTE_PROFILE = 'web';
5
+ export const REMOTE_DSH_DIR = '.dsh';
6
+ export const REMOTE_STATE_DIR = 'remote-go';
7
+ export const API_PREFIX = '/dsh-remote-go/api';
13
8
  /**
14
9
  * Same-origin seat of the remote web UI used by the browser half: every request below
15
- * `<prefix><hostId>/` is proxied to that connected host's loopback tunnel (see remote-proxy.js).
10
+ * `<prefix><hostId>/` is proxied to that connected host's loopback tunnel (see proxy/index.ts).
16
11
  */
17
- export const REMOTE_VIEW_PREFIX = '/dsh-remote-go/remote/'
18
-
19
- export const API_HEADER = 'x-dsh-remote-go'
20
-
21
- export const PLUGIN_ID = 'dsh-remote-go'
22
- export const PLUGIN_VERSION = '0.2.0'
23
-
12
+ export const REMOTE_VIEW_PREFIX = '/dsh-remote-go/remote/';
13
+ export const API_HEADER = 'x-dsh-remote-go';
14
+ export const PLUGIN_ID = 'dsh-remote-go';
15
+ export const PLUGIN_VERSION = '0.3.0';
24
16
  /**
25
17
  * DSH's own lower bound, mirrored from this package's `engines.dsh`. The client may only
26
18
  * backfill a locally-detected DSH version; a value below this floor names a build the plugin
27
19
  * does not support, so `/local-version` refuses it (it would otherwise pin the remote npx
28
20
  * runtime to an arbitrary, possibly unusable version).
29
21
  */
30
- export const MIN_DSH_VERSION = '0.2.2-rc.3'
31
-
32
- /** Host↔Client contract version served by `GET /version` (docs/api.md v2.11). */
33
- export const API_VERSION = '2.11'
34
-
35
- export const DEFAULT_KEY_PATH = '~/.ssh/id_rsa'
36
-
37
- export const REMOTE_START_TIMEOUT_MS = 300_000
38
-
39
- export const REMOTE_CONFLICT_TIMEOUT_MS = 120_000
40
-
41
- export const SSH_READY_TIMEOUT_MS = 20_000
42
-
43
- export const DEFAULT_IDLE_MINUTES = 15
44
-
45
- export const TUNNEL_PROBE_TIMEOUT_MS = 10_000
46
-
22
+ export const MIN_DSH_VERSION = '0.2.2-rc.3';
23
+ /** Host↔Client contract version served by `GET /version` (docs/api.md v2.12). */
24
+ export const API_VERSION = '2.12';
25
+ export const DEFAULT_KEY_PATH = '~/.ssh/id_rsa';
26
+ export const REMOTE_START_TIMEOUT_MS = 300_000;
27
+ export const REMOTE_CONFLICT_TIMEOUT_MS = 120_000;
28
+ export const SSH_READY_TIMEOUT_MS = 20_000;
29
+ export const DEFAULT_IDLE_MINUTES = 15;
30
+ export const TUNNEL_PROBE_TIMEOUT_MS = 10_000;
47
31
  /**
48
32
  * Remote liveness: a connected host's remote UI is probed on this interval
49
33
  * (`settings.remoteHeartbeat`). Two consecutive failed probes - not one failed
50
34
  * request - are what confirm that the remote web really went away.
51
35
  */
52
- export const REMOTE_HEARTBEAT_DEFAULT_SEC = 30
53
-
54
- export const REMOTE_HEARTBEAT_MIN_SEC = 5
55
-
56
- export const REMOTE_HEARTBEAT_MAX_SEC = 600
57
-
36
+ export const REMOTE_HEARTBEAT_DEFAULT_SEC = 30;
37
+ export const REMOTE_HEARTBEAT_MIN_SEC = 5;
38
+ export const REMOTE_HEARTBEAT_MAX_SEC = 600;
58
39
  /** Consecutive failed probes that turn a suspicion into a confirmed restart. */
59
- export const REMOTE_UNREACHABLE_FAILURES = 2
60
-
40
+ export const REMOTE_UNREACHABLE_FAILURES = 2;
61
41
  /** Delay before the confirming probe after a proxy/tunnel error (never trust one failure). */
62
- export const REMOTE_UNREACHABLE_CONFIRM_DELAY_MS = 750
63
-
42
+ export const REMOTE_UNREACHABLE_CONFIRM_DELAY_MS = 750;
64
43
  /** Delay between the two confirming probes, so they are consecutive but not one slow request. */
65
- export const REMOTE_UNREACHABLE_RECHECK_DELAY_MS = 1200
66
-
44
+ export const REMOTE_UNREACHABLE_RECHECK_DELAY_MS = 1200;
67
45
  /**
68
46
  * After a transient (proxy/tunnel) episode is confirmed healthy, the same kind of report is
69
47
  * ignored for this long: a flapping tunnel must not emit suspected/recovered on every request.
70
48
  */
71
- export const REMOTE_EPISODE_COOLDOWN_MS = 15_000
72
-
49
+ export const REMOTE_EPISODE_COOLDOWN_MS = 15_000;
73
50
  /**
74
51
  * A failed listener rebuild waits before the next attempt (doubling up to the max). The
75
52
  * episode cooldown alone would still let a broken rebuild retry every 15s forever.
76
53
  */
77
- export const REMOTE_REPAIR_BACKOFF_MS = 30_000
78
- export const REMOTE_REPAIR_BACKOFF_MAX_MS = 120_000
79
-
54
+ export const REMOTE_REPAIR_BACKOFF_MS = 30_000;
55
+ export const REMOTE_REPAIR_BACKOFF_MAX_MS = 120_000;
80
56
  /**
81
57
  * How long teardown waits for an in-flight listener rebuild. The rebuild is local and fast;
82
58
  * a stuck one must not delay disconnect / host removal / shutdown indefinitely. Its token is
83
59
  * already cancelled, so it still closes any listener it manages to publish afterwards.
84
60
  */
85
- export const REMOTE_TUNNEL_REPAIR_SETTLE_MS = 5_000
86
-
61
+ export const REMOTE_TUNNEL_REPAIR_SETTLE_MS = 5_000;
87
62
  /**
88
63
  * A remote restart needs a little time to print its new readiness line. The
89
64
  * re-attach retries the read-back a few times before it declares the remote gone.
90
65
  */
91
- export const REMOTE_REATTACH_ATTEMPTS = 6
92
-
93
- export const REMOTE_REATTACH_INTERVAL_MS = 2_000
66
+ export const REMOTE_REATTACH_ATTEMPTS = 6;
67
+ export const REMOTE_REATTACH_INTERVAL_MS = 2_000;
@@ -0,0 +1,117 @@
1
+ /**
2
+ * The assembled service context: the one file that knows every injected leaf.
3
+ *
4
+ * P2/1 replaced the 47-key god-`ctx` with six narrow slices, so a module can only reach the
5
+ * capability it declares; the assembly that used to sit in `RemoteGoService`'s constructor moved
6
+ * here. The assembled object keeps the shape it has always had — the same keys under the same
7
+ * paths — because 36 test call sites use `service.ctx` as a public API (design-arch §1.6) and
8
+ * every consumer keeps its `ctx.state.*` / `ctx.deps.*` / `ctx.timers.*` spelling. Narrowing
9
+ * happens in the *parameter* types below, never by renaming a field.
10
+ */
11
+ import { planNpx, verifyNpxVersion } from './bootstrap.js';
12
+ 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';
13
+ import { createConnectProgress } from './connect-progress.js';
14
+ import { loadLocalSshMaterial } from './local-ssh.js';
15
+ import { ensureRemoteNode } from './node-runtime.js';
16
+ import { probeRemote } from './probe.js';
17
+ import { exchangeTokenOverTunnel, findForeignDshProcesses, remoteHttpStatus, remoteProcessIdentity, stopForeignDshProcesses, waitForRemoteUi, } from './remote-proc.js';
18
+ import { clearRunRegistry, readRunRegistry, writeRunRegistry } from './remote-web/registry.js';
19
+ import { adoptRemoteWeb, resolveRemoteWeb } from './remote-web/resolve.js';
20
+ import { startRemoteWeb } from './remote-web/start.js';
21
+ import { stopRemoteWeb } from './remote-web/stop.js';
22
+ import { createSsh2Port } from './ssh.js';
23
+ import { createTunnel, probeLoopback } from './tunnel.js';
24
+ import { createWatchdogBus } from './watchdog-bus.js';
25
+ /** Milliseconds a paused host-key handshake waits for the user. */
26
+ const HOST_KEY_CONFIRM_TIMEOUT_MS = 120_000;
27
+ /**
28
+ * Build the one context object. Every leaf is written out explicitly (no spread): a missing or
29
+ * misspelled field is then a compile error instead of an `undefined` that only surfaces when a
30
+ * connection happens to read it.
31
+ *
32
+ * Nothing here reads the object being built — publishing and loading go through `hooks`, so the
33
+ * literal is complete before the first callback can fire. That is also why no `as Ctx` assertion
34
+ * is needed: `satisfies Ctx` proves the shape and keeps the result fully typed.
35
+ * @param options - the constructor input, defaults applied per leaf.
36
+ * @param hooks - the five leaves only the facade can supply (see `ServiceHooks`).
37
+ * @returns the assembled context.
38
+ */
39
+ export function createCtx(options, hooks) {
40
+ const logger = options.logger ?? console;
41
+ const logLevel = typeof options.logLevel === 'string' ? options.logLevel : null;
42
+ const timers = {
43
+ hostKeyConfirmMs: options.hostKeyConfirmTimeoutMs ?? HOST_KEY_CONFIRM_TIMEOUT_MS,
44
+ conflictConfirmMs: options.conflictConfirmTimeoutMs ?? REMOTE_CONFLICT_TIMEOUT_MS,
45
+ // Liveness confirmation and the re-attach retry loop; tests shorten these.
46
+ remoteConfirmDelayMs: options.remoteConfirmDelayMs ?? REMOTE_UNREACHABLE_CONFIRM_DELAY_MS,
47
+ remoteRecheckMs: options.remoteRecheckMs ?? REMOTE_UNREACHABLE_RECHECK_DELAY_MS,
48
+ reattachAttempts: options.reattachAttempts ?? REMOTE_REATTACH_ATTEMPTS,
49
+ reattachIntervalMs: options.reattachIntervalMs ?? REMOTE_REATTACH_INTERVAL_MS,
50
+ tunnelRepairSettleMs: options.tunnelRepairSettleMs ?? REMOTE_TUNNEL_REPAIR_SETTLE_MS,
51
+ };
52
+ const deps = {
53
+ sshFactory: options.sshFactory ?? ((sshOptions) => createSsh2Port(sshOptions)),
54
+ tunnelFactory: options.tunnelFactory ?? createTunnel,
55
+ /** Local listener health: decides whether a transient proxy failure needs a rebuild. */
56
+ tunnelProbe: options.tunnelProbe ?? probeLoopback,
57
+ probe: options.probe ?? probeRemote,
58
+ plan: options.plan ?? planNpx,
59
+ ensureNode: options.ensureNode ?? ensureRemoteNode,
60
+ preflight: options.preflight ?? verifyNpxVersion,
61
+ startWeb: options.startWeb ?? startRemoteWeb,
62
+ stopWeb: options.stopWeb ?? stopRemoteWeb,
63
+ waitUi: options.waitUi ?? waitForRemoteUi,
64
+ exchange: options.exchange ?? exchangeTokenOverTunnel,
65
+ adopt: options.adopt ?? adoptRemoteWeb,
66
+ resolveRemote: options.resolveRemote ?? resolveRemoteWeb,
67
+ writeRegistry: options.writeRegistry ?? writeRunRegistry,
68
+ clearRegistry: options.clearRegistry ?? clearRunRegistry,
69
+ remoteStatus: options.remoteStatus ?? remoteHttpStatus,
70
+ processIdentity: options.processIdentity ?? remoteProcessIdentity,
71
+ findForeign: options.findForeign ?? findForeignDshProcesses,
72
+ stopForeign: options.stopForeign ?? stopForeignDshProcesses,
73
+ readRegistry: options.readRegistry ?? readRunRegistry,
74
+ loadSshMaterial: options.loadSshMaterial ?? loadLocalSshMaterial,
75
+ };
76
+ const progress = createConnectProgress({
77
+ logger,
78
+ logLevel,
79
+ getSettings: () => options.store.getSettings(),
80
+ emitState: () => hooks.publish(),
81
+ // Log rows and progress lines have different channels (docs/api.md v2.12): a row is not a
82
+ // state change, so it must not bump the revision the Client gates everything else on.
83
+ emitLogs: (runtime) => hooks.publishLogs(runtime.id),
84
+ });
85
+ // One bus per service instance: a test (or a plugin reload) that builds a second service must
86
+ // not inherit the first one's subscriber.
87
+ const bus = createWatchdogBus({ warn: logger.warn });
88
+ const state = {
89
+ runtimes: new Map(),
90
+ activeHostId: null,
91
+ initialized: false,
92
+ disposed: false,
93
+ };
94
+ const ctx = {
95
+ state,
96
+ home: options.home,
97
+ timers,
98
+ // Live readers, never cached: a setting or a detected version can change while a connect is
99
+ // already in flight.
100
+ settings: () => options.store.getSettings(),
101
+ localVersion: () => hooks.localVersion(),
102
+ engineNodeRange: () => hooks.engineNodeRange(),
103
+ userHome: () => process.env.USERPROFILE || process.env.HOME || options.home,
104
+ deps,
105
+ store: options.store,
106
+ secrets: options.secrets ?? null,
107
+ init: () => hooks.load(),
108
+ logger,
109
+ progress,
110
+ emitState: () => hooks.publish(),
111
+ bus,
112
+ onRemoteUnreachable: (runtime, info) => {
113
+ hooks.onEpisode(runtime, info);
114
+ },
115
+ };
116
+ return ctx;
117
+ }
@@ -0,0 +1,102 @@
1
+ /**
2
+ * The diagnostic checklist: read-only, opens no new connections.
3
+ */
4
+ import { isNodeVersionSupported, versionParity } from './version.js';
5
+ import { nowIso } from './util.js';
6
+ import { redactObject } from './redact.js';
7
+ /** Check labels, so each `push` below is only about status and detail. */
8
+ const TITLES = {
9
+ 'ssh-reachable': { zh: 'SSH 可达性', en: 'SSH reachability' },
10
+ auth: { zh: '认证方式', en: 'Authentication' },
11
+ 'host-key': { zh: '主机指纹', en: 'Host key' },
12
+ tunnel: { zh: '本地回环隧道', en: 'Loopback tunnel' },
13
+ 'remote-service': { zh: '远端 DSH 服务', en: 'Remote DSH service' },
14
+ 'remote-ui': { zh: '远端界面可达性', en: 'Remote UI reachability' },
15
+ 'remote-node': { zh: '远端 Node 运行时', en: 'Remote Node runtime' },
16
+ 'remote-version': { zh: '远端 DSH 版本', en: 'Remote DSH version' },
17
+ 'model-credentials': { zh: '模型凭据', en: 'Model credentials' },
18
+ 'desktop-guard': { zh: '远端桌面功能检查', en: 'Remote desktop guard' },
19
+ };
20
+ const NOT_PROBED = { zh: '未探测远端环境。', en: 'Remote environment has not been probed.' };
21
+ const t = (zh, en) => ({ zh, en });
22
+ export async function diagnoseHost(runtime, ctx) {
23
+ const checks = [];
24
+ const push = (id, status, detail) => {
25
+ checks.push({ id, title: TITLES[id], status, detail });
26
+ };
27
+ const entry = runtime.entry;
28
+ const facts = runtime.facts;
29
+ const sshLive = Boolean(runtime.ssh?.connected);
30
+ push('ssh-reachable', sshLive ? 'pass' : runtime.error ? 'fail' : 'unknown', sshLive
31
+ ? t(`已连接 ${entry.address}`, `Connected to ${entry.address}`)
32
+ : (runtime.error?.detail ?? t('尚未连接,请先连接一次。', 'Not connected yet; connect once first.')));
33
+ const authType = entry.auth?.type ?? 'agent';
34
+ push('auth', sshLive ? 'pass' : 'unknown', sshLive
35
+ ? t(`认证方式:${authType}(凭据不会保存在本机)`, `Method: ${authType} (no credentials are stored locally)`)
36
+ : t('连接后检查', 'Checked after connecting'));
37
+ const pinned = entry.pinnedFingerprint;
38
+ const liveFingerprint = runtime.fingerprint?.sha256 ?? null;
39
+ const keyStatus = pinned && liveFingerprint ? (pinned === liveFingerprint ? 'pass' : 'fail') : 'unknown';
40
+ let keyDetail = t('尚未记录指纹,首次连接时会询问。', 'No host key recorded yet; it is asked on first connect.');
41
+ if (pinned) {
42
+ const session = liveFingerprint ? `,本次 ${liveFingerprint}` : '';
43
+ keyDetail = t(`已记录 ${pinned}${session}`, `Pinned ${pinned}${liveFingerprint ? `, this session ${liveFingerprint}` : ''}`);
44
+ }
45
+ else if (liveFingerprint) {
46
+ keyDetail = t(`本次会话 ${liveFingerprint}(尚未记录)`, `This session ${liveFingerprint} (not pinned yet)`);
47
+ }
48
+ push('host-key', keyStatus, keyDetail);
49
+ const tunnel = runtime.tunnel;
50
+ push('tunnel', tunnel ? 'pass' : 'fail', tunnel
51
+ ? 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'}`)
52
+ : t('隧道未建立(连接断开或尚未连接)。', 'The tunnel is not established (disconnected or not connected yet).'));
53
+ const remoteAlive = sshLive && runtime.exchange?.status === 200;
54
+ push('remote-service', remoteAlive ? 'pass' : sshLive ? 'fail' : 'unknown', remoteAlive
55
+ ? t(`远端进程 pid=${runtime.remote.pid ?? '未知'},本地端口 ${runtime.remote.localPort ?? '未知'}`, `Remote pid ${runtime.remote.pid ?? 'unknown'}, local port ${runtime.remote.localPort ?? 'unknown'}`)
56
+ : t('远端服务未确认在运行。', 'The remote service is not confirmed running.'));
57
+ push('remote-ui', runtime.exchange?.ok ? 'pass' : sshLive ? 'fail' : 'unknown', runtime.exchange?.ok
58
+ ? t(`页面标题:${runtime.exchange.title ?? '(无)'}`, `Page title: ${runtime.exchange.title ?? '(none)'}`)
59
+ : t('尚未完成远端界面的鉴权握手。', 'The remote UI authentication handshake has not completed.'));
60
+ const nodeVersion = facts?.nodeVersion ?? null;
61
+ const nodeOk = isNodeVersionSupported(nodeVersion) && Boolean(facts?.npxPath);
62
+ let nodeDetail = NOT_PROBED;
63
+ if (facts) {
64
+ nodeDetail = nodeOk
65
+ ? t(`Node ${nodeVersion}(插件托管),npx 可用`, `Node ${nodeVersion} (plugin-managed) with npx available`)
66
+ : t(`Node ${nodeVersion ?? '未检测到'}${facts.npxPath ? '' : ',缺少 npx'},不满足 ≥ 24.9。`, `Node ${nodeVersion ?? 'not detected'}${facts.npxPath ? '' : ' (npx missing)'} does not meet >= 24.9.`);
67
+ }
68
+ push('remote-node', facts ? (nodeOk ? 'pass' : 'fail') : 'unknown', nodeDetail);
69
+ const parity = versionParity(ctx.targetVersion, runtime.remote.version ?? null);
70
+ push('remote-version', parity.status === 'same' ? 'pass' : parity.status === 'different' ? 'fail' : 'unknown', {
71
+ zh: parity.message.zh,
72
+ en: parity.message.en,
73
+ });
74
+ const credentials = facts
75
+ ? Boolean(facts.credentialsFile || facts.deepseekKeyEnv || facts.providerEnvKeys.length > 0)
76
+ : false;
77
+ push('model-credentials', facts ? (credentials ? 'pass' : 'unknown') : 'unknown', facts
78
+ ? credentials
79
+ ? t('远端已检测到模型凭据配置。', 'Remote model credentials were detected.')
80
+ : t('未检测到模型凭据;请在远端界面里配置。', 'No model credentials detected; configure them in the remote UI.')
81
+ : NOT_PROBED);
82
+ push('desktop-guard', facts ? (facts.sshConnection ? 'pass' : 'unknown') : 'unknown', facts
83
+ ? facts.sshConnection
84
+ ? t('远端 DSH 经 SSH 会话启动,宿主桌面功能已关闭。', 'The remote DSH runs inside an SSH session, so host desktop features stay off.')
85
+ : t('远端未检测到 SSH 会话标记,目录对话框可能弹在远端屏幕上。', 'No SSH session marker on the remote; directory dialogs may appear on the remote screen.')
86
+ : NOT_PROBED);
87
+ const failed = checks.filter((check) => check.status === 'fail').length;
88
+ const unknown = checks.filter((check) => check.status === 'unknown').length;
89
+ const summary = failed > 0 ? 'error' : unknown > 0 ? 'warning' : 'ok';
90
+ // Redaction is the contract of the exported report: tokens, passwords, private
91
+ // keys and home directories never leave the machine.
92
+ return redactObject({
93
+ summary,
94
+ checks,
95
+ redacted: true,
96
+ generatedAt: nowIso(),
97
+ // One entry per restart / re-attach, so an exported report can tell a local restart
98
+ // apart from a remote one without re-reading the whole connect log.
99
+ restarts: (Array.isArray(runtime.restarts) ? runtime.restarts : []).slice(-10),
100
+ logs: runtime.logs.slice(-40).map((entry) => entry.line),
101
+ });
102
+ }