dsh-remote-deck 0.0.0-stage → 1.46.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.
Files changed (118) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +227 -2
  3. package/README.zh-CN.md +201 -0
  4. package/client.js +8645 -0
  5. package/cordis.patch.yml +6 -0
  6. package/icon.svg +19 -0
  7. package/index.js +701 -0
  8. package/lib/api.js +1452 -0
  9. package/lib/bash-result.js +93 -0
  10. package/lib/connection.js +1133 -0
  11. package/lib/delete.js +199 -0
  12. package/lib/drafts.js +299 -0
  13. package/lib/encoding.js +247 -0
  14. package/lib/file-edit.js +339 -0
  15. package/lib/file-ops.js +402 -0
  16. package/lib/forwards.js +186 -0
  17. package/lib/fs-actions.js +235 -0
  18. package/lib/guide.js +162 -0
  19. package/lib/metrics.js +523 -0
  20. package/lib/remote-shells.js +320 -0
  21. package/lib/remote-terminal.js +427 -0
  22. package/lib/routing.js +695 -0
  23. package/lib/ssh-config.js +118 -0
  24. package/lib/terminal.js +123 -0
  25. package/lib/tool-forward.js +185 -0
  26. package/lib/transfer.js +235 -0
  27. package/lib/upload-chunks.js +306 -0
  28. package/lib/util.js +154 -0
  29. package/locale/README.md +160 -0
  30. package/locale/en-ui.json +477 -0
  31. package/locale/en.json +6 -0
  32. package/locale/zh.json +6 -0
  33. package/package.json +63 -4
  34. package/vendor/codemirror/LICENSE +21 -0
  35. package/vendor/codemirror/README.md +18 -0
  36. package/vendor/codemirror/addon/edit/closebrackets.min.js +8 -0
  37. package/vendor/codemirror/addon/edit/matchbrackets.min.js +8 -0
  38. package/vendor/codemirror/addon/search/search.min.js +8 -0
  39. package/vendor/codemirror/addon/search/searchcursor.min.js +8 -0
  40. package/vendor/codemirror/addon/selection/active-line.min.js +8 -0
  41. package/vendor/codemirror/lib/codemirror.css +344 -0
  42. package/vendor/codemirror/lib/codemirror.min.js +8 -0
  43. package/vendor/codemirror/mode/clike/clike.min.js +8 -0
  44. package/vendor/codemirror/mode/css/css.min.js +8 -0
  45. package/vendor/codemirror/mode/go/go.min.js +8 -0
  46. package/vendor/codemirror/mode/htmlmixed/htmlmixed.min.js +8 -0
  47. package/vendor/codemirror/mode/javascript/javascript.min.js +8 -0
  48. package/vendor/codemirror/mode/markdown/markdown.min.js +8 -0
  49. package/vendor/codemirror/mode/python/python.min.js +8 -0
  50. package/vendor/codemirror/mode/rust/rust.min.js +8 -0
  51. package/vendor/codemirror/mode/shell/shell.min.js +8 -0
  52. package/vendor/codemirror/mode/xml/xml.min.js +8 -0
  53. package/vendor/codemirror/mode/yaml/yaml.min.js +8 -0
  54. package/vendor/node_modules/asn1/Jenkinsfile +65 -0
  55. package/vendor/node_modules/asn1/LICENSE +19 -0
  56. package/vendor/node_modules/asn1/README.md +50 -0
  57. package/vendor/node_modules/asn1/lib/ber/errors.js +13 -0
  58. package/vendor/node_modules/asn1/lib/ber/index.js +27 -0
  59. package/vendor/node_modules/asn1/lib/ber/reader.js +262 -0
  60. package/vendor/node_modules/asn1/lib/ber/types.js +36 -0
  61. package/vendor/node_modules/asn1/lib/ber/writer.js +317 -0
  62. package/vendor/node_modules/asn1/lib/index.js +20 -0
  63. package/vendor/node_modules/asn1/package.json +31 -0
  64. package/vendor/node_modules/bcrypt-pbkdf/CONTRIBUTING.md +13 -0
  65. package/vendor/node_modules/bcrypt-pbkdf/LICENSE +66 -0
  66. package/vendor/node_modules/bcrypt-pbkdf/README.md +45 -0
  67. package/vendor/node_modules/bcrypt-pbkdf/index.js +556 -0
  68. package/vendor/node_modules/bcrypt-pbkdf/package.json +15 -0
  69. package/vendor/node_modules/safer-buffer/LICENSE +21 -0
  70. package/vendor/node_modules/safer-buffer/Porting-Buffer.md +268 -0
  71. package/vendor/node_modules/safer-buffer/Readme.md +156 -0
  72. package/vendor/node_modules/safer-buffer/dangerous.js +58 -0
  73. package/vendor/node_modules/safer-buffer/package.json +34 -0
  74. package/vendor/node_modules/safer-buffer/safer.js +77 -0
  75. package/vendor/node_modules/safer-buffer/tests.js +406 -0
  76. package/vendor/node_modules/ssh2/LICENSE +19 -0
  77. package/vendor/node_modules/ssh2/README.md +1529 -0
  78. package/vendor/node_modules/ssh2/SFTP.md +413 -0
  79. package/vendor/node_modules/ssh2/lib/Channel.js +295 -0
  80. package/vendor/node_modules/ssh2/lib/agent.js +1123 -0
  81. package/vendor/node_modules/ssh2/lib/client.js +2176 -0
  82. package/vendor/node_modules/ssh2/lib/http-agents.js +84 -0
  83. package/vendor/node_modules/ssh2/lib/index.js +44 -0
  84. package/vendor/node_modules/ssh2/lib/keygen.js +582 -0
  85. package/vendor/node_modules/ssh2/lib/protocol/Protocol.js +2136 -0
  86. package/vendor/node_modules/ssh2/lib/protocol/SFTP.js +4052 -0
  87. package/vendor/node_modules/ssh2/lib/protocol/constants.js +356 -0
  88. package/vendor/node_modules/ssh2/lib/protocol/crypto/binding.gyp +23 -0
  89. package/vendor/node_modules/ssh2/lib/protocol/crypto/poly1305.js +43 -0
  90. package/vendor/node_modules/ssh2/lib/protocol/crypto/src/binding.cc +2300 -0
  91. package/vendor/node_modules/ssh2/lib/protocol/crypto.js +1602 -0
  92. package/vendor/node_modules/ssh2/lib/protocol/handlers.js +16 -0
  93. package/vendor/node_modules/ssh2/lib/protocol/handlers.misc.js +1285 -0
  94. package/vendor/node_modules/ssh2/lib/protocol/kex.js +1908 -0
  95. package/vendor/node_modules/ssh2/lib/protocol/keyParser.js +1484 -0
  96. package/vendor/node_modules/ssh2/lib/protocol/node-fs-compat.js +115 -0
  97. package/vendor/node_modules/ssh2/lib/protocol/utils.js +356 -0
  98. package/vendor/node_modules/ssh2/lib/protocol/zlib.js +255 -0
  99. package/vendor/node_modules/ssh2/lib/server.js +1380 -0
  100. package/vendor/node_modules/ssh2/lib/utils.js +336 -0
  101. package/vendor/node_modules/ssh2/package.json +49 -0
  102. package/vendor/node_modules/tweetnacl/AUTHORS.md +28 -0
  103. package/vendor/node_modules/tweetnacl/CHANGELOG.md +221 -0
  104. package/vendor/node_modules/tweetnacl/LICENSE +24 -0
  105. package/vendor/node_modules/tweetnacl/PULL_REQUEST_TEMPLATE.md +20 -0
  106. package/vendor/node_modules/tweetnacl/README.md +459 -0
  107. package/vendor/node_modules/tweetnacl/nacl-fast.js +2388 -0
  108. package/vendor/node_modules/tweetnacl/nacl-fast.min.js +2 -0
  109. package/vendor/node_modules/tweetnacl/nacl.d.ts +98 -0
  110. package/vendor/node_modules/tweetnacl/nacl.js +1175 -0
  111. package/vendor/node_modules/tweetnacl/nacl.min.js +1 -0
  112. package/vendor/node_modules/tweetnacl/package.json +58 -0
  113. package/vendor/xterm/LICENSE.addon-fit +19 -0
  114. package/vendor/xterm/LICENSE.xterm +21 -0
  115. package/vendor/xterm/README.md +9 -0
  116. package/vendor/xterm/addon-fit.js +2 -0
  117. package/vendor/xterm/xterm.css +218 -0
  118. package/vendor/xterm/xterm.js +2 -0
package/lib/routing.js ADDED
@@ -0,0 +1,695 @@
1
+ /**
2
+ * Workspace routing: marker files, the remote/host path bridge, and the
3
+ * `ctx.fs` patch that makes a marked directory behave like a local one.
4
+ *
5
+ * A remote workspace is a stub directory holding `.dsh-remote.json`:
6
+ * { version, connectionId, path: '/data/work/app', host: 'dev-box' }
7
+ * Everything under the stub resolves to `path` on the host, so tools, the file
8
+ * tree and the previews need no remote-specific code.
9
+ */
10
+ import { existsSync, readdirSync, readFileSync, rmSync } from 'node:fs'
11
+ import { realpath } from 'node:fs/promises'
12
+ import { dirname, isAbsolute, join, posix, relative, sep } from 'node:path'
13
+ import {
14
+ MARKER,
15
+ MAX_TEXT_BYTES,
16
+ attrsType,
17
+ attrsVersion,
18
+ ensureDir,
19
+ ensureRemoteDir,
20
+ errorText,
21
+ fsError,
22
+ normalizeRemotePath,
23
+ sftpCall,
24
+ shellQuote,
25
+ slugFor,
26
+ writeJsonFile,
27
+ } from './util.js'
28
+
29
+ /**
30
+ * Replace an existing remote file with an already-written temporary sibling.
31
+ *
32
+ * OpenSSH's sftp-server refuses a plain SSH_FXP_RENAME when the destination
33
+ * exists (SSH_FX_FAILURE), so a remote edit or overwrite used to fail while a
34
+ * fresh create worked. Prefer the posix-rename@openssh.com extension (atomic
35
+ * overwrite), then a plain rename for servers that do overwrite, and finally
36
+ * an in-place write for a conservative SFTP server.
37
+ *
38
+ * @param {object} sftp connected ssh2 SFTP session
39
+ * @param {string} temp temporary source path holding the new content
40
+ * @param {string} target destination path, possibly existing
41
+ * @param {Buffer} buffer the new content, for the in-place fallback
42
+ * @returns {Promise<'posix-rename' | 'rename' | 'direct-write'>} strategy used
43
+ */
44
+ export async function replaceRemoteFile(sftp, temp, target, buffer) {
45
+ if (typeof sftp.ext_openssh_rename === 'function') {
46
+ try {
47
+ await sftpCall(sftp, 'ext_openssh_rename', temp, target)
48
+ return 'posix-rename'
49
+ } catch {
50
+ /* extension unsupported or refused: fall through */
51
+ }
52
+ }
53
+ try {
54
+ await sftpCall(sftp, 'rename', temp, target)
55
+ return 'rename'
56
+ } catch {
57
+ /* target exists and the server refuses to overwrite: fall through */
58
+ }
59
+ await sftpCall(sftp, 'writeFile', target, buffer)
60
+ return 'direct-write'
61
+ }
62
+
63
+ export class Routing {
64
+ /**
65
+ * @param {object} options
66
+ * @param {string} options.workspaceRoot directory for new workspace stubs
67
+ * @param {string[]} options.legacyRoots older stub roots, adopted in place
68
+ * @param {(id: string) => import('./connection.js').RemoteHost | undefined} options.hostFor
69
+ * @param {(connectionId: string) => Promise<void>} [options.ensureConnected]
70
+ * @param {() => any} [options.getRegistry]
71
+ */
72
+ constructor(options) {
73
+ this.workspaceRoot = options.workspaceRoot
74
+ this.roots = [options.workspaceRoot, ...(options.legacyRoots ?? [])]
75
+ this.hostFor = options.hostFor
76
+ this.ensureConnected = options.ensureConnected ?? (async () => {})
77
+ this.getRegistry = options.getRegistry ?? (() => undefined)
78
+ this.markerCache = new Map()
79
+ this.rootsCache = { at: 0, rows: [] }
80
+ this.targetMeta = new WeakMap()
81
+ this.pathIndex = new Map()
82
+ }
83
+
84
+ // ------------------------------------------------------------- markers
85
+
86
+ readMarker(dir) {
87
+ const cached = this.markerCache.get(dir)
88
+ if (cached !== undefined && Date.now() - cached.at < 2000) return cached.value
89
+ let value = null
90
+ try {
91
+ const markerText = readFileSync(join(dir, MARKER), 'utf8')
92
+ const parsed = JSON.parse(markerText.charCodeAt(0) === 0xfeff ? markerText.slice(1) : markerText)
93
+ if (parsed && typeof parsed.connectionId === 'string' && typeof parsed.path === 'string') {
94
+ value = {
95
+ connectionId: parsed.connectionId,
96
+ path: normalizeRemotePath(parsed.path),
97
+ host: typeof parsed.host === 'string' ? parsed.host : '',
98
+ color: typeof parsed.color === 'string' ? parsed.color : '',
99
+ }
100
+ }
101
+ } catch {
102
+ value = null
103
+ }
104
+ this.markerCache.set(dir, { at: Date.now(), value })
105
+ return value
106
+ }
107
+
108
+ mappingFor(absPath) {
109
+ let dir = absPath
110
+ for (let depth = 0; depth < 14; depth += 1) {
111
+ const marker = this.readMarker(dir)
112
+ if (marker !== null) return { dir, marker }
113
+ const parent = dirname(dir)
114
+ if (parent === dir) return null
115
+ dir = parent
116
+ }
117
+ return null
118
+ }
119
+
120
+ /** Every marked stub across the new and legacy roots. */
121
+ knownWorkspaceRoots() {
122
+ if (Date.now() - this.rootsCache.at < 2000) return this.rootsCache.rows
123
+ const rows = []
124
+ for (const root of this.roots) {
125
+ if (!existsSync(root)) continue
126
+ try {
127
+ for (const connectionDir of readdirSync(root, { withFileTypes: true })) {
128
+ if (!connectionDir.isDirectory()) continue
129
+ const dir = join(root, connectionDir.name)
130
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
131
+ if (!entry.isDirectory()) continue
132
+ const stub = join(dir, entry.name)
133
+ const marker = this.readMarker(stub)
134
+ if (marker !== null) rows.push({ stub, ...marker })
135
+ }
136
+ }
137
+ } catch {
138
+ /* one unreadable root must not hide the others */
139
+ }
140
+ }
141
+ this.rootsCache = { at: Date.now(), rows }
142
+ return rows
143
+ }
144
+
145
+ invalidate() {
146
+ this.rootsCache = { at: 0, rows: [] }
147
+ this.markerCache.clear()
148
+ }
149
+
150
+ // ------------------------------------------------------------- path mapping
151
+
152
+ /**
153
+ * Resolve a tool path to { connectionId, path } on a remote host, or null
154
+ * when it belongs to the local machine.
155
+ */
156
+ resolveTarget(path, cwd) {
157
+ if (typeof path !== 'string' || path.length === 0) return null
158
+ const isPosix = (value) => typeof value === 'string' && value.startsWith('/') && !value.startsWith('//')
159
+ const cwdMapping = typeof cwd === 'string' && !isPosix(cwd) ? this.mappingFor(cwd) : null
160
+ // A POSIX cwd inside a registered remote workspace is a remote Session.
161
+ // A POSIX cwd outside every workspace (for example `/`, the local drive
162
+ // root) is not: local Windows paths must still resolve against the local
163
+ // machine, otherwise a remote Session could never switch back to a local
164
+ // workspace and local paths would be rejected.
165
+ const posixCwd = isPosix(cwd) ? posix.normalize(cwd) : null
166
+ const cwdRoot = posixCwd === null ? null : this.bestRoot(posixCwd)
167
+
168
+ if (posixCwd !== null && !isPosix(path)) {
169
+ // Remote development still needs local Windows resources: an explicit
170
+ // drive/backslash path means the local machine, even inside a remote
171
+ // Session. POSIX names resolve on the remote host, including paths that
172
+ // step outside the workspace (/tmp, /var, ...).
173
+ if (/^[A-Za-z]:[\\/]/.test(path) || path.includes('\\')) return null
174
+ const candidate = posix.normalize(posix.join(posixCwd, path))
175
+ const best = this.bestRoot(candidate)
176
+ if (best !== null) return { connectionId: best.connectionId, path: candidate }
177
+ if (cwdRoot !== null) return { connectionId: cwdRoot.connectionId, path: candidate }
178
+ return null
179
+ }
180
+ if (isPosix(path)) {
181
+ if (cwdMapping !== null) {
182
+ return { connectionId: cwdMapping.marker.connectionId, path: normalizeRemotePath(path) }
183
+ }
184
+ const normalized = normalizeRemotePath(path)
185
+ const best = this.bestRoot(normalized)
186
+ if (best !== null) return { connectionId: best.connectionId, path: normalized }
187
+ // A POSIX absolute path outside every workspace root inside a remote
188
+ // Session still names the remote machine (/tmp, /var, /home/...).
189
+ // Without this fallback the file tools silently resolved the same
190
+ // spelling against the local Windows drive (for example /tmp -> E:\tmp).
191
+ if (cwdRoot !== null) return { connectionId: cwdRoot.connectionId, path: normalized }
192
+ return null
193
+ }
194
+ const base = isAbsolute(path) ? path : join(cwdMapping === null ? cwd || process.cwd() : cwdMapping.dir, path)
195
+ const mapping = this.mappingFor(base)
196
+ if (mapping === null) {
197
+ const drive = /^([A-Za-z]):[\\/](.*)$/.exec(base)
198
+ if (drive !== null) {
199
+ const candidate = normalizeRemotePath(`/${drive[2].replace(/\\/g, '/')}`)
200
+ const best = this.bestRoot(candidate)
201
+ if (best !== null) return { connectionId: best.connectionId, path: candidate }
202
+ }
203
+ return null
204
+ }
205
+ const rel = relative(mapping.dir, base)
206
+ const remotePath =
207
+ rel === '' ? mapping.marker.path : posix.normalize(posix.join(mapping.marker.path, rel.split(sep).join('/')))
208
+ return { connectionId: mapping.marker.connectionId, path: remotePath }
209
+ }
210
+
211
+ bestRoot(candidate) {
212
+ const rows = this.knownWorkspaceRoots()
213
+ .filter((row) => candidate === row.path || candidate.startsWith(`${row.path}/`))
214
+ .sort((a, b) => b.path.length - a.path.length)
215
+ return rows.length === 0 ? null : rows[0]
216
+ }
217
+
218
+ remember(target, meta) {
219
+ this.targetMeta.set(target, meta)
220
+ this.pathIndex.set(target.targetKey, meta)
221
+ if (this.pathIndex.size > 2000) {
222
+ const first = this.pathIndex.keys().next().value
223
+ this.pathIndex.delete(first)
224
+ }
225
+ return target
226
+ }
227
+
228
+ metaOf(target) {
229
+ if (target === undefined || target === null) return undefined
230
+ const direct = this.targetMeta.get(target)
231
+ if (direct !== undefined) return direct
232
+ return this.pathIndex.get(target.targetKey)
233
+ }
234
+
235
+ // ------------------------------------------------------------- workspaces
236
+
237
+ listWorkspaces() {
238
+ return this.knownWorkspaceRoots().map((row) => ({
239
+ stub: row.stub,
240
+ connectionId: row.connectionId,
241
+ path: row.path,
242
+ host: row.host,
243
+ color: row.color,
244
+ folder: posix.basename(row.path) || '/',
245
+ title: `${row.host || 'remote'} · ${posix.basename(row.path) || '/'}`,
246
+ }))
247
+ }
248
+
249
+ async createWorkspace(connectionId, remotePath, record, options = {}) {
250
+ const host = this.hostFor(connectionId)
251
+ if (host === undefined) throw fsError('REMOTE_DECK_UNKNOWN', 'Connection does not exist.')
252
+ const sftp = host.requireSftp()
253
+ const target = normalizeRemotePath(remotePath)
254
+ await ensureRemoteDir(sftp, target)
255
+ const info = await sftpCall(sftp, 'stat', target)
256
+ if (attrsType(info) !== 'directory') throw fsError('REMOTE_DECK_NOT_DIR', `${target} is not a directory.`)
257
+
258
+ const stub = join(this.workspaceRoot, connectionId, slugFor(target))
259
+ ensureDir(stub)
260
+ writeJsonFile(join(stub, MARKER), {
261
+ version: 1,
262
+ connectionId,
263
+ path: target,
264
+ host: record?.name ?? host.record.name,
265
+ color: record?.color ?? '',
266
+ })
267
+ this.markerCache.delete(stub)
268
+ this.invalidate()
269
+
270
+ const fallbackTitle = `${record?.name ?? host.record.name} · ${posix.basename(target) || '/'}`
271
+ const title = typeof options.title === 'string' && options.title.trim().length > 0
272
+ ? options.title.trim().slice(0, 120)
273
+ : fallbackTitle
274
+ const registry = this.getRegistry()
275
+ let workspace
276
+ if (registry !== undefined) workspace = await registry.create(stub, title)
277
+ return {
278
+ stub,
279
+ path: target,
280
+ connectionId,
281
+ title,
282
+ workspace: workspace === undefined ? undefined : { id: workspace.id, path: workspace.path, title: workspace.title },
283
+ }
284
+ }
285
+
286
+ async removeWorkspace(stub) {
287
+ const registry = this.getRegistry()
288
+ if (registry === undefined) throw fsError('REMOTE_DECK_NO_REGISTRY', 'Workspace registry is unavailable.')
289
+ let entity = await registry.resolveByPath(stub).catch(() => undefined)
290
+ if (entity === undefined) {
291
+ const target = await realpath(stub).catch(() => stub)
292
+ for (const candidate of registry.list()) {
293
+ const canonical = await realpath(candidate.path).catch(() => candidate.path)
294
+ if (canonical.toLowerCase() === target.toLowerCase()) {
295
+ entity = candidate
296
+ break
297
+ }
298
+ }
299
+ }
300
+ if (entity === undefined) throw fsError('REMOTE_DECK_NOT_REGISTERED', 'This workspace is not in the DSH registry.')
301
+ await registry.delete(entity.id)
302
+ try {
303
+ const entries = readdirSync(stub)
304
+ if (entries.every((name) => name === MARKER)) rmSync(stub, { recursive: true, force: true })
305
+ } catch {
306
+ /* the stub may already be gone */
307
+ }
308
+ this.invalidate()
309
+ return { removed: true }
310
+ }
311
+
312
+ // ------------------------------------------------------------- remote text
313
+
314
+ async readText(host, remotePath) {
315
+ const sftp = host.requireSftp()
316
+ const info = await sftpCall(sftp, 'stat', remotePath)
317
+ if (attrsType(info) !== 'file') throw fsError('FS_NOT_REGULAR_FILE', `"${remotePath}" is not a regular file`)
318
+ if ((info.size || 0) > MAX_TEXT_BYTES) throw fsError('FS_TOO_LARGE', `"${remotePath}" exceeds the text read limit`)
319
+ const buffer = await sftpCall(sftp, 'readFile', remotePath)
320
+ if (buffer.includes(0)) throw fsError('FS_NOT_TEXT', `"${remotePath}" is binary, not UTF-8 text`)
321
+ try {
322
+ return new TextDecoder('utf-8', { fatal: true }).decode(buffer)
323
+ } catch {
324
+ throw fsError('FS_NOT_TEXT', `"${remotePath}" is not valid UTF-8 text`)
325
+ }
326
+ }
327
+
328
+ async writeText(host, remotePath, content) {
329
+ const sftp = host.requireSftp()
330
+ const dir = posix.dirname(remotePath)
331
+ const temp = posix.join(dir, `.dsh-tmp-${Date.now()}-${Math.random().toString(16).slice(2)}`)
332
+ const buffer = Buffer.from(content, 'utf8')
333
+ await sftpCall(sftp, 'writeFile', temp, buffer)
334
+ try {
335
+ await replaceRemoteFile(sftp, temp, remotePath, buffer)
336
+ } finally {
337
+ await sftpCall(sftp, 'unlink', temp).catch(() => {})
338
+ }
339
+ }
340
+
341
+ // ------------------------------------------------------------- fs patch
342
+
343
+ installFs(fsService) {
344
+ const routing = this
345
+ const originals = new Map()
346
+ const wrap = (name, factory) => {
347
+ const original = fsService[name]
348
+ if (typeof original !== 'function') return
349
+ originals.set(name, original)
350
+ fsService[name] = factory(original.bind(fsService))
351
+ }
352
+
353
+ const remoteFor = (path, cwd) => {
354
+ const mapped = this.resolveTarget(path, cwd)
355
+ if (mapped === null) return null
356
+ const host = this.hostFor(mapped.connectionId)
357
+ if (host === undefined) return null
358
+ return { host, path: mapped.path }
359
+ }
360
+
361
+ wrap('resolve', (original) => async (path, opts) => {
362
+ const remote = remoteFor(path, opts && opts.cwd)
363
+ if (remote === null) return original(path, opts)
364
+ await this.ensureConnected(remote.host.record.id)
365
+ return this.remember({ targetKey: `${remote.host.record.id}\u0000${remote.path}`, displayPath: remote.path }, {
366
+ connectionId: remote.host.record.id,
367
+ path: remote.path,
368
+ })
369
+ })
370
+
371
+ wrap('stat', (original) => async (target, signal) => {
372
+ const meta = this.metaOf(target)
373
+ if (meta === undefined) return original(target, signal)
374
+ const host = this.hostFor(meta.connectionId)
375
+ if (host === undefined) return undefined
376
+ try {
377
+ const attrs = await sftpCall(host.requireSftp(), 'stat', meta.path)
378
+ return { version: attrsVersion(attrs), type: attrsType(attrs), size: attrs.size || 0 }
379
+ } catch (error) {
380
+ if (error.code === 'FS_NOT_FOUND') return undefined
381
+ throw error
382
+ }
383
+ })
384
+
385
+ wrap('lstat', (original) => async (path, opts, signal) => {
386
+ const remote = remoteFor(path, opts && opts.cwd)
387
+ if (remote === null) return original(path, opts, signal)
388
+ try {
389
+ const attrs = await sftpCall(remote.host.requireSftp(), 'lstat', remote.path)
390
+ return { version: attrsVersion(attrs), type: attrsType(attrs), size: attrs.size || 0 }
391
+ } catch (error) {
392
+ if (error.code === 'FS_NOT_FOUND') return undefined
393
+ throw error
394
+ }
395
+ })
396
+
397
+ wrap('readText', (original) => async (target, signal) => {
398
+ const meta = this.metaOf(target)
399
+ if (meta === undefined) return original(target, signal)
400
+ return this.readText(this.hostFor(meta.connectionId), meta.path)
401
+ })
402
+
403
+ wrap('streamText', (original) => (target, signal) => {
404
+ const meta = this.metaOf(target)
405
+ if (meta === undefined) return original(target, signal)
406
+ const host = this.hostFor(meta.connectionId)
407
+ return (async function* stream() {
408
+ yield await routing.readText(host, meta.path)
409
+ })()
410
+ })
411
+
412
+ wrap('readBytes', (original) => async (target, signal, maxBytes) => {
413
+ const meta = this.metaOf(target)
414
+ if (meta === undefined) return original(target, signal, maxBytes)
415
+ const sftp = this.hostFor(meta.connectionId).requireSftp()
416
+ const info = await sftpCall(sftp, 'stat', meta.path)
417
+ if (attrsType(info) !== 'file') throw fsError('FS_NOT_REGULAR_FILE', 'not a regular file')
418
+ if ((info.size || 0) > maxBytes) throw fsError('FS_TOO_LARGE', `file is larger than the ${maxBytes}-byte cap`)
419
+ return await sftpCall(sftp, 'readFile', meta.path)
420
+ })
421
+
422
+ wrap('readByteRange', (original) => async (target, range, signal) => {
423
+ const meta = this.metaOf(target)
424
+ if (meta === undefined) return original(target, range, signal)
425
+ const offset = Math.max(0, Math.floor(Number(range?.offset) || 0))
426
+ const length = Math.max(0, Math.floor(Number(range?.length) || 0))
427
+ if (length === 0) return Buffer.alloc(0)
428
+ const host = this.hostFor(meta.connectionId)
429
+ const sftp = host.requireSftp()
430
+ const info = await sftpCall(sftp, 'stat', meta.path)
431
+ if (attrsType(info) !== 'file') throw fsError('FS_NOT_REGULAR_FILE', 'not a regular file')
432
+ const total = Number(info.size) || 0
433
+ const start = Math.min(offset, total)
434
+ const endExclusive = Math.min(offset + length, total)
435
+ if (endExclusive <= start) return Buffer.alloc(0)
436
+ return await new Promise((resolve, reject) => {
437
+ const chunks = []
438
+ let settled = false
439
+ let stream = null
440
+ const finish = (error, buffer) => {
441
+ if (settled) return
442
+ settled = true
443
+ if (signal !== undefined) signal.removeEventListener?.('abort', onAbort)
444
+ if (error) reject(error)
445
+ else resolve(buffer)
446
+ }
447
+ const onAbort = () => {
448
+ try {
449
+ stream?.destroy()
450
+ } catch {
451
+ /* ignore */
452
+ }
453
+ finish(fsError('REMOTE_DECK_ABORTED', 'remote read aborted'))
454
+ }
455
+ try {
456
+ stream = sftp.createReadStream(meta.path, { start, end: endExclusive - 1 })
457
+ } catch (error) {
458
+ finish(error)
459
+ return
460
+ }
461
+ stream.on('data', (chunk) => chunks.push(chunk))
462
+ stream.on('error', (error) => finish(error))
463
+ stream.on('end', () => finish(null, Buffer.concat(chunks)))
464
+ if (signal !== undefined) {
465
+ if (signal.aborted) onAbort()
466
+ else signal.addEventListener('abort', onAbort, { once: true })
467
+ }
468
+ })
469
+ })
470
+
471
+ wrap('listDir', (original) => async (target, signal) => {
472
+ const meta = this.metaOf(target)
473
+ if (meta === undefined) return original(target, signal)
474
+ const sftp = this.hostFor(meta.connectionId).requireSftp()
475
+ const entries = await sftpCall(sftp, 'readdir', meta.path)
476
+ return entries
477
+ .map((entry) => {
478
+ const childPath = posix.join(meta.path, entry.filename)
479
+ const type = attrsType(entry.attrs)
480
+ const row = {
481
+ name: entry.filename,
482
+ type,
483
+ target: { targetKey: childPath, displayPath: childPath },
484
+ version: attrsVersion(entry.attrs),
485
+ ...(type === 'file' ? { size: entry.attrs.size || 0 } : {}),
486
+ }
487
+ this.targetMeta.set(row.target, { connectionId: meta.connectionId, path: childPath })
488
+ return row
489
+ })
490
+ .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
491
+ })
492
+
493
+ wrap('writeText', (original) => async (target, content, expected, signal, sandboxPolicy) => {
494
+ const meta = this.metaOf(target)
495
+ if (meta === undefined) return original(target, content, expected, signal, sandboxPolicy)
496
+ const host = this.hostFor(meta.connectionId)
497
+ const sftp = host.requireSftp()
498
+ let existing
499
+ try {
500
+ existing = await sftpCall(sftp, 'stat', meta.path)
501
+ } catch (error) {
502
+ if (error.code !== 'FS_NOT_FOUND') throw error
503
+ existing = undefined
504
+ }
505
+ if (expected && expected.kind === 'replaceIfVersion') {
506
+ if (existing === undefined) throw fsError('FS_STALE_VERSION', `cannot write "${meta.path}": file no longer exists`)
507
+ if (attrsVersion(existing) !== expected.version) throw fsError('FS_STALE_VERSION', `cannot write "${meta.path}": file changed since it was read`)
508
+ } else if (expected && expected.kind === 'createIfAbsent' && existing !== undefined) {
509
+ throw fsError('FS_NOT_OBSERVED', `cannot overwrite existing "${meta.path}" without reading it first`)
510
+ }
511
+ const before = existing !== undefined && (existing.size || 0) <= 1024 * 1024
512
+ ? await this.readText(host, meta.path).catch(() => null)
513
+ : null
514
+ await this.writeText(host, meta.path, content)
515
+ const after = await sftpCall(sftp, 'stat', meta.path)
516
+ return {
517
+ operation: existing === undefined ? 'create' : 'update',
518
+ version: attrsVersion(after),
519
+ before,
520
+ after: content.replace(/\r\n/g, '\n'),
521
+ }
522
+ })
523
+
524
+ wrap('editText', (original) => async (target, edit, expected, signal, sandboxPolicy) => {
525
+ const meta = this.metaOf(target)
526
+ if (meta === undefined) return original(target, edit, expected, signal, sandboxPolicy)
527
+ const host = this.hostFor(meta.connectionId)
528
+ const sftp = host.requireSftp()
529
+ const info = await sftpCall(sftp, 'stat', meta.path)
530
+ if (expected && attrsVersion(info) !== expected.version) {
531
+ throw fsError('FS_STALE_VERSION', `cannot edit "${meta.path}": file changed since it was read`)
532
+ }
533
+ const originalText = await this.readText(host, meta.path)
534
+ const normalized = originalText.replace(/\r\n/g, '\n')
535
+ const oldNorm = String(edit.oldString).replace(/\r\n/g, '\n')
536
+ const newNorm = String(edit.newString).replace(/\r\n/g, '\n')
537
+ if (oldNorm.length === 0) throw fsError('FS_EDIT_NOT_FOUND', 'old_string must be a non-empty string')
538
+ const count = normalized.split(oldNorm).length - 1
539
+ if (count === 0) throw fsError('FS_EDIT_NOT_FOUND', `old_string was not found in "${meta.path}"`)
540
+ if (edit.replaceAll !== true && count > 1) throw fsError('FS_AMBIGUOUS_EDIT', `old_string matched ${count} times in "${meta.path}"`)
541
+ const replaced = normalized.split(oldNorm).join(newNorm)
542
+ const output = originalText.includes('\r\n') ? replaced.replace(/\n/g, '\r\n') : replaced
543
+ await this.writeText(host, meta.path, output)
544
+ const after = await sftpCall(sftp, 'stat', meta.path)
545
+ return { version: attrsVersion(after), before: originalText, after: replaced }
546
+ })
547
+
548
+ wrap('watch', (original) => (target, changed, signal) => {
549
+ const meta = this.metaOf(target)
550
+ if (meta === undefined) return original(target, changed, signal)
551
+ let closed = false
552
+ let timer = null
553
+ let last
554
+ const poll = async () => {
555
+ if (closed) return
556
+ try {
557
+ const sftp = this.hostFor(meta.connectionId).requireSftp()
558
+ const attrs = await sftpCall(sftp, 'stat', meta.path)
559
+ const version = attrsVersion(attrs)
560
+ if (last !== undefined && last !== version) changed()
561
+ last = version
562
+ } catch {
563
+ /* transient poll failure: keep the watcher alive */
564
+ }
565
+ if (!closed) timer = setTimeout(poll, 1500)
566
+ }
567
+ return (async () => {
568
+ signal.throwIfAborted()
569
+ await poll()
570
+ return async () => {
571
+ closed = true
572
+ if (timer !== null) clearTimeout(timer)
573
+ }
574
+ })()
575
+ })
576
+
577
+ wrap('contains', (original) => (parent, child) => {
578
+ const parentMeta = this.metaOf(parent)
579
+ const childMeta = this.metaOf(child)
580
+ if (parentMeta === undefined || childMeta === undefined) return original(parent, child)
581
+ if (parentMeta.connectionId !== childMeta.connectionId) return false
582
+ const rel = posix.relative(parentMeta.path, childMeta.path)
583
+ return rel === '' || (rel !== '..' && !rel.startsWith('../'))
584
+ })
585
+
586
+ wrap('fileUrl', (original) => (target) => {
587
+ const meta = this.metaOf(target)
588
+ if (meta === undefined) return original(target)
589
+ return `file://${encodeURI(meta.path)}`
590
+ })
591
+
592
+ wrap('processPath', (original) => (target) => {
593
+ const meta = this.metaOf(target)
594
+ if (meta === undefined) return original(target)
595
+ return meta.path
596
+ })
597
+
598
+ wrap('patchText', (original) => async (target, ...rest) => {
599
+ const meta = this.metaOf(target)
600
+ if (meta === undefined) return original(target, ...rest)
601
+ throw fsError('REMOTE_DECK_UNSUPPORTED', `apply_patch is not supported on remote workspaces yet; edit or write "${meta.path}" instead`)
602
+ })
603
+
604
+ wrap('deleteFile', (original) => async (target, ...rest) => {
605
+ const meta = this.metaOf(target)
606
+ if (meta === undefined) return original(target, ...rest)
607
+ const sftp = this.hostFor(meta.connectionId).requireSftp()
608
+ try {
609
+ await sftpCall(sftp, 'unlink', meta.path)
610
+ } catch (error) {
611
+ if (error.code !== 'FS_NOT_FOUND') throw error
612
+ }
613
+ return { operation: 'delete' }
614
+ })
615
+
616
+ wrap('moveFile', (original) => async (source, destination, ...rest) => {
617
+ const sourceMeta = this.metaOf(source)
618
+ const destinationMeta = this.metaOf(destination)
619
+ if (sourceMeta === undefined && destinationMeta === undefined) return original(source, destination, ...rest)
620
+ if (sourceMeta === undefined || destinationMeta === undefined || sourceMeta.connectionId !== destinationMeta.connectionId) {
621
+ throw fsError('REMOTE_DECK_UNSUPPORTED', 'moving files between the local machine and a remote host is not supported')
622
+ }
623
+ const sftp = this.hostFor(sourceMeta.connectionId).requireSftp()
624
+ try {
625
+ await sftpCall(sftp, 'ext_openssh_rename', sourceMeta.path, destinationMeta.path)
626
+ } catch {
627
+ await sftpCall(sftp, 'rename', sourceMeta.path, destinationMeta.path)
628
+ }
629
+ return { operation: 'move' }
630
+ })
631
+
632
+ wrap('processPathFromHostPath', (original) => (hostPath) => {
633
+ const mapped = this.resolveTarget(hostPath, undefined)
634
+ return mapped === null ? original(hostPath) : mapped.path
635
+ })
636
+
637
+ return () => {
638
+ for (const [name, original] of originals) {
639
+ try {
640
+ fsService[name] = original
641
+ } catch {
642
+ /* ignore */
643
+ }
644
+ }
645
+ originals.clear()
646
+ }
647
+ }
648
+
649
+ /** Replace the local ripgrep process with one running on the remote host. */
650
+ makeRemoteRipgrep(host, cwd, args, spec) {
651
+ let stdout = ''
652
+ let stderr = ''
653
+ let settle
654
+ const done = new Promise((resolve) => {
655
+ settle = resolve
656
+ })
657
+ let stdoutLossy = false
658
+ let stderrLossy = false
659
+ const abort = new AbortController()
660
+ const signal = spec.signal === undefined
661
+ ? abort.signal
662
+ : (typeof AbortSignal.any === 'function' ? AbortSignal.any([spec.signal, abort.signal]) : spec.signal)
663
+ const configured = Number(spec?.stdio?.stdout?.maxBytes)
664
+ const cap = Number.isFinite(configured) && configured > 0 ? configured : 8 * 1024 * 1024
665
+ const command = `rg ${args.map(shellQuote).join(' ')}`
666
+ host
667
+ .runCommand(command, cwd, { signal, maxBytes: cap, timeoutMs: 120000 })
668
+ .then((result) => {
669
+ stdout = result.stdout
670
+ stderr = result.stderr
671
+ stdoutLossy = result.truncatedOut === true
672
+ stderrLossy = result.truncatedErr === true
673
+ settle({ exitCode: result.code, signal: null })
674
+ })
675
+ .catch((error) => {
676
+ stderr = errorText(error)
677
+ settle({ exitCode: 255, signal: null })
678
+ })
679
+ return {
680
+ done,
681
+ collected: {
682
+ stdout: { readFrom: () => ({ text: stdout, lossy: stdoutLossy }) },
683
+ stderr: { readFrom: () => ({ text: stderr, lossy: stderrLossy }) },
684
+ },
685
+ kill() {
686
+ try {
687
+ abort.abort()
688
+ } catch {
689
+ /* ignore */
690
+ }
691
+ settle({ exitCode: 130, signal: null })
692
+ },
693
+ }
694
+ }
695
+ }