dsh-plain-talk 0.1.15 → 0.1.16

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/dsh/index.js CHANGED
@@ -1,503 +1,510 @@
1
- // 插件入口:会话开关、事件记录、系统提示注入、术语库工具、浏览器状态路由。
2
- import fs from 'node:fs'
3
- import path from 'node:path'
4
- import { analyze } from './check.js'
5
- import { RULES } from './rules.js'
6
- import { resolvePrompt } from './styles.js'
7
- import {
8
- authorizeCategory,
9
- authorizeClassify,
10
- authorizeExplainPolicy,
11
- authorizeRevoke,
12
- authorizeUserConfirmation,
13
- clearPending,
14
- clearPolicy,
15
- detectExplainRequest,
16
- extractObservedTerms,
17
- findDecisionKey,
18
- getPending,
19
- isSafeTerm,
20
- readStore,
21
- recordObservations,
22
- renderPromptBlock,
23
- selectTerms,
24
- setCategoryPolicy,
25
- setPending,
26
- setPolicy,
27
- termKey,
28
- updateStore,
29
- vocabPath,
30
- } from './vocab-policy.js'
31
-
32
- export const name = 'plain-talk'
33
-
34
- // systemPrompt / tools 是必需服务;webServer 通过 ctx.inject 动态获取,
35
- // 没有 Web 表面的 profile 也能挂载。
36
- export const inject = ['systemPrompt', 'tools']
37
-
38
- const ROUTE_STATE = '/plain-talk/state'
39
- const ALLOWED_CATEGORIES = ['common', 'domain', 'project', 'unclassified']
40
- const ACTION_HINT = '支持的动作:list、status、add、explain、remove、classify、preference、context'
41
-
42
- // 运行时注入的通知不是用户写的话,既不能当作用户语言,也不能进词汇统计。
43
- const NOT_USER_TEXT = /^(?:Time sampled|Elapsed since|Current runtime context|Current working directory|Browser time zone|<system-reminder>)/i
44
-
45
- // ---------- 会话状态文件 ----------
46
-
47
- function profileDir() {
48
- const home = process.env.DSH_HOME ?? path.join(process.env.USERPROFILE ?? process.env.HOME ?? '.', '.dsh')
49
- const inside = (dir) => {
50
- if (!dir) return null
51
- const resolved = path.resolve(dir)
52
- return resolved === path.resolve(home) || resolved.startsWith(path.resolve(home) + path.sep) ? resolved : null
53
- }
54
- const injected = inside(process.env.DSH_PROFILE_DIR)
55
- if (injected) return injected
56
- const profile = process.env.DSH_PROFILE
57
- return profile ? path.join(home, 'profiles', profile) : null
58
- }
59
-
60
- function statePath() {
61
- const dir = profileDir()
62
- const home = process.env.DSH_HOME ?? path.join(process.env.USERPROFILE ?? process.env.HOME ?? '.', '.dsh')
63
- return dir ? path.join(dir, 'plain-talk.json') : path.join(home, 'plain-talk.json')
64
- }
65
-
66
- function legacyStatePath() {
67
- const home = process.env.DSH_HOME ?? path.join(process.env.USERPROFILE ?? process.env.HOME ?? '.', '.dsh')
68
- return path.join(home, 'plain-talk.json')
69
- }
70
-
71
- function readJson(file) {
72
- try {
73
- const data = JSON.parse(fs.readFileSync(file, 'utf8'))
74
- if (data && typeof data === 'object' && data.sessions && typeof data.sessions === 'object') return data.sessions
75
- } catch { /* 缺失或损坏按空处理 */ }
76
- return null
77
- }
78
-
79
- function readState() {
80
- const own = readJson(statePath()) ?? {}
81
- const legacy = statePath() === legacyStatePath() ? null : readJson(legacyStatePath())
82
- return { version: 1, sessions: { ...(legacy ?? {}), ...own } }
83
- }
84
-
85
- function writeState(state) {
86
- const file = statePath()
87
- fs.mkdirSync(path.dirname(file), { recursive: true })
88
- const tmp = file + '.' + process.pid + '.tmp'
89
- fs.writeFileSync(tmp, JSON.stringify({ version: 1, sessions: state.sessions ?? {} }, null, 2) + '\n')
90
- fs.renameSync(tmp, file)
91
- }
92
-
93
- export function apply(ctx, config = {}) {
94
- const defaultEnabled = process.env.PLAIN_TALK_DEFAULT
95
- ? process.env.PLAIN_TALK_DEFAULT !== 'off'
96
- : config.enabled === true
97
- const tokenBudget = Number(config.tokenBudget) > 0 ? Number(config.tokenBudget) : undefined
98
-
99
- const sessionEnabled = (sessionId) => {
100
- if (!sessionId) return defaultEnabled
101
- const entry = readState().sessions[sessionId]
102
- if (typeof entry === 'boolean') return entry
103
- return typeof entry?.enabled === 'boolean' ? entry.enabled : defaultEnabled
104
- }
105
- const setSessionEnabled = (sessionId, enabled) => {
106
- const state = readState()
107
- state.sessions[sessionId] = { enabled: Boolean(enabled), updatedAt: Date.now() }
108
- writeState(state)
109
- return Boolean(enabled)
110
- }
111
-
112
- // 每个会话的当前轮次上下文:只在本进程内,是授权判定的依据。
113
- const sessions = new Map()
114
- const sessionOf = (session) => {
115
- const id = session?.id ?? session?.sessionId ?? session?.agent?.id
116
- if (!id) return null
117
- let entry = sessions.get(id)
118
- if (!entry) {
119
- entry = { turn: 0, texts: [], request: '', pending: [] }
120
- sessions.set(id, entry)
121
- }
122
- return { id, entry }
123
- }
124
-
125
- // ---------- 系统提示注入 ----------
126
-
127
- // 回复风格本身:按试验分组选择文案,开关关闭时为空。
128
- ctx.systemPrompt.section({
129
- name: 'plain-talk',
130
- order: 55,
131
- text(agentCtx) {
132
- const agent = agentCtx?.agent ?? agentCtx
133
- const id = agent?.id ?? agent?.session?.id
134
- if (!id || !sessionEnabled(id)) return ''
135
- return resolvePrompt(process.env, RULES).text
136
- },
137
- })
138
-
139
- // 本轮相关术语:只在开关打开且有本轮请求时出现。
140
- ctx.systemPrompt.section({
141
- name: 'plain-talk:vocab',
142
- order: 56,
143
- text(agentCtx) {
144
- const agent = agentCtx?.agent ?? agentCtx
145
- const id = agent?.id ?? agent?.session?.id
146
- if (!id || !sessionEnabled(id)) return ''
147
- const entry = sessions.get(id)
148
- const taskText = entry?.request || lastUserRequestFromLog(agent?.session?.log)
149
- if (!taskText) return ''
150
- const store = readStore(vocabPath())
151
- const selection = selectTerms(store, {
152
- taskText,
153
- pending: entry?.pending?.length ? entry.pending : getPending(store, id),
154
- tokenBudget,
155
- })
156
- return renderPromptBlock(selection)
157
- },
158
- })
159
-
160
- ctx.effect(() => () => { /* 无外部资源需要释放 */ })
161
-
162
- // ---------- 会话事件 ----------
163
-
164
- ctx.on('session/event', (session, event) => {
165
- const found = sessionOf(session)
166
- if (!found) return
167
- const { id, entry } = found
168
- const data = event?.data ?? {}
169
- const enabled = sessionEnabled(id)
170
- switch (event?.type) {
171
- case 'agent/inbox/spliced': {
172
- for (const message of data.inserted ?? []) {
173
- const kind = message?.source?.kind
174
- if (kind && kind !== 'user') continue
175
- if (message?.role && message.role !== 'user') continue
176
- const text = textOf(message)
177
- if (!text || NOT_USER_TEXT.test(text)) continue
178
- entry.texts.push(text)
179
- entry.request = text
180
- // 待解释层:本轮明确问到的词 + 本轮任务里出现的术语(只收拉丁术语,中文短语不进)。
181
- entry.pending = [...new Set([...detectExplainRequest(text), ...extractObservedTerms(text)])].filter(isSafeTerm)
182
- if (enabled) recordTurn(id, entry.turn, text)
183
- }
184
- break
185
- }
186
- case 'turn/start': {
187
- entry.turn = Number(data.turn) || entry.turn || 1
188
- break
189
- }
190
- case 'turn/end': {
191
- if (enabled) clearPendingFor(id)
192
- entry.texts = []
193
- entry.request = ''
194
- entry.pending = []
195
- break
196
- }
197
- default:
198
- break
199
- }
200
- })
201
-
202
- function clearPendingFor(sessionId) {
203
- updateStore(vocabPath(), (store) => {
204
- clearPending(store, sessionId)
205
- return store
206
- })
207
- }
208
-
209
- function recordTurn(sessionId, turn, text) {
210
- const observed = extractObservedTerms(text)
211
- const pending = detectExplainRequest(text).filter(isSafeTerm)
212
- updateStore(vocabPath(), (store) => {
213
- recordObservations(store, observed)
214
- setPending(store, sessionId, turn, pending)
215
- return store
216
- })
217
- }
218
-
219
- // ---------- 浏览器状态路由 ----------
220
-
221
- ctx.inject(['webServer'], (scope) => {
222
- const server = scope.webServer
223
- if (!server || typeof server.register !== 'function') return
224
- scope.effect(() => server.register({
225
- path: ROUTE_STATE,
226
- handler: async (req, res) => {
227
- const remote = req?.socket?.remoteAddress ?? ''
228
- const loopback = isLoopbackAddress(req?.socket?.remoteAddress)
229
- if (!loopback) return end(res, 403, { ok: false, error: 'loopback only' })
230
- if (req.method === 'GET') {
231
- const sessionId = readSessionId(req.url)
232
- if (!sessionId) return end(res, 400, { ok: false, error: 'sessionId is required' })
233
- return end(res, 200, { ok: true, sessionId, enabled: sessionEnabled(sessionId), defaultOn: defaultEnabled })
234
- }
235
- if (req.method === 'POST') {
236
- const body = await readBody(req)
237
- let payload
238
- try { payload = JSON.parse(body || '{}') } catch { return end(res, 400, { ok: false, error: 'invalid json' }) }
239
- const sessionId = payload?.sessionId ?? readSessionId(req.url)
240
- if (!sessionId) return end(res, 400, { ok: false, error: 'sessionId is required' })
241
- if (typeof payload?.enabled !== 'boolean') return end(res, 400, { ok: false, error: 'enabled must be a boolean' })
242
- return end(res, 200, { ok: true, sessionId, enabled: setSessionEnabled(sessionId, payload.enabled), defaultOn: defaultEnabled })
243
- }
244
- return end(res, 405, { ok: false, error: 'method not allowed' })
245
- },
246
- }))
247
- })
248
-
249
- // ---------- 工具 ----------
250
-
251
- ctx.effect(() => ctx.tools.register({
252
- name: 'plain_talk_check',
253
- description: RULES,
254
- parameters: {
255
- type: 'object',
256
- properties: {
257
- draft: { type: 'string', description: '即将发送的回复正文' },
258
- },
259
- required: ['draft'],
260
- },
261
- output: {
262
- schema: { type: 'object', additionalProperties: true },
263
- render: (_args, value) => [{ type: 'text', text: typeof value?.text === 'string' ? value.text : JSON.stringify(value) }],
264
- },
265
- async execute(args, toolCtx) {
266
- const id = toolCtx?.agent?.id ?? toolCtx?.agent?.session?.id
267
- const known = knownTokensFor(id)
268
- const result = analyze(args?.draft ?? '', { language: 'zh', knownTokens: known })
269
- return { ok: true, text: formatCheckResult(result), ...result }
270
- },
271
- }))
272
-
273
- ctx.effect(() => ctx.tools.register({
274
- name: 'plain_talk_vocab',
275
- description: '查看或修改术语清单。' + ACTION_HINT,
276
- parameters: {
277
- type: 'object',
278
- properties: {
279
- action: { type: 'string', enum: ['list', 'status', 'add', 'explain', 'remove', 'classify', 'preference', 'context'] },
280
- terms: { type: 'array', items: { type: 'string' }, description: '术语列表' },
281
- term: { type: 'string', description: '单个术语' },
282
- category: { type: 'string', description: '类别:project 等' },
283
- policy: { type: 'string', enum: ['explain', 'no-explain', 'auto'], description: '类别偏好' },
284
- },
285
- required: ['action'],
286
- },
287
- output: {
288
- schema: { type: 'object', additionalProperties: true },
289
- render: (_args, value) => [{ type: 'text', text: typeof value?.text === 'string' ? value.text : JSON.stringify(value) }],
290
- },
291
- async execute(args, toolCtx) {
292
- const id = toolCtx?.agent?.id ?? toolCtx?.agent?.session?.id ?? null
293
- const result = runVocabAction(id, args ?? {})
294
- return { ok: result.ok, text: result.text }
295
- },
296
- }))
297
-
298
- function knownTokensFor(sessionId) {
299
- const store = readStore(vocabPath())
300
- const known = Object.keys(store.decisions ?? {}).filter((term) => store.decisions[term]?.policy === 'no-explain')
301
- const pending = sessions.get(sessionId)?.pending ?? getPending(store, sessionId)
302
- for (const term of pending) {
303
- const key = termKey(term)
304
- for (let i = known.length - 1; i >= 0; i -= 1) if (termKey(known[i]) === key) known.splice(i, 1)
305
- }
306
- return known
307
- }
308
-
309
- function turnTexts(sessionId) {
310
- if (!sessionId) return []
311
- return sessions.get(sessionId)?.texts ?? []
312
- }
313
-
314
- function runVocabAction(sessionId, args) {
315
- const action = String(args.action ?? '')
316
- const list = [...(Array.isArray(args.terms) ? args.terms : []), ...(args.term ? [args.term] : [])]
317
- .map((term) => String(term ?? '').trim())
318
- .filter(Boolean)
319
- const texts = turnTexts(sessionId)
320
- const OK = (text) => ({ ok: true, text })
321
- const NO = (text) => ({ ok: false, text })
322
-
323
- if (action === 'list' || action === 'context') return OK(formatVocab(sessionId))
324
- if (action === 'status') {
325
- if (!list.length) return OK(formatVocab(sessionId))
326
- const store = readStore(vocabPath())
327
- return OK(list.map((term) => describeTerm(store, sessionId, term)).join('\n'))
328
- }
329
- if (action === 'preference') {
330
- const category = String(args.category ?? '')
331
- if (!['project', 'common'].includes(category)) {
332
- return NO('只能按项目名(project)设置类别偏好,不支持领域、细分领域这类分类:无法确定哪些词属于该类别。')
333
- }
334
- const policy = String(args.policy ?? '')
335
- if (!['explain', 'no-explain', 'auto'].includes(policy)) return NO('策略只能是 explain、no-explain 或 auto。')
336
- if (!authorizeCategory(texts, category)) {
337
- return NO('用户这一轮没有明确提出类别偏好:需要同一句里点名类别,并说明以后默认怎么处理或取消。')
338
- }
339
- updateStore(vocabPath(), (store) => {
340
- if (policy === 'auto') delete store.preferences[category]
341
- else store.preferences[category] = policy
342
- return store
343
- })
344
- return OK(policy === 'auto' ? '已取消 ' + category + ' 类别偏好。' : '已设置 ' + category + ' 类别偏好为 ' + policy + '。')
345
- }
346
- if (!list.length) return NO('需要提供术语。')
347
-
348
- if (action === 'add') {
349
- const unsafe = list.filter((term) => !isSafeTerm(term))
350
- if (unsafe.length) return NO('这些不像术语或疑似凭据,已拒绝:' + unsafe.join('、'))
351
- const denied = list.filter((term) => !authorizeUserConfirmation(texts, term))
352
- if (denied.length) {
353
- return NO('用户这一轮没有明确说已经知道:' + denied.join('、') + '。只提问、只在任务里使用、或出现在举例/引用里,都不算确认。')
354
- }
355
- updateStore(vocabPath(), (store) => {
356
- for (const term of list) setPolicy(store, term, 'no-explain')
357
- return store
358
- })
359
- return OK('已加入免解释清单:' + list.join('、'))
360
- }
361
- if (action === 'explain') {
362
- const denied = list.filter((term) => !authorizeExplainPolicy(texts, term))
363
- if (denied.length) return NO('用户这一轮没有要求长期解释:' + denied.join('、') + '。一次性的“解释一下”不改变长期偏好。')
364
- updateStore(vocabPath(), (store) => {
365
- for (const term of list) setPolicy(store, term, 'explain')
366
- return store
367
- })
368
- return OK('已标记为每次都要解释:' + list.join('、'))
369
- }
370
- if (action === 'remove') {
371
- const store = readStore(vocabPath())
372
- const missing = list.filter((term) => !findDecisionKey(store, term))
373
- if (missing.length) return NO('这些词本来就不在长期清单里:' + missing.join('、'))
374
- const denied = list.filter((term) => !authorizeRevoke(texts, term))
375
- if (denied.length) return NO('用户这一轮没有要求取消:' + denied.join('、'))
376
- updateStore(vocabPath(), (store2) => {
377
- for (const term of list) clearPolicy(store2, term)
378
- return store2
379
- })
380
- return OK('已取消长期设置:' + list.join('、'))
381
- }
382
- if (action === 'classify') {
383
- const category = String(args.category ?? '')
384
- if (!ALLOWED_CATEGORIES.includes(category)) return NO('类别只能是 common、domain、project 或 unclassified。')
385
- if (!authorizeClassify(texts)) return NO('用户这一轮没有给出归类说法。')
386
- updateStore(vocabPath(), (store) => {
387
- for (const term of list) setCategoryPolicy(store, term, category)
388
- return store
389
- })
390
- return OK('已归类为 ' + category + ':' + list.join('、'))
391
- }
392
- return NO('未知动作。' + ACTION_HINT)
393
- }
394
-
395
- function describeTerm(store, sessionId, term) {
396
- const key = findDecisionKey(store, term)
397
- const decision = key ? store.decisions[key] : null
398
- const pending = sessions.get(sessionId)?.pending ?? getPending(store, sessionId)
399
- const pendingKey = pending.find((item) => termKey(item) === termKey(term))
400
- const observation = Object.keys(store.observations ?? {}).find((item) => termKey(item) === termKey(term))
401
- const parts = []
402
- if (decision?.policy === 'no-explain') parts.push('历史:用户确认过免解释')
403
- if (decision?.policy === 'explain') parts.push('历史:用户要求每次都解释')
404
- if (!decision) parts.push('没有长期设置')
405
- if (pendingKey) parts.push('本轮用户提到了它,会要求解释一次,覆盖历史设置')
406
- if (observation) parts.push('观察到使用 ' + String(store.observations[observation]?.count ?? 1) + ' 次')
407
- return term + ':' + parts.join(';')
408
- }
409
-
410
- function formatVocab(sessionId) {
411
- const store = readStore(vocabPath())
412
- const explain = Object.keys(store.decisions ?? {}).filter((term) => store.decisions[term]?.policy === 'explain')
413
- const silent = Object.keys(store.decisions ?? {}).filter((term) => store.decisions[term]?.policy === 'no-explain')
414
- const pending = sessions.get(sessionId)?.pending ?? getPending(store, sessionId)
415
- const preferences = Object.entries(store.preferences ?? {}).map(([category, policy]) => category + '=' + policy)
416
- const lines = []
417
- lines.push('免解释(' + silent.length + '):' + (silent.length ? silent.join('、') : '无'))
418
- lines.push('每次解释(' + explain.length + '):' + (explain.length ? explain.join('、') : '无'))
419
- lines.push('本轮待解释:' + (pending.length ? pending.join('、') : '无'))
420
- lines.push('类别偏好:' + (preferences.length ? preferences.join('、') : '无'))
421
- lines.push('观察词数:' + Object.keys(store.observations ?? {}).length)
422
- return lines.join('\n')
423
- }
424
-
425
- return { sessionEnabled, setSessionEnabled }
426
- }
427
-
428
- // ---------- 小工具 ----------
429
-
430
- function textOf(message) {
431
- const content = message?.content
432
- if (typeof content === 'string') return content.trim()
433
- if (Array.isArray(content)) return content.filter((part) => part?.type === 'text').map((part) => part.text).join(' ').trim()
434
- return ''
435
- }
436
-
437
- function lastUserRequestFromLog(log) {
438
- if (!Array.isArray(log)) return ''
439
- let from = 0
440
- for (let i = log.length - 1; i >= 0; i -= 1) if (log[i]?.type === 'turn/start') { from = i + 1; break }
441
- for (let i = log.length - 1; i >= from; i -= 1) {
442
- const event = log[i]
443
- if (event?.type !== 'user/message' && event?.type !== 'agent/inbox/spliced') continue
444
- const message = event.data ?? {}
445
- const kind = message.source?.kind
446
- if (kind && kind !== 'user') continue
447
- const text = textOf(message)
448
- if (text && !NOT_USER_TEXT.test(text)) return text
449
- }
450
- return ''
451
- }
452
-
453
- // 本机回环判定:空 socket(Unix socket / 内部调用)、IPv6 ::1、
454
- // 127.0.0.0/8 整段、以及 IPv4 映射的十六进制写法(::ffff:7f00:1)。
455
- function isLoopbackAddress(remote) {
456
- const raw = String(remote ?? '').trim().toLowerCase()
457
- if (!raw) return true
458
- if (raw === '::1' || raw === 'localhost') return true
459
- const mapped = raw.startsWith('::ffff:') ? raw.slice(7) : raw
460
- if (mapped.startsWith('127.')) return true
461
- // ::ffff:7f00:1 这类十六进制映射,前两段 7f00:xxxx 覆盖 127.0.0.0/16
462
- if (mapped.startsWith('7f00:')) return true
463
- return false
464
- }
465
-
466
- function readSessionId(url) {
467
- const query = String(url ?? '').split('?')[1] ?? ''
468
- for (const pair of query.split('&')) {
469
- const [key, value = ''] = pair.split('=')
470
- if (key !== 'sessionId') continue
471
- try { return decodeURIComponent(value) } catch { return value }
472
- }
473
- return ''
474
- }
475
-
476
- async function readBody(req) {
477
- const chunks = []
478
- if (req && typeof req[Symbol.asyncIterator] === 'function') {
479
- for await (const chunk of req) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)))
480
- return Buffer.concat(chunks).toString('utf8')
481
- }
482
- if (req && typeof req.on === 'function') {
483
- await new Promise((resolve, reject) => {
484
- req.on('data', (chunk) => chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk))))
485
- req.on('end', resolve)
486
- req.on('error', reject)
487
- })
488
- return Buffer.concat(chunks).toString('utf8')
489
- }
490
- return ''
491
- }
492
-
493
- function end(res, status, payload) {
494
- if (res.statusCode !== undefined) res.statusCode = status
495
- if (typeof res.setHeader === 'function') res.setHeader('content-type', 'application/json; charset=utf-8')
496
- if (typeof res.end === 'function') res.end(JSON.stringify(payload))
497
- }
498
-
499
- function formatCheckResult(result) {
500
- const issues = result?.issues ?? []
501
- if (!issues.length) return '没有发现问题。'
502
- return issues.map((issue) => '- [' + issue.severity + '] ' + issue.rule + ':' + issue.message).join('\n')
503
- }
1
+ // 插件入口:会话开关、事件记录、系统提示注入、术语库工具、浏览器状态路由。
2
+ import fs from 'node:fs'
3
+ import path from 'node:path'
4
+ import { analyze } from './check.js'
5
+ import { RULES } from './rules.js'
6
+ import { resolvePrompt } from './styles.js'
7
+ import {
8
+ authorizeCategory,
9
+ authorizeClassify,
10
+ authorizeExplainPolicy,
11
+ authorizeRevoke,
12
+ authorizeUserConfirmation,
13
+ clearPending,
14
+ clearPolicy,
15
+ detectExplainRequest,
16
+ extractObservedTerms,
17
+ findDecisionKey,
18
+ getPending,
19
+ isSafeTerm,
20
+ readStore,
21
+ recordObservations,
22
+ renderPromptBlock,
23
+ selectTerms,
24
+ setCategoryPolicy,
25
+ setPending,
26
+ setPolicy,
27
+ termKey,
28
+ updateStore,
29
+ vocabPath,
30
+ } from './vocab-policy.js'
31
+
32
+ export const name = 'plain-talk'
33
+
34
+ // systemPrompt / tools 是必需服务;webServer 通过 ctx.inject 动态获取,
35
+ // 没有 Web 表面的 profile 也能挂载。
36
+ export const inject = ['systemPrompt', 'tools']
37
+
38
+ const ROUTE_STATE = '/plain-talk/state'
39
+ const ALLOWED_CATEGORIES = ['common', 'domain', 'project', 'unclassified']
40
+ const ACTION_HINT = '支持的动作:list、status、add、explain、remove、classify、preference、context'
41
+
42
+ // 运行时注入的通知不是用户写的话,既不能当作用户语言,也不能进词汇统计。
43
+ const NOT_USER_TEXT = /^(?:Time sampled|Elapsed since|Current runtime context|Current working directory|Browser time zone|<system-reminder>)/i
44
+
45
+ // ---------- 会话状态文件 ----------
46
+
47
+ function profileDir() {
48
+ const home = process.env.DSH_HOME ?? path.join(process.env.USERPROFILE ?? process.env.HOME ?? '.', '.dsh')
49
+ const inside = (dir) => {
50
+ if (!dir) return null
51
+ const resolved = path.resolve(dir)
52
+ return resolved === path.resolve(home) || resolved.startsWith(path.resolve(home) + path.sep) ? resolved : null
53
+ }
54
+ const injected = inside(process.env.DSH_PROFILE_DIR)
55
+ if (injected) return injected
56
+ const profile = process.env.DSH_PROFILE
57
+ return profile ? path.join(home, 'profiles', profile) : null
58
+ }
59
+
60
+ function statePath() {
61
+ const dir = profileDir()
62
+ const home = process.env.DSH_HOME ?? path.join(process.env.USERPROFILE ?? process.env.HOME ?? '.', '.dsh')
63
+ return dir ? path.join(dir, 'plain-talk.json') : path.join(home, 'plain-talk.json')
64
+ }
65
+
66
+ function legacyStatePath() {
67
+ const home = process.env.DSH_HOME ?? path.join(process.env.USERPROFILE ?? process.env.HOME ?? '.', '.dsh')
68
+ return path.join(home, 'plain-talk.json')
69
+ }
70
+
71
+ function readJson(file) {
72
+ try {
73
+ const data = JSON.parse(fs.readFileSync(file, 'utf8'))
74
+ if (data && typeof data === 'object' && data.sessions && typeof data.sessions === 'object') return data.sessions
75
+ } catch { /* 缺失或损坏按空处理 */ }
76
+ return null
77
+ }
78
+
79
+ function readState() {
80
+ const own = readJson(statePath()) ?? {}
81
+ const legacy = statePath() === legacyStatePath() ? null : readJson(legacyStatePath())
82
+ return { version: 1, sessions: { ...(legacy ?? {}), ...own } }
83
+ }
84
+
85
+ function writeState(state) {
86
+ const file = statePath()
87
+ fs.mkdirSync(path.dirname(file), { recursive: true })
88
+ const tmp = file + '.' + process.pid + '.tmp'
89
+ fs.writeFileSync(tmp, JSON.stringify({ version: 1, sessions: state.sessions ?? {} }, null, 2) + '\n')
90
+ fs.renameSync(tmp, file)
91
+ }
92
+
93
+ export function apply(ctx, config = {}) {
94
+ const defaultEnabled = process.env.PLAIN_TALK_DEFAULT
95
+ ? process.env.PLAIN_TALK_DEFAULT !== 'off'
96
+ : config.enabled === true
97
+ const tokenBudget = Number(config.tokenBudget) > 0 ? Number(config.tokenBudget) : undefined
98
+
99
+ const sessionEnabled = (sessionId) => {
100
+ if (!sessionId) return defaultEnabled
101
+ const entry = readState().sessions[sessionId]
102
+ if (typeof entry === 'boolean') return entry
103
+ return typeof entry?.enabled === 'boolean' ? entry.enabled : defaultEnabled
104
+ }
105
+ const setSessionEnabled = (sessionId, enabled) => {
106
+ const state = readState()
107
+ state.sessions[sessionId] = { enabled: Boolean(enabled), updatedAt: Date.now() }
108
+ writeState(state)
109
+ return Boolean(enabled)
110
+ }
111
+
112
+ // 每个会话的当前轮次上下文:只在本进程内,是授权判定的依据。
113
+ const sessions = new Map()
114
+ const sessionOf = (session) => {
115
+ const id = session?.id ?? session?.sessionId ?? session?.agent?.id
116
+ if (!id) return null
117
+ let entry = sessions.get(id)
118
+ if (!entry) {
119
+ entry = { turn: 0, texts: [], request: '', pending: [] }
120
+ sessions.set(id, entry)
121
+ }
122
+ return { id, entry }
123
+ }
124
+
125
+ // ---------- 系统提示注入 ----------
126
+
127
+ // 回复风格本身:按试验分组选择文案,开关关闭时为空。
128
+ ctx.systemPrompt.section({
129
+ name: 'plain-talk',
130
+ order: 55,
131
+ text(agentCtx) {
132
+ const agent = agentCtx?.agent ?? agentCtx
133
+ const id = agent?.id ?? agent?.session?.id
134
+ if (!id || !sessionEnabled(id)) return ''
135
+ return resolvePrompt(process.env, RULES).text
136
+ },
137
+ })
138
+
139
+ // 本轮相关术语:只在开关打开且有本轮请求时出现。
140
+ ctx.systemPrompt.section({
141
+ name: 'plain-talk:vocab',
142
+ order: 56,
143
+ text(agentCtx) {
144
+ const agent = agentCtx?.agent ?? agentCtx
145
+ const id = agent?.id ?? agent?.session?.id
146
+ if (!id || !sessionEnabled(id)) return ''
147
+ const entry = sessions.get(id)
148
+ const taskText = entry?.request || lastUserRequestFromLog(agent?.session?.log)
149
+ if (!taskText) return ''
150
+ const store = readStore(vocabPath())
151
+ const selection = selectTerms(store, {
152
+ taskText,
153
+ pending: entry?.pending?.length ? entry.pending : getPending(store, id),
154
+ tokenBudget,
155
+ })
156
+ return renderPromptBlock(selection)
157
+ },
158
+ })
159
+
160
+ ctx.effect(() => () => { /* 无外部资源需要释放 */ })
161
+
162
+ // ---------- 会话事件 ----------
163
+
164
+ ctx.on('session/event', (session, event) => {
165
+ const found = sessionOf(session)
166
+ if (!found) return
167
+ const { id, entry } = found
168
+ const data = event?.data ?? {}
169
+ const enabled = sessionEnabled(id)
170
+ switch (event?.type) {
171
+ case 'agent/inbox/spliced': {
172
+ // 真实事件顺序是 splice 先于 turn/start:按“文本所属轮次”判断跨轮。
173
+ if (entry.textsTurn !== undefined && entry.textsTurn !== entry.turn) {
174
+ entry.texts = []
175
+ entry.request = ''
176
+ entry.pending = []
177
+ }
178
+ entry.textsTurn = entry.turn
179
+ for (const message of data.inserted ?? []) {
180
+ const kind = message?.source?.kind
181
+ if (kind && kind !== 'user') continue
182
+ if (message?.role && message.role !== 'user') continue
183
+ const text = textOf(message)
184
+ if (!text || NOT_USER_TEXT.test(text)) continue
185
+ entry.texts.push(text)
186
+ entry.request = text
187
+ // 待解释层:本轮明确问到的词 + 本轮任务里出现的术语(只收拉丁术语,中文短语不进)。
188
+ entry.pending = [...new Set([...detectExplainRequest(text), ...extractObservedTerms(text)])].filter(isSafeTerm)
189
+ if (enabled) recordTurn(id, entry.turn, text)
190
+ }
191
+ break
192
+ }
193
+ case 'turn/start': {
194
+ entry.turn = Number(data.turn) || entry.turn || 1
195
+ break
196
+ }
197
+ case 'turn/end': {
198
+ if (enabled) clearPendingFor(id)
199
+ entry.texts = []
200
+ entry.request = ''
201
+ entry.pending = []
202
+ break
203
+ }
204
+ default:
205
+ break
206
+ }
207
+ })
208
+
209
+ function clearPendingFor(sessionId) {
210
+ updateStore(vocabPath(), (store) => {
211
+ clearPending(store, sessionId)
212
+ return store
213
+ })
214
+ }
215
+
216
+ function recordTurn(sessionId, turn, text) {
217
+ const observed = extractObservedTerms(text)
218
+ const pending = detectExplainRequest(text).filter(isSafeTerm)
219
+ updateStore(vocabPath(), (store) => {
220
+ recordObservations(store, observed)
221
+ setPending(store, sessionId, turn, pending)
222
+ return store
223
+ })
224
+ }
225
+
226
+ // ---------- 浏览器状态路由 ----------
227
+
228
+ ctx.inject(['webServer'], (scope) => {
229
+ const server = scope.webServer
230
+ if (!server || typeof server.register !== 'function') return
231
+ scope.effect(() => server.register({
232
+ path: ROUTE_STATE,
233
+ handler: async (req, res) => {
234
+ const remote = req?.socket?.remoteAddress ?? ''
235
+ const loopback = isLoopbackAddress(req?.socket?.remoteAddress)
236
+ if (!loopback) return end(res, 403, { ok: false, error: 'loopback only' })
237
+ if (req.method === 'GET') {
238
+ const sessionId = readSessionId(req.url)
239
+ if (!sessionId) return end(res, 400, { ok: false, error: 'sessionId is required' })
240
+ return end(res, 200, { ok: true, sessionId, enabled: sessionEnabled(sessionId), defaultOn: defaultEnabled })
241
+ }
242
+ if (req.method === 'POST') {
243
+ const body = await readBody(req)
244
+ let payload
245
+ try { payload = JSON.parse(body || '{}') } catch { return end(res, 400, { ok: false, error: 'invalid json' }) }
246
+ const sessionId = payload?.sessionId ?? readSessionId(req.url)
247
+ if (!sessionId) return end(res, 400, { ok: false, error: 'sessionId is required' })
248
+ if (typeof payload?.enabled !== 'boolean') return end(res, 400, { ok: false, error: 'enabled must be a boolean' })
249
+ return end(res, 200, { ok: true, sessionId, enabled: setSessionEnabled(sessionId, payload.enabled), defaultOn: defaultEnabled })
250
+ }
251
+ return end(res, 405, { ok: false, error: 'method not allowed' })
252
+ },
253
+ }))
254
+ })
255
+
256
+ // ---------- 工具 ----------
257
+
258
+ ctx.effect(() => ctx.tools.register({
259
+ name: 'plain_talk_check',
260
+ description: RULES,
261
+ parameters: {
262
+ type: 'object',
263
+ properties: {
264
+ draft: { type: 'string', description: '即将发送的回复正文' },
265
+ },
266
+ required: ['draft'],
267
+ },
268
+ output: {
269
+ schema: { type: 'object', additionalProperties: true },
270
+ render: (_args, value) => [{ type: 'text', text: typeof value?.text === 'string' ? value.text : JSON.stringify(value) }],
271
+ },
272
+ async execute(args, toolCtx) {
273
+ const id = toolCtx?.agent?.id ?? toolCtx?.agent?.session?.id
274
+ const known = knownTokensFor(id)
275
+ const result = analyze(args?.draft ?? '', { language: 'zh', knownTokens: known })
276
+ return { ok: true, text: formatCheckResult(result), ...result }
277
+ },
278
+ }))
279
+
280
+ ctx.effect(() => ctx.tools.register({
281
+ name: 'plain_talk_vocab',
282
+ description: '查看或修改术语清单。' + ACTION_HINT,
283
+ parameters: {
284
+ type: 'object',
285
+ properties: {
286
+ action: { type: 'string', enum: ['list', 'status', 'add', 'explain', 'remove', 'classify', 'preference', 'context'] },
287
+ terms: { type: 'array', items: { type: 'string' }, description: '术语列表' },
288
+ term: { type: 'string', description: '单个术语' },
289
+ category: { type: 'string', description: '类别:project 等' },
290
+ policy: { type: 'string', enum: ['explain', 'no-explain', 'auto'], description: '类别偏好' },
291
+ },
292
+ required: ['action'],
293
+ },
294
+ output: {
295
+ schema: { type: 'object', additionalProperties: true },
296
+ render: (_args, value) => [{ type: 'text', text: typeof value?.text === 'string' ? value.text : JSON.stringify(value) }],
297
+ },
298
+ async execute(args, toolCtx) {
299
+ const id = toolCtx?.agent?.id ?? toolCtx?.agent?.session?.id ?? null
300
+ const result = runVocabAction(id, args ?? {})
301
+ return { ok: result.ok, text: result.text }
302
+ },
303
+ }))
304
+
305
+ function knownTokensFor(sessionId) {
306
+ const store = readStore(vocabPath())
307
+ const known = Object.keys(store.decisions ?? {}).filter((term) => store.decisions[term]?.policy === 'no-explain')
308
+ const pending = sessions.get(sessionId)?.pending ?? getPending(store, sessionId)
309
+ for (const term of pending) {
310
+ const key = termKey(term)
311
+ for (let i = known.length - 1; i >= 0; i -= 1) if (termKey(known[i]) === key) known.splice(i, 1)
312
+ }
313
+ return known
314
+ }
315
+
316
+ function turnTexts(sessionId) {
317
+ if (!sessionId) return []
318
+ return sessions.get(sessionId)?.texts ?? []
319
+ }
320
+
321
+ function runVocabAction(sessionId, args) {
322
+ const action = String(args.action ?? '')
323
+ const list = [...(Array.isArray(args.terms) ? args.terms : []), ...(args.term ? [args.term] : [])]
324
+ .map((term) => String(term ?? '').trim())
325
+ .filter(Boolean)
326
+ const texts = turnTexts(sessionId)
327
+ const OK = (text) => ({ ok: true, text })
328
+ const NO = (text) => ({ ok: false, text })
329
+
330
+ if (action === 'list' || action === 'context') return OK(formatVocab(sessionId))
331
+ if (action === 'status') {
332
+ if (!list.length) return OK(formatVocab(sessionId))
333
+ const store = readStore(vocabPath())
334
+ return OK(list.map((term) => describeTerm(store, sessionId, term)).join('\n'))
335
+ }
336
+ if (action === 'preference') {
337
+ const category = String(args.category ?? '')
338
+ if (!['project', 'common'].includes(category)) {
339
+ return NO('只能按项目名(project)设置类别偏好,不支持领域、细分领域这类分类:无法确定哪些词属于该类别。')
340
+ }
341
+ const policy = String(args.policy ?? '')
342
+ if (!['explain', 'no-explain', 'auto'].includes(policy)) return NO('策略只能是 explain、no-explain 或 auto。')
343
+ if (!authorizeCategory(texts, category)) {
344
+ return NO('用户这一轮没有明确提出类别偏好:需要同一句里点名类别,并说明以后默认怎么处理或取消。')
345
+ }
346
+ updateStore(vocabPath(), (store) => {
347
+ if (policy === 'auto') delete store.preferences[category]
348
+ else store.preferences[category] = policy
349
+ return store
350
+ })
351
+ return OK(policy === 'auto' ? '已取消 ' + category + ' 类别偏好。' : '已设置 ' + category + ' 类别偏好为 ' + policy + '。')
352
+ }
353
+ if (!list.length) return NO('需要提供术语。')
354
+
355
+ if (action === 'add') {
356
+ const unsafe = list.filter((term) => !isSafeTerm(term))
357
+ if (unsafe.length) return NO('这些不像术语或疑似凭据,已拒绝:' + unsafe.join('、'))
358
+ const denied = list.filter((term) => !authorizeUserConfirmation(texts, term))
359
+ if (denied.length) {
360
+ return NO('用户这一轮没有明确说已经知道:' + denied.join('、') + '。只提问、只在任务里使用、或出现在举例/引用里,都不算确认。')
361
+ }
362
+ updateStore(vocabPath(), (store) => {
363
+ for (const term of list) setPolicy(store, term, 'no-explain')
364
+ return store
365
+ })
366
+ return OK('已加入免解释清单:' + list.join('、'))
367
+ }
368
+ if (action === 'explain') {
369
+ const denied = list.filter((term) => !authorizeExplainPolicy(texts, term))
370
+ if (denied.length) return NO('用户这一轮没有要求长期解释:' + denied.join('、') + '。一次性的“解释一下”不改变长期偏好。')
371
+ updateStore(vocabPath(), (store) => {
372
+ for (const term of list) setPolicy(store, term, 'explain')
373
+ return store
374
+ })
375
+ return OK('已标记为每次都要解释:' + list.join('、'))
376
+ }
377
+ if (action === 'remove') {
378
+ const store = readStore(vocabPath())
379
+ const missing = list.filter((term) => !findDecisionKey(store, term))
380
+ if (missing.length) return NO('这些词本来就不在长期清单里:' + missing.join('、'))
381
+ const denied = list.filter((term) => !authorizeRevoke(texts, term))
382
+ if (denied.length) return NO('用户这一轮没有要求取消:' + denied.join('、'))
383
+ updateStore(vocabPath(), (store2) => {
384
+ for (const term of list) clearPolicy(store2, term)
385
+ return store2
386
+ })
387
+ return OK('已取消长期设置:' + list.join('、'))
388
+ }
389
+ if (action === 'classify') {
390
+ const category = String(args.category ?? '')
391
+ if (!ALLOWED_CATEGORIES.includes(category)) return NO('类别只能是 common、domain、project 或 unclassified。')
392
+ if (!authorizeClassify(texts)) return NO('用户这一轮没有给出归类说法。')
393
+ updateStore(vocabPath(), (store) => {
394
+ for (const term of list) setCategoryPolicy(store, term, category)
395
+ return store
396
+ })
397
+ return OK('已归类为 ' + category + ':' + list.join('、'))
398
+ }
399
+ return NO('未知动作。' + ACTION_HINT)
400
+ }
401
+
402
+ function describeTerm(store, sessionId, term) {
403
+ const key = findDecisionKey(store, term)
404
+ const decision = key ? store.decisions[key] : null
405
+ const pending = sessions.get(sessionId)?.pending ?? getPending(store, sessionId)
406
+ const pendingKey = pending.find((item) => termKey(item) === termKey(term))
407
+ const observation = Object.keys(store.observations ?? {}).find((item) => termKey(item) === termKey(term))
408
+ const parts = []
409
+ if (decision?.policy === 'no-explain') parts.push('历史:用户确认过免解释')
410
+ if (decision?.policy === 'explain') parts.push('历史:用户要求每次都解释')
411
+ if (!decision) parts.push('没有长期设置')
412
+ if (pendingKey) parts.push('本轮用户提到了它,会要求解释一次,覆盖历史设置')
413
+ if (observation) parts.push('观察到使用 ' + String(store.observations[observation]?.count ?? 1) + ' 次')
414
+ return term + ':' + parts.join(';')
415
+ }
416
+
417
+ function formatVocab(sessionId) {
418
+ const store = readStore(vocabPath())
419
+ const explain = Object.keys(store.decisions ?? {}).filter((term) => store.decisions[term]?.policy === 'explain')
420
+ const silent = Object.keys(store.decisions ?? {}).filter((term) => store.decisions[term]?.policy === 'no-explain')
421
+ const pending = sessions.get(sessionId)?.pending ?? getPending(store, sessionId)
422
+ const preferences = Object.entries(store.preferences ?? {}).map(([category, policy]) => category + '=' + policy)
423
+ const lines = []
424
+ lines.push('免解释(' + silent.length + '):' + (silent.length ? silent.join('、') : '无'))
425
+ lines.push('每次解释(' + explain.length + '):' + (explain.length ? explain.join('、') : '无'))
426
+ lines.push('本轮待解释:' + (pending.length ? pending.join('、') : '无'))
427
+ lines.push('类别偏好:' + (preferences.length ? preferences.join('、') : '无'))
428
+ lines.push('观察词数:' + Object.keys(store.observations ?? {}).length)
429
+ return lines.join('\n')
430
+ }
431
+
432
+ return { sessionEnabled, setSessionEnabled }
433
+ }
434
+
435
+ // ---------- 小工具 ----------
436
+
437
+ function textOf(message) {
438
+ const content = message?.content
439
+ if (typeof content === 'string') return content.trim()
440
+ if (Array.isArray(content)) return content.filter((part) => part?.type === 'text').map((part) => part.text).join(' ').trim()
441
+ return ''
442
+ }
443
+
444
+ function lastUserRequestFromLog(log) {
445
+ if (!Array.isArray(log)) return ''
446
+ let from = 0
447
+ for (let i = log.length - 1; i >= 0; i -= 1) if (log[i]?.type === 'turn/start') { from = i + 1; break }
448
+ for (let i = log.length - 1; i >= from; i -= 1) {
449
+ const event = log[i]
450
+ if (event?.type !== 'user/message' && event?.type !== 'agent/inbox/spliced') continue
451
+ const message = event.data ?? {}
452
+ const kind = message.source?.kind
453
+ if (kind && kind !== 'user') continue
454
+ const text = textOf(message)
455
+ if (text && !NOT_USER_TEXT.test(text)) return text
456
+ }
457
+ return ''
458
+ }
459
+
460
+ // 本机回环判定:空 socket(Unix socket / 内部调用)、IPv6 ::1、
461
+ // 127.0.0.0/8 整段、以及 IPv4 映射的十六进制写法(::ffff:7f00:1)。
462
+ function isLoopbackAddress(remote) {
463
+ const raw = String(remote ?? '').trim().toLowerCase()
464
+ if (!raw) return true
465
+ if (raw === '::1' || raw === 'localhost') return true
466
+ const mapped = raw.startsWith('::ffff:') ? raw.slice(7) : raw
467
+ if (mapped.startsWith('127.')) return true
468
+ // ::ffff:7f00:1 这类十六进制映射,前两段 7f00:xxxx 覆盖 127.0.0.0/16
469
+ if (mapped.startsWith('7f00:')) return true
470
+ return false
471
+ }
472
+
473
+ function readSessionId(url) {
474
+ const query = String(url ?? '').split('?')[1] ?? ''
475
+ for (const pair of query.split('&')) {
476
+ const [key, value = ''] = pair.split('=')
477
+ if (key !== 'sessionId') continue
478
+ try { return decodeURIComponent(value) } catch { return value }
479
+ }
480
+ return ''
481
+ }
482
+
483
+ async function readBody(req) {
484
+ const chunks = []
485
+ if (req && typeof req[Symbol.asyncIterator] === 'function') {
486
+ for await (const chunk of req) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)))
487
+ return Buffer.concat(chunks).toString('utf8')
488
+ }
489
+ if (req && typeof req.on === 'function') {
490
+ await new Promise((resolve, reject) => {
491
+ req.on('data', (chunk) => chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk))))
492
+ req.on('end', resolve)
493
+ req.on('error', reject)
494
+ })
495
+ return Buffer.concat(chunks).toString('utf8')
496
+ }
497
+ return ''
498
+ }
499
+
500
+ function end(res, status, payload) {
501
+ if (res.statusCode !== undefined) res.statusCode = status
502
+ if (typeof res.setHeader === 'function') res.setHeader('content-type', 'application/json; charset=utf-8')
503
+ if (typeof res.end === 'function') res.end(JSON.stringify(payload))
504
+ }
505
+
506
+ function formatCheckResult(result) {
507
+ const issues = result?.issues ?? []
508
+ if (!issues.length) return '没有发现问题。'
509
+ return issues.map((issue) => '- [' + issue.severity + '] ' + issue.rule + ':' + issue.message).join('\n')
510
+ }