dsh-remote 1.5.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/main.js CHANGED
@@ -23,7 +23,7 @@ import { createGitRoutes } from './remote-git.js'
23
23
  import { createLocalWorkspacePool } from './local-workspace.js'
24
24
  import { LOCAL_MUTATION_TOOLS, remoteLocalMutationDecision } from './local-mutation.js'
25
25
  import { fileChange, changeOutput, presentFileChange } from './file-changes.js'
26
- import { captureRemoteFile, atomicRemoteWrite } from './remote-write.js'
26
+ import { captureRemoteFile, atomicRemoteWrite, missingRemoteFile } from './remote-write.js'
27
27
  import z from '@deepseek-ai/schemastery'
28
28
  import { createAutoUpdater } from './auto-update.js'
29
29
  import { defineTool } from '@deepseek-ai/dsh-tools'
@@ -37,7 +37,7 @@ import iconv from 'iconv-lite'
37
37
 
38
38
  import {
39
39
  shq, normalizeRemotePath, joinRemotePath, joinRemoteRel, resolveRemoteWorkspacePath, remoteDirname, mkdirRemoteDirs,
40
- toShellPath, toDisplayPath, remotePathBase, remoteWorkspaceTitle, truncate, shortHash,
40
+ toShellPath, toDisplayPath, remoteWorkspaceTitle, truncate,
41
41
  } from './paths.js'
42
42
  import { createHostKeyGuard, isHostKeyKnown as _isHostKeyKnown } from './hostkey.js'
43
43
  import { compileIgnore, ignorePatternsFor, DEFAULT_IGNORE } from './ignore.js'
@@ -51,12 +51,15 @@ import { createInstructionIndex, formatInstructionIndex } from './instructions.j
51
51
  import { resolveExecTimeout, formatExecResult, startExecJob, execWithOptionalPromotion } from './exec-job.js'
52
52
  import { createInjectionTracker, refreshTouched, buildInstructionMessage, pickUserMessageFactory, loadBundledUserMessageFactory } from './instructions-dynamic.js'
53
53
  import { REMOTE_SANDBOX_MODES, checkRemoteSandbox, remoteSandboxDenial } from './remote-sandbox.js'
54
- import { mirrorConstrainLocalTarget, mirrorDownloadTarget, assertDownloadHasNoSymlinks } from './mirror-paths.js'
54
+ import {
55
+ mirrorConstrainLocalTarget, mirrorDownloadTarget, assertDownloadHasNoSymlinks,
56
+ mirrorDirectory, mirrorDirectoriesUnder, readMirrorMeta, sameMirrorMachine,
57
+ } from './mirror-paths.js'
55
58
  import { createTerminalManager } from './terminal.js'
56
59
  import { createTerminalRoutes } from './routes-term.js'
57
60
  import { searchRemote } from './search.js'
58
61
  import { installTerminalShell } from './remote-shell.js'
59
- import { resolveMirror, poolKey, lookupSessionCwd, encodeSegmentSafe, readSessionHeaderCwd, requestSessionHint } from './binding.js'
62
+ import { resolveMirror, poolKey, lookupSessionCwd, requestSessionHint } from './binding.js'
60
63
  import { TaskManager } from './tasks.js'
61
64
  import { ForwardManager } from './forwards.js'
62
65
  import { formatAuditLine, readAuditLines } from './audit.js'
@@ -67,6 +70,7 @@ import { startHeartbeat, pseudonym, heartbeatUrl, hasPersistedId, installIdPath,
67
70
  import { loadMachines as _loadMachines, saveMachines as _saveMachines, sanitizeMachine as _sanitizeMachine, applyMachine as _applyMachine, machineId as _machineId, normalizeMachineGroup, filterMachinesByGroup, resolveProbeCredentials } from './registry.js'
68
71
  import { registerHttpTransports } from './http-transport.js'
69
72
  import { createHostApi } from './host-api.js'
73
+ import { isWorkspaceSessionCwd } from './workspace-cleanup.js'
70
74
  import { SshPool, ActivePool, createPool } from './pool.js'
71
75
  import { isSystemOpenSshBackend, sshBinaryAvailable, resolveSshBinary } from './openssh.js'
72
76
  import { createAuditRoutes } from './routes-audit.js'
@@ -80,7 +84,7 @@ import { createWorkspaceRoutes } from './routes-workspace.js'
80
84
  import { listDirStructured, removeRemoteTree } from './remote-fs.js'
81
85
  import { registerRemoteSkills } from './remote-skills.js'
82
86
  import { installWorkspaceFilesRemote } from './workspace-files-remote.js'
83
- import { describeConnect } from './connect-summary.js'
87
+ import { connectFailureText, describeConnect } from './connect-summary.js'
84
88
 
85
89
  export const name = 'dsh-remote'
86
90
 
@@ -364,12 +368,6 @@ function remoteWorkspacesRoot() {
364
368
  return path.join(dshBase(), 'remote-workspaces')
365
369
  }
366
370
 
367
- /** Local mirrors of one remote host. */
368
- function mirrorRootFor(host, user, port) {
369
- const tag = [host, user, port].filter(Boolean).join('-').replace(/[^a-zA-Z0-9._-]/g, '_')
370
- return path.join(remoteWorkspacesRoot(), tag)
371
- }
372
-
373
371
  /** Generated terminal launchers. Deliberately NOT under `remote-workspaces`: a
374
372
  * launcher there would sit next to the mirrors, where anything that scans the
375
373
  * root for checkouts could pick it up as one. */
@@ -394,34 +392,12 @@ function remoteShellSpec() {
394
392
  }
395
393
  }
396
394
 
397
- /** Local mirror dir for a specific remote path (idempotent → returns same dir). */
398
- function mirrorDirFor(remotePath, host, user, port) {
399
- const base = remotePathBase(remotePath)
400
- const root = mirrorRootFor(host, user, port)
401
- const plain = path.join(root, base)
402
- const norm = normalizeRemotePath(remotePath)
403
- // A pre-existing mirror for this exact remote origin → reuse it (idempotent).
404
- try {
405
- const meta = JSON.parse(readFileSync(path.join(plain, '.dsh-remote-meta.json'), 'utf8'))
406
- if (meta.remotePath === norm) return plain
407
- } catch {
408
- /* no mirror yet → fall through */
409
- }
410
- if (!existsSync(plain)) return plain
411
- return path.join(root, base + '-' + shortHash(norm))
395
+ function mirrorDirFor(remotePath, host, user, port, alias = '') {
396
+ return mirrorDirectory(remoteWorkspacesRoot(), remotePath, host, user, port, { alias })
412
397
  }
413
398
 
414
- /** Create the local mirror dir + a meta file describing its remote origin.
415
- * `extra.alias` records the ~/.ssh/config alias a machine was saved as (issue
416
- * #38), so the mirror keeps resolving to its machine even if the alias's
417
- * HostName/user/port change in that file afterwards. */
418
- function ensureMirror(remotePath, host, user, port, extra = {}) {
419
- const dir = mirrorDirFor(remotePath, host, user, port)
420
- mkdirSync(dir, { recursive: true })
421
- const meta = { host, port, username: user, remotePath: normalizeRemotePath(remotePath), createdAt: new Date().toISOString() }
422
- if (extra.alias) meta.alias = String(extra.alias)
423
- writeFileSync(path.join(dir, '.dsh-remote-meta.json'), JSON.stringify(meta, null, 2))
424
- return dir
399
+ function ensureMirror(remotePath, host, user, port, { alias = '' } = {}) {
400
+ return mirrorDirectory(remoteWorkspacesRoot(), remotePath, host, user, port, { alias, create: true })
425
401
  }
426
402
 
427
403
  /** Recursive directory copy (EXDEV fallback for migrateLegacyData). */
@@ -960,10 +936,9 @@ export async function apply(ctx, config) {
960
936
  * identity, and directly by the alias the mirror recorded — so a mirror keeps
961
937
  * resolving to its machine even after a HostName/port change in ~/.ssh/config,
962
938
  * which is the whole point of not copying those values into the registry. */
963
- const identityOf = (m) => {
964
- const r = withSshConfig(m)
965
- return { host: r.host, port: Number(r.port) || 22, username: r.username || '' }
966
- }
939
+ const resolvedIdentity = (m) => ({ host: m.host, port: Number(m.port) || 22, username: m.username || '' })
940
+ const identityOf = (m) => resolvedIdentity(withSshConfig(m))
941
+ const mirrorOrigin = (resolved) => ({ ...resolvedIdentity(resolved), alias: aliasOf(resolved) })
967
942
  const identityMatches = (m, { host, port, username }) => {
968
943
  if (!m) return false
969
944
  const id = identityOf(m)
@@ -1247,11 +1222,18 @@ export async function apply(ctx, config) {
1247
1222
  /** Mirror-sync matcher for the workspace rooted at `root` (ROOT_IGNORE is
1248
1223
  * merged only for a filesystem-root workspace — issue #60). */
1249
1224
  const ignoreMatcher = (root) => compileIgnore(ignorePatternsFor(root, { fromFile: readUserIgnore() }))
1250
- /** Search-only matcher: same as ignoreMatcher() plus machine-local cache trees
1251
- * (`~/.npm`, `~/.cache`, …) that are huge, almost never what a human is
1252
- * looking for, and the main cause of the issue #44 hang. Mirror sync is
1253
- * deliberately unaffected. An explicit `path` still searches anywhere. */
1254
- const searchIgnoreMatcher = (root) => compileIgnore(ignorePatternsFor(root, { search: true, fromFile: readUserIgnore() }))
1225
+ /** RAW search ignore patterns for the workspace rooted at `root`: the defaults
1226
+ * plus machine-local cache trees (`~/.npm`, `~/.cache`, …) that are huge,
1227
+ * almost never what a human is looking for, and the main cause of the issue
1228
+ * #44 hang, plus the user's `.dsh-remote-ignore`. Mirror sync keeps its own
1229
+ * narrower set and is deliberately unaffected. An explicit `path` still
1230
+ * searches anywhere.
1231
+ *
1232
+ * The POSIX search fast path receives this SAME list (as `ignorePatterns`), so
1233
+ * its rg/grep excludes cannot drift from the matcher the SFTP walk uses. */
1234
+ const searchIgnorePatterns = (root) => ignorePatternsFor(root, { search: true, fromFile: readUserIgnore() })
1235
+ /** Search-only matcher, compiled from exactly the list above. */
1236
+ const searchIgnoreMatcher = (root) => compileIgnore(searchIgnorePatterns(root))
1255
1237
 
1256
1238
  // ── task + forward managers ───────────────────────────────────────────────
1257
1239
  const tasks = new TaskManager()
@@ -1461,7 +1443,8 @@ export async function apply(ctx, config) {
1461
1443
  // invalidate a pool used by another conversation, terminal or file editor.
1462
1444
  const prepareMirrorTarget = async (remotePath, selectedMachine, signal) => {
1463
1445
  const machine = { ...(selectedMachine || activeMachine() || config) }
1464
- const identity = identityOf(machine)
1446
+ const resolved = machine.sshAlias || machine.sshConfigMatched ? machine : withSshConfig(machine)
1447
+ const identity = resolvedIdentity(resolved)
1465
1448
  const base = poolForMachine({ ...identity, alias: aliasOf(machine) })
1466
1449
  const isolated = createPool({ ...base.config }, { knownHostsFile, opensshKnownHostsFile })
1467
1450
  isolated.passwordResolver = base.passwordResolver
@@ -1484,6 +1467,23 @@ export async function apply(ctx, config) {
1484
1467
 
1485
1468
  // ── remote workspace state ────────────────────────────────────────────────
1486
1469
  const wsPath = () => (config.workspace || '').trim()
1470
+ // OpenSSH can dial by name with implicit user/port. A mirror records the
1471
+ // resolved origin of the selected machine, provided its dial target is active.
1472
+ const activeMirrorOrigin = () => {
1473
+ const active = resolvedIdentity(config)
1474
+ const machine = activeMachine()
1475
+ if (machine) {
1476
+ const dial = connectTargetFor(machine)
1477
+ if (dial.host === active.host && dial.username === active.username && (dial.port || 22) === active.port) return mirrorOrigin(machine)
1478
+ }
1479
+ return active
1480
+ }
1481
+ const activeMirrorDir = ({ host, username, port, alias } = activeMirrorOrigin()) =>
1482
+ wsPath() ? mirrorDirFor(wsPath(), host, username, port, alias) : ''
1483
+ const ensureBoundMirror = (remotePath, binding) => {
1484
+ const { host, username, port, alias } = binding.mirrorOrigin || binding
1485
+ return ensureMirror(remotePath, host, username, port, { alias })
1486
+ }
1487
1487
  /** Map a LOCAL path to the remote path its mirror represents ('' when the
1488
1488
  * path is not inside any dsh-remote mirror). Shared by the resolve-mirror
1489
1489
  * route, the session-aware system-prompt injection, and status().
@@ -1618,54 +1618,38 @@ export async function apply(ctx, config) {
1618
1618
  }
1619
1619
  const nextRaw = { host: String(next.host || ''), port: Number(next.port) || 22, username: String(next.username || '') }
1620
1620
  const sameIdentity = (a, b) => a.host === b.host && a.port === b.port && a.username === b.username
1621
- if (!prevAlias && sameIdentity(prevId, nextId) && sameIdentity(prevRaw, nextRaw)) return 0
1622
- if (prevAlias && prevAlias === nextAlias) return 0
1623
- const root = remoteWorkspacesRoot()
1621
+ if (prevAlias === nextAlias && (prevAlias || (sameIdentity(prevId, nextId) && sameIdentity(prevRaw, nextRaw)))) return 0
1622
+ const previous = { ...prevId, alias: prevAlias }
1623
+ const previousRaw = { ...prevRaw, alias: prevAlias }
1624
1624
  let rebound = 0
1625
- let hostDirs = []
1626
- try { hostDirs = readdirSync(root) } catch { return 0 }
1627
- for (const hostDir of hostDirs) {
1628
- const hostPath = path.join(root, hostDir)
1629
- if (!statSync(hostPath, { throwIfNoEntry: false })?.isDirectory?.()) continue
1630
- let entries = []
1631
- try { entries = readdirSync(hostPath) } catch { continue }
1632
- for (const entry of entries) {
1633
- const metaPath = path.join(hostPath, entry, '.dsh-remote-meta.json')
1634
- let meta = null
1635
- try { meta = JSON.parse(readFileSync(metaPath, 'utf8')) } catch { continue }
1636
- if (!meta || !meta.host) continue
1637
- const byAlias = prevAlias && String(meta.alias || '') === prevAlias
1638
- // A meta records the RESOLVED identity at pick time, but that identity
1639
- // can also have been written raw — match on either form of the old
1640
- // identity so a rebind still finds mirrors recorded before a later
1641
- // ssh-config resolution rewrote what "this machine" meant.
1642
- const metaId = { host: String(meta.host), port: Number(meta.port) || 22, username: String(meta.username || '') }
1643
- const byIdentity = sameIdentity(metaId, prevId) || sameIdentity(metaId, prevRaw)
1644
- if (!byAlias && !byIdentity) continue
1645
- const updated = { ...meta }
1646
- if (nextAlias) {
1647
- // Alias machine: the recorded alias is what future resolution keys
1648
- // on; the resolved address refreshes only when it actually resolved
1649
- // (an unmatched alias keeps the old literal values rather than
1650
- // stamping the alias NAME into the address fields).
1651
- updated.alias = nextAlias
1652
- if (nextEff.sshConfigMatched || nextEff.sshAlias) {
1653
- updated.host = nextId.host
1654
- updated.port = nextId.port
1655
- updated.username = nextId.username
1656
- }
1657
- } else {
1658
- delete updated.alias
1659
- updated.host = nextRaw.host
1660
- updated.port = nextRaw.port
1661
- updated.username = nextRaw.username
1625
+ for (const dir of mirrorDirectoriesUnder(remoteWorkspacesRoot())) {
1626
+ const meta = readMirrorMeta(dir)
1627
+ if (typeof meta?.remotePath !== 'string' || !meta.remotePath) continue
1628
+ // Literal mirrors may have recorded the saved or resolved endpoint.
1629
+ if (!sameMirrorMachine(meta, previous) && !sameMirrorMachine(meta, previousRaw)) continue
1630
+ const updated = { ...meta }
1631
+ if (nextAlias) {
1632
+ // Alias machine: the recorded alias is what future resolution keys
1633
+ // on; the resolved address refreshes only when it actually resolved
1634
+ // (an unmatched alias keeps the old literal values rather than
1635
+ // stamping the alias NAME into the address fields).
1636
+ updated.alias = nextAlias
1637
+ if (nextEff.sshConfigMatched || nextEff.sshAlias) {
1638
+ updated.host = nextId.host
1639
+ updated.port = nextId.port
1640
+ updated.username = nextId.username
1662
1641
  }
1663
- updated.reboundAt = new Date().toISOString()
1664
- try {
1665
- writeFileSync(metaPath, JSON.stringify(updated, null, 2))
1666
- rebound++
1667
- } catch { /* leave that mirror as-is */ }
1642
+ } else {
1643
+ delete updated.alias
1644
+ updated.host = nextRaw.host
1645
+ updated.port = nextRaw.port
1646
+ updated.username = nextRaw.username
1668
1647
  }
1648
+ updated.reboundAt = new Date().toISOString()
1649
+ try {
1650
+ writeFileSync(path.join(dir, '.dsh-remote-meta.json'), JSON.stringify(updated, null, 2))
1651
+ rebound++
1652
+ } catch { /* leave that mirror as-is */ }
1669
1653
  }
1670
1654
  if (rebound) {
1671
1655
  // The old identity's pooled connection dials an address the user just
@@ -1680,9 +1664,7 @@ export async function apply(ctx, config) {
1680
1664
  return rebound
1681
1665
  }
1682
1666
 
1683
- if (config.autoPush && wsPath()) {
1684
- startAutoPush(mirrorDirFor(wsPath(), config.host, config.username, config.port))
1685
- }
1667
+ if (config.autoPush && wsPath()) startAutoPush(activeMirrorDir())
1686
1668
  /** The remote path one agent session is bound to, or '' when that session is
1687
1669
  * a plain local one. Walks the mirror registry (host side copy of the
1688
1670
  * resolve-mirror logic) so status / prompt / sidebar agree.
@@ -1693,6 +1675,13 @@ export async function apply(ctx, config) {
1693
1675
  * another machine. Tool calls must never route through this — they resolve
1694
1676
  * their own session through `bindingFor()`, which is authoritative. */
1695
1677
  const sessionsSvc = () => (ctx && typeof ctx.get === 'function' ? ctx.get('sessions') : null)
1678
+ const listLiveWorkspaceSessions = (cwd) => {
1679
+ const ids = []
1680
+ for (const session of sessionsSvc()?.list?.() || []) {
1681
+ if (session?.id && isWorkspaceSessionCwd(cwd, session.header?.cwd)) ids.push(session.id)
1682
+ }
1683
+ return ids
1684
+ }
1696
1685
 
1697
1686
  /** Whether one session is still open somewhere.
1698
1687
  *
@@ -1704,8 +1693,8 @@ export async function apply(ctx, config) {
1704
1693
  */
1705
1694
  const isSessionLive = async (sessionId, dir, opts = {}) => {
1706
1695
  try {
1707
- const live = sessionsSvc()
1708
- if (live && typeof live.get === 'function' && live.get(sessionId)) return true
1696
+ const session = sessionsSvc()?.get?.(sessionId)
1697
+ if (session && isWorkspaceSessionCwd(opts.cwd, session.header?.cwd)) return true
1709
1698
  } catch { /* no sessions service (minimal embedding) */ }
1710
1699
  if (opts && opts.deep === true && process.platform !== 'win32') {
1711
1700
  const lock = path.join(String(dir || ''), 'session.lock')
@@ -1838,13 +1827,15 @@ export async function apply(ctx, config) {
1838
1827
  err.httpStatus = 409
1839
1828
  throw err
1840
1829
  }
1830
+ const mirrorOrigin = activeMirrorOrigin()
1841
1831
  return {
1842
1832
  pool,
1843
1833
  ws: wsPath(),
1844
1834
  host: config.host,
1845
1835
  username: config.username,
1846
1836
  port: config.port,
1847
- mirrorDir: wsPath() ? mirrorDirFor(wsPath(), config.host, config.username, config.port) : null,
1837
+ mirrorOrigin,
1838
+ mirrorDir: activeMirrorDir(mirrorOrigin) || null,
1848
1839
  bound: false,
1849
1840
  local: false,
1850
1841
  }
@@ -1905,13 +1896,15 @@ export async function apply(ctx, config) {
1905
1896
  }
1906
1897
  }
1907
1898
  }
1899
+ const mirrorOrigin = activeMirrorOrigin()
1908
1900
  return {
1909
1901
  pool,
1910
1902
  ws: wsPath(),
1911
1903
  host: config.host,
1912
1904
  username: config.username,
1913
1905
  port: config.port,
1914
- mirrorDir: wsPath() ? mirrorDirFor(wsPath(), config.host, config.username, config.port) : null,
1906
+ mirrorOrigin,
1907
+ mirrorDir: activeMirrorDir(mirrorOrigin) || null,
1915
1908
  bound: false,
1916
1909
  // A caller that identified itself with a cwd, yet resolved to no mirror,
1917
1910
  // is definitively a LOCAL session. Distinguish it from "no caller
@@ -2050,31 +2043,34 @@ export async function apply(ctx, config) {
2050
2043
  const watcher = autoPushWatchers.get(local)
2051
2044
  return { ...observed, ...(watcher && watcher.pending.size ? { phase: 'pending' } : {}), autoPush: !!config.autoPush }
2052
2045
  }
2053
- const status = () => ({
2054
- host: config.host,
2055
- port: config.port,
2056
- username: config.username,
2057
- connected: !!pool.client,
2058
- workspace: toDisplayPath(wsPath(), pool.platform),
2059
- localMirror: wsPath() ? mirrorDirFor(wsPath(), config.host, config.username, config.port) : '',
2060
- currentId: store.currentId || null,
2061
- sync: syncStatusFor(wsPath() ? mirrorDirFor(wsPath(), config.host, config.username, config.port) : ''),
2062
- activeSource: ephemeral ? 'ephemeral' : (store.currentId ? 'machine' : (config.host ? 'config' : 'none')),
2063
- // Issue #13: whether THIS session is in remote mode (cwd inside a mirror).
2064
- // `none`/`local` means the plugin is present but no remote context is
2065
- // active — saved machines stay standby-only.
2066
- sessionMode: sessionRemotePath() ? 'remote' : (store.currentId ? 'standby' : 'local'),
2067
- sessionRemotePath: sessionRemotePath(),
2068
- machines: machinesForClient(),
2069
- hostKeyMode: config.hostKeyMode === 'verify' || config.hostKeyMode === 'off' ? config.hostKeyMode : 'accept-new',
2070
- hostKeyKnown: config.host ? isHostKeyKnown(config.host, config.port) : false,
2071
- forwards: forwards.list(),
2072
- auditEnabled: !!config.auditLog,
2073
- backend: platformBackend(),
2074
- platform: pool.platform,
2075
- shell: pool.shellMode,
2076
- gitBash: pool.gitBashPath || '',
2077
- })
2046
+ const status = () => {
2047
+ const localMirror = activeMirrorDir()
2048
+ return {
2049
+ host: config.host,
2050
+ port: config.port,
2051
+ username: config.username,
2052
+ connected: !!pool.client,
2053
+ workspace: toDisplayPath(wsPath(), pool.platform),
2054
+ localMirror,
2055
+ currentId: store.currentId || null,
2056
+ sync: syncStatusFor(localMirror),
2057
+ activeSource: ephemeral ? 'ephemeral' : (store.currentId ? 'machine' : (config.host ? 'config' : 'none')),
2058
+ // Issue #13: whether THIS session is in remote mode (cwd inside a mirror).
2059
+ // `none`/`local` means the plugin is present but no remote context is
2060
+ // active — saved machines stay standby-only.
2061
+ sessionMode: sessionRemotePath() ? 'remote' : (store.currentId ? 'standby' : 'local'),
2062
+ sessionRemotePath: sessionRemotePath(),
2063
+ machines: machinesForClient(),
2064
+ hostKeyMode: config.hostKeyMode === 'verify' || config.hostKeyMode === 'off' ? config.hostKeyMode : 'accept-new',
2065
+ hostKeyKnown: config.host ? isHostKeyKnown(config.host, config.port) : false,
2066
+ forwards: forwards.list(),
2067
+ auditEnabled: !!config.auditLog,
2068
+ backend: platformBackend(),
2069
+ platform: pool.platform,
2070
+ shell: pool.shellMode,
2071
+ gitBash: pool.gitBashPath || '',
2072
+ }
2073
+ }
2078
2074
 
2079
2075
  // ── remote `@` completion (issue #39) ─────────────────────────────────────
2080
2076
  //
@@ -2421,7 +2417,7 @@ export async function apply(ctx, config) {
2421
2417
  const res = await pool.exec('echo ok', { timeoutMs: 8000 })
2422
2418
  if (res.code !== 0 && !res.stdout) {
2423
2419
  audit('connect', `connect ${effUser}@${effHost}:${effPort}`, res.code)
2424
- return { text: 'connect failed: ' + (res.stderr || 'exit ' + res.code) }
2420
+ return { text: 'connect failed: ' + connectFailureText(res, { host: effHost, timeoutMs: 8000 }) }
2425
2421
  }
2426
2422
  audit('connect', `connect ${effUser}@${effHost}:${effPort}`, 0)
2427
2423
  // The probe's identity is the DIAL one; on the system-OpenSSH backend
@@ -2538,8 +2534,8 @@ export async function apply(ctx, config) {
2538
2534
  if (!ok) return { text: `not a directory (or missing) on ${shown}` }
2539
2535
  // A bound session's workspace lives in its own mirror meta, so the
2540
2536
  // shared active-machine workspace is only updated for the unbound flow.
2537
+ const local = ensureBoundMirror(p, b)
2541
2538
  if (!b.bound) persistWorkspace(p)
2542
- const local = ensureMirror(p, b.host, b.username, b.port, { alias: b.alias || "" })
2543
2539
  startAutoPush(local)
2544
2540
  // Issue #68: discover the workspace's AGENTS.md / CLAUDE.md NOW — the
2545
2541
  // first prompt assembly can come before any rw_sync, and the mirror
@@ -2576,18 +2572,21 @@ export async function apply(ctx, config) {
2576
2572
  async execute(args, exec) {
2577
2573
  const b = requireBinding(exec, 'rw_sync')
2578
2574
  const p = b.ws
2579
- const local = b.mirrorDir || mirrorDirFor(p, b.host, b.username, b.port)
2575
+ const local = b.bound ? b.mirrorDir : ensureBoundMirror(p, b)
2576
+ assertDownloadHasNoSymlinks(local, local)
2580
2577
  mkdirSync(local, { recursive: true })
2581
2578
  const depth = Math.min(Math.max(Number(args.depth) || 8, 1), 16)
2582
2579
  const maxFiles = Math.min(Math.max(Number(args.maxFiles) || 2000, 1), 20000)
2583
2580
  const isIgnored = ignoreMatcher(p)
2584
2581
  const body = { depth, maxDepth: depth, maxFiles, dryRun: !!args.dryRun, force: !!args.force, isIgnored }
2585
- const runSync = () => syncActivity.run(local, 'download', async (record) => {
2582
+ const runSync = (taskCtx) => syncActivity.run(local, 'download', async (record) => {
2583
+ const isCancelled = () => !!taskCtx?.cancelled
2584
+ mkdirSync(local, { recursive: true })
2586
2585
  let sftp
2587
2586
  try {
2588
2587
  sftp = await b.pool.sftp()
2589
2588
  } catch (err) {
2590
- throw new Error('sftp unavailable: ' + ((err && err.message) || err))
2589
+ if (!isCancelled()) throw new Error('sftp unavailable: ' + ((err && err.message) || err))
2591
2590
  }
2592
2591
  const state = loadSyncState(local)
2593
2592
  const { stats, nextState } = await syncTree(sftp, p, local, {
@@ -2595,10 +2594,12 @@ export async function apply(ctx, config) {
2595
2594
  state,
2596
2595
  maxFileBytes: config.maxFileBytes,
2597
2596
  getSftp: () => b.pool.sftp(),
2597
+ isCancelled,
2598
2598
  })
2599
2599
  record(stats)
2600
- if (!args.dryRun) saveSyncState(local, nextState)
2600
+ if (!args.dryRun && (!stats.cancelled || stats.files)) saveSyncState(local, nextState)
2601
2601
  let text = `${args.dryRun ? 'WOULD download' : 'Downloaded'} ${stats.files} file(s) from ${p} → ${local}.`
2602
+ if (stats.cancelled) text += ' CANCELLED (started downloads were allowed to finish; re-run rw_sync to continue).'
2602
2603
  if (stats.abortedError) text += ` ABORTED early (${stats.abortedError}; re-run rw_sync to resume incremental sync, or use rw_download for a specific file).`
2603
2604
  else if (stats.failed) text += ` ${stats.failed} failed.`
2604
2605
  if (stats.truncated || stats.files >= maxFiles) text += ` TRUNCATED (hit depth=${depth} or maxFiles=${maxFiles} cap; raise maxFiles/depth and re-run).`
@@ -2616,9 +2617,9 @@ export async function apply(ctx, config) {
2616
2617
  // Issue #68: a real sync can pull in (or obsolete) instruction files —
2617
2618
  // refresh the prompt index afterwards. Kept inside the task body so a
2618
2619
  // background sync refreshes when IT finishes, not when it is queued.
2619
- const runSyncAndIndex = async () => {
2620
- const r = await runSync()
2621
- if (!args.dryRun) {
2620
+ const runSyncAndIndex = async (taskCtx) => {
2621
+ const r = await runSync(taskCtx)
2622
+ if (!args.dryRun && !taskCtx?.cancelled) {
2622
2623
  try { await instructionIndex.refresh({ pool: b.pool, ws: p, mirrorDir: local, force: true }) } catch { /* best effort */ }
2623
2624
  }
2624
2625
  return r
@@ -2645,24 +2646,27 @@ export async function apply(ctx, config) {
2645
2646
  async execute(args, exec) {
2646
2647
  const b = requireBinding(exec, 'rw_push')
2647
2648
  const p = b.ws
2648
- const local = b.mirrorDir || mirrorDirFor(p, b.host, b.username, b.port)
2649
+ const local = b.mirrorDir || mirrorDirFor(p, b.host, b.username, b.port, b.alias)
2649
2650
  if (!existsSync(local)) throw new Error(`rw_push: local mirror does not exist — run rw_sync first (${local})`)
2650
2651
  const maxFiles = Math.min(Math.max(Number(args.maxFiles) || 2000, 1), 20000)
2651
2652
  const isIgnored = ignoreMatcher(p)
2652
2653
  const body = { maxFiles, dryRun: !!args.dryRun, force: !!args.force, isIgnored }
2653
- const runPush = () => syncActivity.run(local, 'upload', async (record) => {
2654
+ const runPush = (taskCtx) => syncActivity.run(local, 'upload', async (record) => {
2655
+ const isCancelled = () => !!taskCtx?.cancelled
2654
2656
  let sftp
2655
2657
  try {
2656
2658
  sftp = await b.pool.sftp()
2657
2659
  } catch (err) {
2658
- throw new Error('sftp unavailable: ' + ((err && err.message) || err))
2660
+ if (!isCancelled()) throw new Error('sftp unavailable: ' + ((err && err.message) || err))
2659
2661
  }
2660
2662
  const state = loadSyncState(local)
2661
2663
  try {
2662
- const { stats, nextState } = await pushTree(sftp, local, p, { ...body, state, maxFileBytes: config.maxFileBytes })
2664
+ const { stats, nextState } = await pushTree(sftp, local, p, { ...body, state, maxFileBytes: config.maxFileBytes, isCancelled })
2663
2665
  record(stats)
2664
- if (!args.dryRun) saveSyncState(local, nextState)
2666
+ if (!args.dryRun && (!stats.cancelled || stats.files)) saveSyncState(local, nextState)
2665
2667
  let text = `${args.dryRun ? 'WOULD upload' : 'Uploaded'} ${stats.files} file(s) from ${local} → ${p}.`
2668
+ if (stats.failed) text += ` ${stats.failed} failed.`
2669
+ if (stats.cancelled) text += ' CANCELLED (started uploads were allowed to finish; re-run rw_push to continue).'
2666
2670
  if (stats.truncated || stats.files >= maxFiles) text += ` TRUNCATED (hit maxFiles=${maxFiles} cap; raise maxFiles and re-run).`
2667
2671
  if (stats.skippedUnchanged) text += ` ${stats.skippedUnchanged} unchanged.`
2668
2672
  if (stats.skippedLarge) text += ` ${stats.skippedLarge} too large (over ${config.maxFileBytes} bytes).`
@@ -2952,7 +2956,7 @@ export async function apply(ctx, config) {
2952
2956
  defineTool({
2953
2957
  name: 'rw_remove',
2954
2958
  description:
2955
- '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.',
2959
+ 'Delete a remote file or symbolic link. recursive=true removes a directory tree (bounded). Path is absolute. This is destructive — the agent should confirm intent before calling.',
2956
2960
  parameters: {
2957
2961
  path: { type: 'string', required: true, description: 'Absolute remote path to delete' },
2958
2962
  recursive: { type: 'boolean', description: 'Recursively delete a directory (default false)' },
@@ -2965,13 +2969,17 @@ export async function apply(ctx, config) {
2965
2969
  const p = resolveRemoteArg(b, args.path)
2966
2970
  if (!p || p === '/') throw new Error('rw_remove: a path is required')
2967
2971
  const sftp = await b.pool.sftp()
2968
- const st = await sftp.stat(p).catch(() => null)
2972
+ const st = await sftp.lstat(p).catch(error => { if (missingRemoteFile(error)) return null; throw error })
2969
2973
  if (!st) return { ok: false, text: `not found: ${p}` }
2970
- if (st.isDirectory && st.isDirectory()) {
2974
+ if (st.isDirectory?.()) {
2971
2975
  if (!args.recursive) throw new Error(`rw_remove: ${p} is a directory — pass recursive=true to delete its tree`)
2972
- const removed = await removeRemoteTree(sftp, p)
2976
+ const result = await removeRemoteTree(sftp, p)
2977
+ if (result.error) {
2978
+ audit('remove', result.error, 1, b)
2979
+ return { ok: false, text: result.error }
2980
+ }
2973
2981
  audit('remove', `remove -r ${p}`, 0, b)
2974
- return { ok: true, text: `removed ${removed} entries under ${p}` }
2982
+ return { ok: true, text: `removed ${result.removed} entries under ${p}` }
2975
2983
  }
2976
2984
  await sftp.unlink(p)
2977
2985
  audit('remove', `remove ${p}`, 0, b)
@@ -3128,7 +3136,8 @@ export async function apply(ctx, config) {
3128
3136
  // `running` and cancel/steer did nothing (issue #44).
3129
3137
  const maxFiles = Math.min(Math.max(Number(args.maxEntries) || config.searchMaxEntries, 1), 500000)
3130
3138
  const maxDurationMs = Math.min(Math.max(Number(args.maxDurationMs) || config.searchTimeoutMs, 1000), 600000)
3131
- const matcher = searchIgnoreMatcher(dir)
3139
+ const ignorePatterns = searchIgnorePatterns(dir)
3140
+ const matcher = compileIgnore(ignorePatterns)
3132
3141
  const { matches, scanned, truncated, cancelled } = await searchRemote(b.pool, dir, {
3133
3142
  pattern,
3134
3143
  regex,
@@ -3141,6 +3150,9 @@ export async function apply(ctx, config) {
3141
3150
  signal: exec.signal,
3142
3151
  maxScanBytes: Math.min(config.maxFileBytes || 1024 * 1024, 1024 * 1024),
3143
3152
  isIgnored: (name, isDir) => matcher(name, isDir),
3153
+ // The raw patterns, not the compiled matcher: the POSIX fast path
3154
+ // (rg/grep) needs flags derived from the same rule list.
3155
+ ignorePatterns,
3144
3156
  timeoutMs: Math.min(config.commandTimeoutMs, maxDurationMs),
3145
3157
  })
3146
3158
  const note = cancelled
@@ -3175,7 +3187,7 @@ export async function apply(ctx, config) {
3175
3187
  const p = resolveRemoteArg(b, args.path)
3176
3188
  if (!p || p === '/') throw new Error('rw_download: a remote file path is required')
3177
3189
  const ws = b.ws
3178
- let base = b.mirrorDir || (ws ? mirrorDirFor(ws, b.host, b.username, b.port) : '')
3190
+ const base = b.mirrorDir || (ws ? mirrorDirFor(ws, b.host, b.username, b.port, b.alias) : '')
3179
3191
  if (!ws || !base) throw new Error('rw_download: no remote workspace set — downloads land inside the local mirror of the workspace')
3180
3192
  // Both destination forms resolve inside the mirror with the same
3181
3193
  // grammar-aware mapping + symlink guard the HTTP download route applies
@@ -3185,16 +3197,8 @@ export async function apply(ctx, config) {
3185
3197
  ? mirrorConstrainLocalTarget(base, String(args.localPath))
3186
3198
  : mirrorDownloadTarget(base, ws, p)
3187
3199
  assertDownloadHasNoSymlinks(base, local)
3188
- // Persist the mirror meta once downloads start landing here: the
3189
- // registry lookup is only idempotent when the meta exists, and a
3190
- // session opened inside this mirror binds to the machine through it.
3191
- // Persist the mirror meta before landing anything: the directory
3192
- // lookup is only idempotent once the meta exists, and a bare download
3193
- // used to leave the dir anonymous — the next call would then resolve
3194
- // to a hashed sibling and "move" the mirror. Also lets a session
3195
- // opened inside this mirror bind back to the machine.
3196
- if (!existsSync(path.join(base, '.dsh-remote-meta.json'))) {
3197
- try { ensureMirror(ws, b.host, b.username, b.port) } catch { /* meta is an optimization, not a gate */ }
3200
+ if (!b.bound && ensureBoundMirror(ws, b) !== base) {
3201
+ throw new Error('rw_download: local mirror changed while preparing the download — retry')
3198
3202
  }
3199
3203
  mkdirSync(path.dirname(local), { recursive: true })
3200
3204
  const sftp = await b.pool.sftp()
@@ -4213,6 +4217,7 @@ export async function apply(ctx, config) {
4213
4217
  port: t.aliasNative ? 22 : (Number(eff.port) || 22),
4214
4218
  username: t.aliasNative ? '' : String(eff.username || ''),
4215
4219
  alias: aliasOf(eff),
4220
+ mirrorOrigin: mirrorOrigin(eff),
4216
4221
  }
4217
4222
  }
4218
4223
  const rec = store.currentId && machineIndex(store.currentId) >= 0 ? machines[machineIndex(store.currentId)] : null
@@ -4229,6 +4234,7 @@ export async function apply(ctx, config) {
4229
4234
  port: t.aliasNative ? 22 : (Number(m.port) || 22),
4230
4235
  username: t.aliasNative ? '' : String(m.username || ''),
4231
4236
  alias: aliasOf(m),
4237
+ mirrorOrigin: mirrorOrigin(m),
4232
4238
  }
4233
4239
  }
4234
4240
 
@@ -4440,81 +4446,22 @@ export async function apply(ctx, config) {
4440
4446
  handler: async (req, res) => {
4441
4447
  if (req.method !== 'GET') return sendJson(res, 405, { error: 'method not allowed' })
4442
4448
  try {
4443
- const q = new URL(req.url, 'http://localhost').searchParams
4444
- let local = q.get('local') ? decodeURIComponent(q.get('local')) : ''
4445
- const sessionId = q.get('sessionId') ? decodeURIComponent(q.get('sessionId')) : ''
4449
+ let { local, sessionId } = requestSessionHint(req)
4446
4450
  let resolvedVia = 'query'
4447
4451
  if (!local && sessionId) {
4448
- // 1) Live in-memory session header (active sessions only).
4449
- try {
4450
- const sessions = ctx && typeof ctx.get === 'function' ? ctx.get('sessions') : null
4451
- const session = sessions && typeof sessions.get === 'function' ? sessions.get(sessionId) : null
4452
- const header = session && session.header ? session.header : null
4453
- if (header && header.cwd) {
4454
- local = String(header.cwd)
4455
- resolvedVia = 'session'
4456
- }
4457
- } catch { /* sessions service unavailable */ }
4458
- // 2) Durable session log header (works for historical sessions too):
4459
- // walk $DSH_HOME/sessions/<projectKey>/<sessionId>/session.jsonl.zstd
4460
- // and read the header line (first zstd frame) for cwd.
4461
- if (!local) {
4462
- try {
4463
- const sessionsRoot = path.join(dshBase(), 'sessions')
4464
- if (existsSync(sessionsRoot)) {
4465
- const targetDir = encodeSegmentSafe(sessionId)
4466
- for (const projDir of readdirSync(sessionsRoot)) {
4467
- const projPath = path.join(sessionsRoot, projDir)
4468
- if (!statSync(projPath, { throwIfNoEntry: false })?.isDirectory?.()) continue
4469
- const sessDir = path.join(projPath, targetDir)
4470
- if (!statSync(sessDir, { throwIfNoEntry: false })?.isDirectory?.()) continue
4471
- const logFile = ['session.jsonl.zstd', 'session.jsonl', 'session.jsonl.gz'].map((n) => path.join(sessDir, n)).find((p) => existsSync(p))
4472
- if (!logFile) continue
4473
- const cwd = readSessionHeaderCwd(logFile)
4474
- if (cwd) {
4475
- local = cwd
4476
- resolvedVia = 'session-log'
4477
- break
4478
- }
4479
- }
4480
- }
4481
- } catch { /* session log scan failed */ }
4452
+ local = lookupSessionCwd(sessionId, { sessions: sessionsSvc() })
4453
+ if (local) resolvedVia = 'session'
4454
+ else {
4455
+ local = lookupSessionCwd(sessionId, { dshHome: dshBase() })
4456
+ if (local) resolvedVia = 'session-log'
4482
4457
  }
4483
4458
  }
4484
- const root = remoteWorkspacesRoot()
4485
- const norm = (p) => path.resolve(String(p || '')).replace(/[\\/]+$/, '') || ''
4486
- let matched = ''
4487
- let matchedRemote = ''
4488
- if (local && existsSync(root)) {
4489
- const base = norm(local)
4490
- for (const hostDir of readdirSync(root)) {
4491
- const hostPath = path.join(root, hostDir)
4492
- if (!statSync(hostPath, { throwIfNoEntry: false })?.isDirectory?.()) continue
4493
- for (const mirrorDir of readdirSync(hostPath)) {
4494
- const metaPath = path.join(hostPath, mirrorDir, '.dsh-remote-meta.json')
4495
- if (!existsSync(metaPath)) continue
4496
- try {
4497
- const meta = JSON.parse(readFileSync(metaPath, 'utf8'))
4498
- const mirrorAbs = norm(path.join(hostPath, mirrorDir))
4499
- // Exact mirror dir match, or the local path is inside the mirror dir.
4500
- if (mirrorAbs === base || base.startsWith(mirrorAbs + path.sep) || base.startsWith(mirrorAbs + '/')) {
4501
- if (mirrorAbs.length > matched.length) {
4502
- matched = mirrorAbs
4503
- matchedRemote = String(meta.remotePath || '')
4504
- }
4505
- }
4506
- } catch { /* skip unparsable meta */ }
4507
- }
4508
- }
4509
- }
4510
- // Issue #13: a non-mirror session is LOCAL — remotePath stays empty.
4511
- const remotePath = matchedRemote || ''
4459
+ const { remotePath, mirrorDir } = resolveMirrorForLocal(local)
4460
+ // Issue #13: sessions without a mirror never fall back to the active machine.
4512
4461
  return sendJson(res, 200, {
4513
- local, remotePath, mirrorDir: matched || null,
4514
- // `fallback:true` now means "this session is NOT a remote session"
4515
- // (used to mean "fell back to machine workspace").
4516
- fallback: !matchedRemote,
4517
- mode: matchedRemote ? 'remote' : 'local',
4462
+ local, remotePath, mirrorDir,
4463
+ fallback: !remotePath,
4464
+ mode: remotePath ? 'remote' : 'local',
4518
4465
  resolvedVia,
4519
4466
  })
4520
4467
  } catch (err) {
@@ -4546,13 +4493,13 @@ export async function apply(ctx, config) {
4546
4493
  // Mirror/connection surface (extracted for issue #82).
4547
4494
  ...createWorkspaceRoutes({
4548
4495
  sendJson, readBody, parseJsonObject, config, pool, backendFor, status, isRemoteDir, persistWorkspace, ensureMirror,
4549
- aliasOf, activeMachine, startAutoPush, applyRequestedMachine, registerMirroredWorkspace, localPickCapability,
4496
+ aliasOf, activeMachine, activeMirrorOrigin, startAutoPush, applyRequestedMachine, registerMirroredWorkspace, localPickCapability,
4550
4497
  pickLocalNative, listLocalDrives, probeMachineRecord, setCurrent, knownHostsFile, prepareMirrorTarget, machineForId: (id) => machines.find((m) => m.id === id),
4551
4498
  }),
4552
4499
  ...createSearchRoutes({ searches: workspaceSearches, sendJson, readBody, resolveRequestBinding: resolveWorkbenchBinding, isIgnoredFor: searchIgnoreMatcher }),
4553
4500
  ...createGitRoutes({ sendJson, resolveRequestBinding: resolveWorkbenchBinding, decodeBuf, config }),
4554
4501
  ...createFsRoutes({
4555
- sendJson, readBody, resolveRequestBinding: resolveWorkbenchBinding, decodeBuf, encodeText, audit, config, mirrorDirFor,
4502
+ sendJson, readBody, resolveRequestBinding: resolveWorkbenchBinding, decodeBuf, encodeText, audit, config, mirrorDirFor, ensureBoundMirror,
4556
4503
  onRemoteMutation: () => { if (remoteSkills) remoteSkills.invalidate() },
4557
4504
  openLocalPath, mirrorRoot: remoteWorkspacesRoot,
4558
4505
  }),
@@ -4698,7 +4645,10 @@ export async function apply(ctx, config) {
4698
4645
  resolveDirBinding: listDirBindingForApi,
4699
4646
  listRemoteProjects: listRemoteProjectsForApi,
4700
4647
  revealMirrorFolderRecord: revealMirrorFolderForApi,
4701
- resolveMachine: resolveMachineForApi,
4648
+ resolveMachine: (id) => {
4649
+ const machine = resolveMachineForApi(id)
4650
+ return { ...machine, ...machine.mirrorOrigin }
4651
+ },
4702
4652
  ensureMirror,
4703
4653
  registerMirroredWorkspace,
4704
4654
  checkRemoteDir: checkRemoteDirForApi,
@@ -4707,6 +4657,7 @@ export async function apply(ctx, config) {
4707
4657
  workspaceRegistry: () => (ctx && typeof ctx.get === 'function' ? ctx.get('workspaceRegistry') : undefined),
4708
4658
  forgetRemotePath,
4709
4659
  isSessionLive,
4660
+ listLiveWorkspaceSessions,
4710
4661
  })
4711
4662
  // cordis 4: `ctx.provide(name, value)` is the raw service registry (the
4712
4663
  // `Service` base class is only sugar around it). Guarded because a minimal