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.
- package/README.md +126 -7
- package/client.js +5972 -0
- package/cordis.patch.yml +3 -0
- package/index.js +4 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +76 -3
- package/src/api.js +340 -0
- package/src/atomic-json.js +208 -0
- package/src/bootstrap.js +100 -0
- package/src/connect-log.js +39 -0
- package/src/connect-pipeline.js +463 -0
- package/src/connect-progress.js +135 -0
- package/src/constants.js +31 -0
- package/src/diagnostics.js +157 -0
- package/src/download-jobs.js +217 -0
- package/src/errors.js +316 -0
- package/src/host-lifecycle.js +187 -0
- package/src/host-registry.js +145 -0
- package/src/host-runtime.js +53 -0
- package/src/host-view.js +51 -0
- package/src/index.js +162 -0
- package/src/key-files.js +49 -0
- package/src/known-hosts.js +94 -0
- package/src/layout.js +35 -0
- package/src/local-download.js +162 -0
- package/src/local-ssh.js +27 -0
- package/src/local-version.js +88 -0
- package/src/node-runtime.js +521 -0
- package/src/probe.js +89 -0
- package/src/prompts.js +132 -0
- package/src/redact.js +54 -0
- package/src/remote-files.js +71 -0
- package/src/remote-path.js +73 -0
- package/src/remote-proc.js +208 -0
- package/src/remote-web.js +300 -0
- package/src/secrets.js +79 -0
- package/src/service.js +250 -0
- package/src/settings.js +135 -0
- package/src/ssh-config.js +271 -0
- package/src/ssh.js +652 -0
- package/src/store.js +143 -0
- package/src/tunnel.js +73 -0
- package/src/util.js +153 -0
- package/src/version.js +103 -0
- package/src/webapp.js +28 -0
- package/vendor/THIRD_PARTY_NOTICES.md +10 -0
- package/vendor/ssh2-entry.mjs +12 -0
- package/vendor/ssh2.bundle.cjs +25 -0
package/src/bootstrap.js
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
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 result = await ssh.exec(buildPreflightCommand(plan), {
|
|
77
|
+
timeoutMs: options.timeoutMs ?? 0,
|
|
78
|
+
maxBytes: options.maxBytes ?? 4 * 1024 * 1024,
|
|
79
|
+
onStdout: options.onStdout,
|
|
80
|
+
onStderr: options.onStderr,
|
|
81
|
+
})
|
|
82
|
+
const combined = `${result.stdout}\n${result.stderr}`
|
|
83
|
+
if (result.code !== 0) {
|
|
84
|
+
const failure = errors.remoteDshMissing({
|
|
85
|
+
zh: `无法通过 npx 运行 @deepseek-ai/dsh@${plan.start.targetVersion}(退出码 ${result.code})。请确认远端能访问 npm registry,且 Node/npm 版本满足要求。`,
|
|
86
|
+
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.`,
|
|
87
|
+
})
|
|
88
|
+
failure.technical = headTail(combined, 1500)
|
|
89
|
+
throw failure
|
|
90
|
+
}
|
|
91
|
+
const lines = String(result.stdout ?? '')
|
|
92
|
+
.split(/\r?\n/)
|
|
93
|
+
.map((line) => line.trim())
|
|
94
|
+
.filter(Boolean)
|
|
95
|
+
const reported = normalizeVersion(lines[lines.length - 1] ?? '')
|
|
96
|
+
if (!versionsEqual(reported, plan.targetVersion)) {
|
|
97
|
+
throw errors.versionMismatch(plan.targetVersion, reported || 'unknown')
|
|
98
|
+
}
|
|
99
|
+
return reported
|
|
100
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The connect log behind `HostView.logs`: the per-host ring, its bounded `/state` tail and which statuses print it; lines travel as written, unredacted.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
export const CONNECT_LOG_STATUSES = Object.freeze(['connecting', 'fingerprint-pending', 'error'])
|
|
6
|
+
|
|
7
|
+
export const LOG_RING_LIMIT = 200
|
|
8
|
+
|
|
9
|
+
export const LOG_TAIL_LIMIT = 120
|
|
10
|
+
|
|
11
|
+
export function connectLogVisible(status) {
|
|
12
|
+
return typeof status === 'string' && CONNECT_LOG_STATUSES.includes(status)
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function appendConnectLog(runtime, input) {
|
|
16
|
+
const message = typeof input.message === 'string' ? input.message : String(input.message ?? '')
|
|
17
|
+
const entry = {
|
|
18
|
+
seq: (typeof runtime.logSeq === 'number' ? runtime.logSeq : 0) + 1,
|
|
19
|
+
at: typeof input.at === 'string' ? input.at : '',
|
|
20
|
+
level: typeof input.level === 'string' ? input.level : 'info',
|
|
21
|
+
message,
|
|
22
|
+
line: `[dsh-remote-go:${runtime.id}] ${message}`,
|
|
23
|
+
}
|
|
24
|
+
if (!Array.isArray(runtime.logs)) runtime.logs = []
|
|
25
|
+
if (runtime.logs.length >= LOG_RING_LIMIT) runtime.logs.shift()
|
|
26
|
+
runtime.logSeq = entry.seq
|
|
27
|
+
runtime.logs.push(entry)
|
|
28
|
+
return entry
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function connectLogTail(runtime) {
|
|
32
|
+
const entries = runtime && Array.isArray(runtime.logs) ? runtime.logs : []
|
|
33
|
+
return entries.slice(-LOG_TAIL_LIMIT).map((entry) => ({
|
|
34
|
+
seq: typeof entry.seq === 'number' ? entry.seq : 0,
|
|
35
|
+
at: typeof entry.at === 'string' ? entry.at : '',
|
|
36
|
+
level: typeof entry.level === 'string' ? entry.level : 'info',
|
|
37
|
+
message: typeof entry.message === 'string' ? entry.message : String(entry.line ?? ''),
|
|
38
|
+
}))
|
|
39
|
+
}
|
|
@@ -0,0 +1,463 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The connect pipeline: SSH -> probe -> managed Node -> plan -> adopt/conflict -> preflight -> start -> tunnel -> verify; the step order is the behavior and every step is injected.
|
|
3
|
+
*/
|
|
4
|
+
import { REMOTE_START_TIMEOUT_MS, SSH_READY_TIMEOUT_MS, TUNNEL_PROBE_TIMEOUT_MS } from './constants.js'
|
|
5
|
+
import { errors, toErrorView } from './errors.js'
|
|
6
|
+
import { runtimeOf } from './host-registry.js'
|
|
7
|
+
import {
|
|
8
|
+
cancelIdleStop,
|
|
9
|
+
cancelReconnect,
|
|
10
|
+
closeTunnel,
|
|
11
|
+
disconnectHost,
|
|
12
|
+
disposeSsh,
|
|
13
|
+
scheduleReconnect,
|
|
14
|
+
teardownRuntime,
|
|
15
|
+
} from './host-lifecycle.js'
|
|
16
|
+
import { findKnownHostEntries, parseKnownHosts } from './known-hosts.js'
|
|
17
|
+
import { remoteLayout } from './layout.js'
|
|
18
|
+
import { applyManagedNodeFacts, managedNodeVersionFromEngine } from './node-runtime.js'
|
|
19
|
+
import { askConflict, requestHostKey } from './prompts.js'
|
|
20
|
+
import { resolveDestination } from './ssh-config.js'
|
|
21
|
+
import { isPid, messageOf, nowIso } from './util.js'
|
|
22
|
+
import { normalizeVersion, versionsEqual } from './version.js'
|
|
23
|
+
|
|
24
|
+
function describeTarget(entry) {
|
|
25
|
+
const user = entry.username ? `${entry.username}@` : ''
|
|
26
|
+
const port = entry.port && entry.port !== 22 ? `:${entry.port}` : ''
|
|
27
|
+
return `${user}${entry.address || '?'}${port}`
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Accept a connect request: apply the one-time inputs, stop any pending retry,
|
|
32
|
+
* and start the pipeline in the background. Progress travels on `state`.
|
|
33
|
+
*/
|
|
34
|
+
export async function startConnect(ctx, id, options = {}) {
|
|
35
|
+
await ctx.init()
|
|
36
|
+
const runtime = runtimeOf(ctx, id)
|
|
37
|
+
if (runtime.connectPromise) return { accepted: false, reason: 'already-connecting' }
|
|
38
|
+
if (runtime.status === 'connected' && runtime.ssh?.connected) return { accepted: false, reason: 'already-connected' }
|
|
39
|
+
runtime.password = options.password ?? runtime.password
|
|
40
|
+
// A password the user asked to remember is written to the credential store the
|
|
41
|
+
// moment it is known, so a failed first attempt still leaves it available.
|
|
42
|
+
if (options.rememberPassword === true && typeof runtime.password === 'string' && runtime.password !== '') {
|
|
43
|
+
runtime.savePassword = true
|
|
44
|
+
}
|
|
45
|
+
runtime.desired = 'connected'
|
|
46
|
+
cancelReconnect(runtime)
|
|
47
|
+
ctx.progress.log(
|
|
48
|
+
runtime,
|
|
49
|
+
'info',
|
|
50
|
+
`connect: ${describeTarget(runtime.entry)} (auth=${runtime.entry.auth?.type ?? 'key'}${
|
|
51
|
+
runtime.entry.jumpHost ? `, jump=${runtime.entry.jumpHost}` : ''
|
|
52
|
+
})`,
|
|
53
|
+
)
|
|
54
|
+
runtime.connectPromise = connectPipeline(ctx, runtime).finally(() => {
|
|
55
|
+
runtime.connectPromise = null
|
|
56
|
+
})
|
|
57
|
+
return { accepted: true }
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Drop the current link and connect again from scratch (the "Reconnect" button). */
|
|
61
|
+
export async function reconnectHost(ctx, runtime) {
|
|
62
|
+
await disconnectHost(ctx, runtime, { stopRemote: false })
|
|
63
|
+
cancelIdleStop(runtime)
|
|
64
|
+
await disposeSsh(runtime)
|
|
65
|
+
return startConnect(ctx, runtime.id, {})
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Re-enter the pipeline after a dropped link. Lives here rather than in the
|
|
70
|
+
* lifecycle module so `scheduleReconnect` stays a pure timer with a callback.
|
|
71
|
+
*/
|
|
72
|
+
async function reconnectNow(ctx, runtime) {
|
|
73
|
+
if (ctx.state.disposed || runtime.desired !== 'connected') return
|
|
74
|
+
await disposeSsh(runtime)
|
|
75
|
+
runtime.connectPromise = connectPipeline(ctx, runtime).finally(() => {
|
|
76
|
+
runtime.connectPromise = null
|
|
77
|
+
})
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function attachDisconnectHandler(ctx, runtime) {
|
|
81
|
+
const ssh = runtime.ssh
|
|
82
|
+
if (!ssh) return
|
|
83
|
+
ssh.on('close', () => {
|
|
84
|
+
if (runtime.closing || runtime.desired !== 'connected' || runtime.status !== 'connected') return
|
|
85
|
+
runtime.status = 'disconnected'
|
|
86
|
+
runtime.phase = null
|
|
87
|
+
runtime.remote.uiReady = false
|
|
88
|
+
runtime.remote.localPort = null
|
|
89
|
+
runtime.progress = { code: 'reconnecting', params: { attempt: runtime.reconnectAttempts + 1 } }
|
|
90
|
+
ctx.emitState()
|
|
91
|
+
void closeTunnel(runtime)
|
|
92
|
+
scheduleReconnect(ctx, runtime, () => void reconnectNow(ctx, runtime))
|
|
93
|
+
})
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Resolve the SSH destination from the entry + local ssh config, before dialling. */
|
|
97
|
+
async function resolveTargetForRuntime(ctx, runtime) {
|
|
98
|
+
const material = await ctx.deps.loadSshMaterial({ home: ctx.userHome() })
|
|
99
|
+
const entry = runtime.entry
|
|
100
|
+
const resolved = resolveDestination(entry.address, { configText: material.configText, home: ctx.userHome() })
|
|
101
|
+
const host = resolved.host || entry.address
|
|
102
|
+
const port = entry.port && entry.port !== 22 ? entry.port : (resolved.port ?? 22)
|
|
103
|
+
const knownFingerprints = findKnownHostEntries(parseKnownHosts(material.knownHostsText), host, port).map(
|
|
104
|
+
(item) => item.fingerprint,
|
|
105
|
+
)
|
|
106
|
+
return {
|
|
107
|
+
host,
|
|
108
|
+
port,
|
|
109
|
+
username: entry.username || resolved.user || null,
|
|
110
|
+
identityFiles: resolved.identityFiles ?? [],
|
|
111
|
+
knownFingerprints,
|
|
112
|
+
jumpHost: entry.jumpHost
|
|
113
|
+
? resolveDestination(entry.jumpHost, { configText: material.configText, home: ctx.userHome() })
|
|
114
|
+
: null,
|
|
115
|
+
entry,
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Open the transport: direct, or through a jump host with a forwarded stream. */
|
|
120
|
+
async function openTransport(ctx, runtime, target) {
|
|
121
|
+
const settings = ctx.settings()
|
|
122
|
+
const buildOptions = (resolved, sock) => ({
|
|
123
|
+
host: resolved.host,
|
|
124
|
+
port: resolved.port ?? 22,
|
|
125
|
+
username: resolved.username ?? resolved.user ?? null,
|
|
126
|
+
// The key path expands against the *user* home (`~/.ssh/...`), never against
|
|
127
|
+
// DSH_HOME, so the SSH layer needs to know which one that is.
|
|
128
|
+
home: ctx.userHome(),
|
|
129
|
+
auth: {
|
|
130
|
+
type: runtime.entry.auth?.type ?? 'key',
|
|
131
|
+
keyPath: runtime.entry.auth?.keyPath ?? null,
|
|
132
|
+
password: runtime.password ?? null,
|
|
133
|
+
},
|
|
134
|
+
identityFiles: resolved.identityFiles ?? [],
|
|
135
|
+
hostKeyPolicy: runtime.entry.hostKeyPolicy ?? settings.hostKeyPolicy,
|
|
136
|
+
pinnedFingerprint: runtime.entry.pinnedFingerprint ?? null,
|
|
137
|
+
knownHostFingerprints: resolved.knownFingerprints ?? [],
|
|
138
|
+
acceptUnknownHostKey: false,
|
|
139
|
+
readyTimeoutMs: settings.connectTimeoutSec * 1000 || SSH_READY_TIMEOUT_MS,
|
|
140
|
+
...(sock ? { sock } : {}),
|
|
141
|
+
onHostKey: (info) => requestHostKey(ctx, runtime, info),
|
|
142
|
+
})
|
|
143
|
+
if (!target.jumpHost) {
|
|
144
|
+
runtime.ssh = ctx.deps.sshFactory(buildOptions(target))
|
|
145
|
+
ctx.progress.phase(runtime, 'ssh', 'ssh-connecting', { host: target.host })
|
|
146
|
+
captureFingerprint(ctx, runtime, await runtime.ssh.connect())
|
|
147
|
+
return
|
|
148
|
+
}
|
|
149
|
+
ctx.progress.phase(runtime, 'ssh', 'ssh-connecting', { host: target.jumpHost.host, jump: true })
|
|
150
|
+
const jumpTarget = {
|
|
151
|
+
...target.jumpHost,
|
|
152
|
+
username: target.jumpHost.user ?? target.username,
|
|
153
|
+
knownFingerprints: findKnownHostEntries(
|
|
154
|
+
parseKnownHosts((await ctx.deps.loadSshMaterial({ home: ctx.userHome() })).knownHostsText),
|
|
155
|
+
target.jumpHost.host,
|
|
156
|
+
target.jumpHost.port ?? 22,
|
|
157
|
+
).map((item) => item.fingerprint),
|
|
158
|
+
}
|
|
159
|
+
runtime.jumpSsh = ctx.deps.sshFactory(buildOptions(jumpTarget))
|
|
160
|
+
await runtime.jumpSsh.connect()
|
|
161
|
+
ctx.progress.phase(runtime, 'ssh', 'ssh-connecting', { host: target.host, via: target.jumpHost.host })
|
|
162
|
+
const stream = await runtime.jumpSsh.forwardOut(target.host, target.port ?? 22)
|
|
163
|
+
runtime.ssh = ctx.deps.sshFactory(buildOptions(target, stream))
|
|
164
|
+
captureFingerprint(ctx, runtime, await runtime.ssh.connect())
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Remember the session fingerprint so the host card shows it even without a pin. */
|
|
168
|
+
function captureFingerprint(ctx, runtime, info) {
|
|
169
|
+
if (!info?.fingerprint) return
|
|
170
|
+
const pinned = runtime.entry.pinnedFingerprint ?? null
|
|
171
|
+
runtime.fingerprint = {
|
|
172
|
+
sha256: info.fingerprint,
|
|
173
|
+
keyType: info.keyType ?? 'unknown',
|
|
174
|
+
status: pinned === info.fingerprint ? 'pinned' : pinned ? 'changed' : 'observed',
|
|
175
|
+
pinned,
|
|
176
|
+
}
|
|
177
|
+
ctx.progress.log(
|
|
178
|
+
runtime,
|
|
179
|
+
pinned === info.fingerprint ? 'debug' : 'info',
|
|
180
|
+
`host key ${info.keyType ?? 'unknown'}: ${info.fingerprint}${
|
|
181
|
+
pinned === info.fingerprint ? ' (matches the pinned key)' : pinned ? ' (CHANGED from the pinned key)' : ''
|
|
182
|
+
}`,
|
|
183
|
+
)
|
|
184
|
+
ctx.emitState()
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Warn when the remote already runs a DSH this plugin did not start, and let the
|
|
189
|
+
* user decide: stop it, keep it alongside, or cancel.
|
|
190
|
+
*/
|
|
191
|
+
async function resolveForeignConflict(ctx, runtime, layout, profile) {
|
|
192
|
+
const ignorePids = []
|
|
193
|
+
try {
|
|
194
|
+
const registry = await ctx.deps.readRegistry(runtime.ssh, layout)
|
|
195
|
+
const pid = Number(registry?.pid)
|
|
196
|
+
if (isPid(pid) && registry?.dshHome === layout.dshHome && registry?.profile === profile) ignorePids.push(pid)
|
|
197
|
+
} catch (error) {
|
|
198
|
+
// swallow-ok: registry absence is normal; the scan below still finds foreign processes
|
|
199
|
+
ctx.progress.log(runtime, 'debug', 'foreign DSH: registry read failed:', messageOf(error))
|
|
200
|
+
}
|
|
201
|
+
const found = await ctx.deps.findForeign(runtime.ssh, { ignorePids })
|
|
202
|
+
if (found.ok !== true) {
|
|
203
|
+
ctx.progress.log(runtime, 'debug', 'foreign DSH: scan failed:', found.reason ?? found.technical ?? 'unknown')
|
|
204
|
+
return
|
|
205
|
+
}
|
|
206
|
+
if (found.processes.length === 0) return
|
|
207
|
+
const pidList = found.processes.map((entry) => `pid ${entry.pid}`).join(', ')
|
|
208
|
+
ctx.progress.log(
|
|
209
|
+
runtime,
|
|
210
|
+
'warn',
|
|
211
|
+
`foreign DSH on the remote: ${found.processes.length} process(es) sharing this ~/.dsh (${pidList})`,
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
const decision = await askConflict(ctx, runtime, found.processes)
|
|
215
|
+
if (decision.action === 'cancel') throw errors.remoteDshRunning()
|
|
216
|
+
if (decision.action === 'alongside') {
|
|
217
|
+
runtime.warning = {
|
|
218
|
+
zh: '远端已有手工启动的 DSH;已按你的选择并存运行,两者共享 ~/.dsh,请避免同时操作同一会话。',
|
|
219
|
+
en: 'A manually started DSH is already running; it was kept as you chose. Both share ~/.dsh, so avoid editing the same session in both.',
|
|
220
|
+
}
|
|
221
|
+
return
|
|
222
|
+
}
|
|
223
|
+
const stopped = await ctx.deps.stopForeign(runtime.ssh, found.processes)
|
|
224
|
+
if (stopped.ok !== true) {
|
|
225
|
+
throw errors.remoteDshRunning(
|
|
226
|
+
{
|
|
227
|
+
zh: '远端的手工 DSH 进程没有停下来,连接已中止。',
|
|
228
|
+
en: 'The manual remote DSH process did not stop, so the connection was aborted.',
|
|
229
|
+
},
|
|
230
|
+
{
|
|
231
|
+
technical: `alive=${stopped.alive.join(',') || 'unknown'} output=${String(stopped.output ?? '').slice(0, 800)}`,
|
|
232
|
+
},
|
|
233
|
+
)
|
|
234
|
+
}
|
|
235
|
+
ctx.progress.log(runtime, 'info', `stopped ${found.processes.length} manual remote DSH process(es)`)
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
async function connectPipeline(ctx, runtime) {
|
|
239
|
+
const log = (level, ...args) => ctx.progress.log(runtime, level, ...args)
|
|
240
|
+
const phase = (name, code, params) => ctx.progress.phase(runtime, name, code, params)
|
|
241
|
+
runtime.closing = false
|
|
242
|
+
runtime.reconnectAttempts = 0
|
|
243
|
+
ctx.progress.set(runtime, { status: 'connecting', error: null, warning: null })
|
|
244
|
+
let remoteStarted = false
|
|
245
|
+
try {
|
|
246
|
+
const target = await resolveTargetForRuntime(ctx, runtime)
|
|
247
|
+
const viaJump = target.jumpHost ? ` via ${target.jumpHost.host}` : ''
|
|
248
|
+
log('debug', `target resolved: ${target.username ?? '(default)'}@${target.host}:${target.port}${viaJump}`)
|
|
249
|
+
// A password-auth host may have one remembered: load it before the transport
|
|
250
|
+
// is opened, so reconnect and background retries work without a prompt.
|
|
251
|
+
if (runtime.entry.auth?.type === 'password' && !runtime.password && ctx.secrets) {
|
|
252
|
+
const remembered = await ctx.secrets.get(runtime.id)
|
|
253
|
+
if (remembered) {
|
|
254
|
+
runtime.password = remembered
|
|
255
|
+
runtime.passwordSaved = true
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
phase('ssh', 'ssh-connecting', { host: runtime.entry.name })
|
|
259
|
+
await openTransport(ctx, runtime, target)
|
|
260
|
+
log(
|
|
261
|
+
'info',
|
|
262
|
+
`SSH connected to ${target.host}:${target.port} as ${target.username ?? '(default)'} (fingerprint ${
|
|
263
|
+
runtime.fingerprint?.sha256 ?? 'unknown'
|
|
264
|
+
})`,
|
|
265
|
+
)
|
|
266
|
+
|
|
267
|
+
phase('probe', 'probing')
|
|
268
|
+
let facts = await ctx.deps.probe(runtime.ssh)
|
|
269
|
+
const freeGb = Math.round(Number(facts.diskFreeKb ?? 0) / 1_048_576)
|
|
270
|
+
log(
|
|
271
|
+
'debug',
|
|
272
|
+
`probe: ${facts.os}/${facts.arch} · ${String(facts.osName ?? 'unknown OS')} · node ${
|
|
273
|
+
facts.nodeVersion ?? 'not found'
|
|
274
|
+
} · ${freeGb} GB free`,
|
|
275
|
+
)
|
|
276
|
+
// The runtime always runs on a plugin-owned Node (`~/.dsh/remote-go/node`),
|
|
277
|
+
// whether or not the remote already has one: a shared system/nvm Node is
|
|
278
|
+
// exactly what makes "works for my other project" break the remote DSH.
|
|
279
|
+
// There is no system fallback on purpose, so this failure is the connection's.
|
|
280
|
+
const profile = ctx.settings().bootstrap.profile
|
|
281
|
+
const managedVersion = managedNodeVersionFromEngine(ctx.engineNodeRange())
|
|
282
|
+
const nodeLayout = remoteLayout(facts.home)
|
|
283
|
+
log('info', `managed Node: expecting v${managedVersion} in ${nodeLayout.nodeDir}`)
|
|
284
|
+
const managed = await ctx.deps.ensureNode(runtime.ssh, {
|
|
285
|
+
facts,
|
|
286
|
+
layout: nodeLayout,
|
|
287
|
+
version: managedVersion,
|
|
288
|
+
onProgress: (event) => ctx.progress.nodeProgress(runtime, event),
|
|
289
|
+
})
|
|
290
|
+
facts = applyManagedNodeFacts(facts, managed)
|
|
291
|
+
log(
|
|
292
|
+
'info',
|
|
293
|
+
`managed Node ${managed.version}${managed.installed ? ' installed' : ' reused'} at ${managed.nodeBinDir}`,
|
|
294
|
+
)
|
|
295
|
+
runtime.facts = facts
|
|
296
|
+
const targetVersion = ctx.localVersion()
|
|
297
|
+
if (!targetVersion) {
|
|
298
|
+
throw errors.invalidInput('version', {
|
|
299
|
+
zh: '无法确定本机 DSH 版本,无法用 npx 固定同版本启动远端。请从 DSH 界面启动本插件,让 Host 读到本机版本。',
|
|
300
|
+
en: 'The local DSH version is unknown, so the remote cannot be pinned to the same version. Start the plugin from the DSH UI so the Host can read the local version.',
|
|
301
|
+
})
|
|
302
|
+
}
|
|
303
|
+
const plan = ctx.deps.plan({ facts, targetVersion, profile })
|
|
304
|
+
log('info', `runtime plan ${plan.level}: ${plan.reason.en}`)
|
|
305
|
+
|
|
306
|
+
phase('start', 'starting-remote', { level: plan.level })
|
|
307
|
+
const layout = remoteLayout(runtime.facts?.home ?? null)
|
|
308
|
+
let webInfo = null
|
|
309
|
+
// Adopt an instance left running by a previous local process (keep-alive).
|
|
310
|
+
// Checked before the npx preflight: an adoptable instance should not require
|
|
311
|
+
// registry access just to reconnect.
|
|
312
|
+
try {
|
|
313
|
+
const adopted = await ctx.deps.adopt(runtime.ssh, layout, { profile })
|
|
314
|
+
const adoptedVersion = adopted?.version ? normalizeVersion(adopted.version) : null
|
|
315
|
+
if (adopted && (!adoptedVersion || versionsEqual(adoptedVersion, targetVersion))) {
|
|
316
|
+
webInfo = { ...adopted, logPath: layout.logFile, startedAt: nowIso(), rawLine: '' }
|
|
317
|
+
log('info', `adopted running remote web pid=${adopted.pid} port=${adopted.port}`)
|
|
318
|
+
} else if (adopted) {
|
|
319
|
+
log(
|
|
320
|
+
'info',
|
|
321
|
+
`running remote web version ${adoptedVersion} != ${targetVersion}; stopping it and starting a matching instance`,
|
|
322
|
+
)
|
|
323
|
+
// The old process owns the same `~/.dsh` profile; leaving it running next
|
|
324
|
+
// to the new one would share session files with a stale version.
|
|
325
|
+
try {
|
|
326
|
+
await ctx.deps.stopWeb(runtime.ssh, layout, { pid: adopted.pid })
|
|
327
|
+
} catch (error) {
|
|
328
|
+
log('warn', 'could not stop the stale remote web:', messageOf(error))
|
|
329
|
+
}
|
|
330
|
+
} else {
|
|
331
|
+
log('debug', 'adopt: no running remote web to reuse')
|
|
332
|
+
}
|
|
333
|
+
} catch (error) {
|
|
334
|
+
log('debug', 'adopt check failed:', messageOf(error))
|
|
335
|
+
}
|
|
336
|
+
if (!webInfo) {
|
|
337
|
+
// The registry row we refused to adopt (stale launch marker, unresponsive
|
|
338
|
+
// HTTP, ...) still names a process on this ~/.dsh profile. Starting a second
|
|
339
|
+
// one would let two clients write the same session files.
|
|
340
|
+
const leftover = await ctx.deps.readRegistry(runtime.ssh, layout)
|
|
341
|
+
const leftoverPid = Number(leftover?.pid ?? 0)
|
|
342
|
+
if (leftover?.dshHome === layout.dshHome && leftover?.profile === profile && isPid(leftoverPid)) {
|
|
343
|
+
try {
|
|
344
|
+
await ctx.deps.stopWeb(runtime.ssh, layout, { pid: leftoverPid })
|
|
345
|
+
log('info', `stopped a non-adoptable remote web instance pid=${leftoverPid}`)
|
|
346
|
+
} catch (error) {
|
|
347
|
+
log('warn', 'could not stop the non-adoptable remote web:', messageOf(error))
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
await resolveForeignConflict(ctx, runtime, layout, profile)
|
|
351
|
+
phase('bootstrap', 'bootstrapping', { level: plan.level })
|
|
352
|
+
// Resolve the exact package in the foreground first: a cold npx download
|
|
353
|
+
// belongs in the connect error, not in a detached process that only leaves a
|
|
354
|
+
// log behind. This also warms the cache for the real start below.
|
|
355
|
+
log('info', `npx preflight: resolving @deepseek-ai/dsh@${plan.start.targetVersion}`)
|
|
356
|
+
const onStdout = ctx.progress.bootstrapReporter(runtime, plan.start.targetVersion)
|
|
357
|
+
const onStderr = ctx.progress.bootstrapReporter(runtime, plan.start.targetVersion)
|
|
358
|
+
await ctx.deps.preflight(runtime.ssh, plan, { onStdout, onStderr })
|
|
359
|
+
log('info', `npx preflight ready: @deepseek-ai/dsh@${plan.start.targetVersion}`)
|
|
360
|
+
phase('start', 'starting-remote', { level: plan.level })
|
|
361
|
+
webInfo = await ctx.deps.startWeb(runtime.ssh, {
|
|
362
|
+
plan,
|
|
363
|
+
layout,
|
|
364
|
+
profile,
|
|
365
|
+
timeoutMs: REMOTE_START_TIMEOUT_MS,
|
|
366
|
+
onLine: (line) => log('debug', `remote: ${line}`),
|
|
367
|
+
})
|
|
368
|
+
log('info', `remote DSH started: pid ${webInfo.pid ?? '?'}, port ${webInfo.port}`)
|
|
369
|
+
}
|
|
370
|
+
if (webInfo.browserCarrier === 'patched') {
|
|
371
|
+
log(
|
|
372
|
+
'info',
|
|
373
|
+
'the remote profile disables api-remotes (browser Remote-Event carrier); re-enabled it for this launch',
|
|
374
|
+
)
|
|
375
|
+
}
|
|
376
|
+
remoteStarted = true
|
|
377
|
+
runtime.token = webInfo.token
|
|
378
|
+
runtime.remote = {
|
|
379
|
+
version: targetVersion,
|
|
380
|
+
uiReady: false,
|
|
381
|
+
localPort: null,
|
|
382
|
+
port: webInfo.port,
|
|
383
|
+
pid: webInfo.pid ?? null,
|
|
384
|
+
dshHome: layout.dshHome,
|
|
385
|
+
profile,
|
|
386
|
+
bootstrapLevel: plan.level,
|
|
387
|
+
nodeVersion: facts.nodeVersion,
|
|
388
|
+
nodeSource: 'managed',
|
|
389
|
+
startedAt: webInfo.startedAt ?? nowIso(),
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
phase('tunnel', 'tunneling')
|
|
393
|
+
runtime.tunnel = await ctx.deps.tunnelFactory({ ssh: runtime.ssh, remotePort: webInfo.port })
|
|
394
|
+
runtime.remote.localPort = runtime.tunnel.localPort
|
|
395
|
+
log('info', `tunnel open: 127.0.0.1:${runtime.tunnel.localPort} -> 127.0.0.1:${webInfo.port}`)
|
|
396
|
+
|
|
397
|
+
phase('verifying', 'verifying')
|
|
398
|
+
log('debug', `verifying the remote UI on 127.0.0.1:${webInfo.port}`)
|
|
399
|
+
const ui = await ctx.deps.waitUi(runtime.ssh, webInfo.port, { attempts: 20, intervalMs: 500 })
|
|
400
|
+
if (!ui.ok) {
|
|
401
|
+
throw errors.remoteUiUnreachable({
|
|
402
|
+
zh: `远端 DSH 的本地 127.0.0.1:${webInfo.port} 没有响应(HTTP ${ui.status ?? '无'})。`,
|
|
403
|
+
en: `The remote DSH on 127.0.0.1:${webInfo.port} did not respond (HTTP ${ui.status ?? 'none'}).`,
|
|
404
|
+
})
|
|
405
|
+
}
|
|
406
|
+
log('debug', `remote UI answered HTTP ${ui.status}; exchanging the launch token`)
|
|
407
|
+
const exchange = await ctx.deps.exchange(runtime.tunnel.localPort, webInfo.token, {
|
|
408
|
+
timeoutMs: TUNNEL_PROBE_TIMEOUT_MS,
|
|
409
|
+
})
|
|
410
|
+
runtime.exchange = exchange
|
|
411
|
+
if (!exchange.ok) {
|
|
412
|
+
throw errors.remoteUiUnreachable({
|
|
413
|
+
zh: `本地隧道完成了 token 交换,但远端界面返回 HTTP ${exchange.status}(首次状态 ${exchange.firstStatus})。`,
|
|
414
|
+
en: `The tunnel exchanged the token but the remote UI answered HTTP ${exchange.status} (first ${exchange.firstStatus}).`,
|
|
415
|
+
})
|
|
416
|
+
}
|
|
417
|
+
// X-Frame-Options / CSP no longer matter: the remote UI is rendered by the
|
|
418
|
+
// desktop guest, not embedded in a frame, so a page that refuses framing is
|
|
419
|
+
// still a perfectly usable remote host.
|
|
420
|
+
runtime.remote.uiReady = true
|
|
421
|
+
await ctx.store.patchHost(runtime.id, { lastOpenedAt: nowIso() })
|
|
422
|
+
runtime.entry = ctx.store.getHost(runtime.id) ?? runtime.entry
|
|
423
|
+
if (ctx.settings().saveTokens) await ctx.store.saveToken(runtime.id, webInfo.token)
|
|
424
|
+
// Remember the password now that it is proven, if the user asked for that.
|
|
425
|
+
if (runtime.savePassword === true && typeof runtime.password === 'string' && ctx.secrets) {
|
|
426
|
+
runtime.passwordSaved = await ctx.secrets.set(runtime.id, runtime.password)
|
|
427
|
+
}
|
|
428
|
+
runtime.status = 'connected'
|
|
429
|
+
runtime.phase = 'ready'
|
|
430
|
+
runtime.progress = { code: 'ready' }
|
|
431
|
+
runtime.error = null
|
|
432
|
+
ctx.state.activeHostId = runtime.id
|
|
433
|
+
attachDisconnectHandler(ctx, runtime)
|
|
434
|
+
ctx.emitState()
|
|
435
|
+
log('info', `connected: remote ${runtime.remote.version} on 127.0.0.1:${runtime.tunnel.localPort}`)
|
|
436
|
+
} catch (error) {
|
|
437
|
+
const view = toErrorView(error)
|
|
438
|
+
if (runtime.desired !== 'connected') {
|
|
439
|
+
// A user-initiated disconnect/teardown resolved a pending prompt (or closed
|
|
440
|
+
// the window) while the pipeline was in flight: this is not a failure.
|
|
441
|
+
runtime.error = null
|
|
442
|
+
runtime.status = 'disconnected'
|
|
443
|
+
runtime.phase = null
|
|
444
|
+
runtime.progress = null
|
|
445
|
+
log('info', 'connect cancelled by disconnect')
|
|
446
|
+
} else {
|
|
447
|
+
runtime.error = view
|
|
448
|
+
runtime.status = 'error'
|
|
449
|
+
runtime.phase = null
|
|
450
|
+
runtime.progress = null
|
|
451
|
+
log('warn', `connect failed: ${view.code}`, messageOf(error))
|
|
452
|
+
}
|
|
453
|
+
runtime.remote.uiReady = false
|
|
454
|
+
runtime.remote.localPort = null
|
|
455
|
+
await teardownRuntime(ctx, runtime, {
|
|
456
|
+
stopRemote: remoteStarted && runtime.entry.keepAlive === 'stop',
|
|
457
|
+
keepRemote: remoteStarted && runtime.entry.keepAlive !== 'stop',
|
|
458
|
+
})
|
|
459
|
+
ctx.emitState()
|
|
460
|
+
} finally {
|
|
461
|
+
runtime.connectPromise = null
|
|
462
|
+
}
|
|
463
|
+
}
|