dsh-linked-workspace 0.10.0 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +31 -0
- package/README.en.md +166 -162
- package/README.md +151 -174
- package/docs/API.md +53 -37
- package/docs/VERIFY.md +64 -17
- package/lib/client.js +1177 -350
- package/lib/index.js +506 -250
- package/lib/ssh.js +173 -23
- package/locale/en.json +2 -2
- package/locale/zh.json +2 -2
- package/package.json +4 -5
package/lib/index.js
CHANGED
|
@@ -22,7 +22,7 @@ import { mkdir, readdir, stat as fsStat } from 'node:fs/promises'
|
|
|
22
22
|
import { homedir, tmpdir } from 'node:os'
|
|
23
23
|
import { basename, dirname, extname, isAbsolute, join, posix, resolve, sep } from 'node:path'
|
|
24
24
|
import { fileURLToPath } from 'node:url'
|
|
25
|
-
import { listHosts, RemoteHost, SshError } from './ssh.js'
|
|
25
|
+
import { listHosts, RemoteHost, SshError, writeLocalCredential } from './ssh.js'
|
|
26
26
|
import * as linkedFs from './linked.js'
|
|
27
27
|
import * as git from './git.js'
|
|
28
28
|
|
|
@@ -55,6 +55,8 @@ const FILE_OPEN_MODES = new Set(['editor', 'system', 'copy'])
|
|
|
55
55
|
const WORKSPACE_TITLE_PREFIX = '⇄ '
|
|
56
56
|
const LINKED_TOOL_NAME = 'linked_workspace'
|
|
57
57
|
const LINKED_PROMPT_SECTION = 'tool:linked-workspace'
|
|
58
|
+
const REMOTE_TOOL_NAME = 'remote_workspace'
|
|
59
|
+
const REMOTE_PROMPT_SECTION = 'tool:remote-workspace'
|
|
58
60
|
const LINKED_READ_CAP = 512 * 1024
|
|
59
61
|
const LINKED_SYNC_FILES = 500
|
|
60
62
|
const LINKED_SYNC_BYTES = 50 * 1024 * 1024
|
|
@@ -373,75 +375,6 @@ async function readJsonBody(req) {
|
|
|
373
375
|
}
|
|
374
376
|
}
|
|
375
377
|
|
|
376
|
-
// ── workspace registry ──────────────────────────────────────────────────────
|
|
377
|
-
|
|
378
|
-
class WorkspaceStore {
|
|
379
|
-
constructor(file) {
|
|
380
|
-
this.file = file
|
|
381
|
-
this.workspaces = []
|
|
382
|
-
this.load()
|
|
383
|
-
}
|
|
384
|
-
|
|
385
|
-
load() {
|
|
386
|
-
const raw = readJsonFile(this.file, { version: DATA_VERSION, workspaces: [] })
|
|
387
|
-
const list = Array.isArray(raw) ? raw : Array.isArray(raw.workspaces) ? raw.workspaces : []
|
|
388
|
-
this.workspaces = list.filter((item) => {
|
|
389
|
-
return item && typeof item === 'object' && typeof item.id === 'string' && typeof item.remotePath === 'string'
|
|
390
|
-
})
|
|
391
|
-
}
|
|
392
|
-
|
|
393
|
-
save() {
|
|
394
|
-
writeJsonAtomic(this.file, { version: DATA_VERSION, workspaces: this.workspaces })
|
|
395
|
-
}
|
|
396
|
-
|
|
397
|
-
list() {
|
|
398
|
-
return this.workspaces
|
|
399
|
-
}
|
|
400
|
-
|
|
401
|
-
get(id) {
|
|
402
|
-
return this.workspaces.find((item) => item.id === id)
|
|
403
|
-
}
|
|
404
|
-
|
|
405
|
-
find(hostId, remotePath) {
|
|
406
|
-
return this.workspaces.find((item) => item.hostId === hostId && item.remotePath === remotePath)
|
|
407
|
-
}
|
|
408
|
-
|
|
409
|
-
add(entry) {
|
|
410
|
-
this.workspaces.push(entry)
|
|
411
|
-
this.save()
|
|
412
|
-
return entry
|
|
413
|
-
}
|
|
414
|
-
|
|
415
|
-
remove(id) {
|
|
416
|
-
const next = this.workspaces.filter((item) => item.id !== id)
|
|
417
|
-
if (next.length === this.workspaces.length) return false
|
|
418
|
-
this.workspaces = next
|
|
419
|
-
this.save()
|
|
420
|
-
return true
|
|
421
|
-
}
|
|
422
|
-
|
|
423
|
-
rename(id, name) {
|
|
424
|
-
const entry = this.get(id)
|
|
425
|
-
if (!entry) return undefined
|
|
426
|
-
entry.name = name
|
|
427
|
-
this.save()
|
|
428
|
-
return entry
|
|
429
|
-
}
|
|
430
|
-
|
|
431
|
-
updateSnapshot(hostId, snapshot) {
|
|
432
|
-
let changed = false
|
|
433
|
-
for (const entry of this.workspaces) {
|
|
434
|
-
if (entry.hostId !== hostId) continue
|
|
435
|
-
const next = { ...entry.hostSnapshot, ...snapshot }
|
|
436
|
-
if (JSON.stringify(next) !== JSON.stringify(entry.hostSnapshot)) {
|
|
437
|
-
entry.hostSnapshot = next
|
|
438
|
-
changed = true
|
|
439
|
-
}
|
|
440
|
-
}
|
|
441
|
-
if (changed) this.save()
|
|
442
|
-
}
|
|
443
|
-
}
|
|
444
|
-
|
|
445
378
|
// ── settings ────────────────────────────────────────────────────────────────
|
|
446
379
|
|
|
447
380
|
function isThemeId(value) {
|
|
@@ -526,6 +459,112 @@ class SettingsStore {
|
|
|
526
459
|
}
|
|
527
460
|
}
|
|
528
461
|
|
|
462
|
+
// ── remote workspaces ───────────────────────────────────────────────────────
|
|
463
|
+
|
|
464
|
+
/**
|
|
465
|
+
* RemoteWorkspaceStore manages remote workspaces: SSH-backed directories that
|
|
466
|
+
* can host DSH sessions without a paired local folder. Each remote workspace
|
|
467
|
+
* maintains a placeholder directory for occupancy records and references a
|
|
468
|
+
* registered DSH workspace created via ensureDshWorkspace.
|
|
469
|
+
*/
|
|
470
|
+
class RemoteWorkspaceStore {
|
|
471
|
+
constructor(registryFile) {
|
|
472
|
+
this.file = registryFile
|
|
473
|
+
this.records = new Map()
|
|
474
|
+
const raw = readJsonFile(registryFile, { version: 1, remoteWorkspaces: [] })
|
|
475
|
+
const list = raw && Array.isArray(raw.remoteWorkspaces) ? raw.remoteWorkspaces : []
|
|
476
|
+
for (const item of list) {
|
|
477
|
+
if (!item || typeof item !== 'object') continue
|
|
478
|
+
if (typeof item.id !== 'string' || item.id === '') continue
|
|
479
|
+
if (typeof item.hostId !== 'string' || item.hostId === '') continue
|
|
480
|
+
if (typeof item.remotePath !== 'string' || item.remotePath === '') continue
|
|
481
|
+
if (typeof item.placeholderPath !== 'string' || item.placeholderPath === '') continue
|
|
482
|
+
this.records.set(item.id, {
|
|
483
|
+
id: item.id,
|
|
484
|
+
hostId: item.hostId,
|
|
485
|
+
remotePath: item.remotePath,
|
|
486
|
+
placeholderPath: item.placeholderPath,
|
|
487
|
+
name: typeof item.name === 'string' ? item.name : '',
|
|
488
|
+
workspaceId: typeof item.workspaceId === 'string' ? item.workspaceId : '',
|
|
489
|
+
hostSnapshot: item.hostSnapshot && typeof item.hostSnapshot === 'object' ? item.hostSnapshot : null,
|
|
490
|
+
createdAt: typeof item.createdAt === 'number' ? item.createdAt : Date.now(),
|
|
491
|
+
})
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
list() {
|
|
496
|
+
return Array.from(this.records.values())
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
get(id) {
|
|
500
|
+
return this.records.get(id) || null
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
add(record) {
|
|
504
|
+
if (!record || typeof record !== 'object') throw new ApiError('BAD_REQUEST', 'invalid record')
|
|
505
|
+
if (typeof record.id !== 'string' || record.id === '') throw new ApiError('BAD_REQUEST', 'id is required')
|
|
506
|
+
if (this.records.has(record.id)) throw new ApiError('BAD_REQUEST', 'id already exists')
|
|
507
|
+
if (typeof record.hostId !== 'string' || record.hostId === '') throw new ApiError('BAD_REQUEST', 'hostId is required')
|
|
508
|
+
if (typeof record.remotePath !== 'string' || record.remotePath === '') throw new ApiError('BAD_REQUEST', 'remotePath is required')
|
|
509
|
+
if (typeof record.placeholderPath !== 'string' || record.placeholderPath === '') {
|
|
510
|
+
throw new ApiError('BAD_REQUEST', 'placeholderPath is required')
|
|
511
|
+
}
|
|
512
|
+
const entry = {
|
|
513
|
+
id: record.id,
|
|
514
|
+
hostId: record.hostId,
|
|
515
|
+
remotePath: record.remotePath,
|
|
516
|
+
placeholderPath: record.placeholderPath,
|
|
517
|
+
name: typeof record.name === 'string' ? record.name : '',
|
|
518
|
+
workspaceId: typeof record.workspaceId === 'string' ? record.workspaceId : '',
|
|
519
|
+
hostSnapshot: record.hostSnapshot && typeof record.hostSnapshot === 'object' ? record.hostSnapshot : null,
|
|
520
|
+
createdAt: typeof record.createdAt === 'number' ? record.createdAt : Date.now(),
|
|
521
|
+
}
|
|
522
|
+
this.records.set(entry.id, entry)
|
|
523
|
+
this.save()
|
|
524
|
+
return entry
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
update(id, patch) {
|
|
528
|
+
const record = this.records.get(id)
|
|
529
|
+
if (!record) throw new ApiError('NOT_FOUND', 'remote workspace not found')
|
|
530
|
+
if (patch.name !== undefined) {
|
|
531
|
+
if (typeof patch.name !== 'string') throw new ApiError('BAD_REQUEST', 'name must be a string')
|
|
532
|
+
record.name = patch.name
|
|
533
|
+
}
|
|
534
|
+
if (patch.workspaceId !== undefined) {
|
|
535
|
+
if (typeof patch.workspaceId !== 'string') throw new ApiError('BAD_REQUEST', 'workspaceId must be a string')
|
|
536
|
+
record.workspaceId = patch.workspaceId
|
|
537
|
+
}
|
|
538
|
+
if (patch.hostSnapshot !== undefined) {
|
|
539
|
+
record.hostSnapshot = patch.hostSnapshot && typeof patch.hostSnapshot === 'object' ? patch.hostSnapshot : null
|
|
540
|
+
}
|
|
541
|
+
this.save()
|
|
542
|
+
return record
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
remove(id) {
|
|
546
|
+
const record = this.records.get(id)
|
|
547
|
+
if (!record) throw new ApiError('NOT_FOUND', 'remote workspace not found')
|
|
548
|
+
this.records.delete(id)
|
|
549
|
+
this.save()
|
|
550
|
+
return record
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
findByPlaceholder(placeholderPath) {
|
|
554
|
+
const wanted = linkedFs.localPathKey(placeholderPath)
|
|
555
|
+
if (wanted === '') return null
|
|
556
|
+
for (const record of this.records.values()) {
|
|
557
|
+
if (linkedFs.localPathKey(record.placeholderPath) === wanted) return record
|
|
558
|
+
}
|
|
559
|
+
return null
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
save() {
|
|
563
|
+
const list = Array.from(this.records.values())
|
|
564
|
+
writeJsonAtomic(this.file, { version: 1, remoteWorkspaces: list })
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
|
|
529
568
|
// ── local filesystem helpers ────────────────────────────────────────────────
|
|
530
569
|
|
|
531
570
|
function mapLocalFsError(error, fallback = 'INTERNAL') {
|
|
@@ -715,8 +754,11 @@ function linkedManifestFor(record) {
|
|
|
715
754
|
// ── connection pool ─────────────────────────────────────────────────────────
|
|
716
755
|
|
|
717
756
|
class HostPool {
|
|
718
|
-
constructor({ knownHostsFile }) {
|
|
757
|
+
constructor({ knownHostsFile, credentialFile }) {
|
|
719
758
|
this.knownHostsFile = knownHostsFile
|
|
759
|
+
// Secrets the user stored from the add-workspace dialog. Kept apart from the
|
|
760
|
+
// SSH Manager so the plugin works without `dsh-ssh-tunnel`.
|
|
761
|
+
this.credentialFile = credentialFile || null
|
|
720
762
|
this.records = new Map() // hostId -> HostRecord
|
|
721
763
|
this.connections = new Map() // hostId -> { authority, remote: RemoteHost }
|
|
722
764
|
this.connecting = new Map() // hostId -> { authority, promise }
|
|
@@ -758,12 +800,41 @@ class HostPool {
|
|
|
758
800
|
this.statuses.set(hostId, { ...status, checkedAt: Date.now() })
|
|
759
801
|
}
|
|
760
802
|
|
|
803
|
+
/**
|
|
804
|
+
* Record that an established connection died on its own (network drop, server
|
|
805
|
+
* restart, keepalive timeout). Callers keep working: the next request dials
|
|
806
|
+
* again, and a successful connect clears the error.
|
|
807
|
+
*/
|
|
808
|
+
noteConnectionLost(hostId, remote, reason) {
|
|
809
|
+
const entry = this.connections.get(hostId)
|
|
810
|
+
if (!entry || entry.remote !== remote) return
|
|
811
|
+
this.connections.delete(hostId)
|
|
812
|
+
const previous = this.statuses.get(hostId) || {}
|
|
813
|
+
this.setStatus(hostId, {
|
|
814
|
+
state: 'error',
|
|
815
|
+
reason: 'lost',
|
|
816
|
+
message: reason || '',
|
|
817
|
+
latencyMs: previous.latencyMs,
|
|
818
|
+
})
|
|
819
|
+
log('warn', `SSH connection to ${entry.authority} lost: ${reason || 'closed'}`)
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
noteConnectionReady(hostId) {
|
|
823
|
+
const previous = this.statuses.get(hostId) || {}
|
|
824
|
+
if (previous.state === 'connected' && !previous.reason) return
|
|
825
|
+
this.setStatus(hostId, {
|
|
826
|
+
state: 'connected',
|
|
827
|
+
latencyMs: previous.latencyMs,
|
|
828
|
+
})
|
|
829
|
+
}
|
|
830
|
+
|
|
761
831
|
async remote(hostRecord) {
|
|
762
832
|
const authority = `${hostRecord.host}:${hostRecord.port}`
|
|
763
833
|
const existing = this.connections.get(hostRecord.id)
|
|
764
834
|
if (existing && existing.authority === authority) {
|
|
765
835
|
try {
|
|
766
836
|
await existing.remote.ensureConnected()
|
|
837
|
+
this.noteConnectionReady(hostRecord.id)
|
|
767
838
|
return existing.remote
|
|
768
839
|
} catch (error) {
|
|
769
840
|
existing.remote.dispose().catch(() => {})
|
|
@@ -781,8 +852,10 @@ class HostPool {
|
|
|
781
852
|
const remote = new RemoteHost({
|
|
782
853
|
host: hostRecord,
|
|
783
854
|
knownHostsFile: this.knownHostsFile,
|
|
855
|
+
credentialFile: this.credentialFile,
|
|
784
856
|
connectTimeoutMs: CONNECT_TIMEOUT_MS,
|
|
785
857
|
logger: log,
|
|
858
|
+
onLost: (info) => this.noteConnectionLost(hostRecord.id, remote, info && info.reason),
|
|
786
859
|
})
|
|
787
860
|
const entry = { authority, remote }
|
|
788
861
|
this.connections.set(hostRecord.id, entry)
|
|
@@ -793,6 +866,8 @@ class HostPool {
|
|
|
793
866
|
// the map state authoritative so the unused connection is closed.
|
|
794
867
|
if (this.connections.get(hostRecord.id) !== entry) {
|
|
795
868
|
remote.dispose().catch(() => {})
|
|
869
|
+
} else {
|
|
870
|
+
this.noteConnectionReady(hostRecord.id)
|
|
796
871
|
}
|
|
797
872
|
return remote
|
|
798
873
|
} catch (error) {
|
|
@@ -821,9 +896,9 @@ export function apply(ctx) {
|
|
|
821
896
|
const dir = dataDir()
|
|
822
897
|
migrateLegacyDataDir(dir)
|
|
823
898
|
ensureDir(dir)
|
|
824
|
-
const store = new WorkspaceStore(join(dir, 'workspaces.json'))
|
|
825
899
|
const settingsStore = new SettingsStore(join(dir, 'settings.json'))
|
|
826
900
|
const linkedStore = new linkedFs.LinkedStore(join(dir, 'linked.json'))
|
|
901
|
+
const remoteStore = new RemoteWorkspaceStore(join(dir, 'remote-workspaces.json'))
|
|
827
902
|
// 0.5.0: mirror sync is opt-in. Records created under the old default
|
|
828
903
|
// (mirror on, never explicitly chosen) are switched off once.
|
|
829
904
|
for (const existing of linkedStore.list()) {
|
|
@@ -835,7 +910,10 @@ export function apply(ctx) {
|
|
|
835
910
|
}
|
|
836
911
|
}
|
|
837
912
|
}
|
|
838
|
-
const pool = new HostPool({
|
|
913
|
+
const pool = new HostPool({
|
|
914
|
+
knownHostsFile: join(dir, 'known_hosts.json'),
|
|
915
|
+
credentialFile: join(dir, 'ssh-credentials.json'),
|
|
916
|
+
})
|
|
839
917
|
|
|
840
918
|
let hostsCache = null
|
|
841
919
|
let hostsRefreshedAt = 0
|
|
@@ -843,18 +921,33 @@ export function apply(ctx) {
|
|
|
843
921
|
const refreshHosts = async (force) => {
|
|
844
922
|
if (!force && hostsCache !== null && Date.now() - hostsRefreshedAt < 15_000) return hostsCache
|
|
845
923
|
try {
|
|
846
|
-
const hosts = await listHosts()
|
|
924
|
+
const hosts = await listHosts({ credentialFile: join(dir, 'ssh-credentials.json') })
|
|
847
925
|
hostsCache = hosts
|
|
848
926
|
hostsRefreshedAt = Date.now()
|
|
849
927
|
pool.setHosts(hosts)
|
|
850
928
|
for (const host of hosts) {
|
|
851
|
-
// Keep the denormalized snapshot fresh for every workspace on this host
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
929
|
+
// Keep the denormalized snapshot fresh for every workspace on this host,
|
|
930
|
+
// so a removed SSH host still renders with its last known address.
|
|
931
|
+
const snapshot = { name: host.name, host: host.host, port: host.port, username: host.username }
|
|
932
|
+
const fresh = (record) => {
|
|
933
|
+
const current = record.hostSnapshot || {}
|
|
934
|
+
return current.name === snapshot.name
|
|
935
|
+
&& current.host === snapshot.host
|
|
936
|
+
&& current.port === snapshot.port
|
|
937
|
+
&& current.username === snapshot.username
|
|
938
|
+
}
|
|
939
|
+
for (const record of linkedStore.list()) {
|
|
940
|
+
if (record.hostId !== host.id || fresh(record)) continue
|
|
941
|
+
try { linkedStore.update(record.id, { hostSnapshot: snapshot }) } catch (error) {
|
|
942
|
+
log('warn', `cannot refresh host snapshot for link "${record.id}": ${error && error.message ? error.message : error}`)
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
for (const record of remoteStore.list()) {
|
|
946
|
+
if (record.hostId !== host.id || fresh(record)) continue
|
|
947
|
+
try { remoteStore.update(record.id, { hostSnapshot: snapshot }) } catch (error) {
|
|
948
|
+
log('warn', `cannot refresh host snapshot for remote workspace "${record.id}": ${error && error.message ? error.message : error}`)
|
|
949
|
+
}
|
|
950
|
+
}
|
|
858
951
|
}
|
|
859
952
|
return hosts
|
|
860
953
|
} catch (error) {
|
|
@@ -887,33 +980,6 @@ export function apply(ctx) {
|
|
|
887
980
|
}
|
|
888
981
|
}
|
|
889
982
|
|
|
890
|
-
const requireWorkspace = (workspaceId) => {
|
|
891
|
-
if (typeof workspaceId !== 'string' || workspaceId === '') {
|
|
892
|
-
throw new ApiError('BAD_REQUEST', 'workspaceId is required')
|
|
893
|
-
}
|
|
894
|
-
const workspace = store.get(workspaceId)
|
|
895
|
-
if (!workspace) throw new ApiError('NOT_FOUND', `远程工作区不存在: ${workspaceId}`)
|
|
896
|
-
return workspace
|
|
897
|
-
}
|
|
898
|
-
|
|
899
|
-
const workspaceRemote = async (workspace) => {
|
|
900
|
-
let host = pool.host(workspace.hostId)
|
|
901
|
-
if (!host) {
|
|
902
|
-
await refreshHosts(true)
|
|
903
|
-
host = pool.host(workspace.hostId)
|
|
904
|
-
}
|
|
905
|
-
if (!host) {
|
|
906
|
-
// Fall back to the snapshot so a temporarily unreadable SSH store still
|
|
907
|
-
// produces a useful error instead of a generic 404.
|
|
908
|
-
const snapshot = workspace.hostSnapshot || {}
|
|
909
|
-
throw new ApiError(
|
|
910
|
-
'NOT_FOUND',
|
|
911
|
-
`SSH 连接不可用:主机「${snapshot.name || workspace.hostId}」已不在 SSH 管理器中`,
|
|
912
|
-
)
|
|
913
|
-
}
|
|
914
|
-
return connectHost(host)
|
|
915
|
-
}
|
|
916
|
-
|
|
917
983
|
const normalizeRemotePath = async (remote, rawPath) => {
|
|
918
984
|
if (typeof rawPath !== 'string' || rawPath.trim() === '') {
|
|
919
985
|
throw new ApiError('BAD_REQUEST', 'path is required')
|
|
@@ -927,42 +993,6 @@ export function apply(ctx) {
|
|
|
927
993
|
return posix.resolve(target)
|
|
928
994
|
}
|
|
929
995
|
|
|
930
|
-
const resolveInside = (workspace, rawPath) => {
|
|
931
|
-
if (typeof rawPath !== 'string' || rawPath.trim() === '') throw new ApiError('BAD_REQUEST', 'path is required')
|
|
932
|
-
const root = posix.resolve(workspace.remotePath)
|
|
933
|
-
const target = posix.resolve(root, rawPath.trim())
|
|
934
|
-
if (!isInside(root, target)) throw new ApiError('BAD_REQUEST', '路径超出该远程工作区的范围')
|
|
935
|
-
return target
|
|
936
|
-
}
|
|
937
|
-
|
|
938
|
-
const relativeInside = (workspace, absolutePath) => {
|
|
939
|
-
const root = posix.resolve(workspace.remotePath)
|
|
940
|
-
if (absolutePath === root) return ''
|
|
941
|
-
return absolutePath.slice(root.length + 1)
|
|
942
|
-
}
|
|
943
|
-
|
|
944
|
-
const describeWorkspace = (workspace) => {
|
|
945
|
-
const host = pool.host(workspace.hostId)
|
|
946
|
-
const snapshot = workspace.hostSnapshot || {}
|
|
947
|
-
const status = pool.status(workspace.hostId)
|
|
948
|
-
return {
|
|
949
|
-
id: workspace.id,
|
|
950
|
-
name: workspace.name,
|
|
951
|
-
hostId: workspace.hostId,
|
|
952
|
-
hostName: host ? host.name : snapshot.name || workspace.hostId,
|
|
953
|
-
host: host ? host.host : snapshot.host || '',
|
|
954
|
-
port: host ? host.port : snapshot.port || 22,
|
|
955
|
-
username: host ? host.username : snapshot.username || '',
|
|
956
|
-
remotePath: workspace.remotePath,
|
|
957
|
-
createdAt: workspace.createdAt,
|
|
958
|
-
status: {
|
|
959
|
-
state: status ? status.state : 'idle',
|
|
960
|
-
...(status && status.message ? { message: status.message } : {}),
|
|
961
|
-
...(status && typeof status.latencyMs === 'number' ? { latencyMs: status.latencyMs } : {}),
|
|
962
|
-
},
|
|
963
|
-
}
|
|
964
|
-
}
|
|
965
|
-
|
|
966
996
|
// ── linked workspaces ───────────────────────────────────────────────────
|
|
967
997
|
|
|
968
998
|
const linkedRegistry = () => {
|
|
@@ -1020,12 +1050,59 @@ export function apply(ctx) {
|
|
|
1020
1050
|
workspaceTitle: workspace ? workspace.title : null,
|
|
1021
1051
|
status: {
|
|
1022
1052
|
state: status ? status.state : 'idle',
|
|
1053
|
+
...(status && status.reason ? { reason: status.reason } : {}),
|
|
1023
1054
|
...(status && status.message ? { message: status.message } : {}),
|
|
1024
1055
|
...(status && typeof status.latencyMs === 'number' ? { latencyMs: status.latencyMs } : {}),
|
|
1025
1056
|
},
|
|
1026
1057
|
}
|
|
1027
1058
|
}
|
|
1028
1059
|
|
|
1060
|
+
/** A record is a remote workspace when it owns a placeholder directory, not a local path. */
|
|
1061
|
+
const isRemoteRecord = (record) => Boolean(record && record.placeholderPath && !record.localPath)
|
|
1062
|
+
|
|
1063
|
+
const describeRemote = (record) => {
|
|
1064
|
+
const host = pool.host(record.hostId)
|
|
1065
|
+
const snapshot = record.hostSnapshot || {}
|
|
1066
|
+
const status = pool.status(record.hostId)
|
|
1067
|
+
return {
|
|
1068
|
+
id: record.id,
|
|
1069
|
+
name: record.name,
|
|
1070
|
+
hostId: record.hostId,
|
|
1071
|
+
hostName: host ? host.name : snapshot.name || record.hostId,
|
|
1072
|
+
host: host ? host.host : snapshot.host || '',
|
|
1073
|
+
port: host ? host.port : snapshot.port || 22,
|
|
1074
|
+
username: host ? host.username : snapshot.username || '',
|
|
1075
|
+
remotePath: record.remotePath,
|
|
1076
|
+
placeholderPath: record.placeholderPath,
|
|
1077
|
+
workspaceId: record.workspaceId || null,
|
|
1078
|
+
createdAt: record.createdAt,
|
|
1079
|
+
status: {
|
|
1080
|
+
state: status ? status.state : 'idle',
|
|
1081
|
+
...(status && status.reason ? { reason: status.reason } : {}),
|
|
1082
|
+
...(status && status.message ? { message: status.message } : {}),
|
|
1083
|
+
...(status && typeof status.latencyMs === 'number' ? { latencyMs: status.latencyMs } : {}),
|
|
1084
|
+
},
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
/** Path the session runs in: the paired local directory, or the placeholder of a remote workspace. */
|
|
1089
|
+
const recordLocalPath = (record) => (record && (record.localPath || record.placeholderPath)) || ''
|
|
1090
|
+
|
|
1091
|
+
/** Find the remote workspace whose placeholder directory contains this cwd. */
|
|
1092
|
+
const remoteWorkspaceByCwd = (cwd) => {
|
|
1093
|
+
const cwdKey = linkedFs.localPathKey(cwd)
|
|
1094
|
+
if (!cwdKey) return undefined
|
|
1095
|
+
let best
|
|
1096
|
+
for (const record of remoteStore.list()) {
|
|
1097
|
+
const key = linkedFs.localPathKey(record.placeholderPath)
|
|
1098
|
+
if (!key) continue
|
|
1099
|
+
const matches = cwdKey === key || cwdKey.startsWith(`${key}${sep}`) || cwdKey.startsWith(`${key}/`)
|
|
1100
|
+
if (!matches) continue
|
|
1101
|
+
if (!best || key.length > best.key.length) best = { record, key }
|
|
1102
|
+
}
|
|
1103
|
+
return best ? best.record : undefined
|
|
1104
|
+
}
|
|
1105
|
+
|
|
1029
1106
|
/** Strip the old "⇄ " title prefix once; the sidebar icon is replaced by CSS. */
|
|
1030
1107
|
const migrateLinkedWorkspaceTitles = async () => {
|
|
1031
1108
|
const registry = linkedRegistry()
|
|
@@ -1047,6 +1124,12 @@ export function apply(ctx) {
|
|
|
1047
1124
|
return record
|
|
1048
1125
|
}
|
|
1049
1126
|
|
|
1127
|
+
const requireRemote = (id) => {
|
|
1128
|
+
const record = remoteStore.get(id)
|
|
1129
|
+
if (!record) throw new ApiError('NOT_FOUND', `远程工作区不存在: ${id}`)
|
|
1130
|
+
return record
|
|
1131
|
+
}
|
|
1132
|
+
|
|
1050
1133
|
const hostForLink = async (record) => {
|
|
1051
1134
|
let host = pool.host(record.hostId)
|
|
1052
1135
|
if (!host) {
|
|
@@ -1287,11 +1370,17 @@ export function apply(ctx) {
|
|
|
1287
1370
|
if (reference !== '') {
|
|
1288
1371
|
const direct = linkedStore.get(reference)
|
|
1289
1372
|
if (direct) return direct
|
|
1373
|
+
const remoteDirect = remoteStore.get(reference)
|
|
1374
|
+
if (remoteDirect) return remoteDirect
|
|
1290
1375
|
const byPath = linkedStore.findByLocalPath(reference)
|
|
1291
1376
|
if (byPath) return byPath
|
|
1377
|
+
const byPlaceholder = remoteStore.findByPlaceholder(reference)
|
|
1378
|
+
if (byPlaceholder) return byPlaceholder
|
|
1292
1379
|
const byName = linkedStore.list().find((record) => record.name === reference)
|
|
1293
1380
|
if (byName) return byName
|
|
1294
|
-
|
|
1381
|
+
const remoteByName = remoteStore.list().find((record) => record.name === reference)
|
|
1382
|
+
if (remoteByName) return remoteByName
|
|
1383
|
+
throw new ApiError('NOT_FOUND', `联动工作区或远程工作区不存在: ${reference}`)
|
|
1295
1384
|
}
|
|
1296
1385
|
if (!exec || !exec.agent) throw new ApiError('BAD_REQUEST', '需要 agent 会话或显式 workspace 参数')
|
|
1297
1386
|
const cwd = await ctx.workingDirectory.ensure(exec.agent, exec.signal)
|
|
@@ -1303,23 +1392,27 @@ export function apply(ctx) {
|
|
|
1303
1392
|
if (!matches) continue
|
|
1304
1393
|
if (!best || localKey.length > best.key.length) best = { record, key: localKey }
|
|
1305
1394
|
}
|
|
1306
|
-
if (
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1395
|
+
if (best) return best.record
|
|
1396
|
+
// A remote-workspace session runs inside its placeholder directory; the
|
|
1397
|
+
// project files live on the SSH host, so the same tool actions apply.
|
|
1398
|
+
const remoteRecord = remoteWorkspaceByCwd(cwd)
|
|
1399
|
+
if (remoteRecord) return remoteRecord
|
|
1400
|
+
throw new ApiError('NOT_FOUND', '当前会话工作目录既不是联动工作区也不是远程工作区;先调用 action="list" 查看可用工作区,或用 workspace 参数指定')
|
|
1310
1401
|
}
|
|
1311
1402
|
|
|
1312
1403
|
const linkedPrompt = [
|
|
1313
|
-
'
|
|
1314
|
-
'
|
|
1315
|
-
'
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
'- action "
|
|
1404
|
+
'Remote workspaces (dsh-linked-workspace)',
|
|
1405
|
+
'This plugin provides two kinds of SSH-backed project:',
|
|
1406
|
+
'1. Linked workspace — a local directory paired with a remote directory (the local directory shows "⇄" in the sidebar). The session working directory is the LOCAL directory, while the real project files live under the REMOTE root.',
|
|
1407
|
+
'2. Remote workspace — a remote directory that owns a local PLACEHOLDER directory under ~/.dsh/linked-workspace/remote-placeholders/<uuid>. The session working directory is that placeholder; it stays empty, and every project file, build output and log lives on the REMOTE host.',
|
|
1408
|
+
`Use the \`${LINKED_TOOL_NAME}\` tool for remote files in both cases:`,
|
|
1409
|
+
'- action "list" returns every linked and remote workspace with its local path (or placeholder), SSH host, remote root and mirror state.',
|
|
1410
|
+
'- action "info" | "list_dir" | "read" | "write" | "replace" | "stat" | "mkdir" | "rename" | "delete" takes `path` relative to the remote root (or an absolute path inside it).',
|
|
1319
1411
|
'- Writes are atomic. Pass `if_modified_since` (epoch milliseconds from a previous read/stat) to refuse a stale overwrite.',
|
|
1320
|
-
'- action "sync" archives the remote tree into `.remote/`
|
|
1321
|
-
'
|
|
1322
|
-
'
|
|
1412
|
+
'- action "sync" archives the remote tree into `.remote/` and only exists for a linked workspace (a remote workspace has no local copy).',
|
|
1413
|
+
'The workspace is resolved from the session working directory; pass `workspace` (id, local path, placeholder path or name) when working elsewhere.',
|
|
1414
|
+
'For a REMOTE workspace do not create project files in the placeholder and do not expect local paths to exist: read, write, build and inspect logs on the remote host, through linked_workspace actions or `ssh` when an action does not fit.',
|
|
1415
|
+
'Locally installed skills (~/.dsh/skills, ~/.agents/skills) remain available; use `linked_skills` to list or read them. A linked workspace also sees the project skills of its local directory.',
|
|
1323
1416
|
'Do not hand-edit `.remote/`; it is a mirror of the remote tree. Prefer linked_workspace over bash/read/write for anything under the remote root, and list first when unsure which workspace you are in.',
|
|
1324
1417
|
].join('\n')
|
|
1325
1418
|
|
|
@@ -1329,14 +1422,15 @@ export function apply(ctx) {
|
|
|
1329
1422
|
if (typeof params.linkedId === 'string' && params.linkedId.trim() !== '') {
|
|
1330
1423
|
const record = requireLinked(params.linkedId.trim())
|
|
1331
1424
|
const remote = await hostForLink(record)
|
|
1332
|
-
return { kind: 'linked', record, remote, root: linkedRootOf(record) }
|
|
1425
|
+
return { kind: 'linked', record, remote, root: linkedRootOf(record), id: record.id }
|
|
1333
1426
|
}
|
|
1334
|
-
if (typeof params.
|
|
1335
|
-
const
|
|
1336
|
-
const
|
|
1337
|
-
|
|
1427
|
+
if (typeof params.remoteId === 'string' && params.remoteId.trim() !== '') {
|
|
1428
|
+
const record = requireRemote(params.remoteId.trim())
|
|
1429
|
+
const host = await findHost(record.hostId)
|
|
1430
|
+
const remote = await connectHost(host)
|
|
1431
|
+
return { kind: 'remote', record, remote, root: posix.resolve(record.remotePath), id: record.id }
|
|
1338
1432
|
}
|
|
1339
|
-
throw new ApiError('BAD_REQUEST', '
|
|
1433
|
+
throw new ApiError('BAD_REQUEST', 'linkedId or remoteId is required')
|
|
1340
1434
|
}
|
|
1341
1435
|
|
|
1342
1436
|
const scopeTarget = (scope, rawPath) => {
|
|
@@ -1892,10 +1986,50 @@ export function apply(ctx) {
|
|
|
1892
1986
|
authType: host.authType,
|
|
1893
1987
|
source: host.source,
|
|
1894
1988
|
hasCredential: host.hasCredential,
|
|
1989
|
+
hasStoredPassword: Boolean(host.hasStoredPassword),
|
|
1895
1990
|
})),
|
|
1896
1991
|
}
|
|
1897
1992
|
},
|
|
1898
1993
|
|
|
1994
|
+
/**
|
|
1995
|
+
* Store a credential for one SSH host on this machine.
|
|
1996
|
+
*
|
|
1997
|
+
* This is what makes the plugin usable without `dsh-ssh-tunnel`: a host from
|
|
1998
|
+
* `~/.ssh/config` that has no `IdentityFile` becomes selectable once a
|
|
1999
|
+
* password is stored here. The secret is written to
|
|
2000
|
+
* `<dataDir>/ssh-credentials.json` (mode 0600) and never returned.
|
|
2001
|
+
*/
|
|
2002
|
+
async 'hosts.credentials'(params = {}) {
|
|
2003
|
+
const hostId = typeof params.hostId === 'string' ? params.hostId.trim() : ''
|
|
2004
|
+
if (!hostId) throw new ApiError('BAD_REQUEST', 'hostId is required')
|
|
2005
|
+
const clear = params.clear === true
|
|
2006
|
+
const password = typeof params.password === 'string' ? params.password : ''
|
|
2007
|
+
const passphrase = typeof params.passphrase === 'string' ? params.passphrase : ''
|
|
2008
|
+
const privateKey = typeof params.privateKey === 'string' ? params.privateKey : ''
|
|
2009
|
+
if (!clear && !password && !passphrase && !privateKey) {
|
|
2010
|
+
throw new ApiError('BAD_REQUEST', '请填写 SSH 密码(或用 clear 清除已保存的凭据)')
|
|
2011
|
+
}
|
|
2012
|
+
const host = await findHost(hostId)
|
|
2013
|
+
// A live socket authenticated with the old credential must be dropped so
|
|
2014
|
+
// the next request dials again.
|
|
2015
|
+
const live = pool.connection(hostId)
|
|
2016
|
+
if (live) {
|
|
2017
|
+
pool.connections.delete(hostId)
|
|
2018
|
+
live.dispose().catch(() => {})
|
|
2019
|
+
}
|
|
2020
|
+
await writeLocalCredential(join(dir, 'ssh-credentials.json'), hostId, clear
|
|
2021
|
+
? null
|
|
2022
|
+
: { password, passphrase, privateKey })
|
|
2023
|
+
const hosts = await refreshHosts(true)
|
|
2024
|
+
const updated = hosts.find((item) => item.id === host.id) || host
|
|
2025
|
+
return {
|
|
2026
|
+
hostId: host.id,
|
|
2027
|
+
authType: updated.authType,
|
|
2028
|
+
hasCredential: Boolean(updated.hasCredential),
|
|
2029
|
+
hasStoredPassword: Boolean(updated.hasStoredPassword),
|
|
2030
|
+
}
|
|
2031
|
+
},
|
|
2032
|
+
|
|
1899
2033
|
async 'hosts.browse'(params = {}) {
|
|
1900
2034
|
const host = await findHost(params.hostId)
|
|
1901
2035
|
const remote = await connectHost(host)
|
|
@@ -1920,71 +2054,6 @@ export function apply(ctx) {
|
|
|
1920
2054
|
}
|
|
1921
2055
|
},
|
|
1922
2056
|
|
|
1923
|
-
async 'workspaces.list'() {
|
|
1924
|
-
await refreshHosts()
|
|
1925
|
-
return { workspaces: store.list().map(describeWorkspace) }
|
|
1926
|
-
},
|
|
1927
|
-
|
|
1928
|
-
async 'workspaces.add'(params = {}) {
|
|
1929
|
-
const host = await findHost(params.hostId)
|
|
1930
|
-
const remote = await connectHost(host)
|
|
1931
|
-
const requested = typeof params.name === 'string' ? params.name.trim() : ''
|
|
1932
|
-
if (requested.length > MAX_NAME_LENGTH) throw new ApiError('BAD_REQUEST', '工作区名称过长')
|
|
1933
|
-
const rawPath = await normalizeRemotePath(remote, params.remotePath)
|
|
1934
|
-
const resolved = await remote.realpath(rawPath).catch(() => rawPath)
|
|
1935
|
-
const stat = await remote.stat(resolved)
|
|
1936
|
-
if (stat.type !== 'dir') throw new ApiError('FS_NOT_DIR', '远程路径不是目录')
|
|
1937
|
-
const existing = store.find(host.id, resolved)
|
|
1938
|
-
if (existing) throw new ApiError('BAD_REQUEST', '该目录已经是远程工作区')
|
|
1939
|
-
const entry = {
|
|
1940
|
-
id: randomUUID(),
|
|
1941
|
-
name: requested !== '' ? requested : posix.basename(resolved) || host.name,
|
|
1942
|
-
hostId: host.id,
|
|
1943
|
-
hostSnapshot: {
|
|
1944
|
-
name: host.name,
|
|
1945
|
-
host: host.host,
|
|
1946
|
-
port: host.port,
|
|
1947
|
-
username: host.username,
|
|
1948
|
-
},
|
|
1949
|
-
remotePath: resolved,
|
|
1950
|
-
createdAt: Date.now(),
|
|
1951
|
-
}
|
|
1952
|
-
store.add(entry)
|
|
1953
|
-
pool.setStatus(host.id, { state: 'connected', latencyMs: 0 })
|
|
1954
|
-
return { workspace: describeWorkspace(entry) }
|
|
1955
|
-
},
|
|
1956
|
-
|
|
1957
|
-
async 'workspaces.remove'(params = {}) {
|
|
1958
|
-
const workspace = requireWorkspace(params.id)
|
|
1959
|
-
store.remove(workspace.id)
|
|
1960
|
-
return {}
|
|
1961
|
-
},
|
|
1962
|
-
|
|
1963
|
-
async 'workspaces.rename'(params = {}) {
|
|
1964
|
-
const workspace = requireWorkspace(params.id)
|
|
1965
|
-
const next = typeof params.name === 'string' ? params.name.trim() : ''
|
|
1966
|
-
if (next === '') throw new ApiError('BAD_REQUEST', '名称不能为空')
|
|
1967
|
-
if (next.length > MAX_NAME_LENGTH) throw new ApiError('BAD_REQUEST', '名称过长')
|
|
1968
|
-
store.rename(workspace.id, next)
|
|
1969
|
-
return { workspace: describeWorkspace(workspace) }
|
|
1970
|
-
},
|
|
1971
|
-
|
|
1972
|
-
async 'workspaces.test'(params = {}) {
|
|
1973
|
-
const workspace = requireWorkspace(params.id)
|
|
1974
|
-
const started = Date.now()
|
|
1975
|
-
try {
|
|
1976
|
-
const remote = await workspaceRemote(workspace)
|
|
1977
|
-
const stat = await remote.stat(workspace.remotePath)
|
|
1978
|
-
if (stat.type !== 'dir') throw new ApiError('FS_NOT_DIR', '远程目录已不存在')
|
|
1979
|
-
const label = `${workspace.hostSnapshot.username}@${workspace.hostSnapshot.host}`
|
|
1980
|
-
log('info', `test ok ${label}:${workspace.remotePath} in ${Date.now() - started}ms`)
|
|
1981
|
-
return { ok: true, latencyMs: Date.now() - started, resolvedPath: workspace.remotePath }
|
|
1982
|
-
} catch (error) {
|
|
1983
|
-
const apiError = asApiError(error)
|
|
1984
|
-
return { ok: false, latencyMs: Date.now() - started, error: apiError.message }
|
|
1985
|
-
}
|
|
1986
|
-
},
|
|
1987
|
-
|
|
1988
2057
|
async 'fs.list'(params = {}) {
|
|
1989
2058
|
const scope = await requireScope(params)
|
|
1990
2059
|
const target = params.path === undefined || params.path === ''
|
|
@@ -2776,7 +2845,7 @@ export function apply(ctx) {
|
|
|
2776
2845
|
const side = params.side === 'local' ? 'local' : 'remote'
|
|
2777
2846
|
const testMode = process.env.DSH_LINKED_WORKSPACE_NO_TERMINAL === '1'
|
|
2778
2847
|
const scope = await requireScope(params)
|
|
2779
|
-
const snapshot = scope.
|
|
2848
|
+
const snapshot = (scope.record && scope.record.hostSnapshot) || (pool.host(scope.record.hostId) || {})
|
|
2780
2849
|
if (side === 'local') {
|
|
2781
2850
|
if (scope.kind !== 'linked') throw new ApiError('BAD_REQUEST', '该工作区没有本地目录')
|
|
2782
2851
|
const localRoot = resolve(scope.record.localPath)
|
|
@@ -3267,6 +3336,159 @@ export function apply(ctx) {
|
|
|
3267
3336
|
job.cancel = true
|
|
3268
3337
|
return { cancelled: true }
|
|
3269
3338
|
},
|
|
3339
|
+
|
|
3340
|
+
// ── remote_workspaces methods ───────────────────────────────────────────────
|
|
3341
|
+
|
|
3342
|
+
async 'remote_workspaces.list'() {
|
|
3343
|
+
await refreshHosts()
|
|
3344
|
+
return { workspaces: remoteStore.list().map((record) => describeRemote(record)) }
|
|
3345
|
+
},
|
|
3346
|
+
|
|
3347
|
+
async 'remote_workspaces.create'(params = {}) {
|
|
3348
|
+
const host = await findHost(params.hostId)
|
|
3349
|
+
const remote = await connectHost(host)
|
|
3350
|
+
const rawRemote = await normalizeRemotePath(remote, params.remotePath)
|
|
3351
|
+
const remoteRoot = await remote.realpath(rawRemote).catch(() => rawRemote)
|
|
3352
|
+
const remoteStat = await remote.stat(remoteRoot)
|
|
3353
|
+
if (remoteStat.type !== 'dir') throw new ApiError('FS_NOT_DIR', '远程路径不是目录')
|
|
3354
|
+
|
|
3355
|
+
// Check for conflicts
|
|
3356
|
+
const remoteClash = remoteStore.list().find((r) => r.hostId === host.id && r.remotePath === remoteRoot)
|
|
3357
|
+
if (remoteClash) throw new ApiError('BAD_REQUEST', `该远程目录已被远程工作区「${remoteClash.name}」使用`)
|
|
3358
|
+
|
|
3359
|
+
const requestedName = typeof params.name === 'string' ? params.name.trim() : ''
|
|
3360
|
+
if (requestedName.length > MAX_NAME_LENGTH) throw new ApiError('BAD_REQUEST', '工作区名称过长')
|
|
3361
|
+
const name = requestedName !== '' ? requestedName : basename(remoteRoot) || host.name
|
|
3362
|
+
|
|
3363
|
+
// Create placeholder directory
|
|
3364
|
+
const placeholderBase = join(dir, 'remote-placeholders')
|
|
3365
|
+
await mkdir(placeholderBase, { recursive: true })
|
|
3366
|
+
const placeholderId = randomUUID()
|
|
3367
|
+
const placeholderPath = join(placeholderBase, placeholderId)
|
|
3368
|
+
await mkdir(placeholderPath, { recursive: true })
|
|
3369
|
+
|
|
3370
|
+
// Register as DSH workspace
|
|
3371
|
+
const registry = ctx.get('workspaceRegistry', true)
|
|
3372
|
+
const workspace = await ensureDshWorkspace(registry, placeholderPath, name)
|
|
3373
|
+
if (!workspace) throw new ApiError('INTERNAL', '无法注册占位工作区')
|
|
3374
|
+
|
|
3375
|
+
// Create remote workspace record
|
|
3376
|
+
const record = {
|
|
3377
|
+
id: randomUUID(),
|
|
3378
|
+
hostId: host.id,
|
|
3379
|
+
remotePath: remoteRoot,
|
|
3380
|
+
placeholderPath,
|
|
3381
|
+
name,
|
|
3382
|
+
workspaceId: workspace.id,
|
|
3383
|
+
hostSnapshot: {
|
|
3384
|
+
name: host.name,
|
|
3385
|
+
host: host.host,
|
|
3386
|
+
port: host.port,
|
|
3387
|
+
username: host.username,
|
|
3388
|
+
},
|
|
3389
|
+
createdAt: Date.now(),
|
|
3390
|
+
}
|
|
3391
|
+
const saved = remoteStore.add(record)
|
|
3392
|
+
|
|
3393
|
+
pool.setStatus(host.id, { state: 'connected', latencyMs: 0 })
|
|
3394
|
+
log('info', `remote workspace "${name}" (placeholder: ${placeholderPath}, remote: ${host.username}@${host.host}:${remoteRoot})`)
|
|
3395
|
+
|
|
3396
|
+
return { workspace: describeRemote(saved) }
|
|
3397
|
+
},
|
|
3398
|
+
|
|
3399
|
+
async 'remote_workspaces.get'(params = {}) {
|
|
3400
|
+
if (typeof params.id !== 'string' || params.id === '') throw new ApiError('BAD_REQUEST', 'id is required')
|
|
3401
|
+
const record = remoteStore.get(params.id)
|
|
3402
|
+
if (!record) throw new ApiError('NOT_FOUND', 'remote workspace not found')
|
|
3403
|
+
return { workspace: describeRemote(record) }
|
|
3404
|
+
},
|
|
3405
|
+
|
|
3406
|
+
async 'remote_workspaces.update'(params = {}) {
|
|
3407
|
+
if (typeof params.id !== 'string' || params.id === '') throw new ApiError('BAD_REQUEST', 'id is required')
|
|
3408
|
+
const record = remoteStore.get(params.id)
|
|
3409
|
+
if (!record) throw new ApiError('NOT_FOUND', 'remote workspace not found')
|
|
3410
|
+
|
|
3411
|
+
const patch = {}
|
|
3412
|
+
if (params.name !== undefined) {
|
|
3413
|
+
const nextName = typeof params.name === 'string' ? params.name.trim() : ''
|
|
3414
|
+
if (nextName.length > MAX_NAME_LENGTH) throw new ApiError('BAD_REQUEST', '工作区名称过长')
|
|
3415
|
+
if (nextName !== '') patch.name = nextName
|
|
3416
|
+
}
|
|
3417
|
+
|
|
3418
|
+
const updated = remoteStore.update(params.id, patch)
|
|
3419
|
+
|
|
3420
|
+
// Update DSH workspace title if name changed
|
|
3421
|
+
if (patch.name && updated.workspaceId) {
|
|
3422
|
+
try {
|
|
3423
|
+
await renameDshWorkspace(ctx, updated.workspaceId, patch.name)
|
|
3424
|
+
} catch (error) {
|
|
3425
|
+
log('warn', `Failed to rename DSH workspace: ${error && error.message ? error.message : error}`)
|
|
3426
|
+
}
|
|
3427
|
+
}
|
|
3428
|
+
|
|
3429
|
+
return { workspace: describeRemote(updated) }
|
|
3430
|
+
},
|
|
3431
|
+
|
|
3432
|
+
async 'remote_workspaces.remove'(params = {}) {
|
|
3433
|
+
if (typeof params.id !== 'string' || params.id === '') throw new ApiError('BAD_REQUEST', 'id is required')
|
|
3434
|
+
const record = remoteStore.get(params.id)
|
|
3435
|
+
if (!record) throw new ApiError('NOT_FOUND', 'remote workspace not found')
|
|
3436
|
+
|
|
3437
|
+
remoteStore.remove(params.id)
|
|
3438
|
+
|
|
3439
|
+
// Remove DSH workspace
|
|
3440
|
+
let removedWorkspace = false
|
|
3441
|
+
if (record.workspaceId) {
|
|
3442
|
+
const registry = ctx.get('workspaceRegistry', true)
|
|
3443
|
+
if (registry && typeof registry.delete === 'function') {
|
|
3444
|
+
try {
|
|
3445
|
+
removedWorkspace = await registry.delete(record.workspaceId)
|
|
3446
|
+
} catch (error) {
|
|
3447
|
+
log('warn', `DSH workspace removal failed: ${error && error.message ? error.message : error}`)
|
|
3448
|
+
}
|
|
3449
|
+
}
|
|
3450
|
+
}
|
|
3451
|
+
|
|
3452
|
+
// Remove placeholder directory
|
|
3453
|
+
let removedPlaceholder = false
|
|
3454
|
+
try {
|
|
3455
|
+
rmSync(record.placeholderPath, { recursive: true, force: true })
|
|
3456
|
+
removedPlaceholder = true
|
|
3457
|
+
} catch (error) {
|
|
3458
|
+
log('warn', `Placeholder removal failed: ${error && error.message ? error.message : error}`)
|
|
3459
|
+
}
|
|
3460
|
+
|
|
3461
|
+
return { removedWorkspace, removedPlaceholder }
|
|
3462
|
+
},
|
|
3463
|
+
|
|
3464
|
+
async 'remote_workspaces.test'(params = {}) {
|
|
3465
|
+
if (typeof params.id !== 'string' || params.id === '') throw new ApiError('BAD_REQUEST', 'id is required')
|
|
3466
|
+
const record = remoteStore.get(params.id)
|
|
3467
|
+
if (!record) throw new ApiError('NOT_FOUND', 'remote workspace not found')
|
|
3468
|
+
|
|
3469
|
+
const host = await findHost(record.hostId)
|
|
3470
|
+
const started = Date.now()
|
|
3471
|
+
try {
|
|
3472
|
+
const remote = await connectHost(host)
|
|
3473
|
+
const stat = await remote.stat(record.remotePath)
|
|
3474
|
+
const latencyMs = Date.now() - started
|
|
3475
|
+
pool.setStatus(host.id, { state: 'connected', latencyMs })
|
|
3476
|
+
return {
|
|
3477
|
+
ok: true,
|
|
3478
|
+
latencyMs,
|
|
3479
|
+
exists: stat.type === 'dir',
|
|
3480
|
+
type: stat.type,
|
|
3481
|
+
}
|
|
3482
|
+
} catch (error) {
|
|
3483
|
+
const apiError = asApiError(error)
|
|
3484
|
+
pool.setStatus(host.id, { state: 'error', message: apiError.message })
|
|
3485
|
+
return {
|
|
3486
|
+
ok: false,
|
|
3487
|
+
error: apiError.message,
|
|
3488
|
+
latencyMs: Date.now() - started,
|
|
3489
|
+
}
|
|
3490
|
+
}
|
|
3491
|
+
},
|
|
3270
3492
|
}
|
|
3271
3493
|
|
|
3272
3494
|
// ── linked_workspace agent tool + prompt section ──────────────────────────
|
|
@@ -3337,7 +3559,7 @@ export function apply(ctx) {
|
|
|
3337
3559
|
const service = ctx.get('skills')
|
|
3338
3560
|
if (service && typeof service.list === 'function') {
|
|
3339
3561
|
try {
|
|
3340
|
-
const list = await service.list({ cwd: link
|
|
3562
|
+
const list = await service.list({ cwd: recordLocalPath(link), signal })
|
|
3341
3563
|
if (Array.isArray(list)) {
|
|
3342
3564
|
return list.map((skill) => ({
|
|
3343
3565
|
name: skill.name,
|
|
@@ -3351,14 +3573,14 @@ export function apply(ctx) {
|
|
|
3351
3573
|
/* fall back to a direct scan */
|
|
3352
3574
|
}
|
|
3353
3575
|
}
|
|
3354
|
-
return scanLocalSkills(link
|
|
3576
|
+
return scanLocalSkills(recordLocalPath(link))
|
|
3355
3577
|
}
|
|
3356
3578
|
|
|
3357
3579
|
const readLocalSkill = async (link, name, signal) => {
|
|
3358
3580
|
const service = ctx.get('skills')
|
|
3359
3581
|
if (service && typeof service.get === 'function') {
|
|
3360
3582
|
try {
|
|
3361
|
-
const skill = await service.get(name, { cwd: link
|
|
3583
|
+
const skill = await service.get(name, { cwd: recordLocalPath(link), signal })
|
|
3362
3584
|
if (skill && typeof skill.content === 'string') {
|
|
3363
3585
|
return { name: skill.name, description: skill.description || '', content: skill.content, path: skill.path || '' }
|
|
3364
3586
|
}
|
|
@@ -3366,7 +3588,7 @@ export function apply(ctx) {
|
|
|
3366
3588
|
/* fall back */
|
|
3367
3589
|
}
|
|
3368
3590
|
}
|
|
3369
|
-
for (const skill of scanLocalSkills(link
|
|
3591
|
+
for (const skill of scanLocalSkills(recordLocalPath(link))) {
|
|
3370
3592
|
if (skill.name !== name) continue
|
|
3371
3593
|
const content = readFileSync(skill.path, 'utf8')
|
|
3372
3594
|
return { name: skill.name, description: skill.description, content, path: skill.path }
|
|
@@ -3379,26 +3601,26 @@ export function apply(ctx) {
|
|
|
3379
3601
|
timeoutMs: 120_000,
|
|
3380
3602
|
isConcurrencySafe: (args) => ['list', 'info', 'list_dir', 'read', 'stat'].includes(String((args && args.action) || '').trim()),
|
|
3381
3603
|
description:
|
|
3382
|
-
'Read and edit files of a linked
|
|
3383
|
-
+ 'Actions: list (all linked workspaces), info, list_dir, read, write, replace, stat, mkdir, rename, delete, sync. '
|
|
3604
|
+
'Read and edit files of a remote project over SSH: either a linked workspace (a local directory paired with a remote directory) or a remote workspace (a remote directory whose session runs in an empty local placeholder). '
|
|
3605
|
+
+ 'Actions: list (all linked and remote workspaces), info, list_dir, read, write, replace, stat, mkdir, rename, delete, sync (linked workspaces only). '
|
|
3384
3606
|
+ '`path` is relative to the remote root (or an absolute path inside it). Writes are atomic; pass `if_modified_since` from a previous read/stat to refuse a stale overwrite. '
|
|
3385
|
-
+ 'The workspace is resolved from the session working directory; pass `workspace` (
|
|
3386
|
-
+ 'Local files (including .local/ and .remote/) still use the normal read/write/bash tools.',
|
|
3607
|
+
+ 'The workspace is resolved from the session working directory; pass `workspace` (id, local path, placeholder path or name) when working elsewhere. '
|
|
3608
|
+
+ 'Local files of a linked workspace (including .local/ and .remote/) still use the normal read/write/bash tools.',
|
|
3387
3609
|
parameters: {
|
|
3388
3610
|
type: 'object',
|
|
3389
3611
|
properties: {
|
|
3390
3612
|
action: {
|
|
3391
3613
|
type: 'string',
|
|
3392
3614
|
enum: ['list', 'info', 'list_dir', 'read', 'write', 'replace', 'stat', 'mkdir', 'rename', 'delete', 'sync'],
|
|
3393
|
-
description: 'Operation to perform.',
|
|
3615
|
+
description: 'Operation to perform. sync only applies to a linked workspace with mirroring on.',
|
|
3394
3616
|
},
|
|
3395
3617
|
workspace: {
|
|
3396
3618
|
type: 'string',
|
|
3397
|
-
description: 'Optional
|
|
3619
|
+
description: 'Optional workspace reference: id, absolute local path, placeholder path, or workspace name. Omit to use the session working directory.',
|
|
3398
3620
|
},
|
|
3399
3621
|
path: {
|
|
3400
3622
|
type: 'string',
|
|
3401
|
-
description: 'Remote path relative to the
|
|
3623
|
+
description: 'Remote path relative to the workspace root, or an absolute path inside it. Empty means the root.',
|
|
3402
3624
|
},
|
|
3403
3625
|
destination: { type: 'string', description: 'Destination path for rename (relative or absolute inside the root).' },
|
|
3404
3626
|
content: { type: 'string', description: 'Full file content for write.' },
|
|
@@ -3427,30 +3649,61 @@ export function apply(ctx) {
|
|
|
3427
3649
|
if (!exec || !exec.agent) throw new ApiError('BAD_REQUEST', `${LINKED_TOOL_NAME} requires an agent session`)
|
|
3428
3650
|
const action = String((args && args.action) || '').trim()
|
|
3429
3651
|
if (action === 'list') {
|
|
3430
|
-
const
|
|
3652
|
+
const linkedLines = linkedStore.list().map((record) => {
|
|
3431
3653
|
const described = describeLink(record)
|
|
3432
3654
|
return [
|
|
3433
|
-
`- ${described.name}`,
|
|
3655
|
+
`- ${described.name} (linked)`,
|
|
3434
3656
|
` local: ${described.localPath}`,
|
|
3435
3657
|
` remote: ${described.username}@${described.host}:${described.remotePath}`,
|
|
3436
3658
|
` mirror: ${described.mirror ? 'on' : 'off'}`,
|
|
3437
3659
|
].join('\n')
|
|
3438
3660
|
})
|
|
3439
|
-
|
|
3661
|
+
const remoteLines = remoteStore.list().map((record) => {
|
|
3662
|
+
const host = pool.host(record.hostId)
|
|
3663
|
+
const hostLabel = host ? `${host.username}@${host.host}` : record.hostId
|
|
3664
|
+
return [
|
|
3665
|
+
`- ${record.name} (remote)`,
|
|
3666
|
+
` placeholder: ${record.placeholderPath}`,
|
|
3667
|
+
` remote: ${hostLabel}:${record.remotePath}`,
|
|
3668
|
+
` workspaceId: ${record.workspaceId || 'none'}`,
|
|
3669
|
+
].join('\n')
|
|
3670
|
+
})
|
|
3671
|
+
const allLines = [...linkedLines, ...remoteLines]
|
|
3672
|
+
return toolText(allLines.length === 0 ? 'No linked or remote workspaces yet.' : allLines.join('\n'))
|
|
3440
3673
|
}
|
|
3441
3674
|
|
|
3442
3675
|
const link = await resolveLinkedSelection(args, exec)
|
|
3676
|
+
const remoteKind = isRemoteRecord(link)
|
|
3443
3677
|
const remote = await hostForLink(link)
|
|
3444
3678
|
const root = linkedRootOf(link)
|
|
3445
3679
|
const target = linkedTarget(link, args.path)
|
|
3446
3680
|
|
|
3447
3681
|
if (action === 'info') {
|
|
3448
3682
|
const stat = await remote.stat(root)
|
|
3683
|
+
const host = pool.host(link.hostId)
|
|
3684
|
+
const snapshot = link.hostSnapshot || {}
|
|
3685
|
+
const hostLabel = host
|
|
3686
|
+
? `${host.username}@${host.host}:${host.port}`
|
|
3687
|
+
: `${snapshot.username || '?'}@${snapshot.host || link.hostId}:${snapshot.port || 22}`
|
|
3688
|
+
if (remoteKind) {
|
|
3689
|
+
return toolText(JSON.stringify({
|
|
3690
|
+
id: link.id,
|
|
3691
|
+
kind: 'remote',
|
|
3692
|
+
name: link.name,
|
|
3693
|
+
remoteHost: hostLabel,
|
|
3694
|
+
remoteRoot: root,
|
|
3695
|
+
placeholderPath: link.placeholderPath,
|
|
3696
|
+
workspaceId: link.workspaceId || null,
|
|
3697
|
+
mirror: false,
|
|
3698
|
+
remoteRootType: stat.type,
|
|
3699
|
+
}, null, 2))
|
|
3700
|
+
}
|
|
3449
3701
|
return toolText(JSON.stringify({
|
|
3450
3702
|
id: link.id,
|
|
3703
|
+
kind: 'linked',
|
|
3451
3704
|
name: link.name,
|
|
3452
3705
|
localPath: link.localPath,
|
|
3453
|
-
remoteHost:
|
|
3706
|
+
remoteHost: hostLabel,
|
|
3454
3707
|
remoteRoot: root,
|
|
3455
3708
|
mirror: Boolean(link.mirror),
|
|
3456
3709
|
mirrorDir: link.mirror ? join(link.localPath, linkedFs.MIRROR_DIR) : null,
|
|
@@ -3546,24 +3799,27 @@ export function apply(ctx) {
|
|
|
3546
3799
|
throw new ApiError('BAD_REQUEST', 'destination is required')
|
|
3547
3800
|
}
|
|
3548
3801
|
const destination = linkedTarget(link, args.destination)
|
|
3549
|
-
if (target === root) throw new ApiError('BAD_REQUEST', '
|
|
3802
|
+
if (target === root) throw new ApiError('BAD_REQUEST', '不能移动工作区根目录')
|
|
3550
3803
|
await remote.rename(target, destination)
|
|
3551
|
-
await linkedFs.removeMirrorPath(link.localPath, linkedRelative(link, target)).catch(() => {})
|
|
3804
|
+
if (!remoteKind) await linkedFs.removeMirrorPath(link.localPath, linkedRelative(link, target)).catch(() => {})
|
|
3552
3805
|
return toolText(`Renamed ${target} -> ${destination}`)
|
|
3553
3806
|
}
|
|
3554
3807
|
|
|
3555
3808
|
if (action === 'delete') {
|
|
3556
|
-
if (target === root) throw new ApiError('BAD_REQUEST', '
|
|
3809
|
+
if (target === root) throw new ApiError('BAD_REQUEST', '不能删除工作区根目录')
|
|
3557
3810
|
const stat = await remote.stat(target)
|
|
3558
3811
|
// rmdir only removes empty directories (same as the UI's fs.delete,
|
|
3559
3812
|
// which uses this recursive helper).
|
|
3560
3813
|
if (stat.type === 'dir') await remoteDeleteRecursive(remote, target)
|
|
3561
3814
|
else await remote.unlink(target)
|
|
3562
|
-
await linkedFs.removeMirrorPath(link.localPath, linkedRelative(link, target)).catch(() => {})
|
|
3815
|
+
if (!remoteKind) await linkedFs.removeMirrorPath(link.localPath, linkedRelative(link, target)).catch(() => {})
|
|
3563
3816
|
return toolText(`Deleted ${target}`)
|
|
3564
3817
|
}
|
|
3565
3818
|
|
|
3566
3819
|
if (action === 'sync') {
|
|
3820
|
+
if (remoteKind) {
|
|
3821
|
+
throw new ApiError('BAD_REQUEST', '远程工作区没有本地副本,无需 sync;sync 只适用于开启镜像的联动工作区')
|
|
3822
|
+
}
|
|
3567
3823
|
const job = startSyncJob(link, args)
|
|
3568
3824
|
return toolText(
|
|
3569
3825
|
`Sync job running in the background: ${job.files} file(s) / ${job.bytes} bytes archived so far (${job.skipped} skipped). `
|
|
@@ -3709,7 +3965,7 @@ export function apply(ctx) {
|
|
|
3709
3965
|
'dsh-linked-workspace: close ssh sessions',
|
|
3710
3966
|
)
|
|
3711
3967
|
|
|
3712
|
-
log('info', `loaded (${
|
|
3968
|
+
log('info', `loaded (${linkedStore.list().length} linked, ${remoteStore.list().length} remote workspace${linkedStore.list().length + remoteStore.list().length === 1 ? '' : 's'})`)
|
|
3713
3969
|
const autoSyncTimer = setInterval(autoSyncTick, AUTO_SYNC_TICK_MS)
|
|
3714
3970
|
if (autoSyncTimer && typeof autoSyncTimer.unref === 'function') autoSyncTimer.unref()
|
|
3715
3971
|
ctx.effect(() => () => clearInterval(autoSyncTimer), 'dsh-linked-workspace: auto sync timer')
|