dsh-linked-workspace 0.21.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,21 @@
2
2
 
3
3
  English · [简体中文](CHANGELOG.zh.md)
4
4
 
5
+ ## 0.23.0 — 2026-11-21
6
+
7
+ - Models can read the **text of PDF / Word / Excel / PowerPoint** files: new `read_doc` action and `docs.text` method (PDF page by page, Word paragraphs and tables, one block per Excel sheet, PPT slides plus notes, 40k characters by default). No more installing PyPDF2 to read one paper.
8
+ - `sync` is now observable: new `sync_status` action. The prompt used to tell models to poll `linked.syncStatus` while the action list never had it.
9
+ - Port forwards: `forward` / `forwards` / `unforward` actions plus a "Port forwards" settings block that maps a remote TensorBoard or Jupyter onto a local `127.0.0.1` port; tunnels are closed when the plugin unloads.
10
+ - Paths outside the workspace have a supported route: the "Extra roots" setting plus `read_outside` / `write_outside` / `list_outside`. Every access is appended to `outside-audit.jsonl`, and paths that match no prefix still fail hard with a hint pointing at the setting.
11
+ - `info` now spells out the two easiest things to misread: in a linked workspace `.remote/` is that workspace's own mirror (not another workspace's placeholder), and inside a remote workspace's placeholder the host tools (read/grep/glob) see no remote files at all.
12
+ - The binary-file hint points at `read_doc` instead of telling models to download the file locally.
13
+
14
+ ## 0.22.0 — 2026-11-20
15
+
16
+ - Workspace cards gained a **Reconnect** button: it drops the pooled socket, dials once and reports either “Reconnected” with the round-trip time or the host's own error message. New host method `hosts.reconnect` — the read-only `hosts.status` snapshot never dials, so a stale “Not connected” chip previously had no way to refresh itself.
17
+ - “Not connected” now has a documented meaning: the process has not dialled that host yet (or the last failure is older than 60 s), which is normal right after DSH starts. The README explains it and points at the new button.
18
+ - Fixed a mirror regression: turning the mirror off and on again handed the **cancelling** sync job back to the next `linked.sync`, which then finished as “cancelled” without pulling anything. A job that is already winding down is no longer reused.
19
+
5
20
  ## 0.21.0 — 2026-11-20
6
21
 
7
22
  - The diff preview is scoped: right-click a folder → “Push this to the remote”, or select files and choose “Push the N selected items to the remote”, and the rows you see are exactly the rows that get pushed (the host matches a folder as a prefix, so the old “shows 5, pushes 0” mismatch is gone).
package/README.en.md CHANGED
@@ -59,6 +59,8 @@ The plugin takes over the DSH sidebar/hero directory-selection hole; the dialog
59
59
  > Linked workspace rows no longer carry a `⇄` title prefix: a scoped stylesheet keyed on `data-row-key` swaps the host folder glyph for the workspace's own icon — two interlocking links for a linked workspace, a display with an outbound arrow for a remote workspace (normal local workspaces are untouched). When the SSH connection drops the row icon turns red, and the host's hover card gains one line under the name combining the SSH host with its live state (`RTX-PRO-6000-1 · Connected`, turning red with “Connection lost” once the link drops); a remote workspace shows the remote directory, a linked one shows both the remote and local directories. This is the only DOM-level adaptation of the host row; if DSH changes the row structure the selector stops matching and the original folder icon returns, with no other breakage.
60
60
  >
61
61
  > That state follows the real connection in both directions: the page asks the host for every host's state once every 6 seconds (memory only, it never dials), and only repaints that one line when the value actually changed — so a host that drops shows “Connection lost” within seconds while the card stays open, and one that recovers goes back to “Connected” without a reload. A single failure only describes that moment: an error nobody has re-checked decays to “Not connected” after 60 seconds, and “Test connection” finding a missing remote directory is no longer treated as a dead link, so it cannot paint the other workspaces on the same host red.
62
+ >
63
+ > That also explains why a workspace reads “Not connected” right after DSH starts: it means “this process has not dialled that host yet”, not “it cannot”. To find out immediately, press **Reconnect** on the card in settings — it drops the old socket, dials once, and either reports “Reconnected” with the round-trip time or shows the host's own error message.
62
64
 
63
65
  ### Sidebar: “Linked Workspace Directory”
64
66
 
@@ -117,6 +119,13 @@ Appears automatically for sessions that belong to a remote workspace (and can be
117
119
 
118
120
  The workspace resolves automatically when the session cwd falls inside a linked workspace or a remote workspace placeholder; use the `workspace` argument (id, local/placeholder path or name) across workspaces. The remote server only needs SSH — no plugin or Python installation.
119
121
 
122
+ ### Documents, tunnels and paths outside the workspace (0.23.0)
123
+
124
+ - Models can read the **text of PDF / Word / Excel / PowerPoint** files directly (`read_doc`) instead of installing a parser.
125
+ - When TensorBoard or Jupyter runs remotely, map it onto a local `127.0.0.1` port under Settings → Linked workspaces → **Port forwards** and open the URL in a browser; tunnels close with the plugin.
126
+ - To touch a shared drive outside the workspace, add the prefix under Settings → Linked workspaces → **Extra roots** first; only then can the model use `read_outside` / `write_outside` / `list_outside`, and every access lands in `outside-audit.jsonl`.
127
+ - `sync_status` reports progress and counters while a mirror sync runs.
128
+
120
129
  ### Remote command execution (0.17.0, off by default)
121
130
 
122
131
  `exec` lets the model run **one non-interactive command** on the remote host (builds, tests, logs) instead of composing `ssh` itself. It is off unless three things line up:
package/README.md CHANGED
@@ -59,6 +59,8 @@
59
59
  > 左侧工作区行不再带 `⇄` 标题前缀:插件用一份按 `data-row-key` 定位的样式表,把宿主文件夹图标换成工作区自己的图标——联动工作区是**双链环**,远程工作区是**显示器 + 出链箭头**,普通本地工作区不受影响。SSH 连接断开时该行的图标会变红;把鼠标停在行上,宿主那张悬停信息卡里名字下面会多出一行「SSH 主机 · 连接状态」(形如 `RTX-PRO-6000-1 · 已连接`,掉线后变红并显示「连接已断开」);远程工作区显示远端目录、联动工作区同时显示远端与本地目录。这是对宿主行结构的唯一 DOM 级适配;如果 DSH 以后更改行结构,选择器会自然失配并回退到原来的文件夹图标,不破坏其他功能。
60
60
  >
61
61
  > 这一行状态是**跟着实际连通性走的**:页面每 6 秒向宿主取一次各主机的连接状态(只读内存、不发起新连接),只有状态真的变了才重绘那一行,卡片开着时也会即时更新——主机掉线几秒内变「连接已断开」,恢复后自动回到「已连接」,不用刷新页面。一次失败只代表当时:没人再验证的旧错误 60 秒后降级为「未连接」;「测试连接」发现远端目录不存在也不会被当成断连,不会把同一台主机上的其它工作区一起标红。
62
+ >
63
+ > 所以刚重启 DSH 时,还没打开过的工作区显示「未连接」是正常的——那是「这个进程还没连过」而不是「连不上」。想立刻确认,点设置页卡片上的**重新连接**:它会丢掉旧连接、当场拨一次号,成功就变「已连接」并显示耗时,失败则把主机的原话显示出来。
62
64
 
63
65
  ### 右侧栏「联动工作区目录」
64
66
 
@@ -116,6 +118,13 @@
116
118
 
117
119
  会话工作目录落在某个联动工作区或远程工作区的占位目录时会自动解析;跨工作区可用 `workspace` 参数指定(支持 id、本地/占位路径或名称)。远端服务器只需要 SSH,不需要安装插件或 Python。
118
120
 
121
+ ### 读文档、开隧道、访问工作区外(0.23.0)
122
+
123
+ - 模型可以直接读 **PDF / Word / Excel / PowerPoint 的文字**(`read_doc`),不用再自己装解析库。
124
+ - 远端跑着 TensorBoard、Jupyter 时,可以在 设置 → 联动工作区 → **端口转发** 里把它映射到本机 `127.0.0.1` 的端口,点 URL 就能在浏览器打开;插件退出时隧道自动关闭。
125
+ - 需要碰工作区之外的共享盘时,先在 设置 → 联动工作区 → **额外根目录** 里加前缀,模型才能用 `read_outside` / `write_outside` / `list_outside` 访问,而且每次访问都会记进 `outside-audit.jsonl`。
126
+ - 镜像同步进行中可以用 `sync_status` 看进度与计数。
127
+
119
128
  ### 远端命令执行(0.17.0,默认关闭)
120
129
 
121
130
  `exec` 让模型在远端跑**一条非交互命令**(编译、跑测试、看日志),不用再自己拼 `ssh`。它默认是关的,要同时满足三件事才会执行:
package/docs/API.md CHANGED
@@ -21,6 +21,7 @@ Codes: `BAD_REQUEST`, `NOT_FOUND`, `SSH_CONNECT`, `AUTH_FAILED`,
21
21
  | Method | Params | Result |
22
22
  | --- | --- | --- |
23
23
  | `docs.read` | `{ path, linkedId?, remoteId? }` | kind-specific document model |
24
+ | `docs.text` | `{ path, linkedId?, remoteId?, maxChars? }` | `{ kind, path, size, mtime, pageCount?, text, truncated }` (plain text out of PDF / Word / Excel / PowerPoint; `maxChars` is clamped to 1000–200000, default 40000) |
24
25
  | `docs.write` | `{ path, data, expectedMtime?, linkedId?, remoteId? }` | `{ kind, path, size, mtime }` |
25
26
  | `docs.create` | `{ path, kind?, linkedId?, remoteId? }` | `{ kind, path, size, mtime }` |
26
27
  | `docs.mdPreview` | `{ path, text?, linkedId?, remoteId? }` | `{ kind, html }` |
@@ -58,6 +59,13 @@ scope root, or absolute inside it.
58
59
  | `hosts.hostKeys` | `{}` | `{ entries: [{ authority, fingerprint, firstSeen, hostId?, hostName? }] }` — the keys remembered in `known_hosts.json`; `hostId` is filled in when the authority still matches a configured host |
59
60
  | `hosts.forgetHostKey` | `{ hostId?/authority? }` | `{ authority, removed }` — drops the stored key (and the live connection) so the next connect trusts the host again; `settings.hostKeyPolicy` decides whether an unknown key is accepted (`tofu`, default) or refused (`strict`) |
60
61
  | `hosts.status` | `{ hostIds? }` | `{ statuses: { [hostId]: { state, reason?, message?, latencyMs?, checkedAt? } } }` (in-memory snapshot of the pool, never dials; an `error` older than 60 s is reported as `idle`; defaults to every known host of the host list plus every workspace's host id) |
62
+ | `fs.readOutside` | `{ linkedId?, remoteId?, path, maxBytes? }` | `{ path, size, mtime, binary, truncated, content }` (only under an `extraRoots` prefix; audited) |
63
+ | `fs.writeOutside` | `{ linkedId?, remoteId?, path, content, ifModifiedSince? }` | `{ path, size, mtime, created }` (8 MB limit; only under an `extraRoots` prefix; audited) |
64
+ | `fs.listOutside` | `{ linkedId?, remoteId?, path }` | `{ path, entries }` (only under an `extraRoots` prefix; audited) |
65
+ | `hosts.forward` | `{ hostId, remotePort, remoteHost?, localPort? }` | `{ forward: { id, hostId, hostName, remoteHost, remotePort, localPort, startedAt, url } }` (localhost TCP tunnel; reuses an identical one) |
66
+ | `hosts.forwards` | `{}` | `{ forwards: [...] }` |
67
+ | `hosts.unforward` | `{ id }` | `{ removed }` |
68
+ | `hosts.reconnect` | `{ hostId }` | `{ hostId, state, reason?, message?, latencyMs?, checkedAt? }` (drops the pooled socket and dials again; returns the resulting status instead of throwing, so the UI can show the reason) |
61
69
  | `hosts.mkdir` | `{ hostId, path?, name }` | `{ path }` (creates `name` inside `path`; defaults to the login home; `409`/`FS_EXISTS` when it already exists) |
62
70
  | `hosts.exec` | `{ hostId?/linkedId?/remoteId?, command, cwd?, timeoutMs? }` | `{ hostId, hostName, workspaceId, kind, command, cwd, exitCode, stdout, stderr, stdoutBytes, stderrBytes, truncated, durationMs, startedAt, auditId }` — runs **one** non-interactive command on the remote host. Three gates: `settings.execEnabled` must be `true`, the host must be in `settings.execHostIds`, and — when `settings.execWorkspaceIds` is non-empty — the workspace must be in it. Refusals are audited too and answer `403` (`EXEC_DISABLED` / `EXEC_HOST_NOT_ALLOWED` / `EXEC_WORKSPACE_NOT_ALLOWED`); a timeout answers `504` `EXEC_TIMEOUT`, other failures `502` `EXEC_FAILED`. Output is clipped to `settings.execMaxOutputChars` per stream (default 200000, head+tail). `cwd` is resolved inside the workspace root and may not escape it. Output is decoded with `settings.outputEncoding` (`utf8` by default, `gbk` for Chinese Windows remotes). |
63
71
  | `remote_workspaces.list` | `{}` | `{ workspaces: RemoteWorkspaceInfo[] }` |
package/docs/VERIFY.md CHANGED
@@ -327,6 +327,17 @@ Host code (lib/) reloads live with `plugin_manager set_plugin include:linked-wor
327
327
  18. 右键工作区根节点:菜单里**没有**「更改权限」(也没有「重命名」「删除」「移动到…」)。绕过界面直接请求 `fs.chmod` 并把 `path` 指向工作区远端根:返回 400「不能修改工作区根目录的权限」,随后 `fs.stat` 的权限保持不变。
328
328
  19. **覆盖层置顶(0.20.1)**:打开「添加工作区」弹窗时,右侧目录树与对话输入框都应变暗且完全在弹窗之下(在输入框位置 `document.elementFromPoint` 应命中遮罩);弹窗宿主是 `document.body` 下 `showModal()` 打开的 `<dialog class="rw-top-layer">`。按 Esc:弹窗消失且 `.rw-top-layer` 数量归 0(不能留下已关闭的 dialog),随后再点「添加工作区」仍能重新打开。
329
329
  20. **其它覆盖层(0.20.1)**:右键「移动到…」等确认对话框与首次运行欢迎卡片同样走 `.rw-top-layer`;Esc、点遮罩、点关闭按钮三种方式都能把宿主一起移除。
330
+ 21. **重新连接(0.22.0)**:刚重启 DSH 后打开设置 →「联动工作区」,卡片状态为「未连接」(这是「本进程还没连过」,不是故障)。点卡片上的**重新连接**:成功时出现绿色「已重新连接」且状态变「已连接」;把某个主机的端口临时改成不可达再点,则应出现红色「连接失败:…」并带上主机的原话(例如 `ECONNREFUSED`)。绕过界面调用 `hosts.reconnect { hostId: '不存在的 id' }` 返回 404。
331
+ 22. **镜像开关不再卡住同步(0.22.0)**:对开启镜像的联动工作区连续执行 `linked.update { mirror: false }` → `linked.update { mirror: true }` → `linked.sync`,轮询 `linked.syncStatus` 应最终为 `done`(不是 `cancelled`)且 `files >= 1`。
332
+ ## 文档文本、端口转发与额外根目录(0.23.0)
333
+
334
+ 1. 让模型读一篇 PDF:`read_doc` 返回按页拼接的文字(含 `pageCount`),不再提示「二进制文件请下载」。
335
+ 2. 读一个 Word / Excel / PowerPoint:分别返回段落与表格、每个工作表的行、每页文字与备注;超出 40000 字符时末尾标 `(truncated)`。
336
+ 3. 触发一次镜像同步后调用 `sync_status`:能看到 `state` 与计数(以前只有提示词提到过这个名字)。
337
+ 4. 设置 → 联动工作区 → 端口转发:填 `127.0.0.1:6006` 开一条隧道,点「打开」能在浏览器看到远端页面;「停止」后隧道从列表消失,端口不可再连。
338
+ 5. 设置 → 联动工作区 → 额外根目录:填入 `/tmp` 后,`write_outside` / `read_outside` / `list_outside` 可以访问 `/tmp` 下的文件,且 `<DSH_HOME>/linked-workspace/outside-audit.jsonl` 每次都有记录;清空前缀后同样的调用返回 400 并提示去哪儿添加。
339
+ 6. 工作区内部的路径用 `*_outside` 访问会被拒绝(400),避免把「额外根目录」当成万能后门。
340
+
330
341
  ## 旧 Host 自检(0.15.0)
331
342
 
332
343
  1. **正常时不打扰**:插件已重启过后打开任意目录树,顶部**不应**出现任何黄色提示条。
package/lib/client.js CHANGED
@@ -2540,6 +2540,10 @@ function attributeViolation(name, value, tagName) {
2540
2540
  autoPushChip: '自动推送',
2541
2541
  autoPushChipTitle: '已开启:本地静止 {{debounce}} ms 后推送',
2542
2542
  autoPushChipLast: '最近一次 {{when}}',
2543
+ reconnect: '重新连接',
2544
+ reconnecting: '正在连接…',
2545
+ reconnectOk: '已重新连接',
2546
+ reconnectFail: '连接失败:{{reason}}',
2543
2547
  autoPushTitle: '自动推回远端',
2544
2548
  autoPushLabel: '开启自动推送',
2545
2549
  autoPushWarn: '开启后,本地目录里保存的文件会在停止编辑约 1.5 秒后自动写回远端;如果同一文件在远端也被改过,会保留远端版本(不覆盖)。',
@@ -2562,6 +2566,21 @@ function attributeViolation(name, value, tagName) {
2562
2566
  forgetHostKey: '忘记',
2563
2567
  forgotHostKey: '已忘记 {{authority}} 的主机密钥',
2564
2568
  sshTrustSaved: 'SSH 设置已保存',
2569
+ extraRootsTitle: '额外根目录',
2570
+ extraRootsHint: '每行一个绝对路径前缀。默认情况下,模型只能在当前工作区内读写;把共享盘之类的前缀加到这里,模型才能用 read_outside / write_outside / list_outside 访问,每次访问都会写进审计日志。',
2571
+ extraRootsPlaceholder: '/shared_data_ssd1/huangjh',
2572
+ extraRootsSaved: '已保存 {{count}} 个前缀',
2573
+ forwardTitle: '端口转发',
2574
+ forwardHint: '把远端服务(TensorBoard、Jupyter 等)映射到本机 127.0.0.1 的端口,开好后点开 URL 就能在浏览器里看。',
2575
+ forwardHostLabel: '主机',
2576
+ forwardRemoteLabel: '远端地址(host:port)',
2577
+ forwardLocalLabel: '本机端口(留空自动分配)',
2578
+ forwardAdd: '开一条隧道',
2579
+ forwardStop: '停止',
2580
+ forwardOpen: '打开',
2581
+ forwardEmpty: '还没有隧道。',
2582
+ forwardAdded: '隧道已开启:{{url}}',
2583
+ forwardStopped: '隧道已停止',
2565
2584
  execTitle: '远端命令执行',
2566
2585
  execHint: '默认关闭。开启后,会话里的模型可以通过 linked_workspace 的 exec 动作在远端跑命令;只对下面勾选的主机/工作区生效,每次尝试(含被拒)都记进审计日志。',
2567
2586
  execEnabledLabel: '允许在远端执行命令',
@@ -3095,6 +3114,10 @@ function attributeViolation(name, value, tagName) {
3095
3114
  autoPushChip: 'auto push',
3096
3115
  autoPushChipTitle: 'on · pushes after {{debounce}} ms of local quiet',
3097
3116
  autoPushChipLast: 'last {{when}}',
3117
+ reconnect: 'Reconnect',
3118
+ reconnecting: 'Connecting…',
3119
+ reconnectOk: 'Reconnected',
3120
+ reconnectFail: 'Could not connect: {{reason}}',
3098
3121
  autoPushTitle: 'Push back automatically',
3099
3122
  autoPushLabel: 'Enable automatic push',
3100
3123
  autoPushWarn: 'Once enabled, files saved locally are written back about 1.5 s after you stop editing. If the same file also changed on the remote side, the remote version is kept (never overwritten).',
@@ -3117,6 +3140,21 @@ function attributeViolation(name, value, tagName) {
3117
3140
  forgetHostKey: 'Forget',
3118
3141
  forgotHostKey: 'Forgot the host key for {{authority}}',
3119
3142
  sshTrustSaved: 'SSH settings saved',
3143
+ extraRootsTitle: 'Extra roots',
3144
+ extraRootsHint: 'One absolute path prefix per line. By default the model can only read and write inside the current workspace; add shared drives here to let it use read_outside / write_outside / list_outside. Every access is written to the audit log.',
3145
+ extraRootsPlaceholder: '/shared_data_ssd1/huangjh',
3146
+ extraRootsSaved: 'Saved {{count}} prefixes',
3147
+ forwardTitle: 'Port forwards',
3148
+ forwardHint: 'Map a remote service (TensorBoard, Jupyter, …) onto a local 127.0.0.1 port and open the URL in a browser.',
3149
+ forwardHostLabel: 'Host',
3150
+ forwardRemoteLabel: 'Remote address (host:port)',
3151
+ forwardLocalLabel: 'Local port (blank picks one)',
3152
+ forwardAdd: 'Open a tunnel',
3153
+ forwardStop: 'Stop',
3154
+ forwardOpen: 'Open',
3155
+ forwardEmpty: 'No tunnels yet.',
3156
+ forwardAdded: 'Tunnel open: {{url}}',
3157
+ forwardStopped: 'Tunnel stopped',
3120
3158
  execTitle: 'Remote command execution',
3121
3159
  execHint: 'Off by default. When on, the model can run commands on the remote host through the linked_workspace "exec" action — only for the hosts and workspaces ticked below, and every attempt (refusals included) is audited.',
3122
3160
  execEnabledLabel: 'Allow running commands remotely',
@@ -3321,7 +3359,7 @@ function attributeViolation(name, value, tagName) {
3321
3359
  * Host methods the running DSH process does not have yet, the directory
3322
3360
  * pane says so instead of surfacing an unrelated error.
3323
3361
  */
3324
- var HOST_API_REVISION = 6;
3362
+ var HOST_API_REVISION = 8;
3325
3363
  var hostInfoProbe = null;
3326
3364
 
3327
3365
  function probeHostInfo() {
@@ -10793,6 +10831,29 @@ function rememberShowHidden(value) {
10793
10831
  });
10794
10832
  }
10795
10833
 
10834
+ /**
10835
+ * Drop this host's socket and dial again. A stale “not connected” chip is
10836
+ * the usual reason to press it: nothing else asks the host for a file, so
10837
+ * the status would otherwise stay idle until some other action dials.
10838
+ */
10839
+ function reconnect() {
10840
+ setLocal(function (previous) { return Object.assign({}, previous, { busy: 'reconnect', message: null }); });
10841
+ apiCall('hosts.reconnect', { hostId: link.hostId }).then(function (status) {
10842
+ var ok = Boolean(status && status.state === 'connected');
10843
+ setLocal(function (previous) {
10844
+ return Object.assign({}, previous, {
10845
+ busy: '',
10846
+ message: ok
10847
+ ? { kind: 'success', text: t('reconnectOk') }
10848
+ : { kind: 'error', text: t('reconnectFail', { reason: (status && status.message) || t('errorState') }) },
10849
+ });
10850
+ });
10851
+ refresh();
10852
+ }).catch(function (error) {
10853
+ setLocal(function (previous) { return Object.assign({}, previous, { busy: '', message: { kind: 'error', text: messageOf(error, t, locale) } }); });
10854
+ });
10855
+ }
10856
+
10796
10857
  function remove() {
10797
10858
  if (!local.removing) {
10798
10859
  setLocal(function (previous) { return Object.assign({}, previous, { removing: true, message: null }); });
@@ -10842,6 +10903,10 @@ function rememberShowHidden(value) {
10842
10903
  local.busy === 'sync'
10843
10904
  ? h('button', { type: 'button', className: 'rw-btn rw-btn-sm rw-btn-ghost', onClick: cancelSync }, t('syncCancel'))
10844
10905
  : null,
10906
+ h('button', {
10907
+ type: 'button', className: 'rw-btn rw-btn-sm rw-btn-ghost', onClick: reconnect,
10908
+ disabled: local.busy !== '', title: t('reconnect'),
10909
+ }, local.busy === 'reconnect' ? Spinner(12) : IconRefresh(12), local.busy === 'reconnect' ? t('reconnecting') : t('reconnect')),
10845
10910
  h('button', { type: 'button', className: 'rw-btn rw-btn-sm rw-btn-ghost', onClick: remove }, IconTrash(12), t('removeLinked')))),
10846
10911
  h('div', { className: 'rw-meta' },
10847
10912
  h('span', { className: 'rw-chip' }, link.mirror ? t('mirrorOn') : t('mirrorOff')),
@@ -10938,6 +11003,29 @@ function rememberShowHidden(value) {
10938
11003
  });
10939
11004
  }
10940
11005
 
11006
+ /**
11007
+ * Drop this host's socket and dial again. A stale “not connected” chip is
11008
+ * the usual reason to press it: nothing else asks the host for a file, so
11009
+ * the status would otherwise stay idle until some other action dials.
11010
+ */
11011
+ function reconnect() {
11012
+ setLocal(function (previous) { return Object.assign({}, previous, { busy: 'reconnect', message: null }); });
11013
+ apiCall('hosts.reconnect', { hostId: workspace.hostId }).then(function (status) {
11014
+ var ok = Boolean(status && status.state === 'connected');
11015
+ setLocal(function (previous) {
11016
+ return Object.assign({}, previous, {
11017
+ busy: '',
11018
+ message: ok
11019
+ ? { kind: 'success', text: t('reconnectOk') }
11020
+ : { kind: 'error', text: t('reconnectFail', { reason: (status && status.message) || t('errorState') }) },
11021
+ });
11022
+ });
11023
+ refresh();
11024
+ }).catch(function (error) {
11025
+ setLocal(function (previous) { return Object.assign({}, previous, { busy: '', message: { kind: 'error', text: messageOf(error, t, locale) } }); });
11026
+ });
11027
+ }
11028
+
10941
11029
  function testConnection() {
10942
11030
  setLocal(function (previous) { return Object.assign({}, previous, { busy: 'test', message: null }); });
10943
11031
  apiCall('remote_workspaces.test', { id: workspace.id }).then(function (result) {
@@ -11011,6 +11099,10 @@ function rememberShowHidden(value) {
11011
11099
  : null,
11012
11100
  h('button', { type: 'button', className: 'rw-btn rw-btn-sm', onClick: openTree }, IconFolderTree(12), t('openTree')),
11013
11101
  h('button', { type: 'button', className: 'rw-btn rw-btn-sm rw-btn-ghost', onClick: testConnection, disabled: local.busy !== '' }, local.busy === 'test' ? Spinner(12) : IconRefresh(12), t('testConnection')),
11102
+ h('button', {
11103
+ type: 'button', className: 'rw-btn rw-btn-sm rw-btn-ghost', onClick: reconnect,
11104
+ disabled: local.busy !== '', title: t('reconnect'),
11105
+ }, local.busy === 'reconnect' ? Spinner(12) : IconSync(12), local.busy === 'reconnect' ? t('reconnecting') : t('reconnect')),
11014
11106
  h('button', { type: 'button', className: 'rw-btn rw-btn-sm rw-btn-ghost', onClick: startRename, disabled: local.busy !== '' }, t('rename')),
11015
11107
  h('button', { type: 'button', className: 'rw-btn rw-btn-sm rw-btn-ghost', onClick: remove, disabled: local.busy === 'remove' }, IconTrash(12), t('removeRemote'))))),
11016
11108
  h('div', { className: 'rw-hint' }, t('remoteSessionHint')),
@@ -11647,6 +11739,196 @@ function rememberShowHidden(value) {
11647
11739
  return h('div', { className: 'rw-group' }, children);
11648
11740
  }
11649
11741
 
11742
+ function ExtraRootsSettingsGroup(props) {
11743
+ var t = props.t;
11744
+ var locale = props.locale;
11745
+ var localState = useState({ loading: true, saving: false, message: null });
11746
+ var local = localState[0];
11747
+ var setLocal = localState[1];
11748
+ var textState = useState('');
11749
+ var text = textState[0];
11750
+ var setText = textState[1];
11751
+
11752
+ useEffect(function () {
11753
+ var alive = true;
11754
+ apiCall('settings.get', {}).then(function (settings) {
11755
+ if (!alive) return;
11756
+ var roots = Array.isArray(settings.extraRoots) ? settings.extraRoots : [];
11757
+ setText(roots.join('\n'));
11758
+ setLocal({ loading: false, saving: false, message: null });
11759
+ }).catch(function () {
11760
+ if (alive) setLocal({ loading: false, saving: false, message: null });
11761
+ });
11762
+ return function () { alive = false; };
11763
+ }, []);
11764
+
11765
+ function save() {
11766
+ var roots = text.split('\n').map(function (line) { return line.trim(); })
11767
+ .filter(function (line) { return line !== ''; });
11768
+ setLocal(function (previous) { return Object.assign({}, previous, { saving: true, message: null }); });
11769
+ apiCall('settings.update', { extraRoots: roots }).then(function (settings) {
11770
+ var saved = Array.isArray(settings.extraRoots) ? settings.extraRoots : roots;
11771
+ setText(saved.join('\n'));
11772
+ setLocal({ loading: false, saving: false, message: { kind: 'success', text: t('extraRootsSaved', { count: String(saved.length) }) } });
11773
+ }).catch(function (error) {
11774
+ setLocal({ loading: false, saving: false, message: { kind: 'error', text: messageOf(error, t, locale) } });
11775
+ });
11776
+ }
11777
+
11778
+ var children = [
11779
+ h('div', { className: 'rw-group-head' },
11780
+ h('span', { className: 'rw-group-title' }, t('extraRootsTitle')),
11781
+ local.saving ? Spinner(12) : null),
11782
+ h('div', { className: 'rw-group-hint' }, t('extraRootsHint')),
11783
+ h('textarea', {
11784
+ className: 'rw-input rw-textarea-mono',
11785
+ style: { marginTop: 10, minHeight: 84, fontFamily: 'var(--dsw-font-mono, monospace)' },
11786
+ spellCheck: false,
11787
+ value: text,
11788
+ placeholder: t('extraRootsPlaceholder'),
11789
+ onChange: function (event) {
11790
+ var next = event.currentTarget.value;
11791
+ setText(next);
11792
+ },
11793
+ onBlur: save,
11794
+ }),
11795
+ ];
11796
+
11797
+ if (local.message) {
11798
+ children.push(h(Banner, {
11799
+ kind: local.message.kind === 'success' ? 'success' : 'error',
11800
+ onClose: function () { setLocal(function (previous) { return Object.assign({}, previous, { message: null }); }); },
11801
+ }, local.message.text));
11802
+ }
11803
+
11804
+ return h('div', { className: 'rw-group' }, children);
11805
+ }
11806
+
11807
+ function ForwardSettingsGroup(props) {
11808
+ var t = props.t;
11809
+ var locale = props.locale;
11810
+ var localState = useState({ busy: false, message: null });
11811
+ var local = localState[0];
11812
+ var setLocal = localState[1];
11813
+ var listState = useState([]);
11814
+ var forwards = listState[0];
11815
+ var setForwards = listState[1];
11816
+ var formState = useState({ hostId: '', remote: '127.0.0.1:6006', localPort: '' });
11817
+ var form = formState[0];
11818
+ var setForm = formState[1];
11819
+ var hosts = props.hosts || [];
11820
+
11821
+ function refresh() {
11822
+ apiCall('hosts.forwards', {}).then(function (result) {
11823
+ setForwards(Array.isArray(result.forwards) ? result.forwards : []);
11824
+ }).catch(function () { setForwards([]); });
11825
+ }
11826
+
11827
+ useEffect(function () {
11828
+ refresh();
11829
+ var timer = setInterval(refresh, 15000);
11830
+ return function () { clearInterval(timer); };
11831
+ }, []);
11832
+
11833
+ useEffect(function () {
11834
+ if (form.hostId === '' && hosts.length > 0) {
11835
+ setForm(function (previous) { return Object.assign({}, previous, { hostId: hosts[0].id }); });
11836
+ }
11837
+ }, [hosts.length]);
11838
+
11839
+ function open() {
11840
+ var text = String(form.remote || '').trim();
11841
+ var cut = text.lastIndexOf(':');
11842
+ var remoteHost = cut > 0 ? text.slice(0, cut) : '127.0.0.1';
11843
+ var remotePort = Number(cut > 0 ? text.slice(cut + 1) : text);
11844
+ if (!remotePort || form.hostId === '') return;
11845
+ var params = { hostId: form.hostId, remoteHost: remoteHost, remotePort: remotePort };
11846
+ var localPort = Number(form.localPort);
11847
+ if (localPort > 0) params.localPort = localPort;
11848
+ setLocal({ busy: true, message: null });
11849
+ apiCall('hosts.forward', params).then(function (result) {
11850
+ setLocal({ busy: false, message: { kind: 'success', text: t('forwardAdded', { url: result.forward.url }) } });
11851
+ refresh();
11852
+ }).catch(function (error) {
11853
+ setLocal({ busy: false, message: { kind: 'error', text: messageOf(error, t, locale) } });
11854
+ });
11855
+ }
11856
+
11857
+ function stop(entry) {
11858
+ setLocal({ busy: true, message: null });
11859
+ apiCall('hosts.unforward', { id: entry.id }).then(function () {
11860
+ setLocal({ busy: false, message: { kind: 'success', text: t('forwardStopped') } });
11861
+ refresh();
11862
+ }).catch(function (error) {
11863
+ setLocal({ busy: false, message: { kind: 'error', text: messageOf(error, t, locale) } });
11864
+ });
11865
+ }
11866
+
11867
+ var children = [
11868
+ h('div', { className: 'rw-group-head' },
11869
+ h('span', { className: 'rw-group-title' }, t('forwardTitle')),
11870
+ local.busy ? Spinner(12) : null),
11871
+ h('div', { className: 'rw-group-hint' }, t('forwardHint')),
11872
+ h('div', { className: 'rw-inline', style: { marginTop: 10, flexWrap: 'wrap', gap: 8 } },
11873
+ h('select', {
11874
+ className: 'rw-input',
11875
+ style: { maxWidth: 220 },
11876
+ value: form.hostId,
11877
+ onChange: function (event) {
11878
+ var next = event.currentTarget.value;
11879
+ setForm(function (previous) { return Object.assign({}, previous, { hostId: next }); });
11880
+ },
11881
+ title: t('forwardHostLabel'),
11882
+ }, hosts.map(function (host) {
11883
+ return h('option', { key: host.id, value: host.id }, host.name || host.id);
11884
+ })),
11885
+ h('input', {
11886
+ className: 'rw-input',
11887
+ style: { width: 190 },
11888
+ value: form.remote,
11889
+ placeholder: t('forwardRemoteLabel'),
11890
+ onChange: function (event) {
11891
+ var next = event.currentTarget.value;
11892
+ setForm(function (previous) { return Object.assign({}, previous, { remote: next }); });
11893
+ },
11894
+ }),
11895
+ h('input', {
11896
+ className: 'rw-input',
11897
+ style: { width: 150 },
11898
+ value: form.localPort,
11899
+ placeholder: t('forwardLocalLabel'),
11900
+ onChange: function (event) {
11901
+ var next = event.currentTarget.value;
11902
+ setForm(function (previous) { return Object.assign({}, previous, { localPort: next }); });
11903
+ },
11904
+ }),
11905
+ h('button', { type: 'button', className: 'rw-btn rw-btn-primary', disabled: local.busy, onClick: open }, t('forwardAdd'))),
11906
+ ];
11907
+
11908
+ if (forwards.length === 0) {
11909
+ children.push(h('div', { className: 'rw-group-hint', style: { marginTop: 10 } }, t('forwardEmpty')));
11910
+ } else {
11911
+ children.push(h('div', { className: 'rw-known-keys', style: { marginTop: 10 } }, forwards.map(function (entry) {
11912
+ return h('div', { className: 'rw-known-key', key: entry.id },
11913
+ h('div', { className: 'rw-known-key-main' },
11914
+ h('span', { className: 'rw-known-key-host' }, entry.hostName + ' → ' + entry.remoteHost + ':' + entry.remotePort),
11915
+ h('span', { className: 'rw-known-key-fp', title: entry.url }, entry.url)),
11916
+ h('div', { className: 'rw-actions' },
11917
+ h('a', { className: 'rw-btn rw-btn-sm', href: entry.url, target: '_blank', rel: 'noreferrer' }, t('forwardOpen')),
11918
+ h('button', { type: 'button', className: 'rw-btn rw-btn-sm', disabled: local.busy, onClick: function () { stop(entry); } }, t('forwardStop'))));
11919
+ })));
11920
+ }
11921
+
11922
+ if (local.message) {
11923
+ children.push(h(Banner, {
11924
+ kind: local.message.kind === 'success' ? 'success' : 'error',
11925
+ onClose: function () { setLocal(function (previous) { return Object.assign({}, previous, { message: null }); }); },
11926
+ }, local.message.text));
11927
+ }
11928
+
11929
+ return h('div', { className: 'rw-group' }, children);
11930
+ }
11931
+
11650
11932
  function ConnectionsPage(props) {
11651
11933
  var ctx = props.ctx;
11652
11934
  var locale = useLocale(ctx);
@@ -11715,6 +11997,8 @@ function rememberShowHidden(value) {
11715
11997
  }),
11716
11998
  h(AutoPushSettingsGroup, { t: t, locale: locale }),
11717
11999
  h(SshTrustSettingsGroup, { t: t, locale: locale }),
12000
+ h(ExtraRootsSettingsGroup, { t: t, locale: locale }),
12001
+ h(ForwardSettingsGroup, { t: t, locale: locale, hosts: hosts }),
11718
12002
  adding === 'linked'
11719
12003
  ? h(AddWorkspaceFlow, {
11720
12004
  ctx: ctx, t: t, locale: locale,
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 = 6
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.
@@ -1437,7 +1456,10 @@ export function apply(ctx) {
1437
1456
  const startSyncJob = (record, options = {}) => {
1438
1457
  if (!record.mirror) throw new ApiError('BAD_REQUEST', '该联动工作区未启用 .remote 存档;请先在设置中打开镜像')
1439
1458
  const running = syncJobs.get(record.id)
1440
- if (running && running.state === 'running') return running
1459
+ // A job that is already winding down must not be handed back: turning the
1460
+ // mirror off and on again used to return the cancelled job, so the next
1461
+ // `linked.sync` reported "cancelled" without pulling anything.
1462
+ if (running && running.state === 'running' && !running.cancel) return running
1441
1463
  const job = {
1442
1464
  id: randomUUID(),
1443
1465
  linkId: record.id,
@@ -1603,6 +1625,10 @@ export function apply(ctx) {
1603
1625
  '- action "list" returns every linked and remote workspace with its local path (or placeholder), SSH host, remote root and mirror state.',
1604
1626
  '- action "info" | "list_dir" | "read" | "write" | "replace" | "stat" | "mkdir" | "rename" | "delete" takes `path` relative to the remote root (or an absolute path inside it).',
1605
1627
  '- Writes are atomic. Pass `if_modified_since` (epoch milliseconds from a previous read/stat) to refuse a stale overwrite.',
1628
+ '- 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.',
1629
+ '- action "sync_status" reports the progress of the last "sync" job (archived/checked/skipped counts).',
1630
+ '- 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.',
1631
+ '- actions "read_outside"/"write_outside"/"list_outside" reach paths outside the workspace root, but only under the extra roots configured in Settings → Linked workspaces.',
1606
1632
  '- action "sync" archives the remote tree into `.remote/` and only exists for a linked workspace (a remote workspace has no local copy).',
1607
1633
  '- 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.',
1608
1634
  '- 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.',
@@ -1656,6 +1682,49 @@ export function apply(ctx) {
1656
1682
  }
1657
1683
  }
1658
1684
 
1685
+ // ── extra roots (paths outside the workspace the user opted into) ──────
1686
+
1687
+ const EXTRA_ROOT_HINT = '路径在工作区之外;如需访问,请先在 设置 → 联动工作区 → 额外根目录 里添加该前缀'
1688
+
1689
+ const extraRoots = () => settingsStore.get().extraRoots || []
1690
+
1691
+ const matchExtraRoot = (target) => {
1692
+ for (const entry of extraRoots()) {
1693
+ const text = String(entry || '').trim()
1694
+ if (text === '' || !text.startsWith('/')) continue
1695
+ const root = posix.resolve(text)
1696
+ if (root === '/' || root === '') continue
1697
+ if (target === root || target.startsWith(root + '/')) return root
1698
+ }
1699
+ return ''
1700
+ }
1701
+
1702
+ const appendExtraAudit = async (entry) => {
1703
+ try {
1704
+ await mkdir(dir, { recursive: true })
1705
+ const line = JSON.stringify({ at: new Date().toISOString(), ...entry }) + '\n'
1706
+ await appendFile(join(dir, 'outside-audit.jsonl'), line, { mode: 0o600 })
1707
+ } catch (error) {
1708
+ log('warn', `outside audit failed: ${error && error.message ? error.message : error}`)
1709
+ }
1710
+ }
1711
+
1712
+ /**
1713
+ * Resolve a path that may live outside the workspace root, but only under one
1714
+ * of the configured extra roots. Every call is appended to
1715
+ * `outside-audit.jsonl` so the user can see what the plugin touched.
1716
+ */
1717
+ const extraTarget = async (params = {}, method = 'fs') => {
1718
+ const scope = await requireScope(params)
1719
+ const text = typeof params.path === 'string' ? params.path.trim() : ''
1720
+ if (text === '') throw new ApiError('BAD_REQUEST', '路径不能为空')
1721
+ const target = text.startsWith('/') ? posix.resolve(text) : posix.resolve(scope.root, text)
1722
+ const root = matchExtraRoot(target)
1723
+ if (root === '') throw new ApiError('BAD_REQUEST', EXTRA_ROOT_HINT)
1724
+ await appendExtraAudit({ method, target, root, workspace: scope.id, kind: scope.kind })
1725
+ return { scope, root, target }
1726
+ }
1727
+
1659
1728
  // ── context-menu / transfer helpers ─────────────────────────────────────
1660
1729
 
1661
1730
  const CONTEXT_TREE_LIMITS = { maxFiles: 150, maxBytes: 15 * 1024 * 1024, maxDepth: 12 }
@@ -2461,6 +2530,39 @@ export function apply(ctx) {
2461
2530
  })
2462
2531
  }
2463
2532
 
2533
+ /** Flatten the tool's structured output into plain text for the model. */
2534
+ function flattenDocText(kind, data, maxChars) {
2535
+ const chunks = []
2536
+ if (kind === 'pdf') {
2537
+ for (const page of data.pages || []) {
2538
+ chunks.push(`=== page ${page.index + 1} ===\n${String(page.text || '').trimEnd()}`)
2539
+ }
2540
+ } else if (kind === 'docx') {
2541
+ const body = (data.paragraphs || []).join('\n')
2542
+ if (body.trim() !== '') chunks.push(body)
2543
+ ;(data.tables || []).forEach((rows, index) => {
2544
+ const lines = (rows || []).map((row) => row.join('\t'))
2545
+ chunks.push(`=== table ${index + 1} ===\n${lines.join('\n')}`)
2546
+ })
2547
+ } else if (kind === 'xlsx') {
2548
+ for (const sheet of data.sheets || []) {
2549
+ const lines = (sheet.rows || []).map((row) => row.join('\t'))
2550
+ chunks.push(`=== sheet ${sheet.name} ===\n${lines.join('\n')}`)
2551
+ }
2552
+ } else if (kind === 'pptx') {
2553
+ for (const slide of data.slides || []) {
2554
+ const body = (slide.texts || []).join('\n')
2555
+ const notes = slide.notes && String(slide.notes).trim() !== '' ? `\n[notes] ${String(slide.notes).trim()}` : ''
2556
+ chunks.push(`=== slide ${slide.index + 1} ===\n${body}${notes}`)
2557
+ }
2558
+ }
2559
+ let text = chunks.filter((chunk) => chunk.trim() !== '').join('\n\n')
2560
+ const limit = clampInt(maxChars, 1000, 200000, 40000)
2561
+ const truncated = text.length > limit
2562
+ if (truncated) text = text.slice(0, limit) + '\n…(truncated)'
2563
+ return { text, truncated, limit }
2564
+ }
2565
+
2464
2566
  async function docTarget(params) {
2465
2567
  if (params.linkedId || params.remoteId || params.workspaceId) {
2466
2568
  const scope = await requireScope(params)
@@ -3011,6 +3113,33 @@ export function apply(ctx) {
3011
3113
  return { statuses }
3012
3114
  },
3013
3115
 
3116
+ /**
3117
+ * Drop whatever socket we hold for this host and dial again.
3118
+ *
3119
+ * `hosts.status` never dials, so a host whose status went stale (a slept
3120
+ * laptop, a server that came back) keeps reporting "not connected" until
3121
+ * something asks for a file. This is the explicit escape hatch: it returns
3122
+ * the resulting status instead of throwing, so the caller can show the real
3123
+ * reason in the card.
3124
+ */
3125
+ async 'hosts.reconnect'(params = {}) {
3126
+ const host = await findHost(params.hostId)
3127
+ const live = pool.connection(host.id)
3128
+ if (live) {
3129
+ pool.connections.delete(host.id)
3130
+ live.dispose().catch(() => {})
3131
+ }
3132
+ const startedAt = Date.now()
3133
+ try {
3134
+ await pool.remote(host)
3135
+ pool.setStatus(host.id, { state: 'connected', latencyMs: Date.now() - startedAt })
3136
+ } catch (error) {
3137
+ const message = error && error.message ? String(error.message) : String(error)
3138
+ pool.setStatus(host.id, { state: 'error', reason: 'connect', message })
3139
+ }
3140
+ return { hostId: host.id, ...hostStatusView(host.id) }
3141
+ },
3142
+
3014
3143
  /**
3015
3144
  * Store a credential for one SSH host on this machine.
3016
3145
  *
@@ -3098,6 +3227,63 @@ export function apply(ctx) {
3098
3227
  * Every remembered host key, so a changed one can be forgotten in the UI
3099
3228
  * instead of hand-editing `known_hosts.json` (0.20.0).
3100
3229
  */
3230
+ async 'hosts.forward'(params = {}) {
3231
+ const host = await findHost(params.hostId)
3232
+ const remotePort = clampInt(params.remotePort, 1, 65535, 0)
3233
+ if (remotePort === 0) throw new ApiError('BAD_REQUEST', 'remotePort 必须是 1–65535')
3234
+ const remoteHost = typeof params.remoteHost === 'string' && params.remoteHost.trim() !== ''
3235
+ ? params.remoteHost.trim()
3236
+ : '127.0.0.1'
3237
+ const wantedPort = clampInt(params.localPort, 1, 65535, 0)
3238
+ const existing = [...forwardServers.values()].find((item) => item.hostId === host.id
3239
+ && item.remotePort === remotePort && item.remoteHost === remoteHost)
3240
+ if (existing) return { forward: forwardView(existing) }
3241
+ const remote = await pool.remote(host)
3242
+ const id = randomUUID()
3243
+ const server = net.createServer((socket) => {
3244
+ remote.forwardOut(remoteHost, remotePort).then((channel) => {
3245
+ socket.pipe(channel).pipe(socket)
3246
+ channel.on('error', () => socket.destroy())
3247
+ socket.on('error', () => channel.destroy())
3248
+ }).catch((error) => {
3249
+ log('warn', `forward ${id} failed: ${error && error.message ? error.message : error}`)
3250
+ socket.destroy()
3251
+ })
3252
+ })
3253
+ await new Promise((resolvePromise, rejectPromise) => {
3254
+ server.once('error', rejectPromise)
3255
+ server.listen(wantedPort, '127.0.0.1', () => resolvePromise())
3256
+ }).catch((error) => {
3257
+ throw new ApiError('FORWARD_FAILED', `无法监听本地端口:${error && error.message ? error.message : error}`)
3258
+ })
3259
+ const record = {
3260
+ id,
3261
+ hostId: host.id,
3262
+ hostName: host.name || host.id,
3263
+ remoteHost,
3264
+ remotePort,
3265
+ localPort: server.address().port,
3266
+ startedAt: Date.now(),
3267
+ server,
3268
+ remote,
3269
+ }
3270
+ forwardServers.set(id, record)
3271
+ return { forward: forwardView(record) }
3272
+ },
3273
+
3274
+ async 'hosts.forwards'() {
3275
+ return { forwards: [...forwardServers.values()].map(forwardView) }
3276
+ },
3277
+
3278
+ async 'hosts.unforward'(params = {}) {
3279
+ const id = typeof params.id === 'string' ? params.id.trim() : ''
3280
+ const record = forwardServers.get(id)
3281
+ if (!record) return { removed: false }
3282
+ try { record.server.close() } catch { /* already closed */ }
3283
+ forwardServers.delete(id)
3284
+ return { removed: true }
3285
+ },
3286
+
3101
3287
  async 'hosts.hostKeys'() {
3102
3288
  const entries = await listKnownHosts(join(dir, 'known_hosts.json'))
3103
3289
  let hosts = []
@@ -3439,6 +3625,61 @@ export function apply(ctx) {
3439
3625
  }
3440
3626
  },
3441
3627
 
3628
+ /**
3629
+ * Plain text of a document, for the model rather than the viewer.
3630
+ * `docs.read` returns page images so the panel can render them; this returns
3631
+ * extractable text so an agent can actually read a PDF, Word, Excel or
3632
+ * PowerPoint file instead of installing a parser of its own.
3633
+ */
3634
+ async 'docs.text'(params = {}) {
3635
+ const target = await docTarget(params)
3636
+ const kind = assertDocKind(target.path)
3637
+ const limit = clampInt(params.maxChars, 1000, 200000, 40000)
3638
+ const stat = await docStat(target)
3639
+ if (kind === 'markdown') {
3640
+ const current = await readDocBytes(target, target)
3641
+ if (looksBinary(current.data)) throw new ApiError('DOC_BINARY', 'Markdown 文件包含二进制内容')
3642
+ const raw = decodeUtf8(current.data)
3643
+ const truncated = raw.length > limit
3644
+ return {
3645
+ kind,
3646
+ path: target.path,
3647
+ size: current.size,
3648
+ mtime: current.mtime,
3649
+ pageCount: null,
3650
+ text: truncated ? raw.slice(0, limit) + '\n…(truncated)' : raw,
3651
+ truncated,
3652
+ }
3653
+ }
3654
+ const temp = await makeDocTemp()
3655
+ try {
3656
+ let input
3657
+ if (kind === 'pdf') {
3658
+ input = (await ensureDocCache(target)).file
3659
+ } else {
3660
+ const current = await readDocBytes(target, target)
3661
+ input = temp.file('input.' + kind)
3662
+ writeFileSync(input, current.data)
3663
+ }
3664
+ const data = await runDocTool(['read-text', '--kind', kind, '--file', input], 180000)
3665
+ const flat = flattenDocText(kind, data, limit)
3666
+ const pageCount = kind === 'pdf'
3667
+ ? (data.pageCount || 0)
3668
+ : kind === 'pptx' ? (data.slides || []).length : kind === 'xlsx' ? (data.sheets || []).length : null
3669
+ return {
3670
+ kind,
3671
+ path: target.path,
3672
+ size: stat ? stat.size : null,
3673
+ mtime: stat ? stat.mtime : null,
3674
+ pageCount,
3675
+ text: flat.text,
3676
+ truncated: flat.truncated,
3677
+ }
3678
+ } finally {
3679
+ temp.cleanup()
3680
+ }
3681
+ },
3682
+
3442
3683
  async 'docs.pdfPage'(params = {}) {
3443
3684
  const target = await docTarget(params)
3444
3685
  assertDocKind(target.path, 'pdf')
@@ -3773,6 +4014,62 @@ export function apply(ctx) {
3773
4014
  return { path: target, files }
3774
4015
  },
3775
4016
 
4017
+ async 'fs.readOutside'(params = {}) {
4018
+ const { scope, target } = await extraTarget(params, 'readOutside')
4019
+ const stat = await scope.remote.stat(target)
4020
+ if (stat.type === 'dir') throw new ApiError('FS_IS_DIR', '目标是目录,请用 list_outside')
4021
+ const limit = clampInt(params.maxBytes, 1024, READ_CAP, 262144)
4022
+ const read = await scope.remote.readFile(target, { maxBytes: Math.min(stat.size, limit) })
4023
+ const binary = looksBinary(read.data)
4024
+ return {
4025
+ path: target,
4026
+ size: stat.size,
4027
+ mtime: stat.mtime,
4028
+ binary,
4029
+ truncated: read.data.length < stat.size,
4030
+ content: binary ? '' : decodeUtf8(read.data),
4031
+ }
4032
+ },
4033
+
4034
+ async 'fs.writeOutside'(params = {}) {
4035
+ const { scope, target } = await extraTarget(params, 'writeOutside')
4036
+ if (typeof params.content !== 'string') throw new ApiError('BAD_REQUEST', 'content is required')
4037
+ const bytes = Buffer.byteLength(params.content, 'utf8')
4038
+ if (bytes > MAX_WRITE_BYTES) throw new ApiError('FS_TOO_LARGE', '文件超过 8 MB,无法写入')
4039
+ let current
4040
+ try {
4041
+ current = await scope.remote.stat(target)
4042
+ } catch (error) {
4043
+ const apiError = asApiError(error)
4044
+ if (apiError.code !== 'FS_NOT_FOUND') throw apiError
4045
+ current = undefined
4046
+ }
4047
+ if (current && current.type === 'dir') throw new ApiError('FS_IS_DIR', '目标是目录')
4048
+ if (current && typeof params.ifModifiedSince === 'number' && params.ifModifiedSince > 0) {
4049
+ if (Math.floor(current.mtime / 1000) !== Math.floor(params.ifModifiedSince / 1000)) {
4050
+ throw new ApiError('CONFLICT', '文件已被修改,请重新读取后再写入')
4051
+ }
4052
+ }
4053
+ await scope.remote.mkdirp(posix.dirname(target))
4054
+ await scope.remote.writeFileAtomic(target, Buffer.from(params.content, 'utf8'))
4055
+ const after = await scope.remote.stat(target)
4056
+ return { path: target, size: after.size, mtime: after.mtime, created: !current }
4057
+ },
4058
+
4059
+ async 'fs.listOutside'(params = {}) {
4060
+ const { scope, target } = await extraTarget(params, 'listOutside')
4061
+ const listing = await scope.remote.listDir(target)
4062
+ return {
4063
+ path: target,
4064
+ entries: listing.entries.map((entry) => ({
4065
+ name: entry.name,
4066
+ type: entry.type,
4067
+ size: entry.size,
4068
+ mtime: entry.mtime,
4069
+ })),
4070
+ }
4071
+ },
4072
+
3776
4073
  async 'fs.chmod'(params = {}) {
3777
4074
  const scope = await requireScope(params)
3778
4075
  const target = scopeTarget(scope, params.path)
@@ -5046,10 +5343,10 @@ export function apply(ctx) {
5046
5343
  const linkedTool = {
5047
5344
  name: LINKED_TOOL_NAME,
5048
5345
  timeoutMs: 120_000,
5049
- isConcurrencySafe: (args) => ['list', 'info', 'list_dir', 'read', 'stat'].includes(String((args && args.action) || '').trim()),
5346
+ isConcurrencySafe: (args) => ['list', 'info', 'list_dir', 'read', 'read_doc', 'stat', 'sync_status', 'forwards', 'list_outside'].includes(String((args && args.action) || '').trim()),
5050
5347
  description:
5051
5348
  '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). '
5052
- + '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). '
5349
+ + '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). '
5053
5350
  + '`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. '
5054
5351
  + 'The workspace is resolved from the session working directory; pass `workspace` (id, local path, placeholder path or name) when working elsewhere. '
5055
5352
  + 'Local files of a linked workspace (including .local/ and .remote/) still use the normal read/write/bash tools.',
@@ -5058,8 +5355,8 @@ export function apply(ctx) {
5058
5355
  properties: {
5059
5356
  action: {
5060
5357
  type: 'string',
5061
- enum: ['list', 'info', 'list_dir', 'read', 'write', 'replace', 'stat', 'mkdir', 'rename', 'delete', 'sync', 'exec', 'references'],
5062
- description: 'Operation to perform. sync only applies to a linked workspace with mirroring on. exec needs the remote-execution switch and allow-lists.',
5358
+ 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'],
5359
+ 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.',
5063
5360
  },
5064
5361
  workspace: {
5065
5362
  type: 'string',
@@ -5081,6 +5378,11 @@ export function apply(ctx) {
5081
5378
  timeout_ms: { type: 'number', description: 'exec timeout in milliseconds (default from settings, max 600000).' },
5082
5379
  query: { type: 'string', description: 'Search text for references (matches the path, case-insensitive; ≤ 200 characters).' },
5083
5380
  limit: { type: 'number', description: 'How many candidates references returns (default 50, max 200).' },
5381
+ max_chars: { type: 'number', description: 'Character cap for read_doc (default 40000, max 200000).' },
5382
+ remote_port: { type: 'number', description: 'Remote TCP port to forward to (forward).' },
5383
+ remote_host: { type: 'string', description: 'Remote host to forward to (default 127.0.0.1).' },
5384
+ local_port: { type: 'number', description: 'Local port to listen on (default: pick a free one).' },
5385
+ forward_id: { type: 'string', description: 'Id returned by forward, for unforward.' },
5084
5386
  },
5085
5387
  required: ['action'],
5086
5388
  },
@@ -5148,6 +5450,7 @@ export function apply(ctx) {
5148
5450
  workspaceId: link.workspaceId || null,
5149
5451
  mirror: false,
5150
5452
  remoteRootType: stat.type,
5453
+ placeholderNote: 'The session working directory is an empty local placeholder: host tools (read/grep/glob) will not see remote files. Always use this tool.',
5151
5454
  }, null, 2))
5152
5455
  }
5153
5456
  return toolText(JSON.stringify({
@@ -5161,6 +5464,9 @@ export function apply(ctx) {
5161
5464
  mirrorDir: link.mirror ? join(link.localPath, linkedFs.MIRROR_DIR) : null,
5162
5465
  stateDir: join(link.localPath, linkedFs.LINKED_DIR),
5163
5466
  remoteRootType: stat.type,
5467
+ mirrorNote: link.mirror
5468
+ ? `\`${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.`
5469
+ : 'Mirroring is off for this workspace: there is no local copy of the remote tree. Use action "read" / "list_dir" to inspect it.',
5164
5470
  }, null, 2))
5165
5471
  }
5166
5472
 
@@ -5180,7 +5486,7 @@ export function apply(ctx) {
5180
5486
  const cap = Math.min(Math.max(Number(args.max_bytes) || 262144, 1024), LINKED_READ_CAP)
5181
5487
  const read = await remote.readFile(target, { maxBytes: Math.min(stat.size, cap) })
5182
5488
  if (looksBinary(read.data)) {
5183
- return toolText(`${target} (${stat.size} B, mtime ${stat.mtime}) is a binary file; use list_dir/stat or download it locally.`)
5489
+ 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.`)
5184
5490
  }
5185
5491
  const content = decodeUtf8(read.data)
5186
5492
  const truncated = read.data.length < stat.size
@@ -5191,6 +5497,20 @@ export function apply(ctx) {
5191
5497
  return toolText(`${target} (${stat.size} B, mtime ${stat.mtime})${suffix}\n\n${content}`)
5192
5498
  }
5193
5499
 
5500
+ if (action === 'read_doc') {
5501
+ const request = { path: target, maxChars: args.max_chars }
5502
+ if (remoteKind) request.remoteId = link.id
5503
+ else request.linkedId = link.id
5504
+ const doc = await methods['docs.text'](request)
5505
+ const head = [
5506
+ `${target} (${doc.kind}, ${doc.size === null ? '?' : doc.size} B`,
5507
+ doc.pageCount ? `, ${doc.pageCount} page(s)` : '',
5508
+ doc.truncated ? ', text truncated' : '',
5509
+ ')',
5510
+ ].join('')
5511
+ return toolText(`${head}\n\n${doc.text === '' ? '(no extractable text)' : doc.text}`)
5512
+ }
5513
+
5194
5514
  if (action === 'stat') {
5195
5515
  const stat = await remote.stat(target)
5196
5516
  return toolText(JSON.stringify({ path: target, type: stat.type, size: stat.size, mtime: stat.mtime }, null, 2))
@@ -5275,10 +5595,75 @@ export function apply(ctx) {
5275
5595
  const job = startSyncJob(link, args)
5276
5596
  return toolText(
5277
5597
  `Sync job running in the background: ${job.files} file(s) / ${job.bytes} bytes archived so far (${job.skipped} skipped). `
5278
- + 'The Connections settings card shows progress; poll linked.syncStatus there or wait for completion.',
5598
+ + 'Call action "sync_status" to follow it; the Connections settings card shows the same numbers.',
5279
5599
  )
5280
5600
  }
5281
5601
 
5602
+ if (action === 'sync_status') {
5603
+ if (remoteKind) throw new ApiError('BAD_REQUEST', '远程工作区没有本地副本,也没有 sync 作业')
5604
+ const job = methods['linked.syncStatus'] ? await methods['linked.syncStatus']({ id: link.id }) : { job: null }
5605
+ const current = job && job.job
5606
+ if (!current) return toolText('No sync job has run for this workspace yet.')
5607
+ const line = [
5608
+ `state: ${current.state}`,
5609
+ `archived: ${current.files} file(s) / ${current.bytes} bytes`,
5610
+ `checked: ${current.checked || 0}`,
5611
+ `skipped: ${current.skipped}`,
5612
+ `removed: ${current.removed}`,
5613
+ current.truncated ? 'truncated: yes' : '',
5614
+ current.reason ? `reason: ${current.reason}` : '',
5615
+ current.error ? `error: ${current.error}` : '',
5616
+ current.finishedAt ? `finishedAt: ${new Date(current.finishedAt).toISOString()}` : '',
5617
+ ].filter(Boolean).join('\n')
5618
+ return toolText(line)
5619
+ }
5620
+
5621
+ if (action === 'read_outside' || action === 'write_outside' || action === 'list_outside') {
5622
+ const request = { path: target }
5623
+ if (remoteKind) request.remoteId = link.id
5624
+ else request.linkedId = link.id
5625
+ if (action === 'read_outside') {
5626
+ const file = await methods['fs.readOutside']({ ...request, maxBytes: args.max_bytes })
5627
+ if (file.binary) return toolText(`${file.path} (${file.size} B) is binary; only metadata is available.`)
5628
+ const suffix = file.truncated ? `\n...(truncated at ${file.content.length} of ${file.size} bytes)` : ''
5629
+ return toolText(`${file.path} (${file.size} B, mtime ${file.mtime})${suffix}\n\n${file.content}`)
5630
+ }
5631
+ if (action === 'write_outside') {
5632
+ const written = await methods['fs.writeOutside']({
5633
+ ...request,
5634
+ content: args.content,
5635
+ ifModifiedSince: args.if_modified_since,
5636
+ })
5637
+ return toolText(`${written.created ? 'Created' : 'Overwrote'} ${written.path} (${written.size} B)`)
5638
+ }
5639
+ const listing = await methods['fs.listOutside'](request)
5640
+ const rows = listing.entries.map((entry) => (entry.type === 'dir'
5641
+ ? `d ${entry.name}/`
5642
+ : `f ${entry.name} (${entry.size} B)`))
5643
+ return toolText(`${listing.path}\n${rows.length === 0 ? '(empty)' : rows.join('\n')}`)
5644
+ }
5645
+
5646
+ if (action === 'forwards') {
5647
+ const { forwards } = await methods['hosts.forwards']()
5648
+ if (forwards.length === 0) return toolText('No port forwards are open.')
5649
+ return toolText(forwards.map((item) => `${item.id} 127.0.0.1:${item.localPort} -> ${item.hostName}:${item.remoteHost}:${item.remotePort} ${item.url}`).join('\n'))
5650
+ }
5651
+
5652
+ if (action === 'forward') {
5653
+ const { forward } = await methods['hosts.forward']({
5654
+ hostId: link.hostId,
5655
+ remotePort: args.remote_port,
5656
+ remoteHost: args.remote_host,
5657
+ localPort: args.local_port,
5658
+ })
5659
+ 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".`)
5660
+ }
5661
+
5662
+ if (action === 'unforward') {
5663
+ const result = await methods['hosts.unforward']({ id: args.forward_id })
5664
+ return toolText(result.removed ? `Closed tunnel ${args.forward_id}.` : `No tunnel with id ${args.forward_id}.`)
5665
+ }
5666
+
5282
5667
  if (action === 'exec') {
5283
5668
  const command = String((args && args.command) || '')
5284
5669
  if (command.trim() === '') throw new ApiError('BAD_REQUEST', 'command is required for exec')
@@ -5482,6 +5867,12 @@ export function apply(ctx) {
5482
5867
  ctx.effect(() => () => {
5483
5868
  for (const id of [...autoPushWatchers.keys()]) stopAutoPush(id)
5484
5869
  }, 'dsh-linked-workspace: auto push watchers')
5870
+ ctx.effect(() => () => {
5871
+ for (const record of forwardServers.values()) {
5872
+ try { record.server.close() } catch { /* already closed */ }
5873
+ }
5874
+ forwardServers.clear()
5875
+ }, 'dsh-linked-workspace: port forwards')
5485
5876
  }
5486
5877
 
5487
5878
  // ── response helpers ────────────────────────────────────────────────────────
package/lib/ssh.js CHANGED
@@ -1510,6 +1510,34 @@ export class RemoteHost {
1510
1510
  * @param {{ timeoutMs?: number, signal?: AbortSignal }} [options]
1511
1511
  * @returns {Promise<{ stdout: string, stderr: string, code: number }>}
1512
1512
  */
1513
+ /**
1514
+ * Open a direct-tcpip channel to `host:port` as seen from the SSH server.
1515
+ * The caller pipes a local socket through it, which is what makes a local
1516
+ * tunnel to a remote TensorBoard/Jupyter possible.
1517
+ */
1518
+ async forwardOut(host, port) {
1519
+ const targetHost = typeof host === 'string' && host.trim() !== '' ? host.trim() : '127.0.0.1';
1520
+ const targetPort = Number(port);
1521
+ if (!Number.isInteger(targetPort) || targetPort <= 0 || targetPort > 65535) {
1522
+ throw new SshError('BAD_REQUEST', `Invalid remote port: ${port}`);
1523
+ }
1524
+ const client = await this.#readyClient();
1525
+ return await new Promise((resolve, reject) => {
1526
+ client.forwardOut('127.0.0.1', 0, targetHost, targetPort, (err, channel) => {
1527
+ if (err) {
1528
+ reject(
1529
+ new SshError(
1530
+ 'SSH_FORWARD',
1531
+ `Cannot open a tunnel to ${targetHost}:${targetPort} on ${this.authority}: ${(err && err.message) || err}`,
1532
+ ),
1533
+ );
1534
+ return;
1535
+ }
1536
+ resolve(channel);
1537
+ });
1538
+ });
1539
+ }
1540
+
1513
1541
  async exec(command, options = {}) {
1514
1542
  const defaultTimeoutMs = 20000;
1515
1543
  const commandText = typeof command === 'string' ? command : '';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-linked-workspace",
3
- "version": "0.21.0",
3
+ "version": "0.23.0",
4
4
  "description": "Linked local ⇄ remote workspaces and remote workspaces for DeepSeek Harness: theme-aware split editor, file-type icons, and agent tools that edit remote files directly.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -24,6 +24,9 @@ MAX_PDF_WIDTH = 1100
24
24
  MAX_SHEET_ROWS = 200
25
25
  MAX_SHEET_COLS = 40
26
26
  MAX_PPTX_SLIDES = 80
27
+ # Text extraction for the model keeps every page/sheet but stops collecting
28
+ # cells once a sheet gets unreasonably long; the host truncates the final text.
29
+ MAX_XLSX_ROWS = 2000
27
30
 
28
31
 
29
32
  def fail(message):
@@ -183,6 +186,29 @@ def read_pptx(path):
183
186
  emit({"kind": "pptx", "slides": slides, "slideCount": len(presentation.slides)})
184
187
 
185
188
 
189
+ def read_text_pptx(path):
190
+ from pptx import Presentation
191
+
192
+ presentation = Presentation(path)
193
+ slides = []
194
+ for slide_index, slide in enumerate(presentation.slides):
195
+ if slide_index >= MAX_PPTX_SLIDES:
196
+ break
197
+ texts = []
198
+ for shape in slide.shapes:
199
+ if not getattr(shape, "has_text_frame", False):
200
+ continue
201
+ text = shape.text_frame.text
202
+ if text.strip() == "":
203
+ continue
204
+ texts.append(text)
205
+ notes = ""
206
+ if getattr(slide, "has_notes_slide", False):
207
+ notes = slide.notes_slide.notes_text_frame.text or ""
208
+ slides.append({"index": slide_index, "texts": texts, "notes": notes})
209
+ emit({"kind": "pptx", "slides": slides, "slideCount": len(presentation.slides)})
210
+
211
+
186
212
  def write_pptx(source, data, out):
187
213
  from pptx import Presentation
188
214
 
@@ -245,6 +271,54 @@ def read_pdf(path, page_index=None):
245
271
  })
246
272
 
247
273
 
274
+ def read_text_pdf(path):
275
+ import fitz
276
+
277
+ doc = fitz.open(path)
278
+ pages = []
279
+ for index in range(doc.page_count):
280
+ pages.append({"index": index, "text": doc[index].get_text("text")})
281
+ metadata = doc.metadata or {}
282
+ emit({
283
+ "kind": "pdf",
284
+ "pageCount": doc.page_count,
285
+ "title": metadata.get("title", ""),
286
+ "author": metadata.get("author", ""),
287
+ "pages": pages,
288
+ })
289
+
290
+
291
+ def read_text_docx(path):
292
+ from docx import Document
293
+
294
+ document = Document(path)
295
+ paragraphs = [paragraph.text for paragraph in document.paragraphs]
296
+ tables = []
297
+ for table in document.tables:
298
+ rows = []
299
+ for row in table.rows:
300
+ rows.append([cell.text for cell in row.cells])
301
+ tables.append(rows)
302
+ emit({"kind": "docx", "paragraphs": paragraphs, "tables": tables})
303
+
304
+
305
+ def read_text_xlsx(path):
306
+ from openpyxl import load_workbook
307
+
308
+ workbook = load_workbook(path, data_only=True, read_only=True)
309
+ sheets = []
310
+ for sheet in workbook.worksheets:
311
+ rows = []
312
+ for row in sheet.iter_rows(values_only=True):
313
+ cells = ["" if value is None else str(value) for value in row]
314
+ if any(cell.strip() != "" for cell in cells):
315
+ rows.append(cells)
316
+ if len(rows) >= MAX_XLSX_ROWS:
317
+ break
318
+ sheets.append({"name": sheet.title, "rows": rows})
319
+ emit({"kind": "xlsx", "sheets": sheets})
320
+
321
+
248
322
  def write_pdf(source, data, out):
249
323
  import fitz
250
324
 
@@ -381,6 +455,10 @@ def main():
381
455
  pdf.add_argument("--file", required=True)
382
456
  pdf.add_argument("--out", required=True)
383
457
 
458
+ text = sub.add_parser("read-text")
459
+ text.add_argument("--kind", required=True)
460
+ text.add_argument("--file", required=True)
461
+
384
462
  args = parser.parse_args()
385
463
  try:
386
464
  if args.command == "read":
@@ -413,6 +491,17 @@ def main():
413
491
  markdown_preview(args.file)
414
492
  elif args.command == "md-pdf":
415
493
  markdown_pdf(args.file, args.out)
494
+ elif args.command == "read-text":
495
+ if args.kind == "docx":
496
+ read_text_docx(args.file)
497
+ elif args.kind == "xlsx":
498
+ read_text_xlsx(args.file)
499
+ elif args.kind == "pptx":
500
+ read_text_pptx(args.file)
501
+ elif args.kind == "pdf":
502
+ read_text_pdf(args.file)
503
+ else:
504
+ raise ValueError(f"unsupported kind: {args.kind}")
416
505
  except Exception as error: # pragma: no cover - CLI boundary
417
506
  fail(error)
418
507