dsh-linked-workspace 0.9.0 → 0.11.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/lib/index.js CHANGED
@@ -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') {
@@ -758,12 +797,41 @@ class HostPool {
758
797
  this.statuses.set(hostId, { ...status, checkedAt: Date.now() })
759
798
  }
760
799
 
800
+ /**
801
+ * Record that an established connection died on its own (network drop, server
802
+ * restart, keepalive timeout). Callers keep working: the next request dials
803
+ * again, and a successful connect clears the error.
804
+ */
805
+ noteConnectionLost(hostId, remote, reason) {
806
+ const entry = this.connections.get(hostId)
807
+ if (!entry || entry.remote !== remote) return
808
+ this.connections.delete(hostId)
809
+ const previous = this.statuses.get(hostId) || {}
810
+ this.setStatus(hostId, {
811
+ state: 'error',
812
+ reason: 'lost',
813
+ message: reason || '',
814
+ latencyMs: previous.latencyMs,
815
+ })
816
+ log('warn', `SSH connection to ${entry.authority} lost: ${reason || 'closed'}`)
817
+ }
818
+
819
+ noteConnectionReady(hostId) {
820
+ const previous = this.statuses.get(hostId) || {}
821
+ if (previous.state === 'connected' && !previous.reason) return
822
+ this.setStatus(hostId, {
823
+ state: 'connected',
824
+ latencyMs: previous.latencyMs,
825
+ })
826
+ }
827
+
761
828
  async remote(hostRecord) {
762
829
  const authority = `${hostRecord.host}:${hostRecord.port}`
763
830
  const existing = this.connections.get(hostRecord.id)
764
831
  if (existing && existing.authority === authority) {
765
832
  try {
766
833
  await existing.remote.ensureConnected()
834
+ this.noteConnectionReady(hostRecord.id)
767
835
  return existing.remote
768
836
  } catch (error) {
769
837
  existing.remote.dispose().catch(() => {})
@@ -783,6 +851,7 @@ class HostPool {
783
851
  knownHostsFile: this.knownHostsFile,
784
852
  connectTimeoutMs: CONNECT_TIMEOUT_MS,
785
853
  logger: log,
854
+ onLost: (info) => this.noteConnectionLost(hostRecord.id, remote, info && info.reason),
786
855
  })
787
856
  const entry = { authority, remote }
788
857
  this.connections.set(hostRecord.id, entry)
@@ -793,6 +862,8 @@ class HostPool {
793
862
  // the map state authoritative so the unused connection is closed.
794
863
  if (this.connections.get(hostRecord.id) !== entry) {
795
864
  remote.dispose().catch(() => {})
865
+ } else {
866
+ this.noteConnectionReady(hostRecord.id)
796
867
  }
797
868
  return remote
798
869
  } catch (error) {
@@ -821,9 +892,9 @@ export function apply(ctx) {
821
892
  const dir = dataDir()
822
893
  migrateLegacyDataDir(dir)
823
894
  ensureDir(dir)
824
- const store = new WorkspaceStore(join(dir, 'workspaces.json'))
825
895
  const settingsStore = new SettingsStore(join(dir, 'settings.json'))
826
896
  const linkedStore = new linkedFs.LinkedStore(join(dir, 'linked.json'))
897
+ const remoteStore = new RemoteWorkspaceStore(join(dir, 'remote-workspaces.json'))
827
898
  // 0.5.0: mirror sync is opt-in. Records created under the old default
828
899
  // (mirror on, never explicitly chosen) are switched off once.
829
900
  for (const existing of linkedStore.list()) {
@@ -848,13 +919,28 @@ export function apply(ctx) {
848
919
  hostsRefreshedAt = Date.now()
849
920
  pool.setHosts(hosts)
850
921
  for (const host of hosts) {
851
- // Keep the denormalized snapshot fresh for every workspace on this host.
852
- store.updateSnapshot(host.id, {
853
- name: host.name,
854
- host: host.host,
855
- port: host.port,
856
- username: host.username,
857
- })
922
+ // Keep the denormalized snapshot fresh for every workspace on this host,
923
+ // so a removed SSH host still renders with its last known address.
924
+ const snapshot = { name: host.name, host: host.host, port: host.port, username: host.username }
925
+ const fresh = (record) => {
926
+ const current = record.hostSnapshot || {}
927
+ return current.name === snapshot.name
928
+ && current.host === snapshot.host
929
+ && current.port === snapshot.port
930
+ && current.username === snapshot.username
931
+ }
932
+ for (const record of linkedStore.list()) {
933
+ if (record.hostId !== host.id || fresh(record)) continue
934
+ try { linkedStore.update(record.id, { hostSnapshot: snapshot }) } catch (error) {
935
+ log('warn', `cannot refresh host snapshot for link "${record.id}": ${error && error.message ? error.message : error}`)
936
+ }
937
+ }
938
+ for (const record of remoteStore.list()) {
939
+ if (record.hostId !== host.id || fresh(record)) continue
940
+ try { remoteStore.update(record.id, { hostSnapshot: snapshot }) } catch (error) {
941
+ log('warn', `cannot refresh host snapshot for remote workspace "${record.id}": ${error && error.message ? error.message : error}`)
942
+ }
943
+ }
858
944
  }
859
945
  return hosts
860
946
  } catch (error) {
@@ -887,33 +973,6 @@ export function apply(ctx) {
887
973
  }
888
974
  }
889
975
 
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
976
  const normalizeRemotePath = async (remote, rawPath) => {
918
977
  if (typeof rawPath !== 'string' || rawPath.trim() === '') {
919
978
  throw new ApiError('BAD_REQUEST', 'path is required')
@@ -927,42 +986,6 @@ export function apply(ctx) {
927
986
  return posix.resolve(target)
928
987
  }
929
988
 
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
989
  // ── linked workspaces ───────────────────────────────────────────────────
967
990
 
968
991
  const linkedRegistry = () => {
@@ -1020,12 +1043,59 @@ export function apply(ctx) {
1020
1043
  workspaceTitle: workspace ? workspace.title : null,
1021
1044
  status: {
1022
1045
  state: status ? status.state : 'idle',
1046
+ ...(status && status.reason ? { reason: status.reason } : {}),
1023
1047
  ...(status && status.message ? { message: status.message } : {}),
1024
1048
  ...(status && typeof status.latencyMs === 'number' ? { latencyMs: status.latencyMs } : {}),
1025
1049
  },
1026
1050
  }
1027
1051
  }
1028
1052
 
1053
+ /** A record is a remote workspace when it owns a placeholder directory, not a local path. */
1054
+ const isRemoteRecord = (record) => Boolean(record && record.placeholderPath && !record.localPath)
1055
+
1056
+ const describeRemote = (record) => {
1057
+ const host = pool.host(record.hostId)
1058
+ const snapshot = record.hostSnapshot || {}
1059
+ const status = pool.status(record.hostId)
1060
+ return {
1061
+ id: record.id,
1062
+ name: record.name,
1063
+ hostId: record.hostId,
1064
+ hostName: host ? host.name : snapshot.name || record.hostId,
1065
+ host: host ? host.host : snapshot.host || '',
1066
+ port: host ? host.port : snapshot.port || 22,
1067
+ username: host ? host.username : snapshot.username || '',
1068
+ remotePath: record.remotePath,
1069
+ placeholderPath: record.placeholderPath,
1070
+ workspaceId: record.workspaceId || null,
1071
+ createdAt: record.createdAt,
1072
+ status: {
1073
+ state: status ? status.state : 'idle',
1074
+ ...(status && status.reason ? { reason: status.reason } : {}),
1075
+ ...(status && status.message ? { message: status.message } : {}),
1076
+ ...(status && typeof status.latencyMs === 'number' ? { latencyMs: status.latencyMs } : {}),
1077
+ },
1078
+ }
1079
+ }
1080
+
1081
+ /** Path the session runs in: the paired local directory, or the placeholder of a remote workspace. */
1082
+ const recordLocalPath = (record) => (record && (record.localPath || record.placeholderPath)) || ''
1083
+
1084
+ /** Find the remote workspace whose placeholder directory contains this cwd. */
1085
+ const remoteWorkspaceByCwd = (cwd) => {
1086
+ const cwdKey = linkedFs.localPathKey(cwd)
1087
+ if (!cwdKey) return undefined
1088
+ let best
1089
+ for (const record of remoteStore.list()) {
1090
+ const key = linkedFs.localPathKey(record.placeholderPath)
1091
+ if (!key) continue
1092
+ const matches = cwdKey === key || cwdKey.startsWith(`${key}${sep}`) || cwdKey.startsWith(`${key}/`)
1093
+ if (!matches) continue
1094
+ if (!best || key.length > best.key.length) best = { record, key }
1095
+ }
1096
+ return best ? best.record : undefined
1097
+ }
1098
+
1029
1099
  /** Strip the old "⇄ " title prefix once; the sidebar icon is replaced by CSS. */
1030
1100
  const migrateLinkedWorkspaceTitles = async () => {
1031
1101
  const registry = linkedRegistry()
@@ -1047,6 +1117,12 @@ export function apply(ctx) {
1047
1117
  return record
1048
1118
  }
1049
1119
 
1120
+ const requireRemote = (id) => {
1121
+ const record = remoteStore.get(id)
1122
+ if (!record) throw new ApiError('NOT_FOUND', `远程工作区不存在: ${id}`)
1123
+ return record
1124
+ }
1125
+
1050
1126
  const hostForLink = async (record) => {
1051
1127
  let host = pool.host(record.hostId)
1052
1128
  if (!host) {
@@ -1287,11 +1363,17 @@ export function apply(ctx) {
1287
1363
  if (reference !== '') {
1288
1364
  const direct = linkedStore.get(reference)
1289
1365
  if (direct) return direct
1366
+ const remoteDirect = remoteStore.get(reference)
1367
+ if (remoteDirect) return remoteDirect
1290
1368
  const byPath = linkedStore.findByLocalPath(reference)
1291
1369
  if (byPath) return byPath
1370
+ const byPlaceholder = remoteStore.findByPlaceholder(reference)
1371
+ if (byPlaceholder) return byPlaceholder
1292
1372
  const byName = linkedStore.list().find((record) => record.name === reference)
1293
1373
  if (byName) return byName
1294
- throw new ApiError('NOT_FOUND', `联动工作区不存在: ${reference}`)
1374
+ const remoteByName = remoteStore.list().find((record) => record.name === reference)
1375
+ if (remoteByName) return remoteByName
1376
+ throw new ApiError('NOT_FOUND', `联动工作区或远程工作区不存在: ${reference}`)
1295
1377
  }
1296
1378
  if (!exec || !exec.agent) throw new ApiError('BAD_REQUEST', '需要 agent 会话或显式 workspace 参数')
1297
1379
  const cwd = await ctx.workingDirectory.ensure(exec.agent, exec.signal)
@@ -1303,23 +1385,27 @@ export function apply(ctx) {
1303
1385
  if (!matches) continue
1304
1386
  if (!best || localKey.length > best.key.length) best = { record, key: localKey }
1305
1387
  }
1306
- if (!best) {
1307
- throw new ApiError('NOT_FOUND', '当前会话工作目录不是联动工作区;先调用 action="list" 查看可用工作区,或用 workspace 参数指定')
1308
- }
1309
- return best.record
1388
+ if (best) return best.record
1389
+ // A remote-workspace session runs inside its placeholder directory; the
1390
+ // project files live on the SSH host, so the same tool actions apply.
1391
+ const remoteRecord = remoteWorkspaceByCwd(cwd)
1392
+ if (remoteRecord) return remoteRecord
1393
+ throw new ApiError('NOT_FOUND', '当前会话工作目录既不是联动工作区也不是远程工作区;先调用 action="list" 查看可用工作区,或用 workspace 参数指定')
1310
1394
  }
1311
1395
 
1312
1396
  const linkedPrompt = [
1313
- 'Linked remote workspaces (dsh-linked-workspace)',
1314
- 'A workspace may pair a local directory with a remote directory on an SSH host (the local directory shows "⇄" in the sidebar).',
1315
- 'For these workspaces the session working directory is the LOCAL directory, while the real project files live under the REMOTE root.',
1316
- `Use the \`${LINKED_TOOL_NAME}\` tool for remote files:`,
1317
- '- action "list" returns every linked workspace with its local path, SSH host, remote root and mirror state.',
1318
- '- action "list_dir" | "read" | "write" | "replace" | "stat" | "mkdir" | "rename" | "delete" takes `path` relative to the remote root (or an absolute path inside it).',
1397
+ 'Remote workspaces (dsh-linked-workspace)',
1398
+ 'This plugin provides two kinds of SSH-backed project:',
1399
+ '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.',
1400
+ '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.',
1401
+ `Use the \`${LINKED_TOOL_NAME}\` tool for remote files in both cases:`,
1402
+ '- action "list" returns every linked and remote workspace with its local path (or placeholder), SSH host, remote root and mirror state.',
1403
+ '- 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
1404
  '- 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/` (only when the workspace mirrors).',
1321
- 'Local files — including `.local/` (manifest and session intermediates) and `.remote/` (archived copies) — still use the normal read/write/edit/bash tools.',
1322
- 'This session runs in the LOCAL directory: locally installed skills (~/.dsh/skills, ~/.agents/skills, <local>/.dsh/skills) remain available. Use `linked_skills` to list or read them; do NOT install skills into the remote project just to use them.',
1405
+ '- action "sync" archives the remote tree into `.remote/` and only exists for a linked workspace (a remote workspace has no local copy).',
1406
+ 'The workspace is resolved from the session working directory; pass `workspace` (id, local path, placeholder path or name) when working elsewhere.',
1407
+ '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.',
1408
+ '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
1409
  '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
1410
  ].join('\n')
1325
1411
 
@@ -1329,14 +1415,15 @@ export function apply(ctx) {
1329
1415
  if (typeof params.linkedId === 'string' && params.linkedId.trim() !== '') {
1330
1416
  const record = requireLinked(params.linkedId.trim())
1331
1417
  const remote = await hostForLink(record)
1332
- return { kind: 'linked', record, remote, root: linkedRootOf(record) }
1418
+ return { kind: 'linked', record, remote, root: linkedRootOf(record), id: record.id }
1333
1419
  }
1334
- if (typeof params.workspaceId === 'string' && params.workspaceId.trim() !== '') {
1335
- const workspace = requireWorkspace(params.workspaceId)
1336
- const remote = await workspaceRemote(workspace)
1337
- return { kind: 'workspace', workspace, remote, root: posix.resolve(workspace.remotePath) }
1420
+ if (typeof params.remoteId === 'string' && params.remoteId.trim() !== '') {
1421
+ const record = requireRemote(params.remoteId.trim())
1422
+ const host = await findHost(record.hostId)
1423
+ const remote = await connectHost(host)
1424
+ return { kind: 'remote', record, remote, root: posix.resolve(record.remotePath), id: record.id }
1338
1425
  }
1339
- throw new ApiError('BAD_REQUEST', 'workspaceId or linkedId is required')
1426
+ throw new ApiError('BAD_REQUEST', 'linkedId or remoteId is required')
1340
1427
  }
1341
1428
 
1342
1429
  const scopeTarget = (scope, rawPath) => {
@@ -1495,6 +1582,9 @@ export function apply(ctx) {
1495
1582
  return
1496
1583
  }
1497
1584
  const data = readFileSync(localPath)
1585
+ // A single-file transfer can target a directory that does not exist on the
1586
+ // remote side yet (only the directory branch used to mkdirp).
1587
+ await remote.mkdirp(posix.dirname(remotePath))
1498
1588
  await withTimeout(remote.writeFileAtomic(remotePath, data), LINKED_SYNC_TIMEOUT_MS, `transfer ${relative}`)
1499
1589
  limits.files += 1
1500
1590
  limits.bytes += data.length
@@ -1785,6 +1875,95 @@ export function apply(ctx) {
1785
1875
  try { return await target.scope.remote.stat(target.path) } catch { return null }
1786
1876
  }
1787
1877
 
1878
+ // Content search: `fs.search` (git.localSearch / remoteSearch) only matches
1879
+ // file *names*. The workbench therefore needs a separate, bounded scan of
1880
+ // file bodies; both sides stop at a budget and report `truncated` instead of
1881
+ // hanging on a huge tree.
1882
+ const GREP_MAX_FILE_BYTES = 1024 * 1024
1883
+ const GREP_MAX_FILES = 2000
1884
+ const GREP_MAX_BYTES = 8 * 1024 * 1024
1885
+ const GREP_DEADLINE_MS = 5000
1886
+
1887
+ function grepDirectoryExcluded(name) {
1888
+ return LINKED_SYNC_EXCLUDES.has(name) || name === '.local' || name === '.remote'
1889
+ }
1890
+
1891
+ function contentSearchLocal(root, query, maxResults) {
1892
+ const needle = Buffer.from(query, 'utf8')
1893
+ const entries = []
1894
+ const started = Date.now()
1895
+ let files = 0
1896
+ let bytes = 0
1897
+ let truncated = false
1898
+ const visit = (directory, prefix) => {
1899
+ if (truncated) return
1900
+ if (files >= GREP_MAX_FILES || bytes >= GREP_MAX_BYTES || Date.now() - started > GREP_DEADLINE_MS) {
1901
+ truncated = true
1902
+ return
1903
+ }
1904
+ let listing
1905
+ try {
1906
+ listing = readdirSync(directory, { withFileTypes: true })
1907
+ } catch {
1908
+ return
1909
+ }
1910
+ for (const entry of listing) {
1911
+ if (truncated) return
1912
+ if (grepDirectoryExcluded(entry.name)) continue
1913
+ const absolute = join(directory, entry.name)
1914
+ const relative = prefix === '' ? entry.name : `${prefix}/${entry.name}`
1915
+ if (entry.isDirectory()) {
1916
+ visit(absolute, relative)
1917
+ continue
1918
+ }
1919
+ if (!entry.isFile()) continue
1920
+ if (files >= GREP_MAX_FILES || bytes >= GREP_MAX_BYTES || Date.now() - started > GREP_DEADLINE_MS) {
1921
+ truncated = true
1922
+ return
1923
+ }
1924
+ files += 1
1925
+ let data
1926
+ try {
1927
+ data = readFileSync(absolute)
1928
+ } catch {
1929
+ continue
1930
+ }
1931
+ if (data.length > GREP_MAX_FILE_BYTES) continue
1932
+ bytes += data.length
1933
+ if (data.includes(0)) continue
1934
+ if (data.indexOf(needle) === -1) continue
1935
+ if (entries.length >= maxResults) {
1936
+ truncated = true
1937
+ return
1938
+ }
1939
+ entries.push({ path: absolute, relative, size: data.length })
1940
+ }
1941
+ }
1942
+ visit(resolve(root), '')
1943
+ return { ok: true, query, entries, truncated }
1944
+ }
1945
+
1946
+ async function contentSearchRemote(remote, root, query, maxResults) {
1947
+ const command = 'grep -rIl --binary-files=without-match'
1948
+ + ' --exclude-dir=.git --exclude-dir=node_modules --exclude-dir=.local'
1949
+ + ' --exclude-dir=.remote --exclude-dir=__pycache__'
1950
+ + ` -e ${shellQuoteArg(query)} -- ${shellQuoteArg(root)} 2>/dev/null`
1951
+ + ` | head -n ${maxResults + 1}`
1952
+ const result = await remote.exec(command, { timeoutMs: 20000 })
1953
+ if (result.code !== 0 && result.stdout.trim() === '') {
1954
+ // grep exits 1 when nothing matched; a real failure has code > 1.
1955
+ if (result.code > 1) throw new ApiError('INTERNAL', `内容搜索失败:${String(result.stderr || '').trim().slice(0, 200)}`)
1956
+ return { ok: true, query, entries: [], truncated: false }
1957
+ }
1958
+ const lines = String(result.stdout || '').split('\n').map((line) => line.trim()).filter((line) => line !== '')
1959
+ const truncated = lines.length > maxResults
1960
+ const entries = lines.slice(0, maxResults).map((line) => {
1961
+ const relative = line.startsWith(`${root}/`) ? line.slice(root.length + 1) : line
1962
+ return { path: line, relative, size: null }
1963
+ })
1964
+ return { ok: true, query, entries, truncated }
1965
+ }
1966
+
1788
1967
  // ── method table ─────────────────────────────────────────────────────────
1789
1968
 
1790
1969
  const methods = {
@@ -1828,71 +2007,6 @@ export function apply(ctx) {
1828
2007
  }
1829
2008
  },
1830
2009
 
1831
- async 'workspaces.list'() {
1832
- await refreshHosts()
1833
- return { workspaces: store.list().map(describeWorkspace) }
1834
- },
1835
-
1836
- async 'workspaces.add'(params = {}) {
1837
- const host = await findHost(params.hostId)
1838
- const remote = await connectHost(host)
1839
- const requested = typeof params.name === 'string' ? params.name.trim() : ''
1840
- if (requested.length > MAX_NAME_LENGTH) throw new ApiError('BAD_REQUEST', '工作区名称过长')
1841
- const rawPath = await normalizeRemotePath(remote, params.remotePath)
1842
- const resolved = await remote.realpath(rawPath).catch(() => rawPath)
1843
- const stat = await remote.stat(resolved)
1844
- if (stat.type !== 'dir') throw new ApiError('FS_NOT_DIR', '远程路径不是目录')
1845
- const existing = store.find(host.id, resolved)
1846
- if (existing) throw new ApiError('BAD_REQUEST', '该目录已经是远程工作区')
1847
- const entry = {
1848
- id: randomUUID(),
1849
- name: requested !== '' ? requested : posix.basename(resolved) || host.name,
1850
- hostId: host.id,
1851
- hostSnapshot: {
1852
- name: host.name,
1853
- host: host.host,
1854
- port: host.port,
1855
- username: host.username,
1856
- },
1857
- remotePath: resolved,
1858
- createdAt: Date.now(),
1859
- }
1860
- store.add(entry)
1861
- pool.setStatus(host.id, { state: 'connected', latencyMs: 0 })
1862
- return { workspace: describeWorkspace(entry) }
1863
- },
1864
-
1865
- async 'workspaces.remove'(params = {}) {
1866
- const workspace = requireWorkspace(params.id)
1867
- store.remove(workspace.id)
1868
- return {}
1869
- },
1870
-
1871
- async 'workspaces.rename'(params = {}) {
1872
- const workspace = requireWorkspace(params.id)
1873
- const next = typeof params.name === 'string' ? params.name.trim() : ''
1874
- if (next === '') throw new ApiError('BAD_REQUEST', '名称不能为空')
1875
- if (next.length > MAX_NAME_LENGTH) throw new ApiError('BAD_REQUEST', '名称过长')
1876
- store.rename(workspace.id, next)
1877
- return { workspace: describeWorkspace(workspace) }
1878
- },
1879
-
1880
- async 'workspaces.test'(params = {}) {
1881
- const workspace = requireWorkspace(params.id)
1882
- const started = Date.now()
1883
- try {
1884
- const remote = await workspaceRemote(workspace)
1885
- const stat = await remote.stat(workspace.remotePath)
1886
- if (stat.type !== 'dir') throw new ApiError('FS_NOT_DIR', '远程目录已不存在')
1887
- const label = `${workspace.hostSnapshot.username}@${workspace.hostSnapshot.host}`
1888
- log('info', `test ok ${label}:${workspace.remotePath} in ${Date.now() - started}ms`)
1889
- return { ok: true, latencyMs: Date.now() - started, resolvedPath: workspace.remotePath }
1890
- } catch (error) {
1891
- const apiError = asApiError(error)
1892
- return { ok: false, latencyMs: Date.now() - started, error: apiError.message }
1893
- }
1894
- },
1895
-
1896
2010
  async 'fs.list'(params = {}) {
1897
2011
  const scope = await requireScope(params)
1898
2012
  const target = params.path === undefined || params.path === ''
@@ -2684,7 +2798,7 @@ export function apply(ctx) {
2684
2798
  const side = params.side === 'local' ? 'local' : 'remote'
2685
2799
  const testMode = process.env.DSH_LINKED_WORKSPACE_NO_TERMINAL === '1'
2686
2800
  const scope = await requireScope(params)
2687
- const snapshot = scope.kind === 'linked' ? (scope.record.hostSnapshot || {}) : (scope.workspace.hostSnapshot || {})
2801
+ const snapshot = (scope.record && scope.record.hostSnapshot) || (pool.host(scope.record.hostId) || {})
2688
2802
  if (side === 'local') {
2689
2803
  if (scope.kind !== 'linked') throw new ApiError('BAD_REQUEST', '该工作区没有本地目录')
2690
2804
  const localRoot = resolve(scope.record.localPath)
@@ -2757,6 +2871,18 @@ export function apply(ctx) {
2757
2871
  return await git.localSearch(scope.record.localPath, query, { maxResults })
2758
2872
  },
2759
2873
 
2874
+ /** Search file *contents* (fs.search only matches names). */
2875
+ async 'fs.grep'(params = {}) {
2876
+ const scope = await requireScope(params)
2877
+ const query = typeof params.query === 'string' ? params.query.trim() : ''
2878
+ const maxResults = Math.min(Math.max(Number(params.maxResults) || 200, 1), 1000)
2879
+ if (query === '') return { ok: true, query: '', entries: [], truncated: false }
2880
+ const side = params.side === 'local' ? 'local' : 'remote'
2881
+ if (side === 'remote') return await contentSearchRemote(scope.remote, scope.root, query, maxResults)
2882
+ if (scope.kind !== 'linked') throw new ApiError('BAD_REQUEST', '只有联动工作区有本地目录')
2883
+ return contentSearchLocal(scope.record.localPath, query, maxResults)
2884
+ },
2885
+
2760
2886
  /**
2761
2887
  * Read-only comparison of one directory pair. Lists files that exist on one
2762
2888
  * side only and files whose size or mtime disagree; it never touches data.
@@ -2777,23 +2903,25 @@ export function apply(ctx) {
2777
2903
  const excluded = (entryName) => LINKED_SYNC_EXCLUDES.has(entryName) || entryName === '.local' || entryName === '.remote'
2778
2904
  const remoteMap = new Map()
2779
2905
  const localMap = new Map()
2780
- const state = { files: 0, truncated: false }
2906
+ // Each side gets its own budget: a huge remote tree must not silently cut
2907
+ // the local walk (and the other way round).
2908
+ const state = { remoteFiles: 0, localFiles: 0, remoteTruncated: false, localTruncated: false, skippedLinks: 0 }
2781
2909
  const walkRemote = async (directory, prefix, depth) => {
2782
- if (depth > MAX_DEPTH || state.files >= MAX_FILES) {
2783
- state.truncated = true
2910
+ if (depth > MAX_DEPTH || state.remoteFiles >= MAX_FILES) {
2911
+ state.remoteTruncated = true
2784
2912
  return
2785
2913
  }
2786
2914
  let listing
2787
2915
  try {
2788
2916
  listing = await scope.remote.listDir(directory)
2789
2917
  } catch (error) {
2790
- state.truncated = true
2918
+ state.remoteTruncated = true
2791
2919
  return
2792
2920
  }
2793
2921
  for (const entry of listing.entries) {
2794
2922
  if (excluded(entry.name)) continue
2795
- if (state.files >= MAX_FILES) {
2796
- state.truncated = true
2923
+ if (state.remoteFiles >= MAX_FILES) {
2924
+ state.remoteTruncated = true
2797
2925
  return
2798
2926
  }
2799
2927
  const relative = prefix === '' ? entry.name : `${prefix}/${entry.name}`
@@ -2801,27 +2929,30 @@ export function apply(ctx) {
2801
2929
  await walkRemote(entry.path, relative, depth + 1)
2802
2930
  continue
2803
2931
  }
2804
- if (entry.type !== 'file') continue
2932
+ if (entry.type !== 'file') {
2933
+ state.skippedLinks += 1
2934
+ continue
2935
+ }
2805
2936
  remoteMap.set(relative, { size: entry.size, mtime: entry.mtime })
2806
- state.files += 1
2937
+ state.remoteFiles += 1
2807
2938
  }
2808
2939
  }
2809
2940
  const walkLocal = (directory, prefix, depth) => {
2810
- if (depth > MAX_DEPTH || state.files >= MAX_FILES) {
2811
- state.truncated = true
2941
+ if (depth > MAX_DEPTH || state.localFiles >= MAX_FILES) {
2942
+ state.localTruncated = true
2812
2943
  return
2813
2944
  }
2814
2945
  let entries
2815
2946
  try {
2816
2947
  entries = readdirSync(directory, { withFileTypes: true })
2817
2948
  } catch (error) {
2818
- state.truncated = true
2949
+ state.localTruncated = true
2819
2950
  return
2820
2951
  }
2821
2952
  for (const entry of entries) {
2822
2953
  if (excluded(entry.name)) continue
2823
- if (state.files >= MAX_FILES) {
2824
- state.truncated = true
2954
+ if (state.localFiles >= MAX_FILES) {
2955
+ state.localTruncated = true
2825
2956
  return
2826
2957
  }
2827
2958
  const relative = prefix === '' ? entry.name : `${prefix}/${entry.name}`
@@ -2830,16 +2961,19 @@ export function apply(ctx) {
2830
2961
  walkLocal(absolute, relative, depth + 1)
2831
2962
  continue
2832
2963
  }
2833
- if (!entry.isFile()) continue
2964
+ if (!entry.isFile()) {
2965
+ state.skippedLinks += 1
2966
+ continue
2967
+ }
2834
2968
  let info
2835
2969
  try {
2836
2970
  info = statSync(absolute)
2837
2971
  } catch (error) {
2838
- state.truncated = true
2972
+ state.localTruncated = true
2839
2973
  continue
2840
2974
  }
2841
2975
  localMap.set(relative, { size: info.size, mtime: info.mtimeMs })
2842
- state.files += 1
2976
+ state.localFiles += 1
2843
2977
  }
2844
2978
  }
2845
2979
  await walkRemote(root, '', 0)
@@ -2886,7 +3020,10 @@ export function apply(ctx) {
2886
3020
  onlyLocal: sorted(onlyLocal).slice(0, MAX_LIST),
2887
3021
  onlyRemote: sorted(onlyRemote).slice(0, MAX_LIST),
2888
3022
  changed: sorted(changed).slice(0, MAX_LIST),
2889
- truncated: state.truncated,
3023
+ truncated: state.remoteTruncated || state.localTruncated,
3024
+ remoteTruncated: state.remoteTruncated,
3025
+ localTruncated: state.localTruncated,
3026
+ skippedLinks: state.skippedLinks,
2890
3027
  }
2891
3028
  },
2892
3029
 
@@ -2916,6 +3053,12 @@ export function apply(ctx) {
2916
3053
  } else {
2917
3054
  localTarget = join(localRoot, ...relative.split('/'))
2918
3055
  }
3056
+ // Dropping a file must never silently replace an existing local file.
3057
+ const conflict = params.conflict === 'overwrite' || params.conflict === 'unique' ? params.conflict : 'error'
3058
+ if (existsSync(localTarget)) {
3059
+ if (conflict === 'error') throw new ApiError('FS_EXISTS', `本地已存在同名文件:${basename(localTarget)}`)
3060
+ if (conflict === 'unique') localTarget = uniqueLocalPath(dirname(localTarget), basename(localTarget))
3061
+ }
2919
3062
  mkdirSync(dirname(localTarget), { recursive: true })
2920
3063
  const temp = join(dirname(localTarget), `.~${basename(localTarget)}.${process.pid}.${Date.now()}.tmp`)
2921
3064
  try {
@@ -2934,12 +3077,20 @@ export function apply(ctx) {
2934
3077
  async 'fs.upload'(params = {}) {
2935
3078
  const scope = await requireScope(params)
2936
3079
  const targetDir = scopeTarget(scope, params.path)
2937
- const stat = await scope.remote.stat(targetDir)
3080
+ // Upload targets come from dialogs and from compare "push"; nested folders
3081
+ // may not exist remotely yet, so create the chain before validating.
3082
+ let stat = await scope.remote.stat(targetDir).catch(() => null)
3083
+ if (!stat) {
3084
+ await scope.remote.mkdirp(targetDir)
3085
+ stat = await scope.remote.stat(targetDir)
3086
+ }
2938
3087
  if (stat.type !== 'dir') throw new ApiError('FS_NOT_DIR', '目标不是目录')
2939
3088
  const rawPaths = Array.isArray(params.paths) ? params.paths : [params.path]
2940
3089
  const paths = rawPaths.filter((item) => typeof item === 'string' && item.trim() !== '').map((item) => resolve(item.trim()))
2941
3090
  if (paths.length === 0) throw new ApiError('BAD_REQUEST', '没有可上传的文件')
2942
3091
  if (paths.length > 50) throw new ApiError('BAD_REQUEST', '一次最多上传 50 个文件')
3092
+ const conflict = params.conflict === 'overwrite' || params.conflict === 'unique' ? params.conflict : 'error'
3093
+ const prepared = []
2943
3094
  const limits = { files: 0, bytes: 0, skipped: 0 }
2944
3095
  for (const source of paths) {
2945
3096
  let info
@@ -2953,8 +3104,30 @@ export function apply(ctx) {
2953
3104
  limits.skipped += 1
2954
3105
  continue
2955
3106
  }
2956
- const data = readFileSync(source)
2957
- await scope.remote.writeFileAtomic(posix.join(targetDir, basename(source)), data)
3107
+ prepared.push({ source, name: basename(source) })
3108
+ }
3109
+ if (conflict === 'error' && prepared.length > 0) {
3110
+ const conflicts = []
3111
+ for (const item of prepared) {
3112
+ const existing = await scope.remote.stat(posix.join(targetDir, item.name)).catch(() => null)
3113
+ if (existing) conflicts.push(item.name)
3114
+ }
3115
+ if (conflicts.length > 0) {
3116
+ const shown = conflicts.slice(0, 5).join('、')
3117
+ const more = conflicts.length > 5 ? ` 等 ${conflicts.length} 个` : ''
3118
+ throw new ApiError('FS_EXISTS', `目标目录已有同名文件:${shown}${more}`)
3119
+ }
3120
+ }
3121
+ for (const item of prepared) {
3122
+ let targetName = item.name
3123
+ if (conflict === 'unique') {
3124
+ const existing = await scope.remote.stat(posix.join(targetDir, targetName)).catch(() => null)
3125
+ // Computed per item, after the previous write landed, so a batch of
3126
+ // same-named sources cannot collide with itself.
3127
+ if (existing) targetName = posix.basename(await remoteUniqueTarget(scope.remote, targetDir, targetName))
3128
+ }
3129
+ const data = readFileSync(item.source)
3130
+ await scope.remote.writeFileAtomic(posix.join(targetDir, targetName), data)
2958
3131
  limits.files += 1
2959
3132
  limits.bytes += data.length
2960
3133
  }
@@ -3053,6 +3226,13 @@ export function apply(ctx) {
3053
3226
  const workspace = findWorkspaceByPath(linkedRegistry(), record.localPath)
3054
3227
  if (workspace) await renameDshWorkspace(ctx, String(workspace.id), linkedWorkspaceTitle(record.name))
3055
3228
  }
3229
+ if (params.ensureWorkspace === true) {
3230
+ const existing = findWorkspaceByPath(linkedRegistry(), record.localPath)
3231
+ if (!existing) {
3232
+ const created = await ensureDshWorkspace(ctx.get('workspaceRegistry', true), record.localPath, linkedWorkspaceTitle(record.name))
3233
+ if (!created) throw new ApiError('INTERNAL', '无法注册本地工作区')
3234
+ }
3235
+ }
3056
3236
  if (nextMirror === true && params.mirror === true) {
3057
3237
  try {
3058
3238
  startSyncJob(record, { reason: 'enable' })
@@ -3109,6 +3289,159 @@ export function apply(ctx) {
3109
3289
  job.cancel = true
3110
3290
  return { cancelled: true }
3111
3291
  },
3292
+
3293
+ // ── remote_workspaces methods ───────────────────────────────────────────────
3294
+
3295
+ async 'remote_workspaces.list'() {
3296
+ await refreshHosts()
3297
+ return { workspaces: remoteStore.list().map((record) => describeRemote(record)) }
3298
+ },
3299
+
3300
+ async 'remote_workspaces.create'(params = {}) {
3301
+ const host = await findHost(params.hostId)
3302
+ const remote = await connectHost(host)
3303
+ const rawRemote = await normalizeRemotePath(remote, params.remotePath)
3304
+ const remoteRoot = await remote.realpath(rawRemote).catch(() => rawRemote)
3305
+ const remoteStat = await remote.stat(remoteRoot)
3306
+ if (remoteStat.type !== 'dir') throw new ApiError('FS_NOT_DIR', '远程路径不是目录')
3307
+
3308
+ // Check for conflicts
3309
+ const remoteClash = remoteStore.list().find((r) => r.hostId === host.id && r.remotePath === remoteRoot)
3310
+ if (remoteClash) throw new ApiError('BAD_REQUEST', `该远程目录已被远程工作区「${remoteClash.name}」使用`)
3311
+
3312
+ const requestedName = typeof params.name === 'string' ? params.name.trim() : ''
3313
+ if (requestedName.length > MAX_NAME_LENGTH) throw new ApiError('BAD_REQUEST', '工作区名称过长')
3314
+ const name = requestedName !== '' ? requestedName : basename(remoteRoot) || host.name
3315
+
3316
+ // Create placeholder directory
3317
+ const placeholderBase = join(dir, 'remote-placeholders')
3318
+ await mkdir(placeholderBase, { recursive: true })
3319
+ const placeholderId = randomUUID()
3320
+ const placeholderPath = join(placeholderBase, placeholderId)
3321
+ await mkdir(placeholderPath, { recursive: true })
3322
+
3323
+ // Register as DSH workspace
3324
+ const registry = ctx.get('workspaceRegistry', true)
3325
+ const workspace = await ensureDshWorkspace(registry, placeholderPath, name)
3326
+ if (!workspace) throw new ApiError('INTERNAL', '无法注册占位工作区')
3327
+
3328
+ // Create remote workspace record
3329
+ const record = {
3330
+ id: randomUUID(),
3331
+ hostId: host.id,
3332
+ remotePath: remoteRoot,
3333
+ placeholderPath,
3334
+ name,
3335
+ workspaceId: workspace.id,
3336
+ hostSnapshot: {
3337
+ name: host.name,
3338
+ host: host.host,
3339
+ port: host.port,
3340
+ username: host.username,
3341
+ },
3342
+ createdAt: Date.now(),
3343
+ }
3344
+ const saved = remoteStore.add(record)
3345
+
3346
+ pool.setStatus(host.id, { state: 'connected', latencyMs: 0 })
3347
+ log('info', `remote workspace "${name}" (placeholder: ${placeholderPath}, remote: ${host.username}@${host.host}:${remoteRoot})`)
3348
+
3349
+ return { workspace: describeRemote(saved) }
3350
+ },
3351
+
3352
+ async 'remote_workspaces.get'(params = {}) {
3353
+ if (typeof params.id !== 'string' || params.id === '') throw new ApiError('BAD_REQUEST', 'id is required')
3354
+ const record = remoteStore.get(params.id)
3355
+ if (!record) throw new ApiError('NOT_FOUND', 'remote workspace not found')
3356
+ return { workspace: describeRemote(record) }
3357
+ },
3358
+
3359
+ async 'remote_workspaces.update'(params = {}) {
3360
+ if (typeof params.id !== 'string' || params.id === '') throw new ApiError('BAD_REQUEST', 'id is required')
3361
+ const record = remoteStore.get(params.id)
3362
+ if (!record) throw new ApiError('NOT_FOUND', 'remote workspace not found')
3363
+
3364
+ const patch = {}
3365
+ if (params.name !== undefined) {
3366
+ const nextName = typeof params.name === 'string' ? params.name.trim() : ''
3367
+ if (nextName.length > MAX_NAME_LENGTH) throw new ApiError('BAD_REQUEST', '工作区名称过长')
3368
+ if (nextName !== '') patch.name = nextName
3369
+ }
3370
+
3371
+ const updated = remoteStore.update(params.id, patch)
3372
+
3373
+ // Update DSH workspace title if name changed
3374
+ if (patch.name && updated.workspaceId) {
3375
+ try {
3376
+ await renameDshWorkspace(ctx, updated.workspaceId, patch.name)
3377
+ } catch (error) {
3378
+ log('warn', `Failed to rename DSH workspace: ${error && error.message ? error.message : error}`)
3379
+ }
3380
+ }
3381
+
3382
+ return { workspace: describeRemote(updated) }
3383
+ },
3384
+
3385
+ async 'remote_workspaces.remove'(params = {}) {
3386
+ if (typeof params.id !== 'string' || params.id === '') throw new ApiError('BAD_REQUEST', 'id is required')
3387
+ const record = remoteStore.get(params.id)
3388
+ if (!record) throw new ApiError('NOT_FOUND', 'remote workspace not found')
3389
+
3390
+ remoteStore.remove(params.id)
3391
+
3392
+ // Remove DSH workspace
3393
+ let removedWorkspace = false
3394
+ if (record.workspaceId) {
3395
+ const registry = ctx.get('workspaceRegistry', true)
3396
+ if (registry && typeof registry.delete === 'function') {
3397
+ try {
3398
+ removedWorkspace = await registry.delete(record.workspaceId)
3399
+ } catch (error) {
3400
+ log('warn', `DSH workspace removal failed: ${error && error.message ? error.message : error}`)
3401
+ }
3402
+ }
3403
+ }
3404
+
3405
+ // Remove placeholder directory
3406
+ let removedPlaceholder = false
3407
+ try {
3408
+ rmSync(record.placeholderPath, { recursive: true, force: true })
3409
+ removedPlaceholder = true
3410
+ } catch (error) {
3411
+ log('warn', `Placeholder removal failed: ${error && error.message ? error.message : error}`)
3412
+ }
3413
+
3414
+ return { removedWorkspace, removedPlaceholder }
3415
+ },
3416
+
3417
+ async 'remote_workspaces.test'(params = {}) {
3418
+ if (typeof params.id !== 'string' || params.id === '') throw new ApiError('BAD_REQUEST', 'id is required')
3419
+ const record = remoteStore.get(params.id)
3420
+ if (!record) throw new ApiError('NOT_FOUND', 'remote workspace not found')
3421
+
3422
+ const host = await findHost(record.hostId)
3423
+ const started = Date.now()
3424
+ try {
3425
+ const remote = await connectHost(host)
3426
+ const stat = await remote.stat(record.remotePath)
3427
+ const latencyMs = Date.now() - started
3428
+ pool.setStatus(host.id, { state: 'connected', latencyMs })
3429
+ return {
3430
+ ok: true,
3431
+ latencyMs,
3432
+ exists: stat.type === 'dir',
3433
+ type: stat.type,
3434
+ }
3435
+ } catch (error) {
3436
+ const apiError = asApiError(error)
3437
+ pool.setStatus(host.id, { state: 'error', message: apiError.message })
3438
+ return {
3439
+ ok: false,
3440
+ error: apiError.message,
3441
+ latencyMs: Date.now() - started,
3442
+ }
3443
+ }
3444
+ },
3112
3445
  }
3113
3446
 
3114
3447
  // ── linked_workspace agent tool + prompt section ──────────────────────────
@@ -3179,7 +3512,7 @@ export function apply(ctx) {
3179
3512
  const service = ctx.get('skills')
3180
3513
  if (service && typeof service.list === 'function') {
3181
3514
  try {
3182
- const list = await service.list({ cwd: link.localPath, signal })
3515
+ const list = await service.list({ cwd: recordLocalPath(link), signal })
3183
3516
  if (Array.isArray(list)) {
3184
3517
  return list.map((skill) => ({
3185
3518
  name: skill.name,
@@ -3193,14 +3526,14 @@ export function apply(ctx) {
3193
3526
  /* fall back to a direct scan */
3194
3527
  }
3195
3528
  }
3196
- return scanLocalSkills(link.localPath)
3529
+ return scanLocalSkills(recordLocalPath(link))
3197
3530
  }
3198
3531
 
3199
3532
  const readLocalSkill = async (link, name, signal) => {
3200
3533
  const service = ctx.get('skills')
3201
3534
  if (service && typeof service.get === 'function') {
3202
3535
  try {
3203
- const skill = await service.get(name, { cwd: link.localPath, signal })
3536
+ const skill = await service.get(name, { cwd: recordLocalPath(link), signal })
3204
3537
  if (skill && typeof skill.content === 'string') {
3205
3538
  return { name: skill.name, description: skill.description || '', content: skill.content, path: skill.path || '' }
3206
3539
  }
@@ -3208,7 +3541,7 @@ export function apply(ctx) {
3208
3541
  /* fall back */
3209
3542
  }
3210
3543
  }
3211
- for (const skill of scanLocalSkills(link.localPath)) {
3544
+ for (const skill of scanLocalSkills(recordLocalPath(link))) {
3212
3545
  if (skill.name !== name) continue
3213
3546
  const content = readFileSync(skill.path, 'utf8')
3214
3547
  return { name: skill.name, description: skill.description, content, path: skill.path }
@@ -3221,26 +3554,26 @@ export function apply(ctx) {
3221
3554
  timeoutMs: 120_000,
3222
3555
  isConcurrencySafe: (args) => ['list', 'info', 'list_dir', 'read', 'stat'].includes(String((args && args.action) || '').trim()),
3223
3556
  description:
3224
- 'Read and edit files of a linked remote workspace (a local directory paired with a remote directory over SSH). '
3225
- + 'Actions: list (all linked workspaces), info, list_dir, read, write, replace, stat, mkdir, rename, delete, sync. '
3557
+ '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). '
3558
+ + 'Actions: list (all linked and remote workspaces), info, list_dir, read, write, replace, stat, mkdir, rename, delete, sync (linked workspaces only). '
3226
3559
  + '`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. '
3227
- + 'The workspace is resolved from the session working directory; pass `workspace` (link id, local path or name) when working elsewhere. '
3228
- + 'Local files (including .local/ and .remote/) still use the normal read/write/bash tools.',
3560
+ + 'The workspace is resolved from the session working directory; pass `workspace` (id, local path, placeholder path or name) when working elsewhere. '
3561
+ + 'Local files of a linked workspace (including .local/ and .remote/) still use the normal read/write/bash tools.',
3229
3562
  parameters: {
3230
3563
  type: 'object',
3231
3564
  properties: {
3232
3565
  action: {
3233
3566
  type: 'string',
3234
3567
  enum: ['list', 'info', 'list_dir', 'read', 'write', 'replace', 'stat', 'mkdir', 'rename', 'delete', 'sync'],
3235
- description: 'Operation to perform.',
3568
+ description: 'Operation to perform. sync only applies to a linked workspace with mirroring on.',
3236
3569
  },
3237
3570
  workspace: {
3238
3571
  type: 'string',
3239
- description: 'Optional linked workspace reference: link id, absolute local path, or workspace name. Omit to use the session working directory.',
3572
+ description: 'Optional workspace reference: id, absolute local path, placeholder path, or workspace name. Omit to use the session working directory.',
3240
3573
  },
3241
3574
  path: {
3242
3575
  type: 'string',
3243
- description: 'Remote path relative to the linked workspace root, or an absolute path inside it. Empty means the root.',
3576
+ description: 'Remote path relative to the workspace root, or an absolute path inside it. Empty means the root.',
3244
3577
  },
3245
3578
  destination: { type: 'string', description: 'Destination path for rename (relative or absolute inside the root).' },
3246
3579
  content: { type: 'string', description: 'Full file content for write.' },
@@ -3269,30 +3602,61 @@ export function apply(ctx) {
3269
3602
  if (!exec || !exec.agent) throw new ApiError('BAD_REQUEST', `${LINKED_TOOL_NAME} requires an agent session`)
3270
3603
  const action = String((args && args.action) || '').trim()
3271
3604
  if (action === 'list') {
3272
- const lines = linkedStore.list().map((record) => {
3605
+ const linkedLines = linkedStore.list().map((record) => {
3273
3606
  const described = describeLink(record)
3274
3607
  return [
3275
- `- ${described.name}`,
3608
+ `- ${described.name} (linked)`,
3276
3609
  ` local: ${described.localPath}`,
3277
3610
  ` remote: ${described.username}@${described.host}:${described.remotePath}`,
3278
3611
  ` mirror: ${described.mirror ? 'on' : 'off'}`,
3279
3612
  ].join('\n')
3280
3613
  })
3281
- return toolText(lines.length === 0 ? 'No linked workspaces yet.' : lines.join('\n'))
3614
+ const remoteLines = remoteStore.list().map((record) => {
3615
+ const host = pool.host(record.hostId)
3616
+ const hostLabel = host ? `${host.username}@${host.host}` : record.hostId
3617
+ return [
3618
+ `- ${record.name} (remote)`,
3619
+ ` placeholder: ${record.placeholderPath}`,
3620
+ ` remote: ${hostLabel}:${record.remotePath}`,
3621
+ ` workspaceId: ${record.workspaceId || 'none'}`,
3622
+ ].join('\n')
3623
+ })
3624
+ const allLines = [...linkedLines, ...remoteLines]
3625
+ return toolText(allLines.length === 0 ? 'No linked or remote workspaces yet.' : allLines.join('\n'))
3282
3626
  }
3283
3627
 
3284
3628
  const link = await resolveLinkedSelection(args, exec)
3629
+ const remoteKind = isRemoteRecord(link)
3285
3630
  const remote = await hostForLink(link)
3286
3631
  const root = linkedRootOf(link)
3287
3632
  const target = linkedTarget(link, args.path)
3288
3633
 
3289
3634
  if (action === 'info') {
3290
3635
  const stat = await remote.stat(root)
3636
+ const host = pool.host(link.hostId)
3637
+ const snapshot = link.hostSnapshot || {}
3638
+ const hostLabel = host
3639
+ ? `${host.username}@${host.host}:${host.port}`
3640
+ : `${snapshot.username || '?'}@${snapshot.host || link.hostId}:${snapshot.port || 22}`
3641
+ if (remoteKind) {
3642
+ return toolText(JSON.stringify({
3643
+ id: link.id,
3644
+ kind: 'remote',
3645
+ name: link.name,
3646
+ remoteHost: hostLabel,
3647
+ remoteRoot: root,
3648
+ placeholderPath: link.placeholderPath,
3649
+ workspaceId: link.workspaceId || null,
3650
+ mirror: false,
3651
+ remoteRootType: stat.type,
3652
+ }, null, 2))
3653
+ }
3291
3654
  return toolText(JSON.stringify({
3292
3655
  id: link.id,
3656
+ kind: 'linked',
3293
3657
  name: link.name,
3294
3658
  localPath: link.localPath,
3295
- remoteHost: `${link.hostSnapshot.username}@${link.hostSnapshot.host}:${link.hostSnapshot.port}`,
3659
+ remoteHost: hostLabel,
3296
3660
  remoteRoot: root,
3297
3661
  mirror: Boolean(link.mirror),
3298
3662
  mirrorDir: link.mirror ? join(link.localPath, linkedFs.MIRROR_DIR) : null,
@@ -3388,24 +3752,27 @@ export function apply(ctx) {
3388
3752
  throw new ApiError('BAD_REQUEST', 'destination is required')
3389
3753
  }
3390
3754
  const destination = linkedTarget(link, args.destination)
3391
- if (target === root) throw new ApiError('BAD_REQUEST', '不能移动联动工作区根目录')
3755
+ if (target === root) throw new ApiError('BAD_REQUEST', '不能移动工作区根目录')
3392
3756
  await remote.rename(target, destination)
3393
- await linkedFs.removeMirrorPath(link.localPath, linkedRelative(link, target)).catch(() => {})
3757
+ if (!remoteKind) await linkedFs.removeMirrorPath(link.localPath, linkedRelative(link, target)).catch(() => {})
3394
3758
  return toolText(`Renamed ${target} -> ${destination}`)
3395
3759
  }
3396
3760
 
3397
3761
  if (action === 'delete') {
3398
- if (target === root) throw new ApiError('BAD_REQUEST', '不能删除联动工作区根目录')
3762
+ if (target === root) throw new ApiError('BAD_REQUEST', '不能删除工作区根目录')
3399
3763
  const stat = await remote.stat(target)
3400
3764
  // rmdir only removes empty directories (same as the UI's fs.delete,
3401
3765
  // which uses this recursive helper).
3402
3766
  if (stat.type === 'dir') await remoteDeleteRecursive(remote, target)
3403
3767
  else await remote.unlink(target)
3404
- await linkedFs.removeMirrorPath(link.localPath, linkedRelative(link, target)).catch(() => {})
3768
+ if (!remoteKind) await linkedFs.removeMirrorPath(link.localPath, linkedRelative(link, target)).catch(() => {})
3405
3769
  return toolText(`Deleted ${target}`)
3406
3770
  }
3407
3771
 
3408
3772
  if (action === 'sync') {
3773
+ if (remoteKind) {
3774
+ throw new ApiError('BAD_REQUEST', '远程工作区没有本地副本,无需 sync;sync 只适用于开启镜像的联动工作区')
3775
+ }
3409
3776
  const job = startSyncJob(link, args)
3410
3777
  return toolText(
3411
3778
  `Sync job running in the background: ${job.files} file(s) / ${job.bytes} bytes archived so far (${job.skipped} skipped). `
@@ -3551,7 +3918,7 @@ export function apply(ctx) {
3551
3918
  'dsh-linked-workspace: close ssh sessions',
3552
3919
  )
3553
3920
 
3554
- log('info', `loaded (${store.list().length} remote workspace${store.list().length === 1 ? '' : 's'})`)
3921
+ log('info', `loaded (${linkedStore.list().length} linked, ${remoteStore.list().length} remote workspace${linkedStore.list().length + remoteStore.list().length === 1 ? '' : 's'})`)
3555
3922
  const autoSyncTimer = setInterval(autoSyncTick, AUTO_SYNC_TICK_MS)
3556
3923
  if (autoSyncTimer && typeof autoSyncTimer.unref === 'function') autoSyncTimer.unref()
3557
3924
  ctx.effect(() => () => clearInterval(autoSyncTimer), 'dsh-linked-workspace: auto sync timer')