dsh-linked-workspace 0.17.0 → 0.18.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,15 @@
2
2
 
3
3
  English · [简体中文](CHANGELOG.zh.md)
4
4
 
5
+ ## 0.18.0 — 2026-11-19
6
+
7
+ - New `fs.references` and a `references` action on `linked_workspace`: case-insensitive path completion with the **best match first** (exact name → prefix → substring) and directories flagged `dir`; it stops after 20000 entries or 3 s and reports `truncated`. The model can now resolve a remote path you mention by name.
8
+ - The sidebar context menu gained “Copy as @ reference”, which puts `@relative/path` (for example `@src/app.py`) on the clipboard, ready to paste into the chat.
9
+ - Content search options: a “search usually ignored folders” switch (`includeIgnored` — `node_modules`/`.venv`/`dist` … are searched too while `.git`/`.hg`/`.svn` stay out), a files-only mode (`resultMode: 'files'`), and adjustable `maxFiles`/`maxFileBytes`/`timeoutMs` (5 s by default, 10 s at most). The search bar has two more chips for these.
10
+ - Content search now reports what it walked (`scannedFiles`/`scannedBytes`/`skippedFiles`) and shows “Scanned N files · X” above the results, and it can be **stopped midway**: new `fs.grepCancel { jobId }` backs a “Stop” button in the search bar, and a cancelled sweep reports `truncatedReason: 'cancelled'`.
11
+ - Known limitation (0.18.0): DSH's `@` completion popup cannot be extended by a plugin — the Host `fileReferences` service only exposes `list(agent, query, signal)` with no provider registration — so remote paths do not appear in that popup; use the `references` action or “Copy as @ reference”.
12
+ - Host API revision is now `apiRevision: 4`.
13
+
5
14
  ## 0.17.0 — 2026-11-19
6
15
 
7
16
  - New `hosts.exec`: let the model run **one** non-interactive command on the remote host (builds, tests, logs) instead of composing `ssh`. Off by default and gated three ways: the `execEnabled` switch, the host allow-list `execHostIds`, and the optional workspace allow-list `execWorkspaceIds` (empty means no restriction). Refusals are audited too.
package/README.en.md CHANGED
@@ -127,6 +127,13 @@ The workspace resolves automatically when the session cwd falls inside a linked
127
127
 
128
128
  Every attempt — including refused ones — appends a line to `$DSH_HOME/linked-workspace/exec-audit.jsonl` (command, exit code, duration, first 4 KB of output, refusal reason), rotated to `.1` past 5 MB; the settings block has an “Open audit log” button. Output is clipped per stream to `execMaxOutputChars` (200000 by default), timeouts come from `execTimeoutMs` (60 s by default, 600 s per call at most), and `cwd` may not escape the workspace root.
129
129
 
130
+ ### @ references and finer search (0.18.0)
131
+
132
+ - The `references` action (backed by `fs.references`) matches **path names** case-insensitively with the best match first (exact name → prefix → substring) and directories flagged `dir`, so the model can turn a file name you mention into a real remote path.
133
+ - Right-click a file or folder → “Copy as @ reference” to put `@relative/path` (e.g. `@src/app.py`) on the clipboard.
134
+ - Content search gained two switches — “search usually ignored folders” (`node_modules`/`.venv`/`dist` included, `.git` always out) and “file names only” — plus a “Stop” button that cancels a running sweep; the scan stats (“Scanned N files · X”) appear above the results.
135
+ - Known limitation: DSH's `@` completion popup is not extensible by plugins (the Host `fileReferences` service only offers `list()`, with no registration hook), so remote paths do not show up in that dropdown — use the `references` action or copy-as-reference instead.
136
+
130
137
  ### Running icon / local skills
131
138
 
132
139
  - While a linked workspace has a running session, its link icon turns **blue** (refreshed about every 5 seconds).
package/README.md CHANGED
@@ -127,6 +127,13 @@
127
127
  每次尝试——包括被拒绝的——都会写一行到 `$DSH_HOME/linked-workspace/exec-audit.jsonl`(含命令、退出码、耗时、输出的前 4 KB、拒绝原因),超过 5 MB 自动轮转为 `.1`;设置页有「打开审计日志」按钮。输出按 `execMaxOutputChars`(默认 200000 字符/流)截断,超时由 `execTimeoutMs`(默认 60 秒,单次最多 600 秒)控制,`cwd` 不能跑出工作区根目录。
128
128
 
129
129
 
130
+ ### @ 引用与更细的搜索(0.18.0)
131
+
132
+ - `references` 动作(对应 `fs.references`)按**路径名**做大小写不敏感匹配,最佳匹配排在最前(完全同名 → 前缀 → 包含),目录带 `dir` 标记;模型可以用它把你口头提到的文件名解析成远端真实路径。
133
+ - 右键文件或目录 →「复制为 @ 引用」,把 `@相对路径`(如 `@src/app.py`)复制到剪贴板。
134
+ - 内容搜索多了两枚开关:「包含通常忽略的目录」(`node_modules`/`.venv`/`dist` 也会搜,`.git` 始终排除)、「只列文件名」;搜索中可以点「停止」中途取消,结果上方会显示「扫描 N 个文件 · X」。
135
+ - 已知限制:DSH 的 `@` 补全弹窗没有开放给插件(宿主 `fileReferences` 服务只提供 `list()`,没有注册入口),所以远端路径不会出现在 `@` 下拉里,请用 `references` 动作或右键复制。
136
+
130
137
  ### 运行中图标 / 本地技能
131
138
 
132
139
  - 联动工作区下若有正在运行的会话(本地会话 turn 进行中),左侧工作区的链环图标会变成**蓝色**;刷新间隔约 5 秒。
package/docs/API.md CHANGED
@@ -96,7 +96,9 @@ scope root, or absolute inside it.
96
96
  | `skills.read` | `{ linkedId, name }` | `{ name, description, content, path }` |
97
97
  | `git.status` | `{ linkedId?/remoteId?, side: 'remote'|'local' }` | `{ ok, repo, root, branch, changes, error? }` (remote workspaces only support `side: 'remote'`) |
98
98
  | `fs.search` | `{ linkedId?/remoteId?, side, query, maxResults? }` | `{ ok, query, entries, truncated }` (matches **file names**, not contents; use `fs.grep` for contents) |
99
- | `fs.grep` | `{ linkedId?/remoteId?, side, query, maxResults?, path?, ignoreCase?, regex? }` | `{ ok, query, entries: [{ path, relative, size, line, preview }], truncated, truncatedReason }` (searches file **contents**; `path` narrows the scan to a sub-folder; `ignoreCase` defaults to `true`; `regex` treats `query` as a regular expression; limits are 1 MB per file, 2000 files, 8 MB and 5 s for both sides, and `truncatedReason` is one of `files`, `bytes`, `deadline`, `results`; max 1000 rows) |
99
+ | `fs.grep` | `{ linkedId?/remoteId?, side, query, maxResults?, path?, ignoreCase?, regex?, includeIgnored?, resultMode?, maxFiles?, maxFileBytes?, timeoutMs?, jobId? }` | `{ ok, query, entries: [{ path, relative, size, line, preview, matches }], truncated, truncatedReason, scannedFiles, scannedBytes, skippedFiles }` (searches file **contents**; `path` narrows the scan to a sub-folder; `ignoreCase` defaults to `true`; `regex` treats `query` as a regular expression; `includeIgnored: true` also walks usually ignored folders such as `node_modules`/`.venv`/`dist` (`.git`/`.hg`/`.svn` always stay out); `resultMode: 'files'` lists file names only (`line: 0`, empty `preview`, `matches` = hit count); `maxFiles` (default 2000), `maxFileBytes` (default 1 MB) and `timeoutMs` (default 5 s, max 10 s) raise or lower the sweep; limits are 1 MB per file, 2000 files, 8 MB and 5 s for both sides, and `truncatedReason` is one of `files`, `bytes`, `deadline`, `results`, `cancelled`; max 1000 rows) |
100
+ | `fs.grepCancel` | `{ jobId }` | `{ cancelled }` (marks the job started by `fs.grep`'s `jobId`; the Host checks it between files and answers `truncatedReason: 'cancelled'`) |
101
+ | `fs.references` | `{ linkedId?/remoteId?, query, limit?, includeIgnored?, side? }` | `{ ok, query, candidates: [{ path, relative, name, kind }], total, truncated, scannedEntries }` (path completion for `@`-style references: matches the **path**, case-insensitive, best match first — exact name, then prefix, then substring; `limit` defaults to 50 and caps at 200; walking stops after 20000 entries or 3 s; `side: 'local'` searches the local tree of a linked workspace) |
100
102
  | `fs.compare` | `{ linkedId?, path? }` | `{ path, relative, localPath, localMissing, counts: { onlyLocal, onlyRemote, changed, same }, onlyLocal, onlyRemote, changed, truncated, remoteTruncated, localTruncated, skippedLinks }` (linked workspaces only; excludes `.git`, `node_modules`, `.local`, `.remote`; 4000 files and depth 12 **per side**, 200 rows per group; `skippedLinks` counts symlinks and non-regular files) |
101
103
  | `fs.pullToLocal` | `{ linkedId?, path, targetDir?, conflict? }` | `{ path, relative, size, mtime }` (linked workspaces only; single file, ≤64 MB; `targetDir` must stay inside the local root; `conflict` is `error` (default), `overwrite` or `unique`) |
102
104
  | `fs.upload` | `{ linkedId?/remoteId?, path, paths, conflict? }` | `{ side: 'remote', target, files, bytes, skipped }` (≤50 local files, 64 MB each; `conflict` is `error` (default), `overwrite` or `unique`; a missing target directory is created) |
@@ -155,7 +157,7 @@ Under `$DSH_HOME/linked-workspace/`:
155
157
 
156
158
  `linked_workspace` (Host tool, JSON-Schema parameters) actions: `list`, `info`,
157
159
  `list_dir`, `read`, `write`, `replace`, `stat`, `mkdir`, `rename`, `delete`,
158
- `sync`, `exec`. It resolves the workspace from the session working directory (a linked
160
+ `sync`, `exec`, `references`. It resolves the workspace from the session working directory (a linked
159
161
  local directory or a remote workspace placeholder) or from an explicit
160
162
  `workspace` reference (id, local/placeholder path, or name), confines paths to
161
163
  the remote root, and mirrors reads/writes into `.remote/` when a linked
@@ -163,7 +165,13 @@ workspace mirrors. `list` shows both kinds, labelled `(linked)` and `(remote)`;
163
165
  `info` returns `kind: "linked" | "remote"` and `sync` is rejected for remote
164
166
  workspaces. `exec` takes `command` (≤ 8000 characters), an optional `cwd`
165
167
  (inside the workspace root) and `timeout_ms`, and refuses unless the switches
166
- described under `hosts.exec` are on.
168
+ described under `hosts.exec` are on. `references` takes `query` (≤ 200
169
+ characters) and an optional `limit`, and lists matching paths best-match first
170
+ (directories marked `dir`) — that is how the model resolves a remote path a user
171
+ mentioned by name. The `@` completion popup itself is **not** extensible: the
172
+ Host `fileReferences` service only exposes `list(agent, query, signal)` and has
173
+ no provider registration, so remote candidates cannot be injected into it; use
174
+ the action or the sidebar's “Copy as @ reference”.
167
175
 
168
176
  `linked_skills` (Host tool) actions: `list`, `read` — local skills
169
177
  (`~/.dsh/skills`, `~/.agents/skills`, `<local>/.dsh/skills`,
package/docs/VERIFY.md CHANGED
@@ -2,6 +2,17 @@
2
2
 
3
3
  Host code (lib/) reloads live with `plugin_manager set_plugin include:linked-workspace-ui`; client changes load with **应用 → 重新加载界面** (a full restart is only needed after re-installing the package). Then verify:
4
4
 
5
+ ## @ 引用与搜索增强(0.18.0)
6
+
7
+ 1. 内容搜索栏在「内容」模式下有五枚 chip(`Aa`、`.*`、目录范围、`.*/`、文件图标)与一个「停止」按钮(仅在搜索中、且有 jobId 时出现)。
8
+ 2. 打开「只列文件名」→ 结果行不再显示命中行与行号,只列文件;打开「包含通常忽略的目录」→ 原本被跳过的 `node_modules`/`.venv`/`dist` 中的文件也会出现(`.git` 始终不出现)。
9
+ 3. 搜索一段较大的目录时点「停止」→ 请求 `fs.grepCancel { jobId }`,结果提前结束并在 `truncatedReason` 里给出 `cancelled`。
10
+ 4. 结果上方显示「扫描 N 个文件 · X(跳过 M 个)」,数字来自 `scannedFiles`/`scannedBytes`/`skippedFiles`。
11
+ 5. 右键任一文件或目录 → 「复制为 @ 引用」→ 剪贴板得到 `@相对路径`(如 `@src/app.py`),提示「已复制 @src/app.py」。
12
+ 6. `fs.references { linkedId, query: 'a.txt' }` → `{ candidates: [{ relative, name, kind }], scannedEntries }`,完全同名的排最前;`limit` 生效;空 query 返回空候选而不是报错。
13
+ 7. 模型侧:让它「用 linked_workspace 的 references 动作找一下 xxx 文件」→ 工具卡片按「dir/file + 相对路径」列出候选。
14
+ 8. 已知限制(需人工确认未变化):`@` 补全弹窗里不会出现远端路径 —— 宿主 `fileReferences` 服务只有 `list(agent, query, signal)`,没有 provider 注册入口。
15
+
5
16
  ## 远端命令执行(0.17.0)
6
17
 
7
18
  > 注意:本机这套 DSH **Web** 构建里没有可见的设置入口(账号菜单只有「意见反馈 / 退出登录」,`Ctrl+K` 是会话搜索,插件详情页只有「卸载」),所以设置区块的渲染要在**桌面端**确认;Host 侧行为可以直接用下面的 API 命令验证。
package/lib/client.js CHANGED
@@ -2267,6 +2267,13 @@ function attributeViolation(name, value, tagName) {
2267
2267
  searchRegex: '正则表达式',
2268
2268
  searchScopeAll: '整个工作区',
2269
2269
  searchScopeHere: '只搜当前目录',
2270
+ searchIncludeIgnored: '连通常忽略的目录一起搜(.git 仍然排除)',
2271
+ searchFilesOnly: '只列文件名(不显示命中行)',
2272
+ searchStop: '停止',
2273
+ searchStats: '扫描 {{files}} 个文件 · {{size}}',
2274
+ searchStatsSkipped: '跳过 {{count}} 个',
2275
+ ctxCopyReference: '复制为 @ 引用',
2276
+ referenceCopied: '已复制 {{reference}}',
2270
2277
  searchScopeLabel: '范围:{{scope}}',
2271
2278
  findPlaceholder: '查找…',
2272
2279
  replacePlaceholder: '替换为…',
@@ -2758,6 +2765,13 @@ function attributeViolation(name, value, tagName) {
2758
2765
  searchRegex: 'Regular expression',
2759
2766
  searchScopeAll: 'Whole workspace',
2760
2767
  searchScopeHere: 'Current folder only',
2768
+ searchIncludeIgnored: 'Also search usually ignored folders (.git stays out)',
2769
+ searchFilesOnly: 'List file names only (no matching lines)',
2770
+ searchStop: 'Stop',
2771
+ searchStats: 'Scanned {{files}} files · {{size}}',
2772
+ searchStatsSkipped: '{{count}} skipped',
2773
+ ctxCopyReference: 'Copy as @ reference',
2774
+ referenceCopied: 'Copied {{reference}}',
2761
2775
  searchScopeLabel: 'Scope: {{scope}}',
2762
2776
  findPlaceholder: 'Find…',
2763
2777
  replacePlaceholder: 'Replace with…',
@@ -3189,7 +3203,7 @@ function attributeViolation(name, value, tagName) {
3189
3203
  * Host methods the running DSH process does not have yet, the directory
3190
3204
  * pane says so instead of surfacing an unrelated error.
3191
3205
  */
3192
- var HOST_API_REVISION = 3;
3206
+ var HOST_API_REVISION = 4;
3193
3207
  var hostInfoProbe = null;
3194
3208
 
3195
3209
  function probeHostInfo() {
@@ -3718,6 +3732,7 @@ function attributeViolation(name, value, tagName) {
3718
3732
  '.rw-disk{flex:none;font-size:11px;color:var(--dsw-alias-label-secondary,#8b949e);font-variant-numeric:tabular-nums}',
3719
3733
  '.rw-search-history{display:flex;align-items:center;gap:6px;flex-wrap:wrap;padding:4px 8px 6px}',
3720
3734
  '.rw-search-history-label{font-size:11px;color:var(--dsw-alias-label-secondary,#8b949e);flex:none}',
3735
+ '.rw-search-stats{padding:2px 8px 4px;font-size:11px;color:var(--dsw-alias-label-secondary,#8b949e);font-variant-numeric:tabular-nums}',
3721
3736
  '.rw-queue-history{margin-top:12px;border-top:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.28));padding-top:8px}',
3722
3737
  '.rw-queue-history-title{font-size:11px;color:var(--dsw-alias-label-secondary,#8b949e);margin-bottom:4px}',
3723
3738
  '.rw-queue-row.is-history .rw-queue-state{opacity:.75}',
@@ -7200,6 +7215,16 @@ function rememberShowHidden(value) {
7200
7215
  var searchHereState = useState(false);
7201
7216
  var searchHere = searchHereState[0];
7202
7217
  var setSearchHere = searchHereState[1];
7218
+ var searchIncludeIgnoredState = useState(false);
7219
+ var searchIncludeIgnored = searchIncludeIgnoredState[0];
7220
+ var setSearchIncludeIgnored = searchIncludeIgnoredState[1];
7221
+ var searchFilesOnlyState = useState(false);
7222
+ var searchFilesOnly = searchFilesOnlyState[0];
7223
+ var setSearchFilesOnly = searchFilesOnlyState[1];
7224
+ var searchStatsState = useState(null);
7225
+ var searchStats = searchStatsState[0];
7226
+ var setSearchStats = searchStatsState[1];
7227
+ var searchJobRef = useRef('');
7203
7228
  var searchState = useState({ loading: false, remote: [], local: [], truncated: false, truncatedReason: '', error: null });
7204
7229
  var search = searchState[0];
7205
7230
  var setSearch = searchState[1];
@@ -7751,6 +7776,27 @@ function rememberShowHidden(value) {
7751
7776
  } catch (error) { /* clipboard unavailable */ }
7752
7777
  }
7753
7778
 
7779
+ /** Copy the `@relative/path` form the model understands for a workspace path. */
7780
+ function copyReference(filePath) {
7781
+ var scope = sourceScopeOf(selected);
7782
+ var root = selected && selected.kind === 'remote' ? selected.remotePath : (selected && selected.remotePath) || '';
7783
+ var relative = String(filePath || '');
7784
+ if (root && relative.indexOf(root) === 0) {
7785
+ relative = relative.slice(root.length);
7786
+ if (relative.charAt(0) !== '/') relative = '/' + relative;
7787
+ }
7788
+ var reference = '@' + relative.replace(/^\/+/, '');
7789
+ try {
7790
+ if (navigator.clipboard && navigator.clipboard.writeText) {
7791
+ navigator.clipboard.writeText(reference).then(function () {
7792
+ showNotice('success', t('referenceCopied', { reference: reference }));
7793
+ }).catch(function () {});
7794
+ return;
7795
+ }
7796
+ } catch (error) { /* clipboard unavailable */ }
7797
+ void scope
7798
+ }
7799
+
7754
7800
  /** Copy a ready-made ssh command that lands in the given remote directory. */
7755
7801
  function copySshCommand(dirPath) {
7756
7802
  var source = selected || {};
@@ -8316,6 +8362,7 @@ function rememberShowHidden(value) {
8316
8362
  items.push({ label: t('ctxPaste'), disabled: !canPaste, onSelect: function () { pasteEntry(menu); } });
8317
8363
  items.push({ separator: true });
8318
8364
  items.push({ label: t('ctxCopyPath'), onSelect: function () { copyPathToClipboard(menu.path); } });
8365
+ items.push({ label: t('ctxCopyReference'), onSelect: function () { copyReference(menu.path); } });
8319
8366
  if (menu.side === 'remote' && menu.isDir) {
8320
8367
  items.push({ label: t('ctxCopySsh'), onSelect: function () { copySshCommand(menu.path); } });
8321
8368
  }
@@ -8550,11 +8597,18 @@ function rememberShowHidden(value) {
8550
8597
  var contentMode = searchMode === 'content';
8551
8598
  var method = contentMode ? 'fs.grep' : 'fs.search';
8552
8599
  var extra = { side: 'remote', query: query, maxResults: 200 };
8600
+ var jobId = '';
8553
8601
  if (contentMode) {
8554
8602
  // F3: narrow the sweep to the folder the user is standing in.
8555
8603
  if (searchHere && searchRootPath !== '') extra.path = searchRootPath;
8556
8604
  extra.ignoreCase = !searchCase;
8557
8605
  extra.regex = searchRegex;
8606
+ extra.includeIgnored = searchIncludeIgnored;
8607
+ extra.resultMode = searchFilesOnly ? 'files' : 'lines';
8608
+ // One job id per sweep so 「停止」 can cancel it on the Host.
8609
+ jobId = 'grep-' + Date.now() + '-' + Math.random().toString(36).slice(2, 8);
8610
+ extra.jobId = jobId;
8611
+ searchJobRef.current = jobId;
8558
8612
  }
8559
8613
  var jobs = [apiCall(method, Object.assign(extra, scopeParams(scopeNow))).catch(function (error) {
8560
8614
  return { ok: false, entries: [], error: messageOf(error, t, locale) };
@@ -8570,6 +8624,16 @@ function rememberShowHidden(value) {
8570
8624
  }
8571
8625
  Promise.all(jobs).then(function (results) {
8572
8626
  if (!alive) return;
8627
+ if (contentMode && jobId !== '' && searchJobRef.current === jobId) searchJobRef.current = '';
8628
+ var stats = null;
8629
+ if (contentMode && results[0] && typeof results[0].scannedFiles === 'number') {
8630
+ stats = {
8631
+ files: (results[0].scannedFiles || 0) + ((results[1] && results[1].scannedFiles) || 0),
8632
+ bytes: (results[0].scannedBytes || 0) + ((results[1] && results[1].scannedBytes) || 0),
8633
+ skipped: (results[0].skippedFiles || 0) + ((results[1] && results[1].skippedFiles) || 0),
8634
+ };
8635
+ }
8636
+ if (contentMode) setSearchStats(stats);
8573
8637
  setSearch({
8574
8638
  loading: false,
8575
8639
  remote: results[0] && results[0].entries ? results[0].entries : [],
@@ -8581,7 +8645,7 @@ function rememberShowHidden(value) {
8581
8645
  });
8582
8646
  }, 320);
8583
8647
  return function () { alive = false; clearTimeout(timer); };
8584
- }, [searchOpen, searchQuery, selectedKey, version, searchMode, searchCase, searchRegex, searchHere]);
8648
+ }, [searchOpen, searchQuery, selectedKey, version, searchMode, searchCase, searchRegex, searchHere, searchIncludeIgnored, searchFilesOnly]);
8585
8649
 
8586
8650
  if (!selected) {
8587
8651
  return h('div', { className: 'rw-workbench rw-workspace', ref: workbenchRef },
@@ -8838,7 +8902,33 @@ function rememberShowHidden(value) {
8838
8902
  'aria-pressed': searchHere ? 'true' : 'false',
8839
8903
  disabled: searchRootPath === '',
8840
8904
  onClick: function () { setSearchHere(!searchHere); },
8841
- }, IconFolderTree(11)))
8905
+ }, IconFolderTree(11)),
8906
+ h('button', {
8907
+ type: 'button',
8908
+ className: 'rw-chip-btn' + (searchIncludeIgnored ? ' is-on' : ''),
8909
+ title: t('searchIncludeIgnored'),
8910
+ 'aria-pressed': searchIncludeIgnored ? 'true' : 'false',
8911
+ onClick: function () { setSearchIncludeIgnored(!searchIncludeIgnored); },
8912
+ }, '.*/'),
8913
+ h('button', {
8914
+ type: 'button',
8915
+ className: 'rw-chip-btn' + (searchFilesOnly ? ' is-on' : ''),
8916
+ title: t('searchFilesOnly'),
8917
+ 'aria-pressed': searchFilesOnly ? 'true' : 'false',
8918
+ onClick: function () { setSearchFilesOnly(!searchFilesOnly); },
8919
+ }, IconFile(11)),
8920
+ search.loading && searchJobRef.current !== ''
8921
+ ? h('button', {
8922
+ type: 'button',
8923
+ className: 'rw-chip-btn',
8924
+ title: t('searchStop'),
8925
+ onClick: function () {
8926
+ var jobId = searchJobRef.current;
8927
+ searchJobRef.current = '';
8928
+ if (jobId) apiCall('fs.grepCancel', { jobId }).catch(function () {});
8929
+ },
8930
+ }, t('searchStop'))
8931
+ : null)
8842
8932
  : null,
8843
8933
  h('button', {
8844
8934
  type: 'button', className: 'rw-icon-btn', title: t('cancel'),
@@ -8858,6 +8948,11 @@ function rememberShowHidden(value) {
8858
8948
  }, h('span', { style: { overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: '160px' } }, term));
8859
8949
  }))
8860
8950
  : null,
8951
+ searchOpen && searchMode === 'content' && !search.loading && searchStats && searchStats.files > 0
8952
+ ? h('div', { className: 'rw-search-stats' },
8953
+ t('searchStats', { files: searchStats.files, size: formatBytes(searchStats.bytes) }),
8954
+ searchStats.skipped > 0 ? ' · ' + t('searchStatsSkipped', { count: searchStats.skipped }) : '')
8955
+ : null,
8861
8956
  sources.length > 1
8862
8957
  ? h('div', { className: 'rw-chips' },
8863
8958
  sources.map(function (source) {
package/lib/index.js CHANGED
@@ -38,7 +38,7 @@ export const inject = ['webServer', 'tools', 'systemPrompt', 'workingDirectory']
38
38
  * is still running an older copy of the Host — refreshing the page only swaps
39
39
  * the browser bundle, so the two halves can drift by one restart.
40
40
  */
41
- const API_REVISION = 3
41
+ const API_REVISION = 4
42
42
 
43
43
  /** When this copy of the Host was loaded; shown by `meta.info`. */
44
44
  const STARTED_AT = new Date().toISOString()
@@ -1536,6 +1536,7 @@ export function apply(ctx) {
1536
1536
  '- Writes are atomic. Pass `if_modified_since` (epoch milliseconds from a previous read/stat) to refuse a stale overwrite.',
1537
1537
  '- action "sync" archives the remote tree into `.remote/` and only exists for a linked workspace (a remote workspace has no local copy).',
1538
1538
  '- 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.',
1539
+ '- 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.',
1539
1540
  'The workspace is resolved from the session working directory; pass `workspace` (id, local path, placeholder path or name) when working elsewhere.',
1540
1541
  'For a REMOTE workspace do not create project files in the placeholder and do not expect local paths to exist: read, write, build and inspect logs on the remote host, through linked_workspace actions or `ssh` when an action does not fit. Prefer action "exec" over `ssh` when it is enabled: it keeps the audit trail and the output limits.',
1541
1542
  'Locally installed skills (~/.dsh/skills, ~/.agents/skills) remain available; use `linked_skills` to list or read them. A linked workspace also sees the project skills of its local directory.',
@@ -1813,6 +1814,22 @@ export function apply(ctx) {
1813
1814
  job.updatedAt = Date.now()
1814
1815
  }
1815
1816
 
1817
+ // A content search can run for seconds; the client can stop it by job id the
1818
+ // same way it stops a transfer. The flag is checked between files.
1819
+ const GREP_JOB_TTL_MS = 60 * 1000
1820
+ const grepJobs = new Map()
1821
+
1822
+ const beginGrepJob = (id) => {
1823
+ if (typeof id !== 'string' || id.trim() === '') return null
1824
+ const now = Date.now()
1825
+ for (const [key, value] of grepJobs) {
1826
+ if (now - value.startedAt > GREP_JOB_TTL_MS) grepJobs.delete(key)
1827
+ }
1828
+ const job = { id, cancelled: false, startedAt: now }
1829
+ grepJobs.set(id, job)
1830
+ return job
1831
+ }
1832
+
1816
1833
  /** Download one remote file/folder into the OS Downloads folder. */
1817
1834
  const downloadRemotePath = async (remote, target, destDir) => {
1818
1835
  await mkdir(destDir, { recursive: true })
@@ -2077,9 +2094,16 @@ export function apply(ctx) {
2077
2094
  const GREP_MAX_FILES = 2000
2078
2095
  const GREP_MAX_BYTES = 8 * 1024 * 1024
2079
2096
  const GREP_DEADLINE_MS = 5000
2097
+ const GREP_DEADLINE_MAX = 10000
2080
2098
  const GREP_PREVIEW_CHARS = 120
2081
2099
  const GREP_MAX_QUERY = 200
2082
2100
 
2101
+ // Path completion (`fs.references`) is about names, not contents, so it walks
2102
+ // more entries but reads no files.
2103
+ const REFERENCE_MAX_RESULTS = 200
2104
+ const REFERENCE_MAX_ENTRIES = 20000
2105
+ const REFERENCE_DEADLINE_MS = 3000
2106
+
2083
2107
  // Dependency trees and build output make a content search useless: they
2084
2108
  // dwarf the project and always win the result budget. Both sides skip them.
2085
2109
  const GREP_EXCLUDED_DIRS = [
@@ -2089,7 +2113,13 @@ export function apply(ctx) {
2089
2113
  '.ipynb_checkpoints', '.gradle', '.idea', '.vscode',
2090
2114
  ]
2091
2115
 
2092
- function grepDirectoryExcluded(name) {
2116
+ // Version-control metadata stays hidden even when the user asks for ignored
2117
+ // directories: nobody wants `.git/objects` in a completion list.
2118
+ const GREP_ALWAYS_EXCLUDED = new Set(['.git', '.hg', '.svn'])
2119
+
2120
+ function grepDirectoryExcluded(name, includeIgnored) {
2121
+ if (GREP_ALWAYS_EXCLUDED.has(name)) return true
2122
+ if (includeIgnored) return false
2093
2123
  return LINKED_SYNC_EXCLUDES.has(name) || GREP_EXCLUDED_DIRS.indexOf(name) !== -1
2094
2124
  }
2095
2125
 
@@ -2126,21 +2156,51 @@ export function apply(ctx) {
2126
2156
  return { line: 0, preview: '' }
2127
2157
  }
2128
2158
 
2159
+ /** Count occurrences of the query in one file body (used by `files` mode). */
2160
+ function countMatches(text, query, options) {
2161
+ if (query === '') return 0
2162
+ if (options && options.regex) {
2163
+ let expression
2164
+ try {
2165
+ expression = new RegExp(query, options.ignoreCase ? 'gi' : 'g')
2166
+ } catch {
2167
+ return 0
2168
+ }
2169
+ const found = text.match(expression)
2170
+ return found ? found.length : 0
2171
+ }
2172
+ const haystack = options && options.ignoreCase ? text.toLowerCase() : text
2173
+ const needle = options && options.ignoreCase ? query.toLowerCase() : query
2174
+ let count = 0
2175
+ let index = haystack.indexOf(needle)
2176
+ while (index !== -1) {
2177
+ count += 1
2178
+ index = haystack.indexOf(needle, index + needle.length)
2179
+ }
2180
+ return count
2181
+ }
2182
+
2129
2183
  function contentSearchLocal(root, query, maxResults, options = {}) {
2130
2184
  const matcher = compileSearch(query, options)
2131
2185
  const entries = []
2132
2186
  const started = Date.now()
2187
+ const maxFiles = clampInt(options.maxFiles, 1, GREP_MAX_FILES, GREP_MAX_FILES)
2188
+ const maxFileBytes = clampInt(options.maxFileBytes, 1024, GREP_MAX_FILE_BYTES, GREP_MAX_FILE_BYTES)
2189
+ const deadline = clampInt(options.timeoutMs, 500, GREP_DEADLINE_MAX, GREP_DEADLINE_MS)
2190
+ const filesOnly = options.resultMode === 'files'
2133
2191
  let files = 0
2134
2192
  let bytes = 0
2193
+ let skippedFiles = 0
2135
2194
  let truncatedReason = ''
2136
2195
  const stop = (reason) => {
2137
2196
  if (truncatedReason === '') truncatedReason = reason
2138
2197
  }
2139
2198
  const visit = (directory, prefix) => {
2140
2199
  if (truncatedReason !== '') return
2141
- if (files >= GREP_MAX_FILES) return stop('files')
2200
+ if (files >= maxFiles) return stop('files')
2142
2201
  if (bytes >= GREP_MAX_BYTES) return stop('bytes')
2143
- if (Date.now() - started > GREP_DEADLINE_MS) return stop('deadline')
2202
+ if (Date.now() - started > deadline) return stop('deadline')
2203
+ if (options.job && options.job.cancelled) return stop('cancelled')
2144
2204
  let listing
2145
2205
  try {
2146
2206
  listing = readdirSync(directory, { withFileTypes: true })
@@ -2149,7 +2209,8 @@ export function apply(ctx) {
2149
2209
  }
2150
2210
  for (const entry of listing) {
2151
2211
  if (truncatedReason !== '') return
2152
- if (grepDirectoryExcluded(entry.name)) continue
2212
+ if (options.job && options.job.cancelled) return stop('cancelled')
2213
+ if (grepDirectoryExcluded(entry.name, options.includeIgnored)) continue
2153
2214
  const absolute = join(directory, entry.name)
2154
2215
  const relative = prefix === '' ? entry.name : `${prefix}/${entry.name}`
2155
2216
  if (entry.isDirectory()) {
@@ -2157,21 +2218,26 @@ export function apply(ctx) {
2157
2218
  continue
2158
2219
  }
2159
2220
  if (!entry.isFile()) continue
2160
- if (files >= GREP_MAX_FILES) return stop('files')
2221
+ if (files >= maxFiles) return stop('files')
2161
2222
  if (bytes >= GREP_MAX_BYTES) return stop('bytes')
2162
- if (Date.now() - started > GREP_DEADLINE_MS) return stop('deadline')
2223
+ if (Date.now() - started > deadline) return stop('deadline')
2163
2224
  files += 1
2164
2225
  // Skip oversized files before reading them: pulling a 2 GB blob into
2165
2226
  // memory to answer a text query would stall the whole Host.
2166
2227
  try {
2167
- if (statSync(absolute).size > GREP_MAX_FILE_BYTES) continue
2228
+ if (statSync(absolute).size > maxFileBytes) {
2229
+ skippedFiles += 1
2230
+ continue
2231
+ }
2168
2232
  } catch {
2233
+ skippedFiles += 1
2169
2234
  continue
2170
2235
  }
2171
2236
  let data
2172
2237
  try {
2173
2238
  data = readFileSync(absolute)
2174
2239
  } catch {
2240
+ skippedFiles += 1
2175
2241
  continue
2176
2242
  }
2177
2243
  bytes += data.length
@@ -2179,12 +2245,25 @@ export function apply(ctx) {
2179
2245
  const text = data.toString('utf8')
2180
2246
  if (!matcher.test(text)) continue
2181
2247
  if (entries.length >= maxResults) return stop('results')
2182
- const hit = firstMatchLine(text, matcher)
2183
- entries.push({ path: absolute, relative, size: data.length, line: hit.line, preview: hit.preview })
2248
+ if (filesOnly) {
2249
+ entries.push({ path: absolute, relative, size: data.length, line: 0, preview: '', matches: countMatches(text, query, options) })
2250
+ } else {
2251
+ const hit = firstMatchLine(text, matcher)
2252
+ entries.push({ path: absolute, relative, size: data.length, line: hit.line, preview: hit.preview })
2253
+ }
2184
2254
  }
2185
2255
  }
2186
2256
  visit(resolve(root), '')
2187
- return { ok: true, query, entries, truncated: truncatedReason !== '', truncatedReason }
2257
+ return {
2258
+ ok: true,
2259
+ query,
2260
+ entries,
2261
+ truncated: truncatedReason !== '',
2262
+ truncatedReason,
2263
+ scannedFiles: files,
2264
+ scannedBytes: bytes,
2265
+ skippedFiles,
2266
+ }
2188
2267
  }
2189
2268
 
2190
2269
  async function contentSearchRemote(remote, root, query, maxResults, options = {}) {
@@ -2206,17 +2285,26 @@ export function apply(ctx) {
2206
2285
  if (normalized === '..' || normalized.startsWith('../')) throw new ApiError('BAD_REQUEST', '搜索路径超出工作区范围')
2207
2286
  searchRoot = normalized === '' ? root : posix.join(root, normalized)
2208
2287
  }
2209
- const excludes = GREP_EXCLUDED_DIRS.map((dir) => `--exclude-dir=${shellQuoteArg(dir)}`).join(' ')
2288
+ const ignores = options.includeIgnored
2289
+ ? [...GREP_ALWAYS_EXCLUDED]
2290
+ : GREP_EXCLUDED_DIRS
2291
+ const excludes = ignores.map((dir) => `--exclude-dir=${shellQuoteArg(dir)}`).join(' ')
2210
2292
  const pattern = useRegex ? `-E ${shellQuoteArg(query)}` : `-e ${shellQuoteArg(query)}`
2211
- const command = `grep -rIn${ignoreCase ? 'i' : ''} --binary-files=without-match ${excludes} ${pattern}`
2293
+ const filesOnly = options.resultMode === 'files'
2294
+ const deadline = clampInt(options.timeoutMs, 500, GREP_DEADLINE_MAX, GREP_DEADLINE_MS)
2295
+ const listFlag = filesOnly ? 'Il' : 'In'
2296
+ const command = `grep -r${listFlag}${ignoreCase ? 'i' : ''} --binary-files=without-match ${excludes} ${pattern}`
2212
2297
  + ` -- ${shellQuoteArg(searchRoot)} 2>/dev/null | head -n ${maxResults + 1}`
2213
2298
  let result
2214
2299
  try {
2215
- result = await remote.exec(command, { timeoutMs: 20000 })
2300
+ result = await remote.exec(command, { timeoutMs: Math.max(deadline + 2000, 20000) })
2216
2301
  } catch (error) {
2217
2302
  // A timeout means "we looked, but not everywhere": report it as a
2218
2303
  // truncated result instead of failing the whole search.
2219
- return { ok: true, query, entries: [], truncated: true, truncatedReason: 'deadline' }
2304
+ return {
2305
+ ok: true, query, entries: [], truncated: true, truncatedReason: 'deadline',
2306
+ scannedFiles: 0, scannedBytes: 0, skippedFiles: 0,
2307
+ }
2220
2308
  }
2221
2309
  if (result.code !== 0 && String(result.stdout || '').trim() === '') {
2222
2310
  // grep exits 1 when nothing matched; a real failure has code > 1.
@@ -2225,30 +2313,145 @@ export function apply(ctx) {
2225
2313
  if (result.code === 2 && /invalid/i.test(detail)) throw new ApiError('BAD_REQUEST', `正则表达式无效:${detail}`)
2226
2314
  throw new ApiError('INTERNAL', `内容搜索失败:${detail}`)
2227
2315
  }
2228
- return { ok: true, query, entries: [], truncated: false, truncatedReason: '' }
2316
+ return {
2317
+ ok: true, query, entries: [], truncated: false, truncatedReason: '',
2318
+ scannedFiles: 0, scannedBytes: 0, skippedFiles: 0,
2319
+ }
2229
2320
  }
2230
- const lines = String(result.stdout || '').split('\n').filter((line) => line.trim() !== '')
2321
+ const lines = String(result.stdout || '').replace(/\r/g, '').split('\n').filter((line) => line.trim() !== '')
2231
2322
  const entries = []
2323
+ const seen = new Set()
2232
2324
  let truncatedReason = ''
2233
2325
  for (const raw of lines) {
2234
2326
  if (entries.length >= maxResults) {
2235
2327
  truncatedReason = 'results'
2236
2328
  break
2237
2329
  }
2238
- const match = /^(.*?):(\d+):(.*)$/.exec(raw)
2239
- if (!match) continue
2240
- const file = match[1]
2330
+ const common = filesOnly ? /^(.*)$/.exec(raw) : /^(.*?):(\d+):(.*)$/.exec(raw)
2331
+ if (!common) continue
2332
+ const file = common[1]
2333
+ seen.add(file)
2241
2334
  const relative = file.startsWith(`${searchRoot}/`) ? file.slice(searchRoot.length + 1) : file
2242
2335
  entries.push({
2243
2336
  path: file,
2244
2337
  relative,
2245
2338
  size: null,
2246
- line: Number(match[2]),
2247
- preview: match[3].replace(/\s+/g, ' ').trim().slice(0, GREP_PREVIEW_CHARS),
2339
+ line: filesOnly ? 0 : Number(common[2]),
2340
+ preview: filesOnly ? '' : common[3].replace(/\s+/g, ' ').trim().slice(0, GREP_PREVIEW_CHARS),
2248
2341
  })
2249
2342
  }
2250
2343
  if (truncatedReason === '' && lines.length > maxResults) truncatedReason = 'results'
2251
- return { ok: true, query, entries, truncated: truncatedReason !== '', truncatedReason }
2344
+ return {
2345
+ ok: true,
2346
+ query,
2347
+ entries,
2348
+ truncated: truncatedReason !== '',
2349
+ truncatedReason,
2350
+ scannedFiles: seen.size,
2351
+ scannedBytes: 0,
2352
+ skippedFiles: 0,
2353
+ }
2354
+ }
2355
+
2356
+ // ── path completion (`fs.references`, 0.18.0) ─────────────────────────────
2357
+ // Ordering rule: an exact file name wins, then names that start with the
2358
+ // query, then anything else — shorter paths first inside each group, so the
2359
+ // obvious candidate is always at the top of the list.
2360
+
2361
+ function rankReferenceCandidates(list, needle, limit) {
2362
+ const scored = list.map((item) => {
2363
+ const name = item.name.toLowerCase()
2364
+ let score = 2
2365
+ if (name === needle) score = 0
2366
+ else if (name.startsWith(needle)) score = 1
2367
+ return { item, score }
2368
+ })
2369
+ scored.sort((left, right) => {
2370
+ if (left.score !== right.score) return left.score - right.score
2371
+ if (left.item.relative.length !== right.item.relative.length) {
2372
+ return left.item.relative.length - right.item.relative.length
2373
+ }
2374
+ return left.item.relative.localeCompare(right.item.relative)
2375
+ })
2376
+ return scored.slice(0, limit).map((entry) => entry.item)
2377
+ }
2378
+
2379
+ function referenceCandidatesLocal(root, query, limit, options = {}) {
2380
+ const needle = query.toLowerCase()
2381
+ const started = Date.now()
2382
+ const hits = []
2383
+ let visited = 0
2384
+ let truncated = false
2385
+ const walk = (directory, prefix) => {
2386
+ if (truncated) return
2387
+ if (visited >= REFERENCE_MAX_ENTRIES || Date.now() - started > REFERENCE_DEADLINE_MS) {
2388
+ truncated = true
2389
+ return
2390
+ }
2391
+ let listing
2392
+ try {
2393
+ listing = readdirSync(directory, { withFileTypes: true })
2394
+ } catch {
2395
+ return
2396
+ }
2397
+ for (const entry of listing) {
2398
+ if (visited >= REFERENCE_MAX_ENTRIES || Date.now() - started > REFERENCE_DEADLINE_MS) {
2399
+ truncated = true
2400
+ return
2401
+ }
2402
+ if (grepDirectoryExcluded(entry.name, options.includeIgnored)) continue
2403
+ visited += 1
2404
+ const relative = prefix === '' ? entry.name : `${prefix}/${entry.name}`
2405
+ if (entry.isDirectory()) {
2406
+ if (relative.toLowerCase().indexOf(needle) !== -1) {
2407
+ hits.push({ relative, name: entry.name, kind: 'directory' })
2408
+ }
2409
+ walk(join(directory, entry.name), relative)
2410
+ } else if (entry.isFile() && relative.toLowerCase().indexOf(needle) !== -1) {
2411
+ hits.push({ relative, name: entry.name, kind: 'file' })
2412
+ }
2413
+ }
2414
+ }
2415
+ walk(resolve(root), '')
2416
+ const candidates = rankReferenceCandidates(hits, needle, limit)
2417
+ return { ok: true, query, candidates, total: hits.length, truncated, scannedEntries: visited }
2418
+ }
2419
+
2420
+ async function referenceCandidatesRemote(remote, root, query, limit, options = {}) {
2421
+ const needle = query.toLowerCase()
2422
+ const ignores = options.includeIgnored ? [...GREP_ALWAYS_EXCLUDED] : GREP_EXCLUDED_DIRS
2423
+ const excluded = ignores.length === 0
2424
+ ? ''
2425
+ : ` | grep -Ev ${shellQuoteArg(ignores.map((dir) => `/${dir}/`).join('|'))}`
2426
+ const command = `find ${shellQuoteArg(root)} -mindepth 1 -printf '%y\\t%p\\n' 2>/dev/null`
2427
+ + `${excluded} | head -n ${REFERENCE_MAX_ENTRIES + 1}`
2428
+ let result
2429
+ try {
2430
+ result = await remote.exec(command, { timeoutMs: 20000 })
2431
+ } catch {
2432
+ return { ok: true, query, candidates: [], total: 0, truncated: true, scannedEntries: 0 }
2433
+ }
2434
+ const rows = String(result.stdout || '').split('\n').filter((line) => line.indexOf('\t') !== -1)
2435
+ const truncated = rows.length > REFERENCE_MAX_ENTRIES
2436
+ const hits = []
2437
+ for (const row of rows.slice(0, REFERENCE_MAX_ENTRIES)) {
2438
+ const tab = row.indexOf('\t')
2439
+ const kindCode = row.slice(0, tab)
2440
+ const absolute = row.slice(tab + 1)
2441
+ const kind = kindCode === 'd' ? 'directory' : kindCode === 'f' ? 'file' : ''
2442
+ if (kind === '') continue
2443
+ const relative = absolute.startsWith(`${root}/`) ? absolute.slice(root.length + 1) : absolute
2444
+ if (relative.toLowerCase().indexOf(needle) === -1) continue
2445
+ hits.push({ relative, name: posix.basename(relative), kind })
2446
+ }
2447
+ return {
2448
+ ok: true,
2449
+ query,
2450
+ candidates: rankReferenceCandidates(hits, needle, limit),
2451
+ total: hits.length,
2452
+ truncated,
2453
+ scannedEntries: rows.length,
2454
+ }
2252
2455
  }
2253
2456
 
2254
2457
  // ── remote command execution ──────────────────────────────────────────────
@@ -3493,19 +3696,59 @@ export function apply(ctx) {
3493
3696
  const scope = await requireScope(params)
3494
3697
  const query = typeof params.query === 'string' ? params.query.trim() : ''
3495
3698
  const maxResults = Math.min(Math.max(Number(params.maxResults) || 200, 1), 1000)
3496
- if (query === '') return { ok: true, query: '', entries: [], truncated: false, truncatedReason: '' }
3699
+ if (query === '') {
3700
+ return {
3701
+ ok: true, query: '', entries: [], truncated: false, truncatedReason: '',
3702
+ scannedFiles: 0, scannedBytes: 0, skippedFiles: 0,
3703
+ }
3704
+ }
3497
3705
  if (query.length > GREP_MAX_QUERY) throw new ApiError('BAD_REQUEST', `搜索词过长(最多 ${GREP_MAX_QUERY} 个字符)`)
3498
3706
  const side = params.side === 'local' ? 'local' : 'remote'
3499
3707
  const options = {
3500
3708
  path: typeof params.path === 'string' ? params.path : '',
3501
3709
  ignoreCase: params.ignoreCase !== false,
3502
3710
  regex: Boolean(params.regex),
3711
+ includeIgnored: params.includeIgnored === true,
3712
+ resultMode: params.resultMode === 'files' ? 'files' : 'lines',
3713
+ maxFiles: params.maxFiles,
3714
+ maxFileBytes: params.maxFileBytes,
3715
+ timeoutMs: params.timeoutMs,
3716
+ job: beginGrepJob(params.jobId),
3503
3717
  }
3504
3718
  if (side === 'remote') return await contentSearchRemote(scope.remote, scope.root, query, maxResults, options)
3505
3719
  if (scope.kind !== 'linked') throw new ApiError('BAD_REQUEST', '只有联动工作区有本地目录')
3506
3720
  return contentSearchLocal(scope.record.localPath, query, maxResults, options)
3507
3721
  },
3508
3722
 
3723
+ /** Stop a running `fs.grep` (checked between files on the Host). */
3724
+ async 'fs.grepCancel'(params = {}) {
3725
+ const id = typeof params.jobId === 'string' ? params.jobId : ''
3726
+ const job = grepJobs.get(id)
3727
+ if (!job) return { cancelled: false }
3728
+ job.cancelled = true
3729
+ return { cancelled: true }
3730
+ },
3731
+
3732
+ /**
3733
+ * Path completion for `@`-style references (0.18.0). Returns candidate
3734
+ * paths relative to the remote root, best match first. Names only.
3735
+ */
3736
+ async 'fs.references'(params = {}) {
3737
+ const scope = await requireScope(params)
3738
+ const query = typeof params.query === 'string' ? params.query.trim() : ''
3739
+ const limit = clampInt(params.limit, 1, REFERENCE_MAX_RESULTS, 50)
3740
+ const options = { includeIgnored: params.includeIgnored === true }
3741
+ if (query.length > GREP_MAX_QUERY) throw new ApiError('BAD_REQUEST', `搜索词过长(最多 ${GREP_MAX_QUERY} 个字符)`)
3742
+ if (query === '') {
3743
+ return { ok: true, query: '', candidates: [], total: 0, truncated: false, scannedEntries: 0 }
3744
+ }
3745
+ if (params.side === 'local') {
3746
+ if (scope.kind !== 'linked') throw new ApiError('BAD_REQUEST', '只有联动工作区有本地目录')
3747
+ return referenceCandidatesLocal(scope.record.localPath, query, limit, options)
3748
+ }
3749
+ return await referenceCandidatesRemote(scope.remote, scope.root, query, limit, options)
3750
+ },
3751
+
3509
3752
  /**
3510
3753
  * Read-only comparison of one directory pair. Lists files that exist on one
3511
3754
  * side only and files whose size or mtime disagree; it never touches data.
@@ -4187,7 +4430,7 @@ export function apply(ctx) {
4187
4430
  properties: {
4188
4431
  action: {
4189
4432
  type: 'string',
4190
- enum: ['list', 'info', 'list_dir', 'read', 'write', 'replace', 'stat', 'mkdir', 'rename', 'delete', 'sync', 'exec'],
4433
+ enum: ['list', 'info', 'list_dir', 'read', 'write', 'replace', 'stat', 'mkdir', 'rename', 'delete', 'sync', 'exec', 'references'],
4191
4434
  description: 'Operation to perform. sync only applies to a linked workspace with mirroring on. exec needs the remote-execution switch and allow-lists.',
4192
4435
  },
4193
4436
  workspace: {
@@ -4208,6 +4451,8 @@ export function apply(ctx) {
4208
4451
  command: { type: 'string', description: 'Command line for exec (≤ 8000 characters). Runs non-interactively on the remote host.' },
4209
4452
  cwd: { type: 'string', description: 'Working directory for exec: relative to the workspace root (or an absolute path inside it).' },
4210
4453
  timeout_ms: { type: 'number', description: 'exec timeout in milliseconds (default from settings, max 600000).' },
4454
+ query: { type: 'string', description: 'Search text for references (matches the path, case-insensitive; ≤ 200 characters).' },
4455
+ limit: { type: 'number', description: 'How many candidates references returns (default 50, max 200).' },
4211
4456
  },
4212
4457
  required: ['action'],
4213
4458
  },
@@ -4436,6 +4681,20 @@ export function apply(ctx) {
4436
4681
  return toolText(lines.join('\n'))
4437
4682
  }
4438
4683
 
4684
+ if (action === 'references') {
4685
+ const query = String((args && args.query) || ((args && args.path) || ''))
4686
+ if (query.trim() === '') throw new ApiError('BAD_REQUEST', 'query is required for references')
4687
+ const result = await methods['fs.references'](
4688
+ remoteKind
4689
+ ? { remoteId: link.id, query, limit: args.limit }
4690
+ : { linkedId: link.id, query, limit: args.limit },
4691
+ )
4692
+ if (result.candidates.length === 0) return toolText('(no matching path)')
4693
+ const lines = result.candidates.map((item) => `${item.kind === 'directory' ? 'dir ' : 'file'} ${item.relative}`)
4694
+ if (result.truncated) lines.push(`… stopped after ${result.scannedEntries} entries; narrow the query`)
4695
+ return toolText(lines.join('\n'))
4696
+ }
4697
+
4439
4698
  throw new ApiError('BAD_REQUEST', `unknown action: ${action}`)
4440
4699
  } catch (error) {
4441
4700
  const apiError = asApiError(error)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-linked-workspace",
3
- "version": "0.17.0",
3
+ "version": "0.18.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",