dsh-remote 1.1.2 → 1.2.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.
package/lib/index.js CHANGED
@@ -1,4573 +1,20 @@
1
- // dsh-remote — remote-work assistant for DeepSeek Harness.
2
- //
3
- // Host half. Turns "give me a remote host + login" into a usable REMOTE WORKSPACE:
4
- // • one persistent SSH/SFTP pool per configured remote (password OR private key,
5
- // SSH agent, keyboard-interactive, proxy jump),
6
- // • a "current remote workspace" — a remote directory the agent treats as the
7
- // active project root (user@host:/path) — injected into every system prompt,
8
- // • model tools `rw_*` (info/connect/workspace/list/read/write/edit/append/mkdir/
9
- // remove/move/stat/exec/search/download/upload/sync/push/forward/disconnect),
10
- // • JSON endpoints the client settings page + sidebar use over the harness
11
- // `webServer` (machines / ls / read / write / fs / forwards / task / audit /
12
- // ssh-config / local-pick / …),
13
- // • local mirror of the remote workspace (three-way conflict-aware SFTP sync),
14
- // • optional OS-keychain password storage, command audit log, TOFU host keys.
15
- //
16
- // The engine (path guard + shell quoting + ssh pool + exec) keeps the proven
17
- // foundation; `ctx.fs` / the local workspace registry stay untouched — this is a
18
- // REMOTE workspace presented as such to the model and UI.
19
- //
20
- // Plugin Config MUST be a schemastery schema (zod rejects the undefined row config).
21
- import { WorkspaceSearches, createSearchRoutes } from './workspace-search.js'
22
- import { createGitRoutes } from './remote-git.js'
23
- import { LOCAL_MUTATION_TOOLS, remoteLocalMutationDecision } from './local-mutation.js'
24
- import { fileChange, changeOutput, presentFileChange } from './file-changes.js'
25
- import { captureRemoteFile, atomicRemoteWrite } from './remote-write.js'
26
- import z from '@deepseek-ai/schemastery'
27
- import { createAutoUpdater } from './auto-update.js'
28
- import { defineTool } from '@deepseek-ai/dsh-tools'
29
- import { execFile } from 'node:child_process'
30
- import { readFileSync, mkdirSync, writeFileSync, existsSync, readdirSync, statSync, renameSync, copyFileSync, appendFileSync, watch, rmSync, chmodSync } from 'node:fs'
31
- import { createHash, randomBytes, timingSafeEqual } from 'node:crypto'
32
- import { homedir } from 'node:os'
33
- import path from 'node:path'
34
- import { fileURLToPath } from 'node:url'
35
- import iconv from 'iconv-lite'
36
-
37
- import {
38
- shq, normalizeRemotePath, joinRemotePath, joinRemoteRel, resolveRemoteWorkspacePath, remoteDirname, mkdirRemoteDirs,
39
- toShellPath, toDisplayPath, remotePathBase, remoteWorkspaceTitle, truncate, shortHash,
40
- } from './paths.js'
41
- import { createHostKeyGuard, isHostKeyKnown as _isHostKeyKnown } from './hostkey.js'
42
- import { compileIgnore, ignorePatternsFor, DEFAULT_IGNORE } from './ignore.js'
43
- import { friendlyMessage } from './errors.js'
44
- import { sshConfigPath, readSshConfigText, resolveMachineSshConfig, resolveLiteralSshConfig, readRawSshConfig, upsertManagedHostBlock, removeManagedHostBlock, writeSshConfig } from './sshconfig.js'
45
- import { createRemoteFileReference, installFileReferenceOverlay, DEFAULT_EXCLUDED_DIRECTORIES } from './file-reference.js'
46
- import { getSecret, deleteSecret, platformBackend, persistPassword } from './credential.js'
47
- import { syncTree, pushTree, loadSyncState, saveSyncState, pushOneFile } from './sync.js'
48
- import { createSyncActivity } from './sync-status.js'
49
- import { createInstructionIndex, formatInstructionIndex } from './instructions.js'
50
- import { resolveExecTimeout, formatExecResult, startExecJob, execWithOptionalPromotion } from './exec-job.js'
51
- import { createInjectionTracker, refreshTouched, buildInstructionMessage, pickUserMessageFactory, loadBundledUserMessageFactory } from './instructions-dynamic.js'
52
- import { REMOTE_SANDBOX_MODES, checkRemoteSandbox, remoteSandboxDenial } from './remote-sandbox.js'
53
- import { createTerminalManager } from './terminal.js'
54
- import { createTerminalRoutes } from './routes-term.js'
55
- import { searchRemote } from './search.js'
56
- import { installTerminalShell } from './remote-shell.js'
57
- import { resolveMirror, poolKey, lookupSessionCwd, encodeSegmentSafe, readSessionHeaderCwd, requestSessionHint } from './binding.js'
58
- import { TaskManager } from './tasks.js'
59
- import { ForwardManager } from './forwards.js'
60
- import { formatAuditLine, readAuditLines } from './audit.js'
61
- import { openLocalFolder } from './open-folder.js'
62
-
63
- import { selfDir, diskVersion, LOADED_VERSION, gtVersion, fetchLatestVersion, applyUpdate, persistUpdateMode, readUpdateMode, reloadSelf, scheduleSelfReload, lastSelfReload, isInstalledCopy, writeFileAtomic } from './update.js'
64
- import { sendHeartbeat, pseudonym, heartbeatUrl, hasPersistedId, installIdPath, telemetryAllowed } from './telemetry.js'
65
- import { loadMachines as _loadMachines, saveMachines as _saveMachines, sanitizeMachine as _sanitizeMachine, applyMachine as _applyMachine, machineId as _machineId, normalizeMachineGroup, filterMachinesByGroup, resolveProbeCredentials } from './registry.js'
66
- import { registerHttpTransports } from './http-transport.js'
67
- import { createHostApi } from './host-api.js'
68
- import { SshPool, ActivePool, createPool } from './pool.js'
69
- import { isSystemOpenSshBackend, sshBinaryAvailable, resolveSshBinary } from './openssh.js'
70
- import { createAuditRoutes } from './routes-audit.js'
71
- import { createForwardRoutes } from './routes-forwards.js'
72
- import { createMachineRoutes } from './routes-machines.js'
73
- import { createMiscRoutes } from './routes-misc.js'
74
- import { createFsRoutes } from './routes-fs.js'
75
- import { createUpdateRoutes } from './routes-update.js'
76
- import { createWebAttachRoutes } from './routes-web-attach.js'
77
- import { createWorkspaceRoutes } from './routes-workspace.js'
78
- import { listDirStructured, removeRemoteTree } from './remote-fs.js'
79
- import { registerRemoteSkills } from './remote-skills.js'
80
-
81
- export const name = 'dsh-remote'
82
-
83
- /** Update mode used when neither the persisted `update-mode` file nor the
84
- * profile config supplies one.
85
- *
86
- * Kept as one exported constant on purpose: the value appears in the schema
87
- * default, in the `/update-check` response and in the auto-update gate, and
88
- * three hard-coded copies drift (the first version of this change left two
89
- * `|| 'manual'` fallbacks that quietly disagreed with the new schema default).
90
- * Changing the default must change exactly one place. */
91
- export const DEFAULT_UPDATE_MODE = 'auto'
92
-
93
- /** Decode one folder-picker child's stdout into { path } | { cancelled }.
94
- *
95
- * Exported because the base64 contract below is only observable on a Windows
96
- * desktop — the test suite pins it like issue #30's DPAPI scripts. With
97
- * `base64: true` the child printed the path base64(UTF-8)-encoded so a
98
- * non-ASCII (e.g. Chinese) folder name survives a console whose output
99
- * codepage is GBK: Node decodes stdout as UTF-8, and a raw path would arrive
100
- * as mojibake that then failed "not a directory" (issue #58). Base64 stdout
101
- * is ASCII on every codepage. */
102
- export function decodePickStdout(stdout, { base64 = false } = {}) {
103
- let p = String(stdout || '').replace(/[\r\n]+$/, '').trim()
104
- if (base64 && p && p !== 'CANCELED') {
105
- try { p = Buffer.from(p, 'base64').toString('utf8') } catch { /* keep raw */ }
106
- }
107
- return p === 'CANCELED' ? { cancelled: true } : (p ? { path: p } : { cancelled: true })
108
- }
109
-
110
- /** The Windows FolderBrowserDialog one-liner; prints base64(UTF-8) of the
111
- * selected path (see decodePickStdout) or the literal CANCELED. */
112
- export function win32FolderPickScript() {
113
- return (
114
- `Add-Type -AssemblyName System.Windows.Forms;` +
115
- `$f = New-Object System.Windows.Forms.FolderBrowserDialog;` +
116
- `$f.Description = 'Select Workspace Directory';` +
117
- `if ($f.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) { [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($f.SelectedPath)) } else { 'CANCELED' }`
118
- )
119
- }
120
-
121
- /** The rw_* tools a LOCAL session keeps under `localTools: 'bootstrap'`
122
- * (issue #63): exactly the configuration loop — list machines, connect, pick
123
- * a workspace. Every other rw_* tool needs a mirror-bound session and refuses
124
- * a local one with "this session is LOCAL", so keeping it visible only spends
125
- * schema budget. Exported so the test suite pins the set against the real
126
- * registrations. */
127
- export const LOCAL_BOOTSTRAP_TOOLS = ['rw_machines', 'rw_connect', 'rw_pick_workspace']
128
-
129
- /** Normalize the `localTools` config value (issue #63). Anything unrecognized
130
- * degrades to the safe default 'bootstrap' rather than disabling the filter
131
- * (a typo must not silently re-expose the dead surface the user asked to
132
- * hide) — mirroring how an unknown value would otherwise be mistaken for
133
- * 'all'. */
134
- export function normalizeLocalTools(value) {
135
- const v = String(value || '').trim().toLowerCase()
136
- return v === 'none' || v === 'all' ? v : 'bootstrap'
137
- }
138
-
139
- /** rw_pick_workspace's closing "what next" sentence (issue #63). In a LOCAL
140
- * session `rw_sync` cannot run — the mirror path must be opened as a NEW
141
- * session first, because tool routing keys on the session's cwd and picking
142
- * a workspace does not change it. Only a mirror-bound (or caller-context-
143
- * less) session can sync right away. */
144
- export function pickWorkspaceNextStep(localSession) {
145
- return localSession
146
- ? 'NOTE: this session is LOCAL — rw_sync and the other remote tools refuse to run here. Open a session whose workspace IS the local mirror path above, then run rw_sync there to download the remote files.'
147
- : 'Run rw_sync to download its files into the local mirror.'
148
- }
149
-
150
- // Web and Desktop share the SSH tools; each optional UI transport is attached
151
- // reactively below, so service startup order does not drop the JSON routes.
152
- export const inject = ['tools', 'systemPrompt']
153
-
154
- export const Config = z.object({
155
- /** Remote SSH host (empty → the plugin starts disconnected). */
156
- host: z.string().default(''),
157
- /** Remote SSH port (22 unless the machine uses a custom port). */
158
- port: z.number().step(1).min(1).max(65535).default(22),
159
- /** SSH login user. */
160
- username: z.string().default(''),
161
- /** Password login (only when the remote has no key. Override the fallback below). */
162
- password: z.string().default(''),
163
- /** Explicit SSH private-key path (optional; only used when supplied). Never auto-reads ~/.ssh. */
164
- privateKeyPath: z.string().default(''),
165
- /** Key passphrase when the key is encrypted. */
166
- passphrase: z.string().default(''),
167
- /** Initial remote workspace path (absolute dir the agent should treat as root). */
168
- workspace: z.string().default(''),
169
- /** Remote command terminal strategy. '' = auto-detect (Windows remotes look
170
- * for Git Bash and pipe every command through `bash -s`); 'git-bash' = prefer
171
- * Git Bash on Windows; 'native' = never wrap; any other value = explicit
172
- * bash.exe path (e.g. 'C:\\Program Files\\Git\\bin\\bash.exe'). Git Bash makes
173
- * a Windows remote behave like a POSIX host (/c/Users/... paths). */
174
- shell: z.string().default(''),
175
- /** Per-command timeout. */
176
- commandTimeoutMs: z.number().step(1).min(1000).default(20000),
177
- /** SSH connection establishment timeout. */
178
- connectTimeoutMs: z.number().step(1).min(1000).default(15000),
179
- /** Hard ceiling on collected remote output per call. */
180
- maxOutputChars: z.number().step(1).min(1024).default(200000),
181
- /** Skip mirroring files larger than this many bytes (0 = no cap). */
182
- maxFileBytes: z.number().step(1).min(0).default(52428800),
183
- /** Host-key policy: `accept-new` (default) records a host's key on first
184
- * connect and verifies it afterwards (mirrors ssh's StrictHostKeyChecking
185
- * accept-new); `verify` also rejects hosts never seen before; `off` skips
186
- * verification entirely (MITM-unsafe, not recommended). */
187
- hostKeyMode: z.string().default('accept-new'),
188
- /** Use the OpenSSH agent (SSH_AUTH_SOCK) when no password/key is configured. */
189
- useAgent: z.boolean().default(false),
190
- /** Allow keyboard-interactive auth (OTP/MFA chains) using the configured password. */
191
- keyboardInteractive: z.boolean().default(false),
192
- /** SSH transport backend (issue #51):
193
- * `native` (default) speaks SSH through ssh2 — password / private key /
194
- * ssh-agent / keyboard-interactive;
195
- * `openssh` delegates to the LOCAL `ssh` executable, which is the only way to
196
- * reach hosts that allow GSSAPI/Kerberos (kinit) or that rely on other
197
- * OpenSSH-only `~/.ssh/config` features (ProxyCommand, PKCS11Provider,
198
- * ControlMaster, Match blocks). See lib/openssh.js for the trade-offs. */
199
- backend: z.string().default('native'),
200
- /** The `ssh` executable the `openssh` backend drives (PATH name or a full
201
- * path). Ignored by the native backend. */
202
- sshBinary: z.string().default(''),
203
- /** Jump host / bastion: connect through this machine first. All fields have
204
- * defaults so this works on schemastery versions without `.optional()`; an
205
- * empty `host` means "no jump host". */
206
- proxy: z.object({
207
- host: z.string().default(''),
208
- port: z.number().step(1).min(1).max(65535).default(22),
209
- username: z.string().default(''),
210
- password: z.string().default(''),
211
- privateKeyPath: z.string().default(''),
212
- }),
213
- /** Auto-push edited mirror files back to the remote (watcher, debounced). Default off. */
214
- autoPush: z.boolean().default(false),
215
- /** Append executed commands to the audit log under the harness home. */
216
- auditLog: z.boolean().default(true),
217
- /** Text encoding for remote file reads/writes (utf-8 default; gbk etc.). */
218
- encoding: z.string().default('utf-8'),
219
- /** Remote `@` completion (issue #39). When on, a session whose workspace is a
220
- * dsh-remote mirror lists the REMOTE tree for `@` (over SFTP, bounded) instead
221
- * of the local mirror — which `ensureMirror()` leaves empty until a sync, so
222
- * `@` used to find nothing at all. Sessions on a local workspace are
223
- * untouched, and a host that cannot be reached falls back to the mirror. */
224
- fileReference: z.boolean().default(true),
225
- /** Max `@` candidates rendered for one query (mirrors the local provider). */
226
- fileReferenceMaxResults: z.number().step(1).min(1).default(20),
227
- /** Max entries retained in the remote `@` index of one workspace. */
228
- fileReferenceMaxEntries: z.number().step(1).min(1).default(3000),
229
- /** Directory basenames the remote `@` traversal skips. */
230
- fileReferenceExcludedDirectories: z.array(z.string()).default([...DEFAULT_EXCLUDED_DIRECTORIES]),
231
- /** Wall-clock budget (ms) for one remote `@` index pass; on expiry the
232
- * partial index answers rather than making the caret wait. */
233
- fileReferenceTimeoutMs: z.number().step(1).min(200).default(4000),
234
- /** Cooperative budget (ms) for `rw_search`; also declared as the tool's
235
- * `timeoutMs` so @deepseek-ai/dsh-tool-call-timeout-policy can end a call
236
- * that overruns. The search itself stops at this budget and returns partial
237
- * results (issue #44: an unbounded walk over a home directory could never be
238
- * stopped and left the turn `running` forever). */
239
- searchTimeoutMs: z.number().step(1).min(1000).default(60000),
240
- /** Max files `rw_search` will stat/read before returning partial results. */
241
- searchMaxEntries: z.number().step(1).min(1).default(50000),
242
- /** Update mode: `auto` (default) checks on load and periodically, applies a
243
- * newer npm release automatically, then hot-swaps the host half (see
244
- * `updateAutoReload`); `manual` only checks when the user asks; `off` disables
245
- * version checks entirely. (schemastery 3.18 has no .enum — keep string and
246
- * validate in code.)
247
- *
248
- * `auto` became the default in 0.8.27. It could not have been a safe default
249
- * before 0.8.24: an update only replaced files on disk and needed a restart,
250
- * which left users running a new browser half against an old host half with no
251
- * visible signal. 0.8.24 added the hot swap (and `pendingReload` when it is
252
- * turned off), so an unattended update now actually takes effect. */
253
- updateMode: z.string().default(DEFAULT_UPDATE_MODE),
254
- /** How often (ms) auto mode checks the npm registry for a newer release. */
255
- updateCheckIntervalMs: z.number().step(1).min(60000).default(1800000),
256
- /** Whether a landed update also hot-swaps the running host half (default
257
- * true). With `false` an update only takes effect on the next process start
258
- * and `/dsh-remote/update-check` reports `pendingReload: true` meanwhile. */
259
- updateAutoReload: z.boolean().default(true),
260
- /** First local port tried when attaching a remote DSH Web UI (issue #46).
261
- * The listener is loopback-only; consecutive ports are tried when this one
262
- * is taken. */
263
- webAttachPortStart: z.number().step(1).min(1).max(65535).default(3088),
264
- /** Remote command that starts a `dsh web` on the attached machine. Only needs
265
- * changing when the remote's `dsh` is not on the SSH login PATH (e.g. a
266
- * version installed into a private prefix). */
267
- webAttachCommand: z.string().default('dsh'),
268
- /** `DSH_HOME` to export on the remote when attaching. Empty reuses the
269
- * remote user's own harness home; point it at a scratch directory to keep an
270
- * attached instance out of the user's real sessions and settings. */
271
- webAttachDshHome: z.string().default(''),
272
- /** How long (seconds) to wait for a freshly started remote `dsh web` to print
273
- * its startup token before giving up. */
274
- webAttachWaitSeconds: z.number().step(1).min(5).max(300).default(45),
275
- /** Which `rw_*` tools a LOCAL session sees.
276
- * `bootstrap` (default) keeps only the configuration loop —
277
- * rw_machines / rw_connect / rw_pick_workspace — since the other tools
278
- * can never succeed there (they refuse with "this session is LOCAL") and
279
- * exposing them only spends schema tokens per request; `none` hides every
280
- * rw_* tool (remote setup then happens via the settings page only); `all`
281
- * keeps the full surface. A REMOTE session (cwd inside a mirror) always
282
- * sees all tools, and an invalid value falls back to `bootstrap`.
283
- * (schemastery 3.18 has no .enum — validated in code.) */
284
- localTools: z.string().default('bootstrap'),
285
- /** Remote sandbox fence (parity with the local session sandbox).
286
- *
287
- * `inherit` (default) reads the SAME `ctx.sandboxPolicy` the local tools use
288
- * and applies it to remote operations: read-only refuses remote writes and
289
- * commands, workspace-write fences remote writes to the workspace root,
290
- * danger-full-access allows everything. `off` restores the pre-0.8.54
291
- * behaviour (no fence) for deployments whose remotes enforce their own
292
- * boundary. A per-call `sandbox_permissions: 'danger-full-access'` also
293
- * works, but only when the composition advertises escalation. */
294
- remoteSandbox: z.string().default('inherit'),
295
- /** What to do when the OS secure store refuses a password.
296
- *
297
- * `refuse` (default): never write a password to machines.json. The machine is
298
- * saved without a credential and the UI reports the store failure plus the
299
- * repair hint -- you asked for encryption, so silently downgrading to
300
- * plaintext is the one outcome you did not ask for.
301
- * `plain`: the pre-0.8.54 fallback (write it and warn). */
302
- credentialFallback: z.string().default('refuse'),
303
- /** Anonymous install heartbeat (daily-active statistics). The payload is a
304
- * plugin-specific HMAC pseudonym — no machine info leaves the box. Admins
305
- * can turn it off here; users get a settings-page checkbox whose persisted
306
- * choice (in $DSH_HOME) wins over this config value. */
307
- telemetry: z.boolean().default(true),
308
- /** Make the "remote ssh" launcher the terminal's DEFAULT shell when neither
309
- * the host admin (config.shell) nor the user (remembered menu choice) has
310
- * picked one. The launcher is cwd-aware: a session rooted in a remote mirror
311
- * gets a terminal already sshed into the remote workspace; any other session
312
- * transparently falls back to a local shell. `false` keeps "remote ssh"
313
- * menu-only. */
314
- remoteTerminalDefault: z.boolean().default(true),
315
- /** TUI integration layer (docs/tui.md): register the `/dsh-remote` scene,
316
- * the workspace provider and the `/dsh-remote` slash command when a
317
- * dsh-tui profile is present. `false` disables the whole layer — on a Web or
318
- * Desktop profile it already degrades to a no-op by soft-probing its seams. */
319
- tui: z.boolean().default(true),
320
- /** List each machine's recent workspaces in the TUI workspace picker. */
321
- tuiProviderListRecent: z.boolean().default(true),
322
- /** How many recent workspaces per machine the picker lists (1–20). */
323
- tuiProviderRecentLimit: z.number().step(1).min(1).max(20).default(5),
324
- /** Switch the session to a remote workspace right after adopting it in the
325
- * TUI scene. */
326
- tuiAutoSwitchWorkspace: z.boolean().default(true),
327
- /** Language for the TUI layer's own copy: `''` = auto (zh, or `en` when
328
- * `DSH_TUI_LANG=en`), `zh` / `en` pins it. The TUI's own screens keep their
329
- * own language; this only affects `/dsh-remote` and its toasts. */
330
- tuiLang: z.string().default(''),
331
- })
332
-
333
- // ── shell / path helpers (pure implementations in lib/paths.js) ───────────
334
-
335
- /** Harness home: respect `DSH_HOME` when set (the desktop app sets it to its
336
- * own `userData/harness`), otherwise fall back to `~/.dsh`. */
337
- function dshBase() {
338
- const env = process.env.DSH_HOME
339
- if (env && String(env).trim()) return path.resolve(String(env).trim())
340
- return path.join(homedir(), '.dsh')
341
- }
342
-
343
- /** Root holding every remote host's mirrors + the machine registry. */
344
- function remoteWorkspacesRoot() {
345
- return path.join(dshBase(), 'remote-workspaces')
346
- }
347
-
348
- /** Local mirrors of one remote host. */
349
- function mirrorRootFor(host, user, port) {
350
- const tag = [host, user, port].filter(Boolean).join('-').replace(/[^a-zA-Z0-9._-]/g, '_')
351
- return path.join(remoteWorkspacesRoot(), tag)
352
- }
353
-
354
- /** Generated terminal launchers. Deliberately NOT under `remote-workspaces`: a
355
- * launcher there would sit next to the mirrors, where anything that scans the
356
- * root for checkouts could pick it up as one. */
357
- function remoteTerminalRoot() {
358
- return path.join(dshBase(), 'remote-terminal')
359
- }
360
-
361
- /**
362
- * Every path the remote-shell contribution needs, resolved for this install.
363
- *
364
- * Split out from the registration itself so the wiring at the bottom of the
365
- * plugin stays one readable line, and so the launcher path is a pure function
366
- * of where the plugin lives.
367
- *
368
- * @returns {{ dir: string, childPath: string, machinesFile: string }}
369
- */
370
- function remoteShellSpec() {
371
- return {
372
- dir: remoteTerminalRoot(),
373
- childPath: fileURLToPath(new URL('./remote-shell-child.cjs', import.meta.url)),
374
- machinesFile: machinesFile(),
375
- }
376
- }
377
-
378
- /** Local mirror dir for a specific remote path (idempotent → returns same dir). */
379
- function mirrorDirFor(remotePath, host, user, port) {
380
- const base = remotePathBase(remotePath)
381
- const root = mirrorRootFor(host, user, port)
382
- const plain = path.join(root, base)
383
- const norm = normalizeRemotePath(remotePath)
384
- // A pre-existing mirror for this exact remote origin → reuse it (idempotent).
385
- try {
386
- const meta = JSON.parse(readFileSync(path.join(plain, '.dsh-remote-meta.json'), 'utf8'))
387
- if (meta.remotePath === norm) return plain
388
- } catch {
389
- /* no mirror yet → fall through */
390
- }
391
- if (!existsSync(plain)) return plain
392
- return path.join(root, base + '-' + shortHash(norm))
393
- }
394
-
395
- /** Create the local mirror dir + a meta file describing its remote origin.
396
- * `extra.alias` records the ~/.ssh/config alias a machine was saved as (issue
397
- * #38), so the mirror keeps resolving to its machine even if the alias's
398
- * HostName/user/port change in that file afterwards. */
399
- function ensureMirror(remotePath, host, user, port, extra = {}) {
400
- const dir = mirrorDirFor(remotePath, host, user, port)
401
- mkdirSync(dir, { recursive: true })
402
- const meta = { host, port, username: user, remotePath: normalizeRemotePath(remotePath), createdAt: new Date().toISOString() }
403
- if (extra.alias) meta.alias = String(extra.alias)
404
- writeFileSync(path.join(dir, '.dsh-remote-meta.json'), JSON.stringify(meta, null, 2))
405
- return dir
406
- }
407
-
408
- /** Recursive directory copy (EXDEV fallback for migrateLegacyData). */
409
- function copyDirSync(from, to) {
410
- mkdirSync(to, { recursive: true })
411
- for (const e of readdirSync(from, { withFileTypes: true })) {
412
- const s = path.join(from, e.name)
413
- const d = path.join(to, e.name)
414
- if (e.isDirectory()) copyDirSync(s, d)
415
- else try { copyFileSync(s, d) } catch { /* skip unreadable */ }
416
- }
417
- }
418
-
419
- /** One-time migration of pre-0.6 data (~/.dsh/remote-workspaces) into DSH_HOME.
420
- * Only runs when the harness is on its DEFAULT home: an explicitly-set DSH_HOME
421
- * pointing elsewhere means ~/.dsh belongs to another installation — migrating
422
- * would RENAME that other installation's live data out from under it. */
423
- function migrateLegacyData() {
424
- const env = process.env.DSH_HOME
425
- if (env && String(env).trim() && path.resolve(String(env).trim()) !== path.join(homedir(), '.dsh')) return
426
- const legacy = path.join(homedir(), '.dsh', 'remote-workspaces')
427
- const target = remoteWorkspacesRoot()
428
- if (legacy === target || !existsSync(legacy) || existsSync(target)) return
429
- try {
430
- mkdirSync(path.dirname(target), { recursive: true })
431
- try {
432
- renameSync(legacy, target)
433
- } catch (err) {
434
- if (err.code !== 'EXDEV') throw err
435
- copyDirSync(legacy, target)
436
- }
437
- } catch {
438
- // Migration is best-effort: a fresh registry is created on next save.
439
- }
440
- }
441
-
442
- // ── persistent multi-machine registry ─────────────────────────────────────
443
- // Pure registry logic lives in lib/registry.js (unit-tested): saved machines
444
- // are STANDBY connections; only an explicit "set current" activates one.
445
- // (issue #13 — Saved Connections != Active Remote Context)
446
- const MACHINES_FILE = 'machines.json'
447
- const machinesFile = () => path.join(remoteWorkspacesRoot(), MACHINES_FILE)
448
- const secretsDir = () => path.join(remoteWorkspacesRoot(), '.secrets')
449
- const forwardsFile = () => path.join(remoteWorkspacesRoot(), 'forwards.json')
450
- const auditFile = () => path.join(remoteWorkspacesRoot(), 'audit.log')
451
- const ignoreFile = () => path.join(remoteWorkspacesRoot(), '.dsh-remote-ignore')
452
-
453
- const loadMachines = () => _loadMachines(machinesFile())
454
- const saveMachines = (list, currentId, keepCurrentKey) => _saveMachines(machinesFile(), list, currentId, keepCurrentKey)
455
- const sanitizeMachine = _sanitizeMachine
456
- const applyMachine = _applyMachine
457
- const machineId = _machineId
458
-
459
- // ── host-key registry (TOFU) ──────────────────────────────────────────────
460
- const KNOWN_HOSTS_FILE = 'known_hosts.json'
461
- const knownHostsFile = () => path.join(remoteWorkspacesRoot(), KNOWN_HOSTS_FILE)
462
- // OpenSSH must append plain known_hosts lines, never the native JSON registry.
463
- const opensshKnownHostsFile = () => path.join(remoteWorkspacesRoot(), 'known_hosts')
464
- const isHostKeyKnown = (host, port) => _isHostKeyKnown(knownHostsFile(), host, port)
465
-
466
- // ── encoding helpers ───────────────────────────────────────────────────────
467
-
468
- function decodeBuf(buf, enc) {
469
- const e = enc && !/^utf-?8$/i.test(String(enc)) ? String(enc).toLowerCase() : null
470
- return e ? iconv.decode(buf, e) : buf.toString('utf8')
471
- }
472
- function encodeText(s, enc) {
473
- const e = enc && !/^utf-?8$/i.test(String(enc)) ? String(enc).toLowerCase() : null
474
- return e ? iconv.encode(String(s), e) : Buffer.from(String(s), 'utf8')
475
- }
476
-
477
- // ── apply ─────────────────────────────────────────────────────────────────
478
-
479
- export async function apply(ctx, config) {
480
- let autoUpdater
481
-
482
- // The ACTIVE pool: a delegating facade, because `backend` is per machine and
483
- // the plugin must keep ONE long-lived object to hang its hooks on (issue #51).
484
- const pool = new ActivePool(config, { knownHostsFile, opensshKnownHostsFile })
485
- ctx.effect(() => () => pool.close(), 'dsh-remote.close')
486
-
487
- migrateLegacyData()
488
-
489
- // ── 安装心跳(日活统计)─────────────────────────────────────────────────
490
- // 旁路:不 await、不阻塞加载、失败静默(见 lib/telemetry.js 的隐私与失败策略)。
491
- // 默认开启,但可以被关:profile 配置 `telemetry: false`(管理员)或设置页
492
- // 复选框(用户,持久化在 $DSH_HOME,优先于配置)。上报的是本插件专属 HMAC
493
- // 伪名,原始安装 id 与任何机器信息都不离开本机。
494
- if (telemetryAllowed(dshBase(), config.telemetry)) void sendHeartbeat(dshBase(), LOADED_VERSION)
495
-
496
- // ── terminal credential bridge (saved passwords for the `remote ssh` shell) ─
497
- // The generated terminal launcher spawns the OS ssh, which cannot receive the
498
- // plugin's saved passwords by itself. Bridge: a per-boot bearer token in
499
- // $DSH_HOME/remote-terminal/term-secret.json (0600) + a POST route that
500
- // resolves the machine through the SAME credential chain a real connect uses.
501
- // The askpass helper (written next to the launcher) is the only reader.
502
- const termSecretFile = () => path.join(remoteTerminalRoot(), 'term-secret.json')
503
- const termSecretToken = randomBytes(24).toString('hex')
504
- // A stale payload from a previous boot would name a dead port with a dead
505
- // token — and with SSH_ASKPASS_REQUIRE=force a failing bridge means NO tty
506
- // prompt at all. Always boot from absent; only a live webServer re-creates it
507
- // (Desktop compositions have no HTTP listener, so the bridge stays off there
508
- // and the terminal keeps its interactive prompt).
509
- try { rmSync(termSecretFile(), { force: true }) } catch { /* absent is fine */ }
510
- const writeTermSecretPayload = (origin) => {
511
- if (!origin) return false
512
- try {
513
- mkdirSync(remoteTerminalRoot(), { recursive: true })
514
- writeFileAtomic(termSecretFile(), JSON.stringify({ version: 1, url: String(origin).replace(/\/+$/, ''), token: termSecretToken }))
515
- try { chmodSync(termSecretFile(), 0o600) } catch { /* Windows: dir is already user-private */ }
516
- return true
517
- } catch { return false }
518
- }
519
- const termSecretOk = (presented) => {
520
- const dig = (s) => createHash('sha256').update(String(s)).digest()
521
- return timingSafeEqual(dig(presented), dig(termSecretToken))
522
- }
523
-
524
- // The update marker means "a newer version landed on disk but is not the code
525
- // running yet". Reaching apply() with a marker naming the version we just
526
- // loaded means the swap already happened (or this is a plain boot into the
527
- // updated files) → clear it, so the UI's "restart to finish" hint stays true.
528
- try {
529
- const marker = path.join(selfDir(), '.dsh-remote-updated')
530
- if (existsSync(marker) && readFileSync(marker, 'utf8').trim() === LOADED_VERSION) rmSync(marker, { force: true })
531
- } catch {}
532
-
533
- // ── machine registry (multi-host) ─────────────────────────────────────────
534
- const store = loadMachines()
535
- const machines = store.list
536
- const machineIndex = (id) => machines.findIndex((m) => m.id === id)
537
-
538
- // ── ssh-config aliases (issue #38) ────────────────────────────────────────
539
- //
540
- // A machine may be saved as an ALIAS (`useSshConfig: true`, `host` = the Host
541
- // line of ~/.ssh/config). The registry then holds NO HostName/user/port/key —
542
- // every connect resolves the alias against the config file as it is right now
543
- // (VSCode Remote-SSH behaviour). The text is memoised for a couple of seconds
544
- // so one request that resolves several machines reads the file once, while an
545
- // edit to ~/.ssh/config still lands almost immediately.
546
- let sshConfigCache = { text: '', at: 0 }
547
- const sshConfigText = () => {
548
- const now = Date.now()
549
- if (now - sshConfigCache.at > 2000) sshConfigCache = { text: readSshConfigText(), at: now }
550
- return sshConfigCache.text
551
- }
552
-
553
- /**
554
- * A machine's CONNECT identity: alias machines are resolved through
555
- * ~/.ssh/config; every other machine is returned untouched. The returned
556
- * record keeps the registry fields (id, password, credentialBackend, …) so
557
- * keychain lookups and the settings UI keep working.
558
- */
559
- const loggedSshWarnings = new Map()
560
- const warnSshOnce = (alias, warnings) => {
561
- // Warn once per distinct warning set: withSshConfig runs on every tool
562
- // call, and an unmatched alias would otherwise fill the log with the same
563
- // line.
564
- const signature = warnings.join(' | ')
565
- if (signature && loggedSshWarnings.get(alias) !== signature) {
566
- loggedSshWarnings.set(alias, signature)
567
- try {
568
- const logger = typeof ctx.get === 'function' ? ctx.get('logger') : undefined
569
- if (logger && typeof logger.warn === 'function') {
570
- logger.warn(`[dsh-remote] ssh-config alias "${alias}": ${warnings.join(' ')}`)
571
- }
572
- } catch { /* logging is best-effort */ }
573
- }
574
- }
575
- const withSshConfig = (m) => {
576
- if (!m) return m
577
- // Issue #50: ~/.ssh/config wins for ANY host it names, not only alias
578
- // machines. A literal machine's stored host/user/port/key is a COPY that
579
- // goes stale the moment the file is edited; when a Host block names the
580
- // machine's host (a bare `Host *` does not name it), the file's values
581
- // take over and the record fills the gaps.
582
- if (!m.useSshConfig) {
583
- const lit = resolveLiteralSshConfig(m, { text: sshConfigText() })
584
- if (!lit) return m
585
- warnSshOnce(lit.alias, lit.warnings)
586
- return {
587
- ...m,
588
- sshConfigMatched: true,
589
- sshConfigWarnings: lit.warnings,
590
- // The name the user typed, kept for the system-OpenSSH backend: ssh
591
- // must match its Host blocks against exactly this (connectTargetFor).
592
- sshConfigName: m.host,
593
- host: lit.host || m.host,
594
- port: lit.port || m.port,
595
- username: lit.username || m.username,
596
- privateKeyPath: lit.privateKeyPath || m.privateKeyPath,
597
- agentSocket: lit.agentSocket || '',
598
- identitiesOnly: !!lit.identitiesOnly,
599
- proxy: lit.proxy || m.proxy,
600
- }
601
- }
602
- const resolved = resolveMachineSshConfig(m, { text: sshConfigText() })
603
- if (!resolved) return m
604
- warnSshOnce(resolved.alias, resolved.warnings)
605
- return {
606
- ...m,
607
- sshAlias: resolved.alias,
608
- sshConfigMatched: resolved.matched,
609
- sshConfigWarnings: resolved.warnings,
610
- host: resolved.host,
611
- port: resolved.port,
612
- username: resolved.username || m.username,
613
- privateKeyPath: resolved.privateKeyPath || '',
614
- agentSocket: resolved.agentSocket || '',
615
- identitiesOnly: !!resolved.identitiesOnly,
616
- proxy: resolved.proxy,
617
- }
618
- }
619
-
620
- /**
621
- * The CONNECT target for a pool, given a machine's RESOLVED connect identity
622
- * (i.e. a record that already passed through withSshConfig()).
623
- *
624
- * Issue #38 resolves an alias machine into concrete host/user/port/key values
625
- * because the native backend has to dial them itself. Issue #51's
626
- * system-OpenSSH backend must NOT do that: it hands the name to `ssh`, and ssh
627
- * matches its `Host` blocks against exactly the name it was given. Passing the
628
- * resolved HostName instead would stop `Host myalias` blocks from matching and
629
- * silently drop the very settings (GSSAPIAuthentication=yes, ProxyCommand,
630
- * PKCS11Provider, Match blocks) that make this backend worth choosing. For an
631
- * alias machine on that backend the ALIAS is therefore the connect target, no
632
- * -l/-p/-i of our own is emitted, and ~/.ssh/config stays the single source of
633
- * truth for that machine (which is also exactly what issue #50 asks for).
634
- *
635
- * @param {object} eff - a record after withSshConfig() (`sshAlias` present for
636
- * alias machines).
637
- * @returns {{host: string, port: number, username: string, privateKeyPath: string, proxy: object|undefined, aliasNative: boolean}}
638
- */
639
- const connectTargetFor = (eff) => {
640
- // Issue #50: a LITERAL machine whose host a Host block names is in the same
641
- // position as an alias machine on the OpenSSH backend — ssh must match its
642
- // blocks against the ORIGINAL name, so it is handed over verbatim too.
643
- const aliasNative = !!(eff && isSystemOpenSshBackend(eff) && (eff.useSshConfig || eff.sshConfigMatched))
644
- if (!aliasNative) {
645
- return {
646
- host: String((eff && eff.host) || ''),
647
- port: Number((eff && eff.port) || 0) || 22,
648
- username: String((eff && eff.username) || ''),
649
- privateKeyPath: String((eff && eff.privateKeyPath) || ''),
650
- proxy: eff && eff.proxy,
651
- aliasNative: false,
652
- }
653
- }
654
- const alias = String((eff && (eff.sshAlias || eff.sshConfigName || eff.host)) || '')
655
- return {
656
- // The alias itself; ssh expands HostName/User/Port/IdentityFile and every
657
- // other directive while matching that Host block.
658
- host: alias,
659
- port: 0, // 0 → no -p is emitted, so Port comes from the config
660
- username: '', // '' → no -l is emitted, so User comes from the config
661
- privateKeyPath: '', // '' → no -i is emitted, so IdentityFile comes from it
662
- proxy: undefined, // a ProxyJump written in the config is honoured by ssh
663
- aliasNative: true,
664
- }
665
- }
666
-
667
- /**
668
- * Does this machine carry a credential the NATIVE (ssh2) backend can use?
669
- *
670
- * The native backend authenticates only through a password, a private key, an
671
- * agent or keyboard-interactive. A `~/.ssh/config` machine whose Host block
672
- * carries just HostName/User relies on OpenSSH's own default-identity
673
- * discovery (id_rsa/id_ed25519, the agent, AddKeysToAgent/UseKeychain), which
674
- * ssh2 does not implement — so dialing it with native reports "no credentials"
675
- * for a host that `ssh <alias>` reaches fine. The system-OpenSSH backend hands
676
- * the name to the user's own `ssh`, which authenticates exactly like that
677
- * command.
678
- *
679
- * @param {object} m - a machine record or request body carrying the fields.
680
- * @returns {boolean} true when native has something to authenticate with.
681
- */
682
- const nativeUsableCredential = (m) => !!(
683
- (m && String(m.password || '').trim())
684
- || (m && String(m.privateKeyPath || '').trim())
685
- || (m && m.useAgent)
686
- || (m && m.keyboardInteractive)
687
- // A keychain-backed machine stores an empty `password` by design.
688
- || (m && (m.secretStored || (m.credentialBackend && m.credentialBackend !== 'plain')))
689
- )
690
-
691
- /**
692
- * The backend a machine must dial with. Native stays whenever it has a usable
693
- * credential (or the machine explicitly asks for openssh); otherwise openssh,
694
- * because native provably cannot connect and would only report a missing
695
- * credential the user never needed.
696
- *
697
- * @param {object} m - machine record or request body.
698
- * @param {object} cfg - the plugin Config (its `backend` is the fallback).
699
- * @returns {string} 'openssh' | 'native'.
700
- */
701
- const backendFor = (m, cfg) => {
702
- const chosen = String((m && m.backend) || (cfg && cfg.backend) || 'native')
703
- if (chosen === 'openssh') return 'openssh'
704
- return nativeUsableCredential(m) ? 'native' : 'openssh'
705
- }
706
-
707
- /** The alias a machine was saved as ('' for a machine with literal values). */
708
- const aliasOf = (m) => (m && m.sshAlias) || (m && m.useSshConfig ? String(m.host || '') : '')
709
-
710
- /** Machines as the settings UI sees them: secrets stripped, plus the
711
- * ~/.ssh/config resolution of an alias machine (issue #38) — and, since
712
- * issue #50, of a LITERAL machine whose host a Host block names, so the row
713
- * can show that the file now drives it. */
714
- /**
715
- * Does this machine have a LIVE connection right now?
716
- *
717
- * The settings page must tell "I connected a minute ago" from "the socket is up as
718
- * we speak" — a row used to show only the last probe's latency, which is history,
719
- * not state. Two places can hold a connection for a machine: its own session-bound
720
- * pool (`machinePools`) and the active pool when it is the current machine. Both
721
- * are read here; nothing is dialed, so this costs nothing.
722
- */
723
- const isMachineLive = (m) => {
724
- if (!m || !m.host) return false
725
- try {
726
- const p = machinePools.get(poolKey(identityOf(m)))
727
- if (p && p.client) return true
728
- } catch { /* identity resolution is best-effort: a broken alias must not throw */ }
729
- return !!(store.currentId && m.id === store.currentId && pool.client)
730
- }
731
-
732
- const machinesForClient = () => machines.map((m) => ({
733
- ...sanitizeMachine(m),
734
- sshConfigResolved: m.useSshConfig
735
- ? resolveMachineSshConfig(m, { text: sshConfigText() })
736
- : resolveLiteralSshConfig(m, { text: sshConfigText() }),
737
- // Live socket, not a historical latency (see isMachineLive).
738
- connected: isMachineLive(m),
739
- }))
740
-
741
- /**
742
- * The `dsh` command to use for a machine's Web UI attach.
743
- *
744
- * Resolution order is deliberate: a PER-MACHINE value recorded by a completed
745
- * deployment wins, then the global config default. Without the per-machine
746
- * branch, deploying on one host would point every other host at a binary that
747
- * only exists on that one.
748
- *
749
- * @param {object} machine - a registry record (may be undefined).
750
- * @returns {string} the command to run on that machine.
751
- */
752
- const webAttachCommandFor = (machine) => {
753
- const perMachine = machine && typeof machine.webAttachCommand === 'string' ? machine.webAttachCommand.trim() : ''
754
- return perMachine || String(config.webAttachCommand || 'dsh')
755
- }
756
-
757
- /**
758
- * The machine's issue #125 discover command: a user-supplied one-liner that
759
- * prints the URL of an ALREADY-RUNNING remote `dsh web` when one exists.
760
- * Per-machine BY DESIGN (no global default): how a resident instance is
761
- * found depends on that host's own setup (systemd unit, boot script, a saved
762
- * URL file), so a global value would only ever point at the wrong answer.
763
- * Empty disables discovery and keeps the historical always-spawn behaviour.
764
- *
765
- * @param {object} machine - a registry record (may be undefined).
766
- * @returns {string} the discover command, or '' when unconfigured.
767
- */
768
- const webAttachDiscoverCommandFor = (machine) => (
769
- machine && typeof machine.webAttachDiscoverCommand === 'string' ? machine.webAttachDiscoverCommand.trim() : ''
770
- )
771
-
772
- /**
773
- * Record the dsh command a deployment produced, on that machine.
774
- *
775
- * Persisted through the same registry helper every other machine edit uses, so
776
- * the value survives a restart and appears in the settings UI like any other
777
- * field. `keepCurrentKey: false` preserves whichever machine is current —
778
- * deploying must never silently switch the user's active machine.
779
- *
780
- * @param {object} machine - the registry record to update.
781
- * @param {string} command - the working dsh command.
782
- */
783
- const persistWebAttachCommand = (machine, command) => {
784
- try {
785
- const i = machineIndex(machine.id)
786
- if (i < 0) return
787
- machines[i] = { ...machines[i], webAttachCommand: String(command || '') }
788
- saveMachines(machines, store.currentId, false)
789
- } catch { /* a failed persist only costs a re-deploy next time */ }
790
- }
791
-
792
- /** The machine the pool is currently bound to: an ephemeral tool connection
793
- * (rw_connect save:false) wins, then the stored current, then config default. */
794
- let ephemeral = null
795
- const activeMachine = () => {
796
- if (ephemeral) return withSshConfig(ephemeral)
797
- if (store.currentId) {
798
- const i = machineIndex(store.currentId)
799
- if (i >= 0) return withSshConfig(machines[i])
800
- }
801
- if (config.host) return withSshConfig({ id: machineId(), name: config.host, host: config.host, port: config.port, username: config.username, password: config.password, privateKeyPath: config.privateKeyPath, passphrase: config.passphrase })
802
- return null
803
- }
804
- const currentMachine = activeMachine
805
-
806
- /** Resolve a machine's effective password (keychain backend support). */
807
- const machinePassword = async (m) => {
808
- if (m && m.password) return m.password
809
- if (m && m.credentialBackend && m.credentialBackend !== 'plain') {
810
- const p = await getSecret(m.id, secretsDir())
811
- if (p) return p
812
- }
813
- return ''
814
- }
815
-
816
- // The pool resolves keychain-stored passwords lazily at connect time.
817
- pool.passwordResolver = async () => {
818
- const m = activeMachine()
819
- return machinePassword(m)
820
- }
821
-
822
- /** The identity fields pool.setTarget diffs. Used to snapshot the diff
823
- * baseline BEFORE applyMachine mutates the shared config in place. */
824
- const targetFields = (c) => ({
825
- host: c.host, port: c.port, username: c.username,
826
- password: c.password, privateKeyPath: c.privateKeyPath,
827
- passphrase: c.passphrase, workspace: c.workspace,
828
- useAgent: c.useAgent, keyboardInteractive: c.keyboardInteractive,
829
- proxy: c.proxy, hostKeyMode: c.hostKeyMode,
830
- // Issue #51: the backend is part of the target identity, so a machine switch
831
- // between backends must be seen as a change by setTarget.
832
- backend: c.backend, sshBinary: c.sshBinary,
833
- })
834
-
835
- /** Fingerprint of the machine record last applied to the shared pool config.
836
- * Re-applying an identical record is a no-op: the picker posts /current before
837
- * every /ls and used to rewrite the registry + re-read credentials + re-point
838
- * the pool on every autocomplete keystroke. A record change (settings edit)
839
- * changes the fingerprint, so the next /current re-applies it. The value is
840
- * maintained INSIDE applyActiveMachine / clearActiveMachine (not in
841
- * setCurrent) so every apply path — boot restore, rw_connect save:true,
842
- * POST /current — keeps the "fingerprint == applied" invariant without extra
843
- * bookkeeping. */
844
- let lastAppliedMachine = ''
845
-
846
- /** Fingerprint of the registry record the shared config is bound to ('' when
847
- * the binding is ephemeral or no machine is current). */
848
- const appliedFingerprint = () => {
849
- if (ephemeral || !store.currentId) return ''
850
- const i = machineIndex(store.currentId)
851
- return i >= 0 ? JSON.stringify(machines[i]) : ''
852
- }
853
-
854
- const applyActiveMachine = async () => {
855
- const m = activeMachine()
856
- if (!m || !m.host) return
857
- const pw = await machinePassword(m)
858
- // Snapshot the diff baseline BEFORE applyMachine mutates the shared config
859
- // IN PLACE: pool.config IS this config object, so setTarget would otherwise
860
- // compare the new values against themselves, find them equal and keep the
861
- // OLD connection alive across a machine switch (issue #25 hazard).
862
- const previous = targetFields(config)
863
- applyMachine(config, { ...m, password: pw || m.password || '' })
864
- // Issue #51: an ssh-config alias on the system-OpenSSH backend connects AS
865
- // the alias, so ssh — not the plugin — expands HostName/User/Port/
866
- // IdentityFile/ProxyJump, and the `Host` block keeps matching.
867
- const t = connectTargetFor(m)
868
- if (t.aliasNative) {
869
- config.host = t.host
870
- config.port = 22
871
- config.username = ''
872
- config.privateKeyPath = ''
873
- config.proxy = undefined
874
- }
875
- pool.setTarget(targetFields(config), previous)
876
- lastAppliedMachine = appliedFingerprint()
877
- }
878
-
879
- // ── per-machine SSH pools (session-bound) ─────────────────────────────────
880
- // The `pool` above stays the ACTIVE-machine pool: it backs the settings page,
881
- // the workspace picker routes, and `rw_connect`, whose semantics are "switch
882
- // the active machine". Session-bound tool calls must not go through it —
883
- // `setTarget()` rewrites the shared `config` identity and closes the live
884
- // connection, so two sessions on different machines would take the pool from
885
- // each other and commands would land on the wrong host (issue #25).
886
- //
887
- // Instead each machine gets its own pool, keyed by its stable identity. A
888
- // session resolves its machine from its own workspace mirror, so concurrent
889
- // sessions on different hosts never share a connection. Sessions on the SAME
890
- // machine still share one, preserving the single-connection + keepalive model.
891
-
892
- /** Deployment-varying tunables shared by every pool, owned by the live plugin
893
- * Config so a settings change reaches existing pools. Identity, credential,
894
- * and per-machine policy fields (`hostKeyMode`, `shell`, `proxy`) are
895
- * deliberately excluded — those are pinned per pool from the machine record,
896
- * and re-copying them from the shared config is exactly the bug this
897
- * registry fixes. */
898
- const TUNABLE_KEYS = [
899
- 'connectTimeoutMs', 'commandTimeoutMs', 'maxOutputChars', 'maxFileBytes', 'encoding',
900
- ]
901
- const syncTunables = (target) => {
902
- for (const k of TUNABLE_KEYS) {
903
- if (Object.prototype.hasOwnProperty.call(config, k)) target[k] = config[k]
904
- }
905
- return target
906
- }
907
-
908
- const machinePools = new Map()
909
- ctx.effect(() => () => {
910
- for (const p of machinePools.values()) {
911
- try { p.close() } catch { /* a pool already torn down by its own error path */ }
912
- }
913
- machinePools.clear()
914
- }, 'dsh-remote.machine-pools')
915
-
916
- /** Registry record for a resolved mirror origin, so a session-bound pool gets
917
- * the machine's real credentials (key path, passphrase, agent, proxy) rather
918
- * than only the host/user/port the mirror meta records.
919
- *
920
- * An EPHEMERAL connection (rw_connect save:false) is not in the registry but
921
- * is still a legitimate credential source for a pool the same process later
922
- * resolves for that identity: without it a mirror picked on a temporary
923
- * connection would resolve to an empty-credential pool and fail to connect.
924
- *
925
- * An ssh-config ALIAS machine (issue #38) is matched through its RESOLVED
926
- * identity, and directly by the alias the mirror recorded — so a mirror keeps
927
- * resolving to its machine even after a HostName/port change in ~/.ssh/config,
928
- * which is the whole point of not copying those values into the registry. */
929
- const identityOf = (m) => {
930
- const r = withSshConfig(m)
931
- return { host: r.host, port: Number(r.port) || 22, username: r.username || '' }
932
- }
933
- const identityMatches = (m, { host, port, username }) => {
934
- if (!m) return false
935
- const id = identityOf(m)
936
- return id.host === host && id.port === Number(port) && id.username === (username || '')
937
- }
938
- const machineRecordFor = ({ host, port, username, alias }) =>
939
- (identityMatches(ephemeral, { host, port, username }) ? ephemeral : null)
940
- || (alias ? machines.find((m) => aliasOf(m) === alias) : null)
941
- || machines.find((m) => identityMatches(m, { host, port, username }))
942
- || null
943
-
944
- /**
945
- * Get (or lazily create) the dedicated pool for one remote identity.
946
- * @param {{host: string, port: number, username: string}} target - the mirror-recorded origin.
947
- * @returns {SshPool} the pool pinned to that identity; never the active-machine pool.
948
- */
949
- const poolForMachine = (target) => {
950
- const key = poolKey(target)
951
- // `rec` is the registry record (raw); `eff` is its CONNECT identity, with an
952
- // ssh-config alias resolved (issue #38). For an alias whose HostName/USER/port
953
- // changed since the mirror was created, the RESOLVED identity wins over the
954
- // mirror-recorded one — that is what makes an edit to ~/.ssh/config take
955
- // effect for an existing session instead of dialing the stale address.
956
- const rec = machineRecordFor(target)
957
- const eff = rec ? withSshConfig(rec) : null
958
- // Issue #51: on the system-OpenSSH backend an alias machine connects AS its
959
- // alias so ~/.ssh/config (not the registry) supplies host/user/port/key.
960
- const t = connectTargetFor(eff || target)
961
- const host = t.aliasNative ? t.host : ((eff && eff.host) || target.host)
962
- const port = t.aliasNative ? 0 : (Number((eff && eff.port) || target.port) || 22)
963
- const username = t.aliasNative ? '' : ((eff && eff.username) || target.username || 'root')
964
- const existing = machinePools.get(key)
965
- if (existing) {
966
- syncTunables(existing.config)
967
- // Credentials and per-machine policy are re-read from the registry BEFORE
968
- // re-pointing: editing a machine in the settings page must reach a pool
969
- // created earlier, and a pool holding a stale password would keep failing
970
- // to reconnect. The backend belongs in this group too — ActivePool picks
971
- // its delegate class from `config.backend` during setTarget/_sync, so
972
- // assigning it afterwards would hand the OLD backend the new target.
973
- if (eff) {
974
- existing.config.password = eff.password || ''
975
- existing.config.privateKeyPath = t.aliasNative ? '' : (eff.privateKeyPath || '')
976
- existing.config.passphrase = eff.passphrase || ''
977
- existing.config.useAgent = !!eff.useAgent
978
- existing.config.agentSocket = t.aliasNative ? '' : (eff.agentSocket || '')
979
- existing.config.identitiesOnly = !!eff.identitiesOnly
980
- existing.config.keyboardInteractive = !!eff.keyboardInteractive
981
- existing.config.proxy = t.aliasNative ? undefined : (eff.proxy || undefined)
982
- existing.config.hostKeyMode = eff.hostKeyMode || config.hostKeyMode
983
- existing.config.backend = eff.backend || config.backend
984
- existing.config.sshBinary = (typeof eff.sshBinary === 'string') ? eff.sshBinary : config.sshBinary
985
- }
986
- // Re-point a live pool whose resolved identity moved (setTarget closes the
987
- // connection, so only do it when something actually changed).
988
- if (existing.config.host !== host || Number(existing.config.port) !== port || (existing.config.username || '') !== username) {
989
- existing.setTarget({ host, port, username })
990
- }
991
- return existing
992
- }
993
- const poolConfig = syncTunables({
994
- ...config,
995
- host,
996
- port,
997
- username,
998
- password: (eff && eff.password) || '',
999
- privateKeyPath: t.aliasNative ? '' : ((eff && eff.privateKeyPath) || ''),
1000
- passphrase: (eff && eff.passphrase) || '',
1001
- useAgent: eff ? !!eff.useAgent : !!config.useAgent,
1002
- agentSocket: t.aliasNative ? '' : ((eff && eff.agentSocket) || ''),
1003
- identitiesOnly: !!(eff && eff.identitiesOnly),
1004
- keyboardInteractive: eff ? !!eff.keyboardInteractive : !!config.keyboardInteractive,
1005
- proxy: t.aliasNative ? undefined : ((eff && eff.proxy) || undefined),
1006
- hostKeyMode: (eff && eff.hostKeyMode) || config.hostKeyMode,
1007
- // Issue #51: the transport backend is a per-machine choice — an
1008
- // enterprise Kerberos host needs `openssh` while its neighbours stay on
1009
- // the native backend.
1010
- backend: backendFor(eff, config),
1011
- sshBinary: (eff && typeof eff.sshBinary === 'string') ? eff.sshBinary : config.sshBinary,
1012
- // Identity-pinned pools never carry the shared active workspace: a
1013
- // session passes its own mirror-resolved remote path explicitly.
1014
- workspace: '',
1015
- })
1016
- const created = new ActivePool(poolConfig, { knownHostsFile, opensshKnownHostsFile })
1017
- // Keychain-backed passwords resolve against THIS pool's machine record.
1018
- created.passwordResolver = async () => machinePassword(eff || { id: '', password: poolConfig.password })
1019
- machinePools.set(key, created)
1020
- return created
1021
- }
1022
-
1023
- /**
1024
- * Re-assert the ACTIVE machine that a machine-scoped request names.
1025
- *
1026
- * The workspace picker (and the settings page's workspace flow) acts on the
1027
- * shared active pool, but it remembers its own `machineId` locally. Nothing
1028
- * on `/mirror` / `/home` / `/fs` used to carry that identity, so a switch
1029
- * performed by ANOTHER actor between the picker's last fetch and its commit —
1030
- * the settings page's "set as current", or an `rw_connect` in another agent
1031
- * session — silently redirected the commit onto that other machine. Before
1032
- * this PR the picker re-posted /current on every keystroke, which masked the
1033
- * window; the per-keystroke reconnect fix removes that accident. Let the
1034
- * request state its intent so the host can honour it atomically instead.
1035
- *
1036
- * An absent / empty `machineId` keeps the old behaviour (the caller is
1037
- * machine-scoped through the active pool by design). An UNKNOWN id is
1038
- * refused rather than ignored: quietly mirroring onto whichever machine
1039
- * happens to be active is exactly the hazard this closes.
1040
- *
1041
- * @returns {Promise<boolean>} false when the request was already answered.
1042
- */
1043
- const applyRequestedMachine = async (body, res) => {
1044
- const id = String((body && body.machineId) || '').trim()
1045
- if (!id) return true
1046
- if (await setCurrent(id)) return true
1047
- sendJson(res, 404, { ok: false, error: `machine not found: ${id}` })
1048
- return false
1049
- }
1050
-
1051
- const setCurrent = async (id) => {
1052
- if (!id) {
1053
- // Explicit "active remote = none": saved machines stay in the registry
1054
- // (issue #13) but nothing is bound to the pool anymore.
1055
- store.currentId = null
1056
- ephemeral = null
1057
- saveMachines(machines, null)
1058
- await clearActiveMachine()
1059
- return true
1060
- }
1061
- const i = machineIndex(id)
1062
- if (i < 0) return false
1063
- // Idempotent: same machine, no ephemeral override, already applied → keep
1064
- // the registry file, the credentials cache and the live pool untouched.
1065
- // (The fingerprint is maintained by applyActiveMachine itself.)
1066
- const fingerprint = JSON.stringify(machines[i])
1067
- if (store.currentId === id && !ephemeral && config.host && lastAppliedMachine === fingerprint) return true
1068
- store.currentId = id
1069
- ephemeral = null
1070
- saveMachines(machines, id)
1071
- await applyActiveMachine()
1072
- return true
1073
- }
1074
-
1075
- /** Unbind the pool + live config from any machine: the plugin starts in a
1076
- * pure "no remote context" state (issue #13). The host stays configured for
1077
- * tool fallback, but no machine workspace leaks into this session. */
1078
- const clearActiveMachine = async () => {
1079
- ephemeral = null
1080
- // Nothing is applied anymore — reset the applied-machine fingerprint too.
1081
- lastAppliedMachine = ''
1082
- if (!config.host) return
1083
- // Snapshot the diff baseline BEFORE zeroing: pool.config IS this config
1084
- // object, so setTarget would otherwise see an already-zeroed config and
1085
- // keep the old connection alive ("active remote = none" must disconnect).
1086
- const previous = targetFields(config)
1087
- // Clear host + workspace directly (applyMachine keeps the old workspace
1088
- // when the incoming value is empty — it must not be used for a full reset).
1089
- config.host = ''
1090
- config.port = 22
1091
- config.username = ''
1092
- config.password = ''
1093
- config.workspace = ''
1094
- pool.setTarget({ host: '', port: 22, username: '', workspace: '' }, previous)
1095
- // Also stop any auto-push watcher bound to the old machine workspace.
1096
- // (autoPushWatchers is declared later; read it lazily to avoid TDZ.)
1097
- if (typeof autoPushWatchers !== 'undefined' && autoPushWatchers) {
1098
- for (const [, entry] of autoPushWatchers) {
1099
- if (!entry) continue
1100
- try { entry.watcher && entry.watcher.close() } catch {}
1101
- if (entry.timer) clearTimeout(entry.timer)
1102
- }
1103
- autoPushWatchers.clear()
1104
- }
1105
- }
1106
-
1107
- // If no stored current, adopt a CLI-provided default as the active machine —
1108
- // UNLESS the user explicitly cleared the current machine (currentId: null in
1109
- // the registry = "active remote = none", issue #13). A registry that exists
1110
- // with currentId null must stay inert; only a fresh/absent registry lets the
1111
- // config host serve as the bootstrap default.
1112
- {
1113
- const cur = currentMachine()
1114
- const registryExplicitNone = store.explicitNone
1115
- if (cur && cur.host && !store.currentId && !registryExplicitNone) applyMachine(config, cur)
1116
- }
1117
-
1118
- // ── auto-restore the last active machine (best-effort) ───────────────────
1119
- // When the harness (re)starts, bring back the machine that was "current"
1120
- // last time: apply its config to the pool and probe a real SSH connection so
1121
- // the sidebar shows connected instead of a disconnected 500-spamming state.
1122
- // Failures are swallowed — an unreachable host must never break plugin boot
1123
- // (the sidebar will show「未连接」and the user can reconnect or set current).
1124
- if (store.currentId) {
1125
- const i = machineIndex(store.currentId)
1126
- if (i >= 0 && machines[i] && machines[i].host) {
1127
- setImmediate(async () => {
1128
- try {
1129
- await applyActiveMachine()
1130
- await pool.exec('echo dsh-remote-restore', { timeoutMs: Math.min(config.commandTimeoutMs || 20000, 15000) })
1131
- } catch {
1132
- // Offline / bad credentials: leave pool unconnected; UI falls back
1133
- // to the "未连接" state and the user can reconnect manually.
1134
- }
1135
- })
1136
- }
1137
- }
1138
-
1139
- /** Persist the active workspace on the machine the pool is actually bound to
1140
- * (fixes the old bug where a tool-connected machine saved its workspace onto
1141
- * the registry's current machine instead). */
1142
- const persistWorkspace = (p, selectedMachine) => {
1143
- const m = selectedMachine || activeMachine()
1144
- if (!selectedMachine || (m && activeMachine() && m.id === activeMachine().id)) config.workspace = p
1145
- if (m) {
1146
- if (m.id && machineIndex(m.id) >= 0) {
1147
- const rec = machines[machineIndex(m.id)]
1148
- rec.workspace = p
1149
- rec.recentWorkspaces = [p, ...(rec.recentWorkspaces || []).filter((x) => x !== p)].slice(0, 8)
1150
- saveMachines(machines, store.currentId)
1151
- } else if (ephemeral) {
1152
- ephemeral.workspace = p
1153
- }
1154
- }
1155
- }
1156
-
1157
- // ── audit log ─────────────────────────────────────────────────────────────
1158
- /**
1159
- * Append one audit line. `target` names the machine the operation really ran
1160
- * on and must be passed by every session-bound caller: the shared `config`
1161
- * identity belongs to the ACTIVE machine, which can be a different host than
1162
- * the session that issued the command, so defaulting to it would
1163
- * misattribute the operation.
1164
- * @param {string} op - operation name.
1165
- * @param {string} cmd - command text or path detail.
1166
- * @param {number|null} code - exit code, or null when not applicable.
1167
- * @param {{host?: string, username?: string, port?: number}} [target] - machine acted on; defaults to the active machine.
1168
- */
1169
- const audit = (op, cmd, code, target) => {
1170
- if (!config.auditLog) return
1171
- const host = (target && target.host) || config.host
1172
- const user = (target && target.username) || config.username
1173
- const port = (target && target.port) || config.port
1174
- try {
1175
- appendFileSync(auditFile(), formatAuditLine({ op, cmd, code, user, host, port }), 'utf8')
1176
- } catch {}
1177
- }
1178
-
1179
- /**
1180
- * The core background-job registry, or null when this composition has none.
1181
- *
1182
- * Issue #70: `ctx.jobs` is an OPTIONAL service — a minimal embedding, a test
1183
- * double, or a plugin-only harness may mount no registry at all. Resolving it
1184
- * lazily (rather than as an injected dependency) keeps the plugin loadable
1185
- * there and degrades `rw_exec` to foreground-only, which is exactly the
1186
- * pre-#70 behaviour instead of a hard failure at load time.
1187
- *
1188
- * @returns {object|null} the registry, or null.
1189
- */
1190
- const jobRegistry = () => {
1191
- try {
1192
- const jobs = ctx.get('jobs')
1193
- return jobs && typeof jobs.start === 'function' ? jobs : null
1194
- } catch {
1195
- return null
1196
- }
1197
- }
1198
- /**
1199
- * One-line-per-group inventory of the saved machines: which environments,
1200
- * locations and tags exist. This is what makes the filters discoverable — a
1201
- * user who has never set a label sees nothing to filter by, so the empty
1202
- * result reports what IS there.
1203
- *
1204
- * @param {Array<object>} list
1205
- * @returns {string} '' when no machine carries any label.
1206
- */
1207
- const groupSummary = (list) => {
1208
- const envs = new Map(); const locs = new Map(); const tags = new Map()
1209
- const bump = (map, key) => { if (key) map.set(key, (map.get(key) || 0) + 1) }
1210
- for (const m of Array.isArray(list) ? list : []) {
1211
- if (!m) continue
1212
- bump(envs, m.environment)
1213
- bump(locs, m.location)
1214
- for (const t of (Array.isArray(m.tags) ? m.tags : [])) bump(tags, t)
1215
- }
1216
- const fmt = (label, map) => (map.size ? ` ${label}: ` + [...map.entries()].map(([k, n]) => `${k} (${n})`).join(', ') : '')
1217
- return [fmt('environment', envs), fmt('location', locs), fmt('tags', tags)].filter(Boolean).join('\n')
1218
- }
1219
-
1220
- const readAudit = (limit) => readAuditLines(readFileSync, auditFile(), limit)
1221
-
1222
- // ── ignore rules (defaults + user file) ───────────────────────────────────
1223
- // NOTE: this matcher is shared by mirror sync (rw_sync/rw_push) and search.
1224
- // Do NOT add search-only cache excludes here: widening it would silently stop
1225
- // syncing directories a user may rely on. Search uses searchIgnoreMatcher().
1226
- const readUserIgnore = () => {
1227
- try {
1228
- return readFileSync(ignoreFile(), 'utf8').split('\n').map((l) => l.trim()).filter((l) => l && !l.startsWith('#'))
1229
- } catch {
1230
- return []
1231
- }
1232
- }
1233
- /** Mirror-sync matcher for the workspace rooted at `root` (ROOT_IGNORE is
1234
- * merged only for a filesystem-root workspace — issue #60). */
1235
- const ignoreMatcher = (root) => compileIgnore(ignorePatternsFor(root, { fromFile: readUserIgnore() }))
1236
- /** Search-only matcher: same as ignoreMatcher() plus machine-local cache trees
1237
- * (`~/.npm`, `~/.cache`, …) that are huge, almost never what a human is
1238
- * looking for, and the main cause of the issue #44 hang. Mirror sync is
1239
- * deliberately unaffected. An explicit `path` still searches anywhere. */
1240
- const searchIgnoreMatcher = (root) => compileIgnore(ignorePatternsFor(root, { search: true, fromFile: readUserIgnore() }))
1241
-
1242
- // ── task + forward managers ───────────────────────────────────────────────
1243
- const tasks = new TaskManager()
1244
- const workspaceSearches = new WorkspaceSearches({ maxEntries: config.searchMaxEntries || 50000, timeoutMs: Math.min(config.searchTimeoutMs || 30000, 60000), maxReadBytes: Math.min(config.maxFileBytes > 0 ? config.maxFileBytes : 256 * 1024, 256 * 1024), decodeBuf, encoding: config.encoding })
1245
- ctx.effect(() => () => workspaceSearches.dispose(), 'dsh-remote.workspace-searches')
1246
- const forwards = new ForwardManager(pool, { file: forwardsFile() })
1247
- pool.onReady = (client) => forwards.attach(client)
1248
- pool.onCloseHook = () => forwards.detach()
1249
-
1250
- // ── remote DSH Web UI attach sessions (issue #46) ─────────────────────────
1251
- // "Use this DSH as a CLIENT for a DSH on another machine". The remote never
1252
- // opens an inbound port (DSH forbids `--host 0.0.0.0`); we SSH out, start or
1253
- // reuse a loopback-bound `dsh web` there, and carry its socket back over our
1254
- // own SSH connection to a loopback listener here. One session per machine —
1255
- // attaching again to the same machine reuses the live tunnel instead of
1256
- // starting a second remote server. Lifecycle is owned by the plugin fiber, so
1257
- // unloading the plugin tears every tunnel down.
1258
- const webAttaches = new Map() // machineId → WebAttach
1259
- // Deploy tasks run on the HOST, detached from any request: closing the browser
1260
- // window mid-install must not lose the progress, and a re-opened page must be
1261
- // able to re-attach and see the live state (high-availability requirement).
1262
- ctx.effect(() => () => {
1263
- for (const attach of webAttaches.values()) { try { attach.close() } catch { /* already gone */ } }
1264
- webAttaches.clear()
1265
- }, 'dsh-remote.web-attach')
1266
-
1267
- // ── auto-push watcher (config.autoPush, default off) ──────────────────────
1268
- // Watches the local mirror; local edits are pushed back to the remote after a
1269
- // 3s debounce, honoring ignore rules + the three-way conflict guard (a remote
1270
- // change is never clobbered — it is recorded as a conflict in the audit log).
1271
- const syncActivity = createSyncActivity()
1272
- const autoPushWatchers = new Map() // localDir → { watcher, pending:Set, timer }
1273
- const flushAutoPush = async (localDir) => {
1274
- const entry = autoPushWatchers.get(localDir)
1275
- if (!entry || !entry.pending.size) return
1276
- const rels = [...entry.pending]
1277
- entry.pending.clear()
1278
- // Resolve the destination from the WATCHED MIRROR, not from the active
1279
- // machine: a watcher outlives any one session, so gating on the active
1280
- // machine made it silently stop pushing (and, before per-machine pools,
1281
- // risked pushing one host's mirror through another host's connection).
1282
- const { remotePath: ws, machine } = resolveMirrorForLocal(localDir)
1283
- if (!ws || !machine) return
1284
- return syncActivity.run(localDir, 'auto-push', async (record) => {
1285
- const target = poolForMachine(machine)
1286
- const sftp = await target.sftp()
1287
- const stats = { files: 0, conflicts: [] }
1288
- const matcher = ignoreMatcher(ws)
1289
- const state = loadSyncState(localDir)
1290
- const next = { ...state }
1291
- if (rels.includes('*')) {
1292
- const r = await pushTree(sftp, localDir, ws, { maxFiles: 2000, maxFileBytes: config.maxFileBytes, isIgnored: matcher, state: next })
1293
- Object.assign(next, r.nextState)
1294
- Object.assign(stats, r.stats)
1295
- for (const c of r.stats.conflicts) audit('auto-push-conflict', `push ${c.path}`, 1, machine)
1296
- } else {
1297
- for (const rel of rels) {
1298
- const r = await pushOneFile(sftp, localDir, ws, rel, { maxFileBytes: config.maxFileBytes, isIgnored: matcher, state: next })
1299
- if (r.status === 'pushed' && r.state) { Object.assign(next, r.state); stats.files++ }
1300
- else if (r.status === 'conflict') { stats.conflicts.push({ path: rel, reason: r.reason }); audit('auto-push-conflict', `push ${rel}`, 1, machine) }
1301
- else if (r.error) { stats.failed = (stats.failed || 0) + 1; stats.abortedError = r.error }
1302
- }
1303
- }
1304
- record(stats)
1305
- saveSyncState(localDir, next)
1306
- if (remoteSkills) remoteSkills.invalidate()
1307
- }).catch(() => { /* observed as failed; do not create an unhandled watcher rejection */ })
1308
- }
1309
- const startAutoPush = (localDir) => {
1310
- if (!config.autoPush || autoPushWatchers.has(localDir)) return
1311
- const entry = { pending: new Set(), timer: null, watcher: null }
1312
- const schedule = () => {
1313
- if (entry.timer) clearTimeout(entry.timer)
1314
- entry.timer = setTimeout(() => flushAutoPush(localDir), 3000)
1315
- }
1316
- const onEvent = (eventType, filename) => {
1317
- if (!filename) { entry.pending.add('*'); return schedule() }
1318
- const rel = String(filename).replace(/\\/g, '/')
1319
- if (rel === '.dsh-remote-meta.json' || rel === '.dsh-remote-sync-state.json' || rel.startsWith('.dsh-remote-sync-state.json.tmp')) return
1320
- entry.pending.add(rel)
1321
- schedule()
1322
- }
1323
- try {
1324
- entry.watcher = watch(localDir, { recursive: true }, onEvent)
1325
- } catch {
1326
- try { entry.watcher = watch(localDir, onEvent) } catch { return }
1327
- }
1328
- autoPushWatchers.set(localDir, entry)
1329
- }
1330
- ctx.effect(() => () => {
1331
- for (const e of autoPushWatchers.values()) {
1332
- if (e.timer) clearTimeout(e.timer)
1333
- try { e.watcher && e.watcher.close() } catch {}
1334
- }
1335
- autoPushWatchers.clear()
1336
- }, 'dsh-remote.autopush')
1337
-
1338
- // ── remote instruction-file index (issue #68) ────────────────────────────
1339
- // The core AGENTS.md loader only sees the LOCAL mirror, so a remote repo's
1340
- // instruction files never reach the model's context. This index shallow-
1341
- // scans a bound workspace (root + ≤2 levels, AGENTS.md / CLAUDE.md only),
1342
- // mirrors the finds into the local mirror (where the core loader looks),
1343
- // and lists them in the system-prompt section below. See lib/instructions.js.
1344
- const instructionIndex = createInstructionIndex()
1345
-
1346
- // Issue #71: per-session record of which remote instruction files were
1347
- // already delivered, plus the sweep throttle. See the tools/result hook below.
1348
- const instructionTracker = createInjectionTracker()
1349
-
1350
- // Embedded interactive terminal sessions (P1). Host-owned PTY channels; the
1351
- // browser polls for output. Disposed with the plugin fiber so an unload hangs
1352
- // up every remote shell.
1353
- const terminals = createTerminalManager()
1354
- ctx.effect(() => () => { try { terminals.dispose() } catch { /* already gone */ } }, 'dsh-remote.terminals')
1355
-
1356
- /**
1357
- * The core's user-message factory, when this composition exposes one.
1358
- *
1359
- * Issue #71's design leans on the message being a NORMAL user message with a
1360
- * plugin-owned `source.kind` (consumers fall through unknown kinds; the
1361
- * core's reconcile only claims `agent-instructions`). `createUserMessage`
1362
- * lives in `@deepseek-ai/dsh-llm`. On 0.2.x it is a module export, not a
1363
- * method of the `llm` service (issue #75) — the service probe misses it and
1364
- * the module loader is the path that actually stamps `message.id`. Session
1365
- * restore rejects a user message with no id, so a null return here is only
1366
- * safe because `buildInstructionMessage` still writes one.
1367
- *
1368
- * @returns {Function|null} the factory, or null to use the built-in shape.
1369
- */
1370
- const userMessageFactory = () => {
1371
- try {
1372
- const fromService = pickUserMessageFactory(ctx.get('llm'))
1373
- if (fromService) return fromService
1374
- } catch { /* llm is optional; the module export or the built-in id still applies */ }
1375
- return loadBundledUserMessageFactory()
1376
- }
1377
-
1378
- // Helpers shared by session-bound tools and the machine-scoped web routes take
1379
- // the pool explicitly (`p`), defaulting to the active-machine pool so route
1380
- // callers — which are machine-scoped by design — stay unchanged.
1381
- const run = async (cmd, opts = {}, p = pool) => {
1382
- const res = await p.exec(cmd, opts.timeoutMs ? { timeoutMs: opts.timeoutMs } : {})
1383
- const parts = []
1384
- if (res.stdout) parts.push(res.stdout.replace(/\s+$/, ''))
1385
- if (res.stderr) parts.push('-- stderr --\n' + res.stderr.replace(/\s+$/, ''))
1386
- if (!parts.length) parts.push('(no output)')
1387
- let text = parts.join('\n')
1388
- if (res.signal === 'TIMEOUT') text += `\n[command timed out after ${opts.timeoutMs ?? config.commandTimeoutMs}ms]`
1389
- else if (res.code !== 0) text += `\n[exit code: ${res.code}]`
1390
- return text
1391
- }
1392
-
1393
- const isRemoteDir = async (p, sshPool = pool) => {
1394
- const target = normalizeRemotePath(p)
1395
- try {
1396
- const sftp = await sshPool.sftp()
1397
- const st = await sftp.stat(target)
1398
- return !!(st && st.isDirectory && st.isDirectory())
1399
- } catch {
1400
- return false
1401
- }
1402
- }
1403
-
1404
- // A picker owns its directory probe connection. Cancelling it must never
1405
- // invalidate a pool used by another conversation, terminal or file editor.
1406
- const prepareMirrorTarget = async (remotePath, selectedMachine, signal) => {
1407
- const machine = { ...(selectedMachine || activeMachine() || config) }
1408
- const identity = identityOf(machine)
1409
- const base = poolForMachine({ ...identity, alias: aliasOf(machine) })
1410
- const isolated = createPool({ ...base.config }, { knownHostsFile, opensshKnownHostsFile })
1411
- isolated.passwordResolver = base.passwordResolver
1412
- let rejectAbort
1413
- const cancelled = new Promise((_, reject) => { rejectAbort = reject })
1414
- const abort = () => { isolated.close(); rejectAbort(Object.assign(new Error('Opening cancelled'), { name: 'AbortError' })) }
1415
- signal.addEventListener('abort', abort, { once: true })
1416
- try {
1417
- if (signal.aborted) { abort(); await cancelled }
1418
- const stat = await Promise.race([isolated.sftp().then((sftp) => sftp.stat(remotePath)), cancelled])
1419
- return { machine, identity, ok: !!(stat && stat.isDirectory && stat.isDirectory()) }
1420
- } catch (err) {
1421
- if (signal.aborted) throw err
1422
- return { machine, identity, ok: false, error: friendlyMessage(err, identity) }
1423
- } finally {
1424
- signal.removeEventListener('abort', abort)
1425
- isolated.close()
1426
- }
1427
- }
1428
-
1429
- // ── remote workspace state ────────────────────────────────────────────────
1430
- const wsPath = () => (config.workspace || '').trim()
1431
- /** Map a LOCAL path to the remote path its mirror represents ('' when the
1432
- * path is not inside any dsh-remote mirror). Shared by the resolve-mirror
1433
- * route, the session-aware system-prompt injection, and status().
1434
- *
1435
- * `machine` carries the mirror's recorded origin (`host`/`port`/`username`
1436
- * from `.dsh-remote-meta.json`), or null when the path is not inside a
1437
- * mirror. That origin is what makes a session's remote target authoritative
1438
- * without consulting the mutable active-machine state, so a concurrent
1439
- * session switching machines cannot redirect this session's commands. */
1440
- const resolveMirrorForLocal = (local) => resolveMirror(local, remoteWorkspacesRoot())
1441
-
1442
- // Issue #120: project skills live on the REMOTE host, not only in the local
1443
- // mirror. The optional provider supplements (never replaces) the core's local
1444
- // filesystem provider and is inert on hosts without the skills service.
1445
- const remoteSkills = registerRemoteSkills(ctx, {
1446
- resolveBinding: resolveMirrorForLocal,
1447
- poolForMachine,
1448
- logger: typeof ctx.get === 'function' ? ctx.get('logger') : undefined,
1449
- })
1450
-
1451
- /**
1452
- * The whole local-mirror registry with each mirror's recorded remote origin
1453
- * (issue #49).
1454
- *
1455
- * The sidebar's Session rows need to know, for EVERY visible row, whether that
1456
- * session is a remote one and which host it is bound to. Asking
1457
- * `/resolve-mirror` per row would issue one HTTP request per row and would
1458
- * also depend on the host still knowing that session id; instead the client
1459
- * already holds each row's cwd (the sessions snapshot) and matches it against
1460
- * this directory list locally, so the whole sidebar costs ONE request.
1461
- *
1462
- * Mirrors whose meta is missing/unparsable (or has no `host`) are SKIPPED
1463
- * rather than guessed at — the same rule `resolveMirror()` applies, and for
1464
- * the same reason: labelling a session with a host it is not bound to is
1465
- * worse than showing no badge at all.
1466
- *
1467
- * @returns {Array<{dir: string, host: string, port: number, username: string,
1468
- * remotePath: string, alias: string, name: string}>} one entry per mirror.
1469
- */
1470
- const mirrorRegistry = () => {
1471
- const out = []
1472
- const root = remoteWorkspacesRoot()
1473
- if (!existsSync(root)) return out
1474
- let hostDirs = []
1475
- try { hostDirs = readdirSync(root) } catch { return out }
1476
- for (const hostDir of hostDirs) {
1477
- const hostPath = path.join(root, hostDir)
1478
- if (!statSync(hostPath, { throwIfNoEntry: false })?.isDirectory?.()) continue
1479
- let entries = []
1480
- try { entries = readdirSync(hostPath) } catch { continue }
1481
- for (const entry of entries) {
1482
- const dir = path.join(hostPath, entry)
1483
- const metaPath = path.join(dir, '.dsh-remote-meta.json')
1484
- if (!existsSync(metaPath)) continue
1485
- try {
1486
- const meta = JSON.parse(readFileSync(metaPath, 'utf8'))
1487
- if (!meta || !meta.host) continue
1488
- const origin = {
1489
- host: String(meta.host),
1490
- port: Number(meta.port) || 22,
1491
- username: String(meta.username || ''),
1492
- alias: String(meta.alias || ''),
1493
- }
1494
- const rec = machineRecordFor(origin)
1495
- out.push({
1496
- dir: path.resolve(dir),
1497
- host: origin.host,
1498
- port: origin.port,
1499
- username: origin.username,
1500
- remotePath: String(meta.remotePath || ''),
1501
- alias: origin.alias,
1502
- // A saved machine's display name, when this mirror resolves to one:
1503
- // the UI prefers the friendly name over the raw address in its
1504
- // tooltip (the row itself shows the address, which is what the
1505
- // reader asked for).
1506
- name: rec && rec.name ? String(rec.name) : '',
1507
- })
1508
- } catch { /* unparsable meta → not a usable binding */ }
1509
- }
1510
- }
1511
- return out
1512
- }
1513
-
1514
- /**
1515
- * Rebind every mirror recorded for one machine identity to a NEW identity
1516
- * (issue #67): when a machine's IP/user/port changes, its workspaces must
1517
- * follow instead of being recreated. The mirror's `.dsh-remote-meta.json` is
1518
- * the authoritative binding — session routing (bindingFor), pool keying
1519
- * (poolForMachine) and the sidebar badges all read identity FROM THE META,
1520
- * not from the directory name — so rewriting the meta re-points every live
1521
- * session at the new address while the local mirror content stays put.
1522
- *
1523
- * The host directory itself is deliberately NOT renamed: live sessions hold
1524
- * cwd paths inside it, and a rename would dangle them into "session is
1525
- * LOCAL" refusals (on Windows the rename usually fails outright while a
1526
- * shell sits inside). The directory name is a display label only; a stale
1527
- * label after a rebind is the documented cost of keeping sessions alive.
1528
- *
1529
- * Matching covers both machine kinds: an ALIAS machine's mirrors are found
1530
- * through the recorded `alias` (their meta host is the resolved address at
1531
- * creation time), a literal machine's through host+port+username.
1532
- *
1533
- * @param {object} prev - the machine record BEFORE the identity change.
1534
- * @param {object} next - the machine record AFTER it.
1535
- * @returns {number} how many mirrors were rebound.
1536
- */
1537
- const rebindMirrors = (prev, next) => {
1538
- if (!prev || !next) return 0
1539
- const prevAlias = aliasOf(prev)
1540
- const prevId = identityOf(prev)
1541
- const prevRaw = { host: String(prev.host || ''), port: Number(prev.port) || 22, username: String(prev.username || '') }
1542
- const nextAlias = aliasOf(next)
1543
- const nextEff = withSshConfig(next) || next
1544
- const nextId = {
1545
- host: String(nextEff.host || next.host || ''),
1546
- port: Number(nextEff.port || next.port) || 22,
1547
- username: String(nextEff.username || next.username || ''),
1548
- }
1549
- const nextRaw = { host: String(next.host || ''), port: Number(next.port) || 22, username: String(next.username || '') }
1550
- const sameIdentity = (a, b) => a.host === b.host && a.port === b.port && a.username === b.username
1551
- if (!prevAlias && sameIdentity(prevId, nextId) && sameIdentity(prevRaw, nextRaw)) return 0
1552
- if (prevAlias && prevAlias === nextAlias) return 0
1553
- const root = remoteWorkspacesRoot()
1554
- let rebound = 0
1555
- let hostDirs = []
1556
- try { hostDirs = readdirSync(root) } catch { return 0 }
1557
- for (const hostDir of hostDirs) {
1558
- const hostPath = path.join(root, hostDir)
1559
- if (!statSync(hostPath, { throwIfNoEntry: false })?.isDirectory?.()) continue
1560
- let entries = []
1561
- try { entries = readdirSync(hostPath) } catch { continue }
1562
- for (const entry of entries) {
1563
- const metaPath = path.join(hostPath, entry, '.dsh-remote-meta.json')
1564
- let meta = null
1565
- try { meta = JSON.parse(readFileSync(metaPath, 'utf8')) } catch { continue }
1566
- if (!meta || !meta.host) continue
1567
- const byAlias = prevAlias && String(meta.alias || '') === prevAlias
1568
- // A meta records the RESOLVED identity at pick time, but that identity
1569
- // can also have been written raw — match on either form of the old
1570
- // identity so a rebind still finds mirrors recorded before a later
1571
- // ssh-config resolution rewrote what "this machine" meant.
1572
- const metaId = { host: String(meta.host), port: Number(meta.port) || 22, username: String(meta.username || '') }
1573
- const byIdentity = sameIdentity(metaId, prevId) || sameIdentity(metaId, prevRaw)
1574
- if (!byAlias && !byIdentity) continue
1575
- const updated = { ...meta }
1576
- if (nextAlias) {
1577
- // Alias machine: the recorded alias is what future resolution keys
1578
- // on; the resolved address refreshes only when it actually resolved
1579
- // (an unmatched alias keeps the old literal values rather than
1580
- // stamping the alias NAME into the address fields).
1581
- updated.alias = nextAlias
1582
- if (nextEff.sshConfigMatched || nextEff.sshAlias) {
1583
- updated.host = nextId.host
1584
- updated.port = nextId.port
1585
- updated.username = nextId.username
1586
- }
1587
- } else {
1588
- delete updated.alias
1589
- updated.host = nextRaw.host
1590
- updated.port = nextRaw.port
1591
- updated.username = nextRaw.username
1592
- }
1593
- updated.reboundAt = new Date().toISOString()
1594
- try {
1595
- writeFileSync(metaPath, JSON.stringify(updated, null, 2))
1596
- rebound++
1597
- } catch { /* leave that mirror as-is */ }
1598
- }
1599
- }
1600
- if (rebound) {
1601
- // The old identity's pooled connection dials an address the user just
1602
- // abandoned: drop it so nothing keeps a dead SSH session warm. The new
1603
- // identity gets its pool lazily on the next tool call.
1604
- const stale = machinePools.get(poolKey(prevId))
1605
- if (stale) {
1606
- machinePools.delete(poolKey(prevId))
1607
- try { stale.close() } catch { /* already gone */ }
1608
- }
1609
- }
1610
- return rebound
1611
- }
1612
-
1613
- if (config.autoPush && wsPath()) {
1614
- startAutoPush(mirrorDirFor(wsPath(), config.host, config.username, config.port))
1615
- }
1616
- /** The remote path one agent session is bound to, or '' when that session is
1617
- * a plain local one. Walks the mirror registry (host side copy of the
1618
- * resolve-mirror logic) so status / prompt / sidebar agree.
1619
- *
1620
- * `sessionId` narrows to one session. WITHOUT it the first live session's cwd
1621
- * is used, which is only meaningful for the machine-scoped settings view:
1622
- * with several live sessions the "first" one is arbitrary and may belong to
1623
- * another machine. Tool calls must never route through this — they resolve
1624
- * their own session through `bindingFor()`, which is authoritative. */
1625
- const sessionsSvc = () => (ctx && typeof ctx.get === 'function' ? ctx.get('sessions') : null)
1626
-
1627
- /** Whether one session is still open somewhere.
1628
- *
1629
- * In-process: the `sessions` service knows every live (including parked)
1630
- * session of THIS TUI, so the cleanup page can refuse to delete its own.
1631
- * Cross-process: DSH holds a kernel `flock` on `<session dir>/session.lock`
1632
- * for the life of the write handle, so a successful `lsof` names the holder.
1633
- * `deep: false` skips the spawn — list views call it for every row.
1634
- */
1635
- const isSessionLive = async (sessionId, dir, opts = {}) => {
1636
- try {
1637
- const live = sessionsSvc()
1638
- if (live && typeof live.get === 'function' && live.get(sessionId)) return true
1639
- } catch { /* no sessions service (minimal embedding) */ }
1640
- if (opts && opts.deep === true && process.platform !== 'win32') {
1641
- const lock = path.join(String(dir || ''), 'session.lock')
1642
- if (!existsSync(lock)) return false
1643
- return await new Promise((resolve) => {
1644
- try {
1645
- execFile('lsof', ['-t', '--', lock], { timeout: 3000 }, (error, stdout) => {
1646
- resolve(String(stdout || '').trim().length > 0)
1647
- })
1648
- } catch {
1649
- resolve(false)
1650
- }
1651
- })
1652
- }
1653
- return false
1654
- }
1655
-
1656
- /** Drop one remote path from every machine's recent list and current workspace.
1657
- *
1658
- * Deleting a workspace must also forget its remote path, otherwise the TUI
1659
- * provider re-creates the mirror from `recentWorkspaces` on the next start.
1660
- *
1661
- * @param {string} remotePath - remote workspace path to forget.
1662
- * @returns {{recents: number, current: number}} how many fields changed.
1663
- */
1664
- const forgetRemotePath = (remotePath) => {
1665
- const target = String(remotePath || '').trim()
1666
- let recents = 0
1667
- let current = 0
1668
- if (!target) return { recents, current }
1669
- for (const machine of machines) {
1670
- if (Array.isArray(machine.recentWorkspaces)) {
1671
- const before = machine.recentWorkspaces.length
1672
- machine.recentWorkspaces = machine.recentWorkspaces.filter((entry) => String(entry) !== target)
1673
- recents += before - machine.recentWorkspaces.length
1674
- }
1675
- if (String(machine.workspace || '') === target) {
1676
- machine.workspace = ''
1677
- current += 1
1678
- }
1679
- }
1680
- if (recents > 0 || current > 0) saveMachines(machines, store.currentId, false)
1681
- return { recents, current }
1682
- }
1683
- const sessionCwd = (sessionId) => {
1684
- const sessions = sessionsSvc()
1685
- if (sessionId) return lookupSessionCwd(sessionId, { sessions, dshHome: dshBase() })
1686
- try {
1687
- if (sessions && typeof sessions.list === 'function') {
1688
- const s = sessions.list()[0]
1689
- if (s && s.header && s.header.cwd) return String(s.header.cwd)
1690
- }
1691
- } catch { /* sessions service unavailable */ }
1692
- return ''
1693
- }
1694
- const sessionRemotePath = (sessionId) => {
1695
- const cwd = sessionCwd(sessionId)
1696
- if (!cwd) return ''
1697
- return resolveMirrorForLocal(cwd).remotePath
1698
- }
1699
-
1700
- /**
1701
- * HTTP binding for sidebar file routes. A sessionId/local hint is authoritative:
1702
- * a local (non-mirror) session is refused rather than falling back to the
1703
- * active machine. Requests with no hint keep the picker/settings active pool.
1704
- */
1705
- const resolveRequestBinding = async (req, body = {}) => {
1706
- const hint = requestSessionHint(req, body)
1707
- let cwd = hint.local
1708
- if (hint.sessionId) {
1709
- const recorded = lookupSessionCwd(hint.sessionId, { sessions: sessionsSvc(), dshHome: dshBase() })
1710
- if (!recorded || hint.local && path.resolve(recorded) !== path.resolve(hint.local)) {
1711
- throw Object.assign(new Error('Session workspace context is unavailable or mismatched; refusing to use another session or the active machine.'), { httpStatus: 403 })
1712
- }
1713
- cwd = recorded
1714
- }
1715
- if (cwd) {
1716
- const { remotePath, machine, mirrorDir } = resolveMirrorForLocal(cwd)
1717
- if (remotePath && machine) {
1718
- return {
1719
- pool: poolForMachine(machine),
1720
- ws: remotePath,
1721
- host: machine.host,
1722
- username: machine.username,
1723
- port: machine.port,
1724
- alias: machine.alias || '',
1725
- mirrorDir,
1726
- bound: true,
1727
- local: false,
1728
- }
1729
- }
1730
- const err = new Error(
1731
- 'this session is LOCAL — its workspace is not a remote mirror, so there is no remote host to act on. '
1732
- + 'Refusing rather than falling back to the active machine.',
1733
- )
1734
- err.httpStatus = 403
1735
- throw err
1736
- }
1737
- // No session context: fall back to the ACTIVE machine. Boot restore runs on
1738
- // `setImmediate`, so a request that arrives first would see `config.host`
1739
- // still empty even though the registry already names a current machine —
1740
- // apply it here instead of answering "no machine" to a user who HAS one.
1741
- if (!String(config.host || '').trim()) {
1742
- const m = activeMachine()
1743
- if (m && m.host) {
1744
- try { await applyActiveMachine() } catch { /* reported below */ }
1745
- }
1746
- }
1747
- // Still nothing: answer with the REAL reason. Falling through used to hand the
1748
- // caller the un-configured pool, whose first command failed with
1749
- // "no credentials: set a password, a privateKeyPath…" — i.e. a missing
1750
- // *selection* was reported as a missing *credential*, which sends people to the
1751
- // wrong settings page.
1752
- if (!String(config.host || '').trim()) {
1753
- const err = new Error(
1754
- '当前没有活动远程机:请先在「远程工作区」设置里选择或连接一台机器。'
1755
- + '(保存的机器只是备用连接,不会自动成为当前机器。)',
1756
- )
1757
- err.httpStatus = 409
1758
- throw err
1759
- }
1760
- return {
1761
- pool,
1762
- ws: wsPath(),
1763
- host: config.host,
1764
- username: config.username,
1765
- port: config.port,
1766
- mirrorDir: wsPath() ? mirrorDirFor(wsPath(), config.host, config.username, config.port) : null,
1767
- bound: false,
1768
- local: false,
1769
- }
1770
- }
1771
-
1772
- // ── session-bound remote binding (the authoritative tool path) ─────────────
1773
-
1774
- /**
1775
- * Resolve the remote binding a tool call must act on, from the calling
1776
- * session's own workspace cwd.
1777
- *
1778
- * This is what keeps concurrent sessions independent: the machine and the
1779
- * workspace root both come from the session's mirror `.dsh-remote-meta.json`,
1780
- * never from the mutable active-machine state, so another session switching
1781
- * machines cannot redirect this call. Sessions on the same machine resolve to
1782
- * the same key and share one pool.
1783
- *
1784
- * @param {object} [exec] - the tool's `ToolRunContext`; `exec.agent.session.header.cwd` identifies the caller.
1785
- * @returns {{pool: SshPool, ws: string, host: string, username: string, port: number, mirrorDir: string|null, bound: boolean, local: boolean}}
1786
- * `bound` is true only for a session whose cwd resolves to a mirror. A
1787
- * caller with a cwd that is NOT a mirror is a local session: `local` is
1788
- * true and the active-machine values are returned for machine-scoped
1789
- * reporting (`rw_info`) — session-scoped tools must refuse it instead,
1790
- * which is what {@link requireBinding} enforces.
1791
- */
1792
- const bindingFor = (exec) => {
1793
- const cwd = exec?.agent?.session?.header?.cwd
1794
- if (cwd) {
1795
- const { remotePath, machine, mirrorDir } = resolveMirrorForLocal(String(cwd))
1796
- if (remotePath && machine) {
1797
- return {
1798
- pool: poolForMachine(machine),
1799
- ws: remotePath,
1800
- host: machine.host,
1801
- username: machine.username,
1802
- port: machine.port,
1803
- alias: machine.alias || '',
1804
- mirrorDir,
1805
- bound: true,
1806
- local: false,
1807
- }
1808
- }
1809
- }
1810
- return {
1811
- pool,
1812
- ws: wsPath(),
1813
- host: config.host,
1814
- username: config.username,
1815
- port: config.port,
1816
- mirrorDir: wsPath() ? mirrorDirFor(wsPath(), config.host, config.username, config.port) : null,
1817
- bound: false,
1818
- // A caller that identified itself with a cwd, yet resolved to no mirror,
1819
- // is definitively a LOCAL session. Distinguish it from "no caller
1820
- // context at all", where the active machine is still the right answer.
1821
- local: !!cwd,
1822
- }
1823
- }
1824
-
1825
- /**
1826
- * Binding for a tool that requires a remote workspace, with a diagnostic
1827
- * refusal when none is resolvable. Failing loud here is the point: silently
1828
- * falling back to the active machine is how a command reached the wrong host.
1829
- * @param {object} exec - the tool's `ToolRunContext`.
1830
- * @param {string} tool - tool name, used in the error message.
1831
- * @returns {ReturnType<typeof bindingFor>} a binding with `bound: true`.
1832
- */
1833
- const requireBinding = (exec, tool) => {
1834
- const b = bindingFor(exec)
1835
- // A LOCAL session must be refused even when an active machine happens to
1836
- // have a workspace: inheriting it is precisely how a command reaches a host
1837
- // the caller never asked for. Checking only `!b.ws` missed this, because
1838
- // the active machine's workspace is usually non-empty.
1839
- if (b.local) {
1840
- throw new Error(
1841
- `${tool}: this session is LOCAL — its workspace is not a remote mirror, `
1842
- + 'so there is no remote host to act on. Refusing rather than falling back to the active machine '
1843
- + `(${config.username || '?'}@${config.host || '?'}), which belongs to a different session. `
1844
- + 'Use rw_connect + rw_pick_workspace to bind a remote workspace, then open a session in its local mirror.',
1845
- )
1846
- }
1847
- if (!b.ws) {
1848
- throw new Error(
1849
- `${tool}: no remote workspace set — call rw_connect then rw_pick_workspace first.`,
1850
- )
1851
- }
1852
- if (!b.host) throw new Error(`${tool}: no remote host resolved for this session — run rw_connect first.`)
1853
- return b
1854
- }
1855
-
1856
- if (typeof ctx.on === 'function') {
1857
- ctx.on('tools/pre-execute', async (exec, next) => {
1858
- if (!LOCAL_MUTATION_TOOLS.has(exec?.name)) return next()
1859
- return remoteLocalMutationDecision(exec, bindingFor(exec)) || next()
1860
- })
1861
- }
1862
-
1863
- // ── remote sandbox semantics ──────────────────────────────────────────────
1864
- // A local session is confined by ctx.sandboxPolicy; a REMOTE command used to
1865
- // run under no policy at all, so a read-only session could mutate any file on
1866
- // any reachable host. `ctx.sandbox.confine()` cannot help here — it wraps argv
1867
- // for a spawn on THIS machine, while the process we start lives on the other
1868
- // end of an SSH channel. So the fence is applied at the tool boundary, using
1869
- // the SAME resolved policy the local tools consume (see lib/remote-sandbox.js
1870
- // for the threat model: containment, not a security boundary).
1871
- //
1872
- // Optional by design: a composition without ctx.sandboxPolicy (a minimal
1873
- // embedding, a test double, an agentless call) keeps the pre-existing
1874
- // unconfined behaviour instead of failing to load, and `remoteSandbox` config
1875
- // can switch the fence off for deployments whose remotes enforce their own.
1876
- const remoteSandboxEnabled = () => config.remoteSandbox !== 'off'
1877
-
1878
- /**
1879
- * Resolve the sandbox mode for one tool call.
1880
- *
1881
- * Reads the core policy service when present; otherwise honours the plugin's
1882
- * own `remoteSandbox` fallback (`inherit` ⇒ danger-full-access, i.e. the old
1883
- * unconfined behaviour). Any resolution failure is treated as read-only — fail
1884
- * closed, never open.
1885
- *
1886
- * @param {object} [exec] - the tool run context.
1887
- * @returns {string} the mode name.
1888
- */
1889
- const sandboxModeFor = (exec) => {
1890
- if (!remoteSandboxEnabled()) return 'danger-full-access'
1891
- try {
1892
- const svc = ctx.get('sandboxPolicy')
1893
- if (svc && typeof svc.resolve === 'function') {
1894
- const session = exec && exec.agent ? exec.agent.session : undefined
1895
- const resolved = svc.resolve(session ? { session } : {})
1896
- if (resolved && REMOTE_SANDBOX_MODES.includes(resolved.mode)) return resolved.mode
1897
- }
1898
- } catch { /* fall through to the configured default */ }
1899
- const fallback = String(config.remoteSandbox || 'inherit')
1900
- return REMOTE_SANDBOX_MODES.includes(fallback) ? fallback : 'danger-full-access'
1901
- }
1902
-
1903
- /**
1904
- * Assert that one remote operation is permitted, throwing the official denial
1905
- * shape when it is not.
1906
- *
1907
- * @param {object} exec - the tool run context.
1908
- * @param {'read'|'write'|'exec'|'tunnel'|'connect'} operation
1909
- * @param {object} [opts]
1910
- * @param {string} [opts.path] - the remote path a `write` targets.
1911
- * @param {string} [opts.tool] - tool name for the message.
1912
- */
1913
- const requireRemoteSandbox = (exec, operation, opts = {}) => {
1914
- if (!remoteSandboxEnabled()) return
1915
- const mode = sandboxModeFor(exec)
1916
- if (mode === 'danger-full-access') return
1917
- const b = (() => { try { return bindingFor(exec) } catch { return null } })()
1918
- const workspaceRoot = (b && b.ws) || ''
1919
- // Check the execution-world path the rw_* body will actually use. Raw
1920
- // relative and mirror-local paths must resolve exactly as resolveRemoteArg.
1921
- const targetPath = opts.path == null ? opts.path : resolveRemoteWorkspacePath(workspaceRoot, opts.path, b?.mirrorDir || '')
1922
- const verdict = checkRemoteSandbox({ mode, operation, path: targetPath, workspaceRoot })
1923
- if (verdict.allowed) return
1924
- const err = remoteSandboxDenial(verdict)
1925
- if (opts.tool) err.message = `${opts.tool}: ${err.message}`
1926
- throw err
1927
- }
1928
-
1929
- /**
1930
- * Binding for a tool that takes an explicit absolute remote path: it needs a
1931
- * resolvable MACHINE but not a workspace root. A local session is refused for
1932
- * the same reason as {@link requireBinding} — the active machine belongs to
1933
- * whoever set it, not to this caller.
1934
- * @param {object} exec - the tool's `ToolRunContext`.
1935
- * @param {string} tool - tool name, used in the error message.
1936
- * @returns {ReturnType<typeof bindingFor>} a binding whose `host` is non-empty.
1937
- */
1938
- const requireMachine = (exec, tool) => {
1939
- const b = bindingFor(exec)
1940
- if (b.local) {
1941
- throw new Error(
1942
- `${tool}: this session is LOCAL — its workspace is not a remote mirror, `
1943
- + 'so there is no remote host to act on. Refusing rather than falling back to the active machine '
1944
- + `(${config.username || '?'}@${config.host || '?'}), which belongs to a different session.`,
1945
- )
1946
- }
1947
- if (!b.host) throw new Error(`${tool}: no remote host for this session — run rw_connect first`)
1948
- return b
1949
- }
1950
- const syncStatusFor = (local) => {
1951
- const observed = syncActivity.read(local)
1952
- const watcher = autoPushWatchers.get(local)
1953
- return { ...observed, ...(watcher && watcher.pending.size ? { phase: 'pending' } : {}), autoPush: !!config.autoPush }
1954
- }
1955
- const status = () => ({
1956
- host: config.host,
1957
- port: config.port,
1958
- username: config.username,
1959
- connected: !!pool.client,
1960
- workspace: toDisplayPath(wsPath(), pool.platform),
1961
- localMirror: wsPath() ? mirrorDirFor(wsPath(), config.host, config.username, config.port) : '',
1962
- currentId: store.currentId || null,
1963
- sync: syncStatusFor(wsPath() ? mirrorDirFor(wsPath(), config.host, config.username, config.port) : ''),
1964
- activeSource: ephemeral ? 'ephemeral' : (store.currentId ? 'machine' : (config.host ? 'config' : 'none')),
1965
- // Issue #13: whether THIS session is in remote mode (cwd inside a mirror).
1966
- // `none`/`local` means the plugin is present but no remote context is
1967
- // active — saved machines stay standby-only.
1968
- sessionMode: sessionRemotePath() ? 'remote' : (store.currentId ? 'standby' : 'local'),
1969
- sessionRemotePath: sessionRemotePath(),
1970
- machines: machinesForClient(),
1971
- hostKeyMode: config.hostKeyMode === 'verify' || config.hostKeyMode === 'off' ? config.hostKeyMode : 'accept-new',
1972
- hostKeyKnown: config.host ? isHostKeyKnown(config.host, config.port) : false,
1973
- forwards: forwards.list(),
1974
- auditEnabled: !!config.auditLog,
1975
- backend: platformBackend(),
1976
- platform: pool.platform,
1977
- shell: pool.shellMode,
1978
- gitBash: pool.gitBashPath || '',
1979
- })
1980
-
1981
- // ── remote `@` completion (issue #39) ─────────────────────────────────────
1982
- //
1983
- // `@` candidates come from `ctx.fileReferences`, whose only shipped provider
1984
- // indexes the agent session's LOCAL cwd. A remote session's cwd is the (empty
1985
- // until synced) mirror, so `@` listed nothing. The seam is a single-owner
1986
- // service, so lib/file-reference.js WRAPS `fileReferences.list` and answers
1987
- // remote-bound sessions from the remote host over SFTP.
1988
- //
1989
- // Everything below is glue: which remote root an agent is bound to, and how a
1990
- // workspace-relative directory is listed over the machine's own pool.
1991
-
1992
- const fileReferenceLog = (msg) => {
1993
- try {
1994
- const logger = typeof ctx.get === 'function' ? ctx.get('logger') : undefined
1995
- if (logger && typeof logger.warn === 'function') logger.warn('[dsh-remote] ' + msg)
1996
- } catch { /* logging is best-effort */ }
1997
- }
1998
-
1999
- /** Providers, one per (machine, remote root): the index cache is expensive to
2000
- * rebuild, so typing in the SAME workspace keeps reusing it. */
2001
- const fileReferenceProviders = new Map()
2002
- const FILE_REFERENCE_PROVIDER_CAP = 32
2003
-
2004
- /**
2005
- * The remote discovery provider for one agent, or null when that agent is not
2006
- * a remote session (or the feature is off) — in which case the original local
2007
- * provider answers, unchanged.
2008
- */
2009
- const remoteFileReferenceFor = (agent) => {
2010
- // `=== false` rather than falsy: a partially-specified config (a scripted
2011
- // apply(), an older profile) must still get the remote listing, which is
2012
- // what the schema default promises.
2013
- if (config.fileReference === false) return null
2014
- const cwd = agent && agent.session && agent.session.header ? agent.session.header.cwd : ''
2015
- if (!cwd) return null
2016
- const { remotePath, machine } = resolveMirrorForLocal(String(cwd))
2017
- if (!remotePath || !machine) return null
2018
- const root = normalizeRemotePath(remotePath)
2019
- const key = poolKey(machine) + '\u0000' + root
2020
- const cached = fileReferenceProviders.get(key)
2021
- if (cached) return cached
2022
- const provider = createRemoteFileReference({
2023
- root,
2024
- // '' = the workspace root; every other value is a workspace-relative dir.
2025
- listDir: async (rel) => {
2026
- const p = poolForMachine(machine)
2027
- const sftp = await p.sftp()
2028
- const out = await listDirStructured(sftp, rel ? joinRemoteRel(root, rel) : root)
2029
- return out.items.map((item) => ({
2030
- name: item.name,
2031
- kind: item.type === 'dir' ? 'directory' : 'file',
2032
- }))
2033
- },
2034
- config: {
2035
- root,
2036
- maxResults: config.fileReferenceMaxResults,
2037
- maxEntries: config.fileReferenceMaxEntries,
2038
- excludedDirectories: config.fileReferenceExcludedDirectories,
2039
- timeoutMs: config.fileReferenceTimeoutMs,
2040
- },
2041
- onError: (err) => fileReferenceLog(`@ listing failed for ${machine.host}:${root}: ${(err && err.message) || err}`),
2042
- })
2043
- if (fileReferenceProviders.size >= FILE_REFERENCE_PROVIDER_CAP) {
2044
- const oldest = fileReferenceProviders.keys().next().value
2045
- try { fileReferenceProviders.get(oldest)?.dispose() } catch { /* already disposed */ }
2046
- fileReferenceProviders.delete(oldest)
2047
- }
2048
- fileReferenceProviders.set(key, provider)
2049
- return provider
2050
- }
2051
-
2052
- const fileReferenceOverlay = installFileReferenceOverlay(ctx, {
2053
- resolve: remoteFileReferenceFor,
2054
- onError: (err) => fileReferenceLog(`@ completion overlay: ${(err && err.message) || err}`),
2055
- })
2056
- ctx.effect(() => () => {
2057
- try { fileReferenceOverlay?.dispose?.() } catch { /* already disposed */ }
2058
- for (const provider of fileReferenceProviders.values()) {
2059
- try { provider.dispose() } catch { /* already disposed */ }
2060
- }
2061
- fileReferenceProviders.clear()
2062
- }, 'dsh-remote.file-reference')
2063
-
2064
- /**
2065
- * Resolve a PATH ARGUMENT a tool received against the session's remote
2066
- * workspace root when it is not already a remote absolute path (issue #39).
2067
- *
2068
- * Also maps paths inside `b.mirrorDir` onto `b.ws` when the model passes the
2069
- * local mirror cwd reported by the harness's runtime context to an `rw_*` tool.
2070
- *
2071
- * @param {{ws: string, mirrorDir?: string|null}} b - the binding resolved for this call.
2072
- * @param {unknown} raw - the raw argument value.
2073
- * @returns {string} a normalized remote path.
2074
- */
2075
- const resolveRemoteArg = (b, raw) =>
2076
- resolveRemoteWorkspacePath((b && b.ws) || '', raw, (b && b.mirrorDir) || '')
2077
-
2078
- // ── tools ─────────────────────────────────────────────────────────────────
2079
-
2080
- const textOut = {
2081
- schema: { type: 'object', additionalProperties: false, properties: { text: { type: 'string', required: true } } },
2082
- render: (_a, v) => [{ type: 'text', text: v.text }],
2083
- }
2084
- const okOut = {
2085
- schema: { type: 'object', additionalProperties: false, properties: { ok: { type: 'boolean', required: true }, bytes: { type: 'integer' }, text: { type: 'string' } } },
2086
- render: (_a, a) => [{ type: 'text', text: a.text || (a.ok ? 'ok' : 'failed') }],
2087
- }
2088
- // Durable facts for the client, independent of strings printed by a command.
2089
- // The model-facing text stays compatible with earlier tools and PTC callers.
2090
- const execOut = {
2091
- schema: { type: 'object', additionalProperties: false, properties: {
2092
- text: { type: 'string', required: true },
2093
- execution: { type: 'object', required: true, additionalProperties: false, properties: {
2094
- kind: { type: 'string', required: true }, version: { type: 'integer', required: true },
2095
- status: { type: 'string', required: true }, host: { type: 'string', required: true },
2096
- cwd: { type: 'string', required: true }, durationMs: { type: 'integer', required: true },
2097
- code: { type: 'integer' }, signal: { type: 'string' }, jobId: { type: 'string' },
2098
- } },
2099
- } },
2100
- render: (_args, value) => {
2101
- const code = value.execution.code
2102
- const marker = Number.isInteger(code) && code >= 0 ? '[exit code: ' + code + ']' : ''
2103
- return [{ type: 'text', text: value.text + (marker && !value.text.trimEnd().endsWith(marker) ? '\n' + marker : '') }]
2104
- },
2105
- presentationMeta: (_args, value) => value.execution,
2106
- }
2107
-
2108
- const tools = [
2109
- defineTool({
2110
- name: 'rw_info',
2111
- description:
2112
- 'Show the remote environment: host/user/port, connection health, current remote workspace path, active port forwards. Call this first to orient, or when an rw_* call fails to check connectivity. Note: remote context is session-scoped — a saved machine only becomes active when you explicitly rw_connect to it (issue #13).',
2113
- parameters: {},
2114
- output: textOut,
2115
- async execute(_args, exec) {
2116
- // Report THIS session's binding, not the globally active machine: the
2117
- // two differ whenever another session is working on another host, and
2118
- // reporting the active machine is what made this tool contradict itself.
2119
- const b = bindingFor(exec)
2120
- // rw_info is the orientation tool, so resolve the real platform rather
2121
- // than reporting "detecting…" for a pool this session has not used yet.
2122
- if (b.host) {
2123
- try { await b.pool.detect() } catch { /* unreachable host → the ping below reports it */ }
2124
- }
2125
- const s = status()
2126
- const lines = b.bound
2127
- ? [
2128
- `Remote host: ${b.username || '<user>'}@${b.host}:${b.port} (bound to this session's workspace)`,
2129
- `Current remote workspace: ${toDisplayPath(b.ws, b.pool.platform)}`,
2130
- `Local mirror: ${b.mirrorDir || '(none)'}`,
2131
- `Connected: ${b.pool.client ? 'yes' : 'no'}`,
2132
- `Remote shell: ${b.pool.platform === 'windows' ? (b.pool.gitBashPath ? 'Git Bash (' + b.pool.gitBashPath + ')' : 'Windows (Git Bash not found — set config.shell to a bash.exe path)') : (b.pool.platform === 'posix' ? 'native POSIX' : 'detecting…')}`,
2133
- `Active forwards: ${s.forwards.filter((f) => f.active).length} / ${s.forwards.length} (forwards are machine-scoped)`,
2134
- `Host key: ${isHostKeyKnown(b.host, b.port) ? 'trusted' : 'not yet trusted'} (mode=${s.hostKeyMode})`,
2135
- '',
2136
- ]
2137
- : [
2138
- `Remote host: ${s.username || '<user>'}@${s.host || '<host>'}:${s.port}${s.activeSource !== 'machine' ? ` (source: ${s.activeSource})` : ''}`,
2139
- 'Session remote context: (this session is LOCAL — no remote workspace bound)',
2140
- `Active machine workspace: ${s.workspace || '(none — call rw_connect then rw_pick_workspace to set one)'}`,
2141
- `Connected: ${s.connected ? 'yes' : 'no'}`,
2142
- `Host key: ${s.hostKeyKnown ? 'trusted' : 'not yet trusted'} (mode=${s.hostKeyMode})`,
2143
- '',
2144
- ]
2145
- if (b.host && b.ws) {
2146
- try {
2147
- const res = await b.pool.exec('echo ok', { timeoutMs: Math.min(config.commandTimeoutMs, 8000) })
2148
- if (res.signal === 'TIMEOUT') lines.push('Ping: timeout')
2149
- else if (res.code === 0) lines.push('Ping: OK — ' + res.stdout.replace(/\s+/g, ' ').trim())
2150
- else lines.push('Ping: FAILED — ' + (res.stderr || res.stdout || `exit ${res.code}`).trim())
2151
- } catch (err) {
2152
- lines.push('Ping: FAILED — ' + friendlyMessage(err, { host: b.host, port: b.port }))
2153
- }
2154
- } else {
2155
- lines.push('No host + workspace configured — call rw_connect with a host to get started.')
2156
- }
2157
- return { text: lines.join('\n') }
2158
- },
2159
- }),
2160
-
2161
- defineTool({
2162
- name: 'rw_connect',
2163
- description:
2164
- 'Connect SSH to a remote host for remote workspace work. Two ways (issue #48): (1) pass machineId to connect with a machine ALREADY SAVED in the registry (list them with rw_machines) — every stored setting applies: password/keychain password, privateKeyPath + passphrase, useAgent, keyboardInteractive, proxy, hostKeyMode, backend, and ~/.ssh/config aliases; or (2) pass host plus any of username/port/password/privateKeyPath/passphrase/useAgent/keyboardInteractive/hostKeyMode/backend/name. Defaults to saving the machine to the registry (save=false keeps it as a temporary connection). Once connected, call rw_pick_workspace to pick the workspace directory this session should work in. With useSshConfig=true, `host` is an ALIAS from ~/.ssh/config and every value (HostName/user/port/IdentityFile/ProxyJump) is read from that file at connect time. For a host that only accepts GSSAPI/Kerberos (issue #51), pass backend="openssh" (with useSshConfig=true) so the local ssh — which holds your kinit ticket — performs the login. A failed connection is reported as an error message — it never takes the plugin down. Rebinding (issue #67): pass machineId TOGETHER with a new host/username/port to update that saved machine in place — every workspace mirror bound to its old address is re-pointed (local content kept, no re-sync) instead of forcing new workspaces.',
2165
- parameters: {
2166
- host: { type: 'string', description: 'Remote host IP or hostname (or a ~/.ssh/config alias with useSshConfig=true). Required unless machineId is given.' },
2167
- machineId: { type: 'string', description: 'Connect with a saved machine from the registry (see rw_machines): all its stored settings apply and it becomes the current machine. host/other fields are not needed — EXCEPT for rebinding (issue #67): combine machineId with a new host/username/port to update the machine in place and re-point its existing workspace mirrors.' },
2168
- username: { type: 'string', description: 'SSH user (default from config or root)' },
2169
- port: { type: 'integer', description: 'SSH port (default 22)' },
2170
- password: { type: 'string', description: 'SSH password (prefer SSH key when possible)' },
2171
- privateKeyPath: { type: 'string', description: 'Absolute private-key path' },
2172
- passphrase: { type: 'string', description: 'Passphrase for an ENCRYPTED private key — required when the key is passphrase-protected, otherwise ssh2 cannot parse it (issue #48)' },
2173
- useAgent: { type: 'boolean', description: 'Authenticate via the local SSH agent (SSH_AUTH_SOCK) instead of password/key' },
2174
- keyboardInteractive: { type: 'boolean', description: 'Enable keyboard-interactive auth (OTP/动态码 prompts answered with the configured password)' },
2175
- hostKeyMode: { type: 'string', description: 'Host-key policy for this machine: ask | strict | off (default from config)' },
2176
- backend: { type: 'string', description: 'SSH transport backend (issue #51): "native" (default) uses the built-in ssh2 client (password / private key / agent / keyboard-interactive); "openssh" drives the LOCAL ssh command, which is the only way to reach hosts that require GSSAPI/Kerberos (log in once with kinit) and which honours the whole of ~/.ssh/config (ProxyCommand, PKCS11Provider, Match blocks). Prefer "openssh" together with useSshConfig=true so the alias and its settings stay the single source of truth.' },
2177
- sshBinary: { type: 'string', description: 'Path (or PATH name) of the ssh executable the "openssh" backend drives — default "ssh"' },
2178
- name: { type: 'string', description: 'Display name for a newly saved machine (default: the host)' },
2179
- useSshConfig: { type: 'boolean', description: 'Treat `host` as a ~/.ssh/config Host alias; resolve host/user/port/key/proxy from that file (issue #38)' },
2180
- save: { type: 'boolean', description: 'Save this machine to the registry and make it current (default true)' },
2181
- },
2182
- output: textOut,
2183
- async execute(args) {
2184
- // Issue #67: set by the machineId+overrides path, prepended to the
2185
- // success line so the rebind is visible in the tool result.
2186
- let reboundNote = ''
2187
- const mid = String(args.machineId || '').trim()
2188
- if (mid) {
2189
- // Connect with an ALREADY SAVED machine (issue #48): the registry
2190
- // record carries everything the tool schema could not re-supply —
2191
- // keychain-backed passwords, stored passphrases, proxies, aliases.
2192
- const i = machineIndex(mid)
2193
- if (i < 0) throw new Error(`rw_connect: no saved machine "${mid}" — list saved machines with rw_machines`)
2194
- // Issue #67: passing host/username/port ALONGSIDE a machineId rebinds
2195
- // the saved machine in place — the fix for "the IP changed, do not
2196
- // make me recreate every workspace". The record keeps its id (and
2197
- // every credential), and each mirror bound to the old identity is
2198
- // re-pointed so live sessions keep working against the new address.
2199
- const prev = machines[i]
2200
- const overrides = {}
2201
- if (args.host !== undefined && String(args.host).trim()) overrides.host = String(args.host).trim()
2202
- if (args.username !== undefined && String(args.username).trim()) overrides.username = String(args.username).trim()
2203
- if (args.port !== undefined && Number(args.port)) overrides.port = Number(args.port)
2204
- let rebound = 0
2205
- if (Object.keys(overrides).length) {
2206
- const next = { ...prev, ...overrides }
2207
- try { rebound = rebindMirrors(prev, next) } catch { /* best effort */ }
2208
- machines[i] = next
2209
- }
2210
- if (rebound) {
2211
- reboundNote = `Rebound ${rebound} workspace mirror(s) from ${prev.username}@${prev.host}:${prev.port} to the new address (local content kept — no re-sync needed).\n`
2212
- }
2213
- store.currentId = machines[i].id
2214
- ephemeral = null
2215
- saveMachines(machines, store.currentId)
2216
- // rw_connect means "connect now": force a fresh dial even for an
2217
- // identical target (same reconnect-probe reasoning as below).
2218
- pool.invalidate()
2219
- await applyActiveMachine()
2220
- } else {
2221
- const host = String(args.host || '').trim()
2222
- if (!host) throw new Error('rw_connect: host is required — or pass machineId to connect with a saved machine (list them with rw_machines)')
2223
- const useSshConfig = !!args.useSshConfig
2224
- const user = args.username || config.username || 'root'
2225
- const port = Number(args.port) || undefined
2226
- const rec = {
2227
- host,
2228
- port: port || 22,
2229
- username: user,
2230
- password: args.password !== undefined ? String(args.password) : '',
2231
- privateKeyPath: args.privateKeyPath || '',
2232
- }
2233
- // Carry ONLY the fields the caller actually passed: the upsert below
2234
- // merges rec over the stored record, and an always-present default
2235
- // would clobber stored values (e.g. wiping a saved passphrase).
2236
- if (args.passphrase !== undefined) rec.passphrase = String(args.passphrase)
2237
- if (args.useAgent !== undefined) rec.useAgent = !!args.useAgent
2238
- if (args.keyboardInteractive !== undefined) rec.keyboardInteractive = !!args.keyboardInteractive
2239
- // Group labels (host organisation): merge-only, so a partial call
2240
- // never wipes existing labels.
2241
- { const g = normalizeMachineGroup(args); for (const k of Object.keys(g)) rec[k] = g[k] }
2242
- if (args.hostKeyMode) rec.hostKeyMode = String(args.hostKeyMode)
2243
- if (args.name) rec.name = String(args.name)
2244
- // Issue #51: pick the transport backend. `openssh` is what reaches
2245
- // GSSAPI/Kerberos-only hosts, and with useSshConfig=true the alias is
2246
- // handed to ssh verbatim so ~/.ssh/config stays the single source.
2247
- if (args.backend) rec.backend = args.backend === 'openssh' ? 'openssh' : 'native'
2248
- if (args.sshBinary !== undefined) rec.sshBinary = String(args.sshBinary)
2249
- // Issue #54: the per-machine `dsh web` command is settable by hand too,
2250
- // not only by the deploy flow (the README told users to set it and the
2251
- // settings UI offered nowhere to type it).
2252
- if (args.webAttachCommand !== undefined) rec.webAttachCommand = String(args.webAttachCommand)
2253
- // Issue #125: its sibling — the per-machine resident-instance
2254
- // discover command. Undefined keeps the stored value.
2255
- if (args.webAttachDiscoverCommand !== undefined) rec.webAttachDiscoverCommand = String(args.webAttachDiscoverCommand)
2256
- if (useSshConfig) rec.useSshConfig = true
2257
- // An alias connection must dial the RESOLVED identity (~/.ssh/config),
2258
- // while the registry keeps the alias itself — EXCEPT on the
2259
- // system-OpenSSH backend, where ssh resolves the alias itself.
2260
- const eff = useSshConfig ? withSshConfig(rec) : rec
2261
- const ct = connectTargetFor(eff)
2262
- if (args.save !== false) {
2263
- // Upsert into the registry and make it the current machine so the
2264
- // settings UI and the tools always agree on who is active.
2265
- const i = machines.findIndex((m) => m.host === rec.host && m.username === rec.username && Number(m.port) === rec.port)
2266
- if (i >= 0) {
2267
- machines[i] = {
2268
- ...machines[i], ...rec, useSshConfig, id: machines[i].id,
2269
- // Secrets not re-supplied keep their stored values.
2270
- password: rec.password || machines[i].password || '',
2271
- passphrase: rec.passphrase !== undefined ? rec.passphrase : (machines[i].passphrase || ''),
2272
- }
2273
- store.currentId = machines[i].id
2274
- saveMachines(machines, store.currentId)
2275
- } else {
2276
- const id = machineId()
2277
- machines.push({ id, name: rec.name || host, ...rec })
2278
- store.currentId = id
2279
- saveMachines(machines, store.currentId)
2280
- }
2281
- ephemeral = null
2282
- // rw_connect means "connect now": force a fresh dial even for an
2283
- // identical target (setTarget alone would reuse a possibly half-open
2284
- // cached client — same reconnect-probe reasoning as /connect).
2285
- pool.invalidate()
2286
- await applyActiveMachine()
2287
- } else {
2288
- ephemeral = { id: machineId(), name: rec.name || host, ...rec }
2289
- // rw_connect means "connect now": force a fresh dial even for an
2290
- // identical target (setTarget alone would reuse a possibly half-open
2291
- // cached client — same reconnect-probe reasoning as /connect).
2292
- pool.invalidate()
2293
- pool.setTarget({
2294
- // connectTargetFor: on the system-OpenSSH backend an alias machine
2295
- // dials the alias, not the values it expands to.
2296
- host: ct.host, port: ct.aliasNative ? 22 : (Number(eff.port) || port || 22), username: ct.aliasNative ? '' : (eff.username || user),
2297
- password: rec.password, privateKeyPath: ct.privateKeyPath,
2298
- // Explicit (non-undefined) values so a stale passphrase/agent flag
2299
- // from a previous target cannot leak into this connection.
2300
- passphrase: eff.passphrase || '',
2301
- useAgent: !!rec.useAgent,
2302
- keyboardInteractive: !!rec.keyboardInteractive,
2303
- hostKeyMode: rec.hostKeyMode || config.hostKeyMode,
2304
- proxy: ct.proxy,
2305
- backend: backendFor(rec, config),
2306
- sshBinary: rec.sshBinary !== undefined ? rec.sshBinary : config.sshBinary,
2307
- workspace: config.workspace,
2308
- })
2309
- }
2310
- }
2311
- // Shared probe tail: after either path the shared config holds the
2312
- // effective dial identity (applyActiveMachine / setTarget wrote it).
2313
- const effHost = config.host
2314
- const effUser = config.username
2315
- const effPort = Number(config.port) || 22
2316
- try {
2317
- const res = await pool.exec('echo ok', { timeoutMs: 8000 })
2318
- if (res.code !== 0 && !res.stdout) {
2319
- audit('connect', `connect ${effUser}@${effHost}:${effPort}`, res.code)
2320
- return { text: 'connect failed: ' + (res.stderr || 'exit ' + res.code) }
2321
- }
2322
- audit('connect', `connect ${effUser}@${effHost}:${effPort}`, 0)
2323
- const active = activeMachine()
2324
- const via = active && active.sshAlias
2325
- ? `\n(ssh-config alias "${active.sshAlias}" → ${effUser}@${effHost}:${effPort}` + (active.sshConfigWarnings && active.sshConfigWarnings.length ? `; ${active.sshConfigWarnings.join(' ')}` : '') + ')'
2326
- : ''
2327
- return { text: `${reboundNote}Connected to ${effHost} as ${effUser}.${via}\n\npick a workspace with rw_pick_workspace (path=<abs>).` }
2328
- } catch (err) {
2329
- throw new Error(friendlyMessage(err, { host: effHost, port: effPort }))
2330
- }
2331
- },
2332
- }),
2333
-
2334
- defineTool({
2335
- name: 'rw_machines',
2336
- description:
2337
- 'List the machines saved in the registry, secrets stripped: id, name, host/port/username, auth method flags, ssh-config alias resolution, workspace, grouping labels (environment / tags / location), and which one is current. Optional filters (environment / tags / location / query) narrow the list - useful once you have many machines. Pass rw_connect(machineId=<id>) to connect with the full stored settings of a machine (issue #48).',
2338
- parameters: {
2339
- environment: { type: 'string', description: 'Only machines in this environment (e.g. prod, staging)' },
2340
- location: { type: 'string', description: 'Only machines in this location (e.g. shanghai, gpu-lab)' },
2341
- tags: { type: 'string', description: 'Only machines carrying ANY of these tags (comma or space separated)' },
2342
- query: { type: 'string', description: 'Free-text match over name/host/user/environment/location/description/tags' },
2343
- },
2344
- output: textOut,
2345
- async execute(args = {}) {
2346
- if (!machines.length) {
2347
- return { text: 'No saved machines yet — add one in Settings → 远程工作区, or connect with rw_connect(host=..., save defaults to true).' }
2348
- }
2349
- // Group filters (host organisation): a flat list stops being usable once
2350
- // a user has a dozen machines, and picking the wrong one on a destructive
2351
- // tool is how accidents happen.
2352
- const filtered = filterMachinesByGroup(machines, {
2353
- environment: args.environment, location: args.location, tags: args.tags, query: args.query,
2354
- })
2355
- const anyFilter = !!(args.environment || args.location || args.tags || args.query)
2356
- if (anyFilter && !filtered.length) {
2357
- const groups = groupSummary(machines)
2358
- return { text: 'No machine matches that filter.' + (groups ? '\n\nAvailable groups:\n' + groups : '') }
2359
- }
2360
- const rows = filtered.map((m) => {
2361
- const cur = store.currentId === m.id ? ' [CURRENT]' : ''
2362
- const auth = []
2363
- if (m.password || (m.credentialBackend && m.credentialBackend !== 'plain')) auth.push('password')
2364
- if (m.privateKeyPath) auth.push(`key:${m.privateKeyPath}${m.passphrase ? ' (passphrase set)' : ''}`)
2365
- if (m.useAgent) auth.push('agent')
2366
- if (m.keyboardInteractive) auth.push('keyboard-interactive')
2367
- // Issue #51: say which transport will be used — on `openssh` the
2368
- // credentials may come entirely from ~/.ssh/config (GSSAPI/kinit), so
2369
- // "auth: NONE" would be actively misleading there.
2370
- const backend = m.backend === 'openssh' ? 'openssh' : 'native'
2371
- if (backend === 'openssh') auth.push('openssh backend (~/.ssh/config: GSSAPI/key/agent)')
2372
- let via = ''
2373
- if (m.useSshConfig) {
2374
- const eff = withSshConfig(m)
2375
- via = ` alias→${eff.username || ''}@${eff.host}:${Number(eff.port) || 22}`
2376
- }
2377
- const ws = m.workspace ? ` workspace=${m.workspace}` : ''
2378
- // Grouping labels, shown inline so a wrong-host pick is visible.
2379
- const meta = []
2380
- if (m.environment) meta.push('env=' + m.environment)
2381
- if (m.location) meta.push('loc=' + m.location)
2382
- if (Array.isArray(m.tags) && m.tags.length) meta.push('tags=' + m.tags.join(','))
2383
- if (m.description) meta.push(m.description)
2384
- const group = meta.length ? '\n ' + meta.join(' ') : ''
2385
- return `- ${m.id} "${m.name || m.host}" [${backend}] ${m.username || ''}@${m.host}:${Number(m.port) || 22}${via}${cur}\n auth: ${auth.join(' + ') || 'NONE (connect will fail — add credentials)'}${ws}${group}`
2386
- })
2387
- const suffix = anyFilter
2388
- ? `\n\n${rows.length} of ${machines.length} machine(s) match. connect with rw_connect(machineId=<id>).`
2389
- : '\n\nconnect with rw_connect(machineId=<id>) to reuse a machine\'s full stored settings.'
2390
- return { text: rows.join('\n') + suffix }
2391
- },
2392
- }),
2393
-
2394
- defineTool({
2395
- name: 'rw_pick_workspace',
2396
- description:
2397
- 'Set the remote workspace directory this session should treat as its working root on the connected remote. Verifies it exists (a directory). Use rw_list_dir to browse first if unsure. Accepts POSIX (/home/dev/project) or Windows (C:\\Users\\dev\\project) paths.',
2398
- parameters: {
2399
- path: { type: 'string', required: true, description: 'Absolute remote directory path, e.g. /home/dev/code/project or C:\\Users\\dev\\project' },
2400
- },
2401
- output: textOut,
2402
- async execute(args, exec) {
2403
- // Blank input is the only upfront rejection: normalizeRemotePath('')
2404
- // returns '/', so the old `!p || p === '/'` guard actually meant "no
2405
- // root" — but a filesystem root is a legal workspace (issue #60), and
2406
- // its synthetic-tree risk is handled by ROOT_IGNORE in sync/search.
2407
- // Any non-blank path, root included, is answered by the real directory
2408
- // probe below (a missing path still fails there).
2409
- const rawPath = String(args.path || '').trim()
2410
- if (!rawPath) throw new Error('rw_pick_workspace: path must be an absolute directory')
2411
- const p = normalizeRemotePath(rawPath)
2412
- // Picking a workspace targets the machine this session is already bound
2413
- // to when it has one. A LOCAL session deliberately falls back to the
2414
- // active machine here: this is the setup flow that runs right after
2415
- // rw_connect, before any mirror exists to bind to. It creates a mirror
2416
- // rather than reading or writing remote data, so the refusal that
2417
- // guards the other tools would make binding a first workspace
2418
- // impossible.
2419
- const b = bindingFor(exec)
2420
- if (!b.host) throw new Error('rw_pick_workspace: no remote host — call rw_connect first')
2421
- const ok = await isRemoteDir(p, b.pool)
2422
- const shown = toDisplayPath(p, b.pool.platform)
2423
- if (!ok) return { text: `not a directory (or missing) on ${shown}` }
2424
- // A bound session's workspace lives in its own mirror meta, so the
2425
- // shared active-machine workspace is only updated for the unbound flow.
2426
- if (!b.bound) persistWorkspace(p)
2427
- const local = ensureMirror(p, b.host, b.username, b.port, { alias: b.alias || "" })
2428
- startAutoPush(local)
2429
- // Issue #68: discover the workspace's AGENTS.md / CLAUDE.md NOW — the
2430
- // first prompt assembly can come before any rw_sync, and the mirror
2431
- // copy must already be in place for the core instruction loader to
2432
- // pick it up. Awaited (the scan is a handful of shallow readdirs) but
2433
- // fully best-effort: a scan failure never fails the pick.
2434
- try { await instructionIndex.refresh({ pool: b.pool, ws: p, mirrorDir: local, force: true }) } catch { /* best effort */ }
2435
- // The closing hint depends on where THIS session stands (issue #63):
2436
- // in a LOCAL session "Run rw_sync" is a dead instruction — rw_sync
2437
- // refuses a local session — so say the mirror must be OPENED first.
2438
- return {
2439
- text: `Remote workspace set to ${shown} on ${b.username}@${b.host}.\nLocal mirror (native workspace path): ${local}\n\n${pickWorkspaceNextStep(b.local)}`,
2440
- }
2441
- },
2442
- }),
2443
-
2444
- defineTool({
2445
- name: 'rw_sync',
2446
- description:
2447
- 'Download the current remote workspace into its local mirror directory over SFTP (bounded, three-way conflict-aware). Makes the remote files visible/editable locally so the DSH native workspace / fs tools can operate on them. Conflicts (both sides modified) are reported and never overwritten; use force=true to override.',
2448
- parameters: {
2449
- depth: { type: 'integer', description: 'Max directory depth to mirror (default 8)' },
2450
- maxFiles: { type: 'integer', description: 'Max files to download (default 2000)' },
2451
- dryRun: { type: 'boolean', description: 'Compute the plan without downloading (default false)' },
2452
- force: { type: 'boolean', description: 'Overwrite conflicting files (default false)' },
2453
- async: { type: 'boolean', description: 'Run in the background and return a task id (default false)' },
2454
- },
2455
- output: textOut,
2456
- async execute(args, exec) {
2457
- const b = requireBinding(exec, 'rw_sync')
2458
- const p = b.ws
2459
- const local = b.mirrorDir || mirrorDirFor(p, b.host, b.username, b.port)
2460
- mkdirSync(local, { recursive: true })
2461
- const depth = Math.min(Math.max(Number(args.depth) || 8, 1), 16)
2462
- const maxFiles = Math.min(Math.max(Number(args.maxFiles) || 2000, 1), 20000)
2463
- const isIgnored = ignoreMatcher(p)
2464
- const body = { depth, maxDepth: depth, maxFiles, dryRun: !!args.dryRun, force: !!args.force, isIgnored }
2465
- const runSync = () => syncActivity.run(local, 'download', async (record) => {
2466
- let sftp
2467
- try {
2468
- sftp = await b.pool.sftp()
2469
- } catch (err) {
2470
- throw new Error('sftp unavailable: ' + ((err && err.message) || err))
2471
- }
2472
- const state = loadSyncState(local)
2473
- const { stats, nextState } = await syncTree(sftp, p, local, {
2474
- ...body,
2475
- state,
2476
- maxFileBytes: config.maxFileBytes,
2477
- getSftp: () => b.pool.sftp(),
2478
- })
2479
- record(stats)
2480
- if (!args.dryRun) saveSyncState(local, nextState)
2481
- let text = `${args.dryRun ? 'WOULD download' : 'Downloaded'} ${stats.files} file(s) from ${p} → ${local}.`
2482
- if (stats.abortedError) text += ` ABORTED early (${stats.abortedError}; re-run rw_sync to resume incremental sync, or use rw_download for a specific file).`
2483
- else if (stats.failed) text += ` ${stats.failed} failed.`
2484
- if (stats.truncated || stats.files >= maxFiles) text += ` TRUNCATED (hit depth=${depth} or maxFiles=${maxFiles} cap; raise maxFiles/depth and re-run).`
2485
- if (stats.skippedUnchanged) text += ` ${stats.skippedUnchanged} unchanged.`
2486
- if (stats.skippedLarge) text += ` ${stats.skippedLarge} too large (over ${config.maxFileBytes} bytes).`
2487
- if (stats.staleRemote) text += ` ${stats.staleRemote} remote entries gone (kept locally; use rw_push to mirror deletions).`
2488
- if (stats.conflicts.length) {
2489
- text += `\n⚠ ${stats.conflicts.length} conflict(s), NOT overwritten:`
2490
- for (const c of stats.conflicts.slice(0, 10)) text += `\n ${c.path} — ${c.reason}`
2491
- if (stats.conflicts.length > 10) text += `\n … and ${stats.conflicts.length - 10} more`
2492
- text += '\n(use force=true to override)'
2493
- }
2494
- return { text }
2495
- }, !!args.dryRun)
2496
- // Issue #68: a real sync can pull in (or obsolete) instruction files —
2497
- // refresh the prompt index afterwards. Kept inside the task body so a
2498
- // background sync refreshes when IT finishes, not when it is queued.
2499
- const runSyncAndIndex = async () => {
2500
- const r = await runSync()
2501
- if (!args.dryRun) {
2502
- try { await instructionIndex.refresh({ pool: b.pool, ws: p, mirrorDir: local, force: true }) } catch { /* best effort */ }
2503
- }
2504
- return r
2505
- }
2506
- if (args.async) {
2507
- const t = tasks.start('sync', `sync ${p}`, runSyncAndIndex)
2508
- return { text: `sync started in background: taskId=${t.id} (GET /dsh-remote/task?id=${t.id} for progress)` }
2509
- }
2510
- return runSyncAndIndex()
2511
- },
2512
- }),
2513
-
2514
- defineTool({
2515
- name: 'rw_push',
2516
- description:
2517
- 'Upload the local mirror of the current remote workspace back to the remote host over SFTP (bounded, three-way conflict-aware). Use after editing files in the local mirror so the remote reflects your changes. Conflicts (both sides modified) are reported and never overwritten; use force=true to override.',
2518
- parameters: {
2519
- maxFiles: { type: 'integer', description: 'Max files to upload (default 2000)' },
2520
- dryRun: { type: 'boolean', description: 'Compute the plan without uploading (default false)' },
2521
- force: { type: 'boolean', description: 'Overwrite conflicting files (default false)' },
2522
- async: { type: 'boolean', description: 'Run in the background and return a task id (default false)' },
2523
- },
2524
- output: textOut,
2525
- async execute(args, exec) {
2526
- const b = requireBinding(exec, 'rw_push')
2527
- const p = b.ws
2528
- const local = b.mirrorDir || mirrorDirFor(p, b.host, b.username, b.port)
2529
- if (!existsSync(local)) throw new Error(`rw_push: local mirror does not exist — run rw_sync first (${local})`)
2530
- const maxFiles = Math.min(Math.max(Number(args.maxFiles) || 2000, 1), 20000)
2531
- const isIgnored = ignoreMatcher(p)
2532
- const body = { maxFiles, dryRun: !!args.dryRun, force: !!args.force, isIgnored }
2533
- const runPush = () => syncActivity.run(local, 'upload', async (record) => {
2534
- let sftp
2535
- try {
2536
- sftp = await b.pool.sftp()
2537
- } catch (err) {
2538
- throw new Error('sftp unavailable: ' + ((err && err.message) || err))
2539
- }
2540
- const state = loadSyncState(local)
2541
- try {
2542
- const { stats, nextState } = await pushTree(sftp, local, p, { ...body, state, maxFileBytes: config.maxFileBytes })
2543
- record(stats)
2544
- if (!args.dryRun) saveSyncState(local, nextState)
2545
- let text = `${args.dryRun ? 'WOULD upload' : 'Uploaded'} ${stats.files} file(s) from ${local} → ${p}.`
2546
- if (stats.truncated || stats.files >= maxFiles) text += ` TRUNCATED (hit maxFiles=${maxFiles} cap; raise maxFiles and re-run).`
2547
- if (stats.skippedUnchanged) text += ` ${stats.skippedUnchanged} unchanged.`
2548
- if (stats.skippedLarge) text += ` ${stats.skippedLarge} too large (over ${config.maxFileBytes} bytes).`
2549
- if (stats.staleLocal) text += ` ${stats.staleLocal} local entries gone remotely (kept remotely; use rw_remove to mirror deletions).`
2550
- if (stats.conflicts.length) {
2551
- text += `\n⚠ ${stats.conflicts.length} conflict(s), NOT overwritten:`
2552
- for (const c of stats.conflicts.slice(0, 10)) text += `\n ${c.path} — ${c.reason}`
2553
- if (stats.conflicts.length > 10) text += `\n … and ${stats.conflicts.length - 10} more`
2554
- text += '\n(use force=true to override)'
2555
- }
2556
- return { text }
2557
- } finally {
2558
- // Sync AND async tasks share this body: invalidate only after the
2559
- // actual push settles (partial uploads may have changed the remote).
2560
- if (!args.dryRun && remoteSkills) remoteSkills.invalidate()
2561
- }
2562
- }, !!args.dryRun)
2563
- if (args.async) {
2564
- const t = tasks.start('push', `push ${p}`, runPush)
2565
- return { text: `push started in background: taskId=${t.id} (GET /dsh-remote/task?id=${t.id} for progress)` }
2566
- }
2567
- return runPush()
2568
- },
2569
- }),
2570
-
2571
- defineTool({
2572
- name: 'rw_list_dir',
2573
- description:
2574
- 'List a remote directory (or a single file) via SSH. Path is absolute; accepts Windows paths like C:\\Users\\dev\\project on Git Bash remotes. If omitted, lists the current remote workspace. Shows type, size, mtime.',
2575
- parameters: {
2576
- path: { type: 'string', description: 'Absolute remote path (default: current remote workspace)' },
2577
- },
2578
- output: textOut,
2579
- async execute(args, exec) {
2580
- const b = requireBinding(exec, 'rw_list_dir')
2581
- const p = args.path ? resolveRemoteArg(b, args.path) : b.ws
2582
- if (!p) throw new Error('rw_list_dir: no path and no remote workspace set')
2583
- let list
2584
- try {
2585
- const sftp = await b.pool.sftp()
2586
- list = await sftp.readdir(p)
2587
- } catch (err) {
2588
- throw new Error('rw_list_dir: ' + ((err && err.message) || err))
2589
- }
2590
- const fmtMtime = (t) => {
2591
- if (!t) return '?'
2592
- const d = new Date(t * 1000)
2593
- const pad = (n) => String(n).padStart(2, '0')
2594
- return `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())} ${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}`
2595
- }
2596
- const lines = list
2597
- .filter((e) => String(e.filename) !== '.' && String(e.filename) !== '..')
2598
- .map((e) => {
2599
- const a = e.attrs || {}
2600
- const type = a.isDirectory && a.isDirectory() ? 'd' : (a.isSymbolicLink && a.isSymbolicLink() ? 'l' : '-')
2601
- const size = typeof a.size === 'number' ? String(a.size) : '?'
2602
- return `${type} ${size.padStart(10)} ${fmtMtime(a.mtime).padEnd(17)} ${String(e.filename)}`
2603
- })
2604
- return { text: lines.length ? lines.join('\n') : '(empty directory)' }
2605
- },
2606
- }),
2607
-
2608
- defineTool({
2609
- name: 'rw_stat',
2610
- description:
2611
- 'Show detailed stat of a remote file or directory: type, size, mtime, mode (SFTP attrs). Use to verify a remote path exists or to compare files.',
2612
- parameters: {
2613
- path: { type: 'string', required: true, description: 'Absolute remote path' },
2614
- },
2615
- output: textOut,
2616
- async execute(args, exec) {
2617
- const b = requireMachine(exec, 'rw_stat')
2618
- const p = resolveRemoteArg(b, args.path)
2619
- if (!p) throw new Error('rw_stat: path is required')
2620
- const sftp = await b.pool.sftp()
2621
- let st
2622
- try {
2623
- st = await sftp.stat(p)
2624
- } catch (err) {
2625
- throw new Error('rw_stat: not found or unreadable: ' + ((err && err.message) || err))
2626
- }
2627
- const type = st.isDirectory && st.isDirectory() ? 'directory' : (st.isSymbolicLink && st.isSymbolicLink() ? 'symlink' : 'file')
2628
- const lines = [
2629
- `path: ${p}`,
2630
- `type: ${type}`,
2631
- `size: ${st.size} bytes`,
2632
- `mtime: ${new Date(st.mtime * 1000).toISOString()}`,
2633
- `mode: ${typeof st.mode === 'number' ? st.mode.toString(8) : '?'}`,
2634
- ]
2635
- return { text: lines.join('\n') }
2636
- },
2637
- }),
2638
-
2639
- defineTool({
2640
- name: 'rw_read_file',
2641
- description:
2642
- 'Read a text file on the remote host with line numbers. Supports paging with startLine/endLine and an encoding param (utf-8 default, gbk etc). Path is absolute.',
2643
- parameters: {
2644
- path: { type: 'string', required: true, description: 'Absolute remote file path' },
2645
- startLine: { type: 'integer', description: '1-based first line (default 1)' },
2646
- endLine: { type: 'integer', description: '1-based last line (inclusive)' },
2647
- maxLines: { type: 'integer', description: 'Max lines (default 2000)' },
2648
- encoding: { type: 'string', description: 'Text encoding, e.g. utf-8 (default) or gbk' },
2649
- },
2650
- output: textOut,
2651
- async execute(args, exec) {
2652
- const b = requireMachine(exec, 'rw_read_file')
2653
- const p = resolveRemoteArg(b, args.path)
2654
- if (!p) throw new Error('rw_read_file: path is required')
2655
- const maxLines = Math.min(Math.max(Number(args.maxLines) || 2000, 1), 10000)
2656
- let from = Math.max(Number(args.startLine) || 1, 1)
2657
- let to = Number(args.endLine) || 0
2658
- if (!to || to - from + 1 > maxLines) to = from + maxLines - 1
2659
- const sftp = await b.pool.sftp()
2660
- let st
2661
- try { st = await sftp.stat(p) } catch (err) { throw new Error('rw_read_file: ' + ((err && err.message) || err)) }
2662
- if (config.maxFileBytes > 0 && st.size > config.maxFileBytes) {
2663
- throw new Error(`rw_read_file: file is ${st.size} bytes (over ${config.maxFileBytes} cap); use rw_download or rw_exec to read it`)
2664
- }
2665
- let buf
2666
- try {
2667
- buf = await sftp.readFile(p)
2668
- } catch (err) {
2669
- throw new Error('rw_read_file: ' + ((err && err.message) || err))
2670
- }
2671
- const content = decodeBuf(buf, args.encoding || config.encoding).replace(/\r\n/g, '\n')
2672
- const allLines = content.split('\n')
2673
- const page = allLines.slice(from - 1, to)
2674
- const numbered = page.map((l, i) => `${String(from + i).padStart(6)}\t${l}`).join('\n').replace(/\s+$/, '')
2675
- let text = numbered === '' ? '(empty or out of range)' : numbered
2676
- if (!args.endLine) text += '\n(shown up to ' + maxLines + ' lines; use startLine/endLine to page)'
2677
- return { text }
2678
- },
2679
- }),
2680
-
2681
- defineTool({
2682
- name: 'rw_write_file',
2683
- description:
2684
- 'Write text to a file on the remote host (creating parent directories if needed). Path is absolute. Use this to create or overwrite a remote file directly, instead of round-tripping through a local mirror.',
2685
- parameters: {
2686
- path: { type: 'string', required: true, description: 'Absolute remote file path' },
2687
- content: { type: 'string', required: true, description: 'File content to write (overwrites existing file)' },
2688
- mkdir: { type: 'boolean', description: 'Create missing parent directories (default true)' },
2689
- encoding: { type: 'string', description: 'Text encoding, e.g. utf-8 (default) or gbk' },
2690
- },
2691
- output: changeOutput,
2692
- presentResult: presentFileChange,
2693
- async execute(args, exec) {
2694
- const b = requireMachine(exec, 'rw_write_file')
2695
- // Remote sandbox fence: a write must be permitted by this session's resolved mode.
2696
- requireRemoteSandbox(exec, 'write', { tool: 'rw_write_file', path: String(args.path || '') })
2697
- const p = resolveRemoteArg(b, args.path)
2698
- if (!p || p === '/') throw new Error('rw_write_file: a file path is required')
2699
- const content = String(args.content == null ? '' : args.content)
2700
- const sftp = await b.pool.sftp()
2701
- const before = await captureRemoteFile(sftp, p)
2702
- if (args.mkdir !== false) await mkdirRemoteDirs(sftp, remoteDirname(p))
2703
- const buf = encodeText(content, args.encoding || config.encoding)
2704
- await atomicRemoteWrite(sftp, before, buf)
2705
- const bytes = buf.byteLength
2706
- audit('write_file', `write ${p} (${bytes}B)`, 0, b)
2707
- return { ok: true, bytes, change: fileChange(p, 'write', before.bytes === null ? null : before.bytes === undefined ? undefined : decodeBuf(before.bytes, args.encoding || config.encoding), content), text: `wrote ${bytes} bytes to ${p}` }
2708
- },
2709
- }),
2710
-
2711
- defineTool({
2712
- name: 'rw_edit',
2713
- description:
2714
- 'Edit a remote text file by replacing literal text (read-modify-write with an mtime optimistic lock: aborts if the file changed on the remote between read and write). Path is absolute. Accepts the aliases old_string/new_string (and file_path for path), matching the host edit tool, so either spelling works.',
2715
- parameters: {
2716
- // `path`/`old`/`new` also accept the host edit tool's spellings
2717
- // (file_path/old_string/new_string): models habitually use those, and a
2718
- // schema-level `required` on only one spelling rejects the other before
2719
- // execute() ever runs. So NONE of them is declared required here — the
2720
- // resolver below enforces "path + old + new" and reports which spelling
2721
- // to pass. Keep this in sync: adding `required: true` back to any of
2722
- // these silently breaks its alias.
2723
- path: { type: 'string', description: 'Absolute remote file path (alias: file_path)' },
2724
- old: { type: 'string', description: 'Literal text to replace (must appear exactly once unless count is given). Alias: old_string' },
2725
- new: { type: 'string', description: 'Replacement text; an empty string deletes the old text. Alias: new_string' },
2726
- old_string: { type: 'string', description: 'Alias of old (same meaning)' },
2727
- new_string: { type: 'string', description: 'Alias of new (same meaning)' },
2728
- file_path: { type: 'string', description: 'Alias of path (same meaning)' },
2729
- count: { type: 'integer', description: 'How many occurrences to replace (default: error if the text appears more than once)' },
2730
- encoding: { type: 'string', description: 'Text encoding, e.g. utf-8 (default) or gbk' },
2731
- },
2732
- output: changeOutput,
2733
- presentResult: presentFileChange,
2734
- async execute(args, exec) {
2735
- const b = requireMachine(exec, 'rw_edit')
2736
- // Remote sandbox fence: a write must be permitted by this session's resolved mode.
2737
- requireRemoteSandbox(exec, 'write', { tool: 'rw_edit', path: String(args.path || args.file_path || '') })
2738
- // Presence must be checked on the RAW argument, not on the resolved
2739
- // path: resolveRemoteArg falls back to the workspace root for an empty
2740
- // string, so `!p` would never fire and a pathless rw_edit would silently
2741
- // target the workspace root. (That is why `path` cannot simply lose its
2742
- // schema `required` without this check replacing it.)
2743
- const rawPath = args.path ?? args.file_path
2744
- if (rawPath == null || String(rawPath).trim() === '') {
2745
- throw new Error('rw_edit: a file path is required — pass path (alias: file_path)')
2746
- }
2747
- const p = resolveRemoteArg(b, rawPath)
2748
- if (!p || p === '/') throw new Error('rw_edit: a file path is required — pass path (alias: file_path)')
2749
- const oldRaw = args.old ?? args.old_string
2750
- const newRaw = args.new ?? args.new_string
2751
- if (oldRaw == null) throw new Error('rw_edit: old text is required — pass old (alias: old_string)')
2752
- if (newRaw == null) throw new Error('rw_edit: replacement text is required — pass new (alias: new_string); use an empty string to delete the old text')
2753
- const oldS = String(oldRaw)
2754
- const newS = String(newRaw)
2755
- if (oldS === '') throw new Error('rw_edit: old text must not be empty')
2756
- const sftp = await b.pool.sftp()
2757
- const before = await captureRemoteFile(sftp, p, { read: true, maxReadBytes: config.maxFileBytes })
2758
- if (!before.stat) throw new Error('rw_edit: file not found')
2759
- if (config.maxFileBytes > 0 && before.stat.size > config.maxFileBytes) throw new Error('rw_edit: file exceeds maxFileBytes')
2760
- const buf = before.bytes
2761
- const content = decodeBuf(buf, args.encoding || config.encoding)
2762
- const count = args.count == null ? 0 : Math.max(Number(args.count) || 1, 1)
2763
- const idxs = []
2764
- let from = 0
2765
- let hit
2766
- while ((hit = content.indexOf(oldS, from)) !== -1) { idxs.push(hit); from = hit + oldS.length }
2767
- if (!idxs.length) throw new Error(`rw_edit: old text not found in ${p}`)
2768
- if (count === 0 && idxs.length > 1) {
2769
- throw new Error(`rw_edit: "old" appears ${idxs.length} times in ${p} — pass count=<n> to pick how many to replace`)
2770
- }
2771
- const n = count === 0 ? 1 : Math.min(count, idxs.length)
2772
- let out = content
2773
- for (let i = n - 1; i >= 0; i--) {
2774
- out = out.slice(0, idxs[i]) + newS + out.slice(idxs[i] + oldS.length)
2775
- }
2776
- await atomicRemoteWrite(sftp, before, encodeText(out, args.encoding || config.encoding))
2777
- audit('edit', `edit ${p} (${n} occurrence(s))`, 0, b)
2778
- return { ok: true, bytes: encodeText(out, args.encoding || config.encoding).byteLength, change: fileChange(p, 'edit', content, out), text: `edited ${p}: replaced ${n} occurrence(s)` }
2779
- },
2780
- }),
2781
-
2782
- defineTool({
2783
- name: 'rw_append',
2784
- description:
2785
- 'Append text to a remote file (creates it when missing). Path is absolute.',
2786
- parameters: {
2787
- path: { type: 'string', required: true, description: 'Absolute remote file path' },
2788
- content: { type: 'string', required: true, description: 'Text to append' },
2789
- encoding: { type: 'string', description: 'Text encoding, e.g. utf-8 (default) or gbk' },
2790
- },
2791
- output: changeOutput,
2792
- presentResult: presentFileChange,
2793
- async execute(args, exec) {
2794
- const b = requireMachine(exec, 'rw_append')
2795
- // Remote sandbox fence: a write must be permitted by this session's resolved mode.
2796
- requireRemoteSandbox(exec, 'write', { tool: 'rw_append', path: String(args.path || '') })
2797
- const p = resolveRemoteArg(b, args.path)
2798
- if (!p || p === '/') throw new Error('rw_append: a file path is required')
2799
- const sftp = await b.pool.sftp()
2800
- const before = await captureRemoteFile(sftp, p, { read: true, maxReadBytes: config.maxFileBytes })
2801
- const existing = before.bytes ? decodeBuf(before.bytes, args.encoding || config.encoding) : ''
2802
- const content = existing + String(args.content ?? '')
2803
- const encoded = encodeText(content, args.encoding || config.encoding)
2804
- await atomicRemoteWrite(sftp, before, encoded)
2805
- const bytes = encoded.byteLength
2806
- audit('append', `append ${p}`, 0, b)
2807
- return { ok: true, bytes, change: fileChange(p, 'append', before.bytes === null ? null : existing, content), text: `appended to ${p} (now ${bytes} bytes)` }
2808
- },
2809
- }),
2810
-
2811
- defineTool({
2812
- name: 'rw_mkdir',
2813
- description:
2814
- 'Create a remote directory (mkdir -p semantics, all levels). Path is absolute.',
2815
- parameters: {
2816
- path: { type: 'string', required: true, description: 'Absolute remote directory path' },
2817
- },
2818
- output: textOut,
2819
- async execute(args, exec) {
2820
- const b = requireMachine(exec, 'rw_mkdir')
2821
- // Remote sandbox fence: a write must be permitted by this session's resolved mode.
2822
- requireRemoteSandbox(exec, 'write', { tool: 'rw_mkdir', path: String(args.path || '') })
2823
- const p = resolveRemoteArg(b, args.path)
2824
- if (!p || p === '/') throw new Error('rw_mkdir: a directory path is required')
2825
- const sftp = await b.pool.sftp()
2826
- await mkdirRemoteDirs(sftp, p)
2827
- audit('mkdir', `mkdir ${p}`, 0, b)
2828
- return { text: `created ${p}` }
2829
- },
2830
- }),
2831
-
2832
- defineTool({
2833
- name: 'rw_remove',
2834
- description:
2835
- 'Delete a remote file (or an empty directory). recursive=true removes a directory tree (bounded). Path is absolute. This is destructive — the agent should confirm intent before calling.',
2836
- parameters: {
2837
- path: { type: 'string', required: true, description: 'Absolute remote path to delete' },
2838
- recursive: { type: 'boolean', description: 'Recursively delete a directory (default false)' },
2839
- },
2840
- output: okOut,
2841
- async execute(args, exec) {
2842
- const b = requireMachine(exec, 'rw_remove')
2843
- // Remote sandbox fence: a write must be permitted by this session's resolved mode.
2844
- requireRemoteSandbox(exec, 'write', { tool: 'rw_remove', path: String(args.path || '') })
2845
- const p = resolveRemoteArg(b, args.path)
2846
- if (!p || p === '/') throw new Error('rw_remove: a path is required')
2847
- const sftp = await b.pool.sftp()
2848
- const st = await sftp.stat(p).catch(() => null)
2849
- if (!st) return { ok: false, text: `not found: ${p}` }
2850
- if (st.isDirectory && st.isDirectory()) {
2851
- if (!args.recursive) throw new Error(`rw_remove: ${p} is a directory — pass recursive=true to delete its tree`)
2852
- const removed = await removeRemoteTree(sftp, p)
2853
- audit('remove', `remove -r ${p}`, 0, b)
2854
- return { ok: true, text: `removed ${removed} entries under ${p}` }
2855
- }
2856
- await sftp.unlink(p)
2857
- audit('remove', `remove ${p}`, 0, b)
2858
- return { ok: true, text: `removed ${p}` }
2859
- },
2860
- }),
2861
-
2862
- defineTool({
2863
- name: 'rw_move',
2864
- description:
2865
- 'Rename or move a remote file/directory (SFTP rename, same filesystem). Paths are absolute.',
2866
- parameters: {
2867
- path: { type: 'string', required: true, description: 'Current absolute remote path' },
2868
- dest: { type: 'string', required: true, description: 'Destination absolute remote path' },
2869
- },
2870
- output: textOut,
2871
- async execute(args, exec) {
2872
- const b = requireMachine(exec, 'rw_move')
2873
- // Remote sandbox fence: a write must be permitted by this session's resolved mode.
2874
- requireRemoteSandbox(exec, 'write', { tool: 'rw_move', path: String(args.source || args.path || '') })
2875
- const p = resolveRemoteArg(b, args.path)
2876
- const d = resolveRemoteArg(b, args.dest)
2877
- if (!p || !d || p === '/') throw new Error('rw_move: both path and dest are required')
2878
- const sftp = await b.pool.sftp()
2879
- await mkdirRemoteDirs(sftp, remoteDirname(d))
2880
- await sftp.rename(p, d)
2881
- audit('move', `move ${p} → ${d}`, 0, b)
2882
- return { text: `moved ${p} → ${d}` }
2883
- },
2884
- }),
2885
-
2886
- defineTool({
2887
- name: 'rw_exec',
2888
- description:
2889
- 'Run a shell command on the remote host. Use for anything that is not reading a file (build, test, grep, etc). Output is capped. Runs in the current remote workspace by default; pass cwd to run elsewhere. pty=true helps interactive commands (sudo prompts, REPLs); env sets environment variables. timeoutMs (1000-600000) overrides the machine-wide commandTimeoutMs for this call only. A command that outlives its timeout is MOVED TO A BACKGROUND JOB instead of being killed (pass promoteOnTimeout=false to kill it instead); run_in_background=true returns immediately with a job id. Background jobs are read with job_output and stopped with job_kill.',
2890
- parameters: {
2891
- command: { type: 'string', required: true, description: 'Shell command (run on the remote host)' },
2892
- cwd: { type: 'string', description: 'Working directory for the command (default: the current remote workspace)' },
2893
- pty: { type: 'boolean', description: 'Allocate a pseudo-terminal (interactive commands, default false)' },
2894
- env: { type: 'object', additionalProperties: true, description: 'Extra environment variables (string values)' },
2895
- timeoutMs: { type: 'integer', description: 'Timeout for THIS call in milliseconds (clamped to 1000-600000; default: the commandTimeoutMs config)' },
2896
- run_in_background: { type: 'boolean', description: 'Return a job id immediately and let the command run in the background (read it with job_output, stop it with job_kill)' },
2897
- promoteOnTimeout: { type: 'boolean', description: 'When the command outlives its timeout, move it to a background job instead of killing it (default true; needs the core jobs service)' },
2898
- },
2899
- output: execOut,
2900
- async execute(args, exec) {
2901
- const startedAt = Date.now()
2902
- const b = requireBinding(exec, 'rw_exec')
2903
- // Remote sandbox fence: commands change remote state.
2904
- requireRemoteSandbox(exec, 'exec', { tool: 'rw_exec' })
2905
- const cmd = String(args.command || '')
2906
- if (!cmd) throw new Error('rw_exec: command is required')
2907
- const ws = b.ws
2908
- const cwd = args.cwd ? resolveRemoteArg(b, args.cwd) : (ws || '')
2909
- const output = (text, result, jobId) => {
2910
- const signal = result && result.signal
2911
- const code = result && result.code
2912
- const status = jobId ? 'background' : signal === 'ABORTED' ? 'stopped' : signal === 'TIMEOUT' ? 'timeout'
2913
- : Number.isInteger(code) ? (code === 0 && !signal ? 'completed' : 'failed') : 'unknown'
2914
- return { text, execution: {
2915
- kind: 'dsh-remote.exec', version: 1, status, host: String(b.host || ''), cwd: String(cwd),
2916
- durationMs: Math.max(0, Date.now() - startedAt),
2917
- ...(Number.isInteger(code) ? { code } : {}), ...(signal ? { signal: String(signal) } : {}), ...(jobId ? { jobId: String(jobId) } : {}),
2918
- } }
2919
- }
2920
- let full = cmd
2921
- if (cwd) {
2922
- // Detect before choosing the cwd form: a per-machine pool starts
2923
- // undetected, and reading `platform` first would skip the Git Bash
2924
- // mount-path rewrite on the first command sent to a Windows host.
2925
- // detect() is cached and idempotent, so this costs one probe per pool.
2926
- try { await b.pool.detect() } catch { /* probe failed → fall through to the POSIX form */ }
2927
- if (b.pool.platform === 'windows' && b.pool.gitBashPath) {
2928
- // Git Bash terminal: cd in the /c/Users/… mount form
2929
- full = `cd ${shq(toShellPath(cwd))} && ${cmd}`
2930
- } else if (!cwd.includes('\\')) {
2931
- full = `cd ${shq(cwd)} && ${cmd}`
2932
- }
2933
- }
2934
- // Issue #70: a per-call override, clamped, and the value we report is
2935
- // the one we actually applied (never the config value behind an
2936
- // override's back).
2937
- const timeoutMs = resolveExecTimeout(args.timeoutMs, config.commandTimeoutMs)
2938
- const registry = jobRegistry()
2939
- const owner = exec && exec.agent ? exec.agent.id : undefined
2940
- const promote = registry !== null && args.promoteOnTimeout !== false
2941
- try {
2942
- if (args.run_in_background) {
2943
- if (!registry) {
2944
- throw new Error('rw_exec: run_in_background needs the DSH jobs service, which this composition does not provide')
2945
- }
2946
- // A background job needs its OWN deadline, or nothing would ever
2947
- // stop a runaway command. `timeoutMs` becomes that deadline here
2948
- // (unlike the promote path, where it only bounds the caller's wait).
2949
- const job = startExecJob(registry, { pool: b.pool, command: full, label: cmd, owner, jobDeadlineMs: timeoutMs, pty: args.pty, env: args.env })
2950
- audit('exec-background', cmd, 0, b)
2951
- return output(`started in the background: jobId=${job.id}\n`
2952
- + `Read its output with job_output (job_id="${job.id}"); stop it with job_kill.\n`
2953
- + `(the job is killed if it outlives ${timeoutMs}ms)`, null, job.id)
2954
- }
2955
- if (promote) {
2956
- const r = await execWithOptionalPromotion({
2957
- registry, pool: b.pool, command: full, label: cmd, owner, timeoutMs,
2958
- pty: args.pty, env: args.env, signal: exec && exec.signal, formatResult: formatExecResult,
2959
- })
2960
- audit('exec', cmd, r.result ? r.result.code : 0, b)
2961
- return output(r.text, r.result, r.promoted ? r.jobId : undefined)
2962
- }
2963
- const res = await b.pool.exec(full, { timeoutMs, pty: !!args.pty, env: args.env, signal: exec && exec.signal })
2964
- audit('exec', cmd, res.code, b)
2965
- return output(formatExecResult(res, { timeoutMs }), res)
2966
- } catch (err) {
2967
- throw new Error(friendlyMessage(err, { host: b.host, port: b.port }))
2968
- }
2969
- },
2970
- }),
2971
-
2972
- defineTool({
2973
- name: 'rw_search',
2974
- description:
2975
- 'Search remote files for a pattern. POSIX remotes try `rg` then `grep -R` first; Windows and fallbacks use a portable SFTP walk. Honors ignore rules. Returns matching file:line rows; output is capped. Search is bounded (maxEntries/maxDurationMs) and can be cancelled: on a very large tree it returns partial results marked TRUNCATED instead of running indefinitely.',
2976
- // A cooperative budget for @deepseek-ai/dsh-tool-call-timeout-policy.
2977
- // Only useful together with the cancellation support below: the policy can
2978
- // only *ask* a tool to stop, so a tool that ignores exec.signal would keep
2979
- // the caller waiting (issue #44).
2980
- timeoutMs: config.searchTimeoutMs,
2981
- parameters: {
2982
- pattern: { type: 'string', required: true, description: 'Pattern to search for (extended regex)' },
2983
- path: { type: 'string', description: 'Directory to search (default: current remote workspace)' },
2984
- glob: { type: 'string', description: 'Only files whose NAME matches this glob, e.g. *.ts (optional)' },
2985
- ignoreCase: { type: 'boolean', description: 'Case-insensitive search (default true)' },
2986
- contextLines: { type: 'integer', description: 'Lines of context around each match (default 0)' },
2987
- maxMatches: { type: 'integer', description: 'Max matches to return (default 500)' },
2988
- maxEntries: { type: 'integer', description: 'Stop after scanning this many files (default 50000)' },
2989
- maxDurationMs: { type: 'integer', description: 'Stop after this many ms and return partial results (default 60000)' },
2990
- },
2991
- output: textOut,
2992
- async execute(args, exec) {
2993
- const b = requireBinding(exec, 'rw_search')
2994
- const pattern = String(args.pattern || '')
2995
- if (!pattern) throw new Error('rw_search: pattern is required')
2996
- const ws = b.ws
2997
- const dir = args.path ? resolveRemoteArg(b, args.path) : (ws || '')
2998
- if (!dir) throw new Error('rw_search: no path and no remote workspace set')
2999
- let regex
3000
- try {
3001
- regex = new RegExp(pattern, args.ignoreCase === false ? '' : 'i')
3002
- } catch (err) {
3003
- throw new Error('rw_search: bad pattern: ' + ((err && err.message) || err))
3004
- }
3005
- const maxMatches = Math.min(Math.max(Number(args.maxMatches) || 500, 1), 2000)
3006
- // Budgets. The SFTP walk had NO entry/duration cap before, so a search
3007
- // over a home directory could run for hours while the turn stayed
3008
- // `running` and cancel/steer did nothing (issue #44).
3009
- const maxFiles = Math.min(Math.max(Number(args.maxEntries) || config.searchMaxEntries, 1), 500000)
3010
- const maxDurationMs = Math.min(Math.max(Number(args.maxDurationMs) || config.searchTimeoutMs, 1000), 600000)
3011
- const matcher = searchIgnoreMatcher(dir)
3012
- const { matches, scanned, truncated, cancelled } = await searchRemote(b.pool, dir, {
3013
- pattern,
3014
- regex,
3015
- glob: args.glob,
3016
- ignoreCase: args.ignoreCase !== false,
3017
- contextLines: Math.min(Math.max(Number(args.contextLines) || 0, 0), 10),
3018
- maxMatches,
3019
- maxFiles,
3020
- maxDurationMs,
3021
- signal: exec.signal,
3022
- maxScanBytes: Math.min(config.maxFileBytes || 1024 * 1024, 1024 * 1024),
3023
- isIgnored: (name, isDir) => matcher(name, isDir),
3024
- timeoutMs: Math.min(config.commandTimeoutMs, maxDurationMs),
3025
- })
3026
- const note = cancelled
3027
- ? `, CANCELLED after ${scanned} files scanned`
3028
- : truncated
3029
- ? ', TRUNCATED'
3030
- : ''
3031
- if (!matches.length) {
3032
- return { text: `no matches for /${pattern}/ in ${dir} (${scanned} files scanned${note})` }
3033
- }
3034
- let text = matches.map((m) => `${m.path}:${m.line}: ${m.text}`).join('\n')
3035
- text += `\n(${matches.length} match(es), ${scanned} files scanned${note})`
3036
- return { text: truncate(text, config.maxOutputChars) }
3037
- },
3038
- }),
3039
-
3040
- defineTool({
3041
- name: 'rw_download',
3042
- description:
3043
- 'Download a single remote file over SFTP into the local mirror of the current workspace (or to an explicit local path). Use when you need the actual file content locally, not just its text. Streams to disk (fastGet).',
3044
- parameters: {
3045
- path: { type: 'string', required: true, description: 'Absolute remote file path' },
3046
- localPath: { type: 'string', description: 'Local destination (default: the workspace mirror, preserving the relative path)' },
3047
- },
3048
- output: okOut,
3049
- async execute(args, exec) {
3050
- const b = requireMachine(exec, 'rw_download')
3051
- const p = resolveRemoteArg(b, args.path)
3052
- if (!p || p === '/') throw new Error('rw_download: a remote file path is required')
3053
- const sftp = await b.pool.sftp()
3054
- let local
3055
- if (args.localPath) {
3056
- local = path.resolve(String(args.localPath))
3057
- } else {
3058
- const ws = b.ws
3059
- if (!ws) throw new Error('rw_download: no remote workspace set — pass localPath explicitly')
3060
- const base = mirrorDirFor(ws, b.host, b.username, b.port)
3061
- const rel = p.startsWith(ws) ? p.slice(ws.length).replace(/^\/+/, '') : p.slice(1)
3062
- local = path.join(base, rel)
3063
- }
3064
- mkdirSync(path.dirname(local), { recursive: true })
3065
- const st = await sftp.stat(p).catch(() => null)
3066
- if (config.maxFileBytes > 0 && st && st.size > config.maxFileBytes) {
3067
- throw new Error(`rw_download: file is ${st.size} bytes (over ${config.maxFileBytes} cap)`)
3068
- }
3069
- await sftp.fastGet(p, local)
3070
- const bytes = existsSync(local) ? statSync(local).size : 0
3071
- return { ok: true, bytes, text: `downloaded ${bytes} bytes from ${p} → ${local}` }
3072
- },
3073
- }),
3074
-
3075
- defineTool({
3076
- name: 'rw_upload',
3077
- description:
3078
- 'Upload a local file over SFTP to a path on the remote host (creating parent directories if needed). Use to push a local file directly, without a full rw_push of the whole mirror.',
3079
- parameters: {
3080
- localPath: { type: 'string', required: true, description: 'Absolute local file path' },
3081
- path: { type: 'string', required: true, description: 'Absolute remote destination path' },
3082
- },
3083
- output: okOut,
3084
- async execute(args, exec) {
3085
- const b = requireMachine(exec, 'rw_upload')
3086
- // Remote sandbox fence: a write must be permitted by this session's resolved mode.
3087
- requireRemoteSandbox(exec, 'write', { tool: 'rw_upload', path: String(args.path || '') })
3088
- const rp = resolveRemoteArg(b, args.path)
3089
- const lp = String(args.localPath || '')
3090
- if (!rp || rp === '/' || !lp) throw new Error('rw_upload: both localPath and a remote path are required')
3091
- if (!existsSync(lp)) throw new Error(`rw_upload: local file not found: ${lp}`)
3092
- const sftp = await b.pool.sftp()
3093
- await mkdirRemoteDirs(sftp, remoteDirname(rp))
3094
- const st = statSync(lp)
3095
- await sftp.fastPut(lp, rp)
3096
- audit('upload', `upload ${lp} → ${rp}`, 0, b)
3097
- return { ok: true, bytes: st.size, text: `uploaded ${st.size} bytes from ${lp} → ${rp}` }
3098
- },
3099
- }),
3100
-
3101
-
3102
- defineTool({
3103
- name: 'rw_forward',
3104
- description:
3105
- 'Manage SSH port forwards. Direction "local" listens on 127.0.0.1:<listenPort> on THIS machine and forwards connections through SSH to <targetHost>:<targetPort> on the remote. Direction "reverse" asks the REMOTE to listen on 127.0.0.1:<listenPort> and pipes connections back to <targetHost>:<targetPort> on this machine. Call with a listenPort to create+start; with remove=true to delete.',
3106
- parameters: {
3107
- listenPort: { type: 'integer', required: true, description: 'Port to listen on (local for direction=local, remote for direction=reverse)' },
3108
- targetHost: { type: 'string', description: 'Forward target host (default 127.0.0.1)' },
3109
- targetPort: { type: 'integer', description: 'Forward target port (default: same as listenPort)' },
3110
- direction: { type: 'string', description: 'local (default) or reverse' },
3111
- autoStart: { type: 'boolean', description: 'Restart this forward automatically on future connects (default false)' },
3112
- remove: { type: 'boolean', description: 'Remove an existing forward by listenPort (default false)' },
3113
- },
3114
- output: textOut,
3115
- async execute(args, exec) {
3116
- const port = Number(args.listenPort)
3117
- if (!port || port < 1 || port > 65535) throw new Error('rw_forward: a valid listenPort is required')
3118
- // Remote sandbox fence: a forward opens a network path into the remote.
3119
- requireRemoteSandbox(exec, 'tunnel', { tool: 'rw_forward' })
3120
- const dir = args.direction === 'reverse' ? 'reverse' : 'local'
3121
- const existing = forwards.list().find((f) => Number(f.listenPort) === port && f.direction === dir)
3122
- if (args.remove) {
3123
- if (!existing) return { text: `no forward on port ${port} to remove` }
3124
- forwards.remove(existing.id)
3125
- return { text: `removed ${existing.direction} forward on port ${port}` }
3126
- }
3127
- if (existing && existing.active) return { text: `already active: ${existing.direction} forward 127.0.0.1:${port} → ${existing.targetHost}:${existing.targetPort}` }
3128
- const d = existing || forwards.define({
3129
- direction: dir,
3130
- listenPort: port,
3131
- targetHost: args.targetHost || '127.0.0.1',
3132
- targetPort: Number(args.targetPort) || port,
3133
- autoStart: !!args.autoStart,
3134
- machineId: store.currentId,
3135
- })
3136
- const r = await forwards.start(d)
3137
- audit('forward', `${d.direction} forward ${port} → ${d.targetHost}:${d.targetPort}`, r.ok ? 0 : 1)
3138
- if (!r.ok) throw new Error(r.error)
3139
- return { text: `${d.direction} forward active: 127.0.0.1:${port} → ${d.targetHost}:${d.targetPort} (id=${d.id})` }
3140
- },
3141
- }),
3142
-
3143
- defineTool({
3144
- name: 'rw_disconnect',
3145
- description:
3146
- "Close this session's SSH connection to its remote host, releasing the persistent pool. Useful to rotate a connection or after a long idle. Sessions bound to other machines keep their own connections.",
3147
- parameters: {},
3148
- output: okOut,
3149
- async execute(_args, exec) {
3150
- // Close the connection THIS session actually uses: closing the
3151
- // active-machine pool instead would look like a no-op to a bound
3152
- // session while disconnecting whichever machine happened to be active.
3153
- const b = bindingFor(exec)
3154
- b.pool.close()
3155
- if (!b.bound) return { ok: true, text: 'disconnected the active machine (forwards stopped)' }
3156
- return { ok: true, text: `disconnected ${b.username}@${b.host}:${b.port} for this session` }
3157
- },
3158
- }),
3159
-
3160
- ]
3161
-
3162
- for (const t of tools) {
3163
- ctx.tools.register(t)
3164
- }
3165
-
3166
- // ── system-prompt injection: session-aware remote workspace ──────────────
3167
- // Issue #13: remote context must be SESSION-scoped, not machine-global.
3168
- // The section text is evaluated per assembly with the current agent's
3169
- // session; it is injected ONLY when that session's cwd actually maps to a
3170
- // dsh-remote mirror (i.e. the user picked a remote workspace as the session
3171
- // workspace). A plain local session gets no remote section — saved machines
3172
- // never leak their workspace into an unrelated local session's prompt.
3173
- // (resolveMirrorForLocal is defined above, next to wsPath.)
3174
- ctx.systemPrompt.section({
3175
- name: 'dsh-remote',
3176
- order: 88,
3177
- text: (promptContext) => {
3178
- const agent = promptContext && promptContext.agent
3179
- const session = agent && agent.session
3180
- const cwd = session && session.header && session.header.cwd
3181
- if (!cwd) return '' // no session cwd → nothing to map → stay quiet
3182
- const { remotePath, machine, mirrorDir } = resolveMirrorForLocal(cwd)
3183
- if (!remotePath) return '' // this session is NOT a remote session (issue #13)
3184
- // Name the machine the MIRROR records, not the active one: pairing this
3185
- // session's remote path with whichever machine happens to be active
3186
- // states a host/path combination that may not exist (issue #25).
3187
- const who = machine
3188
- ? `${machine.username || 'user'}@${machine.host}`
3189
- : `${config.username || 'user'}@${config.host}`
3190
- const platform = machine ? poolForMachine(machine).platform : pool.platform
3191
- const shown = toDisplayPath(remotePath, platform)
3192
- const fwd = forwards.list().filter((f) => f.active).map((f) => `${f.direction}:127.0.0.1:${f.listenPort}→${f.targetHost}:${f.targetPort}`)
3193
- let extra = ''
3194
- if (fwd.length) extra = `\nActive port forwards: ${fwd.join(', ')}`
3195
- // Issue #68: surface the workspace's AGENTS.md / CLAUDE.md. The scan is
3196
- // lazy (fire-and-forget on first assembly; negative-cached on failure),
3197
- // so the index appears from the NEXT assembly once known — rw_pick_workspace
3198
- // scans eagerly, so a picked workspace normally has it from the start.
3199
- if (machine && mirrorDir) {
3200
- instructionIndex.note({ pool: poolForMachine(machine), ws: remotePath, mirrorDir })
3201
- const instr = instructionIndex.get(mirrorDir)
3202
- if (instr && instr.files && instr.files.length) {
3203
- extra += `\n${formatInstructionIndex(instr.files, (p) => toDisplayPath(p, platform))}`
3204
- }
3205
- }
3206
- // Issue #39: `@` mentions are resolved from the REMOTE tree by
3207
- // lib/file-reference.js, so the model must know they are remote-relative
3208
- // and that the built-in read tool sees only the local mirror.
3209
- const mirrorNote = mirrorDir ? ` (${mirrorDir})` : ''
3210
- return (
3211
- '## Remote workspace\n' +
3212
- `Current remote workspace: ${who}:${shown}\n` +
3213
- 'Use the rw_* tools (rw_list_dir / rw_read_file / rw_write_file / rw_edit / rw_exec / rw_search / rw_sync / rw_push / rw_download / rw_upload) to inspect and act on files on the remote host. Treat this directory as the working root for this task.\n' +
3214
- `\`@path\` mentions in this conversation name files under THAT remote root (\`@src/main.c\` = ${shown}/src/main.c). ` +
3215
- 'The rw_* tools take such paths as workspace-relative and resolve them against this root. ' +
3216
- `The harness's built-in local tools (read / write / edit / grep / glob / working_directory / local shell) only see the LOCAL mirror of this directory${mirrorNote}, which stays empty until rw_sync — use rw_read_file / rw_list_dir / rw_search / rw_exec for remote files, or rw_download to fetch a specific remote file locally.\n` +
3217
- 'Creating a file with local write/edit, a local shell, or Python does NOT save it on the remote host. Native write/edit mutations are refused in remote sessions: use rw_write_file / rw_edit or rw_exec to create and modify remote results. For an already-local artifact, explicitly use rw_push / rw_upload and verify it through rw_read_file or rw_stat before claiming it is saved remotely or giving a remote file link. run_code/PTC remains available for orchestration; its raw local filesystem IO is still LOCAL.\n' +
3218
- extra
3219
- )
3220
- },
3221
- })
3222
-
3223
- // ── local-session tool visibility (issues #63 / #117) ────────────────────
3224
- // All rw_* tools register globally (at registration time there is no session
3225
- // to consult). A scoped restriction is the primary filter: DSH feeds the
3226
- // SAME visible set to native schemas, the PTC SDK, run_code bindings and
3227
- // dispatch. Filtering assembled.tools alone cannot touch the PTC SDK, which
3228
- // is rendered from scope visibility before the assemble waterfall runs.
3229
- //
3230
- // Use deny, not an allowlist containing only the bootstrap tools: an allow
3231
- // filter applies to every inherited tool and would hide unrelated Harness
3232
- // capabilities too. Existing agents must be covered because this plugin
3233
- // hot-reloads; created/disposed listeners cover the normal agent lifecycle.
3234
- const localToolRestrictions = new Map()
3235
- const localToolNames = tools.map((t) => t.name)
3236
- const installLocalToolRestriction = (agent) => {
3237
- if (localToolRestrictions.has(agent)) return
3238
- const mode = normalizeLocalTools(config.localTools)
3239
- if (mode === 'all') return
3240
- const cwd = agent && agent.session && agent.session.header && agent.session.header.cwd
3241
- if (!cwd) return // no caller context → not definitively local
3242
- const { remotePath, machine } = resolveMirrorForLocal(String(cwd))
3243
- if (remotePath && machine) return // remote session → full surface
3244
- const agentCtx = agent && agent.ctx
3245
- // Optional service lookup avoids Cordis's "without inject" property error
3246
- // on custom/older agent contexts; get() still preserves the caller scope.
3247
- const agentTools = agentCtx && (typeof agentCtx.get === 'function' ? agentCtx.get('tools') : agentCtx.tools)
3248
- // Older DSH versions without scoped restriction keep the native waterfall
3249
- // fallback below instead of failing agent creation.
3250
- if (!agentTools || typeof agentTools.restrict !== 'function') return
3251
- const deny = mode === 'none'
3252
- ? localToolNames
3253
- : localToolNames.filter((name) => !LOCAL_BOOTSTRAP_TOOLS.includes(name))
3254
- if (deny.length === 0) return
3255
- try {
3256
- const dispose = agentTools.restrict({ deny })
3257
- if (typeof dispose === 'function') localToolRestrictions.set(agent, dispose)
3258
- } catch (error) {
3259
- // A creation listener must not reject the whole agent for a presentation
3260
- // compatibility problem. Native filtering remains active; surface the
3261
- // degraded PTC behavior instead of silently pretending it was fixed.
3262
- fileReferenceLog(`local tool restriction failed: ${(error && error.message) || error}`)
3263
- }
3264
- }
3265
- const disposeLocalToolRestriction = (agent) => {
3266
- const dispose = localToolRestrictions.get(agent)
3267
- if (!dispose) return Promise.resolve()
3268
- localToolRestrictions.delete(agent)
3269
- return Promise.resolve()
3270
- .then(() => dispose())
3271
- .catch((error) => fileReferenceLog(`local tool restriction cleanup failed: ${(error && error.message) || error}`))
3272
- }
3273
- const agents = typeof ctx.get === 'function' ? ctx.get('agents') : undefined
3274
- if (agents && typeof agents.list === 'function') {
3275
- for (const agent of agents.list()) installLocalToolRestriction(agent)
3276
- }
3277
- if (typeof ctx.on === 'function') {
3278
- ctx.on('agent/created', ({ agent }) => installLocalToolRestriction(agent))
3279
- ctx.on('agent/disposed', ({ agent }) => { void disposeLocalToolRestriction(agent) })
3280
- }
3281
- ctx.effect(
3282
- () => () => Promise.all([...localToolRestrictions.keys()].map((agent) => disposeLocalToolRestriction(agent))),
3283
- 'dsh-remote.local-tool-visibility',
3284
- )
3285
-
3286
- // Native/legacy fallback: the final per-request wire list also passes through
3287
- // this waterfall. PTC keeps only run_code here; its SDK is handled by the
3288
- // scoped restriction above. An assembly without agent/cwd is left alone,
3289
- // matching bindingFor's "no caller context" semantics. Minimal embeddings
3290
- // without event support retain the legacy full surface.
3291
- if (typeof ctx.on === 'function') {
3292
- ctx.on('system-prompt/assemble', async (_assembly, assembleContext, next) => {
3293
- const assembled = await next()
3294
- const mode = normalizeLocalTools(config.localTools)
3295
- if (mode === 'all') return assembled
3296
- const agent = assembleContext && assembleContext.agent
3297
- const cwd = agent && agent.session && agent.session.header && agent.session.header.cwd
3298
- if (!cwd) return assembled // no caller context → not definitively local
3299
- const { remotePath, machine } = resolveMirrorForLocal(String(cwd))
3300
- if (remotePath && machine) return assembled // remote session → full surface
3301
- const tools = (assembled.tools || []).filter(
3302
- (t) => !t.name || !t.name.startsWith('rw_') || (mode === 'bootstrap' && LOCAL_BOOTSTRAP_TOOLS.includes(t.name)),
3303
- )
3304
- return { ...assembled, tools }
3305
- })
3306
- }
3307
-
3308
- // ── dynamic remote instruction injection (issue #71) ──────────────────────
3309
- // #68 delivered the STATIC half (shallow scan + mirror + prompt index). The
3310
- // dynamic half the core does for local sessions was still missing, because
3311
- // the core's incremental path is keyed on (a) the tool names read/write/edit
3312
- // and (b) a `file_path` argument, and it expands scopes using LOCAL paths.
3313
- // `rw_read_file` is named differently, takes `path`, and its argument is a
3314
- // REMOTE absolute path — none of the three can ever line up.
3315
- //
3316
- // So the plugin does it itself, without touching core: after any successful
3317
- // rw_* file touch, take the touched path's whole ancestor chain below the
3318
- // workspace root, stat each level's AGENTS.md / CLAUDE.md, and hand the
3319
- // current contents to the model as ONE user message carrying our OWN source
3320
- // kind. Consumers fall through unknown kinds, and the core's reconcile only
3321
- // claims its own `agent-instructions` kind — which is exactly why the two
3322
- // injection paths cannot fight over the same inbox slot.
3323
- //
3324
- // Everything here is best-effort: the hook never rejects, never blocks the
3325
- // tool result, and treats an offline machine as "nothing to inject".
3326
- if (typeof ctx.on === 'function') {
3327
- ctx.on('tools/result', async (result, hookContext) => {
3328
- try {
3329
- const agent = hookContext && (hookContext.agent || (result && result.agent))
3330
- const name = String((hookContext && hookContext.name) || (result && result.name) || '')
3331
- // Only the tools that actually reach a remote file. `rw_exec` is
3332
- // deliberately excluded: a shell command's argument is not a path we
3333
- // can trust, and scanning arbitrary strings would be a guess.
3334
- const TOUCH_TOOLS = new Set(['rw_read_file', 'rw_write_file', 'rw_edit', 'rw_list_dir'])
3335
- if (!TOUCH_TOOLS.has(name)) return
3336
- if (!agent || !agent.session || !agent.inbox) return
3337
- const args = (hookContext && hookContext.arguments) || (result && result.arguments) || {}
3338
- const rawPath = String(args.path || args.file_path || '')
3339
- if (!rawPath) return
3340
- const cwd = agent.session.header && agent.session.header.cwd
3341
- if (!cwd) return
3342
- const { remotePath, machine, mirrorDir } = resolveMirrorForLocal(String(cwd))
3343
- if (!remotePath || !machine) return // a LOCAL session: the core owns it
3344
- const touched = normalizeRemotePath(rawPath)
3345
- // Reading the workspace root itself adds no chain (the core's baseline
3346
- // already covers `<root>/AGENTS.md`), so this is the "reading a file
3347
- // directly in the root triggers no extra scan" boundary from the issue.
3348
- const sessionId = agent.id || agent.session.id || 'unscoped'
3349
- if (instructionTracker.throttled(sessionId)) return
3350
- instructionTracker.swept(sessionId)
3351
- const pool = poolForMachine(machine)
3352
- // Never let a slow/offline machine hold the tool result: the sweep runs
3353
- // against a short-lived SFTP surface and any failure is swallowed.
3354
- const sftp = await pool.sftp()
3355
- const { items, removed } = await refreshTouched({
3356
- sftp, remoteRoot: remotePath, touched, mirrorDir, tracker: instructionTracker, sessionId,
3357
- })
3358
- if (!items.length && !removed.length) return
3359
- const platform = pool.platform
3360
- const msg = buildInstructionMessage(items, removed, {
3361
- // Items carry an ABSOLUTE `remote` path; removed entries carry a
3362
- // workspace-RELATIVE rel. Prefix only the latter — always joining
3363
- // would double the root prefix (caught by the issue #71 live E2E).
3364
- display: (p) => {
3365
- const s = String(p)
3366
- const abs = s.startsWith('/') || /^[a-zA-Z]:[\\/]/.test(s)
3367
- return toDisplayPath(abs ? s : joinRemotePath(remotePath, s), platform)
3368
- },
3369
- createUserMessage: userMessageFactory(),
3370
- })
3371
- if (!msg) return
3372
- agent.inbox.prepend('next-step', msg)
3373
- } catch { /* best effort — an injection failure must never break the tool */ }
3374
- })
3375
- }
3376
-
3377
- // Remote skill catalogs are cached by cwd/revision. Invalidate after any
3378
- // operation that MAY have changed the remote (a failed/partial write counts
3379
- // too), but never after caller cancellation. rw_push has its own settlement
3380
- // hook above; rw_sync only downloads and need not invalidate.
3381
- if (remoteSkills && typeof ctx.on === 'function') {
3382
- const SKILL_MUTATIONS = new Set([
3383
- 'rw_write_file', 'rw_edit', 'rw_append', 'rw_remove', 'rw_move',
3384
- 'rw_mkdir', 'rw_upload', 'rw_exec',
3385
- // Rebinding a workspace/connection must not resurrect the old catalog.
3386
- 'rw_connect', 'rw_pick_workspace', 'rw_disconnect',
3387
- ])
3388
- ctx.on('tools/result', (result, hookContext) => {
3389
- try {
3390
- const name = String((hookContext && hookContext.name) || (result && result.name) || '')
3391
- if (!SKILL_MUTATIONS.has(name)) return
3392
- const signal = (hookContext && hookContext.signal) || (result && result.signal)
3393
- if (signal && signal.aborted) return
3394
- remoteSkills.invalidate()
3395
- } catch { /* cache invalidation is best-effort and never blocks the tool */ }
3396
- })
3397
- }
3398
-
3399
- // ── slash commands ─────────────────────────────────────────────────────────
3400
- const commands = ctx.get('commands')
3401
- if (commands !== undefined) {
3402
- commands.register({
3403
- name: 'remote',
3404
- description: 'Show the current remote workspace / connection status, active forwards, and how to use remote tools.',
3405
- handler: (invocation) => {
3406
- const s = status()
3407
- const fwd = s.forwards.filter((f) => f.active)
3408
- return {
3409
- kind: 'success',
3410
- text:
3411
- `Remote host: ${s.username}@${s.host || '<none>'} (connected: ${s.connected}, source: ${s.activeSource})\n` +
3412
- `Remote workspace: ${s.workspace || '(none)'}\n` +
3413
- `Host key: ${s.hostKeyKnown ? 'trusted ✓' : 'not yet trusted'} (mode=${s.hostKeyMode})\n` +
3414
- (s.hostKeyKnown ? ` — if the key changed / was mistrusted, run /remote-forget-key\n` : '') +
3415
- (fwd.length ? `Active forwards:\n${fwd.map((f) => ` ${f.direction} 127.0.0.1:${f.listenPort} → ${f.targetHost}:${f.targetPort}`).join('\n')}\n` : '') +
3416
- `\nUse tools: rw_list_dir / rw_read_file / rw_edit / rw_exec / rw_search / rw_forward.` +
3417
- (s.workspace ? `\nCurrently working in ${s.workspace}.` : ''),
3418
- }
3419
- },
3420
- })
3421
- commands.register({
3422
- name: 'remote-forget-key',
3423
- description: 'Drop the trusted host-key record for the current machine so the next connect re-records it.',
3424
- handler: () => {
3425
- createHostKeyGuard(config, knownHostsFile()).forgetHost()
3426
- return { kind: 'success', text: `forgot host key for ${config.host || '<none>'}:${config.port} — the next connect will re-record it.` }
3427
- },
3428
- })
3429
- commands.register({
3430
- name: 'remote-ignore',
3431
- description: 'Show the mirror ignore rules file location and the current default patterns (gitignore syntax).',
3432
- handler: () => {
3433
- return {
3434
- kind: 'success',
3435
- text:
3436
- `Ignore file: ${ignoreFile()}\n(defaults merged with the file; gitignore syntax, '#' comments)\n\nDefault patterns:\n${DEFAULT_IGNORE.map((p) => ' ' + p).join('\n')}`,
3437
- }
3438
- },
3439
- })
3440
- }
3441
-
3442
- // ── JSON endpoints for settings UI ─────────────────────────────────────────
3443
- const sendJson = (res, status, body) => {
3444
- res.statusCode = status
3445
- res.setHeader('Content-Type', 'application/json; charset=utf-8')
3446
- res.end(JSON.stringify(body))
3447
- }
3448
- const MAX_BODY_BYTES = 1024 * 1024
3449
- const readBody = (req) =>
3450
- new Promise((resolve) => {
3451
- const chunks = []
3452
- let total = 0
3453
- req.on('data', (c) => {
3454
- total += c.length
3455
- if (total > MAX_BODY_BYTES) {
3456
- req.removeAllListeners('data')
3457
- resolve('{}')
3458
- return
3459
- }
3460
- chunks.push(c)
3461
- })
3462
- req.on('end', () => resolve(chunks.join('')))
3463
- })
3464
-
3465
- /** Parse a JSON *object* request body.
3466
- *
3467
- * Throws an Error carrying `httpStatus: 400` when the body is not valid JSON
3468
- * or not an object, so a route can answer `400 + {ok:false, error}` instead of
3469
- * rejecting the handler — a rejected handler makes dsh-host-webserver reply
3470
- * with an empty 400 that carries neither Content-Type nor a reason, which is
3471
- * exactly the "everything is just HTTP 400" symptom of issue #30. */
3472
- const parseJsonObject = (raw) => {
3473
- let parsed
3474
- try {
3475
- parsed = JSON.parse(raw || '{}')
3476
- } catch (e) {
3477
- const err = new Error(`请求体不是合法 JSON:${String((e && e.message) || e)}`)
3478
- err.httpStatus = 400
3479
- throw err
3480
- }
3481
- if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
3482
- const err = new Error('请求体必须是一个 JSON 对象')
3483
- err.httpStatus = 400
3484
- throw err
3485
- }
3486
- return parsed
3487
- }
3488
-
3489
- // ── 在本机打开一个文件/目录(审计日志用)───────────────────────────────
3490
- /**
3491
- * Ask the OPERATING SYSTEM to open (or reveal) a path on the machine running this
3492
- * host, and report what happened.
3493
- *
3494
- * Deliberately narrow: the caller may only pass a path the plugin itself computed
3495
- * (the audit log), never an arbitrary one from a request — this is a "show me my
3496
- * log" affordance, not a file launcher for the browser.
3497
- *
3498
- * Resolves `{ok, how}` on success and `{ok:false, error, httpStatus}` on failure, so
3499
- * every route can answer with a reason instead of an empty 500. Headless hosts
3500
- * (servers, CI, no desktop) fail here by design — the audit router turns that into
3501
- * "here is the path, open it yourself" instead of pretending.
3502
- *
3503
- * @param {string} target - absolute path to open.
3504
- * @param {'open'|'reveal'} [action] - open with the default app, or reveal in the
3505
- * file manager.
3506
- */
3507
- const openLocalPath = (target, action = 'open') => new Promise((resolve) => {
3508
- if (String(process.env.DSH_REMOTE_NO_NATIVE_DIALOG || '') && process.env.DSH_REMOTE_NO_NATIVE_DIALOG !== '0') {
3509
- return resolve({ ok: false, error: '本机没有桌面环境(DSH_REMOTE_NO_NATIVE_DIALOG),请直接用编辑器打开下面这个路径', httpStatus: 501 })
3510
- }
3511
- let bin
3512
- let args
3513
- if (process.platform === 'darwin') {
3514
- bin = 'open'; args = action === 'reveal' ? ['-R', target] : [target]
3515
- } else if (process.platform === 'win32') {
3516
- // `explorer.exe <path>` opens; `explorer.exe /select,<path>` highlights.
3517
- bin = 'explorer.exe'
3518
- args = action === 'reveal' ? [`/select,${target}`] : [target]
3519
- } else {
3520
- // No portable "reveal" on Linux; open with the desktop opener either way.
3521
- bin = 'xdg-open'; args = [action === 'reveal' ? path.dirname(target) : target]
3522
- }
3523
- try {
3524
- execFile(bin, args, { timeout: 15000, maxBuffer: 1 << 20 }, (err) => {
3525
- // explorer.exe returns 1 even when it succeeds; the launch itself is the
3526
- // signal we have, so only a SPAWN failure (ENOENT) counts as a real error.
3527
- if (err && err.code === 'ENOENT') {
3528
- return resolve({ ok: false, error: `本机找不到 ${bin},无法自动打开;请直接打开 ${target}`, httpStatus: 501 })
3529
- }
3530
- resolve({ ok: true, how: `${bin} ${args.join(' ')}` })
3531
- })
3532
- } catch (err) {
3533
- resolve({ ok: false, error: String((err && err.message) || err), httpStatus: 500 })
3534
- }
3535
- })
3536
-
3537
- // ── 本机目录选择器:DSH directoryPicker 服务优先,缺位/非原生则自持兜底 ──
3538
- const PICK_TIMEOUT_MS = 120000
3539
- const runPick = (bin, args, opts = {}) =>
3540
- new Promise((resolve, reject) => {
3541
- execFile(bin, args, { timeout: PICK_TIMEOUT_MS, maxBuffer: 1 << 20 }, (err, stdout, stderr) => {
3542
- if (err) {
3543
- const code = err.code
3544
- const msg = String(stderr || '')
3545
- if (code === 1 && /(?:user canceled|-128)/i.test(msg)) return resolve({ cancelled: true })
3546
- if (err.signal || err.killed) return reject(new Error('目录选择已超时,请重试或直接在输入框填本地路径'))
3547
- if (code === 'ENOENT') return reject(Object.assign(new Error('未找到目录选择器程序 ' + bin), { code }))
3548
- return reject(new Error((msg.trim() || (err && err.message) || '无法打开系统文件夹选择器').split('\n')[0]))
3549
- }
3550
- resolve(decodePickStdout(stdout, { base64: !!opts.base64 }))
3551
- })
3552
- })
3553
- const pickLocalNative = async () => {
3554
- const platform = process.platform
3555
- // Escape hatch for non-interactive hosts and for the test suite: opening a
3556
- // real OS folder dialog from a request handler means the REQUEST waits for a
3557
- // human. In a headless host (or CI) that is a hang nobody can see or cancel —
3558
- // the route then falls back to its browse capability / "type the path" hint.
3559
- if (String(process.env.DSH_REMOTE_NO_NATIVE_DIALOG || '') && process.env.DSH_REMOTE_NO_NATIVE_DIALOG !== '0') {
3560
- throw new Error('已禁用本机目录选择器对话框(DSH_REMOTE_NO_NATIVE_DIALOG)—— 请直接在输入框填本地路径')
3561
- }
3562
- if (platform === 'darwin') {
3563
- return runPick('osascript', ['-e', 'set selectedFolder to choose folder with prompt "Select Workspace Directory"', '-e', 'POSIX path of selectedFolder'])
3564
- }
3565
- if (platform === 'linux') {
3566
- try {
3567
- return await runPick('zenity', ['--file-selection', '--directory', '--title=Select Workspace Directory'])
3568
- } catch (err) {
3569
- if (err && err.code === 'ENOENT') return runPick('kdialog', ['--getexistingdirectory', '.', '--title', 'Select Workspace Directory'])
3570
- throw err
3571
- }
3572
- }
3573
- if (platform === 'win32') {
3574
- // The selected path leaves PowerShell base64(UTF-8)-encoded so a Chinese
3575
- // folder name survives the GBK console → UTF-8 Node decode (issue #58).
3576
- return runPick('powershell', ['-NoProfile', '-STA', '-Command', win32FolderPickScript()], { base64: true })
3577
- }
3578
- throw new Error('当前系统不支持自动打开目录选择器,请在输入框直接填本地路径')
3579
- }
3580
-
3581
- /** The ctx.directoryPicker capability object, or null when the service is
3582
- * absent/unusable. Never throws — callers fall through to pickLocalNative. */
3583
- const localPickCapability = async () => {
3584
- const dp = (ctx && typeof ctx.get === 'function') ? (ctx.get('directoryPicker') || null) : null
3585
- if (!dp || typeof dp.capability !== 'function') return null
3586
- try {
3587
- return await Promise.resolve(dp.capability())
3588
- } catch {
3589
- return null
3590
- }
3591
- }
3592
-
3593
- /** Windows has no single filesystem root — enumerate fixed/mapped drive
3594
- * letters so the in-app browser can switch between them (the browse
3595
- * backend's crumbs stop at the current drive's root). Empty on POSIX. */
3596
- const listLocalDrives = () => {
3597
- if (process.platform !== 'win32') return []
3598
- const out = []
3599
- for (let i = 67; i <= 90; i++) { // C..Z (A/B are legacy floppy — skip)
3600
- const root = String.fromCharCode(i) + ':\\'
3601
- try {
3602
- statSync(root)
3603
- out.push({ name: root.slice(0, -1), path: root })
3604
- } catch {}
3605
- }
3606
- return out
3607
- }
3608
-
3609
- /**
3610
- * Give a freshly created mirror a host-qualified Workspace title.
3611
- *
3612
- * DSH's Workspace Create API accepts a path only (`WorkspaceCreateRequest`),
3613
- * and the resulting title is the basename of the registered directory. For a
3614
- * remote workspace that directory is the LOCAL mirror, so a remote
3615
- * `/mnt/xdfs` and a local `/mnt/xdfs` both become "xdfs" — impossible to tell
3616
- * apart in the workspace list. Creating the record HERE first closes that
3617
- * hole: the core's later `workspace.create(<mirror>)` resolves the canonical
3618
- * path to this record and reuses it WITHOUT touching the title.
3619
- *
3620
- * Never renames: a mirror that is already a workspace (possibly renamed by
3621
- * the user) keeps its title. Best-effort by contract — an older host without
3622
- * `ctx.workspaceRegistry`, or a rejected create, must never fail the mirror
3623
- * the picker already committed.
3624
- *
3625
- * @param {string} localDir - local mirror directory (the Workspace path).
3626
- * @param {string} remotePath - remote directory the mirror represents.
3627
- * @param {object|null} machine - machine the mirror belongs to.
3628
- * @returns {Promise<object|undefined>} the created Workspace, when created.
3629
- */
3630
- const registerMirroredWorkspace = async (localDir, remotePath, machine, signal) => {
3631
- try {
3632
- const registry = ctx && typeof ctx.get === 'function' ? ctx.get('workspaceRegistry') : undefined
3633
- if (!registry || typeof registry.create !== 'function') return undefined
3634
- if (typeof registry.resolveByPath === 'function' && await registry.resolveByPath(localDir)) return undefined
3635
- const base = remoteWorkspaceTitle(remotePath, machine)
3636
- const taken = typeof registry.list === 'function'
3637
- ? new Set(registry.list().map((w) => String((w && w.title) || '')))
3638
- : new Set()
3639
- let title = base
3640
- for (let n = 2; taken.has(title); n += 1) title = base + '-' + n
3641
- if (signal && signal.aborted) return undefined
3642
- return await registry.create(localDir, title)
3643
- } catch {
3644
- return undefined
3645
- }
3646
- }
3647
-
3648
- /** Add/update one machine. Shared by POST /dsh-remote/machines and the
3649
- * in-process API (`upsertMachine`). Returns the shape the route sends minus
3650
- * `ok`; throws HOST_REQUIRED (httpStatus 400) for a missing host, which the
3651
- * route maps back to its historical 400 response. */
3652
- const upsertMachineRecord = async (body) => {
3653
- let warning = ''
3654
- let warningDetail = ''
3655
- const host = String(body.host || '').trim()
3656
- if (!host) throw codedError('HOST_REQUIRED', 'host required', { httpStatus: 400 })
3657
- const id = body.id || machineId()
3658
- const i = machineIndex(id)
3659
- const prev = i >= 0 ? machines[i] : null
3660
- const credBackend = body.credentialBackend === 'plain' ? 'plain'
3661
- : (body.encryptPassword ? platformBackend() : (prev && prev.credentialBackend ? prev.credentialBackend : 'plain'))
3662
- const rec = {
3663
- id,
3664
- name: String(body.name || '').trim() || host,
3665
- host,
3666
- // Issue #38: an ALIAS machine stores only the Host line of
3667
- // ~/.ssh/config — HostName/user/port/key are resolved live at
3668
- // every connect instead of being copied into the registry.
3669
- useSshConfig: !!body.useSshConfig,
3670
- port: Number(body.port) || 22,
3671
- username: String(body.username || '').trim() || 'root',
3672
- password: '',
3673
- // An OMITTED `privateKeyPath` keeps the stored one; an explicit
3674
- // empty string clears it (that is what the form sends when the user
3675
- // empties the box). A partial update from an API/agent caller used
3676
- // to silently wipe the key path, leaving a machine that can only
3677
- // fail to authenticate — the same data-loss class as the passphrase.
3678
- privateKeyPath: body.privateKeyPath === undefined
3679
- ? String((prev && prev.privateKeyPath) || '')
3680
- : String(body.privateKeyPath || '').trim(),
3681
- // An EMPTY passphrase from the form means "unchanged", not
3682
- // "delete it": the value is never echoed back to the browser, so
3683
- // an edit that touched any other field used to silently wipe a
3684
- // saved private-key passphrase (and the next connect then failed
3685
- // with "no passphrase given" for a key that had been working).
3686
- passphrase: String(body.passphrase || (prev && prev.passphrase) || ''),
3687
- workspace: String(body.workspace || '').trim(),
3688
- hostKeyMode: body.hostKeyMode || '',
3689
- useAgent: !!body.useAgent,
3690
- keyboardInteractive: !!body.keyboardInteractive,
3691
- // Issue #51: the transport backend is per machine. Native stays when it
3692
- // has a credential to authenticate with; otherwise openssh, so saving a
3693
- // credential-less machine (the normal shape of a ~/.ssh/config alias) can
3694
- // actually connect instead of reporting a missing credential the user
3695
- // never needed. An unknown value is not persisted as-is.
3696
- backend: backendFor({
3697
- backend: body.backend,
3698
- password: body.password || (prev && prev.password),
3699
- privateKeyPath: body.privateKeyPath === undefined ? (prev && prev.privateKeyPath) : body.privateKeyPath,
3700
- useAgent: !!body.useAgent,
3701
- keyboardInteractive: !!body.keyboardInteractive,
3702
- secretStored: prev && prev.secretStored,
3703
- credentialBackend: prev && prev.credentialBackend,
3704
- }, config),
3705
- sshBinary: String(body.sshBinary || '').trim(),
3706
- // Issue #54: the per-machine `dsh web` launch command was only
3707
- // ever writable by the deploy flow or by hand-editing
3708
- // machines.json — the README told users to set it and the
3709
- // settings UI offered nowhere to type it. It is an ordinary
3710
- // machine field now; empty means "fall back to the global
3711
- // webAttachCommand".
3712
- webAttachCommand: body.webAttachCommand === undefined
3713
- ? String((prev && prev.webAttachCommand) || '')
3714
- : String(body.webAttachCommand || '').trim(),
3715
- // Issue #125: the discover command follows the same merge rule — a form
3716
- // that omits it keeps the stored value, an explicit '' clears it.
3717
- webAttachDiscoverCommand: body.webAttachDiscoverCommand === undefined
3718
- ? String((prev && prev.webAttachDiscoverCommand) || '')
3719
- : String(body.webAttachDiscoverCommand || '').trim(),
3720
- // Group labels (host organisation). Merge-only: a request that
3721
- // omits them keeps the stored values instead of wiping them.
3722
- ...normalizeMachineGroup({
3723
- environment: body.environment === undefined ? (prev && prev.environment) : body.environment,
3724
- location: body.location === undefined ? (prev && prev.location) : body.location,
3725
- description: body.description === undefined ? (prev && prev.description) : body.description,
3726
- tags: body.tags === undefined ? (prev && prev.tags) : body.tags,
3727
- }),
3728
- // A jump host the form did not mention is KEPT (omitted ≠
3729
- // removed), and a jump PASSWORD the form did not re-supply is
3730
- // kept too: the settings page never receives it back, so an edit
3731
- // used to strip the bastion credential and the machine could
3732
- // only fail at connect time.
3733
- proxy: body.proxy === undefined
3734
- ? (prev && prev.proxy && prev.proxy.host ? prev.proxy : undefined)
3735
- : (body.proxy && body.proxy.host ? {
3736
- host: String(body.proxy.host),
3737
- port: Number(body.proxy.port) || 22,
3738
- username: String(body.proxy.username || '').trim(),
3739
- password: String(body.proxy.password || (prev && prev.proxy && prev.proxy.password) || ''),
3740
- privateKeyPath: String(body.proxy.privateKeyPath || '').trim(),
3741
- } : undefined),
3742
- credentialBackend: credBackend,
3743
- recentWorkspaces: prev && prev.recentWorkspaces ? prev.recentWorkspaces : [],
3744
- lastConnectedAt: prev && prev.lastConnectedAt ? prev.lastConnectedAt : null,
3745
- latencyMs: prev && prev.latencyMs ? prev.latencyMs : null,
3746
- }
3747
- if (body.password) {
3748
- // Issue #30: `saveSecret()` is best-effort — the old code threw
3749
- // its result away and kept `password: ''`, so on Windows (DPAPI
3750
- // missing the System.Security assembly) the machine was saved
3751
- // WITHOUT any credential and every later connect failed with no
3752
- // visible reason. Now a failed OS-store write falls back to
3753
- // plaintext and is reported to the UI.
3754
- const persisted = await persistPassword({
3755
- backend: credBackend,
3756
- machineId: id,
3757
- password: body.password,
3758
- secretsDir: secretsDir(),
3759
- onStoreFailure: config.credentialFallback === 'plain' ? 'plain' : 'refuse',
3760
- })
3761
- rec.credentialBackend = persisted.credentialBackend
3762
- rec.password = persisted.password
3763
- // Record WHERE the secret ended up, so the settings page can say
3764
- // "已保存" for a keychain machine too (its record carries an
3765
- // empty `password` by design).
3766
- rec.secretStored = persisted.stored === 'secret'
3767
- if (persisted.warning) {
3768
- warning = persisted.warning
3769
- warningDetail = persisted.error
3770
- }
3771
- } else if (prev) {
3772
- // No password typed: keep whatever the machine already had —
3773
- // the plaintext copy AND the keychain flag. Turning the
3774
- // "加密保存密码" checkbox OFF is handled next: it must actually
3775
- // MOVE the secret, or the checkbox is a lie.
3776
- rec.password = prev.password || ''
3777
- rec.secretStored = prev.secretStored
3778
- const prevKeychain = prev.credentialBackend && prev.credentialBackend !== 'plain'
3779
- if (credBackend === 'plain' && prevKeychain) {
3780
- try {
3781
- const existing = await machinePassword(prev)
3782
- if (existing) {
3783
- rec.password = existing
3784
- rec.secretStored = false
3785
- rec.credentialBackend = 'plain'
3786
- await deleteSecret(id, secretsDir()).catch(() => {})
3787
- }
3788
- } catch { /* keep the keychain copy; the next connect still works */ }
3789
- }
3790
- }
3791
- if (i >= 0) machines[i] = rec; else machines.push(rec)
3792
- // Issue #13: saving a machine must NOT make it the active
3793
- // remote context. `currentId` stays untouched on add/update —
3794
- // only an explicit "设为当前" (or rw_connect) activates one.
3795
- // keepCurrentKey:false leaves the stored `currentId` byte-for-byte
3796
- // alone, so a fresh registry stays "no choice yet" (not an
3797
- // explicit none) and a previously-cleared registry stays cleared.
3798
- saveMachines(machines, store.currentId, false)
3799
- // Issue #67: an EDITED connection identity (host/user/port) must
3800
- // carry the machine's existing workspaces over — without this the
3801
- // mirrors stayed bound to the old address and the user had to
3802
- // create (and re-sync) a brand-new workspace for the new IP.
3803
- let reboundMirrors = 0
3804
- if (i >= 0 && prev) {
3805
- try { reboundMirrors = rebindMirrors(prev, rec) } catch { /* best effort */ }
3806
- }
3807
- // Issue #50: host/user/port/key have ONE home — ~/.ssh/config.
3808
- // Saving a literal machine upserts a marker-tagged Host block,
3809
- // so the file and the registry can never drift; the record's
3810
- // copy remains only as a fallback for a missing/renamed block.
3811
- // A Host block the USER wrote for the same name is never
3812
- // touched — the conflict is reported instead. Failures here are
3813
- // best-effort: the registry copy is already saved.
3814
- let sshConfigWarning = ''
3815
- if (!rec.useSshConfig) {
3816
- try {
3817
- const raw = readRawSshConfig(sshConfigPath())
3818
- let next = upsertManagedHostBlock(raw, {
3819
- alias: rec.host,
3820
- hostName: rec.host,
3821
- user: rec.username,
3822
- port: rec.port,
3823
- identityFile: rec.privateKeyPath,
3824
- })
3825
- // A RENAMED machine leaves the old managed block behind, and
3826
- // that block is the plugin's own artifact of the edit —
3827
- // retire it. (Deleting a machine removes nothing: the Host
3828
- // block is the user's ssh access, not plugin state.)
3829
- if (prev && prev.host && prev.host !== rec.host && !prev.useSshConfig) {
3830
- const rm = removeManagedHostBlock(next.text, prev.host)
3831
- next = { status: rm.status === 'removed' && next.status === 'unchanged' ? 'updated' : next.status, text: rm.text }
3832
- }
3833
- if (next.status === 'conflict') {
3834
- sshConfigWarning = `~/.ssh/config already names "${rec.host}" in a Host block that is not managed by dsh-remote — it was left untouched, and it now wins over the saved copy.`
3835
- } else if (next.status === 'appended' || next.status === 'updated') {
3836
- writeSshConfig(next.text, sshConfigPath())
3837
- sshConfigCache = { text: '', at: 0 }
3838
- }
3839
- } catch (sshErr) {
3840
- sshConfigWarning = `could not update ~/.ssh/config (${String((sshErr && sshErr.message) || sshErr)}); the registry copy was saved.`
3841
- }
3842
- }
3843
- return {
3844
- machine: sanitizeMachine(rec),
3845
- machines: machinesForClient(),
3846
- currentId: store.currentId,
3847
- ...(reboundMirrors ? { reboundMirrors } : {}),
3848
- ...(warning ? { warning, warningDetail } : {}),
3849
- ...(sshConfigWarning ? { sshConfigWarning } : {}),
3850
- }
3851
- }
3852
-
3853
- /** Delete one machine (never auto-promotes a sibling). Shared by the
3854
- * delete route and the in-process API; throws MACHINE_NOT_FOUND.
3855
- * @param {string} id - machine id. */
3856
- const removeMachineRecord = async (id) => {
3857
- const i = machineIndex(String(id || ''))
3858
- if (i < 0) throw codedError('MACHINE_NOT_FOUND', 'machine not found', { httpStatus: 404 })
3859
- const m = machines[i]
3860
- if (m.credentialBackend && m.credentialBackend !== 'plain') {
3861
- await deleteSecret(m.id, secretsDir()).catch(() => {})
3862
- }
3863
- machines.splice(i, 1)
3864
- const wasCurrent = store.currentId === m.id
3865
- if (wasCurrent) {
3866
- // Issue #13: deleting the current machine leaves NO active
3867
- // remote context (never auto-promote a sibling — that would
3868
- // make an unrelated machine leak into the session again).
3869
- store.currentId = null
3870
- saveMachines(machines, null)
3871
- await clearActiveMachine()
3872
- } else {
3873
- saveMachines(machines, store.currentId)
3874
- }
3875
- return { machines: machinesForClient(), currentId: store.currentId }
3876
- }
3877
-
3878
- /** Unpersisted connectivity probe: dial once with the credentials a REAL
3879
- * connect would use (form values override, blanks fall back to the stored
3880
- * record), report latency/platform/shell. Shared by POST
3881
- * /dsh-remote/test-connect and the in-process API; throws on failure. */
3882
- const probeMachineRecord = async (body) => {
3883
- // ── The probe must dial with the credentials a REAL connect would use.
3884
- //
3885
- // Stored secrets never travel back to the browser (see
3886
- // sanitizeMachine), so "编辑一台已经连接成功的机器 → 点测试连接" posted an
3887
- // EMPTY password while the machine itself connected fine through the
3888
- // pool's keychain/plaintext resolver. Every such probe died with
3889
- // `no credentials: set a password, a privateKeyPath, or enable
3890
- // useAgent to connect` — the error said "you configured nothing" about
3891
- // a machine that was visibly working.
3892
- //
3893
- // So: resolve the saved record (by id when the form is editing one,
3894
- // else by identity) and merge — form values override, blanks fall back
3895
- // to the stored record. The resolved password is then ALSO exposed as a
3896
- // lazy resolver so an OS-keychain machine behaves exactly like a real
3897
- // connect (read on demand, never logged).
3898
- const savedRec = (() => {
3899
- const byId = body.id ? machines[machineIndex(String(body.id))] : null
3900
- if (byId) return byId
3901
- // No id (a fresh form that happens to match a saved machine): match on
3902
- // the identity the form is about to dial.
3903
- const hit = machineRecordFor({
3904
- host: String(body.host || ''),
3905
- port: Number(body.port) || 22,
3906
- username: String(body.username || ''),
3907
- })
3908
- return hit || null
3909
- })()
3910
- const savedPassword = savedRec ? await machinePassword(savedRec) : ''
3911
- const cred = resolveProbeCredentials(body, savedRec, savedPassword)
3912
- // Issue #38: "test" on an ssh-config ALIAS resolves the alias first —
3913
- // the form holds the alias name, not the host it points at.
3914
- const probeBackend = backendFor({
3915
- backend: cred.backend,
3916
- password: cred.password,
3917
- privateKeyPath: cred.privateKeyPath,
3918
- useAgent: cred.useAgent,
3919
- keyboardInteractive: cred.keyboardInteractive,
3920
- secretStored: savedRec && savedRec.secretStored,
3921
- credentialBackend: savedRec && savedRec.credentialBackend,
3922
- }, config)
3923
- const probeIsOpenssh = isSystemOpenSshBackend({ backend: probeBackend })
3924
- const aliasTarget = body.useSshConfig
3925
- ? resolveMachineSshConfig({
3926
- host: String(body.host || ''),
3927
- port: Number(body.port) || 22,
3928
- username: String(body.username || ''),
3929
- privateKeyPath: String(cred.privateKeyPath || ''),
3930
- proxy: cred.proxy,
3931
- useSshConfig: true,
3932
- }, { text: sshConfigText() })
3933
- : null
3934
- // Issue #50: a LITERAL host named by a Host block resolves through
3935
- // the file as well — the probe must dial what a real connect would.
3936
- const literalTarget = !body.useSshConfig
3937
- ? resolveLiteralSshConfig({ host: String(body.host || '') }, { text: sshConfigText() })
3938
- : null
3939
- const probeTarget = aliasTarget || literalTarget
3940
- // Issue #51: on the system-OpenSSH backend an alias is handed to `ssh`
3941
- // VERBATIM (see connectTargetFor) — resolving it here would stop the
3942
- // `Host` block from matching, so the ~/.ssh/config settings the probe
3943
- // is supposed to validate would be silently skipped.
3944
- const probe = createPool({
3945
- ...config,
3946
- backend: probeBackend,
3947
- host: probeTarget && !probeIsOpenssh ? probeTarget.host : String(body.host || config.host),
3948
- port: (probeTarget && !probeIsOpenssh && probeTarget.port) ? probeTarget.port : (Number(body.port) || config.port),
3949
- username: (probeTarget && !probeIsOpenssh && probeTarget.username) ? probeTarget.username : String(body.username || config.username),
3950
- password: cred.password,
3951
- privateKeyPath: (probeTarget && !probeIsOpenssh && probeTarget.privateKeyPath) ? probeTarget.privateKeyPath : String(cred.privateKeyPath || config.privateKeyPath),
3952
- passphrase: cred.passphrase,
3953
- // Auth METHOD flags come from the merge too: a machine that
3954
- // authenticates through an agent or keyboard-interactive used to be
3955
- // probed with `useAgent: false`, i.e. with no auth method at all.
3956
- useAgent: cred.useAgent,
3957
- agentSocket: (probeTarget && !probeIsOpenssh && probeTarget.agentSocket) || '',
3958
- identitiesOnly: !!(probeTarget && !probeIsOpenssh && probeTarget.identitiesOnly),
3959
- keyboardInteractive: cred.keyboardInteractive,
3960
- ...(cred.hostKeyMode ? { hostKeyMode: cred.hostKeyMode } : {}),
3961
- ...(cred.sshBinary ? { sshBinary: cred.sshBinary } : {}),
3962
- proxy: (probeTarget && !probeIsOpenssh && probeTarget.proxy) ? probeTarget.proxy : cred.proxy,
3963
- connectTimeoutMs: Math.min(Math.max(Number(body.connectTimeoutMs) || config.connectTimeoutMs, 2000), 30000),
3964
- commandTimeoutMs: 10000,
3965
- }, { knownHostsFile, opensshKnownHostsFile })
3966
- // Same lazy resolution the active pool uses: if the merged password was
3967
- // empty because the secret lives in the OS keychain, the pool asks again
3968
- // at dial time instead of failing with "no credentials".
3969
- probe.passwordResolver = async () => machinePassword(savedRec || {})
3970
- const started = Date.now()
3971
- try {
3972
- await probe.connect()
3973
- await probe.exec('true', { timeoutMs: 10000 })
3974
- } finally {
3975
- probe.close()
3976
- }
3977
- const latencyMs = Date.now() - started
3978
- // Alias-aware: the probe connects to the RESOLVED host, while the
3979
- // registry stores the alias, so matching must go through the identity.
3980
- const mi = machines.findIndex((m) => identityMatches(m, { host: probe.config.host, port: probe.config.port, username: probe.config.username }))
3981
- if (mi >= 0) {
3982
- machines[mi].lastConnectedAt = new Date().toISOString()
3983
- machines[mi].latencyMs = latencyMs
3984
- saveMachines(machines, store.currentId)
3985
- }
3986
- return {
3987
- ok: true,
3988
- host: probe.config.host,
3989
- user: probe.config.username,
3990
- latencyMs,
3991
- lastConnectedAt: new Date().toISOString(),
3992
- platform: probe.platform,
3993
- shell: probe.shellMode,
3994
- gitBash: probe.gitBashPath || '',
3995
- // Tell the UI whether the probe leaned on the SAVED credential: with
3996
- // an empty password box, "测试成功" otherwise looks impossible.
3997
- usedSavedCredential: cred.usedSavedCredential,
3998
- // Issue #38: tell the settings page where an alias resolved to (and
3999
- // anything the plugin could not honour, e.g. a multi-hop ProxyJump).
4000
- alias: aliasTarget ? { name: aliasTarget.alias, host: aliasTarget.host, port: aliasTarget.port, user: aliasTarget.username, warnings: aliasTarget.warnings } : null,
4001
- }
4002
- }
4003
- // ── in-process host API (ctx.dshRemote) building blocks ───────────────────
4004
- // lib/host-api.js owns the contract shaping (pure data, error codes,
4005
- // subscribe); the functions below are the only bridge to this closure's
4006
- // state. ONE implementation is the point: a second reader of machines.json
4007
- // would see a stale snapshot, a second SSH pool would double every
4008
- // connection, and two writers of saveMachines() race its whole-file rewrite.
4009
- /** Log through the optional harness logger; never lets logging fail a call. */
4010
- const hostLog = (level, message) => {
4011
- try {
4012
- const logger = ctx && typeof ctx.get === 'function' ? ctx.get('logger') : undefined
4013
- if (logger && typeof logger[level] === 'function') logger[level](message)
4014
- } catch { /* logging is best-effort */ }
4015
- }
4016
-
4017
- /** One coded error for the in-process API. Host-side callers get a stable
4018
- * `.code` (contract vocabulary) plus `httpStatus` where the HTTP route has
4019
- * a historical status to preserve. */
4020
- const codedError = (code, message, extra = {}) => {
4021
- const e = new Error(message)
4022
- e.code = code
4023
- if (extra && typeof extra === 'object') Object.assign(e, extra)
4024
- return e
4025
- }
4026
-
4027
- /** Resolve a machine for the API: by id when given, else the ACTIVE machine
4028
- * (explicit current > ephemeral > config default, exactly like status()).
4029
- * Returns the RESOLVED connect identity — ssh-config aliases expanded, and
4030
- * folded back to the alias for the system-OpenSSH backend (which dials the
4031
- * alias itself), i.e. what applyActiveMachine writes into the shared config. */
4032
- const resolveMachineForApi = (machineId) => {
4033
- const id = String(machineId || '').trim()
4034
- if (id) {
4035
- const i = machineIndex(id)
4036
- if (i < 0) throw codedError('MACHINE_NOT_FOUND', `machine not found: ${id}`)
4037
- const rec = machines[i]
4038
- const eff = withSshConfig(rec)
4039
- const t = connectTargetFor(eff)
4040
- return {
4041
- record: rec,
4042
- machineId: rec.id,
4043
- name: String(rec.name || rec.host || ''),
4044
- host: String(t.aliasNative ? t.host : (eff.host || '')),
4045
- port: t.aliasNative ? 22 : (Number(eff.port) || 22),
4046
- username: t.aliasNative ? '' : String(eff.username || ''),
4047
- alias: aliasOf(eff),
4048
- }
4049
- }
4050
- const rec = store.currentId && machineIndex(store.currentId) >= 0 ? machines[machineIndex(store.currentId)] : null
4051
- const m = activeMachine()
4052
- if (!m || !m.host) {
4053
- throw codedError('NO_ACTIVE_MACHINE', '当前没有活动远程机:请先在「远程工作区」设置里选择或连接一台机器。(保存的机器只是备用连接,不会自动成为当前机器。)')
4054
- }
4055
- const t = connectTargetFor(m)
4056
- return {
4057
- record: rec,
4058
- machineId: rec ? rec.id : '',
4059
- name: String((rec && rec.name) || m.name || m.host || ''),
4060
- host: String(t.aliasNative ? t.host : (m.host || '')),
4061
- port: t.aliasNative ? 22 : (Number(m.port) || 22),
4062
- username: t.aliasNative ? '' : String(m.username || ''),
4063
- alias: aliasOf(m),
4064
- }
4065
- }
4066
-
4067
- /** Binding for the API's listDir. Addressing priority (contract):
4068
- * machineId (that machine's own pool, no side effects) > the active machine
4069
- * (the same fallback the /ls route gets from resolveRequestBinding). */
4070
- const listDirBindingForApi = async (opts = {}) => {
4071
- const id = String((opts && opts.machineId) || '').trim()
4072
- if (id) {
4073
- const m = resolveMachineForApi(id)
4074
- // The per-machine pool keeps browsing off the shared active pool: a
4075
- // directory listing must never switch the user's current machine.
4076
- const targetPool = poolForMachine({ host: m.host, port: m.port, username: m.username, alias: m.alias })
4077
- const tgt = (targetPool && targetPool.config) || {}
4078
- return {
4079
- pool: targetPool,
4080
- ws: '',
4081
- bound: false,
4082
- machine: {
4083
- id: m.machineId,
4084
- name: m.name,
4085
- host: String(tgt.host || m.host),
4086
- port: Number(tgt.port) || m.port,
4087
- username: String(tgt.username != null ? tgt.username : m.username),
4088
- },
4089
- }
4090
- }
4091
- // No hint: the /ls route's fallback. resolveRequestBinding throws a 409 with
4092
- // the actionable Chinese message when no machine is active; host-api maps
4093
- // that to NO_ACTIVE_MACHINE.
4094
- const b = await resolveRequestBinding({ url: '/' }, {})
4095
- let name = ''
4096
- try {
4097
- const am = activeMachine()
4098
- name = String((am && (am.name || am.host)) || b.host || '')
4099
- } catch { /* display only */ }
4100
- const tgt = (b.pool && b.pool.config) || {}
4101
- return {
4102
- pool: b.pool,
4103
- ws: b.ws,
4104
- bound: !!b.bound,
4105
- machine: {
4106
- id: store.currentId || '',
4107
- name,
4108
- host: String(tgt.host || b.host || ''),
4109
- port: Number(tgt.port) || Number(b.port) || 22,
4110
- username: String(tgt.username != null ? tgt.username : (b.username || '')),
4111
- },
4112
- }
4113
- }
4114
-
4115
- /** Every local mirror + the registry machine its meta resolves to. Pure
4116
- * filesystem read (mirrorRegistry), so it never dials. */
4117
- const listRemoteProjectsForApi = () => mirrorRegistry().map((p) => {
4118
- const rec = machineRecordFor({ host: p.host, port: p.port, username: p.username, alias: p.alias })
4119
- return { ...p, machineId: rec && rec.id ? String(rec.id) : null }
4120
- })
4121
-
4122
- /** 在系统文件管理器里打开本机 dsh-remote 的镜像根目录
4123
- * (`$DSH_HOME/remote-workspaces`,里面按机器分目录存放所有工作区镜像)。
4124
- * 只打开已存在的目录,不创建任何东西。 */
4125
- const revealMirrorFolderForApi = async () => {
4126
- const dir = remoteWorkspacesRoot()
4127
- if (!existsSync(dir)) {
4128
- throw codedError('VALIDATION', '还没有任何远程工作区镜像目录:先浏览远程目录并按 w 建一个工作区')
4129
- }
4130
- // spawn 失败(例如 Linux 没有 xdg-open)必须让调用方看到错误,不能先报成功。
4131
- await openLocalFolder(dir)
4132
- return { path: dir }
4133
- }
4134
-
4135
- /** SSH `stat` validation used by pickRemoteWorkspace. With a machineId it
4136
- * runs on that machine's OWN pool (validation must not switch the active
4137
- * machine); without one it behaves like the /mirror route (active pool). */
4138
- const checkRemoteDirForApi = async (remotePath, machineId) => {
4139
- const id = String(machineId || '').trim()
4140
- if (id) {
4141
- const m = resolveMachineForApi(id)
4142
- return isRemoteDir(remotePath, poolForMachine({ host: m.host, port: m.port, username: m.username, alias: m.alias }))
4143
- }
4144
- if (!String(config.host || '').trim()) {
4145
- const m = activeMachine()
4146
- if (m && m.host) {
4147
- try { await applyActiveMachine() } catch { /* reported by the probe below */ }
4148
- }
4149
- }
4150
- if (!String(config.host || '').trim()) {
4151
- throw codedError('NO_ACTIVE_MACHINE', '当前没有活动远程机:请先在「远程工作区」设置里选择或连接一台机器。(保存的机器只是备用连接,不会自动成为当前机器。)')
4152
- }
4153
- return isRemoteDir(remotePath)
4154
- }
4155
-
4156
- /** Persist "this machine is current" for the API (null = explicit none). */
4157
- const setCurrentForApi = async (id) => {
4158
- const clean = id == null ? '' : String(id).trim()
4159
- if (!clean) {
4160
- await setCurrent('')
4161
- return
4162
- }
4163
- if (machineIndex(clean) < 0) throw codedError('MACHINE_NOT_FOUND', `machine not found: ${clean}`)
4164
- if (!(await setCurrent(clean))) throw codedError('MACHINE_NOT_FOUND', `machine not found: ${clean}`)
4165
- }
4166
-
4167
- /** Connect (activate) a machine and probe a real SSH connection.
4168
- * `persist:false` keeps the registry's currentId untouched (rw_connect
4169
- * save:false semantics): the target is applied as an EPHEMERAL machine. */
4170
- const connectMachineForApi = async (opts = {}) => {
4171
- const id = String((opts && opts.machineId) || '').trim()
4172
- const persist = !(opts && opts.persist === false)
4173
- let rec = null
4174
- if (id) {
4175
- const i = machineIndex(id)
4176
- if (i < 0) throw codedError('MACHINE_NOT_FOUND', `machine not found: ${id}`)
4177
- rec = machines[i]
4178
- } else if (store.currentId && machineIndex(store.currentId) >= 0) {
4179
- rec = machines[machineIndex(store.currentId)]
4180
- }
4181
- if (!rec) {
4182
- const m = activeMachine()
4183
- if (!m || !m.host) {
4184
- throw codedError('NO_ACTIVE_MACHINE', '当前没有活动远程机:请先在「远程工作区」设置里选择或连接一台机器。(保存的机器只是备用连接,不会自动成为当前机器。)')
4185
- }
4186
- }
4187
- if (persist) {
4188
- ephemeral = null
4189
- if (rec) await setCurrent(rec.id)
4190
- else await applyActiveMachine()
4191
- } else {
4192
- ephemeral = rec ? { ...rec } : { ...activeMachine() }
4193
- await applyActiveMachine()
4194
- }
4195
- // "Connect" means dial NOW: drop a cached (possibly half-open) client so the
4196
- // probe below really reconnects — the same reasoning as the /connect route.
4197
- pool.invalidate()
4198
- const connectHost = config.host
4199
- const connectPort = Number(config.port) || 22
4200
- try {
4201
- await pool.exec('echo ok', { timeoutMs: Math.min(config.commandTimeoutMs || 20000, 8000) })
4202
- } catch (err) {
4203
- if (err && typeof err === 'object') {
4204
- err.host = connectHost
4205
- err.port = connectPort
4206
- }
4207
- audit('connect', `connect ${config.username}@${connectHost}:${connectPort}`, (err && typeof err.code === 'number') ? err.code : -1)
4208
- throw err
4209
- }
4210
- audit('connect', `connect ${config.username}@${connectHost}:${connectPort}`, 0)
4211
- return status()
4212
- }
4213
-
4214
-
4215
- // ── route helpers ─────────────────────────────────────────────────────────
4216
- const routes = [
4217
- {
4218
- kind: 'exact',
4219
- path: '/dsh-remote/status',
4220
- handler: async (req, res) => {
4221
- if (req.method === 'GET') {
4222
- const q = new URL(req.url, 'http://localhost').searchParams
4223
- const sessionId = q.get('sessionId') ? decodeURIComponent(q.get('sessionId')) : ''
4224
- // Per-session remote context (issue #13): when a sessionId is given,
4225
- // sessionMode reflects THAT session's cwd, not the machine default.
4226
- if (!sessionId) return sendJson(res, 200, status())
4227
- const cwd = sessionCwd(sessionId)
4228
- const resolved = cwd ? resolveMirrorForLocal(cwd) : { remotePath: '', machine: null }
4229
- const extra = {
4230
- sessionMode: resolved.remotePath ? 'remote' : 'local',
4231
- sessionRemotePath: resolved.remotePath || '',
4232
- sessionBound: !!(resolved.machine && resolved.remotePath),
4233
- sync: syncStatusFor(resolved.mirrorDir || ''),
4234
- }
4235
- if (resolved.machine && resolved.remotePath) {
4236
- const p = poolForMachine(resolved.machine)
4237
- extra.host = resolved.machine.host
4238
- extra.username = resolved.machine.username
4239
- extra.port = resolved.machine.port
4240
- extra.workspace = toDisplayPath(resolved.remotePath, p.platform)
4241
- // Bound sessions are allowed to list/read even if this process has
4242
- // not yet opened a socket — /ls connects on demand.
4243
- extra.connected = true
4244
- }
4245
- return sendJson(res, 200, { ...status(), ...extra })
4246
- }
4247
- sendJson(res, 405, { error: 'method not allowed' })
4248
- },
4249
- },
4250
- {
4251
- // Map a LOCAL path (typically a session cwd that sits inside a remote
4252
- // mirror dir) to the remote path it mirrors, by reading each mirror
4253
- // dir's .dsh-remote-meta.json. NO machine-workspace fallback (issue #13):
4254
- // a session whose cwd is not inside any mirror is a pure LOCAL session —
4255
- // the sidebar must show "no remote workspace", never another machine's
4256
- // remembered default.
4257
- // Accepts either ?local=<abs path> or ?sessionId=<id> (resolved via
4258
- // the host sessions service header.cwd).
4259
- kind: 'exact',
4260
- path: '/dsh-remote/resolve-mirror',
4261
- handler: async (req, res) => {
4262
- if (req.method !== 'GET') return sendJson(res, 405, { error: 'method not allowed' })
4263
- try {
4264
- const q = new URL(req.url, 'http://localhost').searchParams
4265
- let local = q.get('local') ? decodeURIComponent(q.get('local')) : ''
4266
- const sessionId = q.get('sessionId') ? decodeURIComponent(q.get('sessionId')) : ''
4267
- let resolvedVia = 'query'
4268
- if (!local && sessionId) {
4269
- // 1) Live in-memory session header (active sessions only).
4270
- try {
4271
- const sessions = ctx && typeof ctx.get === 'function' ? ctx.get('sessions') : null
4272
- const session = sessions && typeof sessions.get === 'function' ? sessions.get(sessionId) : null
4273
- const header = session && session.header ? session.header : null
4274
- if (header && header.cwd) {
4275
- local = String(header.cwd)
4276
- resolvedVia = 'session'
4277
- }
4278
- } catch { /* sessions service unavailable */ }
4279
- // 2) Durable session log header (works for historical sessions too):
4280
- // walk $DSH_HOME/sessions/<projectKey>/<sessionId>/session.jsonl.zstd
4281
- // and read the header line (first zstd frame) for cwd.
4282
- if (!local) {
4283
- try {
4284
- const sessionsRoot = path.join(dshBase(), 'sessions')
4285
- if (existsSync(sessionsRoot)) {
4286
- const targetDir = encodeSegmentSafe(sessionId)
4287
- for (const projDir of readdirSync(sessionsRoot)) {
4288
- const projPath = path.join(sessionsRoot, projDir)
4289
- if (!statSync(projPath, { throwIfNoEntry: false })?.isDirectory?.()) continue
4290
- const sessDir = path.join(projPath, targetDir)
4291
- if (!statSync(sessDir, { throwIfNoEntry: false })?.isDirectory?.()) continue
4292
- const logFile = ['session.jsonl.zstd', 'session.jsonl', 'session.jsonl.gz'].map((n) => path.join(sessDir, n)).find((p) => existsSync(p))
4293
- if (!logFile) continue
4294
- const cwd = readSessionHeaderCwd(logFile)
4295
- if (cwd) {
4296
- local = cwd
4297
- resolvedVia = 'session-log'
4298
- break
4299
- }
4300
- }
4301
- }
4302
- } catch { /* session log scan failed */ }
4303
- }
4304
- }
4305
- const root = remoteWorkspacesRoot()
4306
- const norm = (p) => path.resolve(String(p || '')).replace(/[\\/]+$/, '') || ''
4307
- let matched = ''
4308
- let matchedRemote = ''
4309
- if (local && existsSync(root)) {
4310
- const base = norm(local)
4311
- for (const hostDir of readdirSync(root)) {
4312
- const hostPath = path.join(root, hostDir)
4313
- if (!statSync(hostPath, { throwIfNoEntry: false })?.isDirectory?.()) continue
4314
- for (const mirrorDir of readdirSync(hostPath)) {
4315
- const metaPath = path.join(hostPath, mirrorDir, '.dsh-remote-meta.json')
4316
- if (!existsSync(metaPath)) continue
4317
- try {
4318
- const meta = JSON.parse(readFileSync(metaPath, 'utf8'))
4319
- const mirrorAbs = norm(path.join(hostPath, mirrorDir))
4320
- // Exact mirror dir match, or the local path is inside the mirror dir.
4321
- if (mirrorAbs === base || base.startsWith(mirrorAbs + path.sep) || base.startsWith(mirrorAbs + '/')) {
4322
- if (mirrorAbs.length > matched.length) {
4323
- matched = mirrorAbs
4324
- matchedRemote = String(meta.remotePath || '')
4325
- }
4326
- }
4327
- } catch { /* skip unparsable meta */ }
4328
- }
4329
- }
4330
- }
4331
- // Issue #13: a non-mirror session is LOCAL — remotePath stays empty.
4332
- const remotePath = matchedRemote || ''
4333
- return sendJson(res, 200, {
4334
- local, remotePath, mirrorDir: matched || null,
4335
- // `fallback:true` now means "this session is NOT a remote session"
4336
- // (used to mean "fell back to machine workspace").
4337
- fallback: !matchedRemote,
4338
- mode: matchedRemote ? 'remote' : 'local',
4339
- resolvedVia,
4340
- })
4341
- } catch (err) {
4342
- return sendJson(res, 500, { error: String((err && err.message) || err) })
4343
- }
4344
- },
4345
- },
4346
- {
4347
- // Every local mirror with its recorded remote origin (issue #49).
4348
- //
4349
- // The sidebar paints a "this session is remote" mark on a Session row, so
4350
- // it needs the same mapping for every visible row. One directory listing
4351
- // answers all of them: the client matches each row's own cwd (which it
4352
- // already has in the sessions snapshot) against these mirror dirs, and a
4353
- // row whose cwd is inside a mirror is a remote session bound to that
4354
- // mirror's host. Never consults the mutable active machine — a saved
4355
- // machine that happens to be "current" must not label a local session.
4356
- kind: 'exact',
4357
- path: '/dsh-remote/bindings',
4358
- handler: async (req, res) => {
4359
- if (req.method !== 'GET') return sendJson(res, 405, { error: 'method not allowed' })
4360
- try {
4361
- return sendJson(res, 200, { mirrors: mirrorRegistry() })
4362
- } catch (err) {
4363
- return sendJson(res, 500, { error: String((err && err.message) || err) })
4364
- }
4365
- },
4366
- },
4367
- // Mirror/connection surface (extracted for issue #82).
4368
- ...createWorkspaceRoutes({
4369
- sendJson, readBody, parseJsonObject, config, pool, backendFor, status, isRemoteDir, persistWorkspace, ensureMirror,
4370
- aliasOf, activeMachine, startAutoPush, applyRequestedMachine, registerMirroredWorkspace, localPickCapability,
4371
- pickLocalNative, listLocalDrives, probeMachineRecord, setCurrent, knownHostsFile, prepareMirrorTarget, machineForId: (id) => machines.find((m) => m.id === id),
4372
- }),
4373
- ...createSearchRoutes({ searches: workspaceSearches, sendJson, readBody, resolveRequestBinding, isIgnoredFor: searchIgnoreMatcher }),
4374
- ...createGitRoutes({ sendJson, resolveRequestBinding, decodeBuf, config }),
4375
- ...createFsRoutes({
4376
- sendJson, readBody, resolveRequestBinding, decodeBuf, encodeText, audit, config, mirrorDirFor,
4377
- onRemoteMutation: () => { if (remoteSkills) remoteSkills.invalidate() },
4378
- }),
4379
-
4380
- // Embedded terminal (P1): one host-owned PTY session per machine, polled.
4381
- ...createTerminalRoutes({
4382
- sendJson, readBody, resolveRequestBinding, terminals,
4383
- // The machine fence: a session is identified by the mirror-recorded
4384
- // origin, so a terminal opened on host A can never be driven from a
4385
- // request bound to host B.
4386
- machineKey: (b) => poolKey({ host: b.host, port: b.port, username: b.username }),
4387
- }),
4388
-
4389
- // Machine registry + ssh-config surfaces (extracted for issue #82).
4390
- ...createMachineRoutes({
4391
- sendJson, readBody, parseJsonObject, store, machines, machinesForClient, upsertMachineRecord, removeMachineRecord,
4392
- setCurrent, saveMachines, sanitizeMachine, machineId, sshConfigText, nativeUsableCredential, status, openLocalPath,
4393
- onSshConfigWritten: () => { sshConfigCache = { text: '', at: 0 } },
4394
- }),
4395
- // Port-forward surface (extracted for issue #82).
4396
- ...createForwardRoutes({ sendJson, readBody, forwards, store }),
4397
- {
4398
- kind: 'exact',
4399
- path: '/dsh-remote/task',
4400
- handler: async (req, res) => {
4401
- if (req.method === 'GET') {
4402
- const q = new URL(req.url, 'http://localhost').searchParams
4403
- const id = q.get('id') || ''
4404
- const t = tasks.get(id)
4405
- if (!t) return sendJson(res, 404, { ok: false, error: 'task not found' })
4406
- return sendJson(res, 200, { ok: true, task: t })
4407
- }
4408
- if (req.method === 'POST') {
4409
- try {
4410
- const body = JSON.parse((await readBody(req)) || '{}')
4411
- const id = String(body.id || '')
4412
- if (body.action === 'cancel') {
4413
- const ok = tasks.cancel(id)
4414
- return sendJson(res, 200, { ok, task: tasks.get(id) })
4415
- }
4416
- return sendJson(res, 400, { ok: false, error: 'unknown action' })
4417
- } catch (err) {
4418
- return sendJson(res, 500, { ok: false, error: String((err && err.message) || err) })
4419
- }
4420
- }
4421
- return sendJson(res, 405, { ok: false, error: 'method not allowed' })
4422
- },
4423
- },
4424
- {
4425
- kind: 'exact',
4426
- path: '/dsh-remote/tasks',
4427
- handler: async (req, res) => {
4428
- if (req.method !== 'GET') return sendJson(res, 405, { ok: false, error: 'method not allowed' })
4429
- return sendJson(res, 200, { ok: true, tasks: tasks.list() })
4430
- },
4431
- },
4432
- // Audit surface (extracted for issue #82).
4433
- ...createAuditRoutes({ sendJson, readBody, config, auditFile, readAudit, parseJsonObject, openLocalPath }),
4434
- // Remote-Web-UI attach surface (extracted for issue #82).
4435
- ...createWebAttachRoutes({
4436
- sendJson, readBody, parseJsonObject, config, webAttaches, store, machines, poolForMachine, identityOf, webAttachCommandFor, webAttachDiscoverCommandFor, audit,
4437
- }),
4438
- // Self-update surface (extracted for issue #82).
4439
- ...createUpdateRoutes({
4440
- sendJson, readBody, config, loader: ctx.loader, defaultUpdateMode: DEFAULT_UPDATE_MODE,
4441
- autoUpdateState: () => autoUpdater?.snapshot() || null,
4442
- onUpdateModeChange: () => autoUpdater?.modeChanged(),
4443
- }),
4444
-
4445
- // Telemetry / term-secret / workspace-cleanup surfaces (extracted for issue #82).
4446
- // hostApi is late-bound: it is assembled AFTER route registration below.
4447
- ...createMiscRoutes({
4448
- sendJson, readBody, config, dshBase, ctx, termSecretFile, writeTermSecretPayload, termSecretOk, machines, machinePassword,
4449
- getHostApi: () => hostApi,
4450
- }),
4451
- ]
4452
-
4453
- registerHttpTransports(ctx, routes)
4454
-
4455
- // Publish the credential-bridge payload as soon as the loopback origin is
4456
- // known (the listener may still be binding at apply time — retry once).
4457
- ctx.inject(['webServer'], (inner) => {
4458
- const ws = inner.get('webServer')
4459
- const publish = () => {
4460
- try {
4461
- return writeTermSecretPayload(typeof ws.getOrigin === 'function' ? ws.getOrigin() : '')
4462
- } catch { return false } // listener not bound yet
4463
- }
4464
- if (!publish()) {
4465
- const timer = setTimeout(publish, 2000)
4466
- if (typeof timer.unref === 'function') timer.unref()
4467
- }
4468
- })
4469
-
4470
- // ── remote terminal: one extra shell in the host terminal's own list ──────
4471
- // Additive and optional: a composition without `terminalController` simply
4472
- // keeps the terminal it already had.
4473
- //
4474
- // The callback argument is a *new context*, not the service — reading the
4475
- // service off it (as if it were the controller) is a silent no-op, because a
4476
- // context has no `config.shellCandidates`.
4477
- ctx.inject(['terminalController'], (inner) => {
4478
- installTerminalShell(ctx, inner.get('terminalController'), {
4479
- ...remoteShellSpec(),
4480
- claimDefault: config.remoteTerminalDefault !== false,
4481
- })
4482
- })
4483
-
4484
- // Automatic mode is read on every operation; a live settings change can
4485
- // start or stop checking without requiring a plugin restart.
4486
- autoUpdater = createAutoUpdater({
4487
- mode: () => {
4488
- const rawMode = readUpdateMode() || config.updateMode || DEFAULT_UPDATE_MODE
4489
- return ['manual', 'auto', 'off'].includes(rawMode) ? rawMode : DEFAULT_UPDATE_MODE
4490
- },
4491
- isInstalled: isInstalledCopy,
4492
- probe: fetchLatestVersion,
4493
- apply: applyUpdate,
4494
- diskVersion,
4495
- loadedVersion: LOADED_VERSION,
4496
- gtVersion,
4497
- reload: () => scheduleSelfReload(ctx.loader, 500),
4498
- autoReload: () => config.updateAutoReload !== false,
4499
- intervalMs: config.updateCheckIntervalMs,
4500
- })
4501
- ctx.effect(() => { void autoUpdater.start(); return () => autoUpdater.stop() }, 'dsh-remote.update-timer')
4502
-
4503
- // ── in-process API for other plugins (TUI) ────────────────────────────────
4504
- // Same closure state the HTTP routes use. A second implementation would hold
4505
- // a stale `machines` snapshot, open a second SSH connection per host, and
4506
- // race saveMachines()'s whole-file rewrite against this one. `lib/host-api.js`
4507
- // only shapes these functions into pure data + coded errors.
4508
- let hostApi
4509
- try {
4510
- hostApi = createHostApi({
4511
- listMachinesView: () => ({ machines: machinesForClient(), currentId: store.currentId || null }),
4512
- upsertMachineRecord,
4513
- removeMachineRecord,
4514
- setCurrentForApi,
4515
- connectMachine: connectMachineForApi,
4516
- probeMachineRecord,
4517
- statusSnapshot: () => status(),
4518
- resolveDirBinding: listDirBindingForApi,
4519
- listRemoteProjects: listRemoteProjectsForApi,
4520
- revealMirrorFolderRecord: revealMirrorFolderForApi,
4521
- resolveMachine: resolveMachineForApi,
4522
- ensureMirror,
4523
- registerMirroredWorkspace,
4524
- checkRemoteDir: checkRemoteDirForApi,
4525
- workspaceRoot: remoteWorkspacesRoot,
4526
- sessionsRoot: () => path.join(dshBase(), 'sessions'),
4527
- workspaceRegistry: () => (ctx && typeof ctx.get === 'function' ? ctx.get('workspaceRegistry') : undefined),
4528
- forgetRemotePath,
4529
- isSessionLive,
4530
- })
4531
- // cordis 4: `ctx.provide(name, value)` is the raw service registry (the
4532
- // `Service` base class is only sugar around it). Guarded because a minimal
4533
- // embedding — and the test harness before it grew `provide` — has no
4534
- // context service registry; a bare call would abort apply.
4535
- if (ctx && typeof ctx.provide === 'function') {
4536
- try {
4537
- ctx.provide('dshRemote', hostApi)
4538
- hostLog('info', '[dsh-remote] in-process API available as ctx.dshRemote (apiVersion 1)')
4539
- } catch (err) {
4540
- hostLog('warn', `[dsh-remote] could not register ctx.dshRemote: ${String((err && err.message) || err)}`)
4541
- }
4542
- }
4543
- } catch (err) {
4544
- // The API is additive: never let it break the plugin.
4545
- hostLog('warn', `[dsh-remote] in-process API unavailable: ${String((err && err.message) || err)}`)
4546
- }
4547
-
4548
- // ── TUI integration layer (dsh-tui) ───────────────────────────────────────
4549
- // Additive and optional: lib/tui/index.js probes its seams with
4550
- // `ctx.get(name, false)` and is a no-op on a Web/Desktop profile. A broken
4551
- // TUI layer must never take the host down, hence the guard here too.
4552
- //
4553
- // Loaded LAZILY on purpose: `lib/tui/` is the only SUBDIRECTORY under lib/,
4554
- // and a deployment that copies just `lib/*.js` (a hand-rolled sync, a partial
4555
- // unpacks) would otherwise fail at module-import time and take the whole
4556
- // plugin down in the Web profile as well. A missing TUI directory now means
4557
- // "no terminal layer", which is exactly the pre-TUI behaviour.
4558
- if (config.tui !== false && hostApi) {
4559
- import('./tui/index.js').then((mod) => {
4560
- if (typeof mod.installTui !== 'function') {
4561
- hostLog('warn', '[dsh-remote] TUI layer has no installTui export; skipped')
4562
- return
4563
- }
4564
- try {
4565
- mod.installTui(ctx, hostApi, config)
4566
- } catch (err) {
4567
- hostLog('warn', `[dsh-remote] TUI layer failed to install: ${String((err && err.message) || err)}`)
4568
- }
4569
- }).catch((err) => {
4570
- hostLog('warn', `[dsh-remote] TUI layer unavailable: ${String((err && err.message) || err)}`)
4571
- })
4572
- }
4573
- }
1
+ import { importWithSelfHeal } from './self-heal.js'
2
+
3
+ const mainUrl = new URL('./main.js' + new URL(import.meta.url).search, import.meta.url).href
4
+ const retryUrl = mainUrl + (mainUrl.includes('?') ? '&' : '?') + 'dsh-heal=' + Date.now()
5
+ const { module: main, repaired } = await importWithSelfHeal(() => import(mainUrl), { retryImporter: () => import(retryUrl) })
6
+
7
+ if (repaired) {
8
+ console.warn('[dsh-remote] startup self-repair succeeded — the incomplete update has been fully re-applied and this boot is healthy')
9
+ }
10
+
11
+ export const name = main.name
12
+ export const DEFAULT_UPDATE_MODE = main.DEFAULT_UPDATE_MODE
13
+ export const decodePickStdout = main.decodePickStdout
14
+ export const win32FolderPickScript = main.win32FolderPickScript
15
+ export const LOCAL_BOOTSTRAP_TOOLS = main.LOCAL_BOOTSTRAP_TOOLS
16
+ export const normalizeLocalTools = main.normalizeLocalTools
17
+ export const pickWorkspaceNextStep = main.pickWorkspaceNextStep
18
+ export const inject = main.inject
19
+ export const Config = main.Config
20
+ export const apply = main.apply