dsh-remote 1.1.2 → 1.2.1

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