dsh-remote 0.8.92 → 0.8.93

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 (56) hide show
  1. package/LICENSE +21 -21
  2. package/README.en.md +369 -369
  3. package/README.md +354 -354
  4. package/cordis.patch.yml +9 -9
  5. package/lib/audit.js +45 -45
  6. package/lib/binding.js +172 -172
  7. package/lib/client.js +4647 -4647
  8. package/lib/credential.js +270 -270
  9. package/lib/errors.js +141 -141
  10. package/lib/exec-job.js +242 -242
  11. package/lib/file-reference.js +457 -457
  12. package/lib/forwards.js +258 -258
  13. package/lib/host-api.js +822 -822
  14. package/lib/hostkey.js +108 -108
  15. package/lib/http-transport.js +201 -201
  16. package/lib/ignore.js +202 -202
  17. package/lib/index.js +4488 -4488
  18. package/lib/instructions-dynamic.js +415 -415
  19. package/lib/instructions.js +288 -288
  20. package/lib/open-folder.js +56 -56
  21. package/lib/openssh.js +940 -940
  22. package/lib/paths.js +292 -292
  23. package/lib/pool.js +1029 -1029
  24. package/lib/posix-shell.cjs +34 -34
  25. package/lib/registry.js +296 -296
  26. package/lib/remote-fs.js +173 -173
  27. package/lib/remote-sandbox.js +183 -183
  28. package/lib/remote-shell-child.cjs +397 -397
  29. package/lib/remote-shell.js +697 -697
  30. package/lib/remote-skills.js +312 -312
  31. package/lib/routes-audit.js +58 -58
  32. package/lib/routes-forwards.js +72 -72
  33. package/lib/routes-fs.js +251 -251
  34. package/lib/routes-machines.js +186 -186
  35. package/lib/routes-misc.js +187 -187
  36. package/lib/routes-term.js +169 -169
  37. package/lib/routes-update.js +143 -143
  38. package/lib/routes-web-attach.js +112 -112
  39. package/lib/routes-workspace.js +312 -312
  40. package/lib/search.js +235 -235
  41. package/lib/sftp-surface.js +119 -119
  42. package/lib/sshconfig.js +779 -779
  43. package/lib/sync.js +350 -350
  44. package/lib/tasks.js +95 -95
  45. package/lib/telemetry.js +247 -247
  46. package/lib/terminal.js +205 -205
  47. package/lib/tui/flow.js +130 -130
  48. package/lib/tui/format.js +380 -380
  49. package/lib/tui/i18n.js +350 -350
  50. package/lib/tui/index.js +531 -531
  51. package/lib/tui/provider.js +344 -344
  52. package/lib/tui/scene.js +986 -986
  53. package/lib/update.js +490 -472
  54. package/lib/web-attach.js +860 -860
  55. package/lib/workspace-cleanup.js +337 -337
  56. package/package.json +103 -103
package/lib/host-api.js CHANGED
@@ -1,822 +1,822 @@
1
- // Host-side in-process API for OTHER plugins (the TUI layer), exposed as
2
- // `ctx.dshRemote` from `apply()`.
3
- //
4
- // Why a service instead of a second implementation:
5
- // Every mutable piece of dsh-remote state (the active pool, the per-machine
6
- // pools, the in-memory `machines` snapshot, `currentId`, the workspace
7
- // mirror, forwards/terminals) lives inside `apply()`'s closure. A consumer
8
- // that re-read `machines.json` or dialled its own SSH pool would hold a stale
9
- // registry snapshot, open a second TCP connection per host, and race
10
- // `saveMachines()`'s whole-file rewrite against this one. `createHostApi()`
11
- // therefore takes those closure functions as `deps` and only reshapes their
12
- // results — it never imports cordis, never opens a pool and never touches
13
- // the registry file.
14
- //
15
- // Contract (docs/tui.md §3, `apiVersion: 1`):
16
- // · every method is async and returns PURE DATA (no pool / client / sftp
17
- // handles, no passwords, no passphrases);
18
- // · failures THROW one `Error` carrying a semantic `.code`; they never return
19
- // `{ok:false}` (a caller's `if (res.ok)` would swallow the reason);
20
- // · `error.message` is already the user-facing Chinese sentence
21
- // (`friendlyMessage` from lib/errors.js, idempotent);
22
- // · the API has its own tiny emitter: an event fires after THIS object's
23
- // mutations. It deliberately does not splice itself into the SSH pool's
24
- // single-slot `onReady`/`onCloseHook` (the forwards manager owns those).
25
- import { classifyError, friendlyMessage } from './errors.js'
26
- import { joinRemotePath, normalizeRemotePath, remoteDirname, toDisplayPath, remoteWorkspaceTitle } from './paths.js'
27
- import { listDirStructured, listRemoteDrives } from './remote-fs.js'
28
- import {
29
- deleteMirrorTree,
30
- deleteSessionsFor,
31
- dirSizeBytes,
32
- listMirrorEntries,
33
- listSessionDirs,
34
- validateMirror,
35
- } from './workspace-cleanup.js'
36
-
37
-
38
- /** Contract version. Consumers check `api.apiVersion === 1` before use. */
39
- const API_VERSION = 1
40
-
41
- /** Error codes the contract allows (`docs/tui.md` §3). */
42
- const API_CODES = new Set([
43
- 'MACHINE_NOT_FOUND',
44
- 'NO_ACTIVE_MACHINE',
45
- 'NOT_A_DIRECTORY',
46
- 'AUTH',
47
- 'CREDENTIALS',
48
- 'HOSTKEY',
49
- 'NETWORK',
50
- 'TIMEOUT',
51
- 'SFTP',
52
- 'UNSUPPORTED',
53
- 'LOCAL_SESSION',
54
- 'VALIDATION',
55
- 'WORKSPACE_BUSY',
56
- 'INTERNAL',
57
- ])
58
-
59
- /** One coded error. `extra` carries optional machine identity (`host`/`port`)
60
- * so a UI can point at the failing row. */
61
- function apiError(code, message, extra = {}) {
62
- const err = new Error(message)
63
- err.code = API_CODES.has(code) ? code : 'INTERNAL'
64
- if (extra && typeof extra === 'object') Object.assign(err, extra)
65
- return err
66
- }
67
-
68
- /** Map whatever a dep throws onto the contract's error vocabulary.
69
- *
70
- * Coded errors thrown by lib/index.js deps (and by this module) pass through
71
- * untouched; HTTP-layer codes (`httpStatus`) are translated, because the
72
- * same closures answer the web routes; everything else is classified with
73
- * lib/errors.js, which is what makes `AUTH` / `NETWORK` / `HOSTKEY` /
74
- * `TIMEOUT` / `SFTP` / `CREDENTIALS` actionable instead of `INTERNAL`. */
75
- function asApiError(err, opts = {}) {
76
- if (!err) return apiError('INTERNAL', 'unknown error')
77
- if (err.code && API_CODES.has(err.code)) return err
78
- const status = Number(err.httpStatus) || 0
79
- if (status === 400 || err.code === 'HOST_REQUIRED') {
80
- // The route layer throws English strings (`host required`); the contract
81
- // promises a user-facing Chinese sentence, so translate the known one and
82
- // prefix the rest rather than leaking raw English into the TUI footer.
83
- const raw = String(err.message || err)
84
- const message = err.code === 'HOST_REQUIRED' ? '缺少主机地址(host 必填)' : `请求参数不可用:${raw}`
85
- return apiError('VALIDATION', message)
86
- }
87
- if (status === 404) return apiError('MACHINE_NOT_FOUND', friendlyMessage(err, opts))
88
- if (status === 403) return apiError('LOCAL_SESSION', String(err.message || err))
89
- if (status === 409) return apiError('NO_ACTIVE_MACHINE', String(err.message || err))
90
- const category = classifyError(err, opts).category
91
- const map = {
92
- auth: 'AUTH',
93
- network: 'NETWORK',
94
- hostkey: 'HOSTKEY',
95
- timeout: 'TIMEOUT',
96
- sftp: 'SFTP',
97
- credentials: 'CREDENTIALS',
98
- }
99
- const code = map[category] || 'INTERNAL'
100
- const out = apiError(code, friendlyMessage(err, opts), {
101
- host: err.host != null ? err.host : opts.host,
102
- port: err.port != null ? err.port : opts.port,
103
- cause: err,
104
- })
105
- return out
106
- }
107
-
108
- /** Defensive secret strip for anything that leaves this module.
109
- *
110
- * The deps hand back views the web settings page already receives
111
- * (`sanitizeMachine` — password/passphrase replaced by booleans), so this is
112
- * a belt-and-braces pass: a future field added to the record must not leak
113
- * through the in-process API by accident. It also makes the promise
114
- * "no secret ever leaves" testable by seeding a fake deps that returns the
115
- * raw record.
116
- *
117
- * @param {*} value - plain data from a dep.
118
- * @returns {*} a deep copy with `password` / `passphrase` keys removed.
119
- */
120
- function scrub(value) {
121
- if (Array.isArray(value)) return value.map(scrub)
122
- if (value && typeof value === 'object') {
123
- const out = {}
124
- for (const [k, v] of Object.entries(value)) {
125
- if (k === 'password' || k === 'passphrase') continue
126
- out[k] = scrub(v)
127
- }
128
- return out
129
- }
130
- return value
131
- }
132
-
133
- /** The Status shape the TUI contract names (`machineId`), derived from the
134
- * host's own snapshot (`currentId`). Pure data either way. */
135
- function asStatus(snapshot) {
136
- const s = (snapshot && typeof snapshot === 'object') ? { ...snapshot } : {}
137
- return { ...scrub(s), machineId: s.currentId == null ? null : String(s.currentId) }
138
- }
139
-
140
- /** Map the SFTP entry types lib/remote-fs.js produces onto the contract's
141
- * four-value vocabulary. */
142
- function publicEntryType(type) {
143
- if (type === 'dir') return 'dir'
144
- if (type === 'symlink' || type === 'link') return 'link'
145
- if (type === 'file') return 'file'
146
- return 'other'
147
- }
148
-
149
- /** Parent directory for a DirListing, or null for a filesystem root. */
150
- function parentOf(p, platform) {
151
- const norm = normalizeRemotePath(p)
152
- if (norm === '/' || /^[a-zA-Z]:\\?$/.test(norm) || /^\\\\[^\\]+\\[^\\]+$/.test(norm)) return null
153
- return toDisplayPath(remoteDirname(norm), platform)
154
- }
155
-
156
- /**
157
- * Build the host API object.
158
- *
159
- * @param {object} deps - closure functions supplied by lib/index.js. Required
160
- * keys (all throw `INTERNAL` here when missing, never at require time):
161
- * · `listMachinesView()` → `{machines, currentId}` (sanitized views);
162
- * · `upsertMachineRecord(body)` → `{machine, machines, currentId, warning?,
163
- * warningDetail?, sshConfigWarning?}`; throws HOST_REQUIRED / coded errors;
164
- * · `removeMachineRecord(id)` → `{machines, currentId}`; throws
165
- * MACHINE_NOT_FOUND;
166
- * · `setCurrentForApi(id|null)`; throws MACHINE_NOT_FOUND;
167
- * · `connectMachine({machineId, persist})` → Status (throws classified);
168
- * · `probeMachineRecord(body)` → ProbeResult (throws classified);
169
- * · `statusSnapshot()` → Status snapshot;
170
- * · `resolveDirBinding({machineId, sessionId, local})` → `{pool, ws, bound,
171
- * machine}` (throws MACHINE_NOT_FOUND / NO_ACTIVE_MACHINE);
172
- * · `listRemoteProjects()` → mirror registry entries (+machineId);
173
- * · `revealMirrorFolderRecord()` → `{path}` (opens `remote-workspaces` in the file manager);
174
- * · `resolveMachine(machineId?)` → `{record, machineId, name, host, port,
175
- * username, alias}` (resolved connect identity);
176
- * · `ensureMirror(remotePath, host, username, port, extra)` → local dir;
177
- * · `registerMirroredWorkspace(localDir, remotePath, record)`;
178
- * · `checkRemoteDir(remotePath, machineId?)` → boolean (SSH stat).
179
- * @returns {object} the `ctx.dshRemote` value.
180
- */
181
- export function createHostApi(deps = {}) {
182
- const listeners = new Set()
183
-
184
- const need = (name) => {
185
- const fn = deps[name]
186
- if (typeof fn !== 'function') {
187
- throw apiError('INTERNAL', `dshRemote: host dependency "${name}" is missing`)
188
- }
189
- return fn
190
- }
191
-
192
- /** Fire one lifecycle event. Listener failures are contained: a broken TUI
193
- * subscriber must never break a machine save. */
194
- const emit = (type) => {
195
- for (const listener of [...listeners]) {
196
- try { listener({ type }) } catch { /* subscriber is on its own */ }
197
- }
198
- }
199
-
200
- const status = async () => {
201
- const snapshot = await need('statusSnapshot')()
202
- return asStatus(snapshot)
203
- }
204
-
205
- /** Project the record layer's grouping fields onto the contract's `group`.
206
- *
207
- * The registry has no `group` column: `normalizeMachineGroup()` writes
208
- * `environment` / `location` / `description` / `tags` (lib/registry.js),
209
- * and the Web settings page edits `environment` as the host's group label.
210
- * The TUI form exposes ONE text field, so the contract's `group` is that
211
- * `environment` value — without this projection the form would save into a
212
- * field the host never persists.
213
- *
214
- * @param {object} machine - a sanitized record view.
215
- * @returns {object} the same view plus a string `group`.
216
- */
217
- const withGroup = (machine) => {
218
- if (!machine || typeof machine !== 'object') return machine
219
- const group = machine.group !== undefined && machine.group !== null
220
- ? machine.group
221
- : machine.environment
222
- return { ...machine, group: group == null ? '' : String(group) }
223
- }
224
- /** Inverse of {@link withGroup} for a write patch. */
225
- const withGroupPatch = (patch) => {
226
- const body = { ...patch }
227
- if (body.group !== undefined && body.environment === undefined) body.environment = body.group
228
- delete body.group
229
- return body
230
- }
231
-
232
- const listMachines = async () => {
233
- const view = await need('listMachinesView')()
234
- return {
235
- machines: scrub(Array.isArray(view && view.machines) ? view.machines : []).map(withGroup),
236
- currentId: view && view.currentId != null ? String(view.currentId) : null,
237
- }
238
- }
239
-
240
- const upsertMachine = async (patch = {}) => {
241
- const body = withGroupPatch({ ...(patch && typeof patch === 'object' ? patch : {}) })
242
- let result
243
- try {
244
- result = await need('upsertMachineRecord')(body)
245
- } catch (err) {
246
- throw asApiError(err, { host: body.host, port: body.port })
247
- }
248
- emit('machines')
249
- // Non-fatal problems the save could not throw for: the OS secure store
250
- // refused the password, or ~/.ssh/config already names this host with a
251
- // user-owned block. They are collected into one string list per contract.
252
- const warnings = []
253
- if (result && result.warning) {
254
- warnings.push(String(result.warningDetail ? `${result.warning}: ${result.warningDetail}` : result.warning))
255
- }
256
- if (result && result.sshConfigWarning) warnings.push(String(result.sshConfigWarning))
257
- return {
258
- machine: withGroup(scrub(result && result.machine)),
259
- machines: scrub(Array.isArray(result && result.machines) ? result.machines : []).map(withGroup),
260
- currentId: result && result.currentId != null ? String(result.currentId) : null,
261
- warnings,
262
- }
263
- }
264
-
265
- const removeMachine = async (id) => {
266
- let result
267
- try {
268
- result = await need('removeMachineRecord')(String(id == null ? '' : id))
269
- } catch (err) {
270
- throw asApiError(err)
271
- }
272
- emit('machines')
273
- emit('status')
274
- return {
275
- machines: scrub(Array.isArray(result && result.machines) ? result.machines : []).map(withGroup),
276
- currentId: result && result.currentId != null ? String(result.currentId) : null,
277
- }
278
- }
279
-
280
- const setCurrent = async (id) => {
281
- const clean = id == null || String(id).trim() === '' ? null : String(id).trim()
282
- try {
283
- await need('setCurrentForApi')(clean)
284
- } catch (err) {
285
- throw asApiError(err)
286
- }
287
- emit('status')
288
- return status()
289
- }
290
-
291
- const connect = async (opts = {}) => {
292
- const o = opts && typeof opts === 'object' ? opts : {}
293
- let snapshot
294
- try {
295
- snapshot = await need('connectMachine')({
296
- machineId: o.machineId == null ? undefined : String(o.machineId),
297
- persist: o.persist !== false,
298
- })
299
- } catch (err) {
300
- throw asApiError(err)
301
- }
302
- emit('status')
303
- return asStatus(snapshot)
304
- }
305
-
306
- const probeMachine = async (patch = {}) => {
307
- const body = { ...(patch && typeof patch === 'object' ? patch : {}) }
308
- try {
309
- return await need('probeMachineRecord')(body)
310
- } catch (err) {
311
- throw asApiError(err, { host: body.host, port: body.port })
312
- }
313
- }
314
-
315
- /** Resolve which remote pool a listing should run against.
316
- * Addressing priority (contract): machineId > the active machine. */
317
- const bindingForDir = async (opts = {}) => {
318
- const o = opts && typeof opts === 'object' ? opts : {}
319
- try {
320
- return await need('resolveDirBinding')({
321
- machineId: o.machineId == null ? undefined : String(o.machineId),
322
- sessionId: o.sessionId == null ? undefined : String(o.sessionId),
323
- local: o.local == null ? undefined : String(o.local),
324
- })
325
- } catch (err) {
326
- throw asApiError(err)
327
- }
328
- }
329
-
330
- const listDir = async (opts = {}) => {
331
- const o = opts && typeof opts === 'object' ? opts : {}
332
- const binding = await bindingForDir(o)
333
- const pool = binding && binding.pool
334
- if (!pool || typeof pool.detect !== 'function') {
335
- throw apiError('INTERNAL', 'dshRemote.listDir: no remote pool resolved')
336
- }
337
- const machine = {
338
- id: (binding.machine && binding.machine.id) || '',
339
- name: (binding.machine && binding.machine.name) || '',
340
- host: (binding.machine && binding.machine.host) || '',
341
- port: Number(binding.machine && binding.machine.port) || 22,
342
- username: (binding.machine && binding.machine.username) || '',
343
- }
344
- try {
345
- await pool.detect()
346
- const win = pool.platform === 'windows'
347
- const requested = o.path != null && String(o.path).trim() !== '' ? String(o.path) : (binding.ws || '')
348
- const canon = normalizeRemotePath(requested)
349
- // A Windows remote's filesystem root is a drive list, exactly like /ls.
350
- if (canon === '/' || canon === '') {
351
- if (win || pool.platform !== 'posix') {
352
- const drives = await listRemoteDrives(pool)
353
- if (drives.length) {
354
- return {
355
- path: '',
356
- parent: null,
357
- platform: 'windows',
358
- items: drives.map((d) => ({
359
- name: String(d.name || ''),
360
- path: String(d.path || ''),
361
- type: 'dir',
362
- size: 0,
363
- mtime: 0,
364
- })),
365
- machine,
366
- }
367
- }
368
- }
369
- if (win) return { path: '', parent: null, platform: 'windows', items: [], machine }
370
- }
371
- const sftp = await pool.sftp()
372
- const out = await listDirStructured(sftp, canon)
373
- const platform = win ? 'windows' : 'posix'
374
- return {
375
- path: toDisplayPath(out.path, pool.platform),
376
- parent: parentOf(out.path, pool.platform),
377
- platform,
378
- items: out.items.map((it) => ({
379
- name: String(it.name),
380
- path: toDisplayPath(joinRemotePath(canon, it.name), pool.platform),
381
- type: publicEntryType(it.type),
382
- size: typeof it.size === 'number' ? it.size : 0,
383
- mtime: typeof it.mtime === 'number' ? it.mtime : 0,
384
- })),
385
- machine,
386
- }
387
- } catch (err) {
388
- throw asApiError(err, { host: machine.host, port: machine.port })
389
- }
390
- }
391
-
392
- const listRemoteProjects = async () => {
393
- const projects = await need('listRemoteProjects')()
394
- return (Array.isArray(projects) ? projects : []).map((p) => ({
395
- dir: String((p && p.dir) || ''),
396
- host: String((p && p.host) || ''),
397
- port: Number(p && p.port) || 22,
398
- username: String((p && p.username) || ''),
399
- remotePath: String((p && p.remotePath) || ''),
400
- alias: String((p && p.alias) || ''),
401
- name: String((p && p.name) || ''),
402
- machineId: p && p.machineId != null ? String(p.machineId) : null,
403
- }))
404
- }
405
-
406
- /** Shared body of ensureRemoteWorkspace / pickRemoteWorkspace.
407
- * Deliberately NO SSH: it only touches the local mirror directory. */
408
- const ensureWorkspace = async (opts = {}) => {
409
- const o = opts && typeof opts === 'object' ? opts : {}
410
- const raw = String(o.remotePath == null ? '' : o.remotePath).trim()
411
- if (!raw) throw apiError('NOT_A_DIRECTORY', '远程路径不能为空')
412
- const remotePath = normalizeRemotePath(raw)
413
- let machine
414
- try {
415
- machine = await need('resolveMachine')(o.machineId == null ? undefined : String(o.machineId))
416
- } catch (err) {
417
- throw asApiError(err)
418
- }
419
- const extra = machine.alias ? { alias: machine.alias } : {}
420
- let localMirror
421
- try {
422
- localMirror = await need('ensureMirror')(remotePath, machine.host, machine.username, machine.port, extra)
423
- } catch (err) {
424
- throw asApiError(err, { host: machine.host, port: machine.port })
425
- }
426
- const title = remoteWorkspaceTitle(remotePath, { name: machine.name, host: machine.host })
427
- let workspace
428
- if (o.register !== false) {
429
- try {
430
- const created = await need('registerMirroredWorkspace')(localMirror, remotePath, machine.record)
431
- if (created && created.id != null) {
432
- workspace = { id: String(created.id), title: String(created.title || title) }
433
- }
434
- } catch {
435
- // Registration is explicitly best-effort in the host (older harness
436
- // without ctx.workspaceRegistry must not fail the mirror); the mirror
437
- // and its meta are already on disk.
438
- }
439
- }
440
- return {
441
- machineId: machine.machineId == null ? '' : String(machine.machineId),
442
- remotePath,
443
- localMirror,
444
- title,
445
- ...(workspace ? { workspace } : {}),
446
- }
447
- }
448
-
449
- const ensureRemoteWorkspace = async (opts = {}) => {
450
- const result = await ensureWorkspace(opts)
451
- emit('status')
452
- return result
453
- }
454
-
455
- const pickRemoteWorkspace = async (opts = {}) => {
456
- const o = opts && typeof opts === 'object' ? opts : {}
457
- const raw = String(o.remotePath == null ? '' : o.remotePath).trim()
458
- if (!raw) throw apiError('NOT_A_DIRECTORY', '远程路径不能为空')
459
- const remotePath = normalizeRemotePath(raw)
460
- let okDir = false
461
- try {
462
- okDir = await need('checkRemoteDir')(remotePath, o.machineId == null ? undefined : String(o.machineId))
463
- } catch (err) {
464
- throw asApiError(err)
465
- }
466
- if (!okDir) throw apiError('NOT_A_DIRECTORY', `远程路径不是目录(或无法访问):${remotePath}`)
467
- const result = await ensureWorkspace({
468
- machineId: o.machineId,
469
- remotePath,
470
- register: o.registerWorkspace !== false,
471
- })
472
- emit('status')
473
- return { ...result, status: await status() }
474
- }
475
-
476
- /** The workspace registry, when the composition serves one. */
477
- const registryService = () => {
478
- try {
479
- const registry = need('workspaceRegistry')()
480
- return registry && typeof registry === 'object' ? registry : undefined
481
- } catch {
482
- return undefined
483
- }
484
- }
485
-
486
- /** Quick liveness probe: in-process only unless `deep` is requested. */
487
- const liveCheck = async (sessionId, dir, opts = {}) => {
488
- try {
489
- const fn = deps.isSessionLive
490
- if (typeof fn !== 'function') return false
491
- return await fn(String(sessionId), String(dir), opts) === true
492
- } catch {
493
- return false
494
- }
495
- }
496
-
497
- /**
498
- * Every local mirror (workspace) with its conversations — the read model the
499
- * TUI's cleanup page lists.
500
- *
501
- * Read-only: no SSH, no mkdir. `live` is the cheap in-process answer; the
502
- * deletion calls re-check with `{ deep: true }` (kernel lock file) before
503
- * removing anything.
504
- */
505
- const listWorkspaceMirrors = async (opts = {}) => {
506
- const o = opts && typeof opts === 'object' ? opts : {}
507
- let root
508
- let sessionsRoot
509
- try {
510
- root = String(need('workspaceRoot')())
511
- sessionsRoot = String(need('sessionsRoot')())
512
- } catch (err) {
513
- throw asApiError(err)
514
- }
515
- const wantedMachine = o.machineId == null ? '' : String(o.machineId)
516
- const projects = await need('listRemoteProjects')()
517
- const view = await need('listMachinesView')()
518
- const machines = Array.isArray(view && view.machines) ? view.machines : []
519
- const registry = registryService()
520
- let registered = []
521
- try {
522
- registered = typeof registry?.list === 'function' ? [...registry.list()] : []
523
- } catch {
524
- registered = []
525
- }
526
- const byPath = new Map()
527
- for (const record of registered) {
528
- if (record && typeof record.path === 'string') byPath.set(String(record.path), record)
529
- }
530
- const out = []
531
- for (const project of projects) {
532
- if (!project || !project.dir) continue
533
- if (wantedMachine && String(project.machineId || '') !== wantedMachine) continue
534
- const machine = machines.find((m) => m && String(m.id) === String(project.machineId))
535
- || machines.find((m) => m && String(m.host) === String(project.host)
536
- && (Number(m.port) || 22) === (Number(project.port) || 22)
537
- && String(m.username || '') === String(project.username || ''))
538
- if (wantedMachine && !machine) continue
539
- let sessionList
540
- try {
541
- sessionList = listSessionDirs({ sessionsRoot, cwd: project.dir, cwds: [String(project.dir)] })
542
- } catch {
543
- sessionList = []
544
- }
545
- const sessions = []
546
- for (const session of sessionList) {
547
- sessions.push({
548
- id: String(session.id || ''),
549
- modifiedAt: Number(session.modifiedAt) || 0,
550
- live: await liveCheck(session.id, session.dir),
551
- })
552
- }
553
- let size
554
- try {
555
- size = dirSizeBytes(project.dir)
556
- } catch {
557
- size = { bytes: 0, truncated: false }
558
- }
559
- const recent = machine && Array.isArray(machine.recentWorkspaces)
560
- ? machine.recentWorkspaces.includes(project.remotePath)
561
- : false
562
- out.push({
563
- localMirror: String(project.dir),
564
- remotePath: String(project.remotePath || ''),
565
- host: String(project.host || ''),
566
- port: Number(project.port) || 22,
567
- username: String(project.username || ''),
568
- alias: String(project.alias || ''),
569
- machineId: project.machineId == null ? null : String(project.machineId),
570
- machineName: machine ? String(machine.name || machine.host || '') : String(project.name || ''),
571
- title: remoteWorkspaceTitle(String(project.remotePath || ''), {
572
- name: machine && machine.name,
573
- host: project.host,
574
- }),
575
- registered: byPath.has(String(project.dir)),
576
- recent,
577
- sessions,
578
- sessionCount: sessions.length,
579
- liveSessionCount: sessions.filter((s) => s.live).length,
580
- mirrorBytes: Number(size.bytes) || 0,
581
- mirrorSizeTruncated: size.truncated === true,
582
- })
583
- }
584
- out.sort((left, right) => {
585
- const byMachine = String(left.machineName).localeCompare(String(right.machineName))
586
- if (byMachine !== 0) return byMachine
587
- return String(left.remotePath).localeCompare(String(right.remotePath))
588
- })
589
- return out
590
- }
591
-
592
- /** Delete the sessions of one mirror (keeps the mirror + registration). */
593
- const deleteWorkspaceSessions = async (opts = {}) => {
594
- const o = opts && typeof opts === 'object' ? opts : {}
595
- let root
596
- let sessionsRoot
597
- try {
598
- root = String(need('workspaceRoot')())
599
- sessionsRoot = String(need('sessionsRoot')())
600
- } catch (err) {
601
- throw asApiError(err)
602
- }
603
- let validated
604
- try {
605
- validated = validateMirror({ mirrorRoot: root, localMirror: o.localMirror })
606
- } catch (err) {
607
- throw asApiError(err)
608
- }
609
- const cwdAliases = [...new Set([validated.real, String(o.localMirror || '')].filter(Boolean))]
610
- const report = await deleteSessionsFor({
611
- sessionsRoot,
612
- cwd: validated.real,
613
- cwds: cwdAliases,
614
- isLive: (id, dir) => liveCheck(id, dir, { deep: true }),
615
- force: o.force === true,
616
- })
617
- emit('status')
618
- return {
619
- localMirror: validated.real,
620
- remotePath: validated.meta.remotePath,
621
- removedSessions: report.removed.length,
622
- removedSessionIds: report.removed,
623
- skippedLiveSessions: report.skippedLive,
624
- }
625
- }
626
-
627
- /**
628
- * Permanently delete one remote workspace: its conversations, its workspace
629
- * registration, its "recent" entry (so the provider cannot recreate it) and
630
- * the local mirror directory itself.
631
- *
632
- * Refuses while any of its sessions is still live unless `force: true`.
633
- */
634
- const deleteRemoteWorkspace = async (opts = {}) => {
635
- const o = opts && typeof opts === 'object' ? opts : {}
636
- let root
637
- let sessionsRoot
638
- try {
639
- root = String(need('workspaceRoot')())
640
- sessionsRoot = String(need('sessionsRoot')())
641
- } catch (err) {
642
- throw asApiError(err)
643
- }
644
- let validated
645
- try {
646
- validated = validateMirror({ mirrorRoot: root, localMirror: o.localMirror })
647
- } catch (err) {
648
- throw asApiError(err)
649
- }
650
- const deleteSessions = o.deleteSessions !== false
651
- const force = o.force === true
652
- let pending = []
653
- if (deleteSessions) {
654
- try {
655
- pending = listSessionDirs({ sessionsRoot, cwd: validated.real, cwds: [String(o.localMirror || '')] })
656
- } catch {
657
- pending = []
658
- }
659
- if (!force && pending.length > 0) {
660
- const live = []
661
- for (const session of pending) {
662
- if (await liveCheck(session.id, session.dir, { deep: true })) live.push(session.id)
663
- }
664
- if (live.length > 0) {
665
- const error = apiError(
666
- 'WORKSPACE_BUSY',
667
- `还有 ${live.length} 个会话正在使用该工作区,请先在会话管理里停止它们(或退出对应终端)再删除`,
668
- )
669
- error.liveSessions = live
670
- throw error
671
- }
672
- }
673
- }
674
- let sessionReport = { removed: [], skippedLive: [] }
675
- if (deleteSessions) {
676
- const cwdAliases = [...new Set([validated.real, String(o.localMirror || '')].filter(Boolean))]
677
- sessionReport = await deleteSessionsFor({
678
- sessionsRoot,
679
- cwd: validated.real,
680
- cwds: cwdAliases,
681
- isLive: (id, dir) => liveCheck(id, dir, { deep: true }),
682
- force,
683
- })
684
- if (!force && sessionReport.skippedLive.length > 0) {
685
- const error = apiError(
686
- 'WORKSPACE_BUSY',
687
- `还有 ${sessionReport.skippedLive.length} 个会话正在使用该工作区,请先停止后再删除`,
688
- )
689
- error.liveSessions = sessionReport.skippedLive
690
- throw error
691
- }
692
- }
693
- let removedRegistration = false
694
- try {
695
- const registry = registryService()
696
- if (registry && typeof registry.delete === 'function') {
697
- let record
698
- if (typeof registry.resolveByPath === 'function') {
699
- try {
700
- record = await registry.resolveByPath(validated.real)
701
- } catch {
702
- record = undefined
703
- }
704
- }
705
- if (!record && typeof registry.list === 'function') {
706
- try {
707
- record = [...registry.list()].find((entry) => entry && String(entry.path) === validated.real)
708
- } catch {
709
- record = undefined
710
- }
711
- }
712
- if (record && record.id != null) {
713
- removedRegistration = await registry.delete(record.id) === true
714
- }
715
- }
716
- } catch {
717
- removedRegistration = false
718
- }
719
- let forgotten = { recents: 0, current: 0 }
720
- try {
721
- const result = await need('forgetRemotePath')(validated.meta.remotePath)
722
- if (result && typeof result === 'object') {
723
- forgotten = { recents: Number(result.recents) || 0, current: Number(result.current) || 0 }
724
- }
725
- } catch {
726
- forgotten = { recents: 0, current: 0 }
727
- }
728
- let removedMirror = false
729
- try {
730
- removedMirror = deleteMirrorTree({ mirrorRoot: root, localMirror: validated.real }) === true
731
- } catch (err) {
732
- throw asApiError(err)
733
- }
734
- emit('machines')
735
- emit('status')
736
- return {
737
- localMirror: validated.real,
738
- remotePath: validated.meta.remotePath,
739
- removedMirror,
740
- removedRegistration,
741
- removedSessions: sessionReport.removed.length,
742
- removedSessionIds: sessionReport.removed,
743
- removedRecents: forgotten.recents,
744
- clearedMachineWorkspace: forgotten.current,
745
- }
746
- }
747
-
748
- /** Drop a mirror from every machine's recent list / current workspace only. */
749
- const forgetWorkspaceRecent = async (opts = {}) => {
750
- const o = opts && typeof opts === 'object' ? opts : {}
751
- let root
752
- try {
753
- root = String(need('workspaceRoot')())
754
- } catch (err) {
755
- throw asApiError(err)
756
- }
757
- let validated
758
- try {
759
- validated = validateMirror({ mirrorRoot: root, localMirror: o.localMirror })
760
- } catch (err) {
761
- throw asApiError(err)
762
- }
763
- try {
764
- const result = await need('forgetRemotePath')(validated.meta.remotePath)
765
- emit('machines')
766
- return {
767
- localMirror: validated.real,
768
- remotePath: validated.meta.remotePath,
769
- removedRecents: Number(result && result.recents) || 0,
770
- clearedMachineWorkspace: Number(result && result.current) || 0,
771
- }
772
- } catch (err) {
773
- throw asApiError(err)
774
- }
775
- }
776
-
777
- /** 在系统文件管理器里打开本机 dsh-remote 的镜像根目录(`remote-workspaces`)。 */
778
- const revealMirrorFolder = async () => {
779
- try {
780
- const result = await need('revealMirrorFolderRecord')()
781
- const dir = String((result && result.path) || '')
782
- if (!dir) throw apiError('INTERNAL', 'dshRemote.revealMirrorFolder: host returned no path')
783
- return { path: dir }
784
- } catch (err) {
785
- throw asApiError(err)
786
- }
787
- }
788
-
789
- const subscribe = (listener) => {
790
- if (typeof listener !== 'function') {
791
- throw apiError('INTERNAL', 'dshRemote.subscribe: listener must be a function')
792
- }
793
- listeners.add(listener)
794
- let active = true
795
- return () => {
796
- if (!active) return
797
- active = false
798
- listeners.delete(listener)
799
- }
800
- }
801
-
802
- return {
803
- apiVersion: API_VERSION,
804
- listMachines,
805
- upsertMachine,
806
- removeMachine,
807
- setCurrent,
808
- connect,
809
- probeMachine,
810
- status,
811
- listDir,
812
- listRemoteProjects,
813
- ensureRemoteWorkspace,
814
- pickRemoteWorkspace,
815
- listWorkspaceMirrors,
816
- deleteWorkspaceSessions,
817
- deleteRemoteWorkspace,
818
- forgetWorkspaceRecent,
819
- revealMirrorFolder,
820
- subscribe,
821
- }
822
- }
1
+ // Host-side in-process API for OTHER plugins (the TUI layer), exposed as
2
+ // `ctx.dshRemote` from `apply()`.
3
+ //
4
+ // Why a service instead of a second implementation:
5
+ // Every mutable piece of dsh-remote state (the active pool, the per-machine
6
+ // pools, the in-memory `machines` snapshot, `currentId`, the workspace
7
+ // mirror, forwards/terminals) lives inside `apply()`'s closure. A consumer
8
+ // that re-read `machines.json` or dialled its own SSH pool would hold a stale
9
+ // registry snapshot, open a second TCP connection per host, and race
10
+ // `saveMachines()`'s whole-file rewrite against this one. `createHostApi()`
11
+ // therefore takes those closure functions as `deps` and only reshapes their
12
+ // results — it never imports cordis, never opens a pool and never touches
13
+ // the registry file.
14
+ //
15
+ // Contract (docs/tui.md §3, `apiVersion: 1`):
16
+ // · every method is async and returns PURE DATA (no pool / client / sftp
17
+ // handles, no passwords, no passphrases);
18
+ // · failures THROW one `Error` carrying a semantic `.code`; they never return
19
+ // `{ok:false}` (a caller's `if (res.ok)` would swallow the reason);
20
+ // · `error.message` is already the user-facing Chinese sentence
21
+ // (`friendlyMessage` from lib/errors.js, idempotent);
22
+ // · the API has its own tiny emitter: an event fires after THIS object's
23
+ // mutations. It deliberately does not splice itself into the SSH pool's
24
+ // single-slot `onReady`/`onCloseHook` (the forwards manager owns those).
25
+ import { classifyError, friendlyMessage } from './errors.js'
26
+ import { joinRemotePath, normalizeRemotePath, remoteDirname, toDisplayPath, remoteWorkspaceTitle } from './paths.js'
27
+ import { listDirStructured, listRemoteDrives } from './remote-fs.js'
28
+ import {
29
+ deleteMirrorTree,
30
+ deleteSessionsFor,
31
+ dirSizeBytes,
32
+ listMirrorEntries,
33
+ listSessionDirs,
34
+ validateMirror,
35
+ } from './workspace-cleanup.js'
36
+
37
+
38
+ /** Contract version. Consumers check `api.apiVersion === 1` before use. */
39
+ const API_VERSION = 1
40
+
41
+ /** Error codes the contract allows (`docs/tui.md` §3). */
42
+ const API_CODES = new Set([
43
+ 'MACHINE_NOT_FOUND',
44
+ 'NO_ACTIVE_MACHINE',
45
+ 'NOT_A_DIRECTORY',
46
+ 'AUTH',
47
+ 'CREDENTIALS',
48
+ 'HOSTKEY',
49
+ 'NETWORK',
50
+ 'TIMEOUT',
51
+ 'SFTP',
52
+ 'UNSUPPORTED',
53
+ 'LOCAL_SESSION',
54
+ 'VALIDATION',
55
+ 'WORKSPACE_BUSY',
56
+ 'INTERNAL',
57
+ ])
58
+
59
+ /** One coded error. `extra` carries optional machine identity (`host`/`port`)
60
+ * so a UI can point at the failing row. */
61
+ function apiError(code, message, extra = {}) {
62
+ const err = new Error(message)
63
+ err.code = API_CODES.has(code) ? code : 'INTERNAL'
64
+ if (extra && typeof extra === 'object') Object.assign(err, extra)
65
+ return err
66
+ }
67
+
68
+ /** Map whatever a dep throws onto the contract's error vocabulary.
69
+ *
70
+ * Coded errors thrown by lib/index.js deps (and by this module) pass through
71
+ * untouched; HTTP-layer codes (`httpStatus`) are translated, because the
72
+ * same closures answer the web routes; everything else is classified with
73
+ * lib/errors.js, which is what makes `AUTH` / `NETWORK` / `HOSTKEY` /
74
+ * `TIMEOUT` / `SFTP` / `CREDENTIALS` actionable instead of `INTERNAL`. */
75
+ function asApiError(err, opts = {}) {
76
+ if (!err) return apiError('INTERNAL', 'unknown error')
77
+ if (err.code && API_CODES.has(err.code)) return err
78
+ const status = Number(err.httpStatus) || 0
79
+ if (status === 400 || err.code === 'HOST_REQUIRED') {
80
+ // The route layer throws English strings (`host required`); the contract
81
+ // promises a user-facing Chinese sentence, so translate the known one and
82
+ // prefix the rest rather than leaking raw English into the TUI footer.
83
+ const raw = String(err.message || err)
84
+ const message = err.code === 'HOST_REQUIRED' ? '缺少主机地址(host 必填)' : `请求参数不可用:${raw}`
85
+ return apiError('VALIDATION', message)
86
+ }
87
+ if (status === 404) return apiError('MACHINE_NOT_FOUND', friendlyMessage(err, opts))
88
+ if (status === 403) return apiError('LOCAL_SESSION', String(err.message || err))
89
+ if (status === 409) return apiError('NO_ACTIVE_MACHINE', String(err.message || err))
90
+ const category = classifyError(err, opts).category
91
+ const map = {
92
+ auth: 'AUTH',
93
+ network: 'NETWORK',
94
+ hostkey: 'HOSTKEY',
95
+ timeout: 'TIMEOUT',
96
+ sftp: 'SFTP',
97
+ credentials: 'CREDENTIALS',
98
+ }
99
+ const code = map[category] || 'INTERNAL'
100
+ const out = apiError(code, friendlyMessage(err, opts), {
101
+ host: err.host != null ? err.host : opts.host,
102
+ port: err.port != null ? err.port : opts.port,
103
+ cause: err,
104
+ })
105
+ return out
106
+ }
107
+
108
+ /** Defensive secret strip for anything that leaves this module.
109
+ *
110
+ * The deps hand back views the web settings page already receives
111
+ * (`sanitizeMachine` — password/passphrase replaced by booleans), so this is
112
+ * a belt-and-braces pass: a future field added to the record must not leak
113
+ * through the in-process API by accident. It also makes the promise
114
+ * "no secret ever leaves" testable by seeding a fake deps that returns the
115
+ * raw record.
116
+ *
117
+ * @param {*} value - plain data from a dep.
118
+ * @returns {*} a deep copy with `password` / `passphrase` keys removed.
119
+ */
120
+ function scrub(value) {
121
+ if (Array.isArray(value)) return value.map(scrub)
122
+ if (value && typeof value === 'object') {
123
+ const out = {}
124
+ for (const [k, v] of Object.entries(value)) {
125
+ if (k === 'password' || k === 'passphrase') continue
126
+ out[k] = scrub(v)
127
+ }
128
+ return out
129
+ }
130
+ return value
131
+ }
132
+
133
+ /** The Status shape the TUI contract names (`machineId`), derived from the
134
+ * host's own snapshot (`currentId`). Pure data either way. */
135
+ function asStatus(snapshot) {
136
+ const s = (snapshot && typeof snapshot === 'object') ? { ...snapshot } : {}
137
+ return { ...scrub(s), machineId: s.currentId == null ? null : String(s.currentId) }
138
+ }
139
+
140
+ /** Map the SFTP entry types lib/remote-fs.js produces onto the contract's
141
+ * four-value vocabulary. */
142
+ function publicEntryType(type) {
143
+ if (type === 'dir') return 'dir'
144
+ if (type === 'symlink' || type === 'link') return 'link'
145
+ if (type === 'file') return 'file'
146
+ return 'other'
147
+ }
148
+
149
+ /** Parent directory for a DirListing, or null for a filesystem root. */
150
+ function parentOf(p, platform) {
151
+ const norm = normalizeRemotePath(p)
152
+ if (norm === '/' || /^[a-zA-Z]:\\?$/.test(norm) || /^\\\\[^\\]+\\[^\\]+$/.test(norm)) return null
153
+ return toDisplayPath(remoteDirname(norm), platform)
154
+ }
155
+
156
+ /**
157
+ * Build the host API object.
158
+ *
159
+ * @param {object} deps - closure functions supplied by lib/index.js. Required
160
+ * keys (all throw `INTERNAL` here when missing, never at require time):
161
+ * · `listMachinesView()` → `{machines, currentId}` (sanitized views);
162
+ * · `upsertMachineRecord(body)` → `{machine, machines, currentId, warning?,
163
+ * warningDetail?, sshConfigWarning?}`; throws HOST_REQUIRED / coded errors;
164
+ * · `removeMachineRecord(id)` → `{machines, currentId}`; throws
165
+ * MACHINE_NOT_FOUND;
166
+ * · `setCurrentForApi(id|null)`; throws MACHINE_NOT_FOUND;
167
+ * · `connectMachine({machineId, persist})` → Status (throws classified);
168
+ * · `probeMachineRecord(body)` → ProbeResult (throws classified);
169
+ * · `statusSnapshot()` → Status snapshot;
170
+ * · `resolveDirBinding({machineId, sessionId, local})` → `{pool, ws, bound,
171
+ * machine}` (throws MACHINE_NOT_FOUND / NO_ACTIVE_MACHINE);
172
+ * · `listRemoteProjects()` → mirror registry entries (+machineId);
173
+ * · `revealMirrorFolderRecord()` → `{path}` (opens `remote-workspaces` in the file manager);
174
+ * · `resolveMachine(machineId?)` → `{record, machineId, name, host, port,
175
+ * username, alias}` (resolved connect identity);
176
+ * · `ensureMirror(remotePath, host, username, port, extra)` → local dir;
177
+ * · `registerMirroredWorkspace(localDir, remotePath, record)`;
178
+ * · `checkRemoteDir(remotePath, machineId?)` → boolean (SSH stat).
179
+ * @returns {object} the `ctx.dshRemote` value.
180
+ */
181
+ export function createHostApi(deps = {}) {
182
+ const listeners = new Set()
183
+
184
+ const need = (name) => {
185
+ const fn = deps[name]
186
+ if (typeof fn !== 'function') {
187
+ throw apiError('INTERNAL', `dshRemote: host dependency "${name}" is missing`)
188
+ }
189
+ return fn
190
+ }
191
+
192
+ /** Fire one lifecycle event. Listener failures are contained: a broken TUI
193
+ * subscriber must never break a machine save. */
194
+ const emit = (type) => {
195
+ for (const listener of [...listeners]) {
196
+ try { listener({ type }) } catch { /* subscriber is on its own */ }
197
+ }
198
+ }
199
+
200
+ const status = async () => {
201
+ const snapshot = await need('statusSnapshot')()
202
+ return asStatus(snapshot)
203
+ }
204
+
205
+ /** Project the record layer's grouping fields onto the contract's `group`.
206
+ *
207
+ * The registry has no `group` column: `normalizeMachineGroup()` writes
208
+ * `environment` / `location` / `description` / `tags` (lib/registry.js),
209
+ * and the Web settings page edits `environment` as the host's group label.
210
+ * The TUI form exposes ONE text field, so the contract's `group` is that
211
+ * `environment` value — without this projection the form would save into a
212
+ * field the host never persists.
213
+ *
214
+ * @param {object} machine - a sanitized record view.
215
+ * @returns {object} the same view plus a string `group`.
216
+ */
217
+ const withGroup = (machine) => {
218
+ if (!machine || typeof machine !== 'object') return machine
219
+ const group = machine.group !== undefined && machine.group !== null
220
+ ? machine.group
221
+ : machine.environment
222
+ return { ...machine, group: group == null ? '' : String(group) }
223
+ }
224
+ /** Inverse of {@link withGroup} for a write patch. */
225
+ const withGroupPatch = (patch) => {
226
+ const body = { ...patch }
227
+ if (body.group !== undefined && body.environment === undefined) body.environment = body.group
228
+ delete body.group
229
+ return body
230
+ }
231
+
232
+ const listMachines = async () => {
233
+ const view = await need('listMachinesView')()
234
+ return {
235
+ machines: scrub(Array.isArray(view && view.machines) ? view.machines : []).map(withGroup),
236
+ currentId: view && view.currentId != null ? String(view.currentId) : null,
237
+ }
238
+ }
239
+
240
+ const upsertMachine = async (patch = {}) => {
241
+ const body = withGroupPatch({ ...(patch && typeof patch === 'object' ? patch : {}) })
242
+ let result
243
+ try {
244
+ result = await need('upsertMachineRecord')(body)
245
+ } catch (err) {
246
+ throw asApiError(err, { host: body.host, port: body.port })
247
+ }
248
+ emit('machines')
249
+ // Non-fatal problems the save could not throw for: the OS secure store
250
+ // refused the password, or ~/.ssh/config already names this host with a
251
+ // user-owned block. They are collected into one string list per contract.
252
+ const warnings = []
253
+ if (result && result.warning) {
254
+ warnings.push(String(result.warningDetail ? `${result.warning}: ${result.warningDetail}` : result.warning))
255
+ }
256
+ if (result && result.sshConfigWarning) warnings.push(String(result.sshConfigWarning))
257
+ return {
258
+ machine: withGroup(scrub(result && result.machine)),
259
+ machines: scrub(Array.isArray(result && result.machines) ? result.machines : []).map(withGroup),
260
+ currentId: result && result.currentId != null ? String(result.currentId) : null,
261
+ warnings,
262
+ }
263
+ }
264
+
265
+ const removeMachine = async (id) => {
266
+ let result
267
+ try {
268
+ result = await need('removeMachineRecord')(String(id == null ? '' : id))
269
+ } catch (err) {
270
+ throw asApiError(err)
271
+ }
272
+ emit('machines')
273
+ emit('status')
274
+ return {
275
+ machines: scrub(Array.isArray(result && result.machines) ? result.machines : []).map(withGroup),
276
+ currentId: result && result.currentId != null ? String(result.currentId) : null,
277
+ }
278
+ }
279
+
280
+ const setCurrent = async (id) => {
281
+ const clean = id == null || String(id).trim() === '' ? null : String(id).trim()
282
+ try {
283
+ await need('setCurrentForApi')(clean)
284
+ } catch (err) {
285
+ throw asApiError(err)
286
+ }
287
+ emit('status')
288
+ return status()
289
+ }
290
+
291
+ const connect = async (opts = {}) => {
292
+ const o = opts && typeof opts === 'object' ? opts : {}
293
+ let snapshot
294
+ try {
295
+ snapshot = await need('connectMachine')({
296
+ machineId: o.machineId == null ? undefined : String(o.machineId),
297
+ persist: o.persist !== false,
298
+ })
299
+ } catch (err) {
300
+ throw asApiError(err)
301
+ }
302
+ emit('status')
303
+ return asStatus(snapshot)
304
+ }
305
+
306
+ const probeMachine = async (patch = {}) => {
307
+ const body = { ...(patch && typeof patch === 'object' ? patch : {}) }
308
+ try {
309
+ return await need('probeMachineRecord')(body)
310
+ } catch (err) {
311
+ throw asApiError(err, { host: body.host, port: body.port })
312
+ }
313
+ }
314
+
315
+ /** Resolve which remote pool a listing should run against.
316
+ * Addressing priority (contract): machineId > the active machine. */
317
+ const bindingForDir = async (opts = {}) => {
318
+ const o = opts && typeof opts === 'object' ? opts : {}
319
+ try {
320
+ return await need('resolveDirBinding')({
321
+ machineId: o.machineId == null ? undefined : String(o.machineId),
322
+ sessionId: o.sessionId == null ? undefined : String(o.sessionId),
323
+ local: o.local == null ? undefined : String(o.local),
324
+ })
325
+ } catch (err) {
326
+ throw asApiError(err)
327
+ }
328
+ }
329
+
330
+ const listDir = async (opts = {}) => {
331
+ const o = opts && typeof opts === 'object' ? opts : {}
332
+ const binding = await bindingForDir(o)
333
+ const pool = binding && binding.pool
334
+ if (!pool || typeof pool.detect !== 'function') {
335
+ throw apiError('INTERNAL', 'dshRemote.listDir: no remote pool resolved')
336
+ }
337
+ const machine = {
338
+ id: (binding.machine && binding.machine.id) || '',
339
+ name: (binding.machine && binding.machine.name) || '',
340
+ host: (binding.machine && binding.machine.host) || '',
341
+ port: Number(binding.machine && binding.machine.port) || 22,
342
+ username: (binding.machine && binding.machine.username) || '',
343
+ }
344
+ try {
345
+ await pool.detect()
346
+ const win = pool.platform === 'windows'
347
+ const requested = o.path != null && String(o.path).trim() !== '' ? String(o.path) : (binding.ws || '')
348
+ const canon = normalizeRemotePath(requested)
349
+ // A Windows remote's filesystem root is a drive list, exactly like /ls.
350
+ if (canon === '/' || canon === '') {
351
+ if (win || pool.platform !== 'posix') {
352
+ const drives = await listRemoteDrives(pool)
353
+ if (drives.length) {
354
+ return {
355
+ path: '',
356
+ parent: null,
357
+ platform: 'windows',
358
+ items: drives.map((d) => ({
359
+ name: String(d.name || ''),
360
+ path: String(d.path || ''),
361
+ type: 'dir',
362
+ size: 0,
363
+ mtime: 0,
364
+ })),
365
+ machine,
366
+ }
367
+ }
368
+ }
369
+ if (win) return { path: '', parent: null, platform: 'windows', items: [], machine }
370
+ }
371
+ const sftp = await pool.sftp()
372
+ const out = await listDirStructured(sftp, canon)
373
+ const platform = win ? 'windows' : 'posix'
374
+ return {
375
+ path: toDisplayPath(out.path, pool.platform),
376
+ parent: parentOf(out.path, pool.platform),
377
+ platform,
378
+ items: out.items.map((it) => ({
379
+ name: String(it.name),
380
+ path: toDisplayPath(joinRemotePath(canon, it.name), pool.platform),
381
+ type: publicEntryType(it.type),
382
+ size: typeof it.size === 'number' ? it.size : 0,
383
+ mtime: typeof it.mtime === 'number' ? it.mtime : 0,
384
+ })),
385
+ machine,
386
+ }
387
+ } catch (err) {
388
+ throw asApiError(err, { host: machine.host, port: machine.port })
389
+ }
390
+ }
391
+
392
+ const listRemoteProjects = async () => {
393
+ const projects = await need('listRemoteProjects')()
394
+ return (Array.isArray(projects) ? projects : []).map((p) => ({
395
+ dir: String((p && p.dir) || ''),
396
+ host: String((p && p.host) || ''),
397
+ port: Number(p && p.port) || 22,
398
+ username: String((p && p.username) || ''),
399
+ remotePath: String((p && p.remotePath) || ''),
400
+ alias: String((p && p.alias) || ''),
401
+ name: String((p && p.name) || ''),
402
+ machineId: p && p.machineId != null ? String(p.machineId) : null,
403
+ }))
404
+ }
405
+
406
+ /** Shared body of ensureRemoteWorkspace / pickRemoteWorkspace.
407
+ * Deliberately NO SSH: it only touches the local mirror directory. */
408
+ const ensureWorkspace = async (opts = {}) => {
409
+ const o = opts && typeof opts === 'object' ? opts : {}
410
+ const raw = String(o.remotePath == null ? '' : o.remotePath).trim()
411
+ if (!raw) throw apiError('NOT_A_DIRECTORY', '远程路径不能为空')
412
+ const remotePath = normalizeRemotePath(raw)
413
+ let machine
414
+ try {
415
+ machine = await need('resolveMachine')(o.machineId == null ? undefined : String(o.machineId))
416
+ } catch (err) {
417
+ throw asApiError(err)
418
+ }
419
+ const extra = machine.alias ? { alias: machine.alias } : {}
420
+ let localMirror
421
+ try {
422
+ localMirror = await need('ensureMirror')(remotePath, machine.host, machine.username, machine.port, extra)
423
+ } catch (err) {
424
+ throw asApiError(err, { host: machine.host, port: machine.port })
425
+ }
426
+ const title = remoteWorkspaceTitle(remotePath, { name: machine.name, host: machine.host })
427
+ let workspace
428
+ if (o.register !== false) {
429
+ try {
430
+ const created = await need('registerMirroredWorkspace')(localMirror, remotePath, machine.record)
431
+ if (created && created.id != null) {
432
+ workspace = { id: String(created.id), title: String(created.title || title) }
433
+ }
434
+ } catch {
435
+ // Registration is explicitly best-effort in the host (older harness
436
+ // without ctx.workspaceRegistry must not fail the mirror); the mirror
437
+ // and its meta are already on disk.
438
+ }
439
+ }
440
+ return {
441
+ machineId: machine.machineId == null ? '' : String(machine.machineId),
442
+ remotePath,
443
+ localMirror,
444
+ title,
445
+ ...(workspace ? { workspace } : {}),
446
+ }
447
+ }
448
+
449
+ const ensureRemoteWorkspace = async (opts = {}) => {
450
+ const result = await ensureWorkspace(opts)
451
+ emit('status')
452
+ return result
453
+ }
454
+
455
+ const pickRemoteWorkspace = async (opts = {}) => {
456
+ const o = opts && typeof opts === 'object' ? opts : {}
457
+ const raw = String(o.remotePath == null ? '' : o.remotePath).trim()
458
+ if (!raw) throw apiError('NOT_A_DIRECTORY', '远程路径不能为空')
459
+ const remotePath = normalizeRemotePath(raw)
460
+ let okDir = false
461
+ try {
462
+ okDir = await need('checkRemoteDir')(remotePath, o.machineId == null ? undefined : String(o.machineId))
463
+ } catch (err) {
464
+ throw asApiError(err)
465
+ }
466
+ if (!okDir) throw apiError('NOT_A_DIRECTORY', `远程路径不是目录(或无法访问):${remotePath}`)
467
+ const result = await ensureWorkspace({
468
+ machineId: o.machineId,
469
+ remotePath,
470
+ register: o.registerWorkspace !== false,
471
+ })
472
+ emit('status')
473
+ return { ...result, status: await status() }
474
+ }
475
+
476
+ /** The workspace registry, when the composition serves one. */
477
+ const registryService = () => {
478
+ try {
479
+ const registry = need('workspaceRegistry')()
480
+ return registry && typeof registry === 'object' ? registry : undefined
481
+ } catch {
482
+ return undefined
483
+ }
484
+ }
485
+
486
+ /** Quick liveness probe: in-process only unless `deep` is requested. */
487
+ const liveCheck = async (sessionId, dir, opts = {}) => {
488
+ try {
489
+ const fn = deps.isSessionLive
490
+ if (typeof fn !== 'function') return false
491
+ return await fn(String(sessionId), String(dir), opts) === true
492
+ } catch {
493
+ return false
494
+ }
495
+ }
496
+
497
+ /**
498
+ * Every local mirror (workspace) with its conversations — the read model the
499
+ * TUI's cleanup page lists.
500
+ *
501
+ * Read-only: no SSH, no mkdir. `live` is the cheap in-process answer; the
502
+ * deletion calls re-check with `{ deep: true }` (kernel lock file) before
503
+ * removing anything.
504
+ */
505
+ const listWorkspaceMirrors = async (opts = {}) => {
506
+ const o = opts && typeof opts === 'object' ? opts : {}
507
+ let root
508
+ let sessionsRoot
509
+ try {
510
+ root = String(need('workspaceRoot')())
511
+ sessionsRoot = String(need('sessionsRoot')())
512
+ } catch (err) {
513
+ throw asApiError(err)
514
+ }
515
+ const wantedMachine = o.machineId == null ? '' : String(o.machineId)
516
+ const projects = await need('listRemoteProjects')()
517
+ const view = await need('listMachinesView')()
518
+ const machines = Array.isArray(view && view.machines) ? view.machines : []
519
+ const registry = registryService()
520
+ let registered = []
521
+ try {
522
+ registered = typeof registry?.list === 'function' ? [...registry.list()] : []
523
+ } catch {
524
+ registered = []
525
+ }
526
+ const byPath = new Map()
527
+ for (const record of registered) {
528
+ if (record && typeof record.path === 'string') byPath.set(String(record.path), record)
529
+ }
530
+ const out = []
531
+ for (const project of projects) {
532
+ if (!project || !project.dir) continue
533
+ if (wantedMachine && String(project.machineId || '') !== wantedMachine) continue
534
+ const machine = machines.find((m) => m && String(m.id) === String(project.machineId))
535
+ || machines.find((m) => m && String(m.host) === String(project.host)
536
+ && (Number(m.port) || 22) === (Number(project.port) || 22)
537
+ && String(m.username || '') === String(project.username || ''))
538
+ if (wantedMachine && !machine) continue
539
+ let sessionList
540
+ try {
541
+ sessionList = listSessionDirs({ sessionsRoot, cwd: project.dir, cwds: [String(project.dir)] })
542
+ } catch {
543
+ sessionList = []
544
+ }
545
+ const sessions = []
546
+ for (const session of sessionList) {
547
+ sessions.push({
548
+ id: String(session.id || ''),
549
+ modifiedAt: Number(session.modifiedAt) || 0,
550
+ live: await liveCheck(session.id, session.dir),
551
+ })
552
+ }
553
+ let size
554
+ try {
555
+ size = dirSizeBytes(project.dir)
556
+ } catch {
557
+ size = { bytes: 0, truncated: false }
558
+ }
559
+ const recent = machine && Array.isArray(machine.recentWorkspaces)
560
+ ? machine.recentWorkspaces.includes(project.remotePath)
561
+ : false
562
+ out.push({
563
+ localMirror: String(project.dir),
564
+ remotePath: String(project.remotePath || ''),
565
+ host: String(project.host || ''),
566
+ port: Number(project.port) || 22,
567
+ username: String(project.username || ''),
568
+ alias: String(project.alias || ''),
569
+ machineId: project.machineId == null ? null : String(project.machineId),
570
+ machineName: machine ? String(machine.name || machine.host || '') : String(project.name || ''),
571
+ title: remoteWorkspaceTitle(String(project.remotePath || ''), {
572
+ name: machine && machine.name,
573
+ host: project.host,
574
+ }),
575
+ registered: byPath.has(String(project.dir)),
576
+ recent,
577
+ sessions,
578
+ sessionCount: sessions.length,
579
+ liveSessionCount: sessions.filter((s) => s.live).length,
580
+ mirrorBytes: Number(size.bytes) || 0,
581
+ mirrorSizeTruncated: size.truncated === true,
582
+ })
583
+ }
584
+ out.sort((left, right) => {
585
+ const byMachine = String(left.machineName).localeCompare(String(right.machineName))
586
+ if (byMachine !== 0) return byMachine
587
+ return String(left.remotePath).localeCompare(String(right.remotePath))
588
+ })
589
+ return out
590
+ }
591
+
592
+ /** Delete the sessions of one mirror (keeps the mirror + registration). */
593
+ const deleteWorkspaceSessions = async (opts = {}) => {
594
+ const o = opts && typeof opts === 'object' ? opts : {}
595
+ let root
596
+ let sessionsRoot
597
+ try {
598
+ root = String(need('workspaceRoot')())
599
+ sessionsRoot = String(need('sessionsRoot')())
600
+ } catch (err) {
601
+ throw asApiError(err)
602
+ }
603
+ let validated
604
+ try {
605
+ validated = validateMirror({ mirrorRoot: root, localMirror: o.localMirror })
606
+ } catch (err) {
607
+ throw asApiError(err)
608
+ }
609
+ const cwdAliases = [...new Set([validated.real, String(o.localMirror || '')].filter(Boolean))]
610
+ const report = await deleteSessionsFor({
611
+ sessionsRoot,
612
+ cwd: validated.real,
613
+ cwds: cwdAliases,
614
+ isLive: (id, dir) => liveCheck(id, dir, { deep: true }),
615
+ force: o.force === true,
616
+ })
617
+ emit('status')
618
+ return {
619
+ localMirror: validated.real,
620
+ remotePath: validated.meta.remotePath,
621
+ removedSessions: report.removed.length,
622
+ removedSessionIds: report.removed,
623
+ skippedLiveSessions: report.skippedLive,
624
+ }
625
+ }
626
+
627
+ /**
628
+ * Permanently delete one remote workspace: its conversations, its workspace
629
+ * registration, its "recent" entry (so the provider cannot recreate it) and
630
+ * the local mirror directory itself.
631
+ *
632
+ * Refuses while any of its sessions is still live unless `force: true`.
633
+ */
634
+ const deleteRemoteWorkspace = async (opts = {}) => {
635
+ const o = opts && typeof opts === 'object' ? opts : {}
636
+ let root
637
+ let sessionsRoot
638
+ try {
639
+ root = String(need('workspaceRoot')())
640
+ sessionsRoot = String(need('sessionsRoot')())
641
+ } catch (err) {
642
+ throw asApiError(err)
643
+ }
644
+ let validated
645
+ try {
646
+ validated = validateMirror({ mirrorRoot: root, localMirror: o.localMirror })
647
+ } catch (err) {
648
+ throw asApiError(err)
649
+ }
650
+ const deleteSessions = o.deleteSessions !== false
651
+ const force = o.force === true
652
+ let pending = []
653
+ if (deleteSessions) {
654
+ try {
655
+ pending = listSessionDirs({ sessionsRoot, cwd: validated.real, cwds: [String(o.localMirror || '')] })
656
+ } catch {
657
+ pending = []
658
+ }
659
+ if (!force && pending.length > 0) {
660
+ const live = []
661
+ for (const session of pending) {
662
+ if (await liveCheck(session.id, session.dir, { deep: true })) live.push(session.id)
663
+ }
664
+ if (live.length > 0) {
665
+ const error = apiError(
666
+ 'WORKSPACE_BUSY',
667
+ `还有 ${live.length} 个会话正在使用该工作区,请先在会话管理里停止它们(或退出对应终端)再删除`,
668
+ )
669
+ error.liveSessions = live
670
+ throw error
671
+ }
672
+ }
673
+ }
674
+ let sessionReport = { removed: [], skippedLive: [] }
675
+ if (deleteSessions) {
676
+ const cwdAliases = [...new Set([validated.real, String(o.localMirror || '')].filter(Boolean))]
677
+ sessionReport = await deleteSessionsFor({
678
+ sessionsRoot,
679
+ cwd: validated.real,
680
+ cwds: cwdAliases,
681
+ isLive: (id, dir) => liveCheck(id, dir, { deep: true }),
682
+ force,
683
+ })
684
+ if (!force && sessionReport.skippedLive.length > 0) {
685
+ const error = apiError(
686
+ 'WORKSPACE_BUSY',
687
+ `还有 ${sessionReport.skippedLive.length} 个会话正在使用该工作区,请先停止后再删除`,
688
+ )
689
+ error.liveSessions = sessionReport.skippedLive
690
+ throw error
691
+ }
692
+ }
693
+ let removedRegistration = false
694
+ try {
695
+ const registry = registryService()
696
+ if (registry && typeof registry.delete === 'function') {
697
+ let record
698
+ if (typeof registry.resolveByPath === 'function') {
699
+ try {
700
+ record = await registry.resolveByPath(validated.real)
701
+ } catch {
702
+ record = undefined
703
+ }
704
+ }
705
+ if (!record && typeof registry.list === 'function') {
706
+ try {
707
+ record = [...registry.list()].find((entry) => entry && String(entry.path) === validated.real)
708
+ } catch {
709
+ record = undefined
710
+ }
711
+ }
712
+ if (record && record.id != null) {
713
+ removedRegistration = await registry.delete(record.id) === true
714
+ }
715
+ }
716
+ } catch {
717
+ removedRegistration = false
718
+ }
719
+ let forgotten = { recents: 0, current: 0 }
720
+ try {
721
+ const result = await need('forgetRemotePath')(validated.meta.remotePath)
722
+ if (result && typeof result === 'object') {
723
+ forgotten = { recents: Number(result.recents) || 0, current: Number(result.current) || 0 }
724
+ }
725
+ } catch {
726
+ forgotten = { recents: 0, current: 0 }
727
+ }
728
+ let removedMirror = false
729
+ try {
730
+ removedMirror = deleteMirrorTree({ mirrorRoot: root, localMirror: validated.real }) === true
731
+ } catch (err) {
732
+ throw asApiError(err)
733
+ }
734
+ emit('machines')
735
+ emit('status')
736
+ return {
737
+ localMirror: validated.real,
738
+ remotePath: validated.meta.remotePath,
739
+ removedMirror,
740
+ removedRegistration,
741
+ removedSessions: sessionReport.removed.length,
742
+ removedSessionIds: sessionReport.removed,
743
+ removedRecents: forgotten.recents,
744
+ clearedMachineWorkspace: forgotten.current,
745
+ }
746
+ }
747
+
748
+ /** Drop a mirror from every machine's recent list / current workspace only. */
749
+ const forgetWorkspaceRecent = async (opts = {}) => {
750
+ const o = opts && typeof opts === 'object' ? opts : {}
751
+ let root
752
+ try {
753
+ root = String(need('workspaceRoot')())
754
+ } catch (err) {
755
+ throw asApiError(err)
756
+ }
757
+ let validated
758
+ try {
759
+ validated = validateMirror({ mirrorRoot: root, localMirror: o.localMirror })
760
+ } catch (err) {
761
+ throw asApiError(err)
762
+ }
763
+ try {
764
+ const result = await need('forgetRemotePath')(validated.meta.remotePath)
765
+ emit('machines')
766
+ return {
767
+ localMirror: validated.real,
768
+ remotePath: validated.meta.remotePath,
769
+ removedRecents: Number(result && result.recents) || 0,
770
+ clearedMachineWorkspace: Number(result && result.current) || 0,
771
+ }
772
+ } catch (err) {
773
+ throw asApiError(err)
774
+ }
775
+ }
776
+
777
+ /** 在系统文件管理器里打开本机 dsh-remote 的镜像根目录(`remote-workspaces`)。 */
778
+ const revealMirrorFolder = async () => {
779
+ try {
780
+ const result = await need('revealMirrorFolderRecord')()
781
+ const dir = String((result && result.path) || '')
782
+ if (!dir) throw apiError('INTERNAL', 'dshRemote.revealMirrorFolder: host returned no path')
783
+ return { path: dir }
784
+ } catch (err) {
785
+ throw asApiError(err)
786
+ }
787
+ }
788
+
789
+ const subscribe = (listener) => {
790
+ if (typeof listener !== 'function') {
791
+ throw apiError('INTERNAL', 'dshRemote.subscribe: listener must be a function')
792
+ }
793
+ listeners.add(listener)
794
+ let active = true
795
+ return () => {
796
+ if (!active) return
797
+ active = false
798
+ listeners.delete(listener)
799
+ }
800
+ }
801
+
802
+ return {
803
+ apiVersion: API_VERSION,
804
+ listMachines,
805
+ upsertMachine,
806
+ removeMachine,
807
+ setCurrent,
808
+ connect,
809
+ probeMachine,
810
+ status,
811
+ listDir,
812
+ listRemoteProjects,
813
+ ensureRemoteWorkspace,
814
+ pickRemoteWorkspace,
815
+ listWorkspaceMirrors,
816
+ deleteWorkspaceSessions,
817
+ deleteRemoteWorkspace,
818
+ forgetWorkspaceRecent,
819
+ revealMirrorFolder,
820
+ subscribe,
821
+ }
822
+ }