dsh-remote 1.0.1 → 1.1.2

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.
@@ -0,0 +1,57 @@
1
+ // Bounded, presentation-only facts about successful remote mutations.
2
+ import { structuredPatch } from './vendor/jsdiff/patch/create.js'
3
+
4
+ export const CHANGE_CAPTURE_BYTES = 64 * 1024
5
+ const MAX_LINES = 4000
6
+ const MAX_DIFF_CHARS = 24000
7
+
8
+ export function fileChange(path, operation, before, after) {
9
+ const base = { kind: 'dsh-remote.change', version: 1, path, operation, applied: true, diffs: [], additions: 0, deletions: 0, truncated: false, unchanged: false }
10
+ if (before === undefined) return { ...base, truncated: true, reason: 'baseline-unavailable' }
11
+ const oldText = before === null ? '' : before
12
+ if (Buffer.byteLength(oldText) + Buffer.byteLength(after) > CHANGE_CAPTURE_BYTES * 2 || oldText.split('\n').length + after.split('\n').length > MAX_LINES) return { ...base, truncated: true, reason: 'too-large' }
13
+ if (oldText.includes('\0') || after.includes('\0')) return { ...base, truncated: true, reason: 'binary' }
14
+ if (oldText === after) return { ...base, unchanged: true }
15
+ const patch = structuredPatch('', '', oldText, after, undefined, undefined, { context: 3, timeout: 60, maxEditLength: 3000 })
16
+ if (!patch) return { ...base, truncated: true, reason: 'too-large' }
17
+ let length = 0
18
+ for (const hunk of patch.hunks) {
19
+ const oldLines = [], newLines = []
20
+ for (const line of hunk.lines) {
21
+ if (line[0] === '\\') continue
22
+ if (line[0] === '-') { oldLines.push(line.slice(1)); base.deletions++ }
23
+ else if (line[0] === '+') { newLines.push(line.slice(1)); base.additions++ }
24
+ else { oldLines.push(line.slice(1)); newLines.push(line.slice(1)) }
25
+ }
26
+ const oldPart = oldLines.length ? oldLines.join('\n') : null
27
+ const newPart = newLines.join('\n')
28
+ if (length + (oldPart?.length || 0) + newPart.length > MAX_DIFF_CHARS || base.diffs.length >= 30) {
29
+ base.truncated = true; base.reason = 'too-large'; break
30
+ }
31
+ base.diffs.push({ path, oldText: oldPart, newText: newPart })
32
+ length += (oldPart?.length || 0) + newPart.length
33
+ }
34
+ return base
35
+ }
36
+
37
+ export function presentFileChange(_args, result) {
38
+ const meta = result?.meta
39
+ if (result?.isError || meta?.kind !== 'dsh-remote.change' || meta.applied !== true || !Array.isArray(meta.diffs) || !meta.diffs.length) return undefined
40
+ if (!meta.diffs.every(d => d && typeof d.path === 'string' && (d.oldText === null || typeof d.oldText === 'string') && typeof d.newText === 'string')) return undefined
41
+ return { card: 'diff', title: meta.path, diffs: meta.diffs }
42
+ }
43
+
44
+ export const changeOutput = {
45
+ schema: { type: 'object', additionalProperties: false, properties: {
46
+ ok: { type: 'boolean', required: true }, bytes: { type: 'integer' }, text: { type: 'string' },
47
+ change: { type: 'object', required: true, additionalProperties: false, properties: {
48
+ kind: { type: 'string', required: true }, version: { type: 'integer', required: true }, path: { type: 'string', required: true }, operation: { type: 'string', required: true }, applied: { type: 'boolean', required: true },
49
+ additions: { type: 'integer', required: true }, deletions: { type: 'integer', required: true }, truncated: { type: 'boolean', required: true }, unchanged: { type: 'boolean', required: true }, reason: { type: 'string' },
50
+ diffs: { type: 'array', required: true, items: { type: 'object', additionalProperties: false, properties: {
51
+ path: { type: 'string', required: true }, oldText: { oneOf: [{ type: 'string' }, { type: 'null' }], required: true }, newText: { type: 'string', required: true },
52
+ } } },
53
+ } },
54
+ } },
55
+ render: (_args, value) => [{ type: 'text', text: value.text || (value.ok ? 'ok' : 'failed') }],
56
+ presentationMeta: (_args, value) => value.change,
57
+ }
package/lib/index.js CHANGED
@@ -18,6 +18,11 @@
18
18
  // REMOTE workspace presented as such to the model and UI.
19
19
  //
20
20
  // Plugin Config MUST be a schemastery schema (zod rejects the undefined row config).
21
+ import { WorkspaceSearches, createSearchRoutes } from './workspace-search.js'
22
+ import { createGitRoutes } from './remote-git.js'
23
+ import { LOCAL_MUTATION_TOOLS, remoteLocalMutationDecision } from './local-mutation.js'
24
+ import { fileChange, changeOutput, presentFileChange } from './file-changes.js'
25
+ import { captureRemoteFile, atomicRemoteWrite } from './remote-write.js'
21
26
  import z from '@deepseek-ai/schemastery'
22
27
  import { createAutoUpdater } from './auto-update.js'
23
28
  import { defineTool } from '@deepseek-ai/dsh-tools'
@@ -1236,6 +1241,8 @@ export async function apply(ctx, config) {
1236
1241
 
1237
1242
  // ── task + forward managers ───────────────────────────────────────────────
1238
1243
  const tasks = new TaskManager()
1244
+ const workspaceSearches = new WorkspaceSearches({ maxEntries: config.searchMaxEntries || 50000, timeoutMs: Math.min(config.searchTimeoutMs || 30000, 60000), maxReadBytes: Math.min(config.maxFileBytes > 0 ? config.maxFileBytes : 256 * 1024, 256 * 1024), decodeBuf, encoding: config.encoding })
1245
+ ctx.effect(() => () => workspaceSearches.dispose(), 'dsh-remote.workspace-searches')
1239
1246
  const forwards = new ForwardManager(pool, { file: forwardsFile() })
1240
1247
  pool.onReady = (client) => forwards.attach(client)
1241
1248
  pool.onCloseHook = () => forwards.detach()
@@ -1698,7 +1705,13 @@ export async function apply(ctx, config) {
1698
1705
  const resolveRequestBinding = async (req, body = {}) => {
1699
1706
  const hint = requestSessionHint(req, body)
1700
1707
  let cwd = hint.local
1701
- if (!cwd && hint.sessionId) cwd = lookupSessionCwd(hint.sessionId, { sessions: sessionsSvc(), dshHome: dshBase() })
1708
+ if (hint.sessionId) {
1709
+ const recorded = lookupSessionCwd(hint.sessionId, { sessions: sessionsSvc(), dshHome: dshBase() })
1710
+ if (!recorded || hint.local && path.resolve(recorded) !== path.resolve(hint.local)) {
1711
+ throw Object.assign(new Error('Session workspace context is unavailable or mismatched; refusing to use another session or the active machine.'), { httpStatus: 403 })
1712
+ }
1713
+ cwd = recorded
1714
+ }
1702
1715
  if (cwd) {
1703
1716
  const { remotePath, machine, mirrorDir } = resolveMirrorForLocal(cwd)
1704
1717
  if (remotePath && machine) {
@@ -1840,6 +1853,13 @@ export async function apply(ctx, config) {
1840
1853
  return b
1841
1854
  }
1842
1855
 
1856
+ if (typeof ctx.on === 'function') {
1857
+ ctx.on('tools/pre-execute', async (exec, next) => {
1858
+ if (!LOCAL_MUTATION_TOOLS.has(exec?.name)) return next()
1859
+ return remoteLocalMutationDecision(exec, bindingFor(exec)) || next()
1860
+ })
1861
+ }
1862
+
1843
1863
  // ── remote sandbox semantics ──────────────────────────────────────────────
1844
1864
  // A local session is confined by ctx.sandboxPolicy; a REMOTE command used to
1845
1865
  // run under no policy at all, so a read-only session could mutate any file on
@@ -1896,7 +1916,10 @@ export async function apply(ctx, config) {
1896
1916
  if (mode === 'danger-full-access') return
1897
1917
  const b = (() => { try { return bindingFor(exec) } catch { return null } })()
1898
1918
  const workspaceRoot = (b && b.ws) || ''
1899
- const verdict = checkRemoteSandbox({ mode, operation, path: opts.path, workspaceRoot })
1919
+ // Check the execution-world path the rw_* body will actually use. Raw
1920
+ // relative and mirror-local paths must resolve exactly as resolveRemoteArg.
1921
+ const targetPath = opts.path == null ? opts.path : resolveRemoteWorkspacePath(workspaceRoot, opts.path, b?.mirrorDir || '')
1922
+ const verdict = checkRemoteSandbox({ mode, operation, path: targetPath, workspaceRoot })
1900
1923
  if (verdict.allowed) return
1901
1924
  const err = remoteSandboxDenial(verdict)
1902
1925
  if (opts.tool) err.message = `${opts.tool}: ${err.message}`
@@ -2665,7 +2688,8 @@ export async function apply(ctx, config) {
2665
2688
  mkdir: { type: 'boolean', description: 'Create missing parent directories (default true)' },
2666
2689
  encoding: { type: 'string', description: 'Text encoding, e.g. utf-8 (default) or gbk' },
2667
2690
  },
2668
- output: okOut,
2691
+ output: changeOutput,
2692
+ presentResult: presentFileChange,
2669
2693
  async execute(args, exec) {
2670
2694
  const b = requireMachine(exec, 'rw_write_file')
2671
2695
  // Remote sandbox fence: a write must be permitted by this session's resolved mode.
@@ -2674,12 +2698,13 @@ export async function apply(ctx, config) {
2674
2698
  if (!p || p === '/') throw new Error('rw_write_file: a file path is required')
2675
2699
  const content = String(args.content == null ? '' : args.content)
2676
2700
  const sftp = await b.pool.sftp()
2701
+ const before = await captureRemoteFile(sftp, p)
2677
2702
  if (args.mkdir !== false) await mkdirRemoteDirs(sftp, remoteDirname(p))
2678
2703
  const buf = encodeText(content, args.encoding || config.encoding)
2679
- await sftp.writeFile(p, buf)
2704
+ await atomicRemoteWrite(sftp, before, buf)
2680
2705
  const bytes = buf.byteLength
2681
2706
  audit('write_file', `write ${p} (${bytes}B)`, 0, b)
2682
- return { ok: true, bytes, text: `wrote ${bytes} bytes to ${p}` }
2707
+ return { ok: true, bytes, change: fileChange(p, 'write', before.bytes === null ? null : before.bytes === undefined ? undefined : decodeBuf(before.bytes, args.encoding || config.encoding), content), text: `wrote ${bytes} bytes to ${p}` }
2683
2708
  },
2684
2709
  }),
2685
2710
 
@@ -2704,7 +2729,8 @@ export async function apply(ctx, config) {
2704
2729
  count: { type: 'integer', description: 'How many occurrences to replace (default: error if the text appears more than once)' },
2705
2730
  encoding: { type: 'string', description: 'Text encoding, e.g. utf-8 (default) or gbk' },
2706
2731
  },
2707
- output: okOut,
2732
+ output: changeOutput,
2733
+ presentResult: presentFileChange,
2708
2734
  async execute(args, exec) {
2709
2735
  const b = requireMachine(exec, 'rw_edit')
2710
2736
  // Remote sandbox fence: a write must be permitted by this session's resolved mode.
@@ -2728,8 +2754,10 @@ export async function apply(ctx, config) {
2728
2754
  const newS = String(newRaw)
2729
2755
  if (oldS === '') throw new Error('rw_edit: old text must not be empty')
2730
2756
  const sftp = await b.pool.sftp()
2731
- const st0 = await sftp.stat(p)
2732
- const buf = await sftp.readFile(p)
2757
+ const before = await captureRemoteFile(sftp, p, { read: true, maxReadBytes: config.maxFileBytes })
2758
+ if (!before.stat) throw new Error('rw_edit: file not found')
2759
+ if (config.maxFileBytes > 0 && before.stat.size > config.maxFileBytes) throw new Error('rw_edit: file exceeds maxFileBytes')
2760
+ const buf = before.bytes
2733
2761
  const content = decodeBuf(buf, args.encoding || config.encoding)
2734
2762
  const count = args.count == null ? 0 : Math.max(Number(args.count) || 1, 1)
2735
2763
  const idxs = []
@@ -2745,33 +2773,9 @@ export async function apply(ctx, config) {
2745
2773
  for (let i = n - 1; i >= 0; i--) {
2746
2774
  out = out.slice(0, idxs[i]) + newS + out.slice(idxs[i] + oldS.length)
2747
2775
  }
2748
- // Optimistic lock: the remote must not have changed since we read it.
2749
- const st1 = await sftp.stat(p)
2750
- if (st1.size !== st0.size || st1.mtime !== st0.mtime) {
2751
- throw new Error(`rw_edit: ${p} changed on the remote while editing (conflict) — re-read and retry`)
2752
- }
2753
- // Atomic write: stage to a temp file and rename over the target so a
2754
- // mid-write failure cannot truncate the original (issue #65). Same
2755
- // directory keeps the rename on one filesystem.
2756
- const tmpPath = `${p}.dsh-remote-edit-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.tmp`
2757
- try {
2758
- await sftp.writeFile(tmpPath, encodeText(out, args.encoding || config.encoding))
2759
- // renameOverwrite, not rename: the target EXISTS by definition here,
2760
- // and plain SSH_FXP_RENAME refuses to replace it (issue #65).
2761
- await sftp.renameOverwrite(tmpPath, p)
2762
- // The rename swaps in a FRESH inode, so the original permission bits
2763
- // (an executable script's +x, a 0600 secret) would silently reset to
2764
- // the umask default. Restore them; a chmod failure must not fail the
2765
- // edit itself — the content is already safely in place.
2766
- if (st0 && typeof st0.mode === 'number') {
2767
- try { await sftp.setstat(p, { mode: st0.mode & 0o7777 }) } catch { /* best effort */ }
2768
- }
2769
- } catch (err) {
2770
- try { await sftp.unlink(tmpPath) } catch { /* best effort */ }
2771
- throw err
2772
- }
2776
+ await atomicRemoteWrite(sftp, before, encodeText(out, args.encoding || config.encoding))
2773
2777
  audit('edit', `edit ${p} (${n} occurrence(s))`, 0, b)
2774
- return { ok: true, bytes: Buffer.byteLength(out), text: `edited ${p}: replaced ${n} occurrence(s)` }
2778
+ return { ok: true, bytes: encodeText(out, args.encoding || config.encoding).byteLength, change: fileChange(p, 'edit', content, out), text: `edited ${p}: replaced ${n} occurrence(s)` }
2775
2779
  },
2776
2780
  }),
2777
2781
 
@@ -2784,7 +2788,8 @@ export async function apply(ctx, config) {
2784
2788
  content: { type: 'string', required: true, description: 'Text to append' },
2785
2789
  encoding: { type: 'string', description: 'Text encoding, e.g. utf-8 (default) or gbk' },
2786
2790
  },
2787
- output: okOut,
2791
+ output: changeOutput,
2792
+ presentResult: presentFileChange,
2788
2793
  async execute(args, exec) {
2789
2794
  const b = requireMachine(exec, 'rw_append')
2790
2795
  // Remote sandbox fence: a write must be permitted by this session's resolved mode.
@@ -2792,13 +2797,14 @@ export async function apply(ctx, config) {
2792
2797
  const p = resolveRemoteArg(b, args.path)
2793
2798
  if (!p || p === '/') throw new Error('rw_append: a file path is required')
2794
2799
  const sftp = await b.pool.sftp()
2795
- let existing = ''
2796
- try { existing = decodeBuf(await sftp.readFile(p), args.encoding || config.encoding) } catch { /* new file */ }
2800
+ const before = await captureRemoteFile(sftp, p, { read: true, maxReadBytes: config.maxFileBytes })
2801
+ const existing = before.bytes ? decodeBuf(before.bytes, args.encoding || config.encoding) : ''
2797
2802
  const content = existing + String(args.content ?? '')
2798
- await sftp.writeFile(p, encodeText(content, args.encoding || config.encoding))
2799
- const bytes = Buffer.byteLength(content)
2803
+ const encoded = encodeText(content, args.encoding || config.encoding)
2804
+ await atomicRemoteWrite(sftp, before, encoded)
2805
+ const bytes = encoded.byteLength
2800
2806
  audit('append', `append ${p}`, 0, b)
2801
- return { ok: true, bytes, text: `appended to ${p} (now ${bytes} bytes)` }
2807
+ return { ok: true, bytes, change: fileChange(p, 'append', before.bytes === null ? null : existing, content), text: `appended to ${p} (now ${bytes} bytes)` }
2802
2808
  },
2803
2809
  }),
2804
2810
 
@@ -3207,7 +3213,8 @@ export async function apply(ctx, config) {
3207
3213
  'Use the rw_* tools (rw_list_dir / rw_read_file / rw_write_file / rw_edit / rw_exec / rw_search / rw_sync / rw_push / rw_download / rw_upload) to inspect and act on files on the remote host. Treat this directory as the working root for this task.\n' +
3208
3214
  `\`@path\` mentions in this conversation name files under THAT remote root (\`@src/main.c\` = ${shown}/src/main.c). ` +
3209
3215
  'The rw_* tools take such paths as workspace-relative and resolve them against this root. ' +
3210
- `The harness's built-in local tools (read / write / edit / grep / glob / working_directory / local shell) only see the LOCAL mirror of this directory${mirrorNote}, which stays empty until rw_sync — use rw_read_file / rw_list_dir / rw_search / rw_exec for remote files, or rw_download to fetch a specific remote file locally.` +
3216
+ `The harness's built-in local tools (read / write / edit / grep / glob / working_directory / local shell) only see the LOCAL mirror of this directory${mirrorNote}, which stays empty until rw_sync — use rw_read_file / rw_list_dir / rw_search / rw_exec for remote files, or rw_download to fetch a specific remote file locally.\n` +
3217
+ 'Creating a file with local write/edit, a local shell, or Python does NOT save it on the remote host. Native write/edit mutations are refused in remote sessions: use rw_write_file / rw_edit or rw_exec to create and modify remote results. For an already-local artifact, explicitly use rw_push / rw_upload and verify it through rw_read_file or rw_stat before claiming it is saved remotely or giving a remote file link. run_code/PTC remains available for orchestration; its raw local filesystem IO is still LOCAL.\n' +
3211
3218
  extra
3212
3219
  )
3213
3220
  },
@@ -4363,6 +4370,8 @@ export async function apply(ctx, config) {
4363
4370
  aliasOf, activeMachine, startAutoPush, applyRequestedMachine, registerMirroredWorkspace, localPickCapability,
4364
4371
  pickLocalNative, listLocalDrives, probeMachineRecord, setCurrent, knownHostsFile, prepareMirrorTarget, machineForId: (id) => machines.find((m) => m.id === id),
4365
4372
  }),
4373
+ ...createSearchRoutes({ searches: workspaceSearches, sendJson, readBody, resolveRequestBinding, isIgnoredFor: searchIgnoreMatcher }),
4374
+ ...createGitRoutes({ sendJson, resolveRequestBinding, decodeBuf, config }),
4366
4375
  ...createFsRoutes({
4367
4376
  sendJson, readBody, resolveRequestBinding, decodeBuf, encodeText, audit, config, mirrorDirFor,
4368
4377
  onRemoteMutation: () => { if (remoteSkills) remoteSkills.invalidate() },
@@ -0,0 +1,129 @@
1
+ // Recovery for an explicitly identified local mirror copy. A remote read never
2
+ // substitutes these bytes, and publishing uses SFTP exclusive creation.
3
+ import { open, lstat, realpath } from 'node:fs/promises'
4
+ import path from 'node:path'
5
+ import { mirrorDownloadTarget, assertDownloadHasNoSymlinks } from './mirror-paths.js'
6
+ import { requestSessionHint } from './binding.js'
7
+ import { remoteRevision, missingRemoteFile } from './remote-write.js'
8
+ import { normalizeRemotePath, remoteDirname, mkdirRemoteDirs, joinRemotePath } from './paths.js'
9
+
10
+ const HARD_CAP = 2 * 1024 * 1024
11
+ const failure = (message, httpStatus, code) => Object.assign(new Error(message), { httpStatus, code })
12
+ const changed = () => failure('本地副本已变化,请重新查看后再上传。', 409, 'LOCAL_COPY_CHANGED')
13
+ const unsupported = () => failure('仅支持查看和上传完整的 UTF-8 文本副本;此文件不是受支持的文本。', 415, 'LOCAL_COPY_UNSUPPORTED')
14
+ const sameFile = (a, b) => a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeMs === b.mtimeMs && a.ctimeMs === b.ctimeMs
15
+
16
+ async function checkRemoteParents(sftp, binding, target, allowMissing) {
17
+ const root = normalizeRemotePath(binding.ws)
18
+ const grammar = /^(?:[a-z]:[\\/]|\\\\)/i.test(root) ? path.win32 : path.posix
19
+ const relative = grammar.relative(root, remoteDirname(target))
20
+ let current = root
21
+ for (const part of ['', ...relative.split(grammar.sep).filter(Boolean)]) {
22
+ if (part) current = joinRemotePath(current, part)
23
+ let stat
24
+ try { stat = await sftp.lstat(current) }
25
+ catch (error) { if (allowMissing && missingRemoteFile(error)) return; throw error }
26
+ if (stat.isSymbolicLink?.() || !stat.isDirectory?.()) throw failure('远端父路径不是普通目录或含符号链接,未上传。', 403, 'LOCAL_COPY_UNSAFE_REMOTE_PATH')
27
+ }
28
+ }
29
+
30
+ async function resolveCopy(binding, target) {
31
+ if (!binding.bound || !binding.ws || !binding.mirrorDir) throw failure('An explicitly bound remote session is required', 403, 'LOCAL_COPY_UNBOUND')
32
+ const local = mirrorDownloadTarget(binding.mirrorDir, binding.ws, target)
33
+ assertDownloadHasNoSymlinks(binding.mirrorDir, local)
34
+ const root = await realpath(binding.mirrorDir), physical = await realpath(local)
35
+ const within = path.relative(root, physical)
36
+ if (!within || path.isAbsolute(within) || within.split(path.sep).includes('..')) throw failure('The local copy is outside this session workspace mirror', 403, 'LOCAL_COPY_UNSAFE')
37
+ const stat = await lstat(local)
38
+ if (!stat.isFile() || stat.isSymbolicLink()) throw failure('The local copy must be a regular file without symbolic links', 403, 'LOCAL_COPY_UNSAFE')
39
+ return { local, stat, relativePath: path.relative(path.resolve(binding.mirrorDir), local).split(path.sep).join('/') }
40
+ }
41
+
42
+ export async function localCopyInfo(binding, target) {
43
+ if (!binding.bound || !binding.mirrorDir) return null
44
+ try {
45
+ const copy = await resolveCopy(binding, target)
46
+ return { available: true, source: 'local-mirror', relativePath: copy.relativePath, size: copy.stat.size, mtime: Math.floor(copy.stat.mtimeMs / 1000) }
47
+ } catch (error) {
48
+ // A remote missing-file response is still truthful when a local candidate
49
+ // cannot be offered safely. Do not disclose files behind links/outside root.
50
+ if (error.code === 'ENOENT' || error.code === 'ENOTDIR' || error.httpStatus === 403) return null
51
+ throw error
52
+ }
53
+ }
54
+
55
+ export async function readLocalCopy(binding, target, { maxFileBytes = 0 } = {}) {
56
+ let copy
57
+ try { copy = await resolveCopy(binding, target) }
58
+ catch (error) { if (error.code === 'ENOENT' || error.code === 'ENOTDIR') throw failure('本地副本已不存在。', 404, 'LOCAL_COPY_NOT_FOUND'); throw error }
59
+ const cap = maxFileBytes > 0 ? Math.min(maxFileBytes, HARD_CAP) : HARD_CAP
60
+ if (copy.stat.size > cap) throw failure(`本地副本超过 ${cap} bytes 的文本恢复上限。`, 413, 'LOCAL_COPY_TOO_LARGE')
61
+ if (/\.(?:png|jpe?g|gif|webp|bmp|ico|avif|pdf)$/i.test(target)) throw unsupported()
62
+ const handle = await open(copy.local, 'r')
63
+ let bytes
64
+ try {
65
+ const before = await handle.stat()
66
+ if (!sameFile(copy.stat, before)) throw changed()
67
+ // Resolve and recheck after opening; a replaced file or parent link must
68
+ // never turn an apparent mirror read into an unrelated local read.
69
+ const verified = await resolveCopy(binding, target)
70
+ if (!sameFile(copy.stat, verified.stat)) throw changed()
71
+ const buffer = Buffer.alloc(copy.stat.size + 1)
72
+ let offset = 0
73
+ while (offset < buffer.length) {
74
+ const result = await handle.read(buffer, offset, buffer.length - offset, offset)
75
+ if (!result.bytesRead) break
76
+ offset += result.bytesRead
77
+ }
78
+ if (offset !== copy.stat.size || !sameFile(copy.stat, await handle.stat())) throw changed()
79
+ bytes = buffer.subarray(0, offset)
80
+ } finally { await handle.close() }
81
+ if (bytes.includes(0)) throw unsupported()
82
+ let text
83
+ try { text = new TextDecoder('utf-8', { fatal: true }).decode(bytes) } catch { throw unsupported() }
84
+ return { bytes, preview: { ok: true, source: 'local-mirror', readOnly: true, path: target,
85
+ relativePath: copy.relativePath, content: text.replace(/\r\n/g, '\n'), localRevision: remoteRevision(bytes),
86
+ size: bytes.length, mtime: Math.floor(copy.stat.mtimeMs / 1000), binary: false, image: false, truncated: false } }
87
+ }
88
+
89
+ export async function publishLocalCopy(binding, target, expectedLocalRevision, options = {}) {
90
+ if (typeof expectedLocalRevision !== 'string' || !/^[a-f0-9]{64}$/.test(expectedLocalRevision)) throw failure('A localRevision from the complete local-copy preview is required', 400, 'LOCAL_COPY_REVISION_REQUIRED')
91
+ const { bytes, preview } = await readLocalCopy(binding, target, options)
92
+ if (preview.localRevision !== expectedLocalRevision) throw changed()
93
+ const sftp = await binding.pool.sftp()
94
+ const existing = await sftp.lstat(target).catch(error => { if (missingRemoteFile(error)) return null; throw error })
95
+ if (existing) throw failure('远端已有同名文件,未覆盖。请重新读取并比较。', 409, 'REMOTE_FILE_EXISTS')
96
+ await checkRemoteParents(sftp, binding, target, true)
97
+ await mkdirRemoteDirs(sftp, remoteDirname(target))
98
+ await checkRemoteParents(sftp, binding, target, false)
99
+ try {
100
+ // This flag is forwarded to SSH_FXP_OPEN as CREAT|EXCL. A concurrent file
101
+ // appearing after lstat MUST fail at the server; no replace/rename follows.
102
+ await sftp.createFileExclusive(target, bytes)
103
+ } catch (error) {
104
+ if (error.exclusiveFileCreated) throw failure('上传未完整完成,远端可能留下新建的不完整文件;请检查远端后再重试。', 502, 'LOCAL_COPY_UPLOAD_INCOMPLETE')
105
+ if (error.exclusiveOpenFailed && [4, 11, 'EEXIST'].includes(error.code)) {
106
+ const appeared = await sftp.lstat(target).catch(probe => { if (missingRemoteFile(probe)) return null; throw error })
107
+ if (appeared) throw failure('远端已出现同名文件,上传未覆盖该文件;请重新读取并检查。', 409, 'REMOTE_FILE_EXISTS')
108
+ }
109
+ throw error
110
+ }
111
+ return { ok: true, source: 'remote', path: target, bytes: bytes.length, revision: remoteRevision(bytes) }
112
+ }
113
+
114
+ export function createLocalCopyRoutes({ sendJson, readBody, resolveRequestBinding, config, audit, onRemoteMutation = () => {} }) {
115
+ return ['read', 'publish'].map(action => ({ kind: 'exact', path: '/dsh-remote/local-copy/' + action, async handler(req, res) {
116
+ if (req.method !== 'POST') return sendJson(res, 405, { ok: false, error: 'method not allowed' })
117
+ try {
118
+ const body = JSON.parse((await readBody(req)) || '{}'), hint = requestSessionHint(req, body)
119
+ if (!hint.sessionId && !hint.local) throw failure('An explicit sessionId or local workspace context is required', 403, 'LOCAL_COPY_UNBOUND')
120
+ if (typeof body.path !== 'string' || !body.path.trim()) throw failure('path is required', 400, 'LOCAL_COPY_PATH_REQUIRED')
121
+ const target = normalizeRemotePath(body.path), binding = await resolveRequestBinding(req, body)
122
+ if (action === 'read') return sendJson(res, 200, (await readLocalCopy(binding, target, config)).preview)
123
+ const result = await publishLocalCopy(binding, target, body.expectedLocalRevision, config)
124
+ audit?.('publish-local-copy', `publish ${target}`, 0, binding)
125
+ onRemoteMutation()
126
+ return sendJson(res, 200, result)
127
+ } catch (error) { return sendJson(res, error.httpStatus || 500, { ok: false, error: error.message || String(error), ...(error.code ? { code: error.code } : {}) }) }
128
+ } }))
129
+ }
@@ -0,0 +1,8 @@
1
+ // Native filesystem tools operate on the host mirror, not its SSH origin.
2
+ // Use the same gate for root native calls and nested PTC dispatches.
3
+ export const LOCAL_MUTATION_TOOLS = new Set(['write', 'edit', 'str_replace_editor'])
4
+ export function remoteLocalMutationDecision(exec, binding) {
5
+ if (!binding?.bound || !LOCAL_MUTATION_TOOLS.has(exec?.name)) return null
6
+ if (exec.name === 'str_replace_editor' && exec.arguments?.command === 'view') return null
7
+ return { kind: 'deny', reason: `${exec.name} was not executed: this session is a REMOTE workspace, but this tool writes only the LOCAL mirror. Use rw_write_file to create remote files or rw_edit to modify them; workspace-relative paths and local-mirror paths are accepted. A local write does not publish a remote file or make a remote file link valid. If a local artifact already exists, explicitly upload it with rw_push/rw_upload and verify it remotely before reporting a remote link.` }
8
+ }
@@ -0,0 +1,34 @@
1
+ // Files crossing between a remote workspace and its local mirror must obey
2
+ // both path grammars and must never traverse local symlinks.
3
+ import { lstatSync } from 'node:fs'
4
+ import path from 'node:path'
5
+ import { normalizeRemotePath } from './paths.js'
6
+
7
+ const unsafeDownload = () => Object.assign(new Error('The download destination must be a regular file inside this workspace mirror'), { httpStatus: 403 })
8
+
9
+ // Remote POSIX names may contain backslashes that become separators on a
10
+ // Windows host. Resolve in each filesystem's own grammar, never by prefix.
11
+ export function mirrorDownloadTarget(base, workspace, remote, localPath = path) {
12
+ const remotePath = /^(?:[a-z]:[\\/]|\\\\)/i.test(workspace) ? path.win32 : path.posix
13
+ const relative = remotePath.relative(normalizeRemotePath(workspace), normalizeRemotePath(remote))
14
+ if (!relative || remotePath.isAbsolute(relative) || relative.split(remotePath.sep).some(part => part === '..') || relative.includes('\0')) throw unsafeDownload()
15
+ const parts = relative.split(remotePath.sep)
16
+ // This local-only record determines the session's remote identity.
17
+ if (parts.length === 1 && (localPath.sep === '\\' ? parts[0].toLowerCase() : parts[0]) === '.dsh-remote-meta.json') throw unsafeDownload()
18
+ if (localPath.sep === '\\' && parts.some(part => /[<>:"|?*\\\x00-\x1f]/.test(part) || /[. ]$/.test(part) || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part))) throw unsafeDownload()
19
+ const root = localPath.resolve(base), target = localPath.resolve(root, ...parts)
20
+ const within = localPath.relative(root, target)
21
+ if (!within || localPath.isAbsolute(within) || within.split(localPath.sep).some(part => part === '..')) throw unsafeDownload()
22
+ return target
23
+ }
24
+
25
+ export function assertDownloadHasNoSymlinks(base, target) {
26
+ const root = path.resolve(base)
27
+ let current = root
28
+ for (const segment of ['', ...path.relative(root, target).split(path.sep)]) {
29
+ if (segment) current = path.join(current, segment)
30
+ try { if (lstatSync(current).isSymbolicLink()) throw unsafeDownload() }
31
+ catch (error) { if (error.code !== 'ENOENT') throw error }
32
+ }
33
+ }
34
+
package/lib/remote-fs.js CHANGED
@@ -1,5 +1,6 @@
1
1
  // Shared remote SFTP helpers used by both rw_* tools and the sidebar HTTP routes.
2
2
  import { joinRemotePath, normalizeRemotePath } from './paths.js'
3
+ import { remoteRevision } from './remote-write.js'
3
4
 
4
5
  /** Structured listing: name + type + size + mtime + mode (SFTP protocol-level). */
5
6
  export async function listDirStructured(sftp, p) {
@@ -163,11 +164,16 @@ export async function previewRemoteFile(sftp, target, opts = {}) {
163
164
  truncated,
164
165
  }
165
166
  }
166
- let content = decodeBuf(buf, encoding).replace(/\r\n/g, '\n')
167
+ const decoded = decodeBuf(buf, encoding)
168
+ // Empty/no-newline files default to LF for future edits. A bare CR is kept
169
+ // in the conservative 'mixed' bucket: clients must not rewrite it silently.
170
+ const crlf = /\r\n/.test(decoded)
171
+ const eol = /\r(?!\n)/.test(decoded) || crlf && /(^|[^\r])\n/.test(decoded) ? 'mixed' : crlf ? 'crlf' : 'lf'
172
+ let content = decoded.replace(/\r\n/g, '\n')
167
173
  if (!truncated && content.length > cap) {
168
174
  truncated = true
169
175
  content = content.slice(0, cap)
170
176
  }
171
177
  if (truncated) content += `\n…[truncated: ${Math.max(0, size - cap)} more bytes]`
172
- return { ok: true, binary: false, content, truncated, size, mtime }
178
+ return { ok: true, binary: false, content, truncated, size, mtime, ...(!truncated ? { revision: remoteRevision(buf), eol } : {}) }
173
179
  }
@@ -0,0 +1,127 @@
1
+ // Read-only Git inspection in the session's execution world, never the mirror.
2
+ import { shq, normalizeRemotePath, joinRemotePath, relPathUnder } from './paths.js'
3
+ import { previewRemoteFile } from './remote-fs.js'
4
+
5
+ const LIMIT = 192 * 1024
6
+ const safeRelative = value => typeof value === 'string' && value.length > 0 && !/[\x00-\x1f\x7f\\:]/.test(value) && !value.startsWith('/') && !value.split('/').some(p => p === '..' || p === '.')
7
+ const errorText = result => result.signal === 'TIMEOUT' ? 'Git inspection timed out; narrow the workspace and retry' : String(result.stderr || result.stdout || 'Git command failed').slice(0, 2000)
8
+ const gitPath = value => /^[a-z]:[\\/]/i.test(value) ? value.replace(/\\/g, '/') : value
9
+
10
+ export function parseGitStatus(text, { repo, workspace = repo, limit = 500 } = {}) {
11
+ const parts = text.split('\0'), files = []
12
+ let truncated = !text.endsWith('\0') && text.length > 0
13
+ // Never turn a clipped record into a plausible filename.
14
+ if (truncated) parts.pop()
15
+ for (let i = 0; i < parts.length; i++) {
16
+ const record = parts[i]
17
+ if (!record) continue
18
+ if (record.length < 4 || record[2] !== ' ') { truncated = true; continue }
19
+ const indexStatus = record[0], worktreeStatus = record[1], path = record.slice(3)
20
+ let previousPath
21
+ if (/[RC]/.test(indexStatus + worktreeStatus)) { previousPath = parts[++i]; if (!previousPath) { truncated = true; continue } }
22
+ if (!safeRelative(path)) { truncated = true; continue }
23
+ const absolutePath = joinRemotePath(repo, path)
24
+ if (relPathUnder(workspace, absolutePath) === null) continue
25
+ if (files.length >= limit) { truncated = true; break }
26
+ files.push({ path, absolutePath, ...(previousPath ? { previousPath } : {}), indexStatus, worktreeStatus,
27
+ untracked: indexStatus === '?', deleted: worktreeStatus === 'D' || indexStatus === 'D' && worktreeStatus === ' ',
28
+ conflict: indexStatus === 'U' || worktreeStatus === 'U' || ['AA','DD'].includes(indexStatus + worktreeStatus) })
29
+ }
30
+ return { files, truncated }
31
+ }
32
+
33
+ async function runGit(pool, cwd, args, signal, limit = LIMIT) {
34
+ const cancel = new AbortController()
35
+ const abort = () => cancel.abort()
36
+ if (signal?.aborted) cancel.abort()
37
+ signal?.addEventListener('abort', abort, { once: true })
38
+ let output = [], size = 0, tapped = false, truncated = false
39
+ try {
40
+ const command = ['git', '--no-pager', '--no-optional-locks', '-c', 'core.fsmonitor=false', '-c', 'core.quotePath=false', '-c', 'color.ui=false', '-C', gitPath(cwd), ...args].map(shq).join(' ')
41
+ const result = await pool.exec(command, { timeoutMs: 15000, signal: cancel.signal, onData(channel, chunk) {
42
+ if (channel !== 'stdout') return
43
+ tapped = true
44
+ const bytes = Buffer.from(chunk)
45
+ if (size < limit) output.push(bytes.subarray(0, limit - size))
46
+ size += bytes.length
47
+ if (size > limit) { truncated = true; cancel.abort() }
48
+ } })
49
+ const stdout = tapped ? Buffer.concat(output).toString('utf8') : String(result.stdout || '').slice(0, limit)
50
+ return { ...result, stdout, truncated: truncated || !tapped && String(result.stdout || '').length > limit }
51
+ } finally { signal?.removeEventListener('abort', abort) }
52
+ }
53
+
54
+ export async function inspectRemoteGit(binding, { action = 'status', path: relative, staged = false, signal, decodeBuf, encoding } = {}) {
55
+ const { pool, ws } = binding
56
+ if (!binding.bound || !ws) throw Object.assign(new Error('Git inspection requires a session bound to a remote workspace'), { httpStatus: 403 })
57
+ if (!['status', 'diff'].includes(action)) throw Object.assign(new Error('action must be status or diff'), { httpStatus: 400 })
58
+ if (action === 'diff' && !safeRelative(relative)) throw Object.assign(new Error('A repository-relative Git file path is required'), { httpStatus: 400 })
59
+ await pool.detect()
60
+ if (pool.platform === 'windows' && !pool.gitBashPath) return { ok: true, available: false, reason: 'unsupported-shell' }
61
+ const top = await runGit(pool, ws, ['rev-parse', '--show-toplevel', '--show-prefix'], signal, 8192)
62
+ if (top.code !== 0) {
63
+ if (top.code === 127 || /not recognized|command not found/i.test(top.stderr || '')) return { ok: true, available: false, reason: 'git-unavailable' }
64
+ if (/not a git repository/i.test(top.stderr || '')) return { ok: true, available: false, reason: 'not-repository' }
65
+ throw new Error(errorText(top))
66
+ }
67
+ const rootLines = top.stdout.replace(/\r\n/g, '\n').split('\n')
68
+ const repo = normalizeRemotePath(rootLines[0] || '')
69
+ const prefix = (rootLines[1] || '').replace(/\/$/, '')
70
+ if (top.truncated || rootLines.length !== 3 || rootLines[2] !== '' || !repo || /[\x00-\x1f\x7f]/.test(repo) || prefix && !safeRelative(prefix)) throw new Error('Git returned an unsupported repository path')
71
+ // Git canonicalizes symlinked workspace roots. Keep filtering in that same
72
+ // world, but return navigation paths under the user's original workspace.
73
+ const gitWorkspace = prefix ? joinRemotePath(repo, prefix) : repo
74
+ const navigationPath = target => {
75
+ const within = relPathUnder(gitWorkspace, target)
76
+ return within === null ? null : within ? joinRemotePath(ws, within) : ws
77
+ }
78
+ if (signal?.aborted) throw new Error('Git inspection cancelled')
79
+ if (action === 'status') {
80
+ const status = await runGit(pool, ws, ['status', '--porcelain=v1', '-z', '--untracked-files=all', '--ignore-submodules=all', '--', '.'], signal)
81
+ if (status.code !== 0 && !status.truncated) throw new Error(errorText(status))
82
+ const head = await runGit(pool, ws, ['symbolic-ref', '--quiet', '--short', 'HEAD'], signal, 4096)
83
+ if (![0,1].includes(head.code)) throw new Error(errorText(head))
84
+ const parsed = parseGitStatus(status.stdout, { repo, workspace: gitWorkspace })
85
+ return { ok: true, available: true, repo, workspace: ws, branch: head.code === 0 ? head.stdout.trim() : '', detached: head.code === 1,
86
+ ...parsed, files: parsed.files.map(file => ({ ...file, absolutePath: navigationPath(file.absolutePath) })),
87
+ truncated: parsed.truncated || status.truncated || head.truncated }
88
+ }
89
+ const target = joinRemotePath(repo, relative)
90
+ if (relPathUnder(gitWorkspace, target) === null) throw Object.assign(new Error('The requested file is outside this remote workspace'), { httpStatus: 403 })
91
+ // Literal pathspecs matter: filenames such as "[test].js" are not patterns.
92
+ const diff = await runGit(pool, repo, ['--literal-pathspecs', 'diff', ...(staged ? ['--cached'] : []), '--no-ext-diff', '--no-textconv', '--no-color', '--ignore-submodules=all', '--', relative], signal)
93
+ if (diff.code !== 0 && !diff.truncated) throw new Error(errorText(diff))
94
+ if (diff.stdout || staged) return { ok: true, available: true, repo, path: relative, absolutePath: navigationPath(target), staged, patch: diff.stdout, truncated: diff.truncated }
95
+ // Git diff intentionally omits untracked files. Only read files Git confirms
96
+ // are untracked; do not follow symlinks into an unrelated execution target.
97
+ const untracked = await runGit(pool, repo, ['--literal-pathspecs', 'ls-files', '--others', '--exclude-standard', '-z', '--', relative], signal, 8192)
98
+ if (untracked.code !== 0) throw new Error(errorText(untracked))
99
+ if (!untracked.stdout.split('\0').includes(relative)) return { ok: true, available: true, path: relative, absolutePath: navigationPath(target), patch: '', truncated: false }
100
+ const sftp = await pool.sftp()
101
+ const stat = await sftp.lstat(target)
102
+ if (stat.isSymbolicLink?.()) return { ok: true, available: true, path: relative, absolutePath: navigationPath(target), patch: '', reason: 'symlink', untracked: true }
103
+ const preview = await previewRemoteFile(sftp, target, { maxBytes: 64 * 1024, decodeBuf, encoding })
104
+ if (preview.binary || preview.image || preview.truncated) return { ok: true, available: true, path: relative, absolutePath: navigationPath(target), patch: '', reason: preview.truncated ? 'too-large' : 'binary', untracked: true, truncated: !!preview.truncated }
105
+ const content = preview.content || ''
106
+ const lines = content ? content.split('\n') : []
107
+ if (content.endsWith('\n')) lines.pop()
108
+ const patch = content ? `--- /dev/null\n+++ b/${relative}\n@@ -0,0 +1,${lines.length} @@\n` + lines.map(line => '+' + line).join('\n') + (content.endsWith('\n') ? '\n' : '\n\\n') : ''
109
+ return { ok: true, available: true, path: relative, absolutePath: navigationPath(target), untracked: true, truncated: false,
110
+ patch, empty: content.length === 0 }
111
+ }
112
+
113
+ export function createGitRoutes({ sendJson, resolveRequestBinding, decodeBuf, config }) {
114
+ return [{ kind: 'exact', path: '/dsh-remote/git', async handler(req, res) {
115
+ if (req.method !== 'GET') return sendJson(res, 405, { ok: false, error: 'method not allowed' })
116
+ const cancel = new AbortController(), close = () => cancel.abort()
117
+ res.on?.('close', close)
118
+ try {
119
+ const q = new URL(req.url, 'http://localhost').searchParams
120
+ if (!q.get('sessionId') && !q.get('local')) return sendJson(res, 400, { ok: false, error: 'sessionId or local workspace context is required' })
121
+ const binding = await resolveRequestBinding(req)
122
+ const result = await inspectRemoteGit(binding, { action: q.get('action') || 'status', path: q.get('path'), staged: q.get('staged') === '1', signal: cancel.signal, decodeBuf, encoding: config.encoding })
123
+ if (!cancel.signal.aborted) sendJson(res, 200, result)
124
+ } catch (error) { if (!cancel.signal.aborted) sendJson(res, error.httpStatus || 500, { ok: false, error: error.message || String(error) }) }
125
+ finally { res.off?.('close', close) }
126
+ } }]
127
+ }