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