dsh-remote 1.2.0 → 1.3.0

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