dsh-linked-workspace 0.13.0 → 0.14.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/index.js CHANGED
@@ -1545,7 +1545,7 @@ export function apply(ctx) {
1545
1545
  }
1546
1546
 
1547
1547
  /** Copy one local file/folder of a linked workspace to the same relative remote path. */
1548
- const transferLocalToRemote = async (record, remote, rawPath) => {
1548
+ const transferLocalToRemote = async (record, remote, rawPath, job = null) => {
1549
1549
  const localRoot = resolve(record.localPath)
1550
1550
  const source = resolve(String(rawPath || ''))
1551
1551
  if (source !== localRoot && !source.startsWith(localRoot + sep) && !source.startsWith(localRoot + '/')) {
@@ -1557,6 +1557,7 @@ export function apply(ctx) {
1557
1557
  const target = posix.join(record.remotePath, relative)
1558
1558
  const limits = { files: 0, bytes: 0, skipped: 0, truncated: false }
1559
1559
  const visit = async (localPath, remotePath, depth) => {
1560
+ assertTransferAlive(job)
1560
1561
  if (depth > CONTEXT_TREE_LIMITS.maxDepth || limits.files >= CONTEXT_TREE_LIMITS.maxFiles || limits.bytes >= CONTEXT_TREE_LIMITS.maxBytes) {
1561
1562
  limits.truncated = true
1562
1563
  return
@@ -1595,17 +1596,19 @@ export function apply(ctx) {
1595
1596
  await withTimeout(remote.writeFileAtomic(remotePath, data), LINKED_SYNC_TIMEOUT_MS, `transfer ${relative}`)
1596
1597
  limits.files += 1
1597
1598
  limits.bytes += data.length
1599
+ countTransferred(job, data.length)
1598
1600
  }
1599
1601
  await visit(source, target, 0)
1600
1602
  return { side: 'local', files: limits.files, bytes: limits.bytes, skipped: limits.skipped, truncated: limits.truncated, target }
1601
1603
  }
1602
1604
 
1603
1605
  /** Explicit SFTP transfer of one remote file/folder into <local>/.remote. */
1604
- const transferToMirror = async (record, remote, target) => {
1606
+ const transferToMirror = async (record, remote, target, job = null) => {
1605
1607
  const relative = linkedRelative(record, target)
1606
1608
  if (relative === '') throw new ApiError('BAD_REQUEST', '不能传输联动工作区根目录')
1607
1609
  const limits = { files: 0, bytes: 0, skipped: 0, truncated: false }
1608
1610
  const visit = async (remotePath, rel, depth) => {
1611
+ assertTransferAlive(job)
1609
1612
  if (depth > CONTEXT_TREE_LIMITS.maxDepth || limits.files >= CONTEXT_TREE_LIMITS.maxFiles || limits.bytes >= CONTEXT_TREE_LIMITS.maxBytes) {
1610
1613
  limits.truncated = true
1611
1614
  return
@@ -1631,6 +1634,7 @@ export function apply(ctx) {
1631
1634
  await linkedFs.writeMirrorFile(record.localPath, rel, read.data)
1632
1635
  limits.files += 1
1633
1636
  limits.bytes += read.data.length
1637
+ countTransferred(job, read.data.length)
1634
1638
  }
1635
1639
  const stat = await remote.stat(target)
1636
1640
  if (stat.type !== 'dir') {
@@ -1643,6 +1647,46 @@ export function apply(ctx) {
1643
1647
  return { ...limits, dest: join(record.localPath, linkedFs.MIRROR_DIR, relative) }
1644
1648
  }
1645
1649
 
1650
+ // ── transfer progress ──────────────────────────────────────────────────
1651
+ //
1652
+ // A transfer is a sequence of whole-file requests, so progress is "how many
1653
+ // files and bytes landed so far" rather than a percentage: the Host never
1654
+ // walks the tree twice. Cancellation is cooperative — the flag is checked
1655
+ // between files, so a cancel never leaves a half-written file behind.
1656
+
1657
+ const TRANSFER_JOB_TTL_MS = 5 * 60 * 1000
1658
+ const transferJobs = new Map()
1659
+
1660
+ const beginTransferJob = (id) => {
1661
+ if (typeof id !== 'string' || id.trim() === '') return null
1662
+ const now = Date.now()
1663
+ for (const [key, value] of transferJobs) {
1664
+ if (now - value.updatedAt > TRANSFER_JOB_TTL_MS) transferJobs.delete(key)
1665
+ }
1666
+ const job = { id, files: 0, bytes: 0, skipped: 0, state: 'running', cancelled: false, reason: '', updatedAt: now }
1667
+ transferJobs.set(id, job)
1668
+ return job
1669
+ }
1670
+
1671
+ const finishTransferJob = (job, state, reason = '') => {
1672
+ if (!job) return
1673
+ job.state = state
1674
+ job.reason = reason
1675
+ job.updatedAt = Date.now()
1676
+ }
1677
+
1678
+ /** Throw when the client asked the running transfer to stop. */
1679
+ const assertTransferAlive = (job) => {
1680
+ if (job && job.cancelled) throw new ApiError('CANCELLED', '传输已取消')
1681
+ }
1682
+
1683
+ const countTransferred = (job, size) => {
1684
+ if (!job) return
1685
+ job.files += 1
1686
+ job.bytes += size
1687
+ job.updatedAt = Date.now()
1688
+ }
1689
+
1646
1690
  /** Download one remote file/folder into the OS Downloads folder. */
1647
1691
  const downloadRemotePath = async (remote, target, destDir) => {
1648
1692
  await mkdir(destDir, { recursive: true })
@@ -1890,24 +1934,70 @@ export function apply(ctx) {
1890
1934
  const GREP_MAX_FILES = 2000
1891
1935
  const GREP_MAX_BYTES = 8 * 1024 * 1024
1892
1936
  const GREP_DEADLINE_MS = 5000
1937
+ const GREP_PREVIEW_CHARS = 120
1938
+ const GREP_MAX_QUERY = 200
1939
+
1940
+ // Dependency trees and build output make a content search useless: they
1941
+ // dwarf the project and always win the result budget. Both sides skip them.
1942
+ const GREP_EXCLUDED_DIRS = [
1943
+ '.git', '.hg', '.svn', 'node_modules', '.local', '.remote', '__pycache__',
1944
+ '.conda', 'conda-meta', '.venv', 'venv', 'site-packages', 'dist', 'build',
1945
+ 'target', '.next', '.nuxt', '.cache', '.mypy_cache', '.pytest_cache',
1946
+ '.ipynb_checkpoints', '.gradle', '.idea', '.vscode',
1947
+ ]
1893
1948
 
1894
1949
  function grepDirectoryExcluded(name) {
1895
- return LINKED_SYNC_EXCLUDES.has(name) || name === '.local' || name === '.remote'
1950
+ return LINKED_SYNC_EXCLUDES.has(name) || GREP_EXCLUDED_DIRS.indexOf(name) !== -1
1951
+ }
1952
+
1953
+ /** Compile the query once: a plain substring match or a regular expression. */
1954
+ function compileSearch(query, options) {
1955
+ const ignoreCase = Boolean(options && options.ignoreCase)
1956
+ if (options && options.regex) {
1957
+ let expression
1958
+ try {
1959
+ expression = new RegExp(query, ignoreCase ? 'i' : '')
1960
+ } catch (error) {
1961
+ throw new ApiError('BAD_REQUEST', `正则表达式无效:${error.message}`)
1962
+ }
1963
+ return {
1964
+ test: (text) => expression.test(text),
1965
+ lineTest: (line) => expression.test(line),
1966
+ }
1967
+ }
1968
+ const needle = ignoreCase ? query.toLowerCase() : query
1969
+ return {
1970
+ test: (text) => (ignoreCase ? text.toLowerCase() : text).includes(needle),
1971
+ lineTest: (line) => (ignoreCase ? line.toLowerCase() : line).includes(needle),
1972
+ }
1896
1973
  }
1897
1974
 
1898
- function contentSearchLocal(root, query, maxResults) {
1899
- const needle = Buffer.from(query, 'utf8')
1975
+ /** First line (1-based) that matches, plus a trimmed preview of it. */
1976
+ function firstMatchLine(text, matcher) {
1977
+ const lines = text.split('\n')
1978
+ for (let index = 0; index < lines.length; index += 1) {
1979
+ if (matcher.lineTest(lines[index])) {
1980
+ return { line: index + 1, preview: lines[index].replace(/\s+/g, ' ').trim().slice(0, GREP_PREVIEW_CHARS) }
1981
+ }
1982
+ }
1983
+ return { line: 0, preview: '' }
1984
+ }
1985
+
1986
+ function contentSearchLocal(root, query, maxResults, options = {}) {
1987
+ const matcher = compileSearch(query, options)
1900
1988
  const entries = []
1901
1989
  const started = Date.now()
1902
1990
  let files = 0
1903
1991
  let bytes = 0
1904
- let truncated = false
1992
+ let truncatedReason = ''
1993
+ const stop = (reason) => {
1994
+ if (truncatedReason === '') truncatedReason = reason
1995
+ }
1905
1996
  const visit = (directory, prefix) => {
1906
- if (truncated) return
1907
- if (files >= GREP_MAX_FILES || bytes >= GREP_MAX_BYTES || Date.now() - started > GREP_DEADLINE_MS) {
1908
- truncated = true
1909
- return
1910
- }
1997
+ if (truncatedReason !== '') return
1998
+ if (files >= GREP_MAX_FILES) return stop('files')
1999
+ if (bytes >= GREP_MAX_BYTES) return stop('bytes')
2000
+ if (Date.now() - started > GREP_DEADLINE_MS) return stop('deadline')
1911
2001
  let listing
1912
2002
  try {
1913
2003
  listing = readdirSync(directory, { withFileTypes: true })
@@ -1915,7 +2005,7 @@ export function apply(ctx) {
1915
2005
  return
1916
2006
  }
1917
2007
  for (const entry of listing) {
1918
- if (truncated) return
2008
+ if (truncatedReason !== '') return
1919
2009
  if (grepDirectoryExcluded(entry.name)) continue
1920
2010
  const absolute = join(directory, entry.name)
1921
2011
  const relative = prefix === '' ? entry.name : `${prefix}/${entry.name}`
@@ -1924,51 +2014,98 @@ export function apply(ctx) {
1924
2014
  continue
1925
2015
  }
1926
2016
  if (!entry.isFile()) continue
1927
- if (files >= GREP_MAX_FILES || bytes >= GREP_MAX_BYTES || Date.now() - started > GREP_DEADLINE_MS) {
1928
- truncated = true
1929
- return
1930
- }
2017
+ if (files >= GREP_MAX_FILES) return stop('files')
2018
+ if (bytes >= GREP_MAX_BYTES) return stop('bytes')
2019
+ if (Date.now() - started > GREP_DEADLINE_MS) return stop('deadline')
1931
2020
  files += 1
2021
+ // Skip oversized files before reading them: pulling a 2 GB blob into
2022
+ // memory to answer a text query would stall the whole Host.
2023
+ try {
2024
+ if (statSync(absolute).size > GREP_MAX_FILE_BYTES) continue
2025
+ } catch {
2026
+ continue
2027
+ }
1932
2028
  let data
1933
2029
  try {
1934
2030
  data = readFileSync(absolute)
1935
2031
  } catch {
1936
2032
  continue
1937
2033
  }
1938
- if (data.length > GREP_MAX_FILE_BYTES) continue
1939
2034
  bytes += data.length
1940
2035
  if (data.includes(0)) continue
1941
- if (data.indexOf(needle) === -1) continue
1942
- if (entries.length >= maxResults) {
1943
- truncated = true
1944
- return
1945
- }
1946
- entries.push({ path: absolute, relative, size: data.length })
2036
+ const text = data.toString('utf8')
2037
+ if (!matcher.test(text)) continue
2038
+ if (entries.length >= maxResults) return stop('results')
2039
+ const hit = firstMatchLine(text, matcher)
2040
+ entries.push({ path: absolute, relative, size: data.length, line: hit.line, preview: hit.preview })
1947
2041
  }
1948
2042
  }
1949
2043
  visit(resolve(root), '')
1950
- return { ok: true, query, entries, truncated }
2044
+ return { ok: true, query, entries, truncated: truncatedReason !== '', truncatedReason }
1951
2045
  }
1952
2046
 
1953
- async function contentSearchRemote(remote, root, query, maxResults) {
1954
- const command = 'grep -rIl --binary-files=without-match'
1955
- + ' --exclude-dir=.git --exclude-dir=node_modules --exclude-dir=.local'
1956
- + ' --exclude-dir=.remote --exclude-dir=__pycache__'
1957
- + ` -e ${shellQuoteArg(query)} -- ${shellQuoteArg(root)} 2>/dev/null`
1958
- + ` | head -n ${maxResults + 1}`
1959
- const result = await remote.exec(command, { timeoutMs: 20000 })
1960
- if (result.code !== 0 && result.stdout.trim() === '') {
2047
+ async function contentSearchRemote(remote, root, query, maxResults, options = {}) {
2048
+ const ignoreCase = Boolean(options.ignoreCase)
2049
+ const useRegex = Boolean(options.regex)
2050
+ if (useRegex) {
2051
+ try {
2052
+ // Validate here so a bad pattern is reported as a user error instead of
2053
+ // surfacing as an opaque grep exit code 2.
2054
+ new RegExp(query)
2055
+ } catch (error) {
2056
+ throw new ApiError('BAD_REQUEST', `正则表达式无效:${error.message}`)
2057
+ }
2058
+ }
2059
+ let searchRoot = root
2060
+ const subPath = typeof options.path === 'string' ? options.path.trim() : ''
2061
+ if (subPath !== '') {
2062
+ const normalized = posix.normalize(subPath).replace(/^\/+/, '')
2063
+ if (normalized === '..' || normalized.startsWith('../')) throw new ApiError('BAD_REQUEST', '搜索路径超出工作区范围')
2064
+ searchRoot = normalized === '' ? root : posix.join(root, normalized)
2065
+ }
2066
+ const excludes = GREP_EXCLUDED_DIRS.map((dir) => `--exclude-dir=${shellQuoteArg(dir)}`).join(' ')
2067
+ const pattern = useRegex ? `-E ${shellQuoteArg(query)}` : `-e ${shellQuoteArg(query)}`
2068
+ const command = `grep -rIn${ignoreCase ? 'i' : ''} --binary-files=without-match ${excludes} ${pattern}`
2069
+ + ` -- ${shellQuoteArg(searchRoot)} 2>/dev/null | head -n ${maxResults + 1}`
2070
+ let result
2071
+ try {
2072
+ result = await remote.exec(command, { timeoutMs: 20000 })
2073
+ } catch (error) {
2074
+ // A timeout means "we looked, but not everywhere": report it as a
2075
+ // truncated result instead of failing the whole search.
2076
+ return { ok: true, query, entries: [], truncated: true, truncatedReason: 'deadline' }
2077
+ }
2078
+ if (result.code !== 0 && String(result.stdout || '').trim() === '') {
1961
2079
  // grep exits 1 when nothing matched; a real failure has code > 1.
1962
- if (result.code > 1) throw new ApiError('INTERNAL', `内容搜索失败:${String(result.stderr || '').trim().slice(0, 200)}`)
1963
- return { ok: true, query, entries: [], truncated: false }
1964
- }
1965
- const lines = String(result.stdout || '').split('\n').map((line) => line.trim()).filter((line) => line !== '')
1966
- const truncated = lines.length > maxResults
1967
- const entries = lines.slice(0, maxResults).map((line) => {
1968
- const relative = line.startsWith(`${root}/`) ? line.slice(root.length + 1) : line
1969
- return { path: line, relative, size: null }
1970
- })
1971
- return { ok: true, query, entries, truncated }
2080
+ if (result.code > 1) {
2081
+ const detail = String(result.stderr || '').trim().slice(0, 200)
2082
+ if (result.code === 2 && /invalid/i.test(detail)) throw new ApiError('BAD_REQUEST', `正则表达式无效:${detail}`)
2083
+ throw new ApiError('INTERNAL', `内容搜索失败:${detail}`)
2084
+ }
2085
+ return { ok: true, query, entries: [], truncated: false, truncatedReason: '' }
2086
+ }
2087
+ const lines = String(result.stdout || '').split('\n').filter((line) => line.trim() !== '')
2088
+ const entries = []
2089
+ let truncatedReason = ''
2090
+ for (const raw of lines) {
2091
+ if (entries.length >= maxResults) {
2092
+ truncatedReason = 'results'
2093
+ break
2094
+ }
2095
+ const match = /^(.*?):(\d+):(.*)$/.exec(raw)
2096
+ if (!match) continue
2097
+ const file = match[1]
2098
+ const relative = file.startsWith(`${searchRoot}/`) ? file.slice(searchRoot.length + 1) : file
2099
+ entries.push({
2100
+ path: file,
2101
+ relative,
2102
+ size: null,
2103
+ line: Number(match[2]),
2104
+ preview: match[3].replace(/\s+/g, ' ').trim().slice(0, GREP_PREVIEW_CHARS),
2105
+ })
2106
+ }
2107
+ if (truncatedReason === '' && lines.length > maxResults) truncatedReason = 'results'
2108
+ return { ok: true, query, entries, truncated: truncatedReason !== '', truncatedReason }
1972
2109
  }
1973
2110
 
1974
2111
  // ── method table ─────────────────────────────────────────────────────────
@@ -2054,6 +2191,24 @@ export function apply(ctx) {
2054
2191
  }
2055
2192
  },
2056
2193
 
2194
+ async 'hosts.mkdir'(params = {}) {
2195
+ const host = await findHost(params.hostId)
2196
+ const remote = await connectHost(host)
2197
+ const rawParent = typeof params.path === 'string' && params.path.trim() !== ''
2198
+ ? params.path
2199
+ : await remote.homeDir()
2200
+ const parent = await normalizeRemotePath(remote, rawParent)
2201
+ const name = typeof params.name === 'string' ? params.name.trim() : ''
2202
+ if (name === '' || name === '.' || name === '..' || /[/\\\u0000]/.test(name)) {
2203
+ throw new ApiError('BAD_REQUEST', '文件夹名称无效')
2204
+ }
2205
+ const target = posix.join(parent, name)
2206
+ const existing = await remote.stat(target).catch(() => null)
2207
+ if (existing) throw new ApiError('FS_EXISTS', `远程目录已存在: ${target}`)
2208
+ await remote.mkdirp(target)
2209
+ return { path: target }
2210
+ },
2211
+
2057
2212
  async 'fs.list'(params = {}) {
2058
2213
  const scope = await requireScope(params)
2059
2214
  const target = params.path === undefined || params.path === ''
@@ -2397,13 +2552,50 @@ export function apply(ctx) {
2397
2552
  async 'fs.transfer'(params = {}) {
2398
2553
  const scope = await requireScope(params)
2399
2554
  if (scope.kind !== 'linked') throw new ApiError('BAD_REQUEST', '只有联动工作区支持文件传输')
2400
- if (params.side === 'local') {
2401
- const result = await transferLocalToRemote(scope.record, scope.remote, params.path)
2402
- forgetListings()
2555
+ const job = beginTransferJob(params.jobId)
2556
+ try {
2557
+ if (params.side === 'local') {
2558
+ const result = await transferLocalToRemote(scope.record, scope.remote, params.path, job)
2559
+ forgetListings()
2560
+ finishTransferJob(job, 'done')
2561
+ return result
2562
+ }
2563
+ const target = scopeTarget(scope, params.path)
2564
+ const result = await transferToMirror(scope.record, scope.remote, target, job)
2565
+ finishTransferJob(job, 'done')
2403
2566
  return result
2567
+ } catch (error) {
2568
+ finishTransferJob(job, error && error.code === 'CANCELLED' ? 'cancelled' : 'failed', error && error.message ? error.message : '')
2569
+ throw error
2570
+ }
2571
+ },
2572
+
2573
+ /** Progress of a transfer that was started with a jobId. */
2574
+ async 'fs.transferProgress'(params = {}) {
2575
+ const id = typeof params.jobId === 'string' ? params.jobId : ''
2576
+ const job = transferJobs.get(id) || null
2577
+ if (job === null) return { job: null }
2578
+ return {
2579
+ job: {
2580
+ id: job.id,
2581
+ files: job.files,
2582
+ bytes: job.bytes,
2583
+ skipped: job.skipped,
2584
+ state: job.state,
2585
+ cancelled: job.cancelled,
2586
+ reason: job.reason,
2587
+ },
2404
2588
  }
2405
- const target = scopeTarget(scope, params.path)
2406
- return await transferToMirror(scope.record, scope.remote, target)
2589
+ },
2590
+
2591
+ /** Ask a running transfer to stop after the file it is writing. */
2592
+ async 'fs.transferCancel'(params = {}) {
2593
+ const id = typeof params.jobId === 'string' ? params.jobId : ''
2594
+ const job = transferJobs.get(id)
2595
+ if (!job) return { cancelled: false }
2596
+ job.cancelled = true
2597
+ job.updatedAt = Date.now()
2598
+ return { cancelled: true }
2407
2599
  },
2408
2600
 
2409
2601
  async 'fs.download'(params = {}) {
@@ -2923,11 +3115,17 @@ export function apply(ctx) {
2923
3115
  const scope = await requireScope(params)
2924
3116
  const query = typeof params.query === 'string' ? params.query.trim() : ''
2925
3117
  const maxResults = Math.min(Math.max(Number(params.maxResults) || 200, 1), 1000)
2926
- if (query === '') return { ok: true, query: '', entries: [], truncated: false }
3118
+ if (query === '') return { ok: true, query: '', entries: [], truncated: false, truncatedReason: '' }
3119
+ if (query.length > GREP_MAX_QUERY) throw new ApiError('BAD_REQUEST', `搜索词过长(最多 ${GREP_MAX_QUERY} 个字符)`)
2927
3120
  const side = params.side === 'local' ? 'local' : 'remote'
2928
- if (side === 'remote') return await contentSearchRemote(scope.remote, scope.root, query, maxResults)
3121
+ const options = {
3122
+ path: typeof params.path === 'string' ? params.path : '',
3123
+ ignoreCase: params.ignoreCase !== false,
3124
+ regex: Boolean(params.regex),
3125
+ }
3126
+ if (side === 'remote') return await contentSearchRemote(scope.remote, scope.root, query, maxResults, options)
2929
3127
  if (scope.kind !== 'linked') throw new ApiError('BAD_REQUEST', '只有联动工作区有本地目录')
2930
- return contentSearchLocal(scope.record.localPath, query, maxResults)
3128
+ return contentSearchLocal(scope.record.localPath, query, maxResults, options)
2931
3129
  },
2932
3130
 
2933
3131
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-linked-workspace",
3
- "version": "0.13.0",
3
+ "version": "0.14.0",
4
4
  "description": "Linked local ⇄ remote workspaces and remote workspaces for DeepSeek Harness: theme-aware split editor, file-type icons, and agent tools that edit remote files directly.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",