dsh-knit 0.5.1 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +115 -18
- package/README.md +105 -17
- package/SECURITY.md +51 -0
- package/package.json +7 -4
- package/src/client/client.js +218 -49
- package/src/host/index.js +42 -8
- package/src/host/relevance.js +463 -67
- package/src/host/tool.js +424 -0
- package/test/client.test.mjs +191 -2
- package/test/eval/fixture.mjs +439 -0
- package/test/eval/legacy.mjs +115 -0
- package/test/eval.test.mjs +80 -0
- package/test/harness.mjs +1 -1
- package/test/host-http.test.mjs +21 -8
- package/test/host.test.mjs +117 -3
- package/test/i18n.test.mjs +21 -2
- package/test/label.test.mjs +149 -0
- package/test/path.test.mjs +150 -1
- package/test/peek.test.mjs +3 -1
- package/test/security.test.mjs +148 -0
- package/test/tool.test.mjs +472 -0
package/src/host/tool.js
ADDED
|
@@ -0,0 +1,424 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Knit · agent 文档工具(v0.7)
|
|
3
|
+
*
|
|
4
|
+
* 把一个**只读**工具交给模型:`knit_docs` —— 列出这个项目里已有的 Markdown 文档,
|
|
5
|
+
* 按与当前对话(或调用方给出的 query)的相关性排序。
|
|
6
|
+
*
|
|
7
|
+
* 解决的问题:agent 想引用项目里已有的文档时只能靠猜路径、或者把 glob 出来的
|
|
8
|
+
* 路径一个个 read 试过去。而这份排序 Knit 每一轮**已经算好了**(面板在用),
|
|
9
|
+
* 这里只是同一个结果**再开一个口子给模型**。
|
|
10
|
+
*
|
|
11
|
+
* ── 为什么不用 `defineTool` ───────────────────────────
|
|
12
|
+
*
|
|
13
|
+
* 官方的写法是 `import { defineTool } from '@deepseek-ai/dsh-tools'`。**这个包不能引**:
|
|
14
|
+
* Knit 是被 `link:` 挂进 DSH profile 的,它的真实路径在 profile 的 `node_modules` **之外**,
|
|
15
|
+
* 所以裸 Node 解析不到 `@deepseek-ai/*`(实测 `ERR_MODULE_NOT_FOUND`)。
|
|
16
|
+
* 本机另外两个 `link:` 的开发插件同样是零依赖、从不 import DSH 的包。
|
|
17
|
+
*
|
|
18
|
+
* 所以这里**手写 `ToolDefinition`**。这不是猜:`defineTool` 的实现只是把参数
|
|
19
|
+
* 规格编译成 JSON Schema 再包一层校验,产物就是下面这两个常量 —— 它们是
|
|
20
|
+
* 用真实的 `parameterSchemaSpecToJsonSchema` / `valueSchemaSpecToJsonSchema`
|
|
21
|
+
* 跑出来的结果照抄的。丢掉的那层参数校验由 `clampLimit` 等显式检查补上。
|
|
22
|
+
*
|
|
23
|
+
* 这样 Knit 保持**零依赖**(README 的承诺、也是装完不用 npm install 的前提),
|
|
24
|
+
* 且在「开发目录 / clone / 装进 node_modules」三种布局下都能跑。
|
|
25
|
+
*
|
|
26
|
+
* ── 安全 ─────────────────────────────────────────────
|
|
27
|
+
*
|
|
28
|
+
* 只读。复用的是宿主那条已经加固过的扫描路径(工作区内、跳过 node_modules / .git / dist),
|
|
29
|
+
* **不新增任何 HTTP 路由**,攻击面没有变大。结果里只出现工作区**相对**路径。
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
/** 工具名。`knit_` 前缀是生态惯例(`tiddlywiki_*`、`memory_*`),避免撞名。 */
|
|
33
|
+
export const TOOL_NAME = 'knit_docs'
|
|
34
|
+
|
|
35
|
+
/** 默认返回几条。 */
|
|
36
|
+
export const DEFAULT_LIMIT = 5
|
|
37
|
+
|
|
38
|
+
/** 上限。 */
|
|
39
|
+
export const MAX_LIMIT = 20
|
|
40
|
+
|
|
41
|
+
/** 结果里摘要再截一次(宿主的首段摘要本身是 60 字,这里防的是极端长首段)。 */
|
|
42
|
+
const SUMMARY_CHARS = 90
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* 命中段落的上限(v0.11)。
|
|
46
|
+
*
|
|
47
|
+
* 取值依据是实测:`knit_docs` 一次输出约 710 字符,而**一篇文档平均 12,930 字符**。
|
|
48
|
+
* 每篇多 200 字 ≈ 一篇文档的 7.7%,而它想省掉的是整整一次 `read`。
|
|
49
|
+
* 见 `Knit_SDD-v0.11-knit_docs命中段落.md` §一。
|
|
50
|
+
*/
|
|
51
|
+
const SNIPPET_CHARS = 200
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* 只在原文的**前 2500 字**里找命中段落。
|
|
55
|
+
*
|
|
56
|
+
* 必须与 `index.js` 的 `HAYSTACK_CHARS` 一致 —— 评分只看这个窗口,
|
|
57
|
+
* 若在这里找窗口外的内容,会出现「排上来了、但段落里没有命中词」的自相矛盾。
|
|
58
|
+
*/
|
|
59
|
+
const SNIPPET_WINDOW = 2500
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* 模型面向的描述。**必须短** —— 它会进每一次请求的系统提示词。
|
|
63
|
+
*
|
|
64
|
+
* v0.8 加过「Reports how many exist in total」,**但真机验证显示没用**:
|
|
65
|
+
* agent 照样自己 `grep -c` 数一遍关键词重新排名(`Knit_SDD-v0.8` §8.4)。
|
|
66
|
+
* 原因是它**不认这个排名**,不是怕漏。
|
|
67
|
+
*
|
|
68
|
+
* v0.9 换成直接说明**这个排名比它自己数准** —— 依据是 `tools/scale-benchmark.mjs`
|
|
69
|
+
* 的实测(同一套词、同一个可判定任务、N = 20/60/180/540):
|
|
70
|
+
*
|
|
71
|
+
* 路线 文件名说得清 文件名看不出 MRR 随规模
|
|
72
|
+
* Knit BM25 100% 100% 1.000(不变)
|
|
73
|
+
* grep -c 计数 17% 0% 0.313 → 0.089
|
|
74
|
+
* 只看文件名 100% 0% 0.602
|
|
75
|
+
*
|
|
76
|
+
* 所以描述要点名两件它自己做不到的事:**稀有词权重**(不是数次数)
|
|
77
|
+
* 与**不依赖文件名**。最后一句是行为引导 —— 直说「别自己来」。
|
|
78
|
+
*/
|
|
79
|
+
const DESCRIPTION = 'List Markdown documents that already exist in this project, '
|
|
80
|
+
+ 'ranked by relevance to the current conversation (or to an explicit query). '
|
|
81
|
+
+ 'The ranking weighs rare terms above common ones and normalizes document length, '
|
|
82
|
+
+ 'so it beats matching filenames or counting keyword hits — prefer it to doing that yourself. '
|
|
83
|
+
+ 'Reads the workspace only; stores nothing and calls no model.'
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* 参数 schema。与 `defineTool` 的编译产物逐字一致
|
|
87
|
+
* (两个参数都可选,所以没有 `required`,根对象也没有 `additionalProperties`)。
|
|
88
|
+
*/
|
|
89
|
+
const PARAMETERS = {
|
|
90
|
+
type: 'object',
|
|
91
|
+
properties: {
|
|
92
|
+
query: {
|
|
93
|
+
type: 'string',
|
|
94
|
+
description: 'Optional search text. Omit to rank by the current conversation.',
|
|
95
|
+
},
|
|
96
|
+
limit: {
|
|
97
|
+
type: 'integer',
|
|
98
|
+
description: `How many documents to return (1-${MAX_LIMIT}, default ${DEFAULT_LIMIT}).`,
|
|
99
|
+
},
|
|
100
|
+
},
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* 输出 schema。同样照抄编译产物 —— 注意**没有 `score`**:
|
|
105
|
+
* 相关度是**相对**分数(永远有一篇 100%,且每次刷新可能换人当),
|
|
106
|
+
* 面板里就不显示它,给模型看只会更糟 —— 它会把 86 当成绝对置信度去推理。
|
|
107
|
+
* **顺序即相关度。**
|
|
108
|
+
*/
|
|
109
|
+
const OUTPUT_SCHEMA = {
|
|
110
|
+
type: 'object',
|
|
111
|
+
additionalProperties: false,
|
|
112
|
+
properties: {
|
|
113
|
+
mode: { type: 'string', enum: ['relevance', 'time'] },
|
|
114
|
+
topic: { type: 'string' },
|
|
115
|
+
// 工作区里**一共有多少篇**(不是返回了几条)。
|
|
116
|
+
// 给这个数是为了让模型知道结果不是「随便挑的几条」,不必再自己 glob 一遍
|
|
117
|
+
// 做交叉验证 —— v0.8,依据是真机验收里观察到的行为。
|
|
118
|
+
total: { type: 'integer' },
|
|
119
|
+
docs: {
|
|
120
|
+
type: 'array',
|
|
121
|
+
items: {
|
|
122
|
+
type: 'object',
|
|
123
|
+
additionalProperties: false,
|
|
124
|
+
properties: {
|
|
125
|
+
rel: { type: 'string' },
|
|
126
|
+
title: { type: 'string' },
|
|
127
|
+
summary: { type: 'string' },
|
|
128
|
+
mtimeMs: { type: 'integer' },
|
|
129
|
+
// v0.11:命中的那一小段**原文**(不是整篇)。**可选** ——
|
|
130
|
+
// 时间序模式没有命中词,抽不出来就不带这个字段,
|
|
131
|
+
// 而不是给个空串假装有。
|
|
132
|
+
snippet: { type: 'string' },
|
|
133
|
+
},
|
|
134
|
+
required: ['rel', 'title', 'summary', 'mtimeMs'],
|
|
135
|
+
},
|
|
136
|
+
},
|
|
137
|
+
},
|
|
138
|
+
required: ['mode', 'topic', 'total', 'docs'],
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* 把 `limit` 夹到合法区间。
|
|
143
|
+
*
|
|
144
|
+
* 官方 `defineTool` 会替我们做参数校验,手写定义没有那层,所以在这里补上。
|
|
145
|
+
* 非法值一律**回落到默认值**而不是抛错 —— 一个越界的 `limit` 不值得让整次调用失败。
|
|
146
|
+
*
|
|
147
|
+
* @param {unknown} value - 模型给的 limit
|
|
148
|
+
* @returns {number} 1..MAX_LIMIT 之间的整数
|
|
149
|
+
*/
|
|
150
|
+
export function clampLimit(value) {
|
|
151
|
+
if (typeof value !== 'number' || !Number.isFinite(value)) return DEFAULT_LIMIT
|
|
152
|
+
const n = Math.trunc(value)
|
|
153
|
+
if (n < 1) return 1
|
|
154
|
+
if (n > MAX_LIMIT) return MAX_LIMIT
|
|
155
|
+
return n
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* 从执行上下文里取调用方的工作区根与会话 id。
|
|
160
|
+
*
|
|
161
|
+
* `exec.agent.session.header` 上同时有 `cwd` 与 `id`(见 `@deepseek-ai/dsh-session` 的
|
|
162
|
+
* `SessionHeader`)。**id 必须拿到**:宿主的关键词缓存按 sessionId 键控,
|
|
163
|
+
* 传空串会让不同会话共用一份缓存。
|
|
164
|
+
*
|
|
165
|
+
* @param {object|undefined} exec - 工具执行上下文
|
|
166
|
+
* @returns {{root: string, sessionId: string, session: object|undefined}} 三者都可能是空
|
|
167
|
+
*/
|
|
168
|
+
export function agentScope(exec) {
|
|
169
|
+
const session = exec && exec.agent ? exec.agent.session : undefined
|
|
170
|
+
const header = session && session.header ? session.header : undefined
|
|
171
|
+
const root = header && typeof header.cwd === 'string' ? header.cwd : ''
|
|
172
|
+
const sessionId = header && typeof header.id === 'string' ? header.id : ''
|
|
173
|
+
return { root, sessionId, session }
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* 把摘要压成一行并截断 —— 一条结果不该占掉几十行。
|
|
178
|
+
* @param {unknown} text - 摘要
|
|
179
|
+
* @returns {string} 单行摘要
|
|
180
|
+
*/
|
|
181
|
+
/**
|
|
182
|
+
* 压成单行并截断。
|
|
183
|
+
*
|
|
184
|
+
* ⚠️ **截断上限是参数,不是常量** —— v0.11 加命中段落时踩过一次:
|
|
185
|
+
* 段落提取出来是 200 字,若复用只认 `SUMMARY_CHARS`(90) 的 `oneLine`,
|
|
186
|
+
* 会被二次截掉一半,而且**测试不会报错**(输出仍然是合法的短文本)。
|
|
187
|
+
*
|
|
188
|
+
* @param {unknown} text - 任意文本
|
|
189
|
+
* @param {number} cap - 上限字符数
|
|
190
|
+
* @returns {string} 单行文本
|
|
191
|
+
*/
|
|
192
|
+
function flatten(text, cap) {
|
|
193
|
+
const flat = String(text == null ? '' : text).replace(/\s+/g, ' ').trim()
|
|
194
|
+
return flat.length > cap ? `${flat.slice(0, cap)}…` : flat
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function oneLine(text) {
|
|
198
|
+
return flatten(text, SUMMARY_CHARS)
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* 从**原文**里挑出「命中的那一段」,给模型判断「要不要读整篇」用(v0.11)。
|
|
203
|
+
*
|
|
204
|
+
* 三条设计约束,每条都有原因:
|
|
205
|
+
*
|
|
206
|
+
* 1. **在原文上切,不在 `haystack` 上切。** `haystack.body` 是 `.toLowerCase()` 过的
|
|
207
|
+
* (`index.js:240`),在它上面切会把 `BM25` 变成 `bm25` ——
|
|
208
|
+
* 与「标签是你自己打的字,大小写原样保留」这条既有承诺直接冲突。
|
|
209
|
+
* 2. **只看前 `SNIPPET_WINDOW` 字**,与评分窗口一致,避免「排上来但段落里没命中词」。
|
|
210
|
+
* 3. **块太长时以命中词为中心截**,不是从头截 —— 否则命中那句话可能正好被截掉,
|
|
211
|
+
* 段落就白给了。
|
|
212
|
+
* 4. **跳过与标题重复的块。** 拿真实工作区试跑时发现的:一篇文档的 H1 标题里含全部命中词,
|
|
213
|
+
* 于是「命中词最多的块」就是标题本身 —— 而标题**第 1 行已经给过了**。
|
|
214
|
+
* 这种段落是纯浪费,正是要避免的「负收益」情形。
|
|
215
|
+
*
|
|
216
|
+
* 纯函数:不读盘、不看时钟、无副作用。抽不出命中段落时返回空串
|
|
217
|
+
* (**不编造** —— 「没有命中」和「命中在别处」都不该被伪装成有一段)。
|
|
218
|
+
*
|
|
219
|
+
* @param {string} text - 文档**原文**
|
|
220
|
+
* @param {string[]} terms - 命中词(来自 `scan()` 的 `keywords`,即语料里真实存在的词)
|
|
221
|
+
* @param {{title?: string}} [options] - `title` 用于排除「与标题重复」的块
|
|
222
|
+
* @returns {string} 命中段落(已压成单行、截断),或空串
|
|
223
|
+
*/
|
|
224
|
+
export function pickSnippet(text, terms, options = {}) {
|
|
225
|
+
const source = String(text == null ? '' : text)
|
|
226
|
+
const words = (Array.isArray(terms) ? terms : [])
|
|
227
|
+
.map((term) => String(term == null ? '' : term).trim().toLowerCase())
|
|
228
|
+
.filter(Boolean)
|
|
229
|
+
if (!source || words.length === 0) return ''
|
|
230
|
+
|
|
231
|
+
// 归一化只用于**比较**:去掉 Markdown 标题号、强调号、表格竖线,压平空白,小写
|
|
232
|
+
const norm = (s) => String(s).replace(/[#*|`>\s]+/g, ' ').trim().toLowerCase()
|
|
233
|
+
const titleNorm = norm(options.title || '')
|
|
234
|
+
|
|
235
|
+
const window = source.slice(0, SNIPPET_WINDOW)
|
|
236
|
+
|
|
237
|
+
// 按空行切块 —— 纯字符串运算,不解析 Markdown 结构
|
|
238
|
+
const blocks = window.split(/\n\s*\n/).map((block) => block.trim()).filter(Boolean)
|
|
239
|
+
if (blocks.length === 0) return ''
|
|
240
|
+
|
|
241
|
+
// 选**命中词种数最多**的那块;并列取靠前的(不给后面的块不该有的优势)
|
|
242
|
+
const scored = blocks.map((block) => {
|
|
243
|
+
const lower = block.toLowerCase()
|
|
244
|
+
let hits = 0
|
|
245
|
+
for (const word of words) if (lower.includes(word)) hits += 1
|
|
246
|
+
return { block, hits, norm: norm(block) }
|
|
247
|
+
})
|
|
248
|
+
|
|
249
|
+
// 跳过「与标题重复」的块(见 JSDoc 第 4 条)
|
|
250
|
+
const usable = scored.filter((item) => !(titleNorm && item.norm && titleNorm.includes(item.norm)))
|
|
251
|
+
if (usable.length === 0) return ''
|
|
252
|
+
|
|
253
|
+
let best = null
|
|
254
|
+
for (const item of usable) {
|
|
255
|
+
if (item.hits > 0 && (best === null || item.hits > best.hits)) best = item
|
|
256
|
+
}
|
|
257
|
+
// 一块都没命中 → 返回空串,而不是退化成「随便给第一段」
|
|
258
|
+
if (best === null) return ''
|
|
259
|
+
|
|
260
|
+
const flat = best.block.replace(/\s+/g, ' ').trim()
|
|
261
|
+
if (flat.length <= SNIPPET_CHARS) return flat
|
|
262
|
+
|
|
263
|
+
const lowerFlat = flat.toLowerCase()
|
|
264
|
+
let at = -1
|
|
265
|
+
for (const word of words) {
|
|
266
|
+
const found = lowerFlat.indexOf(word)
|
|
267
|
+
if (found >= 0 && (at < 0 || found < at)) at = found
|
|
268
|
+
}
|
|
269
|
+
const maxStart = flat.length - SNIPPET_CHARS
|
|
270
|
+
const start = at < 0 ? 0 : Math.max(0, Math.min(at - Math.floor(SNIPPET_CHARS / 3), maxStart))
|
|
271
|
+
const head = start > 0 ? '…' : ''
|
|
272
|
+
const tail = start < maxStart ? '…' : ''
|
|
273
|
+
return `${head}${flat.slice(start, start + SNIPPET_CHARS).trim()}${tail}`
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* 把工具结果渲染成模型看的文本。
|
|
278
|
+
*
|
|
279
|
+
* **英文**:模型面向文本要的是词表稳定,不跟随界面语言 —— 官方工具
|
|
280
|
+
* (`todo_write`、`present`)也都是英文硬编码。这不是 i18n 违约:
|
|
281
|
+
* AGENTS.md §4.5 那条规则管的是**用户可见**文案,而这里由模型消费。
|
|
282
|
+
*
|
|
283
|
+
* **头部要说清「一共多少篇」**(v0.8):真机验收里 agent 每次拿到结果都还要
|
|
284
|
+
* 自己 `find` 一遍来确认没漏 —— 把总数写在第一行,是为了消掉这次多余的调用。
|
|
285
|
+
*
|
|
286
|
+
* @param {{mode: string, topic: string, total?: number, docs: Array<object>}} value - 工具结果
|
|
287
|
+
* @returns {string} 文本
|
|
288
|
+
*/
|
|
289
|
+
export function renderToolText(value) {
|
|
290
|
+
const docs = value && Array.isArray(value.docs) ? value.docs : []
|
|
291
|
+
const total = Number.isInteger(value && value.total) ? value.total : docs.length
|
|
292
|
+
if (docs.length === 0) return 'No Markdown documents found in the workspace.'
|
|
293
|
+
|
|
294
|
+
// 「共 total 篇」回答「是不是漏了」;「IDF-weighted … not a keyword count or filename match」
|
|
295
|
+
// 回答「凭什么信这个排名」—— 后者才是 agent 自己再 grep 一遍的真正原因(v0.9)。
|
|
296
|
+
const scope = ` of ${total} Markdown document${total === 1 ? '' : 's'}`
|
|
297
|
+
|
|
298
|
+
// 退化情形要**如实说明**,与面板那行「对话内容还不足,暂按最新排序」同一个口径
|
|
299
|
+
const head = value.mode === 'time'
|
|
300
|
+
? `Not enough conversation to rank by relevance — showing the ${docs.length} most recently modified${scope}:`
|
|
301
|
+
: `Top ${docs.length}${scope} in this workspace, ranked by IDF-weighted relevance to `
|
|
302
|
+
+ `${value.topic ? `「${value.topic}」` : 'the current conversation'} `
|
|
303
|
+
+ '(rare terms weighted, length-normalised — not a keyword count or filename match):'
|
|
304
|
+
|
|
305
|
+
const lines = docs.map((doc, index) => {
|
|
306
|
+
const summary = oneLine(doc.summary)
|
|
307
|
+
// 命中段落(v0.11):给模型判断「要不要读整篇」用。
|
|
308
|
+
// 用一个 `match:` 前缀把它和**首段摘要**区分开 —— 两者都是一行压平的文本,
|
|
309
|
+
// 不加标记的话模型分不清哪行是什么。
|
|
310
|
+
const snippet = doc.snippet ? flatten(doc.snippet, SNIPPET_CHARS) : ''
|
|
311
|
+
return `${index + 1}. ${doc.rel} — ${doc.title}`
|
|
312
|
+
+ `${summary ? `\n ${summary}` : ''}`
|
|
313
|
+
+ `${snippet ? `\n match: ${snippet}` : ''}`
|
|
314
|
+
})
|
|
315
|
+
|
|
316
|
+
return [head, ...lines].join('\n')
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/**
|
|
320
|
+
* 造出 `knit_docs` 的 `ToolDefinition`。
|
|
321
|
+
*
|
|
322
|
+
* 形状与官方 `defineTool(...)` 的产物一致:`{ name, description, parameters, output, execute }`。
|
|
323
|
+
*
|
|
324
|
+
* @param {Function} scan - 宿主的扫描函数(注入进来,避免 index.js ↔ tool.js 循环 import)
|
|
325
|
+
* @param {Function} [read] - 宿主的单篇读取函数 `readDocument(root, rel)`。
|
|
326
|
+
* **同样注入**,理由与 `scan` 一样。**可选** —— 没给就只是不带命中段落,
|
|
327
|
+
* `knit_docs` 的其余行为一字不变(老调用方不会坏)。
|
|
328
|
+
* @returns {object} 工具定义
|
|
329
|
+
*/
|
|
330
|
+
export function knitDocsDefinition(scan, read) {
|
|
331
|
+
/**
|
|
332
|
+
* 给一篇文档抽命中段落。
|
|
333
|
+
*
|
|
334
|
+
* **任何失败都咽掉并返回空串** —— 抽不出段落只是少一条信息,
|
|
335
|
+
* 不该让整次工具调用失败(工具已经拿到了排序结果,那才是主要产出)。
|
|
336
|
+
*
|
|
337
|
+
* @param {string} root - 工作区根
|
|
338
|
+
* @param {string} rel - 相对路径
|
|
339
|
+
* @param {string[]} terms - 命中词
|
|
340
|
+
* @param {string} title - 这一篇的标题(用于排除「与标题重复」的块)
|
|
341
|
+
* @returns {Promise<string>} 命中段落或空串
|
|
342
|
+
*/
|
|
343
|
+
async function snippetFor(root, rel, terms, title) {
|
|
344
|
+
if (typeof read !== 'function' || !rel || terms.length === 0) return ''
|
|
345
|
+
try {
|
|
346
|
+
const doc = await read(root, rel)
|
|
347
|
+
if (!doc || doc.ok !== true) return ''
|
|
348
|
+
return pickSnippet(doc.text, terms, { title })
|
|
349
|
+
} catch {
|
|
350
|
+
return ''
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
return {
|
|
355
|
+
name: TOOL_NAME,
|
|
356
|
+
description: DESCRIPTION,
|
|
357
|
+
parameters: PARAMETERS,
|
|
358
|
+
output: {
|
|
359
|
+
schema: OUTPUT_SCHEMA,
|
|
360
|
+
render: (_args, value) => [{ type: 'text', text: renderToolText(value) }],
|
|
361
|
+
},
|
|
362
|
+
async execute(args, exec) {
|
|
363
|
+
const { root, sessionId, session } = agentScope(exec)
|
|
364
|
+
|
|
365
|
+
// 拿不到会话就**报错,不兜底**。HTTP 路由那条路会兜底 process.cwd(),
|
|
366
|
+
// 因为它要兼容不带 sessionId 的老客户端;工具没有这个包袱 ——
|
|
367
|
+
// 兜底到「DSH 进程的 cwd」只会扫到一个不相干的项目并返回它的文档。
|
|
368
|
+
// 宁可报错,也不要返回错的东西。
|
|
369
|
+
if (!root) throw new Error(`${TOOL_NAME} requires an owning agent session with a workspace root`)
|
|
370
|
+
|
|
371
|
+
const query = typeof (args && args.query) === 'string' ? args.query.trim() : ''
|
|
372
|
+
const limit = clampLimit(args && args.limit)
|
|
373
|
+
|
|
374
|
+
const payload = await scan(root, limit, {
|
|
375
|
+
session,
|
|
376
|
+
sessionId,
|
|
377
|
+
sort: 'relevance',
|
|
378
|
+
query,
|
|
379
|
+
})
|
|
380
|
+
|
|
381
|
+
// 命中词用 `scan()` 的 `keywords` —— 它是**语料里真实存在**的那批词
|
|
382
|
+
// (不是原始候选),所以拿它去原文里找段落,必然找得到。
|
|
383
|
+
// 时间序模式下它是空数组 ⇒ terms 为空 ⇒ 不抽段落,正合语义。
|
|
384
|
+
const terms = Array.isArray(payload.keywords) ? payload.keywords : []
|
|
385
|
+
|
|
386
|
+
const docs = await Promise.all((payload.docs || []).map(async (doc) => {
|
|
387
|
+
const row = {
|
|
388
|
+
rel: String(doc.rel || ''),
|
|
389
|
+
title: String(doc.title || ''),
|
|
390
|
+
summary: doc.summary == null ? '' : String(doc.summary),
|
|
391
|
+
mtimeMs: Number.isFinite(doc.mtimeMs) ? Math.trunc(doc.mtimeMs) : 0,
|
|
392
|
+
}
|
|
393
|
+
const snippet = await snippetFor(root, row.rel, terms, row.title)
|
|
394
|
+
// 抽不到就**不带这个字段**,不写空串 —— 让「没有命中」和「命中但没抽出来」
|
|
395
|
+
// 在输出里都是「没有 match 行」,而不是一行空的 `match: `
|
|
396
|
+
if (snippet) row.snippet = snippet
|
|
397
|
+
return row
|
|
398
|
+
}))
|
|
399
|
+
|
|
400
|
+
return {
|
|
401
|
+
mode: payload.mode === 'relevance' ? 'relevance' : 'time',
|
|
402
|
+
topic: typeof payload.topic === 'string' ? payload.topic : '',
|
|
403
|
+
// `scan()` 的 total 是**全量池子**的条数(在 limit 切片之前),
|
|
404
|
+
// 正好是这里要的「工作区一共有多少篇」。
|
|
405
|
+
total: Number.isInteger(payload.total) ? payload.total : 0,
|
|
406
|
+
docs,
|
|
407
|
+
}
|
|
408
|
+
},
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/**
|
|
413
|
+
* 把工具注册进 `ctx.tools`。
|
|
414
|
+
*
|
|
415
|
+
* 由调用方包在 `ctx.effect(...)` 里 —— `register` 返回的正是注销函数。
|
|
416
|
+
*
|
|
417
|
+
* @param {object} ctx - cordis 上下文(带 `tools` 服务)
|
|
418
|
+
* @param {Function} scan - 宿主的扫描函数
|
|
419
|
+
* @param {Function} [read] - 宿主的单篇读取函数(抽命中段落用;可选)
|
|
420
|
+
* @returns {() => void} 注销函数
|
|
421
|
+
*/
|
|
422
|
+
export function registerKnitDocsTool(ctx, scan, read) {
|
|
423
|
+
return ctx.tools.register(knitDocsDefinition(scan, read))
|
|
424
|
+
}
|
package/test/client.test.mjs
CHANGED
|
@@ -329,6 +329,133 @@ test('渲染:单击展开预览,再点收起', async () => {
|
|
|
329
329
|
assert.equal(panelOf(nodes), undefined, '再点同一条应收起')
|
|
330
330
|
})
|
|
331
331
|
|
|
332
|
+
test('渲染:预览头显示路径面包屑(目录 + 文件名),不再重复正文标题', async () => {
|
|
333
|
+
installFetch((url) => (url.includes('/api/doc')
|
|
334
|
+
? { ok: true, rel: 'sub/需求 文档.md', title: '需求', text: '# 需求\n正文', truncated: false }
|
|
335
|
+
: listPayload()))
|
|
336
|
+
|
|
337
|
+
const { exports } = loadClientModule()
|
|
338
|
+
const { KnitBody } = exports.__test
|
|
339
|
+
harness.reset()
|
|
340
|
+
harness.seed(['', 'time'])
|
|
341
|
+
let nodes = harness.render(h(KnitBody, { sessionId: 's1' }))
|
|
342
|
+
await harness.flush()
|
|
343
|
+
nodes = harness.render(h(KnitBody, { sessionId: 's1' }))
|
|
344
|
+
|
|
345
|
+
byClass(nodes, 'knit-doc')[1].props.onClick() // 第二条是 sub/需求 文档.md
|
|
346
|
+
nodes = harness.render(h(KnitBody, { sessionId: 's1' }))
|
|
347
|
+
|
|
348
|
+
assert.equal(byExactClass(nodes, 'knit-preview-head').length, 1)
|
|
349
|
+
assert.equal(byExactClass(nodes, 'knit-preview-dir').map(textOf).join(''), 'sub/')
|
|
350
|
+
assert.equal(byExactClass(nodes, 'knit-preview-name').map(textOf).join(''), '需求 文档.md')
|
|
351
|
+
// 头部不再放标题:正文 H1 已经写了,重复会让「列表 / 头 / 正文」出现三遍同一个词
|
|
352
|
+
assert.equal(byClass(nodes, 'knit-preview-title').length, 0)
|
|
353
|
+
// 长目录被省略号截掉时,完整路径靠 tooltip 悬停仍能看到(与列表行的 row.tooltip 同一套)
|
|
354
|
+
const pathBtn = byExactClass(nodes, 'knit-preview-path')[0]
|
|
355
|
+
assert.match(String(pathBtn.props.title), /sub\/需求 文档\.md/, 'tooltip 里带完整相对路径')
|
|
356
|
+
assert.equal(pathBtn.props.type, 'button', '路径是可点的')
|
|
357
|
+
assert.ok(pathBtn.props.onClick, '路径带打开本地的回调')
|
|
358
|
+
})
|
|
359
|
+
|
|
360
|
+
test('渲染:无目录时预览头不渲染空的目录段', async () => {
|
|
361
|
+
installFetch((url) => (url.includes('/api/doc')
|
|
362
|
+
? { ok: true, rel: '技术方案.md', title: '技术方案', text: '正文', truncated: false }
|
|
363
|
+
: listPayload()))
|
|
364
|
+
|
|
365
|
+
const { exports } = loadClientModule()
|
|
366
|
+
const { KnitBody } = exports.__test
|
|
367
|
+
harness.reset()
|
|
368
|
+
harness.seed(['', 'time'])
|
|
369
|
+
let nodes = harness.render(h(KnitBody, { sessionId: 's1' }))
|
|
370
|
+
await harness.flush()
|
|
371
|
+
nodes = harness.render(h(KnitBody, { sessionId: 's1' }))
|
|
372
|
+
|
|
373
|
+
byClass(nodes, 'knit-doc')[0].props.onClick() // 技术方案.md,没有目录
|
|
374
|
+
nodes = harness.render(h(KnitBody, { sessionId: 's1' }))
|
|
375
|
+
|
|
376
|
+
assert.equal(byExactClass(nodes, 'knit-preview-dir').length, 0)
|
|
377
|
+
assert.equal(byExactClass(nodes, 'knit-preview-name').map(textOf).join(''), '技术方案.md')
|
|
378
|
+
})
|
|
379
|
+
|
|
380
|
+
test('渲染:滚动正文进入阅读态(背景转纯阅读底色),换一篇复位', async () => {
|
|
381
|
+
installFetch((url) => (url.includes('/api/doc')
|
|
382
|
+
? { ok: true, rel: 'a.md', title: 'A', text: '正文', truncated: false }
|
|
383
|
+
: listPayload()))
|
|
384
|
+
|
|
385
|
+
const { exports } = loadClientModule()
|
|
386
|
+
const { KnitBody } = exports.__test
|
|
387
|
+
harness.reset()
|
|
388
|
+
harness.seed(['', 'time'])
|
|
389
|
+
let nodes = harness.render(h(KnitBody, { sessionId: 's1' }))
|
|
390
|
+
await harness.flush()
|
|
391
|
+
nodes = harness.render(h(KnitBody, { sessionId: 's1' }))
|
|
392
|
+
|
|
393
|
+
byClass(nodes, 'knit-doc')[0].props.onClick()
|
|
394
|
+
nodes = harness.render(h(KnitBody, { sessionId: 's1' }))
|
|
395
|
+
|
|
396
|
+
assert.equal(byToken(nodes, 'reading').length, 0, '刚展开还是分层灰')
|
|
397
|
+
const scrollBody = (top) => {
|
|
398
|
+
byExactClass(nodes, 'knit-preview-body')[0].props.onScroll({ target: { scrollTop: top } })
|
|
399
|
+
nodes = harness.render(h(KnitBody, { sessionId: 's1' }))
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
scrollBody(1)
|
|
403
|
+
assert.equal(byToken(nodes, 'reading').length, 0, '1px 抖动不该换背景')
|
|
404
|
+
|
|
405
|
+
scrollBody(40)
|
|
406
|
+
assert.equal(byToken(nodes, 'reading').length, 1, '真的滚动了才进阅读态')
|
|
407
|
+
|
|
408
|
+
// 换一篇 → 新文档重新从分层灰开始(面板仍一眼可辨是另一层)
|
|
409
|
+
byClass(nodes, 'knit-doc')[1].props.onClick()
|
|
410
|
+
nodes = harness.render(h(KnitBody, { sessionId: 's1' }))
|
|
411
|
+
assert.equal(byToken(nodes, 'reading').length, 0, '换一篇后复位')
|
|
412
|
+
})
|
|
413
|
+
|
|
414
|
+
test('渲染:阅读态存在模块级,面板重新挂载后仍然是纯阅读底色', async () => {
|
|
415
|
+
// 用独立 sessionId,避免模块级集合在用例之间串味
|
|
416
|
+
const sid = 's-durable'
|
|
417
|
+
installFetch((url) => (url.includes('/api/doc')
|
|
418
|
+
? { ok: true, rel: 'a.md', title: 'A', text: '正文', truncated: false }
|
|
419
|
+
: listPayload()))
|
|
420
|
+
|
|
421
|
+
const { exports } = loadClientModule()
|
|
422
|
+
const { KnitBody } = exports.__test
|
|
423
|
+
harness.reset()
|
|
424
|
+
harness.seed(['', 'time'])
|
|
425
|
+
let nodes = harness.render(h(KnitBody, { sessionId: sid }))
|
|
426
|
+
await harness.flush()
|
|
427
|
+
nodes = harness.render(h(KnitBody, { sessionId: sid }))
|
|
428
|
+
|
|
429
|
+
byClass(nodes, 'knit-doc')[0].props.onClick()
|
|
430
|
+
nodes = harness.render(h(KnitBody, { sessionId: sid }))
|
|
431
|
+
byExactClass(nodes, 'knit-preview-body')[0].props.onScroll({ target: { scrollTop: 40 } })
|
|
432
|
+
nodes = harness.render(h(KnitBody, { sessionId: sid }))
|
|
433
|
+
assert.equal(byToken(nodes, 'reading').length, 1)
|
|
434
|
+
|
|
435
|
+
// 模拟宿主把 tab body 重新挂载:hook 槽位清零 = 组件 state 全丢
|
|
436
|
+
// (用户反馈「鼠标移出去以后就没有了」,就是这一类的重挂载)
|
|
437
|
+
harness.reset()
|
|
438
|
+
harness.seed(['', 'time'])
|
|
439
|
+
nodes = harness.render(h(KnitBody, { sessionId: sid }))
|
|
440
|
+
await harness.flush()
|
|
441
|
+
nodes = harness.render(h(KnitBody, { sessionId: sid }))
|
|
442
|
+
assert.equal(byToken(nodes, 'knit-preview').length, 0, '重挂载后预览本身当然要先重新展开')
|
|
443
|
+
|
|
444
|
+
byClass(nodes, 'knit-doc')[0].props.onClick()
|
|
445
|
+
nodes = harness.render(h(KnitBody, { sessionId: sid }))
|
|
446
|
+
assert.equal(byToken(nodes, 'reading').length, 1, '读过这一篇的事实不该随重挂载丢掉')
|
|
447
|
+
})
|
|
448
|
+
|
|
449
|
+
test('splitRelPath:拆目录与文件名(无目录 / 多级 / 空值)', () => {
|
|
450
|
+
const { splitRelPath } = loadClientModule().exports.__test
|
|
451
|
+
assert.deepEqual(splitRelPath('技术方案.md'), { dir: '', name: '技术方案.md' })
|
|
452
|
+
assert.deepEqual(splitRelPath('sub/需求 文档.md'), { dir: 'sub/', name: '需求 文档.md' })
|
|
453
|
+
assert.deepEqual(splitRelPath('a/b/c.md'), { dir: 'a/b/', name: 'c.md' })
|
|
454
|
+
assert.deepEqual(splitRelPath(''), { dir: '', name: '' })
|
|
455
|
+
assert.deepEqual(splitRelPath(null), { dir: '', name: '' })
|
|
456
|
+
assert.deepEqual(splitRelPath(undefined), { dir: '', name: '' })
|
|
457
|
+
})
|
|
458
|
+
|
|
332
459
|
test('渲染:拿不到 ui-primitives 时降级为 pre 并**显式说明**', async () => {
|
|
333
460
|
installFetch((url) => (url.includes('/api/doc')
|
|
334
461
|
? { ok: true, rel: '技术方案.md', title: '技术方案', text: '纯文本正文', truncated: false }
|
|
@@ -903,8 +1030,31 @@ test('样式:类型切换的选中态不再用品牌色描边,与列表行
|
|
|
903
1030
|
const rule = source.match(/\.knit-type-btn\.active\{([^}]*)\}/)
|
|
904
1031
|
assert.ok(rule, '必须还有 .knit-type-btn.active 这条规则')
|
|
905
1032
|
assert.ok(!rule[1].includes('--knit-accent'), `选中态不许再出现品牌色:${rule[1]}`)
|
|
906
|
-
|
|
907
|
-
|
|
1033
|
+
// 中性灰用的是「降档后的」那一套(用户觉得 DSH 默认档太灰),但仍然是中性色
|
|
1034
|
+
assert.match(rule[1], /background:var\(--knit-active-bg/,
|
|
1035
|
+
'选中态用中性选中底色,与列表行同一套')
|
|
1036
|
+
})
|
|
1037
|
+
|
|
1038
|
+
test('样式:悬停 / 选中的灰底各降一档(悬停 −60% / 选中 −40%),两个主题都给了值', async () => {
|
|
1039
|
+
const { readFileSync } = await import('node:fs')
|
|
1040
|
+
const { fileURLToPath } = await import('node:url')
|
|
1041
|
+
const source = readFileSync(fileURLToPath(new URL('../src/client/client.js', import.meta.url)), 'utf8')
|
|
1042
|
+
const start = source.indexOf('const CSS = `') + 'const CSS = `'.length
|
|
1043
|
+
const css = source.slice(start, source.indexOf('`', start)).replace(/\/\*[\s\S]*?\*\//g, '')
|
|
1044
|
+
|
|
1045
|
+
// 两个令牌都要定义:浅色一套 + 暗色主题覆盖一套
|
|
1046
|
+
assert.match(css, /--knit-hover-bg:rgba\(38,49,72,\.024\)/, '浅色悬停 = DSH 的 40%')
|
|
1047
|
+
assert.match(css, /--knit-active-bg:rgba\(38,49,72,\.061\)/, '浅色选中 = DSH 的 60%')
|
|
1048
|
+
const dark = css.match(/body\[data-ds-dark-theme\] \.knit-root\{([^}]*)\}/)
|
|
1049
|
+
assert.ok(dark, '暗色主题必须也覆盖这两个令牌,否则暗色下不跟着降')
|
|
1050
|
+
assert.match(dark[1], /--knit-hover-bg:rgba\(255,255,255,\.031\)/)
|
|
1051
|
+
assert.match(dark[1], /--knit-active-bg:rgba\(255,255,255,\.085\)/)
|
|
1052
|
+
|
|
1053
|
+
// 列表行是用户点名要改的两处
|
|
1054
|
+
assert.match(css, /\.knit-doc:hover\{background:var\(--knit-hover-bg/)
|
|
1055
|
+
assert.match(css, /\.knit-doc\.active\{[^}]*background:var\(--knit-active-bg/)
|
|
1056
|
+
// 缩略图占位底色不是悬停态,不能跟着降(降了就看不出格子边界了)
|
|
1057
|
+
assert.match(css, /\.knit-media-thumbbox\{[^}]*background:var\(--dsw-alias-interactive-bg-hover/)
|
|
908
1058
|
})
|
|
909
1059
|
|
|
910
1060
|
test('样式:媒体网格靠 CSS 变量收列数与格子边长,下限与 JS 常量同源', async () => {
|
|
@@ -959,6 +1109,45 @@ test('样式:每个 --knit-* 引用都必须有定义或 fallback', async () =
|
|
|
959
1109
|
assert.ok(defined.has('--knit-accent'), '品牌色变量必须定义在 .knit-root 上')
|
|
960
1110
|
})
|
|
961
1111
|
|
|
1112
|
+
test('样式:滚动条交给 DSH 的全局样式,只覆盖令牌、不重写伪元素', async () => {
|
|
1113
|
+
const { readFileSync } = await import('node:fs')
|
|
1114
|
+
const { fileURLToPath } = await import('node:url')
|
|
1115
|
+
const source = readFileSync(fileURLToPath(new URL('../src/client/client.js', import.meta.url)), 'utf8')
|
|
1116
|
+
|
|
1117
|
+
// 只看真实规则,注释里提到这个伪元素不算
|
|
1118
|
+
const start = source.indexOf('const CSS = `') + 'const CSS = `'.length
|
|
1119
|
+
const css = source.slice(start, source.indexOf('`', start)).replace(/\/\*[\s\S]*?\*\//g, '')
|
|
1120
|
+
|
|
1121
|
+
// 重写它就会绕开 DSH 主题的 8px + 令牌色滚动条;
|
|
1122
|
+
// 之前写死了 rgba(255,255,255,.14) 的滑块,在白底上完全隐形(用户反馈「没有滑动条」)
|
|
1123
|
+
assert.ok(!css.includes('::-webkit-scrollbar'),
|
|
1124
|
+
'不要重写滚动条伪元素,交给 DSH 全局样式')
|
|
1125
|
+
// 正文区提到 l2,与官方文档预览面板(dsh-client-ui-sidebar-documentpreview 的 body)同档
|
|
1126
|
+
assert.match(css, /--dsh-scrollbar-thumb:var\(--dsw-alias-scrollbar-bg-l2\)/)
|
|
1127
|
+
assert.match(css, /--dsh-scrollbar-thumb-hover:var\(--dsw-alias-scrollbar-hover-l2\)/)
|
|
1128
|
+
})
|
|
1129
|
+
|
|
1130
|
+
test('样式:预览面板靠 bg-module-platform 分层,头部对齐官方预览', async () => {
|
|
1131
|
+
const { readFileSync } = await import('node:fs')
|
|
1132
|
+
const { fileURLToPath } = await import('node:url')
|
|
1133
|
+
const source = readFileSync(fileURLToPath(new URL('../src/client/client.js', import.meta.url)), 'utf8')
|
|
1134
|
+
const start = source.indexOf('const CSS = `') + 'const CSS = `'.length
|
|
1135
|
+
const css = source.slice(start, source.indexOf('`', start)).replace(/\/\*[\s\S]*?\*\//g, '')
|
|
1136
|
+
|
|
1137
|
+
// 浅色主题下 bg-layer-1/2/3 解析出来全是 #fff —— 用 layer-2 分层等于没分
|
|
1138
|
+
assert.match(css, /\.knit-preview\{[^}]*background:var\(--dsw-alias-bg-module-platform/)
|
|
1139
|
+
assert.ok(!/\.knit-preview\{[^}]*bg-layer-2/.test(css),
|
|
1140
|
+
'别用 bg-layer-2 分层:浅色主题下它和 bg-layer-1 都是 #fff')
|
|
1141
|
+
// 头部对齐官方 .dhJKeW_header:38px + border-l3
|
|
1142
|
+
assert.match(css, /\.knit-preview-head\{[^}]*height:38px/)
|
|
1143
|
+
assert.match(css, /\.knit-preview-head\{[^}]*border-bottom:\.5px solid var\(--dsw-alias-border-l3/)
|
|
1144
|
+
// 全屏时要去掉圆角与柔影(那时没有「浮在列表上」的隐喻)
|
|
1145
|
+
assert.match(css, /\.knit-root\.fullscreen \.knit-preview\{[^}]*border-radius:0/)
|
|
1146
|
+
// 阅读态:过渡到纯阅读底色,而不是继续用分层的灰
|
|
1147
|
+
assert.match(css, /\.knit-preview\.reading\{background:var\(--dsw-alias-bg-base/)
|
|
1148
|
+
assert.match(css, /\.knit-preview\{[^}]*transition:background-color/)
|
|
1149
|
+
})
|
|
1150
|
+
|
|
962
1151
|
test('媒体:点类型按钮切到「图片与视频」会带 kind=media 重拉并记住偏好', async () => {
|
|
963
1152
|
const { calls } = installFetch(kindResponder({ doc: listPayload(), media: mediaPayload() }))
|
|
964
1153
|
const { KnitBody } = loadClientModule().exports.__test
|