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.
package/dsh/index.js CHANGED
@@ -1,512 +1,512 @@
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
- case 'user/message': {
173
- // 两种来源:spliced 带 inserted 数组,user/message 直接是消息体。
174
- const incoming = Array.isArray(data.inserted) ? data.inserted : [data]
175
- for (const message of incoming) {
176
- const kind = message?.source?.kind
177
- if (kind && kind !== 'user') continue
178
- if (message?.role && message.role !== 'user') continue
179
- const text = textOf(message)
180
- if (!text || NOT_USER_TEXT.test(text)) continue
181
- // 真实事件顺序是 splice 先于 turn/start:按“文本所属轮次”判断跨轮。
182
- if (entry.textsTurn !== undefined && entry.textsTurn !== entry.turn) {
183
- entry.texts = []
184
- entry.request = ''
185
- entry.pending = []
186
- }
187
- entry.textsTurn = entry.turn
188
- entry.texts.push(text)
189
- entry.request = text
190
- entry.pending = [...new Set([...detectExplainRequest(text), ...extractObservedTerms(text)])].filter(isSafeTerm)
191
- if (enabled) recordTurn(id, entry.turn, text)
192
- }
193
- break
194
- }
195
- case 'turn/start': {
196
- entry.turn = Number(data.turn) || entry.turn || 1
197
- break
198
- }
199
- case 'turn/end': {
200
- if (enabled) clearPendingFor(id)
201
- entry.texts = []
202
- entry.request = ''
203
- entry.pending = []
204
- break
205
- }
206
- default:
207
- break
208
- }
209
- })
210
-
211
- function clearPendingFor(sessionId) {
212
- updateStore(vocabPath(), (store) => {
213
- clearPending(store, sessionId)
214
- return store
215
- })
216
- }
217
-
218
- function recordTurn(sessionId, turn, text) {
219
- const observed = extractObservedTerms(text)
220
- const pending = detectExplainRequest(text).filter(isSafeTerm)
221
- updateStore(vocabPath(), (store) => {
222
- recordObservations(store, observed)
223
- setPending(store, sessionId, turn, pending)
224
- return store
225
- })
226
- }
227
-
228
- // ---------- 浏览器状态路由 ----------
229
-
230
- ctx.inject(['webServer'], (scope) => {
231
- const server = scope.webServer
232
- if (!server || typeof server.register !== 'function') return
233
- scope.effect(() => server.register({
234
- path: ROUTE_STATE,
235
- handler: async (req, res) => {
236
- const remote = req?.socket?.remoteAddress ?? ''
237
- const loopback = isLoopbackAddress(req?.socket?.remoteAddress)
238
- if (!loopback) return end(res, 403, { ok: false, error: 'loopback only' })
239
- if (req.method === 'GET') {
240
- const sessionId = readSessionId(req.url)
241
- if (!sessionId) return end(res, 400, { ok: false, error: 'sessionId is required' })
242
- return end(res, 200, { ok: true, sessionId, enabled: sessionEnabled(sessionId), defaultOn: defaultEnabled })
243
- }
244
- if (req.method === 'POST') {
245
- const body = await readBody(req)
246
- let payload
247
- try { payload = JSON.parse(body || '{}') } catch { return end(res, 400, { ok: false, error: 'invalid json' }) }
248
- const sessionId = payload?.sessionId ?? readSessionId(req.url)
249
- if (!sessionId) return end(res, 400, { ok: false, error: 'sessionId is required' })
250
- if (typeof payload?.enabled !== 'boolean') return end(res, 400, { ok: false, error: 'enabled must be a boolean' })
251
- return end(res, 200, { ok: true, sessionId, enabled: setSessionEnabled(sessionId, payload.enabled), defaultOn: defaultEnabled })
252
- }
253
- return end(res, 405, { ok: false, error: 'method not allowed' })
254
- },
255
- }))
256
- })
257
-
258
- // ---------- 工具 ----------
259
-
260
- ctx.effect(() => ctx.tools.register({
261
- name: 'plain_talk_check',
262
- description: RULES,
263
- parameters: {
264
- type: 'object',
265
- properties: {
266
- draft: { type: 'string', description: '即将发送的回复正文' },
267
- },
268
- required: ['draft'],
269
- },
270
- output: {
271
- schema: { type: 'object', additionalProperties: true },
272
- render: (_args, value) => [{ type: 'text', text: typeof value?.text === 'string' ? value.text : JSON.stringify(value) }],
273
- },
274
- async execute(args, toolCtx) {
275
- const id = toolCtx?.agent?.id ?? toolCtx?.agent?.session?.id
276
- const known = knownTokensFor(id)
277
- const result = analyze(args?.draft ?? '', { language: 'zh', knownTokens: known })
278
- return { ok: true, text: formatCheckResult(result), ...result }
279
- },
280
- }))
281
-
282
- ctx.effect(() => ctx.tools.register({
283
- name: 'plain_talk_vocab',
284
- description: '查看或修改术语清单。' + ACTION_HINT,
285
- parameters: {
286
- type: 'object',
287
- properties: {
288
- action: { type: 'string', enum: ['list', 'status', 'add', 'explain', 'remove', 'classify', 'preference', 'context'] },
289
- terms: { type: 'array', items: { type: 'string' }, description: '术语列表' },
290
- term: { type: 'string', description: '单个术语' },
291
- category: { type: 'string', description: '类别:project 等' },
292
- policy: { type: 'string', enum: ['explain', 'no-explain', 'auto'], description: '类别偏好' },
293
- },
294
- required: ['action'],
295
- },
296
- output: {
297
- schema: { type: 'object', additionalProperties: true },
298
- render: (_args, value) => [{ type: 'text', text: typeof value?.text === 'string' ? value.text : JSON.stringify(value) }],
299
- },
300
- async execute(args, toolCtx) {
301
- const id = toolCtx?.agent?.id ?? toolCtx?.agent?.session?.id ?? null
302
- const result = runVocabAction(id, args ?? {})
303
- return { ok: result.ok, text: result.text }
304
- },
305
- }))
306
-
307
- function knownTokensFor(sessionId) {
308
- const store = readStore(vocabPath())
309
- const known = Object.keys(store.decisions ?? {}).filter((term) => store.decisions[term]?.policy === 'no-explain')
310
- const pending = sessions.get(sessionId)?.pending ?? getPending(store, sessionId)
311
- for (const term of pending) {
312
- const key = termKey(term)
313
- for (let i = known.length - 1; i >= 0; i -= 1) if (termKey(known[i]) === key) known.splice(i, 1)
314
- }
315
- return known
316
- }
317
-
318
- function turnTexts(sessionId) {
319
- if (!sessionId) return []
320
- return sessions.get(sessionId)?.texts ?? []
321
- }
322
-
323
- function runVocabAction(sessionId, args) {
324
- const action = String(args.action ?? '')
325
- const list = [...(Array.isArray(args.terms) ? args.terms : []), ...(args.term ? [args.term] : [])]
326
- .map((term) => String(term ?? '').trim())
327
- .filter(Boolean)
328
- const texts = turnTexts(sessionId)
329
- const OK = (text) => ({ ok: true, text })
330
- const NO = (text) => ({ ok: false, text })
331
-
332
- if (action === 'list' || action === 'context') return OK(formatVocab(sessionId))
333
- if (action === 'status') {
334
- if (!list.length) return OK(formatVocab(sessionId))
335
- const store = readStore(vocabPath())
336
- return OK(list.map((term) => describeTerm(store, sessionId, term)).join('\n'))
337
- }
338
- if (action === 'preference') {
339
- const category = String(args.category ?? '')
340
- if (!['project', 'common'].includes(category)) {
341
- return NO('只能按项目名(project)设置类别偏好,不支持领域、细分领域这类分类:无法确定哪些词属于该类别。')
342
- }
343
- const policy = String(args.policy ?? '')
344
- if (!['explain', 'no-explain', 'auto'].includes(policy)) return NO('策略只能是 explain、no-explain 或 auto。')
345
- if (!authorizeCategory(texts, category)) {
346
- return NO('用户这一轮没有明确提出类别偏好:需要同一句里点名类别,并说明以后默认怎么处理或取消。')
347
- }
348
- updateStore(vocabPath(), (store) => {
349
- if (policy === 'auto') delete store.preferences[category]
350
- else store.preferences[category] = policy
351
- return store
352
- })
353
- return OK(policy === 'auto' ? '已取消 ' + category + ' 类别偏好。' : '已设置 ' + category + ' 类别偏好为 ' + policy + '。')
354
- }
355
- if (!list.length) return NO('需要提供术语。')
356
-
357
- if (action === 'add') {
358
- const unsafe = list.filter((term) => !isSafeTerm(term))
359
- if (unsafe.length) return NO('这些不像术语或疑似凭据,已拒绝:' + unsafe.join('、'))
360
- const denied = list.filter((term) => !authorizeUserConfirmation(texts, term))
361
- if (denied.length) {
362
- return NO('用户这一轮没有明确说已经知道:' + denied.join('、') + '。只提问、只在任务里使用、或出现在举例/引用里,都不算确认。')
363
- }
364
- updateStore(vocabPath(), (store) => {
365
- for (const term of list) setPolicy(store, term, 'no-explain')
366
- return store
367
- })
368
- return OK('已加入免解释清单:' + list.join('、'))
369
- }
370
- if (action === 'explain') {
371
- const denied = list.filter((term) => !authorizeExplainPolicy(texts, term))
372
- if (denied.length) return NO('用户这一轮没有要求长期解释:' + denied.join('、') + '。一次性的“解释一下”不改变长期偏好。')
373
- updateStore(vocabPath(), (store) => {
374
- for (const term of list) setPolicy(store, term, 'explain')
375
- return store
376
- })
377
- return OK('已标记为每次都要解释:' + list.join('、'))
378
- }
379
- if (action === 'remove') {
380
- const store = readStore(vocabPath())
381
- const missing = list.filter((term) => !findDecisionKey(store, term))
382
- if (missing.length) return NO('这些词本来就不在长期清单里:' + missing.join('、'))
383
- const denied = list.filter((term) => !authorizeRevoke(texts, term))
384
- if (denied.length) return NO('用户这一轮没有要求取消:' + denied.join('、'))
385
- updateStore(vocabPath(), (store2) => {
386
- for (const term of list) clearPolicy(store2, term)
387
- return store2
388
- })
389
- return OK('已取消长期设置:' + list.join('、'))
390
- }
391
- if (action === 'classify') {
392
- const category = String(args.category ?? '')
393
- if (!ALLOWED_CATEGORIES.includes(category)) return NO('类别只能是 common、domain、project 或 unclassified。')
394
- if (!authorizeClassify(texts)) return NO('用户这一轮没有给出归类说法。')
395
- updateStore(vocabPath(), (store) => {
396
- for (const term of list) setCategoryPolicy(store, term, category)
397
- return store
398
- })
399
- return OK('已归类为 ' + category + ':' + list.join('、'))
400
- }
401
- return NO('未知动作。' + ACTION_HINT)
402
- }
403
-
404
- function describeTerm(store, sessionId, term) {
405
- const key = findDecisionKey(store, term)
406
- const decision = key ? store.decisions[key] : null
407
- const pending = sessions.get(sessionId)?.pending ?? getPending(store, sessionId)
408
- const pendingKey = pending.find((item) => termKey(item) === termKey(term))
409
- const observation = Object.keys(store.observations ?? {}).find((item) => termKey(item) === termKey(term))
410
- const parts = []
411
- if (decision?.policy === 'no-explain') parts.push('历史:用户确认过免解释')
412
- if (decision?.policy === 'explain') parts.push('历史:用户要求每次都解释')
413
- if (!decision) parts.push('没有长期设置')
414
- if (pendingKey) parts.push('本轮用户提到了它,会要求解释一次,覆盖历史设置')
415
- if (observation) parts.push('观察到使用 ' + String(store.observations[observation]?.count ?? 1) + ' 次')
416
- return term + ':' + parts.join(';')
417
- }
418
-
419
- function formatVocab(sessionId) {
420
- const store = readStore(vocabPath())
421
- const explain = Object.keys(store.decisions ?? {}).filter((term) => store.decisions[term]?.policy === 'explain')
422
- const silent = Object.keys(store.decisions ?? {}).filter((term) => store.decisions[term]?.policy === 'no-explain')
423
- const pending = sessions.get(sessionId)?.pending ?? getPending(store, sessionId)
424
- const preferences = Object.entries(store.preferences ?? {}).map(([category, policy]) => category + '=' + policy)
425
- const lines = []
426
- lines.push('免解释(' + silent.length + '):' + (silent.length ? silent.join('、') : '无'))
427
- lines.push('每次解释(' + explain.length + '):' + (explain.length ? explain.join('、') : '无'))
428
- lines.push('本轮待解释:' + (pending.length ? pending.join('、') : '无'))
429
- lines.push('类别偏好:' + (preferences.length ? preferences.join('、') : '无'))
430
- lines.push('观察词数:' + Object.keys(store.observations ?? {}).length)
431
- return lines.join('\n')
432
- }
433
-
434
- return { sessionEnabled, setSessionEnabled }
435
- }
436
-
437
- // ---------- 小工具 ----------
438
-
439
- function textOf(message) {
440
- const content = message?.content
441
- if (typeof content === 'string') return content.trim()
442
- if (Array.isArray(content)) return content.filter((part) => part?.type === 'text').map((part) => part.text).join(' ').trim()
443
- return ''
444
- }
445
-
446
- function lastUserRequestFromLog(log) {
447
- if (!Array.isArray(log)) return ''
448
- let from = 0
449
- for (let i = log.length - 1; i >= 0; i -= 1) if (log[i]?.type === 'turn/start') { from = i + 1; break }
450
- for (let i = log.length - 1; i >= from; i -= 1) {
451
- const event = log[i]
452
- if (event?.type !== 'user/message' && event?.type !== 'agent/inbox/spliced') continue
453
- const message = event.data ?? {}
454
- const kind = message.source?.kind
455
- if (kind && kind !== 'user') continue
456
- const text = textOf(message)
457
- if (text && !NOT_USER_TEXT.test(text)) return text
458
- }
459
- return ''
460
- }
461
-
462
- // 本机回环判定:空 socket(Unix socket / 内部调用)、IPv6 ::1、
463
- // 127.0.0.0/8 整段、以及 IPv4 映射的十六进制写法(::ffff:7f00:1)。
464
- function isLoopbackAddress(remote) {
465
- const raw = String(remote ?? '').trim().toLowerCase()
466
- if (!raw) return true
467
- if (raw === '::1' || raw === 'localhost') return true
468
- const mapped = raw.startsWith('::ffff:') ? raw.slice(7) : raw
469
- if (mapped.startsWith('127.')) return true
470
- // ::ffff:7f00:1 这类十六进制映射,前两段 7f00:xxxx 覆盖 127.0.0.0/16
471
- if (mapped.startsWith('7f00:')) return true
472
- return false
473
- }
474
-
475
- function readSessionId(url) {
476
- const query = String(url ?? '').split('?')[1] ?? ''
477
- for (const pair of query.split('&')) {
478
- const [key, value = ''] = pair.split('=')
479
- if (key !== 'sessionId') continue
480
- try { return decodeURIComponent(value) } catch { return value }
481
- }
482
- return ''
483
- }
484
-
485
- async function readBody(req) {
486
- const chunks = []
487
- if (req && typeof req[Symbol.asyncIterator] === 'function') {
488
- for await (const chunk of req) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)))
489
- return Buffer.concat(chunks).toString('utf8')
490
- }
491
- if (req && typeof req.on === 'function') {
492
- await new Promise((resolve, reject) => {
493
- req.on('data', (chunk) => chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk))))
494
- req.on('end', resolve)
495
- req.on('error', reject)
496
- })
497
- return Buffer.concat(chunks).toString('utf8')
498
- }
499
- return ''
500
- }
501
-
502
- function end(res, status, payload) {
503
- if (res.statusCode !== undefined) res.statusCode = status
504
- if (typeof res.setHeader === 'function') res.setHeader('content-type', 'application/json; charset=utf-8')
505
- if (typeof res.end === 'function') res.end(JSON.stringify(payload))
506
- }
507
-
508
- function formatCheckResult(result) {
509
- const issues = result?.issues ?? []
510
- if (!issues.length) return '没有发现问题。'
511
- return issues.map((issue) => '- [' + issue.severity + '] ' + issue.rule + ':' + issue.message).join('\n')
512
- }
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
+ case 'user/message': {
173
+ // 两种来源:spliced 带 inserted 数组,user/message 直接是消息体。
174
+ const incoming = Array.isArray(data.inserted) ? data.inserted : [data]
175
+ for (const message of incoming) {
176
+ const kind = message?.source?.kind
177
+ if (kind && kind !== 'user') continue
178
+ if (message?.role && message.role !== 'user') continue
179
+ const text = textOf(message)
180
+ if (!text || NOT_USER_TEXT.test(text)) continue
181
+ // 真实事件顺序是 splice 先于 turn/start:按“文本所属轮次”判断跨轮。
182
+ if (entry.textsTurn !== undefined && entry.textsTurn !== entry.turn) {
183
+ entry.texts = []
184
+ entry.request = ''
185
+ entry.pending = []
186
+ }
187
+ entry.textsTurn = entry.turn
188
+ entry.texts.push(text)
189
+ entry.request = text
190
+ entry.pending = [...new Set([...detectExplainRequest(text), ...extractObservedTerms(text)])].filter(isSafeTerm)
191
+ if (enabled) recordTurn(id, entry.turn, text)
192
+ }
193
+ break
194
+ }
195
+ case 'turn/start': {
196
+ entry.turn = Number(data.turn) || entry.turn || 1
197
+ break
198
+ }
199
+ case 'turn/end': {
200
+ if (enabled) clearPendingFor(id)
201
+ entry.texts = []
202
+ entry.request = ''
203
+ entry.pending = []
204
+ break
205
+ }
206
+ default:
207
+ break
208
+ }
209
+ })
210
+
211
+ function clearPendingFor(sessionId) {
212
+ updateStore(vocabPath(), (store) => {
213
+ clearPending(store, sessionId)
214
+ return store
215
+ })
216
+ }
217
+
218
+ function recordTurn(sessionId, turn, text) {
219
+ const observed = extractObservedTerms(text)
220
+ const pending = detectExplainRequest(text).filter(isSafeTerm)
221
+ updateStore(vocabPath(), (store) => {
222
+ recordObservations(store, observed)
223
+ setPending(store, sessionId, turn, pending)
224
+ return store
225
+ })
226
+ }
227
+
228
+ // ---------- 浏览器状态路由 ----------
229
+
230
+ ctx.inject(['webServer'], (scope) => {
231
+ const server = scope.webServer
232
+ if (!server || typeof server.register !== 'function') return
233
+ scope.effect(() => server.register({
234
+ path: ROUTE_STATE,
235
+ handler: async (req, res) => {
236
+ const remote = req?.socket?.remoteAddress ?? ''
237
+ const loopback = isLoopbackAddress(req?.socket?.remoteAddress)
238
+ if (!loopback) return end(res, 403, { ok: false, error: 'loopback only' })
239
+ if (req.method === 'GET') {
240
+ const sessionId = readSessionId(req.url)
241
+ if (!sessionId) return end(res, 400, { ok: false, error: 'sessionId is required' })
242
+ return end(res, 200, { ok: true, sessionId, enabled: sessionEnabled(sessionId), defaultOn: defaultEnabled })
243
+ }
244
+ if (req.method === 'POST') {
245
+ const body = await readBody(req)
246
+ let payload
247
+ try { payload = JSON.parse(body || '{}') } catch { return end(res, 400, { ok: false, error: 'invalid json' }) }
248
+ const sessionId = payload?.sessionId ?? readSessionId(req.url)
249
+ if (!sessionId) return end(res, 400, { ok: false, error: 'sessionId is required' })
250
+ if (typeof payload?.enabled !== 'boolean') return end(res, 400, { ok: false, error: 'enabled must be a boolean' })
251
+ return end(res, 200, { ok: true, sessionId, enabled: setSessionEnabled(sessionId, payload.enabled), defaultOn: defaultEnabled })
252
+ }
253
+ return end(res, 405, { ok: false, error: 'method not allowed' })
254
+ },
255
+ }))
256
+ })
257
+
258
+ // ---------- 工具 ----------
259
+
260
+ ctx.effect(() => ctx.tools.register({
261
+ name: 'plain_talk_check',
262
+ description: RULES,
263
+ parameters: {
264
+ type: 'object',
265
+ properties: {
266
+ draft: { type: 'string', description: '即将发送的回复正文' },
267
+ },
268
+ required: ['draft'],
269
+ },
270
+ output: {
271
+ schema: { type: 'object', additionalProperties: true },
272
+ render: (_args, value) => [{ type: 'text', text: typeof value?.text === 'string' ? value.text : JSON.stringify(value) }],
273
+ },
274
+ async execute(args, toolCtx) {
275
+ const id = toolCtx?.agent?.id ?? toolCtx?.agent?.session?.id
276
+ const known = knownTokensFor(id)
277
+ const result = analyze(args?.draft ?? '', { language: 'zh', knownTokens: known })
278
+ return { ok: true, text: formatCheckResult(result), ...result }
279
+ },
280
+ }))
281
+
282
+ ctx.effect(() => ctx.tools.register({
283
+ name: 'plain_talk_vocab',
284
+ description: '维护读者术语清单,并回答某个词当前是否免解释。'
285
+ + ' 当用户在本轮明确说"这个词我懂 / 不用解释 / 我了解"时,用 action=add 记下该词;'
286
+ + ' 当用户说"以后每次都解释 X"时,用 action=explain;'
287
+ + ' 用户问"这个词现在是什么状态"时用 action=status。'
288
+ + ' 用户没有明确表态时不要调用,本工具不会替你推断。'
289
+ + ACTION_HINT,
290
+ parameters: {
291
+ type: 'object',
292
+ properties: {
293
+ action: { type: 'string', enum: ['list', 'status', 'add', 'explain', 'remove', 'classify', 'preference', 'context'] },
294
+ terms: { type: 'array', items: { type: 'string' }, description: '术语列表' },
295
+ term: { type: 'string', description: '单个术语' },
296
+ category: { type: 'string', description: '类别:project 等' },
297
+ policy: { type: 'string', enum: ['explain', 'no-explain', 'auto'], description: '类别偏好' },
298
+ },
299
+ required: ['action'],
300
+ },
301
+ output: {
302
+ schema: { type: 'object', additionalProperties: true },
303
+ render: (_args, value) => [{ type: 'text', text: typeof value?.text === 'string' ? value.text : JSON.stringify(value) }],
304
+ },
305
+ async execute(args, toolCtx) {
306
+ const id = toolCtx?.agent?.id ?? toolCtx?.agent?.session?.id ?? null
307
+ const result = runVocabAction(id, args ?? {})
308
+ return { ok: result.ok, text: result.text }
309
+ },
310
+ }))
311
+
312
+ function knownTokensFor(sessionId) {
313
+ const store = readStore(vocabPath())
314
+ const known = Object.keys(store.decisions ?? {}).filter((term) => store.decisions[term]?.policy === 'no-explain')
315
+ const pending = sessions.get(sessionId)?.pending ?? getPending(store, sessionId)
316
+ for (const term of pending) {
317
+ const key = termKey(term)
318
+ for (let i = known.length - 1; i >= 0; i -= 1) if (termKey(known[i]) === key) known.splice(i, 1)
319
+ }
320
+ return known
321
+ }
322
+
323
+ function turnTexts(sessionId) {
324
+ if (!sessionId) return []
325
+ return sessions.get(sessionId)?.texts ?? []
326
+ }
327
+
328
+ function runVocabAction(sessionId, args) {
329
+ const action = String(args.action ?? '')
330
+ const list = [...(Array.isArray(args.terms) ? args.terms : []), ...(args.term ? [args.term] : [])]
331
+ .map((term) => String(term ?? '').trim())
332
+ .filter(Boolean)
333
+ const texts = turnTexts(sessionId)
334
+ const OK = (text) => ({ ok: true, text })
335
+ const NO = (text) => ({ ok: false, text })
336
+
337
+ if (action === 'list' || action === 'context') return OK(formatVocab(sessionId))
338
+ if (action === 'status') {
339
+ if (!list.length) return OK(formatVocab(sessionId))
340
+ const store = readStore(vocabPath())
341
+ return OK(list.map((term) => describeTerm(store, sessionId, term)).join('\n'))
342
+ }
343
+ if (action === 'preference') {
344
+ const category = String(args.category ?? '')
345
+ if (!['project', 'common'].includes(category)) {
346
+ return NO('只能按项目名(project)设置类别偏好,不支持领域、细分领域这类分类:无法确定哪些词属于该类别。')
347
+ }
348
+ const policy = String(args.policy ?? '')
349
+ if (!['explain', 'no-explain', 'auto'].includes(policy)) return NO('策略只能是 explain、no-explain 或 auto。')
350
+ if (!authorizeCategory(texts, category)) {
351
+ return NO('用户这一轮没有明确提出类别偏好:需要同一句里点名类别,并说明以后默认怎么处理或取消。')
352
+ }
353
+ updateStore(vocabPath(), (store) => {
354
+ if (policy === 'auto') delete store.preferences[category]
355
+ else store.preferences[category] = policy
356
+ return store
357
+ })
358
+ return OK(policy === 'auto' ? '已取消 ' + category + ' 类别偏好。' : '已设置 ' + category + ' 类别偏好为 ' + policy + '。')
359
+ }
360
+ if (!list.length) return NO('需要提供术语。')
361
+
362
+ if (action === 'add') {
363
+ const unsafe = list.filter((term) => !isSafeTerm(term))
364
+ if (unsafe.length) return NO('这些不像术语或疑似凭据,已拒绝:' + unsafe.join('、'))
365
+ const denied = list.filter((term) => !authorizeUserConfirmation(texts, term))
366
+ if (denied.length) {
367
+ return NO('用户这一轮没有明确说已经知道:' + denied.join('、') + '。只提问、只在任务里使用、或出现在举例/引用里,都不算确认。')
368
+ }
369
+ updateStore(vocabPath(), (store) => {
370
+ for (const term of list) setPolicy(store, term, 'no-explain')
371
+ return store
372
+ })
373
+ return OK('已加入免解释清单:' + list.join('、'))
374
+ }
375
+ if (action === 'explain') {
376
+ const denied = list.filter((term) => !authorizeExplainPolicy(texts, term))
377
+ if (denied.length) return NO('用户这一轮没有要求长期解释:' + denied.join('、') + '。一次性的“解释一下”不改变长期偏好。')
378
+ updateStore(vocabPath(), (store) => {
379
+ for (const term of list) setPolicy(store, term, 'explain')
380
+ return store
381
+ })
382
+ return OK('已标记为每次都要解释:' + list.join('、'))
383
+ }
384
+ if (action === 'remove') {
385
+ const store = readStore(vocabPath())
386
+ const missing = list.filter((term) => !findDecisionKey(store, term))
387
+ if (missing.length) return NO('这些词本来就不在长期清单里:' + missing.join('、'))
388
+ const denied = list.filter((term) => !authorizeRevoke(texts, term))
389
+ if (denied.length) return NO('用户这一轮没有要求取消:' + denied.join('、'))
390
+ updateStore(vocabPath(), (store2) => {
391
+ for (const term of list) clearPolicy(store2, term)
392
+ return store2
393
+ })
394
+ return OK('已取消长期设置:' + list.join('、'))
395
+ }
396
+ if (action === 'classify') {
397
+ const category = String(args.category ?? '')
398
+ if (!ALLOWED_CATEGORIES.includes(category)) return NO('类别只能是 common、domain、project 或 unclassified。')
399
+ if (!authorizeClassify(texts)) return NO('用户这一轮没有给出归类说法。')
400
+ updateStore(vocabPath(), (store) => {
401
+ for (const term of list) setCategoryPolicy(store, term, category)
402
+ return store
403
+ })
404
+ return OK('已归类为 ' + category + ':' + list.join('、'))
405
+ }
406
+ return NO('未知动作。' + ACTION_HINT)
407
+ }
408
+
409
+ function describeTerm(store, sessionId, term) {
410
+ const key = findDecisionKey(store, term)
411
+ const decision = key ? store.decisions[key] : null
412
+ const pending = sessions.get(sessionId)?.pending ?? getPending(store, sessionId)
413
+ const pendingKey = pending.find((item) => termKey(item) === termKey(term))
414
+ const observation = Object.keys(store.observations ?? {}).find((item) => termKey(item) === termKey(term))
415
+ const parts = []
416
+ if (decision?.policy === 'no-explain') parts.push('历史:用户确认过免解释')
417
+ if (decision?.policy === 'explain') parts.push('历史:用户要求每次都解释')
418
+ if (!decision) parts.push('没有长期设置')
419
+ if (pendingKey) parts.push('本轮用户提到了它,会要求解释一次,覆盖历史设置')
420
+ if (observation) parts.push('观察到使用 ' + String(store.observations[observation]?.count ?? 1) + ' 次')
421
+ return term + ':' + parts.join(';')
422
+ }
423
+
424
+ function formatVocab(sessionId) {
425
+ const store = readStore(vocabPath())
426
+ const explain = Object.keys(store.decisions ?? {}).filter((term) => store.decisions[term]?.policy === 'explain')
427
+ const silent = Object.keys(store.decisions ?? {}).filter((term) => store.decisions[term]?.policy === 'no-explain')
428
+ const pending = sessions.get(sessionId)?.pending ?? getPending(store, sessionId)
429
+ const preferences = Object.entries(store.preferences ?? {}).map(([category, policy]) => category + '=' + policy)
430
+ const lines = []
431
+ lines.push('免解释(' + silent.length + '):' + (silent.length ? silent.join('、') : '无'))
432
+ lines.push('每次解释(' + explain.length + '):' + (explain.length ? explain.join('、') : '无'))
433
+ lines.push('本轮待解释:' + (pending.length ? pending.join('、') : '无'))
434
+ lines.push('类别偏好:' + (preferences.length ? preferences.join('、') : '无'))
435
+ lines.push('观察词数:' + Object.keys(store.observations ?? {}).length)
436
+ return lines.join('\n')
437
+ }
438
+
439
+ return { sessionEnabled, setSessionEnabled }
440
+ }
441
+
442
+ // ---------- 小工具 ----------
443
+
444
+ function textOf(message) {
445
+ const content = message?.content
446
+ if (typeof content === 'string') return content.trim()
447
+ if (Array.isArray(content)) return content.filter((part) => part?.type === 'text').map((part) => part.text).join(' ').trim()
448
+ return ''
449
+ }
450
+
451
+ function lastUserRequestFromLog(log) {
452
+ if (!Array.isArray(log)) return ''
453
+ let from = 0
454
+ for (let i = log.length - 1; i >= 0; i -= 1) if (log[i]?.type === 'turn/start') { from = i + 1; break }
455
+ for (let i = log.length - 1; i >= from; i -= 1) {
456
+ const event = log[i]
457
+ if (event?.type !== 'user/message' && event?.type !== 'agent/inbox/spliced') continue
458
+ const message = event.data ?? {}
459
+ const kind = message.source?.kind
460
+ if (kind && kind !== 'user') continue
461
+ const text = textOf(message)
462
+ if (text && !NOT_USER_TEXT.test(text)) return text
463
+ }
464
+ return ''
465
+ }
466
+
467
+ // 本机回环判定:空 socket(Unix socket / 内部调用)、IPv6 ::1、
468
+ // 127.0.0.0/8 整段、以及 IPv4 映射的十六进制写法(::ffff:7f00:1)。
469
+ function isLoopbackAddress(remote) {
470
+ const raw = String(remote ?? '').trim().toLowerCase()
471
+ if (!raw) return true
472
+ if (raw === '::1' || raw === 'localhost') return true
473
+ const mapped = raw.startsWith('::ffff:') ? raw.slice(7) : raw
474
+ if (mapped.startsWith('127.')) return true
475
+ // ::ffff:7f00:1 这类十六进制映射,前两段 7f00:xxxx 覆盖 127.0.0.0/16
476
+ if (mapped.startsWith('7f00:')) return true
477
+ return false
478
+ }
479
+
480
+ function readSessionId(url) {
481
+ const query = String(url ?? '').split('?')[1] ?? ''
482
+ for (const pair of query.split('&')) {
483
+ const [key, value = ''] = pair.split('=')
484
+ if (key !== 'sessionId') continue
485
+ try { return decodeURIComponent(value) } catch { return value }
486
+ }
487
+ return ''
488
+ }
489
+
490
+ async function readBody(req) {
491
+ const chunks = []
492
+ if (req && typeof req[Symbol.asyncIterator] === 'function') {
493
+ for await (const chunk of req) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)))
494
+ return Buffer.concat(chunks).toString('utf8')
495
+ }
496
+ if (req && typeof req.on === 'function') {
497
+ await new Promise((resolve, reject) => {
498
+ req.on('data', (chunk) => chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk))))
499
+ req.on('end', resolve)
500
+ req.on('error', reject)
501
+ })
502
+ return Buffer.concat(chunks).toString('utf8')
503
+ }
504
+ return ''
505
+ }
506
+
507
+ function end(res, status, payload) {
508
+ if (res.statusCode !== undefined) res.statusCode = status
509
+ if (typeof res.setHeader === 'function') res.setHeader('content-type', 'application/json; charset=utf-8')
510
+ if (typeof res.end === 'function') res.end(JSON.stringify(payload))
511
+ }
512
+
513
+ function formatCheckResult(result) {
514
+ const issues = result?.issues ?? []
515
+ if (!issues.length) return '没有发现问题。'
516
+ return issues.map((issue) => '- [' + issue.severity + '] ' + issue.rule + ':' + issue.message).join('\n')
517
+ }