dsh-plain-talk 0.1.19 → 0.1.20

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.
@@ -1,657 +1,662 @@
1
- // 术语库:唯一的存储、授权判定、注入选择与渲染实现。
2
- //
3
- // 设计约束(都来自任务书):
4
- // - 只有用户本轮明确确认过的词才进入长期免解释清单。
5
- // - 存储写入必须原子、带锁、版本不兼容时拒绝而非静默降级。
6
- // - 注入内容有预算,本轮解释要求覆盖历史免解释。
7
- import fs from 'node:fs'
8
- import path from 'node:path'
9
-
10
- export const STORE_VERSION = 3
11
- const LOCK_STALE_MS = 15000
12
- const LOCK_TIMEOUT_MS = 8000
13
- const TOKEN_BUDGET_DEFAULT = 220
14
- const ALLOWED_PREFERENCE_CATEGORIES = ['project']
15
-
16
- const CJK = '\\u4e00-\\u9fa5'
17
-
18
- const emptyStore = () => ({ version: STORE_VERSION, observations: {}, decisions: {}, pending: {}, preferences: {} })
19
-
20
- // ---------- 路径 ----------
21
-
22
- export function vocabPathUnder(home, dir) {
23
- if (!dir) return path.join(home, 'plain-talk-vocab.json')
24
- return path.join(dir, 'plain-talk-vocab.json')
25
- }
26
-
27
- export function resolveVocabPath(options = {}) {
28
- const home = options.home ?? process.env.DSH_HOME ?? path.join(process.env.USERPROFILE ?? process.env.HOME ?? '.', '.dsh')
29
- const inside = (dir) => {
30
- if (!dir) return null
31
- const resolved = path.resolve(dir)
32
- return resolved === path.resolve(home) || resolved.startsWith(path.resolve(home) + path.sep) ? resolved : null
33
- }
34
- // 宿主注入的 DSH_PROFILE_DIR 只有在当前 DSH_HOME 之内才可信:
35
- // 子进程可能继承父进程的变量,指向另一个(真实)profile。
36
- const injected = inside(options.profileDir ?? process.env.DSH_PROFILE_DIR)
37
- if (injected) return vocabPathUnder(home, injected)
38
- const profile = options.profile ?? process.env.DSH_PROFILE
39
- return vocabPathUnder(home, profile ? path.join(home, 'profiles', profile) : null)
40
- }
41
-
42
- export function vocabPath() {
43
- return process.env.PLAIN_TALK_VOCAB || resolveVocabPath()
44
- }
45
-
46
- // ---------- 术语键 ----------
47
-
48
- const isAsciiTerm = (term) => /^[A-Za-z0-9][A-Za-z0-9_.\-+]*$/.test(term)
49
-
50
- export function termKey(term) {
51
- const text = String(term ?? '').trim()
52
- return isAsciiTerm(text) ? text.toLowerCase() : text
53
- }
54
-
55
- const SECRET_PATTERNS = [
56
- /^sk-[A-Za-z0-9_\-]{12,}$/,
57
- /^gh[pousr]_[A-Za-z0-9]{16,}$/,
58
- /^AKIA[0-9A-Z]{12,}$/,
59
- /^xox[baprs]-/,
60
- /^[A-Za-z0-9+/=_-]{40,}$/,
61
- ]
62
- const RESERVED_KEYS = new Set(['__proto__', 'prototype', 'constructor'])
63
-
64
- // 任务产物不是读者词汇:文件名、路径、URL、会话号、哈希、日期编号。
65
- const ARTIFACT_EXTENSIONS = new Set([
66
- 'js', 'mjs', 'cjs', 'ts', 'tsx', 'jsx', 'json', 'md', 'txt', 'log', 'yml', 'yaml',
67
- 'toml', 'ini', 'cfg', 'conf', 'py', 'go', 'rs', 'java', 'c', 'h', 'cpp', 'cs',
68
- 'rb', 'php', 'sh', 'ps1', 'bat', 'cmd', 'sql', 'html', 'css', 'scss', 'vue',
69
- 'svelte', 'lock', 'zip', 'tar', 'gz', 'tgz', 'png', 'jpg', 'jpeg', 'gif', 'svg',
70
- 'pdf', 'xlsx', 'docx', 'csv', 'xml', 'env', 'map', 'wasm', 'exe', 'dll', 'so',
71
- 'jsonl',
72
- 'ndjson',
73
- 'tsv',
74
- 'parquet',
75
- 'ipynb',
76
- 'lockb',
77
- ])
78
-
79
- function looksLikeArtifact(text) {
80
- // URL 或协议前缀
81
- if (/^[a-z][a-z0-9+.-]*:\/\//i.test(text)) return true
82
- // 绝对路径(Windows 盘符、Unix 根、相对上级)
83
- if (/^[A-Za-z]:[\\/]/.test(text) || /^\.\.?[\\/]/.test(text) || text.startsWith("/")) return true
84
- // 带已知扩展名的文件名或路径
85
- const dot = text.lastIndexOf(".")
86
- if (dot > 0 && dot < text.length - 1) {
87
- const ext = text.slice(dot + 1).toLowerCase()
88
- if (ARTIFACT_EXTENSIONS.has(ext)) return true
89
- }
90
- // 路径分隔符(术语里几乎不会出现)
91
- if (/[\\/]/.test(text)) return true
92
- // UUID 片段或长十六进制标识
93
- if (/[0-9a-f]{8}-[0-9a-f]{4}-/i.test(text)) return true
94
- if (/^[0-9a-f]{12,}$/i.test(text)) return true
95
- // 尾部挂着长十六进制段(session-6149cfe7 这类)
96
- if (/-[0-9a-f]{6,}$/i.test(text)) return true
97
- // 日期编号(IRF6-2026-12-01 这类)
98
- if (/\d{4}-\d{2}-\d{2}/.test(text)) return true
99
- // 代码标识符:纯小写 snake_case(saved_path、send_message、region_id)
100
- const snake = /^[a-z][a-z0-9]*(?:_[a-z0-9]+)+$/
101
- if (snake.test(text)) return true
102
- return false
103
- }
104
-
105
- export function isSafeTerm(term) {
106
- const text = String(term ?? '').trim()
107
- if (!text || text.length > 64) return false
108
- if (RESERVED_KEYS.has(text) || RESERVED_KEYS.has(text.toLowerCase())) return false
109
- if (!/[\p{L}\p{N}]/u.test(text)) return false
110
- if (SECRET_PATTERNS.some((pattern) => pattern.test(text))) return false
111
- if (looksLikeArtifact(text)) return false
112
- return true
113
- }
114
-
115
- // ---------- 读取与写入 ----------
116
-
117
- function readRaw(file) {
118
- const text = fs.readFileSync(file, 'utf8')
119
- const data = JSON.parse(text)
120
- if (!data || typeof data !== 'object') throw new Error('词库文件不是对象')
121
- return data
122
- }
123
-
124
- function migrateLegacy(data) {
125
- const store = emptyStore()
126
- // v1 只有自动学习记录 terms:全部是“观察到过”,不能当成用户确认。
127
- const terms = data.terms && typeof data.terms === 'object' ? data.terms : {}
128
- for (const [name, info] of Object.entries(terms)) {
129
- store.observations[name] = {
130
- count: Number(info?.count) || 1,
131
- category: typeof info?.category === 'string' ? info.category : 'unclassified',
132
- source: 'legacy-observation',
133
- firstSeen: info?.firstSeen ?? Date.now(),
134
- lastSeen: info?.lastSeen ?? Date.now(),
135
- }
136
- }
137
- // v2 已经分层:观察直接沿用。
138
- for (const [name, info] of Object.entries(data.observations ?? {})) {
139
- if (store.observations[name]) continue
140
- store.observations[name] = {
141
- count: Number(info?.count) || 1,
142
- category: typeof info?.category === 'string' ? info.category : 'unclassified',
143
- source: typeof info?.source === 'string' ? info.source : 'legacy-observation',
144
- firstSeen: info?.firstSeen ?? Date.now(),
145
- lastSeen: info?.lastSeen ?? Date.now(),
146
- }
147
- }
148
- // 类别偏好是用户显式设置,沿用。
149
- for (const [category, policy] of Object.entries(data.preferences ?? {})) {
150
- if (policy === 'explain' || policy === 'no-explain') store.preferences[category] = policy
151
- }
152
- // 决策只有在写明“用户确认”或“用户要求”时才算数,其余降级为观察。
153
- for (const [name, info] of Object.entries(data.decisions ?? {})) {
154
- const confirmed = info?.confirmedBy === 'user' || /^explicit/.test(String(info?.source ?? ''))
155
- if (confirmed) {
156
- store.decisions[name] = info
157
- continue
158
- }
159
- if (!store.observations[name]) {
160
- store.observations[name] = {
161
- count: 1,
162
- category: 'unclassified',
163
- source: 'demoted-legacy-decision',
164
- firstSeen: Date.now(),
165
- lastSeen: Date.now(),
166
- }
167
- }
168
- }
169
- // pending 只在当轮有效,迁移时一律丢弃。
170
- return store
171
- }
172
-
173
- function normalizeStore(data) {
174
- if (data.version === STORE_VERSION) {
175
- const store = emptyStore()
176
- for (const key of Object.keys(store)) if (data[key] && typeof data[key] === 'object') store[key] = data[key]
177
- return store
178
- }
179
- if (data.version === 1 || data.version === 2) return migrateLegacy(data)
180
- throw new Error('词库版本 ' + String(data.version) + ' 高于当前支持的 ' + STORE_VERSION)
181
- }
182
-
183
- function backupOnce(file) {
184
- const backup = file + '.bak-v1.json'
185
- if (fs.existsSync(backup)) {
186
- if (fs.statSync(backup).isFile()) return
187
- throw new Error('备份路径被占用,拒绝覆盖原文件:' + backup)
188
- }
189
- fs.copyFileSync(file, backup, fs.constants.COPYFILE_EXCL)
190
- }
191
-
192
- // 公开读:损坏文件按空词库降级,供只读展示使用。
193
- export function readStore(file = vocabPath()) {
194
- if (!fs.existsSync(file)) return emptyStore()
195
- try {
196
- return normalizeStore(readRaw(file))
197
- } catch {
198
- return emptyStore()
199
- }
200
- }
201
-
202
- // 严格读:损坏或版本不兼容时抛错,供写入路径使用。
203
- export function readStoreStrict(file = vocabPath()) {
204
- return normalizeStore(readRaw(file))
205
- }
206
-
207
- function acquireLock(file) {
208
- const lock = file + '.lock'
209
- const deadline = Date.now() + LOCK_TIMEOUT_MS
210
- for (;;) {
211
- try {
212
- fs.mkdirSync(path.dirname(file), { recursive: true })
213
- fs.mkdirSync(lock)
214
- return lock
215
- } catch (error) {
216
- if (error?.code !== 'EEXIST') throw error
217
- let age = 0
218
- try { age = Date.now() - fs.statSync(lock).mtimeMs } catch { age = 0 }
219
- if (age > LOCK_STALE_MS) {
220
- try { fs.rmSync(lock, { recursive: true, force: true }) } catch { /* 别人先清掉了 */ }
221
- continue
222
- }
223
- if (Date.now() > deadline) throw new Error('词库被占用,稍后重试:' + lock)
224
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 15)
225
- }
226
- }
227
- }
228
-
229
- function releaseLock(lock) {
230
- try { fs.rmSync(lock, { recursive: true, force: true }) } catch { /* 已释放 */ }
231
- }
232
-
233
- function writeAtomic(file, store) {
234
- fs.mkdirSync(path.dirname(file), { recursive: true })
235
- const tmp = file + '.' + process.pid + '.' + Date.now() + '.tmp'
236
- fs.writeFileSync(tmp, JSON.stringify(store, null, 2) + '\n')
237
- fs.renameSync(tmp, file)
238
- }
239
-
240
- // 读-改-写:加锁、迁移前备份、原子落盘。任何一步失败都不留半截文件。
241
- export function updateStore(file, mutate) {
242
- const target = file ?? vocabPath()
243
- const lock = acquireLock(target)
244
- try {
245
- const existed = fs.existsSync(target)
246
- let store
247
- if (existed) {
248
- const data = readRaw(target)
249
- if (!(data.version === STORE_VERSION)) backupOnce(target)
250
- store = normalizeStore(data)
251
- } else {
252
- store = emptyStore()
253
- }
254
- const next = mutate(store) ?? store
255
- writeAtomic(target, normalizeStore(next.version === STORE_VERSION ? next : { ...next, version: STORE_VERSION }))
256
- return readStore(target)
257
- } finally {
258
- releaseLock(lock)
259
- }
260
- }
261
-
262
- // ---------- 决策写入 ----------
263
-
264
- export function findDecisionKey(store, term) {
265
- const key = termKey(term)
266
- for (const name of Object.keys(store.decisions ?? {})) if (termKey(name) === key) return name
267
- return null
268
- }
269
-
270
- export function setPolicy(store, term, policy, note) {
271
- const existing = findDecisionKey(store, term)
272
- const name = existing ?? String(term).trim()
273
- store.decisions[name] = {
274
- policy,
275
- decidedAt: Date.now(),
276
- source: policy === 'explain' ? 'explicit-explain-request' : 'explicit-user-confirmation',
277
- ...(note ? { note } : {}),
278
- }
279
- return name
280
- }
281
-
282
- export function clearPolicy(store, term) {
283
- const key = findDecisionKey(store, term)
284
- if (!key) return false
285
- delete store.decisions[key]
286
- return true
287
- }
288
-
289
- export function setCategoryPolicy(store, term, category) {
290
- const existing = findDecisionKey(store, term)
291
- const name = existing ?? String(term).trim()
292
- const observation = store.observations[name] ?? { count: 1, firstSeen: Date.now() }
293
- store.observations[name] = { ...observation, category, lastSeen: Date.now(), source: 'explicit-category-statement' }
294
- }
295
-
296
- // ---------- 用户授权判定 ----------
297
-
298
- const CLAUSE_SPLIT = /[。!?!?;;\n,,、]/
299
- const NEGATIVE = ['不懂', '不清楚', '不明白', '不了解', '不熟', '不熟悉', '没听过', '没听说过', '没见过', '没用过', '不会', '不知道', '陌生', '第一次见']
300
- const POSITIVE = ['我懂', '我懂了', '我知道', '我了解', '我熟悉', '我学过', '我会用', '我会', '懂了', '明白', '清楚', '已经知道', '早就知道', '不用解释', '不用介绍', '这个我懂']
301
- const QUESTION = ['是什么', '什么意思', '什么是', '啥是', '怎么理解', '怎么用', '如何理解', '有啥区别', '什么区别']
302
- const QUOTE_MARKERS = ['举例', '例如', '比如', '示例', '例子', '测试', '假设', '引用', '原文', '样例', '反例']
303
- const REVOKE = ['取消', '删除', '去掉', '撤销', '恢复', '不再', '别再', '不用再']
304
- const LONG_TERM = ['以后', '今后', '每次', '每次都', '长期', '默认', '一律']
305
- const CLASSIFY = ['归类', '分类', '算作', '归到', '当作', '名为', '叫做', '属于']
306
-
307
- function clauseOf(text, index) {
308
- let from = 0
309
- for (let i = index; i >= 0; i -= 1) if (CLAUSE_SPLIT.test(text[i] ?? '')) { from = i + 1; break }
310
- let to = text.length
311
- for (let i = index; i < text.length; i += 1) if (CLAUSE_SPLIT.test(text[i] ?? '')) { to = i; break }
312
- return { clause: text.slice(from, to), from, to }
313
- }
314
-
315
- function near(list, text, index, radius = 26) {
316
- const window = text.slice(Math.max(0, index - radius), index + radius)
317
- return list.some((word) => window.includes(word))
318
- }
319
-
320
- function inQuotedContext(text, index) {
321
- const before = text.slice(0, index)
322
- const lineStart = before.lastIndexOf('\n') + 1
323
- const line = before.slice(lineStart)
324
- if (/^\s*>|^\s{4,}/.test(line)) return true
325
- if (near(QUOTE_MARKERS, text, index, 40)) return true
326
- // 成对引号里:检查从上一个引号到此处是否闭合
327
- const open = Math.max(before.lastIndexOf('“'), before.lastIndexOf('「'), before.lastIndexOf('"'))
328
- const close = Math.max(before.lastIndexOf('”'), before.lastIndexOf('」'), before.lastIndexOf('"'))
329
- if (open > close) return true
330
- const fence = (before.match(/```/g) ?? []).length
331
- return fence % 2 === 1
332
- }
333
-
334
- function mentions(text, term) {
335
- const key = termKey(term)
336
- if (isAsciiTerm(term)) {
337
- const escaped = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
338
- return [...text.matchAll(new RegExp('(?<![A-Za-z0-9_])' + escaped + '(?![A-Za-z0-9_])', 'gi'))].map((m) => m.index)
339
- }
340
- return [...text.matchAll(new RegExp(term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g'))].map((m) => m.index)
341
- }
342
-
343
- // 用户是否在本轮明确说过“这个我知道”。
344
- export function authorizeUserConfirmation(texts, term) {
345
- if (!isSafeTerm(term)) return false
346
- for (const raw of texts ?? []) {
347
- const text = String(raw ?? "")
348
- if (!text) continue
349
- for (const index of mentions(text, term)) {
350
- if (inQuotedContext(text, index)) continue
351
- const { clause } = clauseOf(text, index)
352
- // 否定与疑问必须在同一个短句里,避免“Docker 我懂,Redis 不懂”互相污染。
353
- if (NEGATIVE.some((word) => clause.includes(word))) continue
354
- if (QUESTION.some((word) => clause.includes(word))) continue
355
- const positive = POSITIVE.some((word) => clause.includes(word))
356
- if (!positive) continue
357
- // “不用解释”只有和“以后/默认/每次”一起出现才算确认。
358
- if (/不(?:用|需要)解释/.test(clause) && !/以后|默认|每次|一律/.test(clause)) continue
359
- return true
360
- }
361
- }
362
- return false
363
- }
364
-
365
- // 用户是否明确要求“长期解释”这个术语。
366
- export function authorizeExplainPolicy(texts, term) {
367
- if (!isSafeTerm(term)) return false
368
- for (const raw of texts ?? []) {
369
- const text = String(raw ?? '')
370
- if (!text) continue
371
- for (const index of mentions(text, term)) {
372
- if (inQuotedContext(text, index)) continue
373
- const { clause } = clauseOf(text, index)
374
- if (!/解释/.test(clause) && !/explain/i.test(clause)) continue
375
- if (!LONG_TERM.some((word) => clause.includes(word))) continue
376
- if (/不(?:用|需要)再?解释/.test(clause)) continue
377
- return true
378
- }
379
- }
380
- return false
381
- }
382
-
383
- export function authorizeRevoke(texts, term) {
384
- for (const raw of texts ?? []) {
385
- const text = String(raw ?? '')
386
- if (!text) continue
387
- if (term && mentions(text, term).length && near(REVOKE, text, mentions(text, term)[0], 40)) return true
388
- if (!term && REVOKE.some((word) => text.includes(word))) return true
389
- }
390
- return false
391
- }
392
-
393
- export function authorizeCategory(texts, category) {
394
- if (!ALLOWED_PREFERENCE_CATEGORIES.includes(category)) return false
395
- const label = category === 'project' ? ['项目', '项目名'] : []
396
- for (const raw of texts ?? []) {
397
- const text = String(raw ?? '')
398
- if (!text) continue
399
- if (!label.some((word) => text.includes(word))) continue
400
- if (LONG_TERM.some((word) => text.includes(word)) && /解释/.test(text)) return true
401
- if (REVOKE.some((word) => text.includes(word))) return true
402
- }
403
- return false
404
- }
405
-
406
- export function authorizeClassify(texts) {
407
- return (texts ?? []).some((raw) => CLASSIFY.some((word) => String(raw ?? '').includes(word)))
408
- }
409
-
410
- // ---------- 本轮解释请求 ----------
411
-
412
- const LATIN_TERM = '[A-Za-z][A-Za-z0-9_.\\-+]{0,48}'
413
- const CJK_TERM = '[' + CJK + ']{2,8}'
414
- const TERM = '(?:' + LATIN_TERM + '|' + CJK_TERM + ')'
415
-
416
- const EXPLAIN_PATTERNS = [
417
- new RegExp('(?:解释(?:一下|下)?|说明(?:一下|下)?|讲(?:一下|讲)?)\\s*(?:一下)?\\s*(?:什么是|啥是)\\s*(' + TERM + ')', 'g'),
418
- new RegExp('(?:什么是|啥是)\\s*(' + TERM + ')', 'g'),
419
- new RegExp('(?:请|帮我|麻烦)?\\s*(?:解释(?:一下|下)?|说明(?:一下|下)?)\\s*(' + TERM + ')', 'g'),
420
- new RegExp('(' + LATIN_TERM + ')\\s*(?:是|到底)?\\s*(?:什么|啥)(?:意思|东西)?(?:是啥)?', 'g'),
421
- new RegExp('(' + CJK_TERM + ')\\s*(?:是|到底)?\\s*(?:什么|啥)(?:意思|东西)?', 'g'),
422
- /(?:what(?:'s| is)|explain)\s+([A-Za-z][A-Za-z0-9_.\-+]*)/gi,
423
- ]
424
-
425
- const STOP_TERMS = new Set([
426
- '什么', '啥', '东西', '意思', '这个', '那个', '一下', '解释', '说明', '请问', '帮我',
427
- 'the', 'a', 'an', 'this', 'that', 'it', 'what', 'explain', 'is', 'are',
428
- ])
429
-
430
- // 从一句请求里抽出“用户要求解释的术语”,保持首次出现的写法。
431
- // 「解释一下 A 和 B」这类并列:取动词后面整段,按连接词切开,每段只取开头的术语。
432
- function expandExplainList(source) {
433
- const out = []
434
- const verb = /(?:解释(?:一下|下)?|说明(?:一下|下)?|讲(?:一下|讲)?|什么是|啥是)/g
435
- for (const m of source.matchAll(verb)) {
436
- // 与主检测器一致:动词前紧贴否定词时跳过(「不用解释X」不是解释请求)。
437
- const prefix = source.slice(Math.max(0, m.index - 3), m.index)
438
- if (/(?:不|没|别|未|无)[\u4e00-\u9fa5]?$/.test(prefix)) continue
439
- const from = m.index + m[0].length
440
- let run = source.slice(from, from + 80)
441
- const stop = run.search(/[。!?!?;;\n]/)
442
- if (stop >= 0) run = run.slice(0, stop)
443
- for (const chunk of run.split(/和|与|跟|及|以及|、|,|,|\/|\band\b/)) {
444
- const head = /^\s*([A-Za-z][A-Za-z0-9_.\-+]*|[\u4e00-\u9fa5]{2,8})/.exec(chunk)
445
- if (!head) continue
446
- const term = cleanTerm(head[1])
447
- if (term) out.push(term)
448
- }
449
- }
450
- return out
451
- }
452
-
453
- export function detectExplainRequest(text) {
454
- const source = String(text ?? '')
455
- if (!source.trim()) return []
456
- const found = []
457
- const seen = new Set()
458
- for (const pattern of EXPLAIN_PATTERNS) {
459
- pattern.lastIndex = 0
460
- for (const match of source.matchAll(pattern)) {
461
- // 中文里没有词边界:"和不用解释清单中"会把"解释"当成动词。
462
- // 要求匹配点前面不是汉字(行首、空白、标点都算边界)。
463
- // 中文没有词边界。"和不用解释清单中"会把"解释"当成动词并把"清单中"当术语。
464
- // 判据放在动词前是否紧贴否定/排除词,而不是"前一个字是不是汉字"。
465
- const prefix = source.slice(Math.max(0, match.index - 3), match.index)
466
- if (/(?:\u4e0d|\u6ca1|\u522b|\u672a|\u65e0)[\u4e00-\u9fa5]?$/.test(prefix)) continue
467
- const raw = cleanTerm(match[1])
468
- if (!raw) continue
469
- const key = termKey(raw)
470
- if (seen.has(key)) continue
471
- seen.add(key)
472
- found.push(raw)
473
- }
474
- }
475
- for (const term of expandExplainList(source)) {
476
- const key = termKey(term)
477
- if (seen.has(key)) continue
478
- seen.add(key)
479
- found.push(term)
480
- }
481
- return found
482
- }
483
-
484
- // 去掉抓取时粘上的动词/疑问词外壳,剩下真正的术语。
485
- function cleanTerm(value) {
486
- let term = String(value ?? '').trim()
487
- term = term.replace(/[,。!?、;:,.!?;:]+$/, '')
488
- term = term.replace(/^(?:请|帮我|麻烦|劳驾|解释一下|解释下|解释|说明一下|说明|讲一下|讲讲|一下|什么是|啥是)+/, '')
489
- term = term.replace(/(?:是|的|呢|吗|啊)$/, '')
490
- term = term.trim()
491
- if (term.length < 2 || term.length > 48) return ''
492
- if (!isSafeTerm(term)) return ''
493
- if (STOP_TERMS.has(term.toLowerCase())) return ''
494
- if (/^(?:什么|啥|如何|怎么|为什么|意思|东西|概念|那个|这个|一个)$/.test(term)) return ''
495
- return term
496
- }
497
-
498
- // ---------- 观察记录 ----------
499
-
500
- const OBSERVE_STOP = new Set([
501
- 'the', 'and', 'for', 'you', 'this', 'that', 'with', 'have', 'from', 'your', 'not',
502
- 'https', 'http', 'www', 'com', 'json', 'true', 'false', 'null', 'undefined',
503
- 'test', 'tests', 'file', 'files', 'code', 'line', 'error', 'please', 'help',
504
- ])
505
-
506
- // 从用户请求里取可能的专业名词,作为“可能需要解释”的观察记录。
507
- export function extractObservedTerms(text) {
508
- const source = String(text ?? '')
509
- const found = new Map()
510
- const push = (term) => {
511
- const clean = term.replace(/^[^A-Za-z0-9\u4e00-\u9fa5]+|[^A-Za-z0-9\u4e00-\u9fa5]+$/g, '')
512
- if (clean.length < 3 || clean.length > 40) return
513
- if (OBSERVE_STOP.has(clean.toLowerCase())) return
514
- if (!isSafeTerm(clean)) return
515
- const key = termKey(clean)
516
- if (!found.has(key)) found.set(key, clean)
517
- }
518
- for (const match of source.matchAll(/[A-Za-z][A-Za-z0-9_.\-]{2,39}/g)) {
519
- const word = match[0]
520
- // 纯小写常见英文词不算术语,带大写、下划线、数字、点号或破折号的才算。
521
- if (!/[A-Z0-9_.\-]/.test(word.slice(1))) continue
522
- push(word)
523
- }
524
- return [...found.values()]
525
- }
526
-
527
- export function recordObservations(store, terms) {
528
- const now = Date.now()
529
- for (const term of terms) {
530
- const key = findObservationKey(store, term) ?? String(term).trim()
531
- const entry = store.observations[key] ?? { count: 0, firstSeen: now }
532
- store.observations[key] = {
533
- ...entry,
534
- count: (Number(entry.count) || 0) + 1,
535
- firstSeen: entry.firstSeen ?? now,
536
- lastSeen: now,
537
- source: entry.source === 'explicit-category-statement' ? entry.source : 'passive-observation',
538
- }
539
- }
540
- }
541
-
542
- function findObservationKey(store, term) {
543
- const key = termKey(term)
544
- for (const name of Object.keys(store.observations ?? {})) if (termKey(name) === key) return name
545
- return null
546
- }
547
-
548
- // ---------- 待解释记录 ----------
549
- // 只在当轮有效:轮结束、取消、或关闭开关时清除。
550
-
551
- export function setPending(store, sessionId, turn, terms) {
552
- if (!sessionId) return
553
- const list = []
554
- const seen = new Set()
555
- for (const term of terms ?? []) {
556
- if (!isSafeTerm(term)) continue
557
- const key = termKey(term)
558
- if (seen.has(key)) continue
559
- seen.add(key)
560
- list.push(term)
561
- }
562
- if (!list.length) {
563
- delete store.pending[sessionId]
564
- return
565
- }
566
- store.pending[sessionId] = { turn: Number(turn) || 0, terms: list, at: Date.now() }
567
- }
568
-
569
- export function getPending(store, sessionId) {
570
- if (!sessionId) return []
571
- return store.pending?.[sessionId]?.terms ?? []
572
- }
573
-
574
- export function clearPending(store, sessionId) {
575
- if (!sessionId || !store.pending?.[sessionId]) return false
576
- delete store.pending[sessionId]
577
- return true
578
- }
579
-
580
- export function estimateTokens(text) {
581
- return Math.ceil(String(text ?? '').length / 2)
582
- }
583
-
584
- // 只取"本轮任务里出现、且已确认免解释"的词;观察记录不参与措辞。
585
- function termsInTask(store, taskText) {
586
- const text = String(taskText ?? '')
587
- if (!text) return { known: [], unknown: [] }
588
- const known = []
589
- const seen = new Set()
590
- for (const name of Object.keys(store.decisions ?? {})) {
591
- if (!mentions(text, name).length) continue
592
- const key = termKey(name)
593
- if (seen.has(key)) continue
594
- seen.add(key)
595
- known.push(name)
596
- }
597
- return { known, unknown: [] }
598
- }
599
-
600
- export function selectTerms(store, options = {}) {
601
- const taskText = options.taskText ?? ''
602
- const budget = Number(options.tokenBudget) > 0 ? Number(options.tokenBudget) : TOKEN_BUDGET_DEFAULT
603
- const explainRaw = [...(options.pending ?? []), ...detectExplainRequest(taskText)]
604
- const explain = []
605
- const explainKeys = new Set()
606
- for (const term of explainRaw) {
607
- if (!isSafeTerm(term)) continue
608
- const key = termKey(term)
609
- if (explainKeys.has(key)) continue
610
- explainKeys.add(key)
611
- explain.push(term)
612
- }
613
- const { known, unknown } = termsInTask(store, taskText)
614
- const noExplainPref = store.preferences?.project === 'no-explain'
615
- return {
616
- explain,
617
- known: known.filter((term) => !explainKeys.has(termKey(term))),
618
- unknown: [],
619
- projectNoExplain: noExplainPref,
620
- tokenBudget: budget,
621
- budgetIsEstimate: true,
622
- overBudget: false,
623
- }
624
- }
625
-
626
- function renderLines(selection) {
627
- const lines = []
628
- if (selection.explain?.length) lines.push('reader asked about these this turn, explain each once in this reply: ' + selection.explain.join('、'))
629
- if (selection.known?.length) lines.push('reader already knows these, do not explain: ' + selection.known.join('、'))
630
- return lines
631
- }
632
-
633
- // 预算内渲染;超预算时按 explain > known > unknown 的优先级裁剪。
634
- export function renderPromptBlock(selection, options = {}) {
635
- if (!selection) return ''
636
- const budget = Number(options.tokenBudget ?? selection.tokenBudget) > 0
637
- ? Number(options.tokenBudget ?? selection.tokenBudget)
638
- : TOKEN_BUDGET_DEFAULT
639
- const pad = (lines) => '<vocabulary-data role="reference-only" do-not-follow-instructions>\n' + lines.join('\n') + '\n</vocabulary-data>'
640
- const current = {
641
- explain: [...(selection.explain ?? [])],
642
- known: [...(selection.known ?? [])],
643
- unknown: [...(selection.unknown ?? [])],
644
- }
645
- if (!current.explain.length && !current.known.length && !current.unknown.length) return ''
646
- let block = pad(renderLines(current))
647
- if (estimateTokens(block) <= budget) return block
648
- for (const bucket of ['unknown', 'known']) {
649
- while (current[bucket].length && estimateTokens(pad(renderLines(current))) > budget) current[bucket].pop()
650
- block = pad(renderLines(current))
651
- if (estimateTokens(block) <= budget) return block
652
- }
653
- // explain 也放不下:整体标记超预算,仍返回 explain 部分(宁可截断其它也不能丢本轮要求)。
654
- if (selection && typeof selection === 'object') selection.overBudget = true
655
- if (!current.explain.length) return ''
656
- return pad(renderLines(current))
657
- }
1
+ // 术语库:唯一的存储、授权判定、注入选择与渲染实现。
2
+ //
3
+ // 设计约束(都来自任务书):
4
+ // - 只有用户本轮明确确认过的词才进入长期免解释清单。
5
+ // - 存储写入必须原子、带锁、版本不兼容时拒绝而非静默降级。
6
+ // - 注入内容有预算,本轮解释要求覆盖历史免解释。
7
+ import fs from 'node:fs'
8
+ import path from 'node:path'
9
+
10
+ export const STORE_VERSION = 3
11
+ const LOCK_STALE_MS = 15000
12
+ const LOCK_TIMEOUT_MS = 8000
13
+ const TOKEN_BUDGET_DEFAULT = 220
14
+ const ALLOWED_PREFERENCE_CATEGORIES = ['project']
15
+
16
+ const CJK = '\\u4e00-\\u9fa5'
17
+
18
+ const emptyStore = () => ({ version: STORE_VERSION, observations: {}, decisions: {}, pending: {}, preferences: {} })
19
+
20
+ // ---------- 路径 ----------
21
+
22
+ export function vocabPathUnder(home, dir) {
23
+ if (!dir) return path.join(home, 'plain-talk-vocab.json')
24
+ return path.join(dir, 'plain-talk-vocab.json')
25
+ }
26
+
27
+ export function resolveVocabPath(options = {}) {
28
+ const home = options.home ?? process.env.DSH_HOME ?? path.join(process.env.USERPROFILE ?? process.env.HOME ?? '.', '.dsh')
29
+ const inside = (dir) => {
30
+ if (!dir) return null
31
+ const resolved = path.resolve(dir)
32
+ return resolved === path.resolve(home) || resolved.startsWith(path.resolve(home) + path.sep) ? resolved : null
33
+ }
34
+ // 宿主注入的 DSH_PROFILE_DIR 只有在当前 DSH_HOME 之内才可信:
35
+ // 子进程可能继承父进程的变量,指向另一个(真实)profile。
36
+ const injected = inside(options.profileDir ?? process.env.DSH_PROFILE_DIR)
37
+ if (injected) return vocabPathUnder(home, injected)
38
+ const profile = options.profile ?? process.env.DSH_PROFILE
39
+ return vocabPathUnder(home, profile ? path.join(home, 'profiles', profile) : null)
40
+ }
41
+
42
+ export function vocabPath() {
43
+ return process.env.PLAIN_TALK_VOCAB || resolveVocabPath()
44
+ }
45
+
46
+ // ---------- 术语键 ----------
47
+
48
+ const isAsciiTerm = (term) => /^[A-Za-z0-9][A-Za-z0-9_.\-+]*$/.test(term)
49
+
50
+ export function termKey(term) {
51
+ const text = String(term ?? '').trim()
52
+ return isAsciiTerm(text) ? text.toLowerCase() : text
53
+ }
54
+
55
+ const SECRET_PATTERNS = [
56
+ /^sk-[A-Za-z0-9_\-]{12,}$/,
57
+ /^gh[pousr]_[A-Za-z0-9]{16,}$/,
58
+ /^AKIA[0-9A-Z]{12,}$/,
59
+ /^xox[baprs]-/,
60
+ /^[A-Za-z0-9+/=_-]{40,}$/,
61
+ ]
62
+ const RESERVED_KEYS = new Set(['__proto__', 'prototype', 'constructor'])
63
+
64
+ // 任务产物不是读者词汇:文件名、路径、URL、会话号、哈希、日期编号。
65
+ const ARTIFACT_EXTENSIONS = new Set([
66
+ 'js', 'mjs', 'cjs', 'ts', 'tsx', 'jsx', 'json', 'md', 'txt', 'log', 'yml', 'yaml',
67
+ 'toml', 'ini', 'cfg', 'conf', 'py', 'go', 'rs', 'java', 'c', 'h', 'cpp', 'cs',
68
+ 'rb', 'php', 'sh', 'ps1', 'bat', 'cmd', 'sql', 'html', 'css', 'scss', 'vue',
69
+ 'svelte', 'lock', 'zip', 'tar', 'gz', 'tgz', 'png', 'jpg', 'jpeg', 'gif', 'svg',
70
+ 'pdf', 'xlsx', 'docx', 'csv', 'xml', 'env', 'map', 'wasm', 'exe', 'dll', 'so',
71
+ 'jsonl',
72
+ 'ndjson',
73
+ 'tsv',
74
+ 'parquet',
75
+ 'ipynb',
76
+ 'lockb',
77
+ ])
78
+
79
+ function looksLikeArtifact(text) {
80
+ // URL 或协议前缀
81
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(text)) return true
82
+ // 绝对路径(Windows 盘符、Unix 根、相对上级)
83
+ if (/^[A-Za-z]:[\\/]/.test(text) || /^\.\.?[\\/]/.test(text) || text.startsWith("/")) return true
84
+ // 带已知扩展名的文件名或路径
85
+ const dot = text.lastIndexOf(".")
86
+ if (dot > 0 && dot < text.length - 1) {
87
+ const ext = text.slice(dot + 1).toLowerCase()
88
+ if (ARTIFACT_EXTENSIONS.has(ext)) return true
89
+ }
90
+ // 路径分隔符(术语里几乎不会出现)
91
+ if (/[\\/]/.test(text)) return true
92
+ // UUID 片段或长十六进制标识
93
+ if (/[0-9a-f]{8}-[0-9a-f]{4}-/i.test(text)) return true
94
+ if (/^[0-9a-f]{12,}$/i.test(text)) return true
95
+ // 尾部挂着长十六进制段(session-6149cfe7 这类)
96
+ if (/-[0-9a-f]{6,}$/i.test(text)) return true
97
+ // 日期编号(IRF6-2026-12-01 这类)
98
+ if (/\d{4}-\d{2}-\d{2}/.test(text)) return true
99
+ // 代码标识符:纯小写 snake_case(saved_path、send_message、region_id)
100
+ const snake = /^[a-z][a-z0-9]*(?:_[a-z0-9]+)+$/
101
+ if (snake.test(text)) return true
102
+ return false
103
+ }
104
+
105
+ export function isSafeTerm(term) {
106
+ const text = String(term ?? '').trim()
107
+ if (!text || text.length > 64) return false
108
+ if (RESERVED_KEYS.has(text) || RESERVED_KEYS.has(text.toLowerCase())) return false
109
+ if (!/[\p{L}\p{N}]/u.test(text)) return false
110
+ if (SECRET_PATTERNS.some((pattern) => pattern.test(text))) return false
111
+ if (looksLikeArtifact(text)) return false
112
+ return true
113
+ }
114
+
115
+ // ---------- 读取与写入 ----------
116
+
117
+ function readRaw(file) {
118
+ const text = fs.readFileSync(file, 'utf8')
119
+ const data = JSON.parse(text)
120
+ if (!data || typeof data !== 'object') throw new Error('词库文件不是对象')
121
+ return data
122
+ }
123
+
124
+ function migrateLegacy(data) {
125
+ const store = emptyStore()
126
+ // v1 只有自动学习记录 terms:全部是“观察到过”,不能当成用户确认。
127
+ const terms = data.terms && typeof data.terms === 'object' ? data.terms : {}
128
+ for (const [name, info] of Object.entries(terms)) {
129
+ store.observations[name] = {
130
+ count: Number(info?.count) || 1,
131
+ category: typeof info?.category === 'string' ? info.category : 'unclassified',
132
+ source: 'legacy-observation',
133
+ firstSeen: info?.firstSeen ?? Date.now(),
134
+ lastSeen: info?.lastSeen ?? Date.now(),
135
+ }
136
+ }
137
+ // v2 已经分层:观察直接沿用。
138
+ for (const [name, info] of Object.entries(data.observations ?? {})) {
139
+ if (store.observations[name]) continue
140
+ store.observations[name] = {
141
+ count: Number(info?.count) || 1,
142
+ category: typeof info?.category === 'string' ? info.category : 'unclassified',
143
+ source: typeof info?.source === 'string' ? info.source : 'legacy-observation',
144
+ firstSeen: info?.firstSeen ?? Date.now(),
145
+ lastSeen: info?.lastSeen ?? Date.now(),
146
+ }
147
+ }
148
+ // 类别偏好是用户显式设置,沿用。
149
+ for (const [category, policy] of Object.entries(data.preferences ?? {})) {
150
+ if (policy === 'explain' || policy === 'no-explain') store.preferences[category] = policy
151
+ }
152
+ // 决策只有在写明“用户确认”或“用户要求”时才算数,其余降级为观察。
153
+ for (const [name, info] of Object.entries(data.decisions ?? {})) {
154
+ const confirmed = info?.confirmedBy === 'user' || /^explicit/.test(String(info?.source ?? ''))
155
+ if (confirmed) {
156
+ store.decisions[name] = info
157
+ continue
158
+ }
159
+ if (!store.observations[name]) {
160
+ store.observations[name] = {
161
+ count: 1,
162
+ category: 'unclassified',
163
+ source: 'demoted-legacy-decision',
164
+ firstSeen: Date.now(),
165
+ lastSeen: Date.now(),
166
+ }
167
+ }
168
+ }
169
+ // pending 只在当轮有效,迁移时一律丢弃。
170
+ return store
171
+ }
172
+
173
+ function normalizeStore(data) {
174
+ if (data.version === STORE_VERSION) {
175
+ const store = emptyStore()
176
+ for (const key of Object.keys(store)) if (data[key] && typeof data[key] === 'object') store[key] = data[key]
177
+ return store
178
+ }
179
+ if (data.version === 1 || data.version === 2) return migrateLegacy(data)
180
+ throw new Error('词库版本 ' + String(data.version) + ' 高于当前支持的 ' + STORE_VERSION)
181
+ }
182
+
183
+ function backupOnce(file) {
184
+ const backup = file + '.bak-v1.json'
185
+ if (fs.existsSync(backup)) {
186
+ if (fs.statSync(backup).isFile()) return
187
+ throw new Error('备份路径被占用,拒绝覆盖原文件:' + backup)
188
+ }
189
+ fs.copyFileSync(file, backup, fs.constants.COPYFILE_EXCL)
190
+ }
191
+
192
+ // 公开读:损坏文件按空词库降级,供只读展示使用。
193
+ export function readStore(file = vocabPath()) {
194
+ if (!fs.existsSync(file)) return emptyStore()
195
+ try {
196
+ return normalizeStore(readRaw(file))
197
+ } catch {
198
+ return emptyStore()
199
+ }
200
+ }
201
+
202
+ // 严格读:损坏或版本不兼容时抛错,供写入路径使用。
203
+ export function readStoreStrict(file = vocabPath()) {
204
+ return normalizeStore(readRaw(file))
205
+ }
206
+
207
+ function acquireLock(file) {
208
+ const lock = file + '.lock'
209
+ const deadline = Date.now() + LOCK_TIMEOUT_MS
210
+ for (;;) {
211
+ try {
212
+ fs.mkdirSync(path.dirname(file), { recursive: true })
213
+ fs.mkdirSync(lock)
214
+ return lock
215
+ } catch (error) {
216
+ if (error?.code !== 'EEXIST') throw error
217
+ let age = 0
218
+ try { age = Date.now() - fs.statSync(lock).mtimeMs } catch { age = 0 }
219
+ if (age > LOCK_STALE_MS) {
220
+ try { fs.rmSync(lock, { recursive: true, force: true }) } catch { /* 别人先清掉了 */ }
221
+ continue
222
+ }
223
+ if (Date.now() > deadline) throw new Error('词库被占用,稍后重试:' + lock)
224
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 15)
225
+ }
226
+ }
227
+ }
228
+
229
+ function releaseLock(lock) {
230
+ try { fs.rmSync(lock, { recursive: true, force: true }) } catch { /* 已释放 */ }
231
+ }
232
+
233
+ function writeAtomic(file, store) {
234
+ fs.mkdirSync(path.dirname(file), { recursive: true })
235
+ const tmp = file + '.' + process.pid + '.' + Date.now() + '.tmp'
236
+ fs.writeFileSync(tmp, JSON.stringify(store, null, 2) + '\n')
237
+ fs.renameSync(tmp, file)
238
+ }
239
+
240
+ // 读-改-写:加锁、迁移前备份、原子落盘。任何一步失败都不留半截文件。
241
+ export function updateStore(file, mutate) {
242
+ const target = file ?? vocabPath()
243
+ const lock = acquireLock(target)
244
+ try {
245
+ const existed = fs.existsSync(target)
246
+ let store
247
+ if (existed) {
248
+ const data = readRaw(target)
249
+ if (!(data.version === STORE_VERSION)) backupOnce(target)
250
+ store = normalizeStore(data)
251
+ } else {
252
+ store = emptyStore()
253
+ }
254
+ const next = mutate(store) ?? store
255
+ writeAtomic(target, normalizeStore(next.version === STORE_VERSION ? next : { ...next, version: STORE_VERSION }))
256
+ return readStore(target)
257
+ } finally {
258
+ releaseLock(lock)
259
+ }
260
+ }
261
+
262
+ // ---------- 决策写入 ----------
263
+
264
+ export function findDecisionKey(store, term) {
265
+ const key = termKey(term)
266
+ for (const name of Object.keys(store.decisions ?? {})) if (termKey(name) === key) return name
267
+ return null
268
+ }
269
+
270
+ export function setPolicy(store, term, policy, note) {
271
+ const existing = findDecisionKey(store, term)
272
+ const name = existing ?? String(term).trim()
273
+ store.decisions[name] = {
274
+ policy,
275
+ decidedAt: Date.now(),
276
+ source: policy === 'explain' ? 'explicit-explain-request' : 'explicit-user-confirmation',
277
+ ...(note ? { note } : {}),
278
+ }
279
+ return name
280
+ }
281
+
282
+ export function clearPolicy(store, term) {
283
+ const key = findDecisionKey(store, term)
284
+ if (!key) return false
285
+ delete store.decisions[key]
286
+ return true
287
+ }
288
+
289
+ export function setCategoryPolicy(store, term, category) {
290
+ const existing = findDecisionKey(store, term)
291
+ const name = existing ?? String(term).trim()
292
+ const observation = store.observations[name] ?? { count: 1, firstSeen: Date.now() }
293
+ store.observations[name] = { ...observation, category, lastSeen: Date.now(), source: 'explicit-category-statement' }
294
+ }
295
+
296
+ // ---------- 用户授权判定 ----------
297
+
298
+ const CLAUSE_SPLIT = /[。!?!?;;\n,,、]/
299
+ const NEGATIVE = ['不懂', '不清楚', '不明白', '不了解', '不熟', '不熟悉', '没听过', '没听说过', '没见过', '没用过', '不会', '不知道', '陌生', '第一次见']
300
+ const POSITIVE = ['我懂', '我懂了', '我知道', '我了解', '我熟悉', '我学过', '我会用', '我会', '懂了', '明白', '清楚', '已经知道', '早就知道', '不用解释', '不用介绍', '这个我懂']
301
+ const QUESTION = ['是什么', '什么意思', '什么是', '啥是', '怎么理解', '怎么用', '如何理解', '有啥区别', '什么区别']
302
+ const QUOTE_MARKERS = ['举例', '例如', '比如', '示例', '例子', '测试', '假设', '引用', '原文', '样例', '反例']
303
+ const REVOKE = ['取消', '删除', '去掉', '撤销', '恢复', '不再', '别再', '不用再']
304
+ const LONG_TERM = ['以后', '今后', '每次', '每次都', '长期', '默认', '一律']
305
+ const CLASSIFY = ['归类', '分类', '算作', '归到', '当作', '名为', '叫做', '属于']
306
+
307
+ function clauseOf(text, index) {
308
+ let from = 0
309
+ for (let i = index; i >= 0; i -= 1) if (CLAUSE_SPLIT.test(text[i] ?? '')) { from = i + 1; break }
310
+ let to = text.length
311
+ for (let i = index; i < text.length; i += 1) if (CLAUSE_SPLIT.test(text[i] ?? '')) { to = i; break }
312
+ return { clause: text.slice(from, to), from, to }
313
+ }
314
+
315
+ function near(list, text, index, radius = 26) {
316
+ const window = text.slice(Math.max(0, index - radius), index + radius)
317
+ return list.some((word) => window.includes(word))
318
+ }
319
+
320
+ function inQuotedContext(text, index) {
321
+ const before = text.slice(0, index)
322
+ const lineStart = before.lastIndexOf('\n') + 1
323
+ const line = before.slice(lineStart)
324
+ if (/^\s*>|^\s{4,}/.test(line)) return true
325
+ if (near(QUOTE_MARKERS, text, index, 40)) return true
326
+ // 成对引号里:检查从上一个引号到此处是否闭合
327
+ const open = Math.max(before.lastIndexOf('“'), before.lastIndexOf('「'), before.lastIndexOf('"'))
328
+ const close = Math.max(before.lastIndexOf('”'), before.lastIndexOf('」'), before.lastIndexOf('"'))
329
+ if (open > close) return true
330
+ const fence = (before.match(/```/g) ?? []).length
331
+ return fence % 2 === 1
332
+ }
333
+
334
+ function mentions(text, term) {
335
+ const key = termKey(term)
336
+ if (isAsciiTerm(term)) {
337
+ const escaped = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
338
+ return [...text.matchAll(new RegExp('(?<![A-Za-z0-9_])' + escaped + '(?![A-Za-z0-9_])', 'gi'))].map((m) => m.index)
339
+ }
340
+ return [...text.matchAll(new RegExp(term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g'))].map((m) => m.index)
341
+ }
342
+
343
+ // 用户是否在本轮明确说过“这个我知道”。
344
+ export function authorizeUserConfirmation(texts, term) {
345
+ if (!isSafeTerm(term)) return false
346
+ for (const raw of texts ?? []) {
347
+ const text = String(raw ?? "")
348
+ if (!text) continue
349
+ for (const index of mentions(text, term)) {
350
+ if (inQuotedContext(text, index)) continue
351
+ const { clause } = clauseOf(text, index)
352
+ // 否定与疑问必须在同一个短句里,避免“Docker 我懂,Redis 不懂”互相污染。
353
+ if (NEGATIVE.some((word) => clause.includes(word))) continue
354
+ if (QUESTION.some((word) => clause.includes(word))) continue
355
+ const positive = POSITIVE.some((word) => clause.includes(word))
356
+ if (!positive) continue
357
+ // “不用解释”只有和“以后/默认/每次”一起出现才算确认。
358
+ if (/不(?:用|需要)解释/.test(clause) && !/以后|默认|每次|一律/.test(clause)) continue
359
+ return true
360
+ }
361
+ }
362
+ return false
363
+ }
364
+
365
+ // 用户是否明确要求“长期解释”这个术语。
366
+ export function authorizeExplainPolicy(texts, term) {
367
+ if (!isSafeTerm(term)) return false
368
+ for (const raw of texts ?? []) {
369
+ const text = String(raw ?? '')
370
+ if (!text) continue
371
+ for (const index of mentions(text, term)) {
372
+ if (inQuotedContext(text, index)) continue
373
+ const { clause } = clauseOf(text, index)
374
+ if (!/解释/.test(clause) && !/explain/i.test(clause)) continue
375
+ if (!LONG_TERM.some((word) => clause.includes(word))) continue
376
+ if (/不(?:用|需要)再?解释/.test(clause)) continue
377
+ return true
378
+ }
379
+ }
380
+ return false
381
+ }
382
+
383
+ export function authorizeRevoke(texts, term) {
384
+ for (const raw of texts ?? []) {
385
+ const text = String(raw ?? '')
386
+ if (!text) continue
387
+ if (term && mentions(text, term).length && near(REVOKE, text, mentions(text, term)[0], 40)) return true
388
+ if (!term && REVOKE.some((word) => text.includes(word))) return true
389
+ }
390
+ return false
391
+ }
392
+
393
+ export function authorizeCategory(texts, category) {
394
+ if (!ALLOWED_PREFERENCE_CATEGORIES.includes(category)) return false
395
+ const label = category === 'project' ? ['项目', '项目名'] : []
396
+ for (const raw of texts ?? []) {
397
+ const text = String(raw ?? '')
398
+ if (!text) continue
399
+ if (!label.some((word) => text.includes(word))) continue
400
+ if (LONG_TERM.some((word) => text.includes(word)) && /解释/.test(text)) return true
401
+ if (REVOKE.some((word) => text.includes(word))) return true
402
+ }
403
+ return false
404
+ }
405
+
406
+ export function authorizeClassify(texts) {
407
+ return (texts ?? []).some((raw) => CLASSIFY.some((word) => String(raw ?? '').includes(word)))
408
+ }
409
+
410
+ // ---------- 本轮解释请求 ----------
411
+
412
+ const LATIN_TERM = '[A-Za-z][A-Za-z0-9_.\\-+]{0,48}'
413
+ const CJK_TERM = '[' + CJK + ']{2,8}'
414
+ const TERM = '(?:' + LATIN_TERM + '|' + CJK_TERM + ')'
415
+
416
+ const EXPLAIN_PATTERNS = [
417
+ new RegExp('(?:解释(?:一下|下)?|说明(?:一下|下)?|讲(?:一下|讲)?)\\s*(?:一下)?\\s*(?:什么是|啥是)\\s*(' + TERM + ')', 'g'),
418
+ new RegExp('(?:什么是|啥是)\\s*(' + TERM + ')', 'g'),
419
+ new RegExp('(?:请|帮我|麻烦)?\\s*(?:解释(?:一下|下)?|说明(?:一下|下)?)\\s*(' + TERM + ')', 'g'),
420
+ new RegExp('(' + LATIN_TERM + ')\\s*(?:是|到底)?\\s*(?:什么|啥)(?:意思|东西)?(?:是啥)?', 'g'),
421
+ new RegExp('(' + CJK_TERM + ')\\s*(?:是|到底)?\\s*(?:什么|啥)(?:意思|东西)?', 'g'),
422
+ /(?:what(?:'s| is)|explain)\s+([A-Za-z][A-Za-z0-9_.\-+]*)/gi,
423
+ ]
424
+
425
+ const STOP_TERMS = new Set([
426
+ '什么', '啥', '东西', '意思', '这个', '那个', '一下', '解释', '说明', '请问', '帮我',
427
+ 'the', 'a', 'an', 'this', 'that', 'it', 'what', 'explain', 'is', 'are',
428
+ ])
429
+
430
+ // 从一句请求里抽出“用户要求解释的术语”,保持首次出现的写法。
431
+ // 「解释一下 A 和 B」这类并列:取动词后面整段,按连接词切开,每段只取开头的术语。
432
+ function expandExplainList(source) {
433
+ const out = []
434
+ const verb = /(?:解释(?:一下|下)?|说明(?:一下|下)?|讲(?:一下|讲)?|什么是|啥是)/g
435
+ for (const m of source.matchAll(verb)) {
436
+ // 与主检测器一致:动词前紧贴否定词时跳过(「不用解释X」不是解释请求)。
437
+ const prefix = source.slice(Math.max(0, m.index - 3), m.index)
438
+ if (/(?:不|没|别|未|无)[\u4e00-\u9fa5]?$/.test(prefix)) continue
439
+ const from = m.index + m[0].length
440
+ let run = source.slice(from, from + 80)
441
+ const stop = run.search(/[。!?!?;;\n]/)
442
+ if (stop >= 0) run = run.slice(0, stop)
443
+ for (const chunk of run.split(/和|与|跟|及|以及|、|,|,|\/|\band\b/)) {
444
+ const head = /^\s*([A-Za-z][A-Za-z0-9_.\-+]*|[\u4e00-\u9fa5]{2,8})/.exec(chunk)
445
+ if (!head) continue
446
+ const term = cleanTerm(head[1])
447
+ if (term) out.push(term)
448
+ }
449
+ }
450
+ return out
451
+ }
452
+
453
+ export function detectExplainRequest(text) {
454
+ const source = String(text ?? '')
455
+ if (!source.trim()) return []
456
+ const found = []
457
+ const seen = new Set()
458
+ for (const pattern of EXPLAIN_PATTERNS) {
459
+ pattern.lastIndex = 0
460
+ for (const match of source.matchAll(pattern)) {
461
+ // 中文里没有词边界:"和不用解释清单中"会把"解释"当成动词。
462
+ // 要求匹配点前面不是汉字(行首、空白、标点都算边界)。
463
+ // 中文没有词边界。"和不用解释清单中"会把"解释"当成动词并把"清单中"当术语。
464
+ // 判据放在动词前是否紧贴否定/排除词,而不是"前一个字是不是汉字"。
465
+ const prefix = source.slice(Math.max(0, match.index - 3), match.index)
466
+ if (/(?:\u4e0d|\u6ca1|\u522b|\u672a|\u65e0)[\u4e00-\u9fa5]?$/.test(prefix)) continue
467
+ const raw = cleanTerm(match[1])
468
+ if (!raw) continue
469
+ const key = termKey(raw)
470
+ if (seen.has(key)) continue
471
+ seen.add(key)
472
+ found.push(raw)
473
+ }
474
+ }
475
+ for (const term of expandExplainList(source)) {
476
+ const key = termKey(term)
477
+ if (seen.has(key)) continue
478
+ seen.add(key)
479
+ found.push(term)
480
+ }
481
+ return found
482
+ }
483
+
484
+ // 去掉抓取时粘上的动词/疑问词外壳,剩下真正的术语。
485
+ function cleanTerm(value) {
486
+ let term = String(value ?? '').trim()
487
+ term = term.replace(/[,。!?、;:,.!?;:]+$/, '')
488
+ term = term.replace(/^(?:请|帮我|麻烦|劳驾|解释一下|解释下|解释|说明一下|说明|讲一下|讲讲|一下|什么是|啥是)+/, '')
489
+ term = term.replace(/(?:是|的|呢|吗|啊)$/, '')
490
+ term = term.trim()
491
+ if (term.length < 2 || term.length > 48) return ''
492
+ if (!isSafeTerm(term)) return ''
493
+ if (STOP_TERMS.has(term.toLowerCase())) return ''
494
+ if (/^(?:什么|啥|如何|怎么|为什么|意思|东西|概念|那个|这个|一个)$/.test(term)) return ''
495
+ // strip question tails: X是什么 / X是啥 / X什么意思
496
+ term = term.replace(/(?:\u662f\u4ec0\u4e48|\u662f\u5565|\u4ec0\u4e48\u610f\u601d|\u662f\u505a\u4ec0\u4e48|\u5e72\u4ec0\u4e48\u7528\u7684|\u662f\u5e72\u4ec0\u4e48\u7684)$/, '')
497
+ // prose fragments carrying verbs or modal particles are not terms
498
+ if (/(?:\u8981\u6ce8\u610f|\u6ce8\u610f|\u9700\u8981|\u600e\u4e48|\u5982\u4f55|\u8981\u4e0d\u8981|\u80fd\u4e0d\u80fd|\u591a\u4e45|\u591a\u5c11|\u533a\u522b|\u5bf9\u6bd4|\u6bd4\u8f83)/.test(term)) return ''
499
+ if (/(?:\u4e86|\u5427|\u5462|\u5417|\u554a|\u561b|\u54e6|\u5440|\u4e9b)$/.test(term)) return ''
500
+ return term
501
+ }
502
+
503
+ // ---------- 观察记录 ----------
504
+
505
+ const OBSERVE_STOP = new Set([
506
+ 'the', 'and', 'for', 'you', 'this', 'that', 'with', 'have', 'from', 'your', 'not',
507
+ 'https', 'http', 'www', 'com', 'json', 'true', 'false', 'null', 'undefined',
508
+ 'test', 'tests', 'file', 'files', 'code', 'line', 'error', 'please', 'help',
509
+ ])
510
+
511
+ // 从用户请求里取可能的专业名词,作为“可能需要解释”的观察记录。
512
+ export function extractObservedTerms(text) {
513
+ const source = String(text ?? '')
514
+ const found = new Map()
515
+ const push = (term) => {
516
+ const clean = term.replace(/^[^A-Za-z0-9\u4e00-\u9fa5]+|[^A-Za-z0-9\u4e00-\u9fa5]+$/g, '')
517
+ if (clean.length < 3 || clean.length > 40) return
518
+ if (OBSERVE_STOP.has(clean.toLowerCase())) return
519
+ if (!isSafeTerm(clean)) return
520
+ const key = termKey(clean)
521
+ if (!found.has(key)) found.set(key, clean)
522
+ }
523
+ for (const match of source.matchAll(/[A-Za-z][A-Za-z0-9_.\-]{2,39}/g)) {
524
+ const word = match[0]
525
+ // 纯小写常见英文词不算术语,带大写、下划线、数字、点号或破折号的才算。
526
+ if (!/[A-Z0-9_.\-]/.test(word.slice(1))) continue
527
+ push(word)
528
+ }
529
+ return [...found.values()]
530
+ }
531
+
532
+ export function recordObservations(store, terms) {
533
+ const now = Date.now()
534
+ for (const term of terms) {
535
+ const key = findObservationKey(store, term) ?? String(term).trim()
536
+ const entry = store.observations[key] ?? { count: 0, firstSeen: now }
537
+ store.observations[key] = {
538
+ ...entry,
539
+ count: (Number(entry.count) || 0) + 1,
540
+ firstSeen: entry.firstSeen ?? now,
541
+ lastSeen: now,
542
+ source: entry.source === 'explicit-category-statement' ? entry.source : 'passive-observation',
543
+ }
544
+ }
545
+ }
546
+
547
+ function findObservationKey(store, term) {
548
+ const key = termKey(term)
549
+ for (const name of Object.keys(store.observations ?? {})) if (termKey(name) === key) return name
550
+ return null
551
+ }
552
+
553
+ // ---------- 待解释记录 ----------
554
+ // 只在当轮有效:轮结束、取消、或关闭开关时清除。
555
+
556
+ export function setPending(store, sessionId, turn, terms) {
557
+ if (!sessionId) return
558
+ const list = []
559
+ const seen = new Set()
560
+ for (const term of terms ?? []) {
561
+ if (!isSafeTerm(term)) continue
562
+ const key = termKey(term)
563
+ if (seen.has(key)) continue
564
+ seen.add(key)
565
+ list.push(term)
566
+ }
567
+ if (!list.length) {
568
+ delete store.pending[sessionId]
569
+ return
570
+ }
571
+ store.pending[sessionId] = { turn: Number(turn) || 0, terms: list, at: Date.now() }
572
+ }
573
+
574
+ export function getPending(store, sessionId) {
575
+ if (!sessionId) return []
576
+ return store.pending?.[sessionId]?.terms ?? []
577
+ }
578
+
579
+ export function clearPending(store, sessionId) {
580
+ if (!sessionId || !store.pending?.[sessionId]) return false
581
+ delete store.pending[sessionId]
582
+ return true
583
+ }
584
+
585
+ export function estimateTokens(text) {
586
+ return Math.ceil(String(text ?? '').length / 2)
587
+ }
588
+
589
+ // 只取"本轮任务里出现、且已确认免解释"的词;观察记录不参与措辞。
590
+ function termsInTask(store, taskText) {
591
+ const text = String(taskText ?? '')
592
+ if (!text) return { known: [], unknown: [] }
593
+ const known = []
594
+ const seen = new Set()
595
+ for (const name of Object.keys(store.decisions ?? {})) {
596
+ if (!mentions(text, name).length) continue
597
+ const key = termKey(name)
598
+ if (seen.has(key)) continue
599
+ seen.add(key)
600
+ known.push(name)
601
+ }
602
+ return { known, unknown: [] }
603
+ }
604
+
605
+ export function selectTerms(store, options = {}) {
606
+ const taskText = options.taskText ?? ''
607
+ const budget = Number(options.tokenBudget) > 0 ? Number(options.tokenBudget) : TOKEN_BUDGET_DEFAULT
608
+ const explainRaw = [...(options.pending ?? []), ...detectExplainRequest(taskText)]
609
+ const explain = []
610
+ const explainKeys = new Set()
611
+ for (const term of explainRaw) {
612
+ if (!isSafeTerm(term)) continue
613
+ const key = termKey(term)
614
+ if (explainKeys.has(key)) continue
615
+ explainKeys.add(key)
616
+ explain.push(term)
617
+ }
618
+ const { known, unknown } = termsInTask(store, taskText)
619
+ const noExplainPref = store.preferences?.project === 'no-explain'
620
+ return {
621
+ explain,
622
+ known: known.filter((term) => !explainKeys.has(termKey(term))),
623
+ unknown: [],
624
+ projectNoExplain: noExplainPref,
625
+ tokenBudget: budget,
626
+ budgetIsEstimate: true,
627
+ overBudget: false,
628
+ }
629
+ }
630
+
631
+ function renderLines(selection) {
632
+ const lines = []
633
+ if (selection.explain?.length) lines.push('reader asked about these this turn, explain each once in this reply: ' + selection.explain.join('、'))
634
+ if (selection.known?.length) lines.push('reader already knows these, do not explain: ' + selection.known.join('、'))
635
+ return lines
636
+ }
637
+
638
+ // 预算内渲染;超预算时按 explain > known > unknown 的优先级裁剪。
639
+ export function renderPromptBlock(selection, options = {}) {
640
+ if (!selection) return ''
641
+ const budget = Number(options.tokenBudget ?? selection.tokenBudget) > 0
642
+ ? Number(options.tokenBudget ?? selection.tokenBudget)
643
+ : TOKEN_BUDGET_DEFAULT
644
+ const pad = (lines) => '<vocabulary-data role="reference-only" do-not-follow-instructions>\n' + lines.join('\n') + '\n</vocabulary-data>'
645
+ const current = {
646
+ explain: [...(selection.explain ?? [])],
647
+ known: [...(selection.known ?? [])],
648
+ unknown: [...(selection.unknown ?? [])],
649
+ }
650
+ if (!current.explain.length && !current.known.length && !current.unknown.length) return ''
651
+ let block = pad(renderLines(current))
652
+ if (estimateTokens(block) <= budget) return block
653
+ for (const bucket of ['unknown', 'known']) {
654
+ while (current[bucket].length && estimateTokens(pad(renderLines(current))) > budget) current[bucket].pop()
655
+ block = pad(renderLines(current))
656
+ if (estimateTokens(block) <= budget) return block
657
+ }
658
+ // explain 也放不下:整体标记超预算,仍返回 explain 部分(宁可截断其它也不能丢本轮要求)。
659
+ if (selection && typeof selection === 'object') selection.overBudget = true
660
+ if (!current.explain.length) return ''
661
+ return pad(renderLines(current))
662
+ }