dsh-remote-go 0.3.0 → 0.3.2

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 (86) hide show
  1. package/README.md +1 -0
  2. package/dist/client.js +1348 -2095
  3. package/dist/src/admission.js +3 -28
  4. package/dist/src/api.js +37 -99
  5. package/dist/src/atomic-json.js +32 -66
  6. package/dist/src/bootstrap.js +17 -27
  7. package/dist/src/connect/attach.js +3 -25
  8. package/dist/src/connect/bootstrap.js +2 -8
  9. package/dist/src/connect/failures.js +3 -18
  10. package/dist/src/connect/guards.js +13 -8
  11. package/dist/src/connect/launch.js +11 -21
  12. package/dist/src/connect/links.js +11 -27
  13. package/dist/src/connect/ownership.js +33 -114
  14. package/dist/src/connect/pipeline.js +62 -159
  15. package/dist/src/connect/reattach.js +26 -44
  16. package/dist/src/connect/registry.js +0 -1
  17. package/dist/src/connect/repair.js +8 -37
  18. package/dist/src/connect/restart.js +36 -97
  19. package/dist/src/connect/stop.js +16 -50
  20. package/dist/src/connect/transport.js +10 -18
  21. package/dist/src/connect/verify.js +3 -12
  22. package/dist/src/connect/watchdog.js +6 -38
  23. package/dist/src/connect-log.js +16 -41
  24. package/dist/src/connect-progress.js +13 -45
  25. package/dist/src/constants.js +18 -43
  26. package/dist/src/context.js +13 -32
  27. package/dist/src/diagnostics.js +56 -25
  28. package/dist/src/download-jobs.js +11 -20
  29. package/dist/src/errors.js +175 -190
  30. package/dist/src/events.js +20 -84
  31. package/dist/src/host-lifecycle.js +69 -177
  32. package/dist/src/host-registry.js +27 -78
  33. package/dist/src/host-runtime.js +0 -9
  34. package/dist/src/host-view.js +6 -29
  35. package/dist/src/index.js +15 -35
  36. package/dist/src/kernel-adapter.js +34 -80
  37. package/dist/src/key-files.js +10 -23
  38. package/dist/src/known-hosts.js +13 -34
  39. package/dist/src/layout.js +3 -20
  40. package/dist/src/local-download.js +94 -163
  41. package/dist/src/local-ssh.js +12 -19
  42. package/dist/src/local-version.js +35 -49
  43. package/dist/src/node/download.js +1 -4
  44. package/dist/src/node-runtime.js +19 -38
  45. package/dist/src/probe.js +6 -7
  46. package/dist/src/prompts.js +56 -128
  47. package/dist/src/proxy/cookies.js +26 -60
  48. package/dist/src/proxy/headers.js +30 -125
  49. package/dist/src/proxy/http.js +33 -41
  50. package/dist/src/proxy/index.js +20 -34
  51. package/dist/src/proxy/limits.js +4 -6
  52. package/dist/src/proxy/routes.js +10 -17
  53. package/dist/src/proxy/upgrade.js +27 -42
  54. package/dist/src/redact.js +14 -33
  55. package/dist/src/remote-files.js +9 -21
  56. package/dist/src/remote-path.js +21 -62
  57. package/dist/src/remote-proc.js +35 -103
  58. package/dist/src/remote-web/registry.js +10 -50
  59. package/dist/src/remote-web/resolve.js +23 -104
  60. package/dist/src/remote-web/start.js +27 -64
  61. package/dist/src/remote-web/stop.js +6 -25
  62. package/dist/src/request-trust.js +15 -32
  63. package/dist/src/runtime/dispatch.js +33 -143
  64. package/dist/src/runtime/effects.js +7 -17
  65. package/dist/src/runtime/events.js +1 -1
  66. package/dist/src/runtime/fsm.js +11 -61
  67. package/dist/src/runtime/rules.js +121 -199
  68. package/dist/src/secrets.js +15 -38
  69. package/dist/src/service.js +22 -128
  70. package/dist/src/settings.js +41 -42
  71. package/dist/src/ssh-config.js +22 -41
  72. package/dist/src/ssh-failures.js +23 -74
  73. package/dist/src/ssh-sftp.js +47 -86
  74. package/dist/src/ssh.js +99 -179
  75. package/dist/src/store.js +31 -48
  76. package/dist/src/tool-shared.js +17 -52
  77. package/dist/src/tools-exec-policy.js +33 -79
  78. package/dist/src/tools-exec.js +87 -151
  79. package/dist/src/tools-report.js +100 -167
  80. package/dist/src/tools.js +59 -133
  81. package/dist/src/tunnel.js +9 -27
  82. package/dist/src/util.js +19 -56
  83. package/dist/src/version.js +6 -12
  84. package/dist/src/watchdog-bus.js +0 -8
  85. package/dist/src/watchdog.js +7 -47
  86. package/package.json +3 -3
@@ -1,19 +1,8 @@
1
1
  import { messageOf } from '../util.js';
2
2
  import { watchable } from '../watchdog.js';
3
- /**
4
- * A liveness episode recovered. The remote answers the SSH probe again, so the local listener is
5
- * what may still be broken (B8): ask the listener first — one failed upstream connection is not a
6
- * broken tunnel, and rebuilding would drop live WebSockets for nothing — then rebuild it when it
7
- * really is down. The `recovered` event is announced once the link is usable again, which is the
8
- * point in the sequence the pre-bus code announced it at.
9
- * @param ctx - the actor's three slices.
10
- * @param entries - the bound orchestration entries.
11
- * @param runtime - the host whose episode closed.
12
- * @param source - which reporter saw the remote fail.
13
- */
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. */
14
4
  async function onRecovered(ctx, entries, runtime, source) {
15
- const transient = source === 'proxy' || source === 'tunnel';
16
- if (transient) {
5
+ if (source === 'proxy' || source === 'tunnel') {
17
6
  let healthy = false;
18
7
  try {
19
8
  healthy = (await ctx.deps.tunnelProbe?.(runtime.tunnel?.localPort ?? null)) === true;
@@ -27,9 +16,8 @@ async function onRecovered(ctx, entries, runtime, source) {
27
16
  else {
28
17
  try {
29
18
  const repaired = await entries.repair(runtime);
30
- if (repaired && repaired.ok !== true) {
19
+ if (repaired && repaired.ok !== true)
31
20
  ctx.progress.log(runtime, 'debug', `tunnel rebuild skipped (${repaired.reason ?? 'unknown'})`);
32
- }
33
21
  }
34
22
  catch (error) {
35
23
  // swallow-ok: a failed repair is reported by the helper; the episode still recovers
@@ -42,35 +30,15 @@ async function onRecovered(ctx, entries, runtime, source) {
42
30
  return;
43
31
  ctx.onRemoteUnreachable?.(runtime, { phase: 'recovered', source });
44
32
  }
45
- /**
46
- * One bus event, dispatched to the runtime it names.
47
- * @param ctx - the actor's three slices.
48
- * @param entries - the bound orchestration entries.
49
- * @param event - the action request the liveness detector published.
50
- */
51
33
  function runWatchdogEvent(ctx, entries, event) {
52
34
  const runtime = ctx.state.runtimes.get(event.hostId);
53
- // A host removed between the probe and the event has nothing to act on.
54
35
  if (!runtime)
55
36
  return;
56
- if (event.kind === 'confirmed') {
37
+ if (event.kind === 'confirmed')
57
38
  void entries.reattach(runtime, { reason: event.reason, source: event.source });
58
- return;
59
- }
60
- void onRecovered(ctx, entries, runtime, event.source);
39
+ else
40
+ void onRecovered(ctx, entries, runtime, event.source);
61
41
  }
62
- /**
63
- * Subscribe this service instance to the watchdog bus.
64
- *
65
- * `confirmed` means the probes agreed the remote UI is gone: re-read the remote, refresh the run
66
- * registry and rebuild the tunnel (`reattachHost`). `recovered` means it answers again: fix the
67
- * listener and announce the episode (see {@link onRecovered}).
68
- *
69
- * @param ctx - the actor's three slices (the subscriber drives orchestration, so the facade binds
70
- * the entries rather than handing over the whole context).
71
- * @param entries - the two orchestration entries, bound to the facade's context.
72
- * @returns the unsubscribe function; `service.shutdown()` must call it before tearing hosts down.
73
- */
74
42
  export function installWatchdog(ctx, entries) {
75
43
  return ctx.bus.subscribe((event) => runWatchdogEvent(ctx, entries, event));
76
44
  }
@@ -1,25 +1,16 @@
1
- /**
2
- * The connect log behind `HostView.logs`: the per-host ring, the per-connection reset, the structured failure lines, its bounded `/state` tail and which statuses print it.
3
- */
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. */
4
3
  import { redactText } from './redact.js';
5
4
  import { headTail, isPlainObject } from './util.js';
6
5
  export const CONNECT_LOG_STATUSES = Object.freeze(['connecting', 'fingerprint-pending', 'error']);
7
6
  export const LOG_RING_LIMIT = 200;
8
7
  export const LOG_TAIL_LIMIT = 120;
9
- /** How much of one technical detail (redacted) the log prints before `headTail` elides it. */
10
8
  export const LOG_TECHNICAL_LIMIT = 1200;
11
- /** How long a single remote-log / technical line may get before it is elided. */
12
9
  export const LOG_LINE_LIMIT = 400;
13
- /** Cap on the remote-log lines a failed start prints, so a chatty tail cannot eat the ring. */
14
10
  export const LOG_TAIL_LINES = 60;
15
11
  export function connectLogVisible(status) {
16
12
  return typeof status === 'string' && CONNECT_LOG_STATUSES.includes(status);
17
13
  }
18
- /** A bilingual line: zh and en side by side, the shape the Client already resolves. */
19
- function pair(zh, en) {
20
- return { zh, en };
21
- }
22
- /** Accept only a complete { zh, en } pair; a half-resolved object would render as an empty line. */
23
14
  function normalizeText(value) {
24
15
  if (!isPlainObject(value))
25
16
  return null;
@@ -27,14 +18,12 @@ function normalizeText(value) {
27
18
  const en = typeof value.en === 'string' ? value.en : '';
28
19
  if (zh === '' || en === '')
29
20
  return null;
30
- return pair(zh, en);
21
+ return { zh, en };
31
22
  }
32
23
  export function appendConnectLog(runtime, input) {
33
24
  const raw = typeof input.message === 'string' ? input.message : String(input.message ?? '');
34
- // The remote's own stdout arrives here (`remote-web/start.js` hands every start line to `onLine`,
35
- // and the first one is the launch URL with its session token). This ring is the second exit of
36
- // that text — `HostView.logs`, the SSE state frames and the diagnostics export all read it — so
37
- // it is redacted at write time, not only when the failure view is built.
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.
38
27
  const message = headTail(redactText(raw), LOG_TECHNICAL_LIMIT);
39
28
  const entry = {
40
29
  seq: (typeof runtime.logSeq === 'number' ? runtime.logSeq : 0) + 1,
@@ -57,22 +46,18 @@ export function appendConnectLog(runtime, input) {
57
46
  runtime.logs.push(entry);
58
47
  return entry;
59
48
  }
60
- /** Forget the previous connection's lines; the sequence restarts with this connection. */
61
49
  export function resetConnectLog(runtime) {
62
50
  runtime.logs = [];
63
51
  runtime.logSeq = 0;
64
52
  return runtime;
65
53
  }
66
- /** `YYYY-MM-DD HH:MM:SS` in the Host's own timezone — the clock the user reads. */
67
54
  function localClock(date) {
68
55
  const pad = (value) => String(value).padStart(2, '0');
69
56
  return (`${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` +
70
57
  `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`);
71
58
  }
72
- /**
73
- * Start one connection's log: drop the previous attempt and write its boundary line, so the
74
- * panel opens on this attempt only and a copied log says which attempt it belongs to.
75
- */
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. */
76
61
  export function beginConnectLog(runtime, options = {}) {
77
62
  const at = typeof options.at === 'string' && options.at !== '' ? options.at : new Date().toISOString();
78
63
  const when = new Date(at);
@@ -80,13 +65,12 @@ export function beginConnectLog(runtime, options = {}) {
80
65
  runtime.connectCount = attempt;
81
66
  resetConnectLog(runtime);
82
67
  const clock = Number.isNaN(when.getTime()) ? at : localClock(when);
83
- const text = pair(`— 第 ${attempt} 次连接 · ${clock} —`, `— Connection ${attempt} · ${clock} —`);
68
+ const text = { zh: `— 第 ${attempt} 次连接 · ${clock} —`, en: `— Connection ${attempt} · ${clock} —` };
84
69
  return appendConnectLog(runtime, { at, level: 'info', message: text.en, text, boundary: true });
85
70
  }
86
- /** `{ zh, en }` from any bilingual value, filling a missing side from the other. */
87
71
  function say(value) {
88
72
  if (typeof value === 'string')
89
- return value === '' ? null : pair(value, value);
73
+ return value === '' ? null : { zh: value, en: value };
90
74
  if (!isPlainObject(value))
91
75
  return null;
92
76
  const zh = typeof value.zh === 'string' ? value.zh : '';
@@ -95,14 +79,8 @@ function say(value) {
95
79
  return null;
96
80
  return { zh: zh === '' ? en : zh, en: en === '' ? zh : en };
97
81
  }
98
- /**
99
- * Turn an `ErrorView` into the lines the connect log prints for a failed connection:
100
- * the failed phase and code, the localized reason, every hint, then the redacted and
101
- * head-tail-truncated technical detail — the remote log tail line by line for a failed start.
102
- *
103
- * `options.label` replaces the first line for a one-shot action that is not a connect (the
104
- * explicit remote stop), so its failure is not announced as a connection failure.
105
- */
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). */
106
84
  export function connectFailureLines(view, options = {}) {
107
85
  const code = typeof view?.code === 'string' && view.code !== '' ? view.code : 'internal';
108
86
  const phase = typeof options.phase === 'string' && options.phase !== '' ? options.phase : null;
@@ -112,24 +90,21 @@ export function connectFailureLines(view, options = {}) {
112
90
  const label = normalizeText(options.label);
113
91
  push(label ??
114
92
  (phase === null
115
- ? pair(`连接失败:${code}`, `Connect failed: ${code}`)
116
- : pair(`连接失败于 ${phase} 阶段:${code}`, `Connect failed in phase ${phase}: ${code}`)));
117
- // The card explains the failure in one sentence; the log has to carry that sentence.
93
+ ? { zh: `连接失败:${code}`, en: `Connect failed: ${code}` }
94
+ : { zh: `连接失败于 ${phase} 阶段:${code}`, en: `Connect failed in phase ${phase}: ${code}` }));
118
95
  const reason = say(view?.detail) ?? say(view?.title);
119
96
  if (reason !== null)
120
- push(pair(`原因:${reason.zh}`, `Reason: ${reason.en}`));
97
+ push({ zh: `原因:${reason.zh}`, en: `Reason: ${reason.en}` });
121
98
  const hints = Array.isArray(view?.nextSteps) ? view.nextSteps : [];
122
99
  for (const hint of hints) {
123
100
  const step = say(hint);
124
101
  if (step !== null)
125
- push(pair(`建议:${step.zh}`, `Next: ${step.en}`));
102
+ push({ zh: `建议:${step.zh}`, en: `Next: ${step.en}` });
126
103
  }
127
104
  const technical = typeof view?.technical === 'string' ? view.technical : '';
128
105
  if (technical.trim() !== '') {
129
106
  const tail = code === 'remote-dsh-start-failed';
130
- push(tail ? pair('远端日志尾部:', 'Remote log tail:') : pair('技术细节:', 'Details:'));
131
- // Redaction is the contract of anything copied out of the log; `headTail` keeps both the
132
- // start of the message (what failed) and its end (the error itself) when it is too long.
107
+ push(tail ? { zh: '远端日志尾部:', en: 'Remote log tail:' } : { zh: '技术细节:', en: 'Details:' });
133
108
  let printed = 0;
134
109
  for (const line of headTail(redactText(technical), LOG_TECHNICAL_LIMIT).split(/\r?\n/)) {
135
110
  if (printed >= LOG_TAIL_LINES)
@@ -1,24 +1,17 @@
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
- */
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. */
5
3
  import { appendConnectLog, connectFailureLines, connectLogVisible } from './connect-log.js';
6
4
  import { logVisible, nowIso } from './util.js';
7
- /** Throttle for the npx reporter: one progress frame per 700 ms at most. */
8
5
  const REPORT_MIN_INTERVAL_MS = 700;
9
6
  function stripAnsi(text) {
10
7
  return String(text ?? '').replace(/\u001B\[[0-9;]*m/g, '');
11
8
  }
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
- */
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. */
17
11
  export function describePreflightEvent(line, version) {
18
12
  const text = stripAnsi(line).trim();
19
13
  if (text === '')
20
14
  return null;
21
- // The package's own `--version` output is the success signal, not progress.
22
15
  if (/^v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(text))
23
16
  return null;
24
17
  if (/The following package was not found and will be installed/i.test(text)) {
@@ -31,7 +24,6 @@ export function describePreflightEvent(line, version) {
31
24
  return { code: 'bootstrap-progress', params: { detail: text.slice(0, 160) } };
32
25
  }
33
26
  export function createConnectProgress(options) {
34
- /** Append one line and echo it to the Host logger at the same level. */
35
27
  function write(runtime, input) {
36
28
  const entry = appendConnectLog(runtime, { at: nowIso(), ...input });
37
29
  // Verbosity is a runtime decision: `options.logLevel` (tests, diagnostics) or settings.
@@ -42,17 +34,19 @@ export function createConnectProgress(options) {
42
34
  method?.(entry.line);
43
35
  return entry;
44
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
+ }
45
43
  function log(runtime, level, ...args) {
46
44
  const message = args.map((value) => (typeof value === 'string' ? value : JSON.stringify(value))).join(' ');
47
45
  const entry = write(runtime, { level, message, phase: runtime.phase });
48
46
  publish(runtime);
49
47
  return entry;
50
48
  }
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
- */
49
+ /** Print a failed connection as the lines that explain it; `context.label` replaces the leading line for a stop. */
56
50
  function logFailure(runtime, view, context = {}) {
57
51
  const phase = typeof context.phase === 'string' && context.phase !== '' ? context.phase : null;
58
52
  for (const line of connectFailureLines(view, { phase, label: context.label })) {
@@ -60,30 +54,11 @@ export function createConnectProgress(options) {
60
54
  }
61
55
  publish(runtime);
62
56
  }
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
57
  function phase(runtime, phaseName, code, params) {
78
58
  runtime.phase = phaseName;
79
59
  runtime.progress = { code, ...(params ? { params } : {}) };
80
60
  options.emitState();
81
61
  }
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
62
  function nodeProgress(runtime, event) {
88
63
  if (event.step === 'check')
89
64
  return;
@@ -100,11 +75,8 @@ export function createConnectProgress(options) {
100
75
  log(runtime, 'info', `installing managed Node v${event.version}`);
101
76
  phase(runtime, 'bootstrap', 'installing-node', { version: event.version });
102
77
  }
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
- */
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). */
108
80
  function bootstrapReporter(runtime, version) {
109
81
  let buffer = '';
110
82
  let lastAt = 0;
@@ -133,10 +105,6 @@ export function createConnectProgress(options) {
133
105
  }
134
106
  };
135
107
  }
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
108
  function dispose() { }
141
109
  return { log, logFailure, phase, nodeProgress, bootstrapReporter, dispose };
142
110
  }
@@ -1,67 +1,42 @@
1
- /**
2
- * Shared constants for the remote npx runtime and the plugin surface.
3
- */
1
+ /** Shared constants for the remote npx runtime and the plugin surface. */
4
2
  export const DEFAULT_REMOTE_PROFILE = 'web';
5
3
  export const REMOTE_DSH_DIR = '.dsh';
6
4
  export const REMOTE_STATE_DIR = 'remote-go';
7
5
  export const API_PREFIX = '/dsh-remote-go/api';
8
- /**
9
- * Same-origin seat of the remote web UI used by the browser half: every request below
10
- * `<prefix><hostId>/` is proxied to that connected host's loopback tunnel (see proxy/index.ts).
11
- */
12
6
  export const REMOTE_VIEW_PREFIX = '/dsh-remote-go/remote/';
13
7
  export const API_HEADER = 'x-dsh-remote-go';
14
8
  export const PLUGIN_ID = 'dsh-remote-go';
15
- export const PLUGIN_VERSION = '0.3.0';
16
- /**
17
- * DSH's own lower bound, mirrored from this package's `engines.dsh`. The client may only
18
- * backfill a locally-detected DSH version; a value below this floor names a build the plugin
19
- * does not support, so `/local-version` refuses it (it would otherwise pin the remote npx
20
- * runtime to an arbitrary, possibly unusable version).
21
- */
9
+ export const PLUGIN_VERSION = '0.3.2';
22
10
  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
11
  export const API_VERSION = '2.12';
25
12
  export const DEFAULT_KEY_PATH = '~/.ssh/id_rsa';
26
13
  export const REMOTE_START_TIMEOUT_MS = 300_000;
27
14
  export const REMOTE_CONFLICT_TIMEOUT_MS = 120_000;
28
15
  export const SSH_READY_TIMEOUT_MS = 20_000;
16
+ /** SSH keepalive cadence: a probe every 15 s keeps NAT/firewall state alive without loading a thin link. */
17
+ export const SSH_KEEPALIVE_INTERVAL_MS = 15_000;
18
+ /** Unanswered keepalives tolerated before the transport is declared dead: 4 x 15 s rides out a ~60 s stall
19
+ * (mobile handoff, VPN re-key, congestion) that used to drop the session after 45 s. */
20
+ export const SSH_KEEPALIVE_COUNT_MAX = 4;
29
21
  export const DEFAULT_IDLE_MINUTES = 15;
30
22
  export const TUNNEL_PROBE_TIMEOUT_MS = 10_000;
31
- /**
32
- * Remote liveness: a connected host's remote UI is probed on this interval
33
- * (`settings.remoteHeartbeat`). Two consecutive failed probes - not one failed
34
- * request - are what confirm that the remote web really went away.
35
- */
36
23
  export const REMOTE_HEARTBEAT_DEFAULT_SEC = 30;
37
24
  export const REMOTE_HEARTBEAT_MIN_SEC = 5;
38
25
  export const REMOTE_HEARTBEAT_MAX_SEC = 600;
39
- /** Consecutive failed probes that turn a suspicion into a confirmed restart. */
40
- export const REMOTE_UNREACHABLE_FAILURES = 2;
41
- /** Delay before the confirming probe after a proxy/tunnel error (never trust one failure). */
42
- export const REMOTE_UNREACHABLE_CONFIRM_DELAY_MS = 750;
43
- /** Delay between the two confirming probes, so they are consecutive but not one slow request. */
44
- export const REMOTE_UNREACHABLE_RECHECK_DELAY_MS = 1200;
45
- /**
46
- * After a transient (proxy/tunnel) episode is confirmed healthy, the same kind of report is
47
- * ignored for this long: a flapping tunnel must not emit suspected/recovered on every request.
48
- */
26
+ /** Consecutive failed probes before a re-attach. Two was one lost packet away from tearing down a healthy link over a
27
+ * slow tunnel; the quick recheck after each failure still proves a real restart in a few seconds. */
28
+ export const REMOTE_UNREACHABLE_FAILURES = 3;
29
+ export const REMOTE_UNREACHABLE_CONFIRM_DELAY_MS = 2_500;
30
+ export const REMOTE_UNREACHABLE_RECHECK_DELAY_MS = 3_500;
49
31
  export const REMOTE_EPISODE_COOLDOWN_MS = 15_000;
50
- /**
51
- * A failed listener rebuild waits before the next attempt (doubling up to the max). The
52
- * episode cooldown alone would still let a broken rebuild retry every 15s forever.
53
- */
54
32
  export const REMOTE_REPAIR_BACKOFF_MS = 30_000;
55
33
  export const REMOTE_REPAIR_BACKOFF_MAX_MS = 120_000;
56
- /**
57
- * How long teardown waits for an in-flight listener rebuild. The rebuild is local and fast;
58
- * a stuck one must not delay disconnect / host removal / shutdown indefinitely. Its token is
59
- * already cancelled, so it still closes any listener it manages to publish afterwards.
60
- */
61
34
  export const REMOTE_TUNNEL_REPAIR_SETTLE_MS = 5_000;
62
- /**
63
- * A remote restart needs a little time to print its new readiness line. The
64
- * re-attach retries the read-back a few times before it declares the remote gone.
65
- */
66
35
  export const REMOTE_REATTACH_ATTEMPTS = 6;
67
36
  export const REMOTE_REATTACH_INTERVAL_MS = 2_000;
37
+ /** Spacing of the slow retries that follow the fast reconnect budget: one attempt every 30 s keeps a bad link from
38
+ * being hammered while the user still gets the link back on its own. */
39
+ export const REMOTE_RECONNECT_SLOW_DELAY_MS = 30_000;
40
+ /** How long the slow phase keeps trying before auto-reconnect gives up: 10 minutes covers a reboot, a VPN re-dial or
41
+ * a carrier handoff, which is exactly the window where a user expects the connection to come back by itself. */
42
+ export const REMOTE_RECONNECT_PATIENCE_MS = 10 * 60_000;
@@ -1,15 +1,8 @@
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
- */
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. */
11
4
  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';
5
+ import { REMOTE_CONFLICT_TIMEOUT_MS, REMOTE_REATTACH_ATTEMPTS, REMOTE_REATTACH_INTERVAL_MS, REMOTE_RECONNECT_PATIENCE_MS, REMOTE_RECONNECT_SLOW_DELAY_MS, REMOTE_TUNNEL_REPAIR_SETTLE_MS, REMOTE_UNREACHABLE_CONFIRM_DELAY_MS, REMOTE_UNREACHABLE_RECHECK_DELAY_MS, } from './constants.js';
13
6
  import { createConnectProgress } from './connect-progress.js';
14
7
  import { loadLocalSshMaterial } from './local-ssh.js';
15
8
  import { ensureRemoteNode } from './node-runtime.js';
@@ -22,37 +15,28 @@ import { stopRemoteWeb } from './remote-web/stop.js';
22
15
  import { createSsh2Port } from './ssh.js';
23
16
  import { createTunnel, probeLoopback } from './tunnel.js';
24
17
  import { createWatchdogBus } from './watchdog-bus.js';
25
- /** Milliseconds a paused host-key handshake waits for the user. */
26
18
  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
- */
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. */
39
23
  export function createCtx(options, hooks) {
40
24
  const logger = options.logger ?? console;
41
25
  const logLevel = typeof options.logLevel === 'string' ? options.logLevel : null;
42
26
  const timers = {
43
27
  hostKeyConfirmMs: options.hostKeyConfirmTimeoutMs ?? HOST_KEY_CONFIRM_TIMEOUT_MS,
44
28
  conflictConfirmMs: options.conflictConfirmTimeoutMs ?? REMOTE_CONFLICT_TIMEOUT_MS,
45
- // Liveness confirmation and the re-attach retry loop; tests shorten these.
46
29
  remoteConfirmDelayMs: options.remoteConfirmDelayMs ?? REMOTE_UNREACHABLE_CONFIRM_DELAY_MS,
47
30
  remoteRecheckMs: options.remoteRecheckMs ?? REMOTE_UNREACHABLE_RECHECK_DELAY_MS,
48
31
  reattachAttempts: options.reattachAttempts ?? REMOTE_REATTACH_ATTEMPTS,
49
32
  reattachIntervalMs: options.reattachIntervalMs ?? REMOTE_REATTACH_INTERVAL_MS,
50
33
  tunnelRepairSettleMs: options.tunnelRepairSettleMs ?? REMOTE_TUNNEL_REPAIR_SETTLE_MS,
34
+ reconnectSlowDelayMs: options.reconnectSlowDelayMs ?? REMOTE_RECONNECT_SLOW_DELAY_MS,
35
+ reconnectPatienceMs: options.reconnectPatienceMs ?? REMOTE_RECONNECT_PATIENCE_MS,
51
36
  };
52
37
  const deps = {
53
38
  sshFactory: options.sshFactory ?? ((sshOptions) => createSsh2Port(sshOptions)),
54
39
  tunnelFactory: options.tunnelFactory ?? createTunnel,
55
- /** Local listener health: decides whether a transient proxy failure needs a rebuild. */
56
40
  tunnelProbe: options.tunnelProbe ?? probeLoopback,
57
41
  probe: options.probe ?? probeRemote,
58
42
  plan: options.plan ?? planNpx,
@@ -78,12 +62,10 @@ export function createCtx(options, hooks) {
78
62
  logLevel,
79
63
  getSettings: () => options.store.getSettings(),
80
64
  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
65
  emitLogs: (runtime) => hooks.publishLogs(runtime.id),
84
66
  });
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.
67
+ // One bus per service instance: a test (or a plugin reload) that builds a second service must not
68
+ // inherit the first one's subscriber.
87
69
  const bus = createWatchdogBus({ warn: logger.warn });
88
70
  const state = {
89
71
  runtimes: new Map(),
@@ -95,8 +77,7 @@ export function createCtx(options, hooks) {
95
77
  state,
96
78
  home: options.home,
97
79
  timers,
98
- // Live readers, never cached: a setting or a detected version can change while a connect is
99
- // already in flight.
80
+ // Live readers, never cached: a setting or a detected version can change mid-connect.
100
81
  settings: () => options.store.getSettings(),
101
82
  localVersion: () => hooks.localVersion(),
102
83
  engineNodeRange: () => hooks.engineNodeRange(),
@@ -1,6 +1,4 @@
1
- /**
2
- * The diagnostic checklist: read-only, opens no new connections.
3
- */
1
+ /** The diagnostic checklist: read-only, opens no new connections, and redacts the exported report. */
4
2
  import { isNodeVersionSupported, versionParity } from './version.js';
5
3
  import { nowIso } from './util.js';
6
4
  import { redactObject } from './redact.js';
@@ -27,16 +25,24 @@ export async function diagnoseHost(runtime, ctx) {
27
25
  const entry = runtime.entry;
28
26
  const facts = runtime.facts;
29
27
  const sshLive = Boolean(runtime.ssh?.connected);
30
- push('ssh-reachable', sshLive ? 'pass' : runtime.error ? 'fail' : 'unknown', sshLive
28
+ let sshStatus = 'unknown';
29
+ if (sshLive)
30
+ sshStatus = 'pass';
31
+ else if (runtime.error)
32
+ sshStatus = 'fail';
33
+ push('ssh-reachable', sshStatus, sshLive
31
34
  ? t(`已连接 ${entry.address}`, `Connected to ${entry.address}`)
32
35
  : (runtime.error?.detail ?? t('尚未连接,请先连接一次。', 'Not connected yet; connect once first.')));
33
36
  const authType = entry.auth?.type ?? 'agent';
34
37
  push('auth', sshLive ? 'pass' : 'unknown', sshLive
35
38
  ? t(`认证方式:${authType}(凭据不会保存在本机)`, `Method: ${authType} (no credentials are stored locally)`)
36
39
  : t('连接后检查', 'Checked after connecting'));
40
+ // The pinned fingerprint is compared with the one this session proved, never with the address.
37
41
  const pinned = entry.pinnedFingerprint;
38
42
  const liveFingerprint = runtime.fingerprint?.sha256 ?? null;
39
- const keyStatus = pinned && liveFingerprint ? (pinned === liveFingerprint ? 'pass' : 'fail') : 'unknown';
43
+ let keyStatus = 'unknown';
44
+ if (pinned && liveFingerprint)
45
+ keyStatus = pinned === liveFingerprint ? 'pass' : 'fail';
40
46
  let keyDetail = t('尚未记录指纹,首次连接时会询问。', 'No host key recorded yet; it is asked on first connect.');
41
47
  if (pinned) {
42
48
  const session = liveFingerprint ? `,本次 ${liveFingerprint}` : '';
@@ -50,52 +56,77 @@ export async function diagnoseHost(runtime, ctx) {
50
56
  push('tunnel', tunnel ? 'pass' : 'fail', tunnel
51
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'}`)
52
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.
53
60
  const remoteAlive = sshLive && runtime.exchange?.status === 200;
54
- push('remote-service', remoteAlive ? 'pass' : sshLive ? 'fail' : 'unknown', remoteAlive
61
+ let serviceStatus = 'unknown';
62
+ if (remoteAlive)
63
+ serviceStatus = 'pass';
64
+ else if (sshLive)
65
+ serviceStatus = 'fail';
66
+ push('remote-service', serviceStatus, remoteAlive
55
67
  ? t(`远端进程 pid=${runtime.remote.pid ?? '未知'},本地端口 ${runtime.remote.localPort ?? '未知'}`, `Remote pid ${runtime.remote.pid ?? 'unknown'}, local port ${runtime.remote.localPort ?? 'unknown'}`)
56
68
  : t('远端服务未确认在运行。', 'The remote service is not confirmed running.'));
57
- push('remote-ui', runtime.exchange?.ok ? 'pass' : sshLive ? 'fail' : 'unknown', runtime.exchange?.ok
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
58
75
  ? t(`页面标题:${runtime.exchange.title ?? '(无)'}`, `Page title: ${runtime.exchange.title ?? '(none)'}`)
59
76
  : t('尚未完成远端界面的鉴权握手。', 'The remote UI authentication handshake has not completed.'));
60
77
  const nodeVersion = facts?.nodeVersion ?? null;
61
78
  const nodeOk = isNodeVersionSupported(nodeVersion) && Boolean(facts?.npxPath);
79
+ let nodeStatus = 'unknown';
62
80
  let nodeDetail = NOT_PROBED;
63
81
  if (facts) {
82
+ nodeStatus = nodeOk ? 'pass' : 'fail';
64
83
  nodeDetail = nodeOk
65
84
  ? t(`Node ${nodeVersion}(插件托管),npx 可用`, `Node ${nodeVersion} (plugin-managed) with npx available`)
66
85
  : t(`Node ${nodeVersion ?? '未检测到'}${facts.npxPath ? '' : ',缺少 npx'},不满足 ≥ 24.9。`, `Node ${nodeVersion ?? 'not detected'}${facts.npxPath ? '' : ' (npx missing)'} does not meet >= 24.9.`);
67
86
  }
68
- push('remote-node', facts ? (nodeOk ? 'pass' : 'fail') : 'unknown', nodeDetail);
87
+ push('remote-node', nodeStatus, nodeDetail);
69
88
  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
- });
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 });
74
95
  const credentials = facts
75
96
  ? Boolean(facts.credentialsFile || facts.deepseekKeyEnv || facts.providerEnvKeys.length > 0)
76
97
  : false;
77
- push('model-credentials', facts ? (credentials ? 'pass' : 'unknown') : 'unknown', facts
78
- ? credentials
98
+ let credentialStatus = 'unknown';
99
+ let credentialDetail = NOT_PROBED;
100
+ if (facts) {
101
+ credentialStatus = credentials ? 'pass' : 'unknown';
102
+ credentialDetail = credentials
79
103
  ? 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
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
84
112
  ? 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);
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);
87
116
  const failed = checks.filter((check) => check.status === 'fail').length;
88
117
  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.
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.
92
125
  return redactObject({
93
126
  summary,
94
127
  checks,
95
128
  redacted: true,
96
129
  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
130
  restarts: (Array.isArray(runtime.restarts) ? runtime.restarts : []).slice(-10),
100
131
  logs: runtime.logs.slice(-40).map((entry) => entry.line),
101
132
  });