dsh-knit 0.4.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/LICENSE +21 -0
- package/README.en.md +178 -0
- package/README.md +167 -0
- package/assets/knit-icon-24-mono-4px.svg +1 -0
- package/cordis.patch.yml +8 -0
- package/package.json +63 -0
- package/src/client/client.js +1170 -0
- package/src/host/index.js +653 -0
- package/src/host/relevance.js +236 -0
- package/test/client.test.mjs +500 -0
- package/test/entry.test.mjs +232 -0
- package/test/harness.mjs +235 -0
- package/test/host.test.mjs +249 -0
- package/test/i18n.test.mjs +344 -0
- package/test/icon.test.mjs +153 -0
- package/test/tier1.test.mjs +443 -0
|
@@ -0,0 +1,653 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Knit · 宿主半边
|
|
3
|
+
*
|
|
4
|
+
* 两件事:
|
|
5
|
+
* 1. 扫描会话工作区里的 Markdown,按 mtime 或**与当前对话的相关性**排序后吐给浏览器半边
|
|
6
|
+
* 2. 按需返回单篇正文,供面板内联预览
|
|
7
|
+
*
|
|
8
|
+
* 为什么必须有宿主半边:
|
|
9
|
+
* - DSH 的 workspaceFiles Remote 协议里没有 mtime
|
|
10
|
+
* (WorkspaceFileStat.version 是 opaque token 从不解析,WorkspaceDirectoryEntry 只有 name/type/size),
|
|
11
|
+
* 纯客户端做不出「按修改时间倒序」。
|
|
12
|
+
* - 会话事件(`session.snapshotEvents()`)只有宿主读得到,那正是相关性排序的输入。
|
|
13
|
+
*
|
|
14
|
+
* 零模型、零网络出口:只读本地文件与会话日志。
|
|
15
|
+
*/
|
|
16
|
+
import { readFile, readdir, stat } from 'node:fs/promises'
|
|
17
|
+
import { join, relative, resolve, sep } from 'node:path'
|
|
18
|
+
import { homedir } from 'node:os'
|
|
19
|
+
import { extractKeywords, rankByRelevance, topicLabel } from './relevance.js'
|
|
20
|
+
|
|
21
|
+
export const name = 'dsh-knit'
|
|
22
|
+
|
|
23
|
+
/** 本插件占用的路由前缀。 */
|
|
24
|
+
export const ROUTE_PREFIX = '/knit'
|
|
25
|
+
|
|
26
|
+
/* ── 扫描预算:宁可少列几条,也不能把宿主卡住 ───────────────── */
|
|
27
|
+
const MAX_DEPTH = 6
|
|
28
|
+
const MAX_DIRS = 500
|
|
29
|
+
const MAX_DOCS = 400
|
|
30
|
+
const SCAN_BUDGET_MS = 4000
|
|
31
|
+
const HEAD_BYTES = 16 * 1024
|
|
32
|
+
/** 单次内联预览返回的正文上限(超出截断,面板只做预览不做全量阅读)。 */
|
|
33
|
+
const DOC_MAX_BYTES = 512 * 1024
|
|
34
|
+
/** 参与相关性打分的正文长度(不需要整篇)。 */
|
|
35
|
+
const HAYSTACK_CHARS = 2500
|
|
36
|
+
|
|
37
|
+
/** 相关性输入:最多回看几条消息、总字符上限。 */
|
|
38
|
+
const CONV_MAX_MESSAGES = 6
|
|
39
|
+
const CONV_MAX_CHARS = 6000
|
|
40
|
+
const CONV_MESSAGE_CHARS = 2000
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* 允许内联渲染的图片类型白名单。
|
|
44
|
+
*
|
|
45
|
+
* `/knit/api/raw` 是按路径读文件的接口,口子必须收窄:只有在这个表里的扩展名才放行,
|
|
46
|
+
* 否则就成了「能读工作区里任意文件」的后门。
|
|
47
|
+
*/
|
|
48
|
+
const IMAGE_TYPES = new Map([
|
|
49
|
+
['png', 'image/png'],
|
|
50
|
+
['jpg', 'image/jpeg'],
|
|
51
|
+
['jpeg', 'image/jpeg'],
|
|
52
|
+
['gif', 'image/gif'],
|
|
53
|
+
['webp', 'image/webp'],
|
|
54
|
+
['avif', 'image/avif'],
|
|
55
|
+
['bmp', 'image/bmp'],
|
|
56
|
+
['ico', 'image/x-icon'],
|
|
57
|
+
['svg', 'image/svg+xml'],
|
|
58
|
+
])
|
|
59
|
+
|
|
60
|
+
/** 单张内联图片的字节上限。 */
|
|
61
|
+
const MAX_IMAGE_BYTES = 12 * 1024 * 1024
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* 机器可读的错误码。
|
|
65
|
+
*
|
|
66
|
+
* 宿主**不返回面向用户的文案** —— 文案由浏览器半边按当前语言翻译。
|
|
67
|
+
* 这样宿主不必知道 UI 语言,以后加语言也不用动宿主。
|
|
68
|
+
*/
|
|
69
|
+
export const ERROR_CODES = {
|
|
70
|
+
outsideWorkspace: 'knit/outside-workspace',
|
|
71
|
+
markdownOnly: 'knit/markdown-only',
|
|
72
|
+
notFound: 'knit/not-found',
|
|
73
|
+
notAFile: 'knit/not-a-file',
|
|
74
|
+
imageOnly: 'knit/image-only',
|
|
75
|
+
imageTooLarge: 'knit/image-too-large',
|
|
76
|
+
readFailed: 'knit/read-failed',
|
|
77
|
+
missingRel: 'knit/missing-rel',
|
|
78
|
+
notFoundRoute: 'knit/not-found-route',
|
|
79
|
+
loopbackOnly: 'knit/loopback-only',
|
|
80
|
+
methodNotAllowed: 'knit/method-not-allowed',
|
|
81
|
+
internal: 'knit/internal',
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** 摘要截断长度(需求文档写 20-32 字,演示阶段放宽到 60 更好读)。 */
|
|
85
|
+
export const SUMMARY_CHARS = 60
|
|
86
|
+
|
|
87
|
+
/** 明显的噪音目录,不进。 */
|
|
88
|
+
const SKIP_DIRS = new Set([
|
|
89
|
+
'node_modules', '.git', '.hg', '.svn', '.DSH', '.dsh',
|
|
90
|
+
'dist', 'build', 'out', '.next', '.nuxt', '.cache', '.turbo',
|
|
91
|
+
'__pycache__', '.venv', 'venv', 'env', 'target', 'coverage',
|
|
92
|
+
'.idea', '.vscode', '.gradle', 'Pods', 'DerivedData',
|
|
93
|
+
])
|
|
94
|
+
|
|
95
|
+
/* ── 解析结果缓存:key = 绝对路径,mtime+size 未变则直接复用 ──── */
|
|
96
|
+
/** @type {Map<string, object>} */
|
|
97
|
+
const cache = new Map()
|
|
98
|
+
|
|
99
|
+
/* ── 对话关键词缓存:key = sessionId,seq 未变则直接复用 ─────── */
|
|
100
|
+
/** @type {Map<string, {seq:number, keywords:Array<{term:string,weight:number}>}>} */
|
|
101
|
+
const convCache = new Map()
|
|
102
|
+
|
|
103
|
+
/** 会话里没有对话时的兜底关键词(空)。 */
|
|
104
|
+
const NO_KEYWORDS = []
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* 去掉 Markdown 行内标记,留下一句干净的纯文本。
|
|
108
|
+
* @param {string} line - 原始行
|
|
109
|
+
* @returns {string} 清洗后的行
|
|
110
|
+
*/
|
|
111
|
+
function stripInline(line) {
|
|
112
|
+
return line
|
|
113
|
+
.replace(/!\[[^\]]*\]\([^)]*\)/g, '') // 图片
|
|
114
|
+
.replace(/\[([^\]]*)\]\([^)]*\)/g, '$1') // 链接 → 文字
|
|
115
|
+
.replace(/`([^`]*)`/g, '$1') // 行内代码
|
|
116
|
+
.replace(/[*_~]/g, '') // 强调
|
|
117
|
+
.replace(/\s+/g, ' ')
|
|
118
|
+
.trim()
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* 从 Markdown 头部抽「标题 + 首段摘要」。
|
|
123
|
+
*
|
|
124
|
+
* 标题:正文里第一个 `# xxx`,没有就用文件名(去掉 .md)。
|
|
125
|
+
* 摘要:跳过 YAML frontmatter / 标题行 / 代码围栏 / 列表 / 引用 / 表格,
|
|
126
|
+
* 取第一段真正的正文文字。
|
|
127
|
+
*
|
|
128
|
+
* @param {string} head - 文件头部若干字节的文本
|
|
129
|
+
* @param {string} fileName - 文件名(无路径)
|
|
130
|
+
* @returns {{title:string, summary:string}} 解析结果
|
|
131
|
+
*/
|
|
132
|
+
export function parseMarkdown(head, fileName) {
|
|
133
|
+
const fallbackTitle = fileName.replace(/\.md$/i, '')
|
|
134
|
+
const lines = head.split(/\r?\n/)
|
|
135
|
+
|
|
136
|
+
let title = ''
|
|
137
|
+
let summary = ''
|
|
138
|
+
let inFence = false
|
|
139
|
+
let i = 0
|
|
140
|
+
|
|
141
|
+
// 跳过开头可能存在的 YAML frontmatter
|
|
142
|
+
if (lines[0] !== undefined && lines[0].trim() === '---') {
|
|
143
|
+
for (i = 1; i < lines.length; i += 1) {
|
|
144
|
+
if (lines[i].trim() === '---') { i += 1; break }
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
for (; i < lines.length; i += 1) {
|
|
149
|
+
const line = lines[i].trim()
|
|
150
|
+
|
|
151
|
+
if (/^(```|~~~)/.test(line)) { inFence = !inFence; continue }
|
|
152
|
+
if (inFence) continue
|
|
153
|
+
|
|
154
|
+
if (!title) {
|
|
155
|
+
const m = /^#\s+(.+)$/.exec(line)
|
|
156
|
+
if (m) { title = stripInline(m[1]); continue }
|
|
157
|
+
}
|
|
158
|
+
if (summary) continue
|
|
159
|
+
if (!line) continue
|
|
160
|
+
if (/^#{1,6}\s/.test(line)) continue // 其它级标题
|
|
161
|
+
if (/^([-*+]|\d+\.)\s/.test(line)) continue // 列表
|
|
162
|
+
if (/^>/.test(line)) continue // 引用
|
|
163
|
+
if (/^\|/.test(line)) continue // 表格
|
|
164
|
+
if (/^([-*_]\s*){3,}$/.test(line)) continue // 分隔线
|
|
165
|
+
if (/^</.test(line)) continue // HTML 块
|
|
166
|
+
|
|
167
|
+
const cleaned = stripInline(line)
|
|
168
|
+
if (cleaned) summary = cleaned
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
if (!title) title = fallbackTitle
|
|
172
|
+
if (summary.length > SUMMARY_CHARS) summary = `${summary.slice(0, SUMMARY_CHARS)}…`
|
|
173
|
+
|
|
174
|
+
return { title, summary }
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* 读一个 Markdown 文件的元信息,命中缓存则跳过读盘。
|
|
179
|
+
* @param {string} absPath - 绝对路径
|
|
180
|
+
* @returns {Promise<object|null>} 解析结果(含小写 haystack),读失败返回 null
|
|
181
|
+
*/
|
|
182
|
+
async function readDoc(absPath) {
|
|
183
|
+
let st
|
|
184
|
+
try {
|
|
185
|
+
st = await stat(absPath)
|
|
186
|
+
} catch {
|
|
187
|
+
return null
|
|
188
|
+
}
|
|
189
|
+
if (!st.isFile()) return null
|
|
190
|
+
|
|
191
|
+
const hit = cache.get(absPath)
|
|
192
|
+
if (hit && hit.mtimeMs === st.mtimeMs && hit.size === st.size) return hit
|
|
193
|
+
|
|
194
|
+
let head = ''
|
|
195
|
+
try {
|
|
196
|
+
const buf = await readFile(absPath)
|
|
197
|
+
head = buf.subarray(0, HEAD_BYTES).toString('utf8')
|
|
198
|
+
} catch {
|
|
199
|
+
return null
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
const fileName = absPath.split(sep).pop() || absPath
|
|
203
|
+
const { title, summary } = parseMarkdown(head, fileName)
|
|
204
|
+
const entry = {
|
|
205
|
+
mtimeMs: st.mtimeMs,
|
|
206
|
+
size: st.size,
|
|
207
|
+
title,
|
|
208
|
+
summary,
|
|
209
|
+
hayTitle: title.toLowerCase(),
|
|
210
|
+
haySummary: summary.toLowerCase(),
|
|
211
|
+
hayBody: head.slice(0, HAYSTACK_CHARS).toLowerCase(),
|
|
212
|
+
}
|
|
213
|
+
cache.set(absPath, entry)
|
|
214
|
+
return entry
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* 广度优先扫出工作区里的 .md 文件。
|
|
219
|
+
* @param {string} root - 工作区根(会话 cwd)
|
|
220
|
+
* @returns {Promise<string[]>} 绝对路径列表
|
|
221
|
+
*/
|
|
222
|
+
async function collectMarkdown(root) {
|
|
223
|
+
const found = []
|
|
224
|
+
const deadline = Date.now() + SCAN_BUDGET_MS
|
|
225
|
+
/** @type {Array<{dir:string,depth:number}>} */
|
|
226
|
+
const queue = [{ dir: root, depth: 0 }]
|
|
227
|
+
let visited = 0
|
|
228
|
+
|
|
229
|
+
while (queue.length > 0) {
|
|
230
|
+
if (visited >= MAX_DIRS || found.length >= MAX_DOCS || Date.now() > deadline) break
|
|
231
|
+
const { dir, depth } = queue.shift()
|
|
232
|
+
visited += 1
|
|
233
|
+
|
|
234
|
+
let entries
|
|
235
|
+
try {
|
|
236
|
+
entries = await readdir(dir, { withFileTypes: true })
|
|
237
|
+
} catch {
|
|
238
|
+
continue
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
for (const entry of entries) {
|
|
242
|
+
const abs = join(dir, entry.name)
|
|
243
|
+
if (entry.isDirectory()) {
|
|
244
|
+
if (depth >= MAX_DEPTH) continue
|
|
245
|
+
if (SKIP_DIRS.has(entry.name)) continue
|
|
246
|
+
if (entry.name.startsWith('.')) continue
|
|
247
|
+
queue.push({ dir: abs, depth: depth + 1 })
|
|
248
|
+
} else if (entry.isFile() && /\.md$/i.test(entry.name)) {
|
|
249
|
+
found.push(abs)
|
|
250
|
+
if (found.length >= MAX_DOCS) break
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
return found
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* 扫出工作区里全部 Markdown 的元信息(按 mtime 倒序)。
|
|
260
|
+
* @param {string} root - 工作区根
|
|
261
|
+
* @returns {Promise<{docs: Array<object>, truncated: boolean}>} 文档列表
|
|
262
|
+
*/
|
|
263
|
+
export async function collectDocs(root) {
|
|
264
|
+
const files = await collectMarkdown(root)
|
|
265
|
+
const docs = []
|
|
266
|
+
|
|
267
|
+
for (const abs of files) {
|
|
268
|
+
const meta = await readDoc(abs)
|
|
269
|
+
if (!meta) continue
|
|
270
|
+
docs.push({
|
|
271
|
+
path: abs,
|
|
272
|
+
rel: relative(root, abs).split(sep).join('/'),
|
|
273
|
+
name: abs.split(sep).pop(),
|
|
274
|
+
title: meta.title,
|
|
275
|
+
summary: meta.summary,
|
|
276
|
+
mtimeMs: meta.mtimeMs,
|
|
277
|
+
haystack: { title: meta.hayTitle, summary: meta.haySummary, body: meta.hayBody },
|
|
278
|
+
})
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
docs.sort((a, b) => b.mtimeMs - a.mtimeMs)
|
|
282
|
+
return { docs, truncated: files.length >= MAX_DOCS }
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/* ── 会话事件 → 对话文本 ────────────────────────────── */
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* 拼一条消息里所有 text block 的文字。
|
|
289
|
+
* @param {object} message - UserMessage / AssistantMessage
|
|
290
|
+
* @returns {string} 文本
|
|
291
|
+
*/
|
|
292
|
+
function messageText(message) {
|
|
293
|
+
if (!message || !Array.isArray(message.content)) return ''
|
|
294
|
+
let out = ''
|
|
295
|
+
for (const block of message.content) {
|
|
296
|
+
if (block && block.type === 'text' && typeof block.text === 'string') out += `${block.text}\n`
|
|
297
|
+
}
|
|
298
|
+
return out
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* 取会话里最近的若干条人机对话文本(**最新在前**)。
|
|
303
|
+
*
|
|
304
|
+
* 只收 `source.kind === 'user'` 的 user/message —— `agent.inject()` 塞进来的
|
|
305
|
+
* 合成上下文(AGENTS.md、skill 内容、文件变更通知)不是用户意图,会把话题带偏。
|
|
306
|
+
*
|
|
307
|
+
* @param {object} session - 宿主会话对象
|
|
308
|
+
* @returns {{texts: string[], seq: number}} 对话文本与最新事件的 seq
|
|
309
|
+
*/
|
|
310
|
+
function recentConversation(session) {
|
|
311
|
+
let events
|
|
312
|
+
try {
|
|
313
|
+
events = session && typeof session.snapshotEvents === 'function' ? session.snapshotEvents() : null
|
|
314
|
+
} catch {
|
|
315
|
+
return { texts: [], seq: -1 }
|
|
316
|
+
}
|
|
317
|
+
if (!Array.isArray(events) || events.length === 0) return { texts: [], seq: -1 }
|
|
318
|
+
|
|
319
|
+
const texts = []
|
|
320
|
+
let seq = -1
|
|
321
|
+
let chars = 0
|
|
322
|
+
|
|
323
|
+
for (let i = events.length - 1; i >= 0 && texts.length < CONV_MAX_MESSAGES; i -= 1) {
|
|
324
|
+
const event = events[i]
|
|
325
|
+
if (!event || typeof event.type !== 'string') continue
|
|
326
|
+
|
|
327
|
+
let text = ''
|
|
328
|
+
if (event.type === 'user/message') {
|
|
329
|
+
const source = event.data && event.data.source
|
|
330
|
+
if (source && source.kind && source.kind !== 'user') continue
|
|
331
|
+
text = messageText(event.data)
|
|
332
|
+
} else if (event.type === 'assistant/message') {
|
|
333
|
+
text = messageText(event.data && event.data.message)
|
|
334
|
+
} else {
|
|
335
|
+
continue
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
if (!text.trim()) continue
|
|
339
|
+
if (seq < 0) seq = event.seq
|
|
340
|
+
|
|
341
|
+
const sliced = text.slice(0, CONV_MESSAGE_CHARS)
|
|
342
|
+
texts.push(sliced)
|
|
343
|
+
chars += sliced.length
|
|
344
|
+
if (chars >= CONV_MAX_CHARS) break
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
return { texts, seq }
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* 取一个会话当前的话题关键词,按最新事件 seq 缓存。
|
|
352
|
+
* @param {object} session - 宿主会话对象
|
|
353
|
+
* @param {string} sessionId - 会话 id(缓存键)
|
|
354
|
+
* @returns {Array<{term:string,weight:number}>} 关键词表
|
|
355
|
+
*/
|
|
356
|
+
function keywordsFor(session, sessionId) {
|
|
357
|
+
const { texts, seq } = recentConversation(session)
|
|
358
|
+
const hit = convCache.get(sessionId)
|
|
359
|
+
if (hit && hit.seq === seq) return hit.keywords
|
|
360
|
+
|
|
361
|
+
const keywords = extractKeywords(texts, 30)
|
|
362
|
+
convCache.set(sessionId, { seq, keywords })
|
|
363
|
+
return keywords
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/* ── 对外载荷 ───────────────────────────────────────── */
|
|
367
|
+
|
|
368
|
+
/**
|
|
369
|
+
* 剥掉内部字段,得到发给浏览器的文档记录。
|
|
370
|
+
* @param {object} doc - 内部文档记录
|
|
371
|
+
* @returns {object} 公开记录
|
|
372
|
+
*/
|
|
373
|
+
function publicDoc(doc) {
|
|
374
|
+
return {
|
|
375
|
+
path: doc.path,
|
|
376
|
+
rel: doc.rel,
|
|
377
|
+
name: doc.name,
|
|
378
|
+
title: doc.title,
|
|
379
|
+
summary: doc.summary,
|
|
380
|
+
mtimeMs: doc.mtimeMs,
|
|
381
|
+
score: typeof doc.score === 'number' ? doc.score : null,
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/**
|
|
386
|
+
* 组装一次列表扫描结果。
|
|
387
|
+
*
|
|
388
|
+
* @param {string} root - 工作区根
|
|
389
|
+
* @param {number} limit - 最多返回多少条
|
|
390
|
+
* @param {{session?: object, sessionId?: string, sort?: string}} options - 排序上下文
|
|
391
|
+
* @returns {Promise<object>} 给浏览器的载荷
|
|
392
|
+
*/
|
|
393
|
+
export async function scan(root, limit, options = {}) {
|
|
394
|
+
const { docs, truncated } = await collectDocs(root)
|
|
395
|
+
|
|
396
|
+
const wantRelevance = options.sort === 'relevance'
|
|
397
|
+
const sessionId = options.sessionId || ''
|
|
398
|
+
let keywords = NO_KEYWORDS
|
|
399
|
+
let mode = 'time'
|
|
400
|
+
|
|
401
|
+
if (wantRelevance) {
|
|
402
|
+
keywords = keywordsFor(options.session, sessionId)
|
|
403
|
+
// 没有对话可依据时老实退回时间序,而不是假装排了个序
|
|
404
|
+
mode = keywords.length > 0 ? 'relevance' : 'time'
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
const ordered = mode === 'relevance'
|
|
408
|
+
? rankByRelevance(docs, keywords, Date.now()).docs
|
|
409
|
+
: docs.map((doc) => ({ ...doc, score: null }))
|
|
410
|
+
|
|
411
|
+
return {
|
|
412
|
+
ok: true,
|
|
413
|
+
root,
|
|
414
|
+
total: ordered.length,
|
|
415
|
+
truncated,
|
|
416
|
+
sessionId,
|
|
417
|
+
mode,
|
|
418
|
+
topic: mode === 'relevance' ? topicLabel(keywords) : '',
|
|
419
|
+
keywords: mode === 'relevance' ? keywords.slice(0, 8).map((k) => k.term) : [],
|
|
420
|
+
docs: ordered.slice(0, limit).map(publicDoc),
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/**
|
|
425
|
+
* 读一篇文档的完整正文,供面板内联预览。
|
|
426
|
+
*
|
|
427
|
+
* 路径必须落在工作区根之内——`rel` 来自浏览器,按不可信输入处理。
|
|
428
|
+
*
|
|
429
|
+
* @param {string} root - 工作区根
|
|
430
|
+
* @param {string} rel - 工作区相对路径
|
|
431
|
+
* @returns {Promise<object>} 载荷
|
|
432
|
+
*/
|
|
433
|
+
export async function readDocument(root, rel) {
|
|
434
|
+
// root 由调用方给出,这里自己归一化,不假设它已经 resolve 过
|
|
435
|
+
const base = resolve(root)
|
|
436
|
+
const abs = resolve(base, rel)
|
|
437
|
+
if (abs !== base && !abs.startsWith(base + sep)) {
|
|
438
|
+
return { ok: false, code: ERROR_CODES.outsideWorkspace }
|
|
439
|
+
}
|
|
440
|
+
if (!/\.md$/i.test(abs)) return { ok: false, code: ERROR_CODES.markdownOnly }
|
|
441
|
+
|
|
442
|
+
let st
|
|
443
|
+
try {
|
|
444
|
+
st = await stat(abs)
|
|
445
|
+
} catch {
|
|
446
|
+
return { ok: false, code: ERROR_CODES.notFound }
|
|
447
|
+
}
|
|
448
|
+
if (!st.isFile()) return { ok: false, code: ERROR_CODES.notAFile }
|
|
449
|
+
|
|
450
|
+
const buf = await readFile(abs)
|
|
451
|
+
const truncated = buf.length > DOC_MAX_BYTES
|
|
452
|
+
const text = buf.subarray(0, DOC_MAX_BYTES).toString('utf8')
|
|
453
|
+
|
|
454
|
+
return {
|
|
455
|
+
ok: true,
|
|
456
|
+
rel: relative(base, abs).split(sep).join('/'),
|
|
457
|
+
title: parseMarkdown(text, abs.split(sep).pop() || abs).title,
|
|
458
|
+
bytes: buf.length,
|
|
459
|
+
truncated,
|
|
460
|
+
text,
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/**
|
|
465
|
+
* 读一张内联图片的字节,供预览里的相对路径图片渲染。
|
|
466
|
+
*
|
|
467
|
+
* 与 `readDocument` 同样的越界防护,再叠一层扩展名白名单 —— 这是按路径读文件的接口,
|
|
468
|
+
* 不设限就等于开了一个读任意文件的后门。
|
|
469
|
+
*
|
|
470
|
+
* @param {string} root - 工作区根
|
|
471
|
+
* @param {string} rel - 工作区相对路径
|
|
472
|
+
* @returns {Promise<object>} 成功时带 `type` 与 `bytes`
|
|
473
|
+
*/
|
|
474
|
+
export async function readImage(root, rel) {
|
|
475
|
+
const base = resolve(root)
|
|
476
|
+
const abs = resolve(base, rel)
|
|
477
|
+
if (abs !== base && !abs.startsWith(base + sep)) {
|
|
478
|
+
return { ok: false, code: ERROR_CODES.outsideWorkspace }
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
const ext = (abs.split('.').pop() || '').toLowerCase()
|
|
482
|
+
const type = IMAGE_TYPES.get(ext)
|
|
483
|
+
if (!type) return { ok: false, code: ERROR_CODES.imageOnly }
|
|
484
|
+
|
|
485
|
+
let st
|
|
486
|
+
try {
|
|
487
|
+
st = await stat(abs)
|
|
488
|
+
} catch {
|
|
489
|
+
return { ok: false, code: ERROR_CODES.notFound }
|
|
490
|
+
}
|
|
491
|
+
if (!st.isFile()) return { ok: false, code: ERROR_CODES.notAFile }
|
|
492
|
+
if (st.size > MAX_IMAGE_BYTES) return { ok: false, code: ERROR_CODES.imageTooLarge }
|
|
493
|
+
|
|
494
|
+
try {
|
|
495
|
+
const bytes = await readFile(abs)
|
|
496
|
+
return { ok: true, type, bytes }
|
|
497
|
+
} catch {
|
|
498
|
+
return { ok: false, code: ERROR_CODES.readFailed }
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/**
|
|
503
|
+
* 解析一个会话的工作区根。
|
|
504
|
+
* @param {object} webCtx - 注入了 sessions 的上下文
|
|
505
|
+
* @param {string} sessionId - 会话 id(可为空)
|
|
506
|
+
* @returns {string} 绝对路径根
|
|
507
|
+
*/
|
|
508
|
+
function workspaceRootOf(webCtx, sessionId) {
|
|
509
|
+
let root = ''
|
|
510
|
+
try {
|
|
511
|
+
const session = sessionId && typeof webCtx.sessions.get === 'function'
|
|
512
|
+
? webCtx.sessions.get(sessionId)
|
|
513
|
+
: undefined
|
|
514
|
+
if (session && session.header && typeof session.header.cwd === 'string') root = session.header.cwd
|
|
515
|
+
} catch { /* 会话查不到就走兜底根 */ }
|
|
516
|
+
if (!root) root = process.cwd()
|
|
517
|
+
if (root.startsWith('~')) root = join(homedir(), root.slice(1))
|
|
518
|
+
return resolve(root)
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
/**
|
|
522
|
+
* 解析请求对应的宿主会话对象。
|
|
523
|
+
* @param {object} webCtx - 注入了 sessions 的上下文
|
|
524
|
+
* @param {string} sessionId - 会话 id
|
|
525
|
+
* @returns {object|undefined} 会话对象
|
|
526
|
+
*/
|
|
527
|
+
function sessionOf(webCtx, sessionId) {
|
|
528
|
+
try {
|
|
529
|
+
return sessionId && typeof webCtx.sessions.get === 'function' ? webCtx.sessions.get(sessionId) : undefined
|
|
530
|
+
} catch {
|
|
531
|
+
return undefined
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/**
|
|
536
|
+
* 判断来源是不是本机回环。
|
|
537
|
+
* @param {string|undefined} address - socket remoteAddress
|
|
538
|
+
* @returns {boolean} 是否放行
|
|
539
|
+
*/
|
|
540
|
+
function isLoopback(address) {
|
|
541
|
+
if (!address) return false
|
|
542
|
+
return address === '::1' || address === '127.0.0.1' || address.startsWith('::ffff:127.')
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
/**
|
|
546
|
+
* 写一个 JSON 响应。
|
|
547
|
+
* @param {import('node:http').ServerResponse} res - 响应对象
|
|
548
|
+
* @param {number} status - HTTP 状态码
|
|
549
|
+
* @param {object} body - 载荷
|
|
550
|
+
* @returns {void}
|
|
551
|
+
*/
|
|
552
|
+
function sendJson(res, status, body) {
|
|
553
|
+
const text = JSON.stringify(body)
|
|
554
|
+
res.writeHead(status, {
|
|
555
|
+
'content-type': 'application/json; charset=utf-8',
|
|
556
|
+
'content-length': Buffer.byteLength(text),
|
|
557
|
+
'cache-control': 'no-store',
|
|
558
|
+
'x-content-type-options': 'nosniff',
|
|
559
|
+
})
|
|
560
|
+
res.end(text)
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
/**
|
|
564
|
+
* 写一个二进制响应(内联图片用)。
|
|
565
|
+
*
|
|
566
|
+
* 安全头是刻意的:`nosniff` 防止浏览器把非图片当图片猜类型;
|
|
567
|
+
* `default-src 'none'` 让 SVG 里的脚本、外链一并失效 —— 即使它被直接打开也跑不起来。
|
|
568
|
+
*
|
|
569
|
+
* @param {import('node:http').ServerResponse} res - 响应对象
|
|
570
|
+
* @param {string} type - Content-Type
|
|
571
|
+
* @param {Buffer} bytes - 文件字节
|
|
572
|
+
* @returns {void}
|
|
573
|
+
*/
|
|
574
|
+
function sendBytes(res, type, bytes) {
|
|
575
|
+
res.writeHead(200, {
|
|
576
|
+
'content-type': type,
|
|
577
|
+
'content-length': bytes.length,
|
|
578
|
+
'cache-control': 'no-store',
|
|
579
|
+
'x-content-type-options': 'nosniff',
|
|
580
|
+
'content-security-policy': "default-src 'none'; sandbox",
|
|
581
|
+
})
|
|
582
|
+
res.end(bytes)
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
/**
|
|
586
|
+
* 宿主插件体:等 webServer / sessions 到位后挂只读路由。
|
|
587
|
+
* @param {import('@deepseek-ai/cordis').Context} ctx - 宿主根上下文
|
|
588
|
+
* @returns {void}
|
|
589
|
+
*/
|
|
590
|
+
export function apply(ctx) {
|
|
591
|
+
ctx.inject(['webServer', 'sessions'], (webCtx) => {
|
|
592
|
+
const handler = async (req, res) => {
|
|
593
|
+
if (!isLoopback(req.socket?.remoteAddress)) {
|
|
594
|
+
sendJson(res, 403, { ok: false, code: ERROR_CODES.loopbackOnly })
|
|
595
|
+
return
|
|
596
|
+
}
|
|
597
|
+
if (req.method !== 'GET') {
|
|
598
|
+
sendJson(res, 405, { ok: false, code: ERROR_CODES.methodNotAllowed })
|
|
599
|
+
return
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
const url = new URL(req.url || '/', 'http://localhost')
|
|
603
|
+
const sessionId = url.searchParams.get('sessionId') || ''
|
|
604
|
+
const root = workspaceRootOf(webCtx, sessionId)
|
|
605
|
+
|
|
606
|
+
try {
|
|
607
|
+
if (url.pathname === `${ROUTE_PREFIX}/api/recent`) {
|
|
608
|
+
const limit = Math.min(Math.max(Number(url.searchParams.get('limit')) || 20, 1), 100)
|
|
609
|
+
const sort = url.searchParams.get('sort') === 'relevance' ? 'relevance' : 'time'
|
|
610
|
+
const payload = await scan(root, limit, { session: sessionOf(webCtx, sessionId), sessionId, sort })
|
|
611
|
+
sendJson(res, 200, payload)
|
|
612
|
+
return
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
if (url.pathname === `${ROUTE_PREFIX}/api/doc`) {
|
|
616
|
+
const rel = url.searchParams.get('rel') || ''
|
|
617
|
+
if (!rel) {
|
|
618
|
+
sendJson(res, 400, { ok: false, code: ERROR_CODES.missingRel })
|
|
619
|
+
return
|
|
620
|
+
}
|
|
621
|
+
const payload = await readDocument(root, rel)
|
|
622
|
+
sendJson(res, payload.ok ? 200 : 404, payload)
|
|
623
|
+
return
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
if (url.pathname === `${ROUTE_PREFIX}/api/raw`) {
|
|
627
|
+
const rel = url.searchParams.get('rel') || ''
|
|
628
|
+
if (!rel) {
|
|
629
|
+
sendJson(res, 400, { ok: false, code: ERROR_CODES.missingRel })
|
|
630
|
+
return
|
|
631
|
+
}
|
|
632
|
+
const image = await readImage(root, rel)
|
|
633
|
+
if (!image.ok) {
|
|
634
|
+
sendJson(res, 404, { ok: false, code: image.code })
|
|
635
|
+
return
|
|
636
|
+
}
|
|
637
|
+
sendBytes(res, image.type, image.bytes)
|
|
638
|
+
return
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
sendJson(res, 404, { ok: false, code: ERROR_CODES.notFoundRoute })
|
|
642
|
+
} catch (error) {
|
|
643
|
+
sendJson(res, 500, { ok: false, code: ERROR_CODES.internal, detail: String((error && error.message) || error) })
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
webCtx.effect(() => {
|
|
648
|
+
const unregister = webCtx.webServer.register({ kind: 'prefix', path: ROUTE_PREFIX, handler })
|
|
649
|
+
console.log(`[${name}] route ready: ${ROUTE_PREFIX}/api/recent, ${ROUTE_PREFIX}/api/doc, ${ROUTE_PREFIX}/api/raw`)
|
|
650
|
+
return () => unregister()
|
|
651
|
+
}, 'dsh-knit: host route')
|
|
652
|
+
})
|
|
653
|
+
}
|