dsh-tool-folder 0.2.2 → 0.2.3

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/README.md CHANGED
@@ -149,6 +149,31 @@ were never unregistered, so nothing else changes.
149
149
 
150
150
  ## Changelog
151
151
 
152
+ ### v0.2.3 — fold-ux: search fallback catalog + query expansion + stable results + discovery stats (2026-08-30)
153
+ 1. **Zero-match fallback catalog** (`fallbackCatalogSize`, default 30): when
154
+ `tools_search` finds nothing, it returns a name-sorted lightweight catalog
155
+ (name + 80-char description) instead of an empty list — the model never
156
+ concludes a capability doesn't exist just because its wording missed.
157
+ `total` reports the real catalog size (not the listed slice); the output
158
+ carries `fallback: true`. `0` restores the legacy empty result.
159
+ 2. **CN→EN query expansion** (`queryExpandEnabled`, default on): a 48-term
160
+ high-frequency intent table appends English synonyms to the search text
161
+ (search/find, file, image/ocr, database, deploy, schedule…). Only adds
162
+ terms, never rewrites the original query; exact-name priority still uses
163
+ the raw query, so precise lookups are byte-identical to v0.2.2.
164
+ 3. **Stable results** (`createSearchCache`, 60s TTL / LRU 200): the same query
165
+ returns the same result set across turns — kills per-turn candidate drift.
166
+ 4. **Discovery stats** (`recordDiscoveries`): every found tool is counted and
167
+ persisted (30s-throttled, merged into tool-folder-state.json); on restart
168
+ the top-5 are logged so low-discovery tools can be identified and their
169
+ descriptions improved (Anthropic's "monitor discovery rate" loop).
170
+ 5. 83 tests green (11 new: ux module).
171
+ 6. Three-axis audit (Standards / Spec / compatibility): 1 P1 fixed — warm and
172
+ discovery state now merge-write the shared state file instead of clobbering
173
+ each other; P2 hardening — `tools_search` execute got a whole-body
174
+ fail-open catch, fallback `total` semantics clarified, comments corrected
175
+ to process-level scope.
176
+
152
177
  ### v0.2.2 — tiered disclosure budget + warm LRU + incremental semantic cache (2026-08-30)
153
178
  1. **Tiered disclosure budget** (`disclosureBudget`, default 0 = off): caps how
154
179
  many tool names + descriptions are disclosed per request. Over budget, tools
package/lib/index.js CHANGED
@@ -36,6 +36,7 @@ import { compressTool, normalizeDescription, sanitizeLossless } from "./schema.j
36
36
  import { selectionCoverage, isHotTool, prioritizeExact, touchWarm, evictWarm, missingMetaTools } from "./metrics.js";
37
37
  import { tierForBudget } from "./budget.js";
38
38
  import { readState, writeState } from "./storage.js";
39
+ import { expandQuery, fallbackCatalog, createSearchCache, recordDiscoveries, serializeDiscoveries, deserializeDiscoveries } from "./ux.js";
39
40
  import { ChainGuard, verdict } from "./chainguard.js";
40
41
  import { matchCategory } from "./category.js";
41
42
  import { toonifyValue } from "./toonify.js";
@@ -83,6 +84,10 @@ export const Config = z.object({
83
84
  .description("分级披露预算(字节):0=关闭。开启后可见工具 schema 估算字节超预算时,动态段按 完整schema→name+desc→仅name→折叠进catalog 逐级降级(core/hot 永不降级)"),
84
85
  maxWarmTools: z.number().min(0).max(50).default(0)
85
86
  .description("warm LRU 上限:tools_search/schema 发现或折叠后被调用的工具进入 warm 集合,下一轮注入(完整 schema);达上限逐出最久未用;0=关闭(默认关,无配置升级逐字节等价,显式开启才启用)"),
87
+ fallbackCatalogSize: z.number().min(0).max(200).default(30)
88
+ .description("P0: tools_search 零匹配时回退的轻目录条数(name+80字描述,名字典序);0=关闭回退(返回空=旧行为)"),
89
+ queryExpandEnabled: z.boolean().default(true)
90
+ .description("P0: 中文意图→英文同义词扩展(只加词不改原词,扩大 BM25/语义召回;精确名匹配不受影响)"),
86
91
  });
87
92
 
88
93
  const DEFAULTS = {
@@ -119,6 +124,8 @@ const DEFAULTS = {
119
124
  embedModel: "bge-m3",
120
125
  disclosureBudget: 0, // v0.2.2: 分级披露预算(0=关闭)
121
126
  maxWarmTools: 0, // v0.2.2: warm LRU 上限(0=关闭,默认关=无配置升级逐字节等价)
127
+ fallbackCatalogSize: 30, // P0: 零匹配回退轻目录条数(0=关闭)
128
+ queryExpandEnabled: true, // P0: 中文→英文 query 扩展
122
129
  };
123
130
 
124
131
  function feedbackPath(cfg) {
@@ -330,7 +337,8 @@ export function apply(ctx, config) {
330
337
  };
331
338
  const persistWarmState = () => {
332
339
  if (!warmEnabled) return;
333
- const payload = { warm: [...warm.entries()], ts: Date.now() };
340
+ // merge 写:与 discoveries 共用 state 文件,整写会互抹(Standards 轴 P1)。
341
+ const payload = { ...readState(activeStateFile, {}), warm: [...warm.entries()], ts: Date.now() };
334
342
  let ok = writeState(activeStateFile, payload);
335
343
  if (!ok) {
336
344
  // 首选目录不可写 → 降到 ~/.dsh/state/
@@ -340,6 +348,39 @@ export function apply(ctx, config) {
340
348
  };
341
349
  restoreWarm();
342
350
 
351
+ // P0-④: 发现率统计(独立于 warm 门控——maxWarmTools=0 时统计照常工作)。
352
+ // 与 warm 共用同一个 state 文件;落盘节流 30s(工具输出非注入面,频率低)。
353
+ let discoveries = new Map();
354
+ let lastPersistTs = 0;
355
+ const restoreDiscoveries = () => {
356
+ let cloud = readState(activeStateFile, null);
357
+ if (!cloud) {
358
+ activeStateFile = fallbackStateFile();
359
+ cloud = readState(activeStateFile, null);
360
+ }
361
+ discoveries = deserializeDiscoveries(cloud && Array.isArray(cloud.discoveries) ? cloud.discoveries : null);
362
+ };
363
+ const persistDiscoveries = () => {
364
+ const now = Date.now();
365
+ if (now - lastPersistTs < 30000) return; // 节流:30s 内只写一次
366
+ lastPersistTs = now;
367
+ // merge 写:与 warm 共用 state 文件,整写会互抹(Standards 轴 P1)。
368
+ const payload = { ...readState(activeStateFile, {}), discoveries: serializeDiscoveries(discoveries), ts: now };
369
+ let ok = writeState(activeStateFile, payload);
370
+ if (!ok) {
371
+ activeStateFile = fallbackStateFile();
372
+ writeState(activeStateFile, payload);
373
+ }
374
+ };
375
+ restoreDiscoveries();
376
+ if (discoveries.size > 0) {
377
+ const top = serializeDiscoveries(discoveries, 5).map((e) => `${e.name}(${e.count})`).join(", ");
378
+ logger.info("discovery stats restored: %d tools, top: %s", discoveries.size, top);
379
+ }
380
+
381
+ // P0-②: 检索结果缓存(同 query 60s 内稳定;LRU 200 条;进程级共享)。
382
+ const searchCache = createSearchCache(200, 60000);
383
+
343
384
  // "mcp__viking__remember" → "mcp__viking"; plain tools ("tool-bash") stay
344
385
  // as themselves (single segment survives slice(0,2)).
345
386
  const serverOf = (name) => String(name).split("__").slice(0, 2).join("__");
@@ -440,6 +481,7 @@ export function apply(ctx, config) {
440
481
  },
441
482
  },
442
483
  total: { type: "integer", required: true },
484
+ fallback: { type: "boolean", description: "true = 零匹配,结果回退为按名字典序的轻目录" },
443
485
  },
444
486
  };
445
487
  const toolsSearch = defineTool({
@@ -461,15 +503,27 @@ export function apply(ctx, config) {
461
503
  output: { schema: outputSchema, render: (_a, v) => [{ type: "text", text: JSON.stringify(v, null, 2) }] },
462
504
  isConcurrencySafe: () => true,
463
505
  async execute(args) {
464
- const q = String(args.query || "");
465
- const lim = args.limit ?? 8;
466
- if (!index || !q) return { query: q, results: [], total: 0 };
506
+ // 整体 fail-open 兜底(Spec 轴 P2):任何未来 helper 意外抛错 → 空结果
507
+ // 而非硬失败,保持"折叠绝不误伤能力"的底线。
508
+ try {
509
+ const q = String(args.query || "");
510
+ const lim = args.limit ?? 8;
511
+ if (!index) return { query: q, results: [], total: 0 };
512
+ // P0-②: 同 query 内容指纹的结果缓存——重复搜索返回同一结果集(漂移的
513
+ // 最小修)。进程级共享(非单会话隔离);空 query("*" 语义)不走缓存。
514
+ const cacheKey = `${lim}|${q}`;
515
+ if (q) {
516
+ const cached = searchCache.get(cacheKey);
517
+ if (cached) return cached;
518
+ }
519
+ // P0-③: 中文意图→英文同义词扩展(只加词不改原词;精确名匹配用原 q)。
520
+ const eq = cfg.queryExpandEnabled !== false ? expandQuery(q) : q;
467
521
  // v0.2.1: exact-name > name-substring > BM25 priority (deterministic
468
522
  // fallback chain, borrowed from Hermes-style tool search).
469
523
  const bm25Hits = prioritizeExact(
470
524
  allTools,
471
525
  q,
472
- search(index, q, lim * 2).map((i) => ({ id: allTools[i].name })),
526
+ search(index, eq, lim * 2).map((i) => ({ id: allTools[i].name })),
473
527
  );
474
528
  let fused = bm25Hits;
475
529
  // Semantic leg (P0-1): RRF-fuse BM25 with local bge-m3 similarity.
@@ -480,7 +534,7 @@ export function apply(ctx, config) {
480
534
  const sem = await getSemanticIndex();
481
535
  if (sem?.available) {
482
536
  const docs = allTools.map((t) => ({ id: t.name, text: `${t.name} ${t.description || ""}` }));
483
- const semHits = await searchSemantic(sem.vectors, docs, q);
537
+ const semHits = await searchSemantic(sem.vectors, docs, eq);
484
538
  fused = rrfFuse(bm25Hits, semHits.slice(0, lim * 2), lim);
485
539
  }
486
540
  } catch (e) {
@@ -488,7 +542,7 @@ export function apply(ctx, config) {
488
542
  }
489
543
  }
490
544
  const byName = new Map(allTools.map((t) => [t.name, t]));
491
- const results = fused.map((h) => {
545
+ let results = fused.map((h) => {
492
546
  const t = byName.get(h.id) || {};
493
547
  return {
494
548
  name: h.id,
@@ -496,13 +550,31 @@ export function apply(ctx, config) {
496
550
  server: serverOf(h.id),
497
551
  };
498
552
  });
553
+ // P0-①: 零匹配回退轻目录(name+80字描述,名字典序)——根治「搜词不对
554
+ // 就以为没有该能力」。fallbackCatalogSize=0 关闭(返回空=旧行为)。
555
+ // total 在回退时=全量目录大小(而非列出条数),避免模型误以为目录总容量=limit。
556
+ let fallback = false;
557
+ if (results.length === 0 && cfg.fallbackCatalogSize > 0) {
558
+ results = fallbackCatalog(allTools, cfg.fallbackCatalogSize, serverOf);
559
+ fallback = true;
560
+ }
499
561
  // v0.2.2: 被搜到的工具名进入 warm 集合,下一轮注入完整 schema。
500
562
  touchWarmNames(results.map((r) => r.name));
501
- return {
563
+ // P0-④: 发现率统计(节流落盘,低频工具名单反哺描述改进)。
564
+ recordDiscoveries(discoveries, results.map((r) => r.name));
565
+ persistDiscoveries();
566
+ const out = {
502
567
  query: q,
503
568
  results,
504
- total: fused.length,
569
+ total: fallback ? allTools.length : results.length,
570
+ ...(fallback ? { fallback: true } : {}),
505
571
  };
572
+ if (q) searchCache.set(cacheKey, out);
573
+ return out;
574
+ } catch (e) {
575
+ logger.warn("tools_search failed (%s) — empty results", e?.message);
576
+ return { query: String(args.query || ""), results: [], total: 0 };
577
+ }
506
578
  },
507
579
  });
508
580
  try {
package/lib/ux.js ADDED
@@ -0,0 +1,178 @@
1
+ /**
2
+ * ux.js — P0 折叠体验改进(2026-08-30 第二轮调研落地,来源见 AGENTS.md §0.3)。
3
+ *
4
+ * 四个纯函数/工厂,全部不触碰注入面(每轮 prompt 字节零变化,兼容红线保持):
5
+ * ① expandQuery 中文高频意图 → 追加英文检索词(只加词不改原词;BM25 召回
6
+ * 更宽,精确名匹配 prioritizeExact 仍用原 query,不受影响)
7
+ * ② fallbackCatalog tools_search 零匹配时回退的全量轻目录(name + 80 字描述,
8
+ * 按名字典序稳定排序)——根治「搜词不对就以为没有」
9
+ * ③ createSearchCache 同 query 内容指纹的结果缓存(固定 TTL + LRU 上限)——
10
+ * 同会话重复搜索返回同一结果集(漂移的最小修)
11
+ * ④ recordDiscoveries 发现率统计(name→count,落盘可恢复)——低频工具名单
12
+ * 反哺描述改进(官方「监控发现率」建议的本地等价物)
13
+ */
14
+
15
+ /* ------------------------- ① query 扩展词表 ------------------------- */
16
+
17
+ /** 中文高频意图 → 英文检索词。只做「包含即追加」,不做分词/替换。 */
18
+ const EXPAND = {
19
+ 搜索: "search find lookup",
20
+ 查找: "search find lookup",
21
+ 文件: "file files read write edit",
22
+ 图片: "image picture photo vision ocr",
23
+ 截图: "screenshot screen capture image",
24
+ 识别: "ocr recognize extract text",
25
+ 文字: "text ocr recognize",
26
+ 数据库: "database db sql query",
27
+ 查询: "query select fetch search",
28
+ 网络: "network web http fetch url",
29
+ 浏览器: "browser chrome page navigate",
30
+ 下载: "download fetch get",
31
+ 上传: "upload put push",
32
+ 发布: "publish deploy release",
33
+ 部署: "deploy release publish",
34
+ 测试: "test run verify",
35
+ 运行: "run execute start",
36
+ 执行: "run execute command",
37
+ 命令: "command shell exec terminal",
38
+ 安装: "install setup configure",
39
+ 配置: "config configure setup",
40
+ 错误: "error fail exception debug",
41
+ 修复: "fix repair patch debug",
42
+ 删除: "delete remove rm",
43
+ 创建: "create new make init",
44
+ 修改: "edit update modify change",
45
+ 查看: "view show list inspect read",
46
+ 列表: "list enumerate show",
47
+ 记忆: "memory remember recall viking",
48
+ 技能: "skill search catalog",
49
+ 工具: "tool search schema",
50
+ 定时: "schedule cron timer",
51
+ 提醒: "remind schedule alert",
52
+ 邮件: "email mail send",
53
+ 键盘: "keyboard type input",
54
+ 鼠标: "mouse click move",
55
+ 窗口: "window open close",
56
+ 进程: "process task list kill",
57
+ 服务: "service server daemon",
58
+ 日志: "log trace tail",
59
+ 监控: "monitor watch observe",
60
+ 版本: "version release tag git",
61
+ 提交: "commit push git",
62
+ 分支: "branch git merge",
63
+ 仓库: "repo repository git",
64
+ 会话: "session agent",
65
+ 对话: "chat session message",
66
+ };
67
+
68
+ /**
69
+ * 中文意图 → 扩展查询串:命中的每个中文词追加其英文同义词组到尾部。
70
+ * 无中文(或词表未命中)时原样返回——旧行为零变化。
71
+ * @param {string} q
72
+ * @returns {string}
73
+ */
74
+ export function expandQuery(q) {
75
+ const s = String(q || "").trim();
76
+ if (!s) return s;
77
+ const extra = [];
78
+ for (const [cn, en] of Object.entries(EXPAND)) {
79
+ if (s.includes(cn)) extra.push(en);
80
+ }
81
+ return extra.length ? `${s} ${extra.join(" ")}` : s;
82
+ }
83
+
84
+ /* ------------------------- ② 零匹配回退轻目录 ------------------------- */
85
+
86
+ /**
87
+ * 轻目录:按名字典序排序取前 limit 个(name + 描述截 80 + server)。
88
+ * limit<=0 → [](关闭回退,行为与旧版一致)。
89
+ * @param {Array<{name:string,description?:string}>} allTools
90
+ * @param {number} limit
91
+ * @param {(name:string)=>string} [serverOf]
92
+ * @returns {Array<{name:string,description:string,server:string}>}
93
+ */
94
+ export function fallbackCatalog(allTools, limit, serverOf) {
95
+ const lim = Math.max(0, Number(limit) || 0);
96
+ if (!lim || !Array.isArray(allTools) || allTools.length === 0) return [];
97
+ const svc = typeof serverOf === "function" ? serverOf : () => "";
98
+ return [...allTools]
99
+ .sort((a, b) => String(a.name).localeCompare(String(b.name)))
100
+ .slice(0, lim)
101
+ .map((t) => ({
102
+ name: String(t.name || ""),
103
+ description: String(t.description || "").slice(0, 80),
104
+ server: svc(t.name),
105
+ }));
106
+ }
107
+
108
+ /* ------------------------- ③ 检索结果缓存 ------------------------- */
109
+
110
+ /**
111
+ * 结果缓存工厂:同 key 在 TTL 内返回同一结果(确定性),超 TTL 或超上限逐出。
112
+ * @param {number} [maxSize] LRU 上限(默认 200)
113
+ * @param {number} [ttlMs] 有效期(默认 60s)
114
+ */
115
+ export function createSearchCache(maxSize = 200, ttlMs = 60000) {
116
+ const map = new Map();
117
+ return {
118
+ get(key) {
119
+ const e = map.get(key);
120
+ if (!e) return null;
121
+ if (Date.now() - e.ts > ttlMs) {
122
+ map.delete(key);
123
+ return null;
124
+ }
125
+ return e.value;
126
+ },
127
+ set(key, value) {
128
+ map.set(key, { ts: Date.now(), value });
129
+ if (map.size > maxSize) {
130
+ const oldest = map.keys().next().value;
131
+ if (oldest !== undefined) map.delete(oldest);
132
+ }
133
+ },
134
+ size() {
135
+ return map.size;
136
+ },
137
+ };
138
+ }
139
+
140
+ /* ------------------------- ④ 发现率统计 ------------------------- */
141
+
142
+ /**
143
+ * 记录一次发现的工具名(name→count)。
144
+ * @param {Map<string,number>} stats
145
+ * @param {Array<string>} names
146
+ * @returns {number} 当前去重工具数
147
+ */
148
+ export function recordDiscoveries(stats, names) {
149
+ const list = Array.isArray(names) ? names.filter(Boolean) : [];
150
+ for (const n of list) stats.set(n, (stats.get(n) || 0) + 1);
151
+ return stats.size;
152
+ }
153
+
154
+ /**
155
+ * 序列化为按 count 降序的数组(cap 截断),供落盘。
156
+ * @param {Map<string,number>} stats
157
+ * @param {number} [cap]
158
+ */
159
+ export function serializeDiscoveries(stats, cap = 200) {
160
+ return [...stats.entries()]
161
+ .sort((a, b) => b[1] - a[1])
162
+ .slice(0, Math.max(1, cap))
163
+ .map(([name, count]) => ({ name, count }));
164
+ }
165
+
166
+ /**
167
+ * 从落盘数组恢复 Map;坏条目跳过(fail-safe)。
168
+ * @param {Array<{name:string,count:number}>} [list]
169
+ */
170
+ export function deserializeDiscoveries(list) {
171
+ const m = new Map();
172
+ for (const e of list || []) {
173
+ if (e && typeof e.name === "string" && e.name.length > 0 && Number.isFinite(e.count) && e.count > 0) {
174
+ m.set(e.name, e.count);
175
+ }
176
+ }
177
+ return m;
178
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-tool-folder",
3
- "version": "0.2.2",
3
+ "version": "0.2.3",
4
4
  "description": "Fold the DSH tool surface per request + ChainGuard firewall (high-risk block + exfil-chain detection + anti-obfuscation) + BM25/bge-m3 hybrid tools_search. Shrinks schema tokens 80-90% while keeping selection accuracy. v0.2.0 adds a semantic retrieval leg (local Ollama bge-m3, RRF hybrid) and ChainGuard obfuscation detection (concat-rebuild / -enc / certutil / bitsadmin / homoglyphs).",
5
5
  "keywords": [
6
6
  "dsh-plugin",
@@ -45,4 +45,4 @@
45
45
  ".": "./lib/index.js",
46
46
  "./lib/*": "./lib/*"
47
47
  }
48
- }
48
+ }