dsh-remote-go 0.0.1 → 0.1.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 (49) hide show
  1. package/README.md +126 -7
  2. package/client.js +5972 -0
  3. package/cordis.patch.yml +3 -0
  4. package/index.js +4 -0
  5. package/locale/en.json +6 -0
  6. package/locale/zh.json +6 -0
  7. package/package.json +76 -3
  8. package/src/api.js +340 -0
  9. package/src/atomic-json.js +208 -0
  10. package/src/bootstrap.js +100 -0
  11. package/src/connect-log.js +39 -0
  12. package/src/connect-pipeline.js +463 -0
  13. package/src/connect-progress.js +135 -0
  14. package/src/constants.js +31 -0
  15. package/src/diagnostics.js +157 -0
  16. package/src/download-jobs.js +217 -0
  17. package/src/errors.js +316 -0
  18. package/src/host-lifecycle.js +187 -0
  19. package/src/host-registry.js +145 -0
  20. package/src/host-runtime.js +53 -0
  21. package/src/host-view.js +51 -0
  22. package/src/index.js +162 -0
  23. package/src/key-files.js +49 -0
  24. package/src/known-hosts.js +94 -0
  25. package/src/layout.js +35 -0
  26. package/src/local-download.js +162 -0
  27. package/src/local-ssh.js +27 -0
  28. package/src/local-version.js +88 -0
  29. package/src/node-runtime.js +521 -0
  30. package/src/probe.js +89 -0
  31. package/src/prompts.js +132 -0
  32. package/src/redact.js +54 -0
  33. package/src/remote-files.js +71 -0
  34. package/src/remote-path.js +73 -0
  35. package/src/remote-proc.js +208 -0
  36. package/src/remote-web.js +300 -0
  37. package/src/secrets.js +79 -0
  38. package/src/service.js +250 -0
  39. package/src/settings.js +135 -0
  40. package/src/ssh-config.js +271 -0
  41. package/src/ssh.js +652 -0
  42. package/src/store.js +143 -0
  43. package/src/tunnel.js +73 -0
  44. package/src/util.js +153 -0
  45. package/src/version.js +103 -0
  46. package/src/webapp.js +28 -0
  47. package/vendor/THIRD_PARTY_NOTICES.md +10 -0
  48. package/vendor/ssh2-entry.mjs +12 -0
  49. package/vendor/ssh2.bundle.cjs +25 -0
@@ -0,0 +1,135 @@
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, 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
+ function log(runtime, level, ...args) {
43
+ const message = args.map((value) => (typeof value === 'string' ? value : JSON.stringify(value))).join(' ')
44
+ const entry = appendConnectLog(runtime, { at: nowIso(), level, message })
45
+ scheduleFlush(runtime)
46
+ // Verbosity is a runtime decision: `options.logLevel` (tests, diagnostics) or settings.
47
+ const threshold = options.logLevel ?? options.getSettings()?.logLevel ?? 'info'
48
+ if (!logVisible(level, threshold)) return
49
+ const method = options.logger[level] ?? options.logger.info
50
+ method?.(entry.line)
51
+ }
52
+
53
+ /** Ship the log tail to the Client's console without one `/state` frame per line. */
54
+ function scheduleFlush(runtime) {
55
+ if (!connectLogVisible(runtime.status)) return
56
+ if (flushTimer !== null) return
57
+ flushTimer = setTimeout(() => {
58
+ flushTimer = null
59
+ options.emitState()
60
+ }, LOG_FLUSH_MS)
61
+ // A pending log frame must never keep the process alive on its own.
62
+ flushTimer.unref?.()
63
+ }
64
+
65
+ function set(runtime, patch) {
66
+ Object.assign(runtime, patch)
67
+ options.emitState()
68
+ }
69
+
70
+ function phase(runtime, phaseName, code, params) {
71
+ runtime.phase = phaseName
72
+ runtime.progress = { code, ...(params ? { params } : {}) }
73
+ options.emitState()
74
+ }
75
+
76
+ /**
77
+ * Managed-Node provisioning reports coarse steps; surface them in the same
78
+ * progress line the rest of the pipeline uses (the installer already bundles
79
+ * byte progress into ~5s/8 MB events).
80
+ */
81
+ function nodeProgress(runtime, event) {
82
+ if (event.step === 'check') return
83
+ if (event.step === 'download') {
84
+ const mb = Math.max(0, Math.round(Number(event.bytes ?? 0) / (1024 * 1024)))
85
+ log(runtime, 'info', `downloading managed Node v${event.version} (${mb} MB so far)`)
86
+ phase(runtime, 'bootstrap', 'downloading-node', { version: event.version, mb })
87
+ return
88
+ }
89
+ if (event.step === 'ready') {
90
+ log(runtime, 'info', `managed Node v${event.version} is ready`)
91
+ return
92
+ }
93
+ log(runtime, 'info', `installing managed Node v${event.version}`)
94
+ phase(runtime, 'bootstrap', 'installing-node', { version: event.version })
95
+ }
96
+
97
+ /**
98
+ * Stream one channel of the npx preflight into the connect progress line. npm
99
+ * has no TTY over SSH, so the command enables `npm_config_loglevel=http`; each
100
+ * line becomes a short detail, throttled so the SSE stream is not flooded.
101
+ */
102
+ function bootstrapReporter(runtime, version) {
103
+ let buffer = ''
104
+ let lastAt = 0
105
+ let lastKey = ''
106
+ return (chunk) => {
107
+ buffer += String(chunk ?? '')
108
+ const lines = buffer.split(/\r?\n/)
109
+ buffer = lines.pop() ?? ''
110
+ for (const rawLine of lines) {
111
+ const text = stripAnsi(rawLine).trim()
112
+ // npx is the slowest step on a cold cache: print what it says at debug level.
113
+ if (text !== '') log(runtime, 'debug', `npx: ${text}`)
114
+ const event = describePreflightEvent(rawLine, version)
115
+ if (!event) continue
116
+ const key = `${event.code}:${event.params?.detail ?? ''}`
117
+ if (key === lastKey) continue
118
+ const now = Date.now()
119
+ if (now - lastAt < REPORT_MIN_INTERVAL_MS) continue
120
+ lastAt = now
121
+ lastKey = key
122
+ phase(runtime, 'bootstrap', event.code, event.params)
123
+ }
124
+ }
125
+ }
126
+
127
+ function dispose() {
128
+ if (flushTimer !== null) {
129
+ clearTimeout(flushTimer)
130
+ flushTimer = null
131
+ }
132
+ }
133
+
134
+ return { log, set, phase, nodeProgress, bootstrapReporter, dispose }
135
+ }
@@ -0,0 +1,31 @@
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
+ export const API_HEADER = 'x-dsh-remote-go'
14
+
15
+ export const PLUGIN_ID = 'dsh-remote-go'
16
+ export const PLUGIN_VERSION = '0.1.0'
17
+
18
+ /** Host↔Client contract version served by `GET /version` (docs/api.md v2.4). */
19
+ export const API_VERSION = '2.6'
20
+
21
+ export const DEFAULT_KEY_PATH = '~/.ssh/id_rsa'
22
+
23
+ export const REMOTE_START_TIMEOUT_MS = 300_000
24
+
25
+ export const REMOTE_CONFLICT_TIMEOUT_MS = 120_000
26
+
27
+ export const SSH_READY_TIMEOUT_MS = 20_000
28
+
29
+ export const DEFAULT_IDLE_MINUTES = 15
30
+
31
+ export const TUNNEL_PROBE_TIMEOUT_MS = 10_000
@@ -0,0 +1,157 @@
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
+ logs: runtime.logs.slice(-40).map((entry) => entry.line),
156
+ })
157
+ }
@@ -0,0 +1,217 @@
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
+ destination: job.destination ?? null,
50
+ startedAt: job.startedAt,
51
+ error: job.error,
52
+ })
53
+
54
+ const publish = (job, force = false) => {
55
+ if (job.cancelled || !jobs.has(job.id)) return
56
+ const stamp = now()
57
+ if (!force && stamp - job.lastEmit < PROGRESS_INTERVAL_MS) return
58
+ job.lastEmit = stamp
59
+ try {
60
+ emit(view(job))
61
+ } catch (error) {
62
+ logger.warn?.('[dsh-remote-go] download progress listener failed:', error)
63
+ }
64
+ }
65
+
66
+ const clearTimer = (job) => {
67
+ if (job.timer !== null && typeof clearTimeout === 'function') clearTimeout(job.timer)
68
+ job.timer = null
69
+ }
70
+
71
+ const scheduleExpiry = (job) => {
72
+ clearTimer(job)
73
+ job.timer = setTimeout(() => {
74
+ if (jobs.get(job.id) === job) {
75
+ jobs.delete(job.id)
76
+ logger.debug?.('[dsh-remote-go] download job expired:', job.id)
77
+ }
78
+ }, ttlMs)
79
+ job.timer.unref?.()
80
+ }
81
+
82
+ const failJob = (job, error) => {
83
+ if (job.cancelled) return
84
+ job.phase = 'error'
85
+ job.error = toErrorView(error)
86
+ clearTimer(job)
87
+ publish(job, true)
88
+ scheduleExpiry(job)
89
+ }
90
+
91
+ const prepare = async (runtime, job) => {
92
+ try {
93
+ const result = await readDownload(runtime, job.path, {
94
+ destination: job.destination ?? undefined,
95
+ isCancelled: () => job.cancelled === true,
96
+ onInventory: (info) => {
97
+ if (job.cancelled) return
98
+ if (Number.isFinite(info?.totalBytes)) job.totalBytes = Math.max(0, Number(info.totalBytes))
99
+ if (Number.isFinite(info?.totalFiles)) job.totalFiles = Math.max(0, Number(info.totalFiles))
100
+ publish(job)
101
+ },
102
+ onProgress: (info) => {
103
+ if (job.cancelled) return
104
+ if (Number.isFinite(info?.doneBytes)) job.doneBytes = Math.max(0, Number(info.doneBytes))
105
+ if (Number.isFinite(info?.totalBytes)) job.totalBytes = Math.max(0, Number(info.totalBytes))
106
+ if (Number.isFinite(info?.doneFiles)) job.doneFiles = Math.max(0, Number(info.doneFiles))
107
+ if (Number.isFinite(info?.totalFiles)) job.totalFiles = Math.max(0, Number(info.totalFiles))
108
+ publish(job)
109
+ },
110
+ })
111
+ if (job.cancelled) return
112
+ job.kind = result.kind
113
+ job.name = result.name || remoteFileName(job.path)
114
+ job.destination = result.destination ?? job.destination
115
+ job.totalBytes = Number(result.totalBytes ?? result.size ?? job.totalBytes ?? 0)
116
+ job.doneBytes = job.totalBytes
117
+ job.totalFiles = Number(result.files ?? job.totalFiles ?? 0)
118
+ job.doneFiles = job.totalFiles
119
+ job.phase = 'ready'
120
+ clearTimer(job)
121
+ publish(job, true)
122
+ scheduleExpiry(job)
123
+ } catch (error) {
124
+ if (job.cancelled) return
125
+ logger.warn?.('[dsh-remote-go] download preparation failed:', error)
126
+ failJob(job, error)
127
+ }
128
+ }
129
+
130
+ return {
131
+ /**
132
+ * Create and start a download job.
133
+ * @param {object} runtime - connected host runtime.
134
+ * @param {unknown} rawPath - absolute remote file or folder path.
135
+ * @param {{ destination?: string }} [options] - local destination for a folder job.
136
+ * @returns {object} the initial job view (phase `preparing`).
137
+ */
138
+ start(runtime, rawPath, options = {}) {
139
+ const path = normalizeRemoteFilePath(rawPath)
140
+ if (jobs.size >= maxJobs) {
141
+ throw errors.downloadBusy({
142
+ zh: `最多同时保留 ${maxJobs} 个下载任务,请先完成或取消一个。`,
143
+ en: `At most ${maxJobs} download jobs can be kept; finish or cancel one first.`,
144
+ })
145
+ }
146
+ if (preparingCount() >= maxPreparing) {
147
+ throw errors.downloadBusy({
148
+ zh: `正在准备 ${maxPreparing} 个下载,请等一个完成后再试。`,
149
+ en: `${maxPreparing} downloads are already being prepared; wait for one to finish.`,
150
+ })
151
+ }
152
+ if (!runtime || runtime.status !== 'connected' || !runtime.ssh) {
153
+ throw errors.remoteFileUnavailable({
154
+ zh: '这台主机还没有连接,无法读取远端文件。',
155
+ en: 'This host is not connected, so the remote file cannot be read.',
156
+ })
157
+ }
158
+ const job = {
159
+ id: 'dl_' + randomUUID(),
160
+ hostId: runtime.id,
161
+ path,
162
+ name: remoteFileName(path),
163
+ kind: null,
164
+ phase: 'preparing',
165
+ totalBytes: 0,
166
+ doneBytes: 0,
167
+ totalFiles: 0,
168
+ doneFiles: 0,
169
+ destination: typeof options.destination === 'string' && options.destination !== '' ? options.destination : null,
170
+ startedAt: new Date(now()).toISOString(),
171
+ error: null,
172
+ timer: null,
173
+ lastEmit: 0,
174
+ cancelled: false,
175
+ }
176
+ jobs.set(job.id, job)
177
+ publish(job, true)
178
+ void prepare(runtime, job)
179
+ return view(job)
180
+ },
181
+
182
+ /** Current status of one job. */
183
+ status(id) {
184
+ const job = typeof id === 'string' ? jobs.get(id) : undefined
185
+ if (!job) {
186
+ throw errors.downloadNotReady({
187
+ zh: '这个下载任务不存在或已过期,请重新发起下载。',
188
+ en: 'This download job no longer exists or expired; start the download again.',
189
+ })
190
+ }
191
+ return view(job)
192
+ },
193
+
194
+ /** Cancel one preparing/ready job. Returns false when it was already gone. */
195
+ cancel(id) {
196
+ const job = typeof id === 'string' ? jobs.get(id) : undefined
197
+ if (!job) return false
198
+ job.cancelled = true
199
+ clearTimer(job)
200
+ jobs.delete(job.id)
201
+ return true
202
+ },
203
+
204
+ /** Number of retained jobs, for tests/diagnostics. */
205
+ get size() {
206
+ return jobs.size
207
+ },
208
+
209
+ dispose() {
210
+ for (const job of jobs.values()) {
211
+ job.cancelled = true
212
+ clearTimer(job)
213
+ }
214
+ jobs.clear()
215
+ },
216
+ }
217
+ }