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,225 +0,0 @@
1
- /**
2
- * Atomic JSON persistence: 0700 dir, 0600 file, fsynced temp, rename retry and a cross-process lock; a bad file is reported, never thrown.
3
- */
4
- import { promises as fs } from 'node:fs'
5
- import { existsSync } from 'node:fs'
6
- import { randomUUID } from 'node:crypto'
7
- import path from 'node:path'
8
- import { sleep } from './util.js'
9
-
10
- const RENAME_RETRY_ATTEMPTS = 5
11
- const RENAME_RETRY_BASE_MS = 20
12
- const LOCK_STALE_MS = 10_000
13
- const LOCK_WAIT_MS = 20_000
14
- const LOCK_RETRY_MS = 10
15
- /**
16
- * How long a non-`EEXIST` lock error counts as contention without the lock present.
17
- * Windows reports mid-create/mid-delete races as EPERM/EACCES, but those codes also
18
- * mean a lock that can never be created (ACL denial, read-only mount); past this
19
- * window the original error is surfaced instead of a misleading timeout.
20
- */
21
- const LOCK_TRANSIENT_MS = 250
22
- const LOCK_UNLINK_ATTEMPTS = 3
23
-
24
- /**
25
- * In-process chains keyed by lock path; the value is the always-settled tail so a
26
- * rejected write never poisons the next waiter.
27
- */
28
- const LOCAL_CHAINS = new Map()
29
-
30
- /**
31
- * Run `task` under the cross-process lock, serialized with every in-process holder
32
- * of the same lock path.
33
- */
34
- export function withProcessLock(lockFile, options, task) {
35
- const previous = LOCAL_CHAINS.get(lockFile) ?? Promise.resolve()
36
- const run = previous.then(
37
- () => runExclusive(lockFile, options ?? {}, task),
38
- () => runExclusive(lockFile, options ?? {}, task),
39
- )
40
- LOCAL_CHAINS.set(
41
- lockFile,
42
- run.catch(() => undefined),
43
- )
44
- return run
45
- }
46
-
47
- async function runExclusive(lockFile, options, task) {
48
- const release = await acquireLock(lockFile, options)
49
- try {
50
- return await task()
51
- } finally {
52
- await release()
53
- }
54
- }
55
-
56
- async function acquireLock(lockFile, options) {
57
- const fsImpl = options.fs ?? fs
58
- const staleMs = options.staleMs ?? LOCK_STALE_MS
59
- const waitMs = options.waitMs ?? LOCK_WAIT_MS
60
- const retryMs = options.retryMs ?? LOCK_RETRY_MS
61
- const started = Date.now()
62
- // Only a lock we never once observed can be a permanent permission error: under
63
- // real contention the lock is created and unlinked constantly.
64
- let sawLock = false
65
- while (true) {
66
- try {
67
- const handle = await fsImpl.open(lockFile, 'wx', 0o600)
68
- return async () => {
69
- try {
70
- await handle.close()
71
- } catch {}
72
- // A leaked lock costs the next writer a full stale wait, so retry the unlink
73
- // (Windows can hold it briefly after close).
74
- for (let attempt = 0; attempt < LOCK_UNLINK_ATTEMPTS; attempt += 1) {
75
- try {
76
- await fsImpl.unlink(lockFile)
77
- return
78
- } catch (unlinkError) {
79
- const unlinkCode = /** @type {any} */ (unlinkError)?.code
80
- if (unlinkCode === 'ENOENT') return
81
- if (attempt === LOCK_UNLINK_ATTEMPTS - 1) return
82
- await sleep(retryMs)
83
- }
84
- }
85
- }
86
- } catch (error) {
87
- // Windows reports contention on an exclusive create as EPERM/EACCES/EBUSY
88
- // rather than EEXIST when the other process is mid-create or mid-delete.
89
- const code = /** @type {any} */ (error)?.code
90
- if (code !== 'EEXIST' && code !== 'EPERM' && code !== 'EACCES' && code !== 'EBUSY') throw error
91
- if (code !== 'EEXIST' && !sawLock && Date.now() - started > LOCK_TRANSIENT_MS) {
92
- if (!(await lockExists(fsImpl, lockFile))) throw error
93
- }
94
- if (code === 'EEXIST' || (await lockExists(fsImpl, lockFile))) sawLock = true
95
- await breakStaleLock(fsImpl, lockFile, staleMs)
96
- if (Date.now() - started > waitMs) {
97
- const timeout = new Error('timed out waiting for another process to release the store lock')
98
- timeout.code = 'ELOCKTIMEOUT'
99
- throw timeout
100
- }
101
- await sleep(retryMs)
102
- }
103
- }
104
- }
105
-
106
- async function breakStaleLock(fsImpl, lockFile, staleMs) {
107
- try {
108
- const info = await fsImpl.stat(lockFile)
109
- if (Date.now() - info.mtimeMs > staleMs) await removeQuietly(fsImpl, lockFile)
110
- } catch {
111
- /* the lock disappeared or cannot be inspected: retry the create */
112
- }
113
- }
114
-
115
- export async function writeJsonAtomic(file, value, options = {}) {
116
- const fsImpl = options.fs ?? fs
117
- const logger = options.logger ?? console
118
- const dir = options.dir ?? path.dirname(file)
119
- const dirMode = options.dirMode ?? 0o700
120
- const fileMode = options.fileMode ?? 0o600
121
- try {
122
- await fsImpl.mkdir(dir, { recursive: true, mode: dirMode })
123
- } catch (error) {
124
- logger.warn?.(`[dsh-remote-go] cannot create ${dir}:`, error)
125
- }
126
- const tmp = `${file}.${randomUUID()}.tmp`
127
- const text = `${JSON.stringify(value, null, 2)}\n`
128
- let handle = null
129
- try {
130
- handle = await fsImpl.open(tmp, 'wx', fileMode)
131
- await handle.writeFile(text, 'utf8')
132
- await handle.sync()
133
- await handle.close()
134
- handle = null
135
- } catch (error) {
136
- if (handle) {
137
- try {
138
- await handle.close()
139
- } catch {}
140
- }
141
- await removeQuietly(fsImpl, tmp)
142
- throw error
143
- }
144
- await renameWithRetry(fsImpl, tmp, file)
145
- await syncDir(fsImpl, dir)
146
- }
147
-
148
- async function renameWithRetry(fsImpl, tmp, file) {
149
- for (let attempt = 1; attempt <= RENAME_RETRY_ATTEMPTS; attempt += 1) {
150
- try {
151
- await fsImpl.rename(tmp, file)
152
- return
153
- } catch (error) {
154
- const code = /** @type {any} */ (error)?.code
155
- const retryable = code === 'EPERM' || code === 'EBUSY' || code === 'EACCES'
156
- if (retryable && attempt < RENAME_RETRY_ATTEMPTS) {
157
- await sleep(RENAME_RETRY_BASE_MS * attempt)
158
- continue
159
- }
160
- await removeQuietly(fsImpl, tmp)
161
- throw error
162
- }
163
- }
164
- }
165
-
166
- async function syncDir(fsImpl, dir) {
167
- let handle = null
168
- try {
169
- handle = await fsImpl.open(dir, 'r')
170
- await handle.sync()
171
- } catch {
172
- /* not supported on this platform/filesystem */
173
- } finally {
174
- if (handle) {
175
- try {
176
- await handle.close()
177
- } catch {}
178
- }
179
- }
180
- }
181
-
182
- /**
183
- * Read one JSON state file.
184
- *
185
- * The three outcomes are deliberately distinct: `missing` (never written), `corrupt` (the bytes
186
- * are not JSON — the caller may quarantine them and recover) and `unreadable` (the file exists
187
- * but could not be read: EACCES/EPERM/EISDIR/IO). A merely unreadable file must not be renamed
188
- * away: that would turn a transient permission problem into a lost host list.
189
- * @param {string} file
190
- * @param {{ fs?: object, logger?: object }} [options]
191
- * @returns {Promise<{ status: 'ok', value: any } | { status: 'missing'|'corrupt'|'unreadable', value: null }>}
192
- */
193
- export async function readJsonFile(file, options = {}) {
194
- const fsImpl = options.fs ?? fs
195
- const logger = options.logger ?? console
196
- let text
197
- try {
198
- if (!existsSync(file)) return { status: 'missing', value: null }
199
- text = await fsImpl.readFile(file, 'utf8')
200
- } catch (error) {
201
- logger.warn?.(`[dsh-remote-go] cannot read ${path.basename(file)}:`, error)
202
- return { status: 'unreadable', value: null }
203
- }
204
- try {
205
- return { status: 'ok', value: JSON.parse(text) }
206
- } catch (error) {
207
- logger.warn?.(`[dsh-remote-go] ${path.basename(file)} is not valid JSON:`, error)
208
- return { status: 'corrupt', value: null }
209
- }
210
- }
211
-
212
- async function removeQuietly(fsImpl, target) {
213
- try {
214
- await fsImpl.unlink(target)
215
- } catch {}
216
- }
217
-
218
- async function lockExists(fsImpl, lockFile) {
219
- try {
220
- await fsImpl.stat(lockFile)
221
- return true
222
- } catch {
223
- return false
224
- }
225
- }
package/src/bootstrap.js DELETED
@@ -1,113 +0,0 @@
1
- /**
2
- * Remote runtime preparation: `npx` pinned to the local DSH version against the remote's real `$DSH_HOME`; the executor runs only fixed templates.
3
- */
4
- import { errors } from './errors.js'
5
- import { headTail, shellQuote } from './util.js'
6
- import { isNodeVersionSupported, normalizeVersion, parseVersion, versionsEqual } from './version.js'
7
-
8
- export function assertSupportedRemote(facts) {
9
- if (facts.os !== 'Linux') {
10
- throw errors.unsupportedOs(`${facts.os} ${facts.arch}`.trim())
11
- }
12
- }
13
-
14
- export function planNpx(input) {
15
- const targetVersion = normalizeVersion(input.targetVersion)
16
- if (!parseVersion(targetVersion)) {
17
- throw errors.invalidInput('targetVersion', {
18
- zh: `目标版本「${input.targetVersion}」不是合法版本号。`,
19
- en: `Target version "${input.targetVersion}" is not a valid version.`,
20
- })
21
- }
22
- assertSupportedRemote(input.facts)
23
- if (!isNodeVersionSupported(input.facts.nodeVersion)) {
24
- throw errors.remoteDshMissing({
25
- zh: `远端 Node 不可用或版本过低(需要 ≥ 24.9.0,检测到 ${input.facts.nodeVersion ?? '无'}),自动准备也没有完成。请检查远端网络,或在远端安装 Node 后重试。`,
26
- en: `The remote Node is missing or too old (>= 24.9.0 required, detected ${input.facts.nodeVersion ?? 'none'}) and automatic preparation did not finish. Check the remote network, or install Node on the remote and retry.`,
27
- })
28
- }
29
- if (!input.facts.npxPath) {
30
- throw errors.remoteDshMissing({
31
- zh: '远端没有找到 npx。请安装 npm(随 Node 一起提供),或把 npm 的 bin 目录加入远程 shell 的 PATH。',
32
- en: 'npx was not found on the remote. Install npm (shipped with Node) or add its bin directory to the remote shell PATH.',
33
- })
34
- }
35
- if (!input.facts.curlPath && !input.facts.wgetPath) {
36
- throw errors.remoteDshMissing({
37
- zh: '远端既没有 curl 也没有 wget,无法在启动后探活远端界面。请安装其中之一。',
38
- en: 'The remote has neither curl nor wget, so the remote UI cannot be health-checked after start. Install one of them.',
39
- })
40
- }
41
- const nodeBinDir = input.facts.nodePath ? input.facts.nodePath.replace(/\/node$/, '') : undefined
42
- return {
43
- level: 'npx',
44
- profile: input.profile,
45
- targetVersion,
46
- reason: {
47
- zh: `用 npx 精确版本 ${targetVersion} 启动远端 DSH(Node 运行时由插件准备)`,
48
- en: `Launch the remote DSH with npx pinned to ${targetVersion} (Node runtime prepared by the plugin)`,
49
- },
50
- start: {
51
- kind: 'npx',
52
- npxPath: input.facts.npxPath,
53
- nodePath: input.facts.nodePath ?? undefined,
54
- nodeBinDir,
55
- targetVersion,
56
- },
57
- }
58
- }
59
-
60
- /**
61
- * The npx preflight: resolve and run the exact package once, so a first-run
62
- * download happens in the foreground (and fails with a readable error) instead
63
- * of inside the detached start script.
64
- *
65
- * `npm_config_loglevel=http` is deliberate: over an SSH channel npm has no TTY and
66
- * would otherwise print nothing until it finishes. At `http` it reports fetches
67
- * on stderr, which the caller turns into progress.
68
- */
69
- export function buildPreflightCommand(plan) {
70
- const pathPrefix = plan.start.nodeBinDir ? `PATH=${shellQuote(plan.start.nodeBinDir)}:"$PATH" ` : ''
71
- return `set -eu
72
- ${pathPrefix}npm_config_loglevel=http ${shellQuote(plan.start.npxPath)} -y @deepseek-ai/dsh@${normalizeVersion(plan.start.targetVersion)} --version`
73
- }
74
-
75
- export async function verifyNpxVersion(ssh, plan, options = {}) {
76
- const timeoutMs = options.timeoutMs ?? 0
77
- const result = await ssh.exec(buildPreflightCommand(plan), {
78
- timeoutMs,
79
- maxBytes: options.maxBytes ?? 4 * 1024 * 1024,
80
- onStdout: options.onStdout,
81
- onStderr: options.onStderr,
82
- })
83
- // `timeoutMs: 0` means "no timeout" (a cold npx download is unbounded by design); only a
84
- // caller-supplied deadline can time out, and that is a network condition, not a missing
85
- // remote runtime (L).
86
- if (result.timedOut === true) {
87
- throw errors.network(
88
- {
89
- zh: `远端 npx 预检超过 ${Math.round(timeoutMs / 1000)} 秒没有完成,可能是下载很慢或远端负载过高。`,
90
- en: `The remote npx preflight did not finish within ${Math.round(timeoutMs / 1000)}s; the download may be slow or the remote overloaded.`,
91
- },
92
- { technical: `reason=preflight-timeout timeoutMs=${timeoutMs}` },
93
- )
94
- }
95
- const combined = `${result.stdout}\n${result.stderr}`
96
- if (result.code !== 0) {
97
- const failure = errors.remoteDshMissing({
98
- zh: `无法通过 npx 运行 @deepseek-ai/dsh@${plan.start.targetVersion}(退出码 ${result.code})。请确认远端能访问 npm registry,且 Node/npm 版本满足要求。`,
99
- en: `Could not run @deepseek-ai/dsh@${plan.start.targetVersion} through npx (exit ${result.code}). Make sure the remote can reach the npm registry and Node/npm meet the requirements.`,
100
- })
101
- failure.technical = headTail(combined, 1500)
102
- throw failure
103
- }
104
- const lines = String(result.stdout ?? '')
105
- .split(/\r?\n/)
106
- .map((line) => line.trim())
107
- .filter(Boolean)
108
- const reported = normalizeVersion(lines[lines.length - 1] ?? '')
109
- if (!versionsEqual(reported, plan.targetVersion)) {
110
- throw errors.versionMismatch(plan.targetVersion, reported || 'unknown')
111
- }
112
- return reported
113
- }
@@ -1,176 +0,0 @@
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
- */
4
- import { redactText } from './redact.js'
5
- import { headTail } from './util.js'
6
-
7
- export const CONNECT_LOG_STATUSES = Object.freeze(['connecting', 'fingerprint-pending', 'error'])
8
-
9
- export const LOG_RING_LIMIT = 200
10
-
11
- export const LOG_TAIL_LIMIT = 120
12
-
13
- /** How much of one technical detail (redacted) the log prints before `headTail` elides it. */
14
- export const LOG_TECHNICAL_LIMIT = 1200
15
-
16
- /** How long a single remote-log / technical line may get before it is elided. */
17
- export const LOG_LINE_LIMIT = 400
18
-
19
- /** Cap on the remote-log lines a failed start prints, so a chatty tail cannot eat the ring. */
20
- export const LOG_TAIL_LINES = 60
21
-
22
- export function connectLogVisible(status) {
23
- return typeof status === 'string' && CONNECT_LOG_STATUSES.includes(status)
24
- }
25
-
26
- /** A bilingual line: zh and en side by side, the shape the Client already resolves. */
27
- function pair(zh, en) {
28
- return { zh, en }
29
- }
30
-
31
- /** Accept only a complete { zh, en } pair; a half-resolved object would render as an empty line. */
32
- function normalizeText(value) {
33
- if (!value || typeof value !== 'object') return null
34
- const zh = typeof value.zh === 'string' ? value.zh : ''
35
- const en = typeof value.en === 'string' ? value.en : ''
36
- if (zh === '' || en === '') return null
37
- return pair(zh, en)
38
- }
39
-
40
- export function appendConnectLog(runtime, input) {
41
- const raw = typeof input.message === 'string' ? input.message : String(input.message ?? '')
42
- // The remote's own stdout arrives here (`remote-web.js` hands every start line to `onLine`, and
43
- // the first one is the launch URL with its session token). This ring is the second exit of that
44
- // text — `HostView.logs`, the SSE state frames and the diagnostics export all read it — so it
45
- // is redacted at write time, not only when the failure view is built.
46
- const message = headTail(redactText(raw), LOG_TECHNICAL_LIMIT)
47
- const entry = {
48
- seq: (typeof runtime.logSeq === 'number' ? runtime.logSeq : 0) + 1,
49
- at: typeof input.at === 'string' ? input.at : '',
50
- level: typeof input.level === 'string' ? input.level : 'info',
51
- phase: typeof input.phase === 'string' && input.phase !== '' ? input.phase : null,
52
- message,
53
- line: `[dsh-remote-go:${runtime.id}] ${message}`,
54
- }
55
- const text = normalizeText(input.text)
56
- if (text !== null) entry.text = text
57
- if (input.boundary === true) entry.boundary = true
58
- if (!Array.isArray(runtime.logs)) runtime.logs = []
59
- if (runtime.logs.length >= LOG_RING_LIMIT) runtime.logs.shift()
60
- runtime.logSeq = entry.seq
61
- runtime.logs.push(entry)
62
- return entry
63
- }
64
-
65
- /** Forget the previous connection's lines; the sequence restarts with this connection. */
66
- export function resetConnectLog(runtime) {
67
- runtime.logs = []
68
- runtime.logSeq = 0
69
- return runtime
70
- }
71
-
72
- /** `YYYY-MM-DD HH:MM:SS` in the Host's own timezone — the clock the user reads. */
73
- function localClock(date) {
74
- const pad = (value) => String(value).padStart(2, '0')
75
- return (
76
- `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` +
77
- `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
78
- )
79
- }
80
-
81
- /**
82
- * Start one connection's log: drop the previous attempt and write its boundary line, so the
83
- * panel opens on this attempt only and a copied log says which attempt it belongs to.
84
- */
85
- export function beginConnectLog(runtime, options = {}) {
86
- const at = typeof options.at === 'string' && options.at !== '' ? options.at : new Date().toISOString()
87
- const when = new Date(at)
88
- const attempt = (typeof runtime.connectCount === 'number' ? runtime.connectCount : 0) + 1
89
- runtime.connectCount = attempt
90
- resetConnectLog(runtime)
91
- const clock = Number.isNaN(when.getTime()) ? at : localClock(when)
92
- const text = pair(`— 第 ${attempt} 次连接 · ${clock} —`, `— Connection ${attempt} · ${clock} —`)
93
- return appendConnectLog(runtime, { at, level: 'info', message: text.en, text, boundary: true })
94
- }
95
-
96
- /** `{ zh, en }` from any bilingual value, filling a missing side from the other. */
97
- function say(value) {
98
- if (typeof value === 'string') return value === '' ? null : pair(value, value)
99
- if (!value || typeof value !== 'object') return null
100
- const zh = typeof value.zh === 'string' ? value.zh : ''
101
- const en = typeof value.en === 'string' ? value.en : ''
102
- if (zh === '' && en === '') return null
103
- return { zh: zh === '' ? en : zh, en: en === '' ? zh : en }
104
- }
105
-
106
- /**
107
- * Turn an `ErrorView` into the lines the connect log prints for a failed connection:
108
- * the failed phase and code, the localized reason, every hint, then the redacted and
109
- * head-tail-truncated technical detail — the remote log tail line by line for a failed start.
110
- *
111
- * `options.label` replaces the first line for a one-shot action that is not a connect (the
112
- * explicit remote stop), so its failure is not announced as a connection failure.
113
- *
114
- * @param {{ code?: string, title?: unknown, detail?: unknown, nextSteps?: unknown[], technical?: string } | null} view
115
- * @param {{ phase?: string | null, label?: { zh: string, en: string } | null }} [options] -
116
- * the phase the pipeline was in when it failed, and the first line's wording.
117
- * @returns {{ level: string, phase: string | null, message: string, text?: { zh: string, en: string } }[]}
118
- */
119
- export function connectFailureLines(view, options = {}) {
120
- const code = typeof view?.code === 'string' && view.code !== '' ? view.code : 'internal'
121
- const phase = typeof options.phase === 'string' && options.phase !== '' ? options.phase : null
122
- const lines = []
123
- const push = (text) => lines.push({ level: 'error', phase, message: text.en, text })
124
- const raw = (message) => lines.push({ level: 'error', phase, message })
125
-
126
- const label = normalizeText(options.label)
127
- push(
128
- label ??
129
- (phase === null
130
- ? pair(`连接失败:${code}`, `Connect failed: ${code}`)
131
- : pair(`连接失败于 ${phase} 阶段:${code}`, `Connect failed in phase ${phase}: ${code}`)),
132
- )
133
-
134
- // The card explains the failure in one sentence; the log has to carry that sentence.
135
- const reason = say(view?.detail) ?? say(view?.title)
136
- if (reason !== null) push(pair(`原因:${reason.zh}`, `Reason: ${reason.en}`))
137
-
138
- const hints = Array.isArray(view?.nextSteps) ? view.nextSteps : []
139
- for (const hint of hints) {
140
- const step = say(hint)
141
- if (step !== null) push(pair(`建议:${step.zh}`, `Next: ${step.en}`))
142
- }
143
-
144
- const technical = typeof view?.technical === 'string' ? view.technical : ''
145
- if (technical.trim() !== '') {
146
- const tail = code === 'remote-dsh-start-failed'
147
- push(tail ? pair('远端日志尾部:', 'Remote log tail:') : pair('技术细节:', 'Details:'))
148
- // Redaction is the contract of anything copied out of the log; `headTail` keeps both the
149
- // start of the message (what failed) and its end (the error itself) when it is too long.
150
- let printed = 0
151
- for (const line of headTail(redactText(technical), LOG_TECHNICAL_LIMIT).split(/\r?\n/)) {
152
- if (printed >= LOG_TAIL_LINES) break
153
- if (line.trim() === '') continue
154
- raw(headTail(line, LOG_LINE_LIMIT))
155
- printed += 1
156
- }
157
- }
158
- return lines
159
- }
160
-
161
- export function connectLogTail(runtime) {
162
- const entries = runtime && Array.isArray(runtime.logs) ? runtime.logs : []
163
- return entries.slice(-LOG_TAIL_LIMIT).map((entry) => {
164
- const item = {
165
- seq: typeof entry.seq === 'number' ? entry.seq : 0,
166
- at: typeof entry.at === 'string' ? entry.at : '',
167
- level: typeof entry.level === 'string' ? entry.level : 'info',
168
- phase: typeof entry.phase === 'string' && entry.phase !== '' ? entry.phase : null,
169
- message: typeof entry.message === 'string' ? entry.message : String(entry.line ?? ''),
170
- }
171
- const text = normalizeText(entry.text)
172
- if (text !== null) item.text = text
173
- if (entry.boundary === true) item.boundary = true
174
- return item
175
- })
176
- }