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
@@ -1,155 +0,0 @@
1
- /**
2
- * Connect progress: the coalesced `/state` frame that carries log lines, the staged progress line and the npm / managed-Node reporters; it never sets a status.
3
- */
4
- import { appendConnectLog, connectFailureLines, connectLogVisible } from './connect-log.js'
5
- import { logVisible, nowIso } from './util.js'
6
-
7
- /**
8
- * Coalescing window for shipping log lines: the connect console may print many
9
- * lines a second (npx download, remote stdout), and every one of them would
10
- * otherwise be its own `/state` frame.
11
- */
12
- const LOG_FLUSH_MS = 150
13
-
14
- /** Throttle for the npx reporter: one progress frame per 700 ms at most. */
15
- const REPORT_MIN_INTERVAL_MS = 700
16
-
17
- function stripAnsi(text) {
18
- return String(text ?? '').replace(/\u001B\[[0-9;]*m/g, '')
19
- }
20
-
21
- /**
22
- * Turn one npm/npx output line into a progress event for the connect line.
23
- * `npm_config_loglevel=http` makes npm report fetches without a TTY; known shapes
24
- * get a localized progress code, anything else is kept (truncated) as a detail.
25
- */
26
- export function describePreflightEvent(line, version) {
27
- const text = stripAnsi(line).trim()
28
- if (text === '') return null
29
- // The package's own `--version` output is the success signal, not progress.
30
- if (/^v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(text)) return null
31
- if (/The following package was not found and will be installed/i.test(text)) {
32
- return { code: 'bootstrap-first-run', params: { version } }
33
- }
34
- if (/^npm (http fetch|http request)/i.test(text)) return { code: 'bootstrap-fetching' }
35
- if (/added \d+ packages? in/i.test(text)) return { code: 'bootstrap-installed' }
36
- return { code: 'bootstrap-progress', params: { detail: text.slice(0, 160) } }
37
- }
38
-
39
- export function createConnectProgress(options) {
40
- let flushTimer = null
41
-
42
- /** Append one line and echo it to the Host logger at the same level. */
43
- function write(runtime, input) {
44
- const entry = appendConnectLog(runtime, { at: nowIso(), ...input })
45
- // Verbosity is a runtime decision: `options.logLevel` (tests, diagnostics) or settings.
46
- const threshold = options.logLevel ?? options.getSettings()?.logLevel ?? 'info'
47
- if (!logVisible(entry.level, threshold)) return entry
48
- const method = options.logger[entry.level] ?? options.logger.info
49
- method?.(entry.line)
50
- return entry
51
- }
52
-
53
- function log(runtime, level, ...args) {
54
- const message = args.map((value) => (typeof value === 'string' ? value : JSON.stringify(value))).join(' ')
55
- const entry = write(runtime, { level, message, phase: runtime.phase })
56
- scheduleFlush(runtime)
57
- return entry
58
- }
59
-
60
- /**
61
- * Print a failed connection as the lines that explain it (phase, code, localized reason,
62
- * hints, redacted details), instead of one line of code plus a raw message. `context.label`
63
- * replaces the leading line for a one-shot action that is not a connect (the remote stop).
64
- */
65
- function logFailure(runtime, view, context = {}) {
66
- const phase = typeof context.phase === 'string' && context.phase !== '' ? context.phase : null
67
- for (const line of connectFailureLines(view, { phase, label: context.label })) {
68
- write(runtime, { level: line.level, message: line.message, text: line.text, phase: line.phase })
69
- }
70
- scheduleFlush(runtime)
71
- }
72
-
73
- /** Ship the log tail to the Client's console without one `/state` frame per line. */
74
- function scheduleFlush(runtime) {
75
- if (!connectLogVisible(runtime.status)) return
76
- if (flushTimer !== null) return
77
- flushTimer = setTimeout(() => {
78
- flushTimer = null
79
- options.emitState()
80
- }, LOG_FLUSH_MS)
81
- // A pending log frame must never keep the process alive on its own.
82
- flushTimer.unref?.()
83
- }
84
-
85
- function set(runtime, patch) {
86
- Object.assign(runtime, patch)
87
- options.emitState()
88
- }
89
-
90
- function phase(runtime, phaseName, code, params) {
91
- runtime.phase = phaseName
92
- runtime.progress = { code, ...(params ? { params } : {}) }
93
- options.emitState()
94
- }
95
-
96
- /**
97
- * Managed-Node provisioning reports coarse steps; surface them in the same
98
- * progress line the rest of the pipeline uses (the installer already bundles
99
- * byte progress into ~5s/8 MB events).
100
- */
101
- function nodeProgress(runtime, event) {
102
- if (event.step === 'check') return
103
- if (event.step === 'download') {
104
- const mb = Math.max(0, Math.round(Number(event.bytes ?? 0) / (1024 * 1024)))
105
- log(runtime, 'info', `downloading managed Node v${event.version} (${mb} MB so far)`)
106
- phase(runtime, 'bootstrap', 'downloading-node', { version: event.version, mb })
107
- return
108
- }
109
- if (event.step === 'ready') {
110
- log(runtime, 'info', `managed Node v${event.version} is ready`)
111
- return
112
- }
113
- log(runtime, 'info', `installing managed Node v${event.version}`)
114
- phase(runtime, 'bootstrap', 'installing-node', { version: event.version })
115
- }
116
-
117
- /**
118
- * Stream one channel of the npx preflight into the connect progress line. npm
119
- * has no TTY over SSH, so the command enables `npm_config_loglevel=http`; each
120
- * line becomes a short detail, throttled so the SSE stream is not flooded.
121
- */
122
- function bootstrapReporter(runtime, version) {
123
- let buffer = ''
124
- let lastAt = 0
125
- let lastKey = ''
126
- return (chunk) => {
127
- buffer += String(chunk ?? '')
128
- const lines = buffer.split(/\r?\n/)
129
- buffer = lines.pop() ?? ''
130
- for (const rawLine of lines) {
131
- const text = stripAnsi(rawLine).trim()
132
- // npx is the slowest step on a cold cache: print what it says at debug level.
133
- if (text !== '') log(runtime, 'debug', `npx: ${text}`)
134
- const event = describePreflightEvent(rawLine, version)
135
- if (!event) continue
136
- const key = `${event.code}:${event.params?.detail ?? ''}`
137
- if (key === lastKey) continue
138
- const now = Date.now()
139
- if (now - lastAt < REPORT_MIN_INTERVAL_MS) continue
140
- lastAt = now
141
- lastKey = key
142
- phase(runtime, 'bootstrap', event.code, event.params)
143
- }
144
- }
145
- }
146
-
147
- function dispose() {
148
- if (flushTimer !== null) {
149
- clearTimeout(flushTimer)
150
- flushTimer = null
151
- }
152
- }
153
-
154
- return { log, logFailure, set, phase, nodeProgress, bootstrapReporter, dispose }
155
- }
package/src/constants.js DELETED
@@ -1,93 +0,0 @@
1
- /**
2
- * Shared constants for the remote npx runtime and the plugin surface.
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
-
13
- /**
14
- * 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).
16
- */
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
-
24
- /**
25
- * DSH's own lower bound, mirrored from this package's `engines.dsh`. The client may only
26
- * backfill a locally-detected DSH version; a value below this floor names a build the plugin
27
- * does not support, so `/local-version` refuses it (it would otherwise pin the remote npx
28
- * runtime to an arbitrary, possibly unusable version).
29
- */
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
-
47
- /**
48
- * Remote liveness: a connected host's remote UI is probed on this interval
49
- * (`settings.remoteHeartbeat`). Two consecutive failed probes - not one failed
50
- * request - are what confirm that the remote web really went away.
51
- */
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
-
58
- /** Consecutive failed probes that turn a suspicion into a confirmed restart. */
59
- export const REMOTE_UNREACHABLE_FAILURES = 2
60
-
61
- /** Delay before the confirming probe after a proxy/tunnel error (never trust one failure). */
62
- export const REMOTE_UNREACHABLE_CONFIRM_DELAY_MS = 750
63
-
64
- /** 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
-
67
- /**
68
- * After a transient (proxy/tunnel) episode is confirmed healthy, the same kind of report is
69
- * ignored for this long: a flapping tunnel must not emit suspected/recovered on every request.
70
- */
71
- export const REMOTE_EPISODE_COOLDOWN_MS = 15_000
72
-
73
- /**
74
- * A failed listener rebuild waits before the next attempt (doubling up to the max). The
75
- * episode cooldown alone would still let a broken rebuild retry every 15s forever.
76
- */
77
- export const REMOTE_REPAIR_BACKOFF_MS = 30_000
78
- export const REMOTE_REPAIR_BACKOFF_MAX_MS = 120_000
79
-
80
- /**
81
- * How long teardown waits for an in-flight listener rebuild. The rebuild is local and fast;
82
- * a stuck one must not delay disconnect / host removal / shutdown indefinitely. Its token is
83
- * already cancelled, so it still closes any listener it manages to publish afterwards.
84
- */
85
- export const REMOTE_TUNNEL_REPAIR_SETTLE_MS = 5_000
86
-
87
- /**
88
- * A remote restart needs a little time to print its new readiness line. The
89
- * re-attach retries the read-back a few times before it declares the remote gone.
90
- */
91
- export const REMOTE_REATTACH_ATTEMPTS = 6
92
-
93
- export const REMOTE_REATTACH_INTERVAL_MS = 2_000
@@ -1,160 +0,0 @@
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
-
8
- /** Check labels, so each `push` below is only about status and detail. */
9
- const TITLES = {
10
- 'ssh-reachable': { zh: 'SSH 可达性', en: 'SSH reachability' },
11
- auth: { zh: '认证方式', en: 'Authentication' },
12
- 'host-key': { zh: '主机指纹', en: 'Host key' },
13
- tunnel: { zh: '本地回环隧道', en: 'Loopback tunnel' },
14
- 'remote-service': { zh: '远端 DSH 服务', en: 'Remote DSH service' },
15
- 'remote-ui': { zh: '远端界面可达性', en: 'Remote UI reachability' },
16
- 'remote-node': { zh: '远端 Node 运行时', en: 'Remote Node runtime' },
17
- 'remote-version': { zh: '远端 DSH 版本', en: 'Remote DSH version' },
18
- 'model-credentials': { zh: '模型凭据', en: 'Model credentials' },
19
- 'desktop-guard': { zh: '远端桌面功能检查', en: 'Remote desktop guard' },
20
- }
21
-
22
- const NOT_PROBED = { zh: '未探测远端环境。', en: 'Remote environment has not been probed.' }
23
-
24
- const t = (zh, en) => ({ zh, en })
25
-
26
- export async function diagnoseHost(runtime, ctx) {
27
- const checks = []
28
- const push = (id, status, detail) => checks.push({ id, title: TITLES[id], status, detail })
29
- const entry = runtime.entry
30
- const facts = runtime.facts
31
- const sshLive = Boolean(runtime.ssh?.connected)
32
-
33
- push(
34
- 'ssh-reachable',
35
- sshLive ? 'pass' : runtime.error ? 'fail' : 'unknown',
36
- sshLive
37
- ? t(`已连接 ${entry.address}`, `Connected to ${entry.address}`)
38
- : (runtime.error?.detail ?? t('尚未连接,请先连接一次。', 'Not connected yet; connect once first.')),
39
- )
40
-
41
- const authType = entry.auth?.type ?? 'agent'
42
- push(
43
- 'auth',
44
- sshLive ? 'pass' : 'unknown',
45
- sshLive
46
- ? t(`认证方式:${authType}(凭据不会保存在本机)`, `Method: ${authType} (no credentials are stored locally)`)
47
- : t('连接后检查', 'Checked after connecting'),
48
- )
49
-
50
- const pinned = entry.pinnedFingerprint
51
- const liveFingerprint = runtime.fingerprint?.sha256 ?? null
52
- const keyStatus = pinned && liveFingerprint ? (pinned === liveFingerprint ? 'pass' : 'fail') : 'unknown'
53
- let keyDetail = t('尚未记录指纹,首次连接时会询问。', 'No host key recorded yet; it is asked on first connect.')
54
- if (pinned) {
55
- const session = liveFingerprint ? `,本次 ${liveFingerprint}` : ''
56
- keyDetail = t(
57
- `已记录 ${pinned}${session}`,
58
- `Pinned ${pinned}${liveFingerprint ? `, this session ${liveFingerprint}` : ''}`,
59
- )
60
- } else if (liveFingerprint) {
61
- keyDetail = t(`本次会话 ${liveFingerprint}(尚未记录)`, `This session ${liveFingerprint} (not pinned yet)`)
62
- }
63
- push('host-key', keyStatus, keyDetail)
64
-
65
- const tunnel = runtime.tunnel
66
- push(
67
- 'tunnel',
68
- tunnel ? 'pass' : 'fail',
69
- tunnel
70
- ? t(
71
- `127.0.0.1:${tunnel.localPort} → 远端 127.0.0.1:${runtime.remote.port ?? '未知'}`,
72
- `127.0.0.1:${tunnel.localPort} → remote 127.0.0.1:${runtime.remote.port ?? 'unknown'}`,
73
- )
74
- : t('隧道未建立(连接断开或尚未连接)。', 'The tunnel is not established (disconnected or not connected yet).'),
75
- )
76
-
77
- const remoteAlive = sshLive && runtime.exchange?.status === 200
78
- push(
79
- 'remote-service',
80
- remoteAlive ? 'pass' : sshLive ? 'fail' : 'unknown',
81
- remoteAlive
82
- ? t(
83
- `远端进程 pid=${runtime.remote.pid ?? '未知'},本地端口 ${runtime.remote.localPort ?? '未知'}`,
84
- `Remote pid ${runtime.remote.pid ?? 'unknown'}, local port ${runtime.remote.localPort ?? 'unknown'}`,
85
- )
86
- : t('远端服务未确认在运行。', 'The remote service is not confirmed running.'),
87
- )
88
-
89
- push(
90
- 'remote-ui',
91
- runtime.exchange?.ok ? 'pass' : sshLive ? 'fail' : 'unknown',
92
- runtime.exchange?.ok
93
- ? t(`页面标题:${runtime.exchange.title ?? '(无)'}`, `Page title: ${runtime.exchange.title ?? '(none)'}`)
94
- : t('尚未完成远端界面的鉴权握手。', 'The remote UI authentication handshake has not completed.'),
95
- )
96
-
97
- const nodeVersion = facts?.nodeVersion ?? null
98
- const nodeOk = isNodeVersionSupported(nodeVersion) && Boolean(facts?.npxPath)
99
- let nodeDetail = NOT_PROBED
100
- if (facts) {
101
- nodeDetail = nodeOk
102
- ? t(`Node ${nodeVersion}(插件托管),npx 可用`, `Node ${nodeVersion} (plugin-managed) with npx available`)
103
- : t(
104
- `Node ${nodeVersion ?? '未检测到'}${facts.npxPath ? '' : ',缺少 npx'},不满足 ≥ 24.9。`,
105
- `Node ${nodeVersion ?? 'not detected'}${facts.npxPath ? '' : ' (npx missing)'} does not meet >= 24.9.`,
106
- )
107
- }
108
- push('remote-node', facts ? (nodeOk ? 'pass' : 'fail') : 'unknown', nodeDetail)
109
-
110
- const parity = versionParity(ctx.targetVersion, runtime.remote.version ?? null)
111
- push('remote-version', parity.status === 'same' ? 'pass' : parity.status === 'different' ? 'fail' : 'unknown', {
112
- zh: parity.message.zh,
113
- en: parity.message.en,
114
- })
115
-
116
- const credentials = facts
117
- ? Boolean(facts.credentialsFile || facts.deepseekKeyEnv || facts.providerEnvKeys.length > 0)
118
- : false
119
- push(
120
- 'model-credentials',
121
- facts ? (credentials ? 'pass' : 'unknown') : 'unknown',
122
- facts
123
- ? credentials
124
- ? t('远端已检测到模型凭据配置。', 'Remote model credentials were detected.')
125
- : t('未检测到模型凭据;请在远端界面里配置。', 'No model credentials detected; configure them in the remote UI.')
126
- : NOT_PROBED,
127
- )
128
-
129
- push(
130
- 'desktop-guard',
131
- facts ? (facts.sshConnection ? 'pass' : 'unknown') : 'unknown',
132
- facts
133
- ? facts.sshConnection
134
- ? t(
135
- '远端 DSH 经 SSH 会话启动,宿主桌面功能已关闭。',
136
- 'The remote DSH runs inside an SSH session, so host desktop features stay off.',
137
- )
138
- : t(
139
- '远端未检测到 SSH 会话标记,目录对话框可能弹在远端屏幕上。',
140
- 'No SSH session marker on the remote; directory dialogs may appear on the remote screen.',
141
- )
142
- : NOT_PROBED,
143
- )
144
-
145
- const failed = checks.filter((check) => check.status === 'fail').length
146
- const unknown = checks.filter((check) => check.status === 'unknown').length
147
- const summary = failed > 0 ? 'error' : unknown > 0 ? 'warning' : 'ok'
148
- // Redaction is the contract of the exported report: tokens, passwords, private
149
- // keys and home directories never leave the machine.
150
- return redactObject({
151
- summary,
152
- checks,
153
- redacted: true,
154
- generatedAt: nowIso(),
155
- // One entry per restart / re-attach, so an exported report can tell a local restart
156
- // apart from a remote one without re-reading the whole connect log.
157
- restarts: (Array.isArray(runtime.restarts) ? runtime.restarts : []).slice(-10),
158
- logs: runtime.logs.slice(-40).map((entry) => entry.line),
159
- })
160
- }
@@ -1,234 +0,0 @@
1
- /**
2
- * Host-side download jobs. Each job streams one remote file or folder directly into
3
- * the local directory the user chose; nothing is buffered in the Host. Jobs publish
4
- * progress and expire so a closed browser cannot pin job slots forever.
5
- */
6
- import { randomUUID } from 'node:crypto'
7
- import { errors, toErrorView } from './errors.js'
8
- import { normalizeRemoteFilePath, readHostDownload, remoteFileName } from './remote-files.js'
9
-
10
- /** How long a finished job remains inspectable before it is pruned. */
11
- export const DOWNLOAD_JOB_TTL_MS = 10 * 60 * 1000
12
- /** Maximum jobs retained at once (preparing + ready). */
13
- export const MAX_DOWNLOAD_JOBS = 4
14
- /** Maximum jobs allowed to read SFTP at the same time. */
15
- export const MAX_PREPARING_DOWNLOADS = 2
16
- /** Minimum interval between progress frames for one job. */
17
- const PROGRESS_INTERVAL_MS = 120
18
-
19
- /**
20
- * @param {{ emit: (job: object) => void, logger?: object, readDownload?: Function,
21
- * ttlMs?: number, maxJobs?: number, maxPreparing?: number, now?: () => number }} options
22
- */
23
- export function createDownloadJobs(options) {
24
- const emit = typeof options.emit === 'function' ? options.emit : () => {}
25
- const logger = options.logger ?? console
26
- const readDownload = typeof options.readDownload === 'function' ? options.readDownload : readHostDownload
27
- const ttlMs = Number.isSafeInteger(options.ttlMs) && options.ttlMs > 0 ? options.ttlMs : DOWNLOAD_JOB_TTL_MS
28
- const maxJobs = Number.isSafeInteger(options.maxJobs) && options.maxJobs > 0 ? options.maxJobs : MAX_DOWNLOAD_JOBS
29
- const maxPreparing =
30
- Number.isSafeInteger(options.maxPreparing) && options.maxPreparing > 0
31
- ? options.maxPreparing
32
- : MAX_PREPARING_DOWNLOADS
33
- const now = typeof options.now === 'function' ? options.now : Date.now
34
- const jobs = new Map()
35
-
36
- const preparingCount = () => [...jobs.values()].filter((job) => job.phase === 'preparing').length
37
-
38
- const view = (job) => ({
39
- id: job.id,
40
- hostId: job.hostId,
41
- path: job.path,
42
- name: job.name,
43
- kind: job.kind,
44
- phase: job.phase,
45
- totalBytes: job.totalBytes,
46
- doneBytes: job.doneBytes,
47
- totalFiles: job.totalFiles,
48
- doneFiles: job.doneFiles,
49
- /**
50
- * Names a folder download deliberately skipped (Windows metadata / shell shortcuts on a
51
- * Windows host). Surfaced so nothing disappears without the user seeing it.
52
- */
53
- ignoredNames: Array.isArray(job.ignoredNames) ? job.ignoredNames : [],
54
- destination: job.destination ?? null,
55
- startedAt: job.startedAt,
56
- error: job.error,
57
- })
58
-
59
- const publish = (job, force = false) => {
60
- if (job.cancelled || !jobs.has(job.id)) return
61
- const stamp = now()
62
- if (!force && stamp - job.lastEmit < PROGRESS_INTERVAL_MS) return
63
- job.lastEmit = stamp
64
- try {
65
- emit(view(job))
66
- } catch (error) {
67
- logger.warn?.('[dsh-remote-go] download progress listener failed:', error)
68
- }
69
- }
70
-
71
- const clearTimer = (job) => {
72
- if (job.timer !== null && typeof clearTimeout === 'function') clearTimeout(job.timer)
73
- job.timer = null
74
- }
75
-
76
- const scheduleExpiry = (job) => {
77
- clearTimer(job)
78
- job.timer = setTimeout(() => {
79
- if (jobs.get(job.id) === job) {
80
- jobs.delete(job.id)
81
- logger.debug?.('[dsh-remote-go] download job expired:', job.id)
82
- }
83
- }, ttlMs)
84
- job.timer.unref?.()
85
- }
86
-
87
- const failJob = (job, error) => {
88
- if (job.cancelled) return
89
- job.phase = 'error'
90
- job.error = toErrorView(error)
91
- clearTimer(job)
92
- publish(job, true)
93
- scheduleExpiry(job)
94
- }
95
-
96
- const prepare = async (runtime, job) => {
97
- try {
98
- const result = await readDownload(runtime, job.path, {
99
- destination: job.destination ?? undefined,
100
- // The same home root the API pre-flight used; the write is judged by it again.
101
- home: job.home,
102
- isCancelled: () => job.cancelled === true,
103
- onInventory: (info) => {
104
- if (job.cancelled) return
105
- if (Number.isFinite(info?.totalBytes)) job.totalBytes = Math.max(0, Number(info.totalBytes))
106
- if (Number.isFinite(info?.totalFiles)) job.totalFiles = Math.max(0, Number(info.totalFiles))
107
- publish(job)
108
- },
109
- onProgress: (info) => {
110
- if (job.cancelled) return
111
- if (Number.isFinite(info?.doneBytes)) job.doneBytes = Math.max(0, Number(info.doneBytes))
112
- if (Number.isFinite(info?.totalBytes)) job.totalBytes = Math.max(0, Number(info.totalBytes))
113
- if (Number.isFinite(info?.doneFiles)) job.doneFiles = Math.max(0, Number(info.doneFiles))
114
- if (Number.isFinite(info?.totalFiles)) job.totalFiles = Math.max(0, Number(info.totalFiles))
115
- publish(job)
116
- },
117
- // Folder downloads report the names they skipped (Windows-only metadata/shortcuts);
118
- // `saveHostFolder` forwards this options object to the SSH layer unchanged.
119
- onIgnored: (names) => {
120
- if (job.cancelled || !Array.isArray(names)) return
121
- job.ignoredNames = names.slice(0, 200).map((name) => String(name))
122
- publish(job)
123
- },
124
- })
125
- if (job.cancelled) return
126
- job.kind = result.kind
127
- job.name = result.name || remoteFileName(job.path)
128
- job.destination = result.destination ?? job.destination
129
- job.totalBytes = Number(result.totalBytes ?? result.size ?? job.totalBytes ?? 0)
130
- job.doneBytes = job.totalBytes
131
- job.totalFiles = Number(result.files ?? job.totalFiles ?? 0)
132
- job.doneFiles = job.totalFiles
133
- job.phase = 'ready'
134
- clearTimer(job)
135
- publish(job, true)
136
- scheduleExpiry(job)
137
- } catch (error) {
138
- if (job.cancelled) return
139
- logger.warn?.('[dsh-remote-go] download preparation failed:', error)
140
- failJob(job, error)
141
- }
142
- }
143
-
144
- return {
145
- /**
146
- * Create and start a download job.
147
- * @param {object} runtime - connected host runtime.
148
- * @param {unknown} rawPath - absolute remote file or folder path.
149
- * @param {{ destination?: string }} [options] - local destination for a folder job.
150
- * @returns {object} the initial job view (phase `preparing`).
151
- */
152
- start(runtime, rawPath, options = {}) {
153
- const path = normalizeRemoteFilePath(rawPath)
154
- if (jobs.size >= maxJobs) {
155
- throw errors.downloadBusy({
156
- zh: `最多同时保留 ${maxJobs} 个下载任务,请先完成或取消一个。`,
157
- en: `At most ${maxJobs} download jobs can be kept; finish or cancel one first.`,
158
- })
159
- }
160
- if (preparingCount() >= maxPreparing) {
161
- throw errors.downloadBusy({
162
- zh: `正在准备 ${maxPreparing} 个下载,请等一个完成后再试。`,
163
- en: `${maxPreparing} downloads are already being prepared; wait for one to finish.`,
164
- })
165
- }
166
- if (!runtime || runtime.status !== 'connected' || !runtime.ssh) {
167
- throw errors.remoteFileUnavailable({
168
- zh: '这台主机还没有连接,无法读取远端文件。',
169
- en: 'This host is not connected, so the remote file cannot be read.',
170
- })
171
- }
172
- const job = {
173
- id: 'dl_' + randomUUID(),
174
- hostId: runtime.id,
175
- path,
176
- name: remoteFileName(path),
177
- kind: null,
178
- phase: 'preparing',
179
- totalBytes: 0,
180
- doneBytes: 0,
181
- totalFiles: 0,
182
- doneFiles: 0,
183
- destination: typeof options.destination === 'string' && options.destination !== '' ? options.destination : null,
184
- // The local home root the destination policy must judge against; not part of the view.
185
- home: typeof options.home === 'string' && options.home !== '' ? options.home : undefined,
186
- startedAt: new Date(now()).toISOString(),
187
- error: null,
188
- ignoredNames: [],
189
- timer: null,
190
- lastEmit: 0,
191
- cancelled: false,
192
- }
193
- jobs.set(job.id, job)
194
- publish(job, true)
195
- void prepare(runtime, job)
196
- return view(job)
197
- },
198
-
199
- /** Current status of one job. */
200
- status(id) {
201
- const job = typeof id === 'string' ? jobs.get(id) : undefined
202
- if (!job) {
203
- throw errors.downloadNotReady({
204
- zh: '这个下载任务不存在或已过期,请重新发起下载。',
205
- en: 'This download job no longer exists or expired; start the download again.',
206
- })
207
- }
208
- return view(job)
209
- },
210
-
211
- /** Cancel one preparing/ready job. Returns false when it was already gone. */
212
- cancel(id) {
213
- const job = typeof id === 'string' ? jobs.get(id) : undefined
214
- if (!job) return false
215
- job.cancelled = true
216
- clearTimer(job)
217
- jobs.delete(job.id)
218
- return true
219
- },
220
-
221
- /** Number of retained jobs, for tests/diagnostics. */
222
- get size() {
223
- return jobs.size
224
- },
225
-
226
- dispose() {
227
- for (const job of jobs.values()) {
228
- job.cancelled = true
229
- clearTimer(job)
230
- }
231
- jobs.clear()
232
- },
233
- }
234
- }