dsh-plain-talk 0.1.13 → 0.1.15

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,479 +1,503 @@
1
- // dsh-plain-talk — host half.
2
- //
3
- // Four jobs:
4
- // - one persisted switch per Session (`$DSH_HOME/plain-talk.json`) that the
5
- // composer button flips over the loopback state route;
6
- // - one system-prompt section whose text appears only while that Session's
7
- // switch is on;
8
- // - one user vocabulary (`$DSH_HOME/plain-talk-vocab.json`) shared by every
9
- // Session, so "the user already knows this word" survives restarts;
10
- // - two optional tools: a reply self-check and vocabulary maintenance.
11
- //
12
- // Research requests are two-phase: "调研 X" marks X pending for that Session,
13
- // so the first reply must still explain it; the next turn end promotes X into
14
- // the vocabulary.
15
- //
16
- // The plugin writes no session events: switches and vocabulary are sidecar
17
- // files, and the prompt section is derived state.
18
-
19
- import { readFileSync, mkdirSync, renameSync, writeFileSync } from 'node:fs'
20
- import { homedir } from 'node:os'
21
- import { dirname, join } from 'node:path'
22
- import { RULES } from './rules.js'
23
- import { analyze, scanIdentifiers, isCommonTerm } from './check.js'
24
- import {
25
- CATEGORIES,
26
- addTerm,
27
- isCodeLike,
28
- knownSet,
29
- listByCategory,
30
- loadVocab,
31
- markPending,
32
- pendingFor,
33
- promotePending,
34
- removeTerm,
35
- saveVocab,
36
- setCategory,
37
- researchTargets,
38
- } from './vocab.js'
39
-
40
- export const name = 'plain-talk'
41
-
42
- // systemPrompt and tools are required; webServer is reached through ctx.inject
43
- // so the plugin still mounts in profiles without the Web surface.
44
- export const inject = ['systemPrompt', 'tools']
45
-
46
- const SECTION_NAME = 'plain-talk'
47
- // After the persona (0) and next to the other reply-style sections, before
48
- // tool guidance (100+).
49
- const SECTION_ORDER = 55
50
-
51
- const ROUTE_STATE = '/plain-talk/state'
52
- const MAX_BODY = 8 * 1024
53
- const MAX_SESSIONS = 256
54
-
55
- /** New Sessions start off; one click turns the mode on and records that choice.
56
- * PLAIN_TALK_DEFAULT=on makes unseen Sessions start on. */
57
- const DEFAULT_ON = String(process.env.PLAIN_TALK_DEFAULT ?? 'off').toLowerCase() === 'on'
58
-
59
- function dshHome() {
60
- return process.env.DSH_HOME && process.env.DSH_HOME.length > 0
61
- ? process.env.DSH_HOME
62
- : join(homedir(), '.dsh')
63
- }
64
-
65
- function statePath() {
66
- return join(dshHome(), 'plain-talk.json')
67
- }
68
-
69
- function vocabPath() {
70
- return join(dshHome(), 'plain-talk-vocab.json')
71
- }
72
-
73
- function emptyState() {
74
- return { version: 1, sessions: {} }
75
- }
76
-
77
- function readState() {
78
- try {
79
- const parsed = JSON.parse(readFileSync(statePath(), 'utf8'))
80
- const raw = parsed && typeof parsed === 'object' && parsed.sessions && typeof parsed.sessions === 'object' ? parsed.sessions : {}
81
- const sessions = {}
82
- for (const [id, value] of Object.entries(raw)) {
83
- if (typeof id === 'string' && id.length > 0 && typeof value === 'boolean') sessions[id] = value
84
- }
85
- return { version: 1, sessions }
86
- } catch {
87
- // A missing, unreadable or malformed file reads as "no choices recorded";
88
- // DEFAULT_ON then applies, and a broken file can never lock the mode on.
89
- return emptyState()
90
- }
91
- }
92
-
93
- function sessionEnabled(state, sessionId) {
94
- if (typeof sessionId !== 'string' || sessionId.length === 0) return false
95
- if (Object.prototype.hasOwnProperty.call(state.sessions, sessionId)) return state.sessions[sessionId] === true
96
- return DEFAULT_ON
97
- }
98
-
99
- function persistJson(file, value) {
100
- mkdirSync(dirname(file), { recursive: true })
101
- const tmp = `${file}.${process.pid}.${Date.now()}.tmp`
102
- writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`, 'utf8')
103
- renameSync(tmp, file)
104
- }
105
-
106
- function setSessionEnabled(state, sessionId, enabled) {
107
- if (typeof sessionId !== 'string' || sessionId.length === 0) throw new Error('sessionId is required')
108
- const sessions = { ...state.sessions }
109
- sessions[sessionId] = enabled === true
110
- while (Object.keys(sessions).length > MAX_SESSIONS) {
111
- const oldest = Object.keys(sessions)[0]
112
- if (oldest === undefined) break
113
- delete sessions[oldest]
114
- }
115
- const next = { version: 1, sessions }
116
- persistJson(statePath(), next)
117
- return next
118
- }
119
-
120
- function sessionIdOf(context) {
121
- const agent = context === undefined || context === null ? undefined : context.agent
122
- if (agent === undefined || agent === null) return undefined
123
- const direct = agent.session !== undefined && agent.session !== null ? agent.session.id : undefined
124
- if (typeof direct === 'string' && direct.length > 0) return direct
125
- if (typeof agent.id === 'string' && agent.id.length > 0) return agent.id
126
- return undefined
127
- }
128
-
129
- /** The Session's directory, when the runtime exposes it. */
130
- function cwdOf(agent) {
131
- const session = agent && agent.session
132
- const header = session && session.header
133
- const value = (header && header.cwd) || (session && session.cwd) || (agent && agent.cwd)
134
- return typeof value === 'string' && value.length > 0 ? value : undefined
135
- }
136
-
137
- function projectName(cwd) {
138
- if (typeof cwd !== 'string' || cwd.length === 0) return undefined
139
- const parts = cwd.split(/[\\/]/).filter(Boolean)
140
- const last = parts[parts.length - 1]
141
- return last && last.length >= 3 ? last : undefined
142
- }
143
-
144
- function textOf(message) {
145
- if (!message || !Array.isArray(message.content)) return ''
146
- return message.content.filter((b) => b && b.type === 'text' && typeof b.text === 'string').map((b) => b.text).join('\n')
147
- }
148
-
149
- function isLoopback(req) {
150
- const address = req && req.socket ? req.socket.remoteAddress : undefined
151
- if (typeof address !== 'string') return false
152
- return address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1'
153
- }
154
-
155
- async function readJson(req) {
156
- const chunks = []
157
- let size = 0
158
- for await (const chunk of req) {
159
- size += chunk.length
160
- if (size > MAX_BODY) return undefined
161
- chunks.push(chunk)
162
- }
163
- try {
164
- const parsed = JSON.parse(Buffer.concat(chunks).toString('utf8'))
165
- return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : undefined
166
- } catch {
167
- return undefined
168
- }
169
- }
170
-
171
- function sendJson(res, status, body) {
172
- res.statusCode = status
173
- res.setHeader('content-type', 'application/json; charset=utf-8')
174
- res.setHeader('cache-control', 'no-store')
175
- res.end(JSON.stringify(body))
176
- }
177
-
178
- const VALID_SESSION_ID = /^[A-Za-z0-9_.:-]{1,200}$/
179
-
180
- export function apply(ctx) {
181
- let state = readState()
182
- let userVocab = loadVocab(vocabPath())
183
-
184
- // Language mix per Session. Vocabulary is profile-wide; this is not.
185
- const language = new Map()
186
-
187
- const rememberUserText = (sessionId, text) => {
188
- if (!sessionId || !text) return
189
- const entry = language.get(sessionId) ?? { zh: 0, latin: 0 }
190
- entry.zh += (text.match(/[\u4e00-\u9fff]/g) ?? []).length
191
- entry.latin += (text.match(/[A-Za-z]/g) ?? []).length
192
- language.set(sessionId, entry)
193
- while (language.size > MAX_SESSIONS) {
194
- const oldest = language.keys().next().value
195
- if (oldest === undefined) break
196
- language.delete(oldest)
197
- }
198
-
199
- // Research subjects stay unknown until this turn's reply is delivered.
200
- const targets = researchTargets(text).filter((term) => !isCommonTerm(term))
201
- for (const term of targets) markPending(userVocab, sessionId, term)
202
-
203
- // Everything else the user typed is vocabulary they already hold.
204
- const pending = new Set(targets)
205
- for (const found of scanIdentifiers(text)) {
206
- if (found.token.includes('/') || found.token.includes('\\')) continue
207
- if (pending.has(found.token)) continue
208
- addTerm(userVocab, found.token, { session: sessionId, source: 'user' })
209
- }
210
- saveVocab(vocabPath(), userVocab)
211
- }
212
-
213
- const knownFor = (sessionId, agent) => {
214
- const tokens = new Set(knownSet(userVocab, sessionId))
215
- const project = projectName(cwdOf(agent))
216
- if (project) tokens.add(project)
217
- return [...tokens]
218
- }
219
-
220
- const languageFor = (sessionId) => {
221
- const entry = language.get(sessionId)
222
- if (!entry) return 'unknown'
223
- const total = entry.zh + entry.latin
224
- if (total === 0) return 'unknown'
225
- return entry.zh / total >= 0.3 ? 'zh' : 'en'
226
- }
227
-
228
- ctx.effect(() => ctx.on('session/event', (session, event) => {
229
- if (!event || event.type !== 'user/message') return
230
- const sessionId = session?.id ?? session?.sessionId
231
- const text = textOf(event.data)
232
- if (!sessionId || !text) return
233
- // Only the human's own words count as vocabulary. Approval notices,
234
- // runtime reminders and time-sampled injects are not the user's language.
235
- const source = event.data?.source
236
- if (source && source.kind !== 'user') return
237
- if (/^(?:Time sampled|Elapsed since|Current runtime context|Current working directory|<system-reminder>)/i.test(text.trim())) return
238
- rememberUserText(String(sessionId), text)
239
- }))
240
-
241
- // Turn end: the reply has been sent, so a research subject is now known.
242
- ctx.effect(() => ctx.on('agent/turn-stopping', (payload) => {
243
- const sessionId = payload?.agent?.id
244
- if (!sessionId) return
245
- const promoted = promotePending(userVocab, String(sessionId), { cwdName: projectName(cwdOf(payload.agent)) })
246
- if (promoted.length > 0) saveVocab(vocabPath(), userVocab)
247
- }))
248
-
249
- // Prompt section: empty string when the Session has the switch off.
250
- ctx.effect(() => ctx.systemPrompt.section({
251
- name: SECTION_NAME,
252
- order: SECTION_ORDER,
253
- text: (context) => {
254
- try {
255
- const sessionId = sessionIdOf(context)
256
- if (!sessionId) return ''
257
- return sessionEnabled(state, sessionId) ? RULES : ''
258
- } catch {
259
- return ''
260
- }
261
- },
262
- }))
263
-
264
- // Loopback state route used by the composer button.
265
- ctx.inject(['webServer'], (scope) => {
266
- const server = scope.webServer
267
- if (!server || typeof server.register !== 'function') return
268
- scope.effect(() => server.register({
269
- kind: 'exact',
270
- path: ROUTE_STATE,
271
- handler: async (req, res) => {
272
- try {
273
- if (!isLoopback(req)) return sendJson(res, 403, { ok: false, error: 'loopback only' })
274
- const url = new URL(req.url ?? '/', 'http://127.0.0.1')
275
- if (req.method === 'GET') {
276
- const sessionId = url.searchParams.get('sessionId')
277
- if (!sessionId || !VALID_SESSION_ID.test(sessionId)) {
278
- return sendJson(res, 400, { ok: false, error: 'sessionId is required' })
279
- }
280
- return sendJson(res, 200, {
281
- ok: true,
282
- sessionId,
283
- enabled: sessionEnabled(state, sessionId),
284
- defaultOn: DEFAULT_ON,
285
- })
286
- }
287
- if (req.method === 'POST') {
288
- const body = await readJson(req)
289
- if (!body) return sendJson(res, 400, { ok: false, error: 'invalid JSON body' })
290
- const sessionId = typeof body.sessionId === 'string' ? body.sessionId : ''
291
- if (!VALID_SESSION_ID.test(sessionId)) {
292
- return sendJson(res, 400, { ok: false, error: 'sessionId is required' })
293
- }
294
- if (typeof body.enabled !== 'boolean') {
295
- return sendJson(res, 400, { ok: false, error: 'enabled must be a boolean' })
296
- }
297
- state = setSessionEnabled(state, sessionId, body.enabled)
298
- return sendJson(res, 200, { ok: true, sessionId, enabled: body.enabled, defaultOn: DEFAULT_ON })
299
- }
300
- return sendJson(res, 405, { ok: false, error: 'method not allowed' })
301
- } catch (error) {
302
- return sendJson(res, 500, { ok: false, error: error?.message ?? 'state route failed' })
303
- }
304
- },
305
- }))
306
- })
307
-
308
- // Optional self-check tool.
309
- ctx.effect(() => ctx.tools.register({
310
- name: 'plain_talk_check',
311
- description:
312
- 'Self-check one reply draft against the plain-talk rules before sending it. ' +
313
- 'Call it for a completion report or any reply longer than about 12 lines. ' +
314
- 'It reports cross-turn wording, internal identifiers, pointer-only citations, ' +
315
- 'unexplained opaque codes, and length/shape problems. All user-facing strings are Chinese.',
316
- parameters: {
317
- type: 'object',
318
- properties: {
319
- draft: { type: 'string', description: 'The full reply text you are about to send.' },
320
- },
321
- required: ['draft'],
322
- additionalProperties: false,
323
- },
324
- output: {
325
- schema: {
326
- type: 'object',
327
- properties: {
328
- ok: { type: 'boolean' },
329
- issues: {
330
- type: 'array',
331
- items: {
332
- type: 'object',
333
- properties: {
334
- severity: { type: 'string' },
335
- rule: { type: 'string' },
336
- message: { type: 'string' },
337
- fix: { type: 'string' },
338
- },
339
- },
340
- },
341
- stats: {
342
- type: 'object',
343
- properties: {
344
- chars: { type: 'number' },
345
- cjk: { type: 'number' },
346
- lines: { type: 'number' },
347
- cjkRatio: { type: 'number' },
348
- identifiers: { type: 'number' },
349
- backrefs: { type: 'number' },
350
- maxListRun: { type: 'number' },
351
- hasNext: { type: 'boolean' },
352
- },
353
- },
354
- },
355
- },
356
- render: (_args, value) => [{ type: 'text', text: renderCheck(value) }],
357
- },
358
- async execute(args, exec) {
359
- const draft = typeof args?.draft === 'string' ? args.draft : ''
360
- const sessionId = exec?.agent?.id ? String(exec.agent.id) : ''
361
- const result = analyze(draft, {
362
- knownTokens: knownFor(sessionId, exec?.agent),
363
- language: languageFor(sessionId),
364
- })
365
- return result
366
- },
367
- }))
368
-
369
- // Vocabulary maintenance.
370
- ctx.effect(() => ctx.tools.register({
371
- name: 'plain_talk_vocab',
372
- description:
373
- 'Read or maintain the user vocabulary that decides which terms no longer need an explanation. ' +
374
- 'Categories: common (built in), domain, project, internal, unclassified. ' +
375
- 'Use action=list to show it, add/remove/classify to correct it. All user-facing strings are Chinese.',
376
- parameters: {
377
- type: 'object',
378
- properties: {
379
- action: { type: 'string', enum: ['list', 'add', 'remove', 'classify'] },
380
- terms: { type: 'array', items: { type: 'string' }, description: 'Terms for add/remove.' },
381
- term: { type: 'string', description: 'One term for classify.' },
382
- category: { type: 'string', enum: Object.keys(CATEGORIES) },
383
- },
384
- required: ['action'],
385
- additionalProperties: false,
386
- },
387
- output: {
388
- schema: {
389
- type: 'object',
390
- properties: {
391
- ok: { type: 'boolean' },
392
- text: { type: 'string' },
393
- },
394
- },
395
- render: (_args, value) => [{ type: 'text', text: String(value?.text ?? '') }],
396
- },
397
- async execute(args, exec) {
398
- const action = String(args?.action ?? '')
399
- const sessionId = exec?.agent?.id ? String(exec.agent.id) : ''
400
- const cwdName = projectName(cwdOf(exec?.agent))
401
-
402
- if (action === 'list') {
403
- const groups = listByCategory(userVocab)
404
- const total = Object.keys(userVocab.terms).length
405
- const lines = [`词汇清单:已记录 ${total} 条;本会话待确认 ${pendingFor(userVocab, sessionId).length} 条。`]
406
- for (const [key, label] of Object.entries(CATEGORIES)) {
407
- const items = groups[key] ?? []
408
- if (key === 'common') {
409
- lines.push(`${label}:内置常用词(不占文件),例如 arXiv、DOI、API。`)
410
- continue
411
- }
412
- if (items.length === 0) {
413
- lines.push(`${label}:0 条`)
414
- continue
415
- }
416
- const shown = items.slice(0, 12).map((item) => `${item.term}(${item.count})`).join('、')
417
- lines.push(`${label}:${items.length} 条 — ${shown}${items.length > 12 ? ' …' : ''}`)
418
- }
419
- const pending = pendingFor(userVocab, sessionId)
420
- if (pending.length) lines.push(`本次调研、尚未转为已知:${pending.join('、')}`)
421
- return { ok: true, text: lines.join('\n') }
422
- }
423
-
424
- if (action === 'add') {
425
- const terms = (Array.isArray(args?.terms) ? args.terms : []).map((t) => String(t).trim()).filter(Boolean)
426
- if (terms.length === 0) return { ok: false, text: '没有要加入的词:给 terms 一个非空数组。' }
427
- const kept = terms.filter((term) => !isCodeLike(term))
428
- const skipped = terms.filter((t) => !kept.includes(t))
429
- for (const term of kept) addTerm(userVocab, term, { session: sessionId, cwdName, source: 'manual' })
430
- saveVocab(vocabPath(), userVocab)
431
- const note = skipped.length ? `;跳过代号 ${skipped.join('、')}(代号不进词表)` : ''
432
- return { ok: kept.length > 0, text: `已加入 ${kept.length} 条:${kept.join('、') || '无'}${note}` }
433
- }
434
-
435
- if (action === 'remove') {
436
- const terms = (Array.isArray(args?.terms) ? args.terms : []).map((t) => String(t).trim()).filter(Boolean)
437
- if (terms.length === 0) return { ok: false, text: '没有要删除的词:给 terms 一个非空数组。' }
438
- for (const term of terms) removeTerm(userVocab, term)
439
- saveVocab(vocabPath(), userVocab)
440
- return { ok: true, text: `已删除 ${terms.length} 条:${terms.join('、')}` }
441
- }
442
-
443
- if (action === 'classify') {
444
- const term = String(args?.term ?? '').trim()
445
- const category = String(args?.category ?? '')
446
- if (!term || !CATEGORIES[category]) {
447
- return { ok: false, text: `需要 term 和有效 category(${Object.keys(CATEGORIES).join(' / ')})。` }
448
- }
449
- if (isCodeLike(term)) {
450
- return { ok: false, text: `「${term}」是内部代号,不进入词汇清单;它每次出现都应按未知处理并解释。` }
451
- }
452
- if (!userVocab.terms[term]) addTerm(userVocab, term, { session: sessionId, cwdName, category, source: 'manual' })
453
- else setCategory(userVocab, term, category)
454
- saveVocab(vocabPath(), userVocab)
455
- return { ok: true, text: `已把「${term}」归到「${CATEGORIES[category]}」。` }
456
- }
457
-
458
- return { ok: false, text: `未知 action「${action}」。用 list / add / remove / classify。` }
459
- },
460
- }))
461
-
462
- console.log(`[plain-talk] host active (default ${DEFAULT_ON ? 'on' : 'off'}; section ${SECTION_NAME}@${SECTION_ORDER}; vocab ${Object.keys(userVocab.terms).length} terms)`)
463
- }
464
-
465
- function renderCheck(value) {
466
- const issues = Array.isArray(value?.issues) ? value.issues : []
467
- const stats = value?.stats ?? {}
468
- if (issues.length === 0) {
469
- return `说人话自检:通过。\n字数 ${stats.chars ?? 0},行数 ${stats.lines ?? 0},未解释代号 ${stats.identifiers ?? 0},回指 ${stats.backrefs ?? 0}。`
470
- }
471
- const errors = issues.filter((i) => i.severity === 'error').length
472
- const warns = issues.length - errors
473
- const lines = [`说人话自检:${errors} 个必须改,${warns} 个建议改。`, '']
474
- for (const issue of issues) {
475
- lines.push(`[${issue.severity === 'error' ? '必须改' : '建议改'}] ${issue.message}`)
476
- if (issue.fix) lines.push(` 改法:${issue.fix}`)
477
- }
478
- return lines.join('\n')
479
- }
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
+ }