dsh-remote 1.0.1 → 1.1.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/README.en.md +38 -318
- package/README.md +36 -298
- package/lib/binding.js +4 -2
- package/lib/client.js +828 -62
- package/lib/file-changes.js +57 -0
- package/lib/index.js +29 -38
- package/lib/remote-fs.js +8 -2
- package/lib/remote-git.js +127 -0
- package/lib/remote-shell-child.cjs +59 -12
- package/lib/remote-shell.js +1 -1
- package/lib/remote-write.js +51 -0
- package/lib/routes-fs.js +72 -24
- package/lib/sftp-surface.js +1 -1
- package/lib/vendor/jsdiff/LICENSE +29 -0
- package/lib/vendor/jsdiff/SOURCE.md +4 -0
- package/lib/vendor/jsdiff/diff/base.js +254 -0
- package/lib/vendor/jsdiff/diff/line.js +66 -0
- package/lib/vendor/jsdiff/patch/create.js +229 -0
- package/lib/vendor/jsdiff/util/params.js +15 -0
- package/lib/workspace-search.js +219 -0
- package/package.json +6 -5
|
@@ -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,10 @@
|
|
|
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 { fileChange, changeOutput, presentFileChange } from './file-changes.js'
|
|
24
|
+
import { captureRemoteFile, atomicRemoteWrite } from './remote-write.js'
|
|
21
25
|
import z from '@deepseek-ai/schemastery'
|
|
22
26
|
import { createAutoUpdater } from './auto-update.js'
|
|
23
27
|
import { defineTool } from '@deepseek-ai/dsh-tools'
|
|
@@ -1236,6 +1240,8 @@ export async function apply(ctx, config) {
|
|
|
1236
1240
|
|
|
1237
1241
|
// ── task + forward managers ───────────────────────────────────────────────
|
|
1238
1242
|
const tasks = new TaskManager()
|
|
1243
|
+
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 })
|
|
1244
|
+
ctx.effect(() => () => workspaceSearches.dispose(), 'dsh-remote.workspace-searches')
|
|
1239
1245
|
const forwards = new ForwardManager(pool, { file: forwardsFile() })
|
|
1240
1246
|
pool.onReady = (client) => forwards.attach(client)
|
|
1241
1247
|
pool.onCloseHook = () => forwards.detach()
|
|
@@ -2665,7 +2671,8 @@ export async function apply(ctx, config) {
|
|
|
2665
2671
|
mkdir: { type: 'boolean', description: 'Create missing parent directories (default true)' },
|
|
2666
2672
|
encoding: { type: 'string', description: 'Text encoding, e.g. utf-8 (default) or gbk' },
|
|
2667
2673
|
},
|
|
2668
|
-
output:
|
|
2674
|
+
output: changeOutput,
|
|
2675
|
+
presentResult: presentFileChange,
|
|
2669
2676
|
async execute(args, exec) {
|
|
2670
2677
|
const b = requireMachine(exec, 'rw_write_file')
|
|
2671
2678
|
// Remote sandbox fence: a write must be permitted by this session's resolved mode.
|
|
@@ -2674,12 +2681,13 @@ export async function apply(ctx, config) {
|
|
|
2674
2681
|
if (!p || p === '/') throw new Error('rw_write_file: a file path is required')
|
|
2675
2682
|
const content = String(args.content == null ? '' : args.content)
|
|
2676
2683
|
const sftp = await b.pool.sftp()
|
|
2684
|
+
const before = await captureRemoteFile(sftp, p)
|
|
2677
2685
|
if (args.mkdir !== false) await mkdirRemoteDirs(sftp, remoteDirname(p))
|
|
2678
2686
|
const buf = encodeText(content, args.encoding || config.encoding)
|
|
2679
|
-
await sftp
|
|
2687
|
+
await atomicRemoteWrite(sftp, before, buf)
|
|
2680
2688
|
const bytes = buf.byteLength
|
|
2681
2689
|
audit('write_file', `write ${p} (${bytes}B)`, 0, b)
|
|
2682
|
-
return { ok: true, bytes, text: `wrote ${bytes} bytes to ${p}` }
|
|
2690
|
+
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
2691
|
},
|
|
2684
2692
|
}),
|
|
2685
2693
|
|
|
@@ -2704,7 +2712,8 @@ export async function apply(ctx, config) {
|
|
|
2704
2712
|
count: { type: 'integer', description: 'How many occurrences to replace (default: error if the text appears more than once)' },
|
|
2705
2713
|
encoding: { type: 'string', description: 'Text encoding, e.g. utf-8 (default) or gbk' },
|
|
2706
2714
|
},
|
|
2707
|
-
output:
|
|
2715
|
+
output: changeOutput,
|
|
2716
|
+
presentResult: presentFileChange,
|
|
2708
2717
|
async execute(args, exec) {
|
|
2709
2718
|
const b = requireMachine(exec, 'rw_edit')
|
|
2710
2719
|
// Remote sandbox fence: a write must be permitted by this session's resolved mode.
|
|
@@ -2728,8 +2737,10 @@ export async function apply(ctx, config) {
|
|
|
2728
2737
|
const newS = String(newRaw)
|
|
2729
2738
|
if (oldS === '') throw new Error('rw_edit: old text must not be empty')
|
|
2730
2739
|
const sftp = await b.pool.sftp()
|
|
2731
|
-
const
|
|
2732
|
-
|
|
2740
|
+
const before = await captureRemoteFile(sftp, p, { read: true, maxReadBytes: config.maxFileBytes })
|
|
2741
|
+
if (!before.stat) throw new Error('rw_edit: file not found')
|
|
2742
|
+
if (config.maxFileBytes > 0 && before.stat.size > config.maxFileBytes) throw new Error('rw_edit: file exceeds maxFileBytes')
|
|
2743
|
+
const buf = before.bytes
|
|
2733
2744
|
const content = decodeBuf(buf, args.encoding || config.encoding)
|
|
2734
2745
|
const count = args.count == null ? 0 : Math.max(Number(args.count) || 1, 1)
|
|
2735
2746
|
const idxs = []
|
|
@@ -2745,33 +2756,9 @@ export async function apply(ctx, config) {
|
|
|
2745
2756
|
for (let i = n - 1; i >= 0; i--) {
|
|
2746
2757
|
out = out.slice(0, idxs[i]) + newS + out.slice(idxs[i] + oldS.length)
|
|
2747
2758
|
}
|
|
2748
|
-
|
|
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
|
-
}
|
|
2759
|
+
await atomicRemoteWrite(sftp, before, encodeText(out, args.encoding || config.encoding))
|
|
2773
2760
|
audit('edit', `edit ${p} (${n} occurrence(s))`, 0, b)
|
|
2774
|
-
return { ok: true, bytes:
|
|
2761
|
+
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
2762
|
},
|
|
2776
2763
|
}),
|
|
2777
2764
|
|
|
@@ -2784,7 +2771,8 @@ export async function apply(ctx, config) {
|
|
|
2784
2771
|
content: { type: 'string', required: true, description: 'Text to append' },
|
|
2785
2772
|
encoding: { type: 'string', description: 'Text encoding, e.g. utf-8 (default) or gbk' },
|
|
2786
2773
|
},
|
|
2787
|
-
output:
|
|
2774
|
+
output: changeOutput,
|
|
2775
|
+
presentResult: presentFileChange,
|
|
2788
2776
|
async execute(args, exec) {
|
|
2789
2777
|
const b = requireMachine(exec, 'rw_append')
|
|
2790
2778
|
// Remote sandbox fence: a write must be permitted by this session's resolved mode.
|
|
@@ -2792,13 +2780,14 @@ export async function apply(ctx, config) {
|
|
|
2792
2780
|
const p = resolveRemoteArg(b, args.path)
|
|
2793
2781
|
if (!p || p === '/') throw new Error('rw_append: a file path is required')
|
|
2794
2782
|
const sftp = await b.pool.sftp()
|
|
2795
|
-
|
|
2796
|
-
|
|
2783
|
+
const before = await captureRemoteFile(sftp, p, { read: true, maxReadBytes: config.maxFileBytes })
|
|
2784
|
+
const existing = before.bytes ? decodeBuf(before.bytes, args.encoding || config.encoding) : ''
|
|
2797
2785
|
const content = existing + String(args.content ?? '')
|
|
2798
|
-
|
|
2799
|
-
|
|
2786
|
+
const encoded = encodeText(content, args.encoding || config.encoding)
|
|
2787
|
+
await atomicRemoteWrite(sftp, before, encoded)
|
|
2788
|
+
const bytes = encoded.byteLength
|
|
2800
2789
|
audit('append', `append ${p}`, 0, b)
|
|
2801
|
-
return { ok: true, bytes, text: `appended to ${p} (now ${bytes} bytes)` }
|
|
2790
|
+
return { ok: true, bytes, change: fileChange(p, 'append', before.bytes === null ? null : existing, content), text: `appended to ${p} (now ${bytes} bytes)` }
|
|
2802
2791
|
},
|
|
2803
2792
|
}),
|
|
2804
2793
|
|
|
@@ -4363,6 +4352,8 @@ export async function apply(ctx, config) {
|
|
|
4363
4352
|
aliasOf, activeMachine, startAutoPush, applyRequestedMachine, registerMirroredWorkspace, localPickCapability,
|
|
4364
4353
|
pickLocalNative, listLocalDrives, probeMachineRecord, setCurrent, knownHostsFile, prepareMirrorTarget, machineForId: (id) => machines.find((m) => m.id === id),
|
|
4365
4354
|
}),
|
|
4355
|
+
...createSearchRoutes({ searches: workspaceSearches, sendJson, readBody, resolveRequestBinding, isIgnoredFor: searchIgnoreMatcher }),
|
|
4356
|
+
...createGitRoutes({ sendJson, resolveRequestBinding, decodeBuf, config }),
|
|
4366
4357
|
...createFsRoutes({
|
|
4367
4358
|
sendJson, readBody, resolveRequestBinding, decodeBuf, encodeText, audit, config, mirrorDirFor,
|
|
4368
4359
|
onRemoteMutation: () => { if (remoteSkills) remoteSkills.invalidate() },
|
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
|
-
|
|
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
|
+
}
|
|
@@ -332,23 +332,70 @@ function handover(file, args, extraEnv) {
|
|
|
332
332
|
return child
|
|
333
333
|
}
|
|
334
334
|
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
335
|
+
// A small whale-shaped pixel mark, following the DSH mascot silhouette. Two
|
|
336
|
+
// pixel rows share one terminal row so it stays compact beside a normal prompt.
|
|
337
|
+
// This is terminal text (SGR + block characters), not an image protocol or DOM
|
|
338
|
+
// overlay; it works in the native terminal and never echoes connection secrets.
|
|
339
|
+
const TERMINAL_FISH = [
|
|
340
|
+
' bbbb b',
|
|
341
|
+
' bbbbbbbbbb bb',
|
|
342
|
+
' bbbbbbbbbbbbbb bbb',
|
|
343
|
+
' bbbbbbbbbbbbbbbbbbbbb',
|
|
344
|
+
'bbbbbbbbbbbbbbbbbbbb',
|
|
345
|
+
'bbbbbbebbbbbbbbbbbb',
|
|
346
|
+
'bbbbbbbbbllllbbbbbb',
|
|
347
|
+
' bbbbbbblllllbbbbb',
|
|
348
|
+
' bbbbbbbbbbbbbb',
|
|
349
|
+
' bbbbbbbb',
|
|
350
|
+
]
|
|
351
|
+
|
|
352
|
+
/** Render a static welcome mark; a restart prints once, never on a poll/resize.
|
|
353
|
+
* `_target` is deliberately ignored: shell prompts and the workbench already
|
|
354
|
+
* identify the remote, so the decoration must not duplicate host/path metadata.
|
|
355
|
+
*/
|
|
356
|
+
function connectionBanner(_target, env = process.env, terminalColumns) {
|
|
357
|
+
const columns = Number(terminalColumns || env.COLUMNS)
|
|
358
|
+
const width = Number.isFinite(columns) && columns > 0 ? Math.floor(columns) : 80
|
|
359
|
+
if (width < 12) return ''
|
|
360
|
+
const color = env.NO_COLOR === undefined && !!env.TERM && env.TERM !== 'dumb'
|
|
361
|
+
const reset = color ? '\x1b[0m' : ''
|
|
362
|
+
// Avoid wrapping the fish in a narrow split terminal. ASCII is the most
|
|
363
|
+
// portable fallback, including terminals without block-character support.
|
|
364
|
+
if (width < 30 || env.TERM === 'dumb') return '\r\n' + (color ? '\x1b[36m' : '') + '><(((o> dsh' + reset + '\r\n\r\n'
|
|
365
|
+
const pixelWidth = 23
|
|
366
|
+
const ink = { b: '36', l: '96', e: '30' }
|
|
367
|
+
const lines = []
|
|
368
|
+
for (let y = 0; y < TERMINAL_FISH.length; y += 2) {
|
|
369
|
+
const upper = TERMINAL_FISH[y].padEnd(pixelWidth)
|
|
370
|
+
const lower = TERMINAL_FISH[y + 1].padEnd(pixelWidth)
|
|
371
|
+
let line = ' ', lastStyle = ''
|
|
372
|
+
for (let x = 0; x < pixelWidth; x++) {
|
|
373
|
+
// In monochrome the eye stays a hole rather than a filled body pixel.
|
|
374
|
+
const top = color ? ink[upper[x]] : upper[x] !== ' ' && upper[x] !== 'e'
|
|
375
|
+
const bottom = color ? ink[lower[x]] : lower[x] !== ' ' && lower[x] !== 'e'
|
|
376
|
+
let glyph = ' ', style = ''
|
|
377
|
+
if (top && bottom) {
|
|
378
|
+
glyph = top === bottom ? '█' : '▀'
|
|
379
|
+
if (color) style = '\x1b[' + top + ';' + (top === bottom ? '49' : String(Number(bottom) + 10)) + 'm'
|
|
380
|
+
} else if (top || bottom) {
|
|
381
|
+
glyph = top ? '▀' : '▄'
|
|
382
|
+
if (color) style = '\x1b[' + (top || bottom) + ';49m'
|
|
383
|
+
} else if (color) style = '\x1b[0m'
|
|
384
|
+
if (style !== lastStyle) { line += style; lastStyle = style }
|
|
385
|
+
line += glyph
|
|
386
|
+
}
|
|
387
|
+
line += reset
|
|
388
|
+
if (y === 4) line += ' dsh'
|
|
389
|
+
lines.push(line.trimEnd())
|
|
390
|
+
}
|
|
391
|
+
return '\r\n' + lines.join('\r\n') + '\r\n\r\n'
|
|
345
392
|
}
|
|
346
393
|
|
|
347
394
|
/**
|
|
348
395
|
* Entry point: connect, or explain why a local shell was used instead.
|
|
349
396
|
* @param {string[]} [argv]
|
|
350
397
|
* @param {{ cwd?: string, platform?: string, env?: object,
|
|
351
|
-
* stdin?: object, fstat?: (fd: number) => any,
|
|
398
|
+
* stdin?: object, columns?: number, fstat?: (fd: number) => any,
|
|
352
399
|
* write?: (line: string) => void, exit?: (code: number) => any }} [deps]
|
|
353
400
|
*/
|
|
354
401
|
function main(argv = process.argv.slice(2), deps = {}) {
|
|
@@ -375,7 +422,7 @@ function main(argv = process.argv.slice(2), deps = {}) {
|
|
|
375
422
|
}
|
|
376
423
|
const ssh = sshBinary(platform, env)
|
|
377
424
|
const args = buildSshArgs(resolved.target, resolved.machine)
|
|
378
|
-
write(connectionBanner(resolved.target, env))
|
|
425
|
+
write(connectionBanner(resolved.target, env, deps.columns || process.stderr.columns || process.stdout.columns))
|
|
379
426
|
if (isWindowsRemotePath(resolved.target.remotePath)) {
|
|
380
427
|
process.stderr.write('[dsh-remote] the remote workspace is a Windows path; opening the remote default shell without changing directory.\n')
|
|
381
428
|
process.stderr.write('[dsh-remote] 远端工作区是 Windows 路径,已打开默认 shell(未自动切换目录)。\n')
|
package/lib/remote-shell.js
CHANGED
|
@@ -292,7 +292,7 @@ export function launcherSource(spec) {
|
|
|
292
292
|
`DSH_CHILD=${shqPosix(child)}`,
|
|
293
293
|
`DSH_MACHINES=${shqPosix(machines)}`,
|
|
294
294
|
// Physical directory of this script: the askpass helper + payload live here.
|
|
295
|
-
'DSH_TERM_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)',
|
|
295
|
+
'export DSH_TERM_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)',
|
|
296
296
|
node ? `DSH_NODE=${shqPosix(node)}` : 'DSH_NODE=',
|
|
297
297
|
'if [ -n "$DSH_NODE" ] && [ -x "$DSH_NODE" ]; then exec "$DSH_NODE" "$DSH_CHILD" --machines "$DSH_MACHINES"; fi',
|
|
298
298
|
'if command -v node >/dev/null 2>&1; then exec node "$DSH_CHILD" --machines "$DSH_MACHINES"; fi',
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// Stage complete writes beside their target, check the captured baseline, then
|
|
2
|
+
// replace. This is optimistic conflict detection, not a cross-process CAS.
|
|
3
|
+
import { randomUUID, createHash } from 'node:crypto'
|
|
4
|
+
import { CHANGE_CAPTURE_BYTES } from './file-changes.js'
|
|
5
|
+
|
|
6
|
+
export const missingRemoteFile = error => error?.code === 2 || error?.code === 'ENOENT' || error?.code === 'NO_SUCH_FILE'
|
|
7
|
+
export const remoteRevision = buf => createHash('sha256').update(buf).digest('hex')
|
|
8
|
+
const conflict = () => Object.assign(new Error('Remote file changed while saving; reload and compare before retrying.'), { httpStatus: 409, code: 'REMOTE_FILE_CONFLICT' })
|
|
9
|
+
const statOrMissing = async (sftp, path) => { try { return await sftp.stat(path) } catch (error) { if (!missingRemoteFile(error)) throw error; return null } }
|
|
10
|
+
|
|
11
|
+
export async function captureRemoteFile(sftp, path, { read = false, maxBytes = CHANGE_CAPTURE_BYTES, maxReadBytes = 0 } = {}) {
|
|
12
|
+
const stat = await statOrMissing(sftp, path)
|
|
13
|
+
if (!stat) return { path, target: path, stat: null, bytes: null }
|
|
14
|
+
if (stat.isDirectory?.()) throw new Error('A file path is required, not a directory')
|
|
15
|
+
if (read && maxReadBytes > 0 && stat.size > maxReadBytes) throw Object.assign(new Error('File exceeds the configured editing size limit'), { httpStatus: 413, code: 'REMOTE_FILE_TOO_LARGE' })
|
|
16
|
+
const target = typeof sftp.realpath === 'function' ? await sftp.realpath(path) : path
|
|
17
|
+
let bytes
|
|
18
|
+
if (read || stat.size <= maxBytes) {
|
|
19
|
+
// Production surfaces have a bounded range reader. Request one byte past
|
|
20
|
+
// the observed size to detect growth without reading an arbitrarily large
|
|
21
|
+
// file that changed after stat().
|
|
22
|
+
bytes = typeof sftp.readPartial === 'function'
|
|
23
|
+
? await sftp.readPartial(target, 0, stat.size + 1)
|
|
24
|
+
: await sftp.readFile(target)
|
|
25
|
+
if (bytes.byteLength !== stat.size) throw conflict()
|
|
26
|
+
}
|
|
27
|
+
return { path, target, stat, bytes }
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export async function atomicRemoteWrite(sftp, snapshot, content) {
|
|
31
|
+
const { path, target, stat, bytes } = snapshot
|
|
32
|
+
const temporary = `${target}.dsh-remote-edit-${randomUUID()}.tmp`
|
|
33
|
+
try {
|
|
34
|
+
// Passing mode at creation avoids a public temporary copy of a 0600 file.
|
|
35
|
+
await sftp.writeFile(temporary, content, { mode: typeof stat?.mode === 'number' ? stat.mode & 0o777 : 0o666 })
|
|
36
|
+
if (stat && typeof stat.mode === 'number' && typeof sftp.setstat === 'function') await sftp.setstat(temporary, { mode: stat.mode & 0o777 })
|
|
37
|
+
const current = await statOrMissing(sftp, path)
|
|
38
|
+
if (!!stat !== !!current || stat && (stat.size !== current.size || stat.mtime !== current.mtime)) throw conflict()
|
|
39
|
+
if (stat && typeof sftp.realpath === 'function' && await sftp.realpath(path) !== target) throw conflict()
|
|
40
|
+
if (stat && bytes) {
|
|
41
|
+
const latest = typeof sftp.readPartial === 'function'
|
|
42
|
+
? await sftp.readPartial(target, 0, bytes.byteLength + 1)
|
|
43
|
+
: await sftp.readFile(target)
|
|
44
|
+
if (!Buffer.from(latest).equals(Buffer.from(bytes))) throw conflict()
|
|
45
|
+
}
|
|
46
|
+
if (stat) await sftp.renameOverwrite(temporary, target)
|
|
47
|
+
else await sftp.rename(temporary, target)
|
|
48
|
+
} finally {
|
|
49
|
+
try { await sftp.unlink(temporary) } catch { /* original error wins */ }
|
|
50
|
+
}
|
|
51
|
+
}
|