dsh-linked-workspace 0.22.0 → 0.24.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
@@ -18,6 +18,7 @@
18
18
  import { createHash, randomUUID } from 'node:crypto'
19
19
  import { chmodSync, closeSync, cpSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, renameSync, rmSync, statSync, watch, writeFileSync } from 'node:fs'
20
20
  import { spawn } from 'node:child_process'
21
+ import net from 'node:net'
21
22
  import { appendFile, mkdir, readdir, rename, rm, stat as fsStat } from 'node:fs/promises'
22
23
  import { homedir, tmpdir } from 'node:os'
23
24
  import { basename, dirname, extname, isAbsolute, join, posix, resolve, sep } from 'node:path'
@@ -38,7 +39,7 @@ export const inject = ['webServer', 'tools', 'systemPrompt', 'workingDirectory']
38
39
  * is still running an older copy of the Host — refreshing the page only swaps
39
40
  * the browser bundle, so the two halves can drift by one restart.
40
41
  */
41
- const API_REVISION = 7
42
+ const API_REVISION = 8
42
43
 
43
44
  /** When this copy of the Host was loaded; shown by `meta.info`. */
44
45
  const STARTED_AT = new Date().toISOString()
@@ -474,7 +475,7 @@ function normalizeStringList(value) {
474
475
  class SettingsStore {
475
476
  constructor(file) {
476
477
  this.file = file
477
- this.value = { ...SETTINGS_DEFAULTS, execHostIds: [], execWorkspaceIds: [], autoPushInclude: [], autoPushExclude: [] }
478
+ this.value = { ...SETTINGS_DEFAULTS, execHostIds: [], execWorkspaceIds: [], autoPushInclude: [], autoPushExclude: [], extraRoots: [] }
478
479
  const raw = readJsonFile(file, { version: SETTINGS_VERSION, settings: {} })
479
480
  const settings = raw && typeof raw === 'object' && raw.settings && typeof raw.settings === 'object'
480
481
  ? raw.settings
@@ -513,6 +514,7 @@ class SettingsStore {
513
514
  }
514
515
  this.value.autoPushInclude = normalizeStringList(settings.autoPushInclude)
515
516
  this.value.autoPushExclude = normalizeStringList(settings.autoPushExclude)
517
+ this.value.extraRoots = normalizeStringList(settings.extraRoots)
516
518
  }
517
519
  if (settings && typeof settings === 'object' && HOST_KEY_POLICIES.has(settings.hostKeyPolicy)) {
518
520
  this.value.hostKeyPolicy = settings.hostKeyPolicy
@@ -554,6 +556,7 @@ class SettingsStore {
554
556
  execWorkspaceIds: this.value.execWorkspaceIds ? this.value.execWorkspaceIds.slice() : [],
555
557
  autoPushInclude: this.value.autoPushInclude ? this.value.autoPushInclude.slice() : [],
556
558
  autoPushExclude: this.value.autoPushExclude ? this.value.autoPushExclude.slice() : [],
559
+ extraRoots: this.value.extraRoots ? this.value.extraRoots.slice() : [],
557
560
  }
558
561
  }
559
562
 
@@ -629,6 +632,10 @@ class SettingsStore {
629
632
  if (!Array.isArray(patch.autoPushExclude)) throw new ApiError('BAD_REQUEST', '自动推送排除列表必须是字符串数组')
630
633
  this.value.autoPushExclude = normalizeStringList(patch.autoPushExclude)
631
634
  }
635
+ if (patch && typeof patch === 'object' && patch.extraRoots !== undefined) {
636
+ if (!Array.isArray(patch.extraRoots)) throw new ApiError('BAD_REQUEST', '额外根目录必须是字符串数组')
637
+ this.value.extraRoots = normalizeStringList(patch.extraRoots)
638
+ }
632
639
  writeJsonAtomic(this.file, { version: SETTINGS_VERSION, settings: { ...this.value, themeExplicit: this.themeExplicit === true } })
633
640
  return this.get()
634
641
  }
@@ -1076,6 +1083,18 @@ export function apply(ctx) {
1076
1083
  migrateLegacyDataDir(dir)
1077
1084
  ensureDir(dir)
1078
1085
  const settingsStore = new SettingsStore(join(dir, 'settings.json'))
1086
+ /** localhost TCP tunnels opened by hosts.forward (id -> { server, ... }) */
1087
+ const forwardServers = new Map()
1088
+ const forwardView = (record) => ({
1089
+ id: record.id,
1090
+ hostId: record.hostId,
1091
+ hostName: record.hostName,
1092
+ remoteHost: record.remoteHost,
1093
+ remotePort: record.remotePort,
1094
+ localPort: record.localPort,
1095
+ startedAt: record.startedAt,
1096
+ url: `http://127.0.0.1:${record.localPort}/`,
1097
+ })
1079
1098
  const linkedStore = new linkedFs.LinkedStore(join(dir, 'linked.json'))
1080
1099
  const remoteStore = new RemoteWorkspaceStore(join(dir, 'remote-workspaces.json'))
1081
1100
  // Old "open in notepad" copies are dead weight; clear them once per start.
@@ -1249,6 +1268,7 @@ export function apply(ctx) {
1249
1268
  username: host ? host.username : snapshot.username || '',
1250
1269
  remotePath: record.remotePath,
1251
1270
  mirror: Boolean(record.mirror),
1271
+ autoPush: record.autoPush,
1252
1272
  running: Boolean(runningKeys && runningKeys.has(linkedFs.localPathKey(record.localPath))),
1253
1273
  createdAt: record.createdAt,
1254
1274
  workspaceId: workspace ? String(workspace.id) : null,
@@ -1606,6 +1626,10 @@ export function apply(ctx) {
1606
1626
  '- action "list" returns every linked and remote workspace with its local path (or placeholder), SSH host, remote root and mirror state.',
1607
1627
  '- action "info" | "list_dir" | "read" | "write" | "replace" | "stat" | "mkdir" | "rename" | "delete" takes `path` relative to the remote root (or an absolute path inside it).',
1608
1628
  '- Writes are atomic. Pass `if_modified_since` (epoch milliseconds from a previous read/stat) to refuse a stale overwrite.',
1629
+ '- action "read_doc" returns the text of a PDF/Word/Excel/PowerPoint file; plain action "read" only returns metadata for those, so do not install a parser.',
1630
+ '- action "sync_status" reports the progress of the last "sync" job (archived/checked/skipped counts).',
1631
+ '- action "forward" opens a local TCP tunnel to a port on the host (for TensorBoard, Jupyter, a notebook preview); "forwards" lists them and "unforward" closes one.',
1632
+ '- actions "read_outside"/"write_outside"/"list_outside" reach paths outside the workspace root, but only under the extra roots configured in Settings → Linked workspaces.',
1609
1633
  '- action "sync" archives the remote tree into `.remote/` and only exists for a linked workspace (a remote workspace has no local copy).',
1610
1634
  '- action "exec" runs ONE non-interactive command on the remote host (builds, tests, logs). It only works when the user switched remote execution on and allow-listed this host/workspace; every attempt is audited.',
1611
1635
  '- action "references" lists workspace paths matching a query (best match first, directories marked `dir`), which is how you resolve a remote path a user mentioned by name.',
@@ -1659,6 +1683,49 @@ export function apply(ctx) {
1659
1683
  }
1660
1684
  }
1661
1685
 
1686
+ // ── extra roots (paths outside the workspace the user opted into) ──────
1687
+
1688
+ const EXTRA_ROOT_HINT = '路径在工作区之外;如需访问,请先在 设置 → 联动工作区 → 额外根目录 里添加该前缀'
1689
+
1690
+ const extraRoots = () => settingsStore.get().extraRoots || []
1691
+
1692
+ const matchExtraRoot = (target) => {
1693
+ for (const entry of extraRoots()) {
1694
+ const text = String(entry || '').trim()
1695
+ if (text === '' || !text.startsWith('/')) continue
1696
+ const root = posix.resolve(text)
1697
+ if (root === '/' || root === '') continue
1698
+ if (target === root || target.startsWith(root + '/')) return root
1699
+ }
1700
+ return ''
1701
+ }
1702
+
1703
+ const appendExtraAudit = async (entry) => {
1704
+ try {
1705
+ await mkdir(dir, { recursive: true })
1706
+ const line = JSON.stringify({ at: new Date().toISOString(), ...entry }) + '\n'
1707
+ await appendFile(join(dir, 'outside-audit.jsonl'), line, { mode: 0o600 })
1708
+ } catch (error) {
1709
+ log('warn', `outside audit failed: ${error && error.message ? error.message : error}`)
1710
+ }
1711
+ }
1712
+
1713
+ /**
1714
+ * Resolve a path that may live outside the workspace root, but only under one
1715
+ * of the configured extra roots. Every call is appended to
1716
+ * `outside-audit.jsonl` so the user can see what the plugin touched.
1717
+ */
1718
+ const extraTarget = async (params = {}, method = 'fs') => {
1719
+ const scope = await requireScope(params)
1720
+ const text = typeof params.path === 'string' ? params.path.trim() : ''
1721
+ if (text === '') throw new ApiError('BAD_REQUEST', '路径不能为空')
1722
+ const target = text.startsWith('/') ? posix.resolve(text) : posix.resolve(scope.root, text)
1723
+ const root = matchExtraRoot(target)
1724
+ if (root === '') throw new ApiError('BAD_REQUEST', EXTRA_ROOT_HINT)
1725
+ await appendExtraAudit({ method, target, root, workspace: scope.id, kind: scope.kind })
1726
+ return { scope, root, target }
1727
+ }
1728
+
1662
1729
  // ── context-menu / transfer helpers ─────────────────────────────────────
1663
1730
 
1664
1731
  const CONTEXT_TREE_LIMITS = { maxFiles: 150, maxBytes: 15 * 1024 * 1024, maxDepth: 12 }
@@ -2198,16 +2265,18 @@ export function apply(ctx) {
2198
2265
  return false
2199
2266
  }
2200
2267
 
2201
- const autoPushFilter = (settings, plan) => {
2202
- const include = autoPushMatches(settings.autoPushInclude, '')
2268
+ // The include/exclude globs and the debounce now live on each linked record
2269
+ // (`record.autoPush`, see lib/linked.js), so two workspaces can behave very
2270
+ // differently: one pushes every save, another only `docs/**`.
2271
+
2272
+ const autoPushFilter = (autoPush, plan) => {
2203
2273
  const keep = (item) => {
2204
- const included = autoPushMatches(settings.autoPushInclude, item.relative)
2274
+ const included = autoPushMatches(autoPush.include, item.relative)
2205
2275
  if (included === false) return false
2206
- const excluded = autoPushMatches(settings.autoPushExclude, item.relative)
2276
+ const excluded = autoPushMatches(autoPush.exclude, item.relative)
2207
2277
  if (excluded === true) return false
2208
2278
  return true
2209
2279
  }
2210
- void include
2211
2280
  return { ...plan, added: plan.added.filter(keep), changed: plan.changed.filter(keep) }
2212
2281
  }
2213
2282
 
@@ -2219,15 +2288,20 @@ export function apply(ctx) {
2219
2288
  autoPushWatchers.delete(id)
2220
2289
  }
2221
2290
 
2222
- const runAutoPush = async (record, entry) => {
2291
+ const runAutoPush = async (recordId, entry) => {
2223
2292
  if (entry.running) return
2224
2293
  entry.running = true
2225
2294
  try {
2226
- const settings = settingsStore.get()
2227
- if (!settings.autoPushEnabled) return
2295
+ // Re-read the record: the config may have changed (or the workspace may
2296
+ // be gone) since the watcher was armed.
2297
+ const record = linkedStore.get(recordId)
2298
+ if (!record || record.autoPush.enabled !== true) {
2299
+ stopAutoPush(recordId)
2300
+ return
2301
+ }
2228
2302
  const host = await findHost(record.hostId)
2229
2303
  const remote = await connectHost(host)
2230
- const plan = autoPushFilter(settings, await buildPlan(record, remote, {}))
2304
+ const plan = autoPushFilter(record.autoPush, await buildPlan(record, remote, {}))
2231
2305
  if (plan.added.length === 0 && plan.changed.length === 0) {
2232
2306
  entry.failures = 0
2233
2307
  return
@@ -2243,45 +2317,45 @@ export function apply(ctx) {
2243
2317
  // An unreachable host must not retry forever: five attempts with
2244
2318
  // backoff, then wait for the next local edit to start over.
2245
2319
  entry.failures = 0
2246
- log('warn', `autoPush ${record.name} gave up after ${AUTO_PUSH_MAX_ATTEMPTS} attempts: ${message}`)
2320
+ log('warn', `autoPush ${recordId} gave up after ${AUTO_PUSH_MAX_ATTEMPTS} attempts: ${message}`)
2247
2321
  return
2248
2322
  }
2249
2323
  const wait = Math.min(AUTO_PUSH_RETRY_MS * 2 ** (entry.failures - 1), AUTO_PUSH_RETRY_MAX)
2250
- log('warn', `autoPush ${record.name} failed (attempt ${entry.failures}/${AUTO_PUSH_MAX_ATTEMPTS}, retry in ${wait}ms): ${message}`)
2251
- entry.timer = setTimeout(() => { entry.timer = null; void runAutoPush(record, entry) }, wait)
2324
+ log('warn', `autoPush ${recordId} failed (attempt ${entry.failures}/${AUTO_PUSH_MAX_ATTEMPTS}, retry in ${wait}ms): ${message}`)
2325
+ entry.timer = setTimeout(() => { entry.timer = null; void runAutoPush(recordId, entry) }, wait)
2252
2326
  if (entry.timer && typeof entry.timer.unref === 'function') entry.timer.unref()
2253
2327
  } finally {
2254
2328
  entry.running = false
2255
2329
  }
2256
2330
  }
2257
2331
 
2258
- const scheduleAutoPush = (record, entry) => {
2332
+ const scheduleAutoPush = (recordId, entry) => {
2259
2333
  if (entry.timer) clearTimeout(entry.timer)
2260
- const settings = settingsStore.get()
2261
- const delay = clampInt(settings.autoPushDebounceMs, AUTO_PUSH_DEBOUNCE_MIN, AUTO_PUSH_DEBOUNCE_MAX, 1500)
2334
+ const record = linkedStore.get(recordId)
2335
+ if (!record) {
2336
+ stopAutoPush(recordId)
2337
+ return
2338
+ }
2339
+ const delay = clampInt(record.autoPush.debounceMs, AUTO_PUSH_DEBOUNCE_MIN, AUTO_PUSH_DEBOUNCE_MAX, 1500)
2262
2340
  entry.timer = setTimeout(() => {
2263
2341
  entry.timer = null
2264
- void runAutoPush(record, entry)
2342
+ void runAutoPush(recordId, entry)
2265
2343
  }, delay)
2266
2344
  if (entry.timer && typeof entry.timer.unref === 'function') entry.timer.unref()
2267
2345
  }
2268
2346
 
2269
- /** Start/stop watchers so they match the current settings; safe to call often. */
2347
+ /** Start/stop watchers so they match each workspace's own autoPush switch. */
2270
2348
  const syncAutoPush = () => {
2271
- const settings = settingsStore.get()
2272
- const wanted = settings.autoPushEnabled === true
2273
- for (const id of [...autoPushWatchers.keys()]) {
2274
- const record = linkedStore.get(id)
2275
- if (!wanted || !record) stopAutoPush(id)
2276
- }
2277
- if (!wanted) return
2349
+ const live = new Set()
2278
2350
  for (const record of linkedStore.list()) {
2351
+ if (record.autoPush.enabled !== true) continue
2352
+ live.add(record.id)
2279
2353
  if (autoPushWatchers.has(record.id)) continue
2280
2354
  let watcher
2281
2355
  try {
2282
2356
  watcher = watch(record.localPath, { recursive: true, persistent: false }, () => {
2283
2357
  const entry = autoPushWatchers.get(record.id)
2284
- if (entry) scheduleAutoPush(record, entry)
2358
+ if (entry) scheduleAutoPush(record.id, entry)
2285
2359
  })
2286
2360
  } catch (error) {
2287
2361
  log('warn', `autoPush watcher for ${record.name} failed: ${error && error.message ? error.message : error}`)
@@ -2290,6 +2364,9 @@ export function apply(ctx) {
2290
2364
  watcher.on('error', () => stopAutoPush(record.id))
2291
2365
  autoPushWatchers.set(record.id, { watcher, timer: null, running: false })
2292
2366
  }
2367
+ for (const id of [...autoPushWatchers.keys()]) {
2368
+ if (!live.has(id)) stopAutoPush(id)
2369
+ }
2293
2370
  }
2294
2371
 
2295
2372
  // A content search can run for seconds; the client can stop it by job id the
@@ -2464,6 +2541,39 @@ export function apply(ctx) {
2464
2541
  })
2465
2542
  }
2466
2543
 
2544
+ /** Flatten the tool's structured output into plain text for the model. */
2545
+ function flattenDocText(kind, data, maxChars) {
2546
+ const chunks = []
2547
+ if (kind === 'pdf') {
2548
+ for (const page of data.pages || []) {
2549
+ chunks.push(`=== page ${page.index + 1} ===\n${String(page.text || '').trimEnd()}`)
2550
+ }
2551
+ } else if (kind === 'docx') {
2552
+ const body = (data.paragraphs || []).join('\n')
2553
+ if (body.trim() !== '') chunks.push(body)
2554
+ ;(data.tables || []).forEach((rows, index) => {
2555
+ const lines = (rows || []).map((row) => row.join('\t'))
2556
+ chunks.push(`=== table ${index + 1} ===\n${lines.join('\n')}`)
2557
+ })
2558
+ } else if (kind === 'xlsx') {
2559
+ for (const sheet of data.sheets || []) {
2560
+ const lines = (sheet.rows || []).map((row) => row.join('\t'))
2561
+ chunks.push(`=== sheet ${sheet.name} ===\n${lines.join('\n')}`)
2562
+ }
2563
+ } else if (kind === 'pptx') {
2564
+ for (const slide of data.slides || []) {
2565
+ const body = (slide.texts || []).join('\n')
2566
+ const notes = slide.notes && String(slide.notes).trim() !== '' ? `\n[notes] ${String(slide.notes).trim()}` : ''
2567
+ chunks.push(`=== slide ${slide.index + 1} ===\n${body}${notes}`)
2568
+ }
2569
+ }
2570
+ let text = chunks.filter((chunk) => chunk.trim() !== '').join('\n\n')
2571
+ const limit = clampInt(maxChars, 1000, 200000, 40000)
2572
+ const truncated = text.length > limit
2573
+ if (truncated) text = text.slice(0, limit) + '\n…(truncated)'
2574
+ return { text, truncated, limit }
2575
+ }
2576
+
2467
2577
  async function docTarget(params) {
2468
2578
  if (params.linkedId || params.remoteId || params.workspaceId) {
2469
2579
  const scope = await requireScope(params)
@@ -3128,6 +3238,63 @@ export function apply(ctx) {
3128
3238
  * Every remembered host key, so a changed one can be forgotten in the UI
3129
3239
  * instead of hand-editing `known_hosts.json` (0.20.0).
3130
3240
  */
3241
+ async 'hosts.forward'(params = {}) {
3242
+ const host = await findHost(params.hostId)
3243
+ const remotePort = clampInt(params.remotePort, 1, 65535, 0)
3244
+ if (remotePort === 0) throw new ApiError('BAD_REQUEST', 'remotePort 必须是 1–65535')
3245
+ const remoteHost = typeof params.remoteHost === 'string' && params.remoteHost.trim() !== ''
3246
+ ? params.remoteHost.trim()
3247
+ : '127.0.0.1'
3248
+ const wantedPort = clampInt(params.localPort, 1, 65535, 0)
3249
+ const existing = [...forwardServers.values()].find((item) => item.hostId === host.id
3250
+ && item.remotePort === remotePort && item.remoteHost === remoteHost)
3251
+ if (existing) return { forward: forwardView(existing) }
3252
+ const remote = await pool.remote(host)
3253
+ const id = randomUUID()
3254
+ const server = net.createServer((socket) => {
3255
+ remote.forwardOut(remoteHost, remotePort).then((channel) => {
3256
+ socket.pipe(channel).pipe(socket)
3257
+ channel.on('error', () => socket.destroy())
3258
+ socket.on('error', () => channel.destroy())
3259
+ }).catch((error) => {
3260
+ log('warn', `forward ${id} failed: ${error && error.message ? error.message : error}`)
3261
+ socket.destroy()
3262
+ })
3263
+ })
3264
+ await new Promise((resolvePromise, rejectPromise) => {
3265
+ server.once('error', rejectPromise)
3266
+ server.listen(wantedPort, '127.0.0.1', () => resolvePromise())
3267
+ }).catch((error) => {
3268
+ throw new ApiError('FORWARD_FAILED', `无法监听本地端口:${error && error.message ? error.message : error}`)
3269
+ })
3270
+ const record = {
3271
+ id,
3272
+ hostId: host.id,
3273
+ hostName: host.name || host.id,
3274
+ remoteHost,
3275
+ remotePort,
3276
+ localPort: server.address().port,
3277
+ startedAt: Date.now(),
3278
+ server,
3279
+ remote,
3280
+ }
3281
+ forwardServers.set(id, record)
3282
+ return { forward: forwardView(record) }
3283
+ },
3284
+
3285
+ async 'hosts.forwards'() {
3286
+ return { forwards: [...forwardServers.values()].map(forwardView) }
3287
+ },
3288
+
3289
+ async 'hosts.unforward'(params = {}) {
3290
+ const id = typeof params.id === 'string' ? params.id.trim() : ''
3291
+ const record = forwardServers.get(id)
3292
+ if (!record) return { removed: false }
3293
+ try { record.server.close() } catch { /* already closed */ }
3294
+ forwardServers.delete(id)
3295
+ return { removed: true }
3296
+ },
3297
+
3131
3298
  async 'hosts.hostKeys'() {
3132
3299
  const entries = await listKnownHosts(join(dir, 'known_hosts.json'))
3133
3300
  let hosts = []
@@ -3469,6 +3636,61 @@ export function apply(ctx) {
3469
3636
  }
3470
3637
  },
3471
3638
 
3639
+ /**
3640
+ * Plain text of a document, for the model rather than the viewer.
3641
+ * `docs.read` returns page images so the panel can render them; this returns
3642
+ * extractable text so an agent can actually read a PDF, Word, Excel or
3643
+ * PowerPoint file instead of installing a parser of its own.
3644
+ */
3645
+ async 'docs.text'(params = {}) {
3646
+ const target = await docTarget(params)
3647
+ const kind = assertDocKind(target.path)
3648
+ const limit = clampInt(params.maxChars, 1000, 200000, 40000)
3649
+ const stat = await docStat(target)
3650
+ if (kind === 'markdown') {
3651
+ const current = await readDocBytes(target, target)
3652
+ if (looksBinary(current.data)) throw new ApiError('DOC_BINARY', 'Markdown 文件包含二进制内容')
3653
+ const raw = decodeUtf8(current.data)
3654
+ const truncated = raw.length > limit
3655
+ return {
3656
+ kind,
3657
+ path: target.path,
3658
+ size: current.size,
3659
+ mtime: current.mtime,
3660
+ pageCount: null,
3661
+ text: truncated ? raw.slice(0, limit) + '\n…(truncated)' : raw,
3662
+ truncated,
3663
+ }
3664
+ }
3665
+ const temp = await makeDocTemp()
3666
+ try {
3667
+ let input
3668
+ if (kind === 'pdf') {
3669
+ input = (await ensureDocCache(target)).file
3670
+ } else {
3671
+ const current = await readDocBytes(target, target)
3672
+ input = temp.file('input.' + kind)
3673
+ writeFileSync(input, current.data)
3674
+ }
3675
+ const data = await runDocTool(['read-text', '--kind', kind, '--file', input], 180000)
3676
+ const flat = flattenDocText(kind, data, limit)
3677
+ const pageCount = kind === 'pdf'
3678
+ ? (data.pageCount || 0)
3679
+ : kind === 'pptx' ? (data.slides || []).length : kind === 'xlsx' ? (data.sheets || []).length : null
3680
+ return {
3681
+ kind,
3682
+ path: target.path,
3683
+ size: stat ? stat.size : null,
3684
+ mtime: stat ? stat.mtime : null,
3685
+ pageCount,
3686
+ text: flat.text,
3687
+ truncated: flat.truncated,
3688
+ }
3689
+ } finally {
3690
+ temp.cleanup()
3691
+ }
3692
+ },
3693
+
3472
3694
  async 'docs.pdfPage'(params = {}) {
3473
3695
  const target = await docTarget(params)
3474
3696
  assertDocKind(target.path, 'pdf')
@@ -3803,6 +4025,62 @@ export function apply(ctx) {
3803
4025
  return { path: target, files }
3804
4026
  },
3805
4027
 
4028
+ async 'fs.readOutside'(params = {}) {
4029
+ const { scope, target } = await extraTarget(params, 'readOutside')
4030
+ const stat = await scope.remote.stat(target)
4031
+ if (stat.type === 'dir') throw new ApiError('FS_IS_DIR', '目标是目录,请用 list_outside')
4032
+ const limit = clampInt(params.maxBytes, 1024, READ_CAP, 262144)
4033
+ const read = await scope.remote.readFile(target, { maxBytes: Math.min(stat.size, limit) })
4034
+ const binary = looksBinary(read.data)
4035
+ return {
4036
+ path: target,
4037
+ size: stat.size,
4038
+ mtime: stat.mtime,
4039
+ binary,
4040
+ truncated: read.data.length < stat.size,
4041
+ content: binary ? '' : decodeUtf8(read.data),
4042
+ }
4043
+ },
4044
+
4045
+ async 'fs.writeOutside'(params = {}) {
4046
+ const { scope, target } = await extraTarget(params, 'writeOutside')
4047
+ if (typeof params.content !== 'string') throw new ApiError('BAD_REQUEST', 'content is required')
4048
+ const bytes = Buffer.byteLength(params.content, 'utf8')
4049
+ if (bytes > MAX_WRITE_BYTES) throw new ApiError('FS_TOO_LARGE', '文件超过 8 MB,无法写入')
4050
+ let current
4051
+ try {
4052
+ current = await scope.remote.stat(target)
4053
+ } catch (error) {
4054
+ const apiError = asApiError(error)
4055
+ if (apiError.code !== 'FS_NOT_FOUND') throw apiError
4056
+ current = undefined
4057
+ }
4058
+ if (current && current.type === 'dir') throw new ApiError('FS_IS_DIR', '目标是目录')
4059
+ if (current && typeof params.ifModifiedSince === 'number' && params.ifModifiedSince > 0) {
4060
+ if (Math.floor(current.mtime / 1000) !== Math.floor(params.ifModifiedSince / 1000)) {
4061
+ throw new ApiError('CONFLICT', '文件已被修改,请重新读取后再写入')
4062
+ }
4063
+ }
4064
+ await scope.remote.mkdirp(posix.dirname(target))
4065
+ await scope.remote.writeFileAtomic(target, Buffer.from(params.content, 'utf8'))
4066
+ const after = await scope.remote.stat(target)
4067
+ return { path: target, size: after.size, mtime: after.mtime, created: !current }
4068
+ },
4069
+
4070
+ async 'fs.listOutside'(params = {}) {
4071
+ const { scope, target } = await extraTarget(params, 'listOutside')
4072
+ const listing = await scope.remote.listDir(target)
4073
+ return {
4074
+ path: target,
4075
+ entries: listing.entries.map((entry) => ({
4076
+ name: entry.name,
4077
+ type: entry.type,
4078
+ size: entry.size,
4079
+ mtime: entry.mtime,
4080
+ })),
4081
+ }
4082
+ },
4083
+
3806
4084
  async 'fs.chmod'(params = {}) {
3807
4085
  const scope = await requireScope(params)
3808
4086
  const target = scopeTarget(scope, params.path)
@@ -4695,11 +4973,22 @@ export function apply(ctx) {
4695
4973
  const renamed = nextName !== '' && nextName !== record.name
4696
4974
  record.name = nextName !== '' ? nextName : record.name
4697
4975
  record.mirror = nextMirror
4976
+ const nextAutoPush = params.autoPush !== undefined ? params.autoPush : record.autoPush
4977
+ if (nextAutoPush !== null && typeof nextAutoPush !== 'object') throw new ApiError('BAD_REQUEST', '自动推送设置无效')
4698
4978
  if (nextMirror === false) {
4699
4979
  const running = syncJobs.get(record.id)
4700
4980
  if (running && running.state === 'running') running.cancel = true
4701
4981
  }
4702
- linkedStore.update(record.id, { name: record.name, mirror: record.mirror, syncChoice: true })
4982
+ linkedStore.update(record.id, {
4983
+ name: record.name,
4984
+ mirror: record.mirror,
4985
+ autoPush: nextAutoPush,
4986
+ syncChoice: true,
4987
+ })
4988
+ // The store normalises what we just wrote (debounce clamps, glob cleanup),
4989
+ // so read it back before describing it or arming watchers.
4990
+ const saved = linkedStore.get(record.id) || record
4991
+ if (params.autoPush !== undefined) syncAutoPush()
4703
4992
  if (renamed) {
4704
4993
  const workspace = findWorkspaceByPath(linkedRegistry(), record.localPath)
4705
4994
  if (workspace) await renameDshWorkspace(ctx, String(workspace.id), linkedWorkspaceTitle(record.name))
@@ -4718,7 +5007,7 @@ export function apply(ctx) {
4718
5007
  log('warn', `could not start the first mirror check: ${error && error.message ? error.message : error}`)
4719
5008
  }
4720
5009
  }
4721
- return { link: describeLink(record) }
5010
+ return { link: describeLink(saved) }
4722
5011
  },
4723
5012
 
4724
5013
  async 'linked.remove'(params = {}) {
@@ -5076,10 +5365,10 @@ export function apply(ctx) {
5076
5365
  const linkedTool = {
5077
5366
  name: LINKED_TOOL_NAME,
5078
5367
  timeoutMs: 120_000,
5079
- isConcurrencySafe: (args) => ['list', 'info', 'list_dir', 'read', 'stat'].includes(String((args && args.action) || '').trim()),
5368
+ isConcurrencySafe: (args) => ['list', 'info', 'list_dir', 'read', 'read_doc', 'stat', 'sync_status', 'forwards', 'list_outside'].includes(String((args && args.action) || '').trim()),
5080
5369
  description:
5081
5370
  '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). '
5082
- + 'Actions: list (all linked and remote workspaces), info, list_dir, read, write, replace, stat, mkdir, rename, delete, sync (linked workspaces only), exec (runs one non-interactive command on the remote host; needs the switch and allow-lists). '
5371
+ + 'Actions: list (all linked and remote workspaces), info, list_dir, read, read_doc (extractable text of a PDF/Word/Excel/PowerPoint file — use this instead of a parser), write, replace, stat, mkdir, rename, delete, sync (linked workspaces only) + sync_status, forward/forwards/unforward (localhost TCP tunnels to the host), exec (runs one non-interactive command on the remote host; needs the switch and allow-lists), read_outside/write_outside/list_outside (paths under the configured extra roots, outside the workspace). '
5083
5372
  + '`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. '
5084
5373
  + 'The workspace is resolved from the session working directory; pass `workspace` (id, local path, placeholder path or name) when working elsewhere. '
5085
5374
  + 'Local files of a linked workspace (including .local/ and .remote/) still use the normal read/write/bash tools.',
@@ -5088,8 +5377,8 @@ export function apply(ctx) {
5088
5377
  properties: {
5089
5378
  action: {
5090
5379
  type: 'string',
5091
- enum: ['list', 'info', 'list_dir', 'read', 'write', 'replace', 'stat', 'mkdir', 'rename', 'delete', 'sync', 'exec', 'references'],
5092
- description: 'Operation to perform. sync only applies to a linked workspace with mirroring on. exec needs the remote-execution switch and allow-lists.',
5380
+ enum: ['list', 'info', 'list_dir', 'read', 'read_doc', 'write', 'replace', 'stat', 'mkdir', 'rename', 'delete', 'sync', 'sync_status', 'forward', 'forwards', 'unforward', 'exec', 'references', 'read_outside', 'write_outside', 'list_outside'],
5381
+ description: 'Operation to perform. sync/sync_status only apply to a linked workspace with mirroring on. exec needs the remote-execution switch and allow-lists. read_doc extracts text from PDF/Word/Excel/PowerPoint. read_outside/write_outside/list_outside work under the configured extra roots only.',
5093
5382
  },
5094
5383
  workspace: {
5095
5384
  type: 'string',
@@ -5111,6 +5400,11 @@ export function apply(ctx) {
5111
5400
  timeout_ms: { type: 'number', description: 'exec timeout in milliseconds (default from settings, max 600000).' },
5112
5401
  query: { type: 'string', description: 'Search text for references (matches the path, case-insensitive; ≤ 200 characters).' },
5113
5402
  limit: { type: 'number', description: 'How many candidates references returns (default 50, max 200).' },
5403
+ max_chars: { type: 'number', description: 'Character cap for read_doc (default 40000, max 200000).' },
5404
+ remote_port: { type: 'number', description: 'Remote TCP port to forward to (forward).' },
5405
+ remote_host: { type: 'string', description: 'Remote host to forward to (default 127.0.0.1).' },
5406
+ local_port: { type: 'number', description: 'Local port to listen on (default: pick a free one).' },
5407
+ forward_id: { type: 'string', description: 'Id returned by forward, for unforward.' },
5114
5408
  },
5115
5409
  required: ['action'],
5116
5410
  },
@@ -5178,6 +5472,7 @@ export function apply(ctx) {
5178
5472
  workspaceId: link.workspaceId || null,
5179
5473
  mirror: false,
5180
5474
  remoteRootType: stat.type,
5475
+ placeholderNote: 'The session working directory is an empty local placeholder: host tools (read/grep/glob) will not see remote files. Always use this tool.',
5181
5476
  }, null, 2))
5182
5477
  }
5183
5478
  return toolText(JSON.stringify({
@@ -5191,6 +5486,9 @@ export function apply(ctx) {
5191
5486
  mirrorDir: link.mirror ? join(link.localPath, linkedFs.MIRROR_DIR) : null,
5192
5487
  stateDir: join(link.localPath, linkedFs.LINKED_DIR),
5193
5488
  remoteRootType: stat.type,
5489
+ mirrorNote: link.mirror
5490
+ ? `\`${linkedFs.MIRROR_DIR}/\` here is the local mirror of this linked workspace's remote tree, not another workspace's placeholder. Read it when you want a local copy; do not edit it by hand — use action "sync" or the push actions to write remote changes.`
5491
+ : 'Mirroring is off for this workspace: there is no local copy of the remote tree. Use action "read" / "list_dir" to inspect it.',
5194
5492
  }, null, 2))
5195
5493
  }
5196
5494
 
@@ -5210,7 +5508,7 @@ export function apply(ctx) {
5210
5508
  const cap = Math.min(Math.max(Number(args.max_bytes) || 262144, 1024), LINKED_READ_CAP)
5211
5509
  const read = await remote.readFile(target, { maxBytes: Math.min(stat.size, cap) })
5212
5510
  if (looksBinary(read.data)) {
5213
- return toolText(`${target} (${stat.size} B, mtime ${stat.mtime}) is a binary file; use list_dir/stat or download it locally.`)
5511
+ return toolText(`${target} (${stat.size} B, mtime ${stat.mtime}) is a binary file. Use action "read_doc" for PDF/Word/Excel/PowerPoint text; otherwise open it in the app to download it locally.`)
5214
5512
  }
5215
5513
  const content = decodeUtf8(read.data)
5216
5514
  const truncated = read.data.length < stat.size
@@ -5221,6 +5519,20 @@ export function apply(ctx) {
5221
5519
  return toolText(`${target} (${stat.size} B, mtime ${stat.mtime})${suffix}\n\n${content}`)
5222
5520
  }
5223
5521
 
5522
+ if (action === 'read_doc') {
5523
+ const request = { path: target, maxChars: args.max_chars }
5524
+ if (remoteKind) request.remoteId = link.id
5525
+ else request.linkedId = link.id
5526
+ const doc = await methods['docs.text'](request)
5527
+ const head = [
5528
+ `${target} (${doc.kind}, ${doc.size === null ? '?' : doc.size} B`,
5529
+ doc.pageCount ? `, ${doc.pageCount} page(s)` : '',
5530
+ doc.truncated ? ', text truncated' : '',
5531
+ ')',
5532
+ ].join('')
5533
+ return toolText(`${head}\n\n${doc.text === '' ? '(no extractable text)' : doc.text}`)
5534
+ }
5535
+
5224
5536
  if (action === 'stat') {
5225
5537
  const stat = await remote.stat(target)
5226
5538
  return toolText(JSON.stringify({ path: target, type: stat.type, size: stat.size, mtime: stat.mtime }, null, 2))
@@ -5305,10 +5617,75 @@ export function apply(ctx) {
5305
5617
  const job = startSyncJob(link, args)
5306
5618
  return toolText(
5307
5619
  `Sync job running in the background: ${job.files} file(s) / ${job.bytes} bytes archived so far (${job.skipped} skipped). `
5308
- + 'The Connections settings card shows progress; poll linked.syncStatus there or wait for completion.',
5620
+ + 'Call action "sync_status" to follow it; the Connections settings card shows the same numbers.',
5309
5621
  )
5310
5622
  }
5311
5623
 
5624
+ if (action === 'sync_status') {
5625
+ if (remoteKind) throw new ApiError('BAD_REQUEST', '远程工作区没有本地副本,也没有 sync 作业')
5626
+ const job = methods['linked.syncStatus'] ? await methods['linked.syncStatus']({ id: link.id }) : { job: null }
5627
+ const current = job && job.job
5628
+ if (!current) return toolText('No sync job has run for this workspace yet.')
5629
+ const line = [
5630
+ `state: ${current.state}`,
5631
+ `archived: ${current.files} file(s) / ${current.bytes} bytes`,
5632
+ `checked: ${current.checked || 0}`,
5633
+ `skipped: ${current.skipped}`,
5634
+ `removed: ${current.removed}`,
5635
+ current.truncated ? 'truncated: yes' : '',
5636
+ current.reason ? `reason: ${current.reason}` : '',
5637
+ current.error ? `error: ${current.error}` : '',
5638
+ current.finishedAt ? `finishedAt: ${new Date(current.finishedAt).toISOString()}` : '',
5639
+ ].filter(Boolean).join('\n')
5640
+ return toolText(line)
5641
+ }
5642
+
5643
+ if (action === 'read_outside' || action === 'write_outside' || action === 'list_outside') {
5644
+ const request = { path: target }
5645
+ if (remoteKind) request.remoteId = link.id
5646
+ else request.linkedId = link.id
5647
+ if (action === 'read_outside') {
5648
+ const file = await methods['fs.readOutside']({ ...request, maxBytes: args.max_bytes })
5649
+ if (file.binary) return toolText(`${file.path} (${file.size} B) is binary; only metadata is available.`)
5650
+ const suffix = file.truncated ? `\n...(truncated at ${file.content.length} of ${file.size} bytes)` : ''
5651
+ return toolText(`${file.path} (${file.size} B, mtime ${file.mtime})${suffix}\n\n${file.content}`)
5652
+ }
5653
+ if (action === 'write_outside') {
5654
+ const written = await methods['fs.writeOutside']({
5655
+ ...request,
5656
+ content: args.content,
5657
+ ifModifiedSince: args.if_modified_since,
5658
+ })
5659
+ return toolText(`${written.created ? 'Created' : 'Overwrote'} ${written.path} (${written.size} B)`)
5660
+ }
5661
+ const listing = await methods['fs.listOutside'](request)
5662
+ const rows = listing.entries.map((entry) => (entry.type === 'dir'
5663
+ ? `d ${entry.name}/`
5664
+ : `f ${entry.name} (${entry.size} B)`))
5665
+ return toolText(`${listing.path}\n${rows.length === 0 ? '(empty)' : rows.join('\n')}`)
5666
+ }
5667
+
5668
+ if (action === 'forwards') {
5669
+ const { forwards } = await methods['hosts.forwards']()
5670
+ if (forwards.length === 0) return toolText('No port forwards are open.')
5671
+ return toolText(forwards.map((item) => `${item.id} 127.0.0.1:${item.localPort} -> ${item.hostName}:${item.remoteHost}:${item.remotePort} ${item.url}`).join('\n'))
5672
+ }
5673
+
5674
+ if (action === 'forward') {
5675
+ const { forward } = await methods['hosts.forward']({
5676
+ hostId: link.hostId,
5677
+ remotePort: args.remote_port,
5678
+ remoteHost: args.remote_host,
5679
+ localPort: args.local_port,
5680
+ })
5681
+ return toolText(`Tunnel open: ${forward.url} -> ${forward.hostName}:${forward.remoteHost}:${forward.remotePort} (id ${forward.id}). Open that URL to view it; close it with action "unforward".`)
5682
+ }
5683
+
5684
+ if (action === 'unforward') {
5685
+ const result = await methods['hosts.unforward']({ id: args.forward_id })
5686
+ return toolText(result.removed ? `Closed tunnel ${args.forward_id}.` : `No tunnel with id ${args.forward_id}.`)
5687
+ }
5688
+
5312
5689
  if (action === 'exec') {
5313
5690
  const command = String((args && args.command) || '')
5314
5691
  if (command.trim() === '') throw new ApiError('BAD_REQUEST', 'command is required for exec')
@@ -5512,6 +5889,12 @@ export function apply(ctx) {
5512
5889
  ctx.effect(() => () => {
5513
5890
  for (const id of [...autoPushWatchers.keys()]) stopAutoPush(id)
5514
5891
  }, 'dsh-linked-workspace: auto push watchers')
5892
+ ctx.effect(() => () => {
5893
+ for (const record of forwardServers.values()) {
5894
+ try { record.server.close() } catch { /* already closed */ }
5895
+ }
5896
+ forwardServers.clear()
5897
+ }, 'dsh-linked-workspace: port forwards')
5515
5898
  }
5516
5899
 
5517
5900
  // ── response helpers ────────────────────────────────────────────────────────