dsh-remote 1.5.0 → 1.6.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 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). */
@@ -804,10 +780,12 @@ export async function apply(ctx, config) {
804
780
  const persistWebAttachCommand = (machine, command) => {
805
781
  try {
806
782
  const i = machineIndex(machine.id)
807
- if (i < 0) return
783
+ if (i < 0) return false
808
784
  machines[i] = { ...machines[i], webAttachCommand: String(command || '') }
809
785
  saveMachines(machines, store.currentId, false)
786
+ return true
810
787
  } catch { /* a failed persist only costs a re-deploy next time */ }
788
+ return false
811
789
  }
812
790
 
813
791
  /** The machine the pool is currently bound to: an ephemeral tool connection
@@ -960,10 +938,9 @@ export async function apply(ctx, config) {
960
938
  * identity, and directly by the alias the mirror recorded — so a mirror keeps
961
939
  * resolving to its machine even after a HostName/port change in ~/.ssh/config,
962
940
  * 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
- }
941
+ const resolvedIdentity = (m) => ({ host: m.host, port: Number(m.port) || 22, username: m.username || '' })
942
+ const identityOf = (m) => resolvedIdentity(withSshConfig(m))
943
+ const mirrorOrigin = (resolved) => ({ ...resolvedIdentity(resolved), alias: aliasOf(resolved) })
967
944
  const identityMatches = (m, { host, port, username }) => {
968
945
  if (!m) return false
969
946
  const id = identityOf(m)
@@ -1247,11 +1224,18 @@ export async function apply(ctx, config) {
1247
1224
  /** Mirror-sync matcher for the workspace rooted at `root` (ROOT_IGNORE is
1248
1225
  * merged only for a filesystem-root workspace — issue #60). */
1249
1226
  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() }))
1227
+ /** RAW search ignore patterns for the workspace rooted at `root`: the defaults
1228
+ * plus machine-local cache trees (`~/.npm`, `~/.cache`, …) that are huge,
1229
+ * almost never what a human is looking for, and the main cause of the issue
1230
+ * #44 hang, plus the user's `.dsh-remote-ignore`. Mirror sync keeps its own
1231
+ * narrower set and is deliberately unaffected. An explicit `path` still
1232
+ * searches anywhere.
1233
+ *
1234
+ * The POSIX search fast path receives this SAME list (as `ignorePatterns`), so
1235
+ * its rg/grep excludes cannot drift from the matcher the SFTP walk uses. */
1236
+ const searchIgnorePatterns = (root) => ignorePatternsFor(root, { search: true, fromFile: readUserIgnore() })
1237
+ /** Search-only matcher, compiled from exactly the list above. */
1238
+ const searchIgnoreMatcher = (root) => compileIgnore(searchIgnorePatterns(root))
1255
1239
 
1256
1240
  // ── task + forward managers ───────────────────────────────────────────────
1257
1241
  const tasks = new TaskManager()
@@ -1461,7 +1445,8 @@ export async function apply(ctx, config) {
1461
1445
  // invalidate a pool used by another conversation, terminal or file editor.
1462
1446
  const prepareMirrorTarget = async (remotePath, selectedMachine, signal) => {
1463
1447
  const machine = { ...(selectedMachine || activeMachine() || config) }
1464
- const identity = identityOf(machine)
1448
+ const resolved = machine.sshAlias || machine.sshConfigMatched ? machine : withSshConfig(machine)
1449
+ const identity = resolvedIdentity(resolved)
1465
1450
  const base = poolForMachine({ ...identity, alias: aliasOf(machine) })
1466
1451
  const isolated = createPool({ ...base.config }, { knownHostsFile, opensshKnownHostsFile })
1467
1452
  isolated.passwordResolver = base.passwordResolver
@@ -1484,6 +1469,23 @@ export async function apply(ctx, config) {
1484
1469
 
1485
1470
  // ── remote workspace state ────────────────────────────────────────────────
1486
1471
  const wsPath = () => (config.workspace || '').trim()
1472
+ // OpenSSH can dial by name with implicit user/port. A mirror records the
1473
+ // resolved origin of the selected machine, provided its dial target is active.
1474
+ const activeMirrorOrigin = () => {
1475
+ const active = resolvedIdentity(config)
1476
+ const machine = activeMachine()
1477
+ if (machine) {
1478
+ const dial = connectTargetFor(machine)
1479
+ if (dial.host === active.host && dial.username === active.username && (dial.port || 22) === active.port) return mirrorOrigin(machine)
1480
+ }
1481
+ return active
1482
+ }
1483
+ const activeMirrorDir = ({ host, username, port, alias } = activeMirrorOrigin()) =>
1484
+ wsPath() ? mirrorDirFor(wsPath(), host, username, port, alias) : ''
1485
+ const ensureBoundMirror = (remotePath, binding) => {
1486
+ const { host, username, port, alias } = binding.mirrorOrigin || binding
1487
+ return ensureMirror(remotePath, host, username, port, { alias })
1488
+ }
1487
1489
  /** Map a LOCAL path to the remote path its mirror represents ('' when the
1488
1490
  * path is not inside any dsh-remote mirror). Shared by the resolve-mirror
1489
1491
  * route, the session-aware system-prompt injection, and status().
@@ -1618,54 +1620,38 @@ export async function apply(ctx, config) {
1618
1620
  }
1619
1621
  const nextRaw = { host: String(next.host || ''), port: Number(next.port) || 22, username: String(next.username || '') }
1620
1622
  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()
1623
+ if (prevAlias === nextAlias && (prevAlias || (sameIdentity(prevId, nextId) && sameIdentity(prevRaw, nextRaw)))) return 0
1624
+ const previous = { ...prevId, alias: prevAlias }
1625
+ const previousRaw = { ...prevRaw, alias: prevAlias }
1624
1626
  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
1627
+ for (const dir of mirrorDirectoriesUnder(remoteWorkspacesRoot())) {
1628
+ const meta = readMirrorMeta(dir)
1629
+ if (typeof meta?.remotePath !== 'string' || !meta.remotePath) continue
1630
+ // Literal mirrors may have recorded the saved or resolved endpoint.
1631
+ if (!sameMirrorMachine(meta, previous) && !sameMirrorMachine(meta, previousRaw)) continue
1632
+ const updated = { ...meta }
1633
+ if (nextAlias) {
1634
+ // Alias machine: the recorded alias is what future resolution keys
1635
+ // on; the resolved address refreshes only when it actually resolved
1636
+ // (an unmatched alias keeps the old literal values rather than
1637
+ // stamping the alias NAME into the address fields).
1638
+ updated.alias = nextAlias
1639
+ if (nextEff.sshConfigMatched || nextEff.sshAlias) {
1640
+ updated.host = nextId.host
1641
+ updated.port = nextId.port
1642
+ updated.username = nextId.username
1662
1643
  }
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 */ }
1644
+ } else {
1645
+ delete updated.alias
1646
+ updated.host = nextRaw.host
1647
+ updated.port = nextRaw.port
1648
+ updated.username = nextRaw.username
1668
1649
  }
1650
+ updated.reboundAt = new Date().toISOString()
1651
+ try {
1652
+ writeFileSync(path.join(dir, '.dsh-remote-meta.json'), JSON.stringify(updated, null, 2))
1653
+ rebound++
1654
+ } catch { /* leave that mirror as-is */ }
1669
1655
  }
1670
1656
  if (rebound) {
1671
1657
  // The old identity's pooled connection dials an address the user just
@@ -1680,9 +1666,7 @@ export async function apply(ctx, config) {
1680
1666
  return rebound
1681
1667
  }
1682
1668
 
1683
- if (config.autoPush && wsPath()) {
1684
- startAutoPush(mirrorDirFor(wsPath(), config.host, config.username, config.port))
1685
- }
1669
+ if (config.autoPush && wsPath()) startAutoPush(activeMirrorDir())
1686
1670
  /** The remote path one agent session is bound to, or '' when that session is
1687
1671
  * a plain local one. Walks the mirror registry (host side copy of the
1688
1672
  * resolve-mirror logic) so status / prompt / sidebar agree.
@@ -1693,6 +1677,13 @@ export async function apply(ctx, config) {
1693
1677
  * another machine. Tool calls must never route through this — they resolve
1694
1678
  * their own session through `bindingFor()`, which is authoritative. */
1695
1679
  const sessionsSvc = () => (ctx && typeof ctx.get === 'function' ? ctx.get('sessions') : null)
1680
+ const listLiveWorkspaceSessions = (cwd) => {
1681
+ const ids = []
1682
+ for (const session of sessionsSvc()?.list?.() || []) {
1683
+ if (session?.id && isWorkspaceSessionCwd(cwd, session.header?.cwd)) ids.push(session.id)
1684
+ }
1685
+ return ids
1686
+ }
1696
1687
 
1697
1688
  /** Whether one session is still open somewhere.
1698
1689
  *
@@ -1704,8 +1695,8 @@ export async function apply(ctx, config) {
1704
1695
  */
1705
1696
  const isSessionLive = async (sessionId, dir, opts = {}) => {
1706
1697
  try {
1707
- const live = sessionsSvc()
1708
- if (live && typeof live.get === 'function' && live.get(sessionId)) return true
1698
+ const session = sessionsSvc()?.get?.(sessionId)
1699
+ if (session && isWorkspaceSessionCwd(opts.cwd, session.header?.cwd)) return true
1709
1700
  } catch { /* no sessions service (minimal embedding) */ }
1710
1701
  if (opts && opts.deep === true && process.platform !== 'win32') {
1711
1702
  const lock = path.join(String(dir || ''), 'session.lock')
@@ -1838,13 +1829,15 @@ export async function apply(ctx, config) {
1838
1829
  err.httpStatus = 409
1839
1830
  throw err
1840
1831
  }
1832
+ const mirrorOrigin = activeMirrorOrigin()
1841
1833
  return {
1842
1834
  pool,
1843
1835
  ws: wsPath(),
1844
1836
  host: config.host,
1845
1837
  username: config.username,
1846
1838
  port: config.port,
1847
- mirrorDir: wsPath() ? mirrorDirFor(wsPath(), config.host, config.username, config.port) : null,
1839
+ mirrorOrigin,
1840
+ mirrorDir: activeMirrorDir(mirrorOrigin) || null,
1848
1841
  bound: false,
1849
1842
  local: false,
1850
1843
  }
@@ -1905,13 +1898,15 @@ export async function apply(ctx, config) {
1905
1898
  }
1906
1899
  }
1907
1900
  }
1901
+ const mirrorOrigin = activeMirrorOrigin()
1908
1902
  return {
1909
1903
  pool,
1910
1904
  ws: wsPath(),
1911
1905
  host: config.host,
1912
1906
  username: config.username,
1913
1907
  port: config.port,
1914
- mirrorDir: wsPath() ? mirrorDirFor(wsPath(), config.host, config.username, config.port) : null,
1908
+ mirrorOrigin,
1909
+ mirrorDir: activeMirrorDir(mirrorOrigin) || null,
1915
1910
  bound: false,
1916
1911
  // A caller that identified itself with a cwd, yet resolved to no mirror,
1917
1912
  // is definitively a LOCAL session. Distinguish it from "no caller
@@ -2050,31 +2045,34 @@ export async function apply(ctx, config) {
2050
2045
  const watcher = autoPushWatchers.get(local)
2051
2046
  return { ...observed, ...(watcher && watcher.pending.size ? { phase: 'pending' } : {}), autoPush: !!config.autoPush }
2052
2047
  }
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
- })
2048
+ const status = () => {
2049
+ const localMirror = activeMirrorDir()
2050
+ return {
2051
+ host: config.host,
2052
+ port: config.port,
2053
+ username: config.username,
2054
+ connected: !!pool.client,
2055
+ workspace: toDisplayPath(wsPath(), pool.platform),
2056
+ localMirror,
2057
+ currentId: store.currentId || null,
2058
+ sync: syncStatusFor(localMirror),
2059
+ activeSource: ephemeral ? 'ephemeral' : (store.currentId ? 'machine' : (config.host ? 'config' : 'none')),
2060
+ // Issue #13: whether THIS session is in remote mode (cwd inside a mirror).
2061
+ // `none`/`local` means the plugin is present but no remote context is
2062
+ // active — saved machines stay standby-only.
2063
+ sessionMode: sessionRemotePath() ? 'remote' : (store.currentId ? 'standby' : 'local'),
2064
+ sessionRemotePath: sessionRemotePath(),
2065
+ machines: machinesForClient(),
2066
+ hostKeyMode: config.hostKeyMode === 'verify' || config.hostKeyMode === 'off' ? config.hostKeyMode : 'accept-new',
2067
+ hostKeyKnown: config.host ? isHostKeyKnown(config.host, config.port) : false,
2068
+ forwards: forwards.list(),
2069
+ auditEnabled: !!config.auditLog,
2070
+ backend: platformBackend(),
2071
+ platform: pool.platform,
2072
+ shell: pool.shellMode,
2073
+ gitBash: pool.gitBashPath || '',
2074
+ }
2075
+ }
2078
2076
 
2079
2077
  // ── remote `@` completion (issue #39) ─────────────────────────────────────
2080
2078
  //
@@ -2421,7 +2419,7 @@ export async function apply(ctx, config) {
2421
2419
  const res = await pool.exec('echo ok', { timeoutMs: 8000 })
2422
2420
  if (res.code !== 0 && !res.stdout) {
2423
2421
  audit('connect', `connect ${effUser}@${effHost}:${effPort}`, res.code)
2424
- return { text: 'connect failed: ' + (res.stderr || 'exit ' + res.code) }
2422
+ return { text: 'connect failed: ' + connectFailureText(res, { host: effHost, timeoutMs: 8000 }) }
2425
2423
  }
2426
2424
  audit('connect', `connect ${effUser}@${effHost}:${effPort}`, 0)
2427
2425
  // The probe's identity is the DIAL one; on the system-OpenSSH backend
@@ -2538,8 +2536,8 @@ export async function apply(ctx, config) {
2538
2536
  if (!ok) return { text: `not a directory (or missing) on ${shown}` }
2539
2537
  // A bound session's workspace lives in its own mirror meta, so the
2540
2538
  // shared active-machine workspace is only updated for the unbound flow.
2539
+ const local = ensureBoundMirror(p, b)
2541
2540
  if (!b.bound) persistWorkspace(p)
2542
- const local = ensureMirror(p, b.host, b.username, b.port, { alias: b.alias || "" })
2543
2541
  startAutoPush(local)
2544
2542
  // Issue #68: discover the workspace's AGENTS.md / CLAUDE.md NOW — the
2545
2543
  // first prompt assembly can come before any rw_sync, and the mirror
@@ -2576,18 +2574,21 @@ export async function apply(ctx, config) {
2576
2574
  async execute(args, exec) {
2577
2575
  const b = requireBinding(exec, 'rw_sync')
2578
2576
  const p = b.ws
2579
- const local = b.mirrorDir || mirrorDirFor(p, b.host, b.username, b.port)
2577
+ const local = b.bound ? b.mirrorDir : ensureBoundMirror(p, b)
2578
+ assertDownloadHasNoSymlinks(local, local)
2580
2579
  mkdirSync(local, { recursive: true })
2581
2580
  const depth = Math.min(Math.max(Number(args.depth) || 8, 1), 16)
2582
2581
  const maxFiles = Math.min(Math.max(Number(args.maxFiles) || 2000, 1), 20000)
2583
2582
  const isIgnored = ignoreMatcher(p)
2584
2583
  const body = { depth, maxDepth: depth, maxFiles, dryRun: !!args.dryRun, force: !!args.force, isIgnored }
2585
- const runSync = () => syncActivity.run(local, 'download', async (record) => {
2584
+ const runSync = (taskCtx) => syncActivity.run(local, 'download', async (record) => {
2585
+ const isCancelled = () => !!taskCtx?.cancelled
2586
+ mkdirSync(local, { recursive: true })
2586
2587
  let sftp
2587
2588
  try {
2588
2589
  sftp = await b.pool.sftp()
2589
2590
  } catch (err) {
2590
- throw new Error('sftp unavailable: ' + ((err && err.message) || err))
2591
+ if (!isCancelled()) throw new Error('sftp unavailable: ' + ((err && err.message) || err))
2591
2592
  }
2592
2593
  const state = loadSyncState(local)
2593
2594
  const { stats, nextState } = await syncTree(sftp, p, local, {
@@ -2595,10 +2596,12 @@ export async function apply(ctx, config) {
2595
2596
  state,
2596
2597
  maxFileBytes: config.maxFileBytes,
2597
2598
  getSftp: () => b.pool.sftp(),
2599
+ isCancelled,
2598
2600
  })
2599
2601
  record(stats)
2600
- if (!args.dryRun) saveSyncState(local, nextState)
2602
+ if (!args.dryRun && (!stats.cancelled || stats.files)) saveSyncState(local, nextState)
2601
2603
  let text = `${args.dryRun ? 'WOULD download' : 'Downloaded'} ${stats.files} file(s) from ${p} → ${local}.`
2604
+ if (stats.cancelled) text += ' CANCELLED (started downloads were allowed to finish; re-run rw_sync to continue).'
2602
2605
  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
2606
  else if (stats.failed) text += ` ${stats.failed} failed.`
2604
2607
  if (stats.truncated || stats.files >= maxFiles) text += ` TRUNCATED (hit depth=${depth} or maxFiles=${maxFiles} cap; raise maxFiles/depth and re-run).`
@@ -2616,9 +2619,9 @@ export async function apply(ctx, config) {
2616
2619
  // Issue #68: a real sync can pull in (or obsolete) instruction files —
2617
2620
  // refresh the prompt index afterwards. Kept inside the task body so a
2618
2621
  // background sync refreshes when IT finishes, not when it is queued.
2619
- const runSyncAndIndex = async () => {
2620
- const r = await runSync()
2621
- if (!args.dryRun) {
2622
+ const runSyncAndIndex = async (taskCtx) => {
2623
+ const r = await runSync(taskCtx)
2624
+ if (!args.dryRun && !taskCtx?.cancelled) {
2622
2625
  try { await instructionIndex.refresh({ pool: b.pool, ws: p, mirrorDir: local, force: true }) } catch { /* best effort */ }
2623
2626
  }
2624
2627
  return r
@@ -2645,24 +2648,27 @@ export async function apply(ctx, config) {
2645
2648
  async execute(args, exec) {
2646
2649
  const b = requireBinding(exec, 'rw_push')
2647
2650
  const p = b.ws
2648
- const local = b.mirrorDir || mirrorDirFor(p, b.host, b.username, b.port)
2651
+ const local = b.mirrorDir || mirrorDirFor(p, b.host, b.username, b.port, b.alias)
2649
2652
  if (!existsSync(local)) throw new Error(`rw_push: local mirror does not exist — run rw_sync first (${local})`)
2650
2653
  const maxFiles = Math.min(Math.max(Number(args.maxFiles) || 2000, 1), 20000)
2651
2654
  const isIgnored = ignoreMatcher(p)
2652
2655
  const body = { maxFiles, dryRun: !!args.dryRun, force: !!args.force, isIgnored }
2653
- const runPush = () => syncActivity.run(local, 'upload', async (record) => {
2656
+ const runPush = (taskCtx) => syncActivity.run(local, 'upload', async (record) => {
2657
+ const isCancelled = () => !!taskCtx?.cancelled
2654
2658
  let sftp
2655
2659
  try {
2656
2660
  sftp = await b.pool.sftp()
2657
2661
  } catch (err) {
2658
- throw new Error('sftp unavailable: ' + ((err && err.message) || err))
2662
+ if (!isCancelled()) throw new Error('sftp unavailable: ' + ((err && err.message) || err))
2659
2663
  }
2660
2664
  const state = loadSyncState(local)
2661
2665
  try {
2662
- const { stats, nextState } = await pushTree(sftp, local, p, { ...body, state, maxFileBytes: config.maxFileBytes })
2666
+ const { stats, nextState } = await pushTree(sftp, local, p, { ...body, state, maxFileBytes: config.maxFileBytes, isCancelled })
2663
2667
  record(stats)
2664
- if (!args.dryRun) saveSyncState(local, nextState)
2668
+ if (!args.dryRun && (!stats.cancelled || stats.files)) saveSyncState(local, nextState)
2665
2669
  let text = `${args.dryRun ? 'WOULD upload' : 'Uploaded'} ${stats.files} file(s) from ${local} → ${p}.`
2670
+ if (stats.failed) text += ` ${stats.failed} failed.`
2671
+ if (stats.cancelled) text += ' CANCELLED (started uploads were allowed to finish; re-run rw_push to continue).'
2666
2672
  if (stats.truncated || stats.files >= maxFiles) text += ` TRUNCATED (hit maxFiles=${maxFiles} cap; raise maxFiles and re-run).`
2667
2673
  if (stats.skippedUnchanged) text += ` ${stats.skippedUnchanged} unchanged.`
2668
2674
  if (stats.skippedLarge) text += ` ${stats.skippedLarge} too large (over ${config.maxFileBytes} bytes).`
@@ -2952,7 +2958,7 @@ export async function apply(ctx, config) {
2952
2958
  defineTool({
2953
2959
  name: 'rw_remove',
2954
2960
  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.',
2961
+ '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
2962
  parameters: {
2957
2963
  path: { type: 'string', required: true, description: 'Absolute remote path to delete' },
2958
2964
  recursive: { type: 'boolean', description: 'Recursively delete a directory (default false)' },
@@ -2965,13 +2971,17 @@ export async function apply(ctx, config) {
2965
2971
  const p = resolveRemoteArg(b, args.path)
2966
2972
  if (!p || p === '/') throw new Error('rw_remove: a path is required')
2967
2973
  const sftp = await b.pool.sftp()
2968
- const st = await sftp.stat(p).catch(() => null)
2974
+ const st = await sftp.lstat(p).catch(error => { if (missingRemoteFile(error)) return null; throw error })
2969
2975
  if (!st) return { ok: false, text: `not found: ${p}` }
2970
- if (st.isDirectory && st.isDirectory()) {
2976
+ if (st.isDirectory?.()) {
2971
2977
  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)
2978
+ const result = await removeRemoteTree(sftp, p)
2979
+ if (result.error) {
2980
+ audit('remove', result.error, 1, b)
2981
+ return { ok: false, text: result.error }
2982
+ }
2973
2983
  audit('remove', `remove -r ${p}`, 0, b)
2974
- return { ok: true, text: `removed ${removed} entries under ${p}` }
2984
+ return { ok: true, text: `removed ${result.removed} entries under ${p}` }
2975
2985
  }
2976
2986
  await sftp.unlink(p)
2977
2987
  audit('remove', `remove ${p}`, 0, b)
@@ -3128,7 +3138,8 @@ export async function apply(ctx, config) {
3128
3138
  // `running` and cancel/steer did nothing (issue #44).
3129
3139
  const maxFiles = Math.min(Math.max(Number(args.maxEntries) || config.searchMaxEntries, 1), 500000)
3130
3140
  const maxDurationMs = Math.min(Math.max(Number(args.maxDurationMs) || config.searchTimeoutMs, 1000), 600000)
3131
- const matcher = searchIgnoreMatcher(dir)
3141
+ const ignorePatterns = searchIgnorePatterns(dir)
3142
+ const matcher = compileIgnore(ignorePatterns)
3132
3143
  const { matches, scanned, truncated, cancelled } = await searchRemote(b.pool, dir, {
3133
3144
  pattern,
3134
3145
  regex,
@@ -3141,6 +3152,9 @@ export async function apply(ctx, config) {
3141
3152
  signal: exec.signal,
3142
3153
  maxScanBytes: Math.min(config.maxFileBytes || 1024 * 1024, 1024 * 1024),
3143
3154
  isIgnored: (name, isDir) => matcher(name, isDir),
3155
+ // The raw patterns, not the compiled matcher: the POSIX fast path
3156
+ // (rg/grep) needs flags derived from the same rule list.
3157
+ ignorePatterns,
3144
3158
  timeoutMs: Math.min(config.commandTimeoutMs, maxDurationMs),
3145
3159
  })
3146
3160
  const note = cancelled
@@ -3175,7 +3189,7 @@ export async function apply(ctx, config) {
3175
3189
  const p = resolveRemoteArg(b, args.path)
3176
3190
  if (!p || p === '/') throw new Error('rw_download: a remote file path is required')
3177
3191
  const ws = b.ws
3178
- let base = b.mirrorDir || (ws ? mirrorDirFor(ws, b.host, b.username, b.port) : '')
3192
+ const base = b.mirrorDir || (ws ? mirrorDirFor(ws, b.host, b.username, b.port, b.alias) : '')
3179
3193
  if (!ws || !base) throw new Error('rw_download: no remote workspace set — downloads land inside the local mirror of the workspace')
3180
3194
  // Both destination forms resolve inside the mirror with the same
3181
3195
  // grammar-aware mapping + symlink guard the HTTP download route applies
@@ -3185,16 +3199,8 @@ export async function apply(ctx, config) {
3185
3199
  ? mirrorConstrainLocalTarget(base, String(args.localPath))
3186
3200
  : mirrorDownloadTarget(base, ws, p)
3187
3201
  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 */ }
3202
+ if (!b.bound && ensureBoundMirror(ws, b) !== base) {
3203
+ throw new Error('rw_download: local mirror changed while preparing the download — retry')
3198
3204
  }
3199
3205
  mkdirSync(path.dirname(local), { recursive: true })
3200
3206
  const sftp = await b.pool.sftp()
@@ -3236,6 +3242,103 @@ export async function apply(ctx, config) {
3236
3242
  }),
3237
3243
 
3238
3244
 
3245
+ defineTool({
3246
+ name: 'rw_dsh_install',
3247
+ description:
3248
+ 'Install (or locate) the DeepSeek Harness CLI on the remote machine, without any AI involvement. Probes `dsh` first: if it is already on PATH, reports its path and version (optionally records it as the machine\'s webAttachCommand). If missing, installs it with the package manager the remote already has: npm/pnpm global when available, otherwise the official installer script (`curl -fsSL https://… | sh` on POSIX). After a successful install the absolute dsh path is persisted as the machine\'s webAttachCommand so the remote Web UI can be opened. Read-only probe when `probeOnly: true`. Use rw_connect first so the machine is active; installation is idempotent (re-running is a no-op when dsh is already present).',
3249
+ parameters: {
3250
+ probeOnly: { type: 'boolean', description: 'Only probe whether dsh is installed (path + version); never install (default false)' },
3251
+ recordPath: { type: 'boolean', description: 'Persist the discovered/installed absolute dsh path as this machine\'s webAttachCommand (default true)' },
3252
+ },
3253
+ output: textOut,
3254
+ async execute(args, exec) {
3255
+ const b = requireBinding(exec, 'rw_dsh_install')
3256
+ const record = args.recordPath !== false
3257
+ const probeOnly = !!args.probeOnly
3258
+ // One POSIX probe, NEWLINE-joined. Joining these lines with '; ' turned
3259
+ // the loop into `for ...; do;`, a syntax error in every shell, so the
3260
+ // probe exited 2 before its first test and this tool reported "not
3261
+ // installed" on hosts that had dsh — and re-ran an installer over a
3262
+ // working install. `report` prints the absolute path + version and
3263
+ // exits; the npm/pnpm prefix fallbacks cover a global bin that is not
3264
+ // on this non-login shell's PATH (nvm, a custom prefix), which is the
3265
+ // case where `command -v dsh` alone cannot name a usable
3266
+ // webAttachCommand.
3267
+ const probeScript = [
3268
+ 'report() { echo "FOUND:$1"; "$1" --version 2>/dev/null | head -1; exit 0; }',
3269
+ 'if command -v dsh >/dev/null 2>&1; then report "$(command -v dsh)"; fi',
3270
+ 'for p in "$HOME/.dsh/bin/dsh" "$HOME/.local/bin/dsh" "/usr/local/bin/dsh" "/opt/homebrew/bin/dsh"; do',
3271
+ ' if [ -x "$p" ]; then report "$p"; fi',
3272
+ 'done',
3273
+ 'if command -v npm >/dev/null 2>&1; then',
3274
+ ' d="$(npm prefix -g 2>/dev/null)"',
3275
+ ' for p in "$d/bin/dsh" "$d/dsh"; do if [ -x "$p" ]; then report "$p"; fi; done',
3276
+ 'fi',
3277
+ 'if command -v pnpm >/dev/null 2>&1; then',
3278
+ ' d="$(pnpm bin -g 2>/dev/null)"',
3279
+ ' if [ -x "$d/dsh" ]; then report "$d/dsh"; fi',
3280
+ 'fi',
3281
+ 'exit 1',
3282
+ ].join('\n')
3283
+ /** Locate dsh: `{ path, version }` or null. Shared by the pre-install
3284
+ * probe and the post-install one, so both report the same facts. */
3285
+ const probeDsh = async () => {
3286
+ const probe = await b.pool.exec(probeScript, { timeoutMs: Math.min(config.commandTimeoutMs, 15000) })
3287
+ const found = /^FOUND:(.+)$/m.exec(String(probe.stdout || ''))
3288
+ if (probe.code !== 0 || !found) return null
3289
+ const version = String(probe.stdout || '').split('\n')
3290
+ .map((line) => line.trim())
3291
+ .filter((line) => line && !line.startsWith('FOUND:'))
3292
+ .pop() || 'unknown'
3293
+ return { path: found[1].trim(), version }
3294
+ }
3295
+ /** Persist on the machine THIS SESSION is bound to, never the active
3296
+ * one: with two saved machines, store.currentId can point at B while
3297
+ * the session (and the pool we just ran on) belongs to A. */
3298
+ const recordOnSessionMachine = (pathFound) => {
3299
+ const machine = record ? machineRecordFor(b) : null
3300
+ return !!machine && persistWebAttachCommand(machine, pathFound)
3301
+ }
3302
+
3303
+ const located = await probeDsh()
3304
+ if (located) {
3305
+ const recorded = recordOnSessionMachine(located.path)
3306
+ return { text: `dsh is already installed: ${located.path} (version ${located.version}).${recorded ? ' Recorded as this machine\'s webAttachCommand.' : ''}` }
3307
+ }
3308
+ if (probeOnly) return { text: 'dsh is NOT installed on this remote (not on PATH and no common install location found). Run rw_dsh_install without probeOnly to install it.' }
3309
+
3310
+ // Choose the install path by what the remote already has. Each command
3311
+ // INSTALLS only: appending `&& dsh --version` made a successful install
3312
+ // report failure whenever the fresh global bin was not on PATH yet.
3313
+ const pm = await b.pool.exec('command -v npm; command -v pnpm; command -v node; command -v curl; command -v wget', { timeoutMs: Math.min(config.commandTimeoutMs, 15000) })
3314
+ const hasNpm = /\/npm\b/.test(pm.stdout), hasPnpm = /\/pnpm\b/.test(pm.stdout), hasNode = /\/node\b/.test(pm.stdout), hasCurl = /\/curl\b/.test(pm.stdout), hasWget = /\/wget\b/.test(pm.stdout)
3315
+ let installScript
3316
+ if (hasNpm) {
3317
+ installScript = 'npm install -g @deepseek-ai/dsh'
3318
+ } else if (hasPnpm) {
3319
+ installScript = 'pnpm add -g @deepseek-ai/dsh'
3320
+ } else if (hasNode && (hasCurl || hasWget)) {
3321
+ const fetcher = hasCurl ? 'curl -fsSL' : 'wget -qO-'
3322
+ installScript = `${fetcher} https://get.dsh.dev/install.sh | sh`
3323
+ } else {
3324
+ throw new Error('rw_dsh_install: no npm, pnpm, or node+curl/wget on the remote — install Node.js first (or use your package manager to install @deepseek-ai/dsh)')
3325
+ }
3326
+ const install = await b.pool.exec(installScript, { timeoutMs: Math.min(config.commandTimeoutMs || 120000, 120000) })
3327
+ if (install.code !== 0) {
3328
+ throw new Error(`rw_dsh_install failed (exit ${install.code}): ${String(install.stderr || install.stdout || '').trim().slice(0, 400)}`)
3329
+ }
3330
+ // Re-probe instead of trusting the installer's own output: the absolute
3331
+ // path is what webAttachCommand must carry, and a fresh global bin is
3332
+ // often outside this shell's PATH.
3333
+ const installed = await probeDsh()
3334
+ if (!installed) {
3335
+ return { text: `dsh was installed (${installScript}) but no binary could be located afterwards — it is probably outside this shell's PATH. Add npm/pnpm's global bin to the remote PATH, then run rw_dsh_install with probeOnly: true to record it.` }
3336
+ }
3337
+ const recorded = recordOnSessionMachine(installed.path)
3338
+ return { text: `dsh installed successfully: ${installed.path} (version ${installed.version}).${recorded ? ' Recorded as this machine\'s webAttachCommand — you can now open the remote Web UI.' : ''}` }
3339
+ },
3340
+ }),
3341
+
3239
3342
  defineTool({
3240
3343
  name: 'rw_forward',
3241
3344
  description:
@@ -4213,6 +4316,7 @@ export async function apply(ctx, config) {
4213
4316
  port: t.aliasNative ? 22 : (Number(eff.port) || 22),
4214
4317
  username: t.aliasNative ? '' : String(eff.username || ''),
4215
4318
  alias: aliasOf(eff),
4319
+ mirrorOrigin: mirrorOrigin(eff),
4216
4320
  }
4217
4321
  }
4218
4322
  const rec = store.currentId && machineIndex(store.currentId) >= 0 ? machines[machineIndex(store.currentId)] : null
@@ -4229,6 +4333,7 @@ export async function apply(ctx, config) {
4229
4333
  port: t.aliasNative ? 22 : (Number(m.port) || 22),
4230
4334
  username: t.aliasNative ? '' : String(m.username || ''),
4231
4335
  alias: aliasOf(m),
4336
+ mirrorOrigin: mirrorOrigin(m),
4232
4337
  }
4233
4338
  }
4234
4339
 
@@ -4440,81 +4545,22 @@ export async function apply(ctx, config) {
4440
4545
  handler: async (req, res) => {
4441
4546
  if (req.method !== 'GET') return sendJson(res, 405, { error: 'method not allowed' })
4442
4547
  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')) : ''
4548
+ let { local, sessionId } = requestSessionHint(req)
4446
4549
  let resolvedVia = 'query'
4447
4550
  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 */ }
4551
+ local = lookupSessionCwd(sessionId, { sessions: sessionsSvc() })
4552
+ if (local) resolvedVia = 'session'
4553
+ else {
4554
+ local = lookupSessionCwd(sessionId, { dshHome: dshBase() })
4555
+ if (local) resolvedVia = 'session-log'
4482
4556
  }
4483
4557
  }
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 || ''
4558
+ const { remotePath, mirrorDir } = resolveMirrorForLocal(local)
4559
+ // Issue #13: sessions without a mirror never fall back to the active machine.
4512
4560
  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',
4561
+ local, remotePath, mirrorDir,
4562
+ fallback: !remotePath,
4563
+ mode: remotePath ? 'remote' : 'local',
4518
4564
  resolvedVia,
4519
4565
  })
4520
4566
  } catch (err) {
@@ -4546,13 +4592,13 @@ export async function apply(ctx, config) {
4546
4592
  // Mirror/connection surface (extracted for issue #82).
4547
4593
  ...createWorkspaceRoutes({
4548
4594
  sendJson, readBody, parseJsonObject, config, pool, backendFor, status, isRemoteDir, persistWorkspace, ensureMirror,
4549
- aliasOf, activeMachine, startAutoPush, applyRequestedMachine, registerMirroredWorkspace, localPickCapability,
4595
+ aliasOf, activeMachine, activeMirrorOrigin, startAutoPush, applyRequestedMachine, registerMirroredWorkspace, localPickCapability,
4550
4596
  pickLocalNative, listLocalDrives, probeMachineRecord, setCurrent, knownHostsFile, prepareMirrorTarget, machineForId: (id) => machines.find((m) => m.id === id),
4551
4597
  }),
4552
4598
  ...createSearchRoutes({ searches: workspaceSearches, sendJson, readBody, resolveRequestBinding: resolveWorkbenchBinding, isIgnoredFor: searchIgnoreMatcher }),
4553
4599
  ...createGitRoutes({ sendJson, resolveRequestBinding: resolveWorkbenchBinding, decodeBuf, config }),
4554
4600
  ...createFsRoutes({
4555
- sendJson, readBody, resolveRequestBinding: resolveWorkbenchBinding, decodeBuf, encodeText, audit, config, mirrorDirFor,
4601
+ sendJson, readBody, resolveRequestBinding: resolveWorkbenchBinding, decodeBuf, encodeText, audit, config, mirrorDirFor, ensureBoundMirror,
4556
4602
  onRemoteMutation: () => { if (remoteSkills) remoteSkills.invalidate() },
4557
4603
  openLocalPath, mirrorRoot: remoteWorkspacesRoot,
4558
4604
  }),
@@ -4698,7 +4744,10 @@ export async function apply(ctx, config) {
4698
4744
  resolveDirBinding: listDirBindingForApi,
4699
4745
  listRemoteProjects: listRemoteProjectsForApi,
4700
4746
  revealMirrorFolderRecord: revealMirrorFolderForApi,
4701
- resolveMachine: resolveMachineForApi,
4747
+ resolveMachine: (id) => {
4748
+ const machine = resolveMachineForApi(id)
4749
+ return { ...machine, ...machine.mirrorOrigin }
4750
+ },
4702
4751
  ensureMirror,
4703
4752
  registerMirroredWorkspace,
4704
4753
  checkRemoteDir: checkRemoteDirForApi,
@@ -4707,6 +4756,7 @@ export async function apply(ctx, config) {
4707
4756
  workspaceRegistry: () => (ctx && typeof ctx.get === 'function' ? ctx.get('workspaceRegistry') : undefined),
4708
4757
  forgetRemotePath,
4709
4758
  isSessionLive,
4759
+ listLiveWorkspaceSessions,
4710
4760
  })
4711
4761
  // cordis 4: `ctx.provide(name, value)` is the raw service registry (the
4712
4762
  // `Service` base class is only sugar around it). Guarded because a minimal