dsh-plain-talk 0.1.14 → 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,479 +1,510 @@
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'
1
+ // 插件入口:会话开关、事件记录、系统提示注入、术语库工具、浏览器状态路由。
2
+ import fs from 'node:fs'
3
+ import path from 'node:path'
4
+ import { analyze } from './check.js'
22
5
  import { RULES } from './rules.js'
23
- import { analyze, scanIdentifiers, isCommonTerm } from './check.js'
6
+ import { resolvePrompt } from './styles.js'
24
7
  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'
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'
39
31
 
40
32
  export const name = 'plain-talk'
41
33
 
42
- // systemPrompt and tools are required; webServer is reached through ctx.inject
43
- // so the plugin still mounts in profiles without the Web surface.
34
+ // systemPrompt / tools 是必需服务;webServer 通过 ctx.inject 动态获取,
35
+ // 没有 Web 表面的 profile 也能挂载。
44
36
  export const inject = ['systemPrompt', 'tools']
45
37
 
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
38
  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
- }
39
+ const ALLOWED_CATEGORIES = ['common', 'domain', 'project', 'unclassified']
40
+ const ACTION_HINT = '支持的动作:list、status、add、explain、remove、classify、preference、context'
92
41
 
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
- }
42
+ // 运行时注入的通知不是用户写的话,既不能当作用户语言,也不能进词汇统计。
43
+ const NOT_USER_TEXT = /^(?:Time sampled|Elapsed since|Current runtime context|Current working directory|Browser time zone|<system-reminder>)/i
98
44
 
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
- }
45
+ // ---------- 会话状态文件 ----------
105
46
 
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]
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
114
53
  }
115
- const next = { version: 1, sessions }
116
- persistJson(statePath(), next)
117
- return next
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
118
58
  }
119
59
 
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
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')
127
64
  }
128
65
 
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
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')
135
69
  }
136
70
 
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
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
142
77
  }
143
78
 
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')
79
+ function readState() {
80
+ const own = readJson(statePath()) ?? {}
81
+ const legacy = statePath() === legacyStatePath() ? null : readJson(legacyStatePath())
82
+ return { version: 1, sessions: { ...(legacy ?? {}), ...own } }
147
83
  }
148
84
 
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'
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)
153
91
  }
154
92
 
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)
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
162
104
  }
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
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)
168
110
  }
169
- }
170
111
 
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)
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)
197
121
  }
122
+ return { id, entry }
123
+ }
198
124
 
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)
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
+ })
202
138
 
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' })
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
209
206
  }
210
- saveVocab(vocabPath(), userVocab)
211
- }
207
+ })
212
208
 
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]
209
+ function clearPendingFor(sessionId) {
210
+ updateStore(vocabPath(), (store) => {
211
+ clearPending(store, sessionId)
212
+ return store
213
+ })
218
214
  }
219
215
 
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'
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
+ })
226
224
  }
227
225
 
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
- }))
226
+ // ---------- 浏览器状态路由 ----------
263
227
 
264
- // Loopback state route used by the composer button.
265
228
  ctx.inject(['webServer'], (scope) => {
266
229
  const server = scope.webServer
267
230
  if (!server || typeof server.register !== 'function') return
268
231
  scope.effect(() => server.register({
269
- kind: 'exact',
270
232
  path: ROUTE_STATE,
271
233
  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' })
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 })
303
250
  }
251
+ return end(res, 405, { ok: false, error: 'method not allowed' })
304
252
  },
305
253
  }))
306
254
  })
307
255
 
308
- // Optional self-check tool.
256
+ // ---------- 工具 ----------
257
+
309
258
  ctx.effect(() => ctx.tools.register({
310
259
  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.',
260
+ description: RULES,
316
261
  parameters: {
317
262
  type: 'object',
318
263
  properties: {
319
- draft: { type: 'string', description: 'The full reply text you are about to send.' },
264
+ draft: { type: 'string', description: '即将发送的回复正文' },
320
265
  },
321
266
  required: ['draft'],
322
- additionalProperties: false,
323
267
  },
324
268
  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) }],
269
+ schema: { type: 'object', additionalProperties: true },
270
+ render: (_args, value) => [{ type: 'text', text: typeof value?.text === 'string' ? value.text : JSON.stringify(value) }],
357
271
  },
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
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 }
366
277
  },
367
278
  }))
368
279
 
369
- // Vocabulary maintenance.
370
280
  ctx.effect(() => ctx.tools.register({
371
281
  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.',
282
+ description: '查看或修改术语清单。' + ACTION_HINT,
376
283
  parameters: {
377
284
  type: 'object',
378
285
  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) },
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: '类别偏好' },
383
291
  },
384
292
  required: ['action'],
385
- additionalProperties: false,
386
293
  },
387
294
  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 ?? '') }],
295
+ schema: { type: 'object', additionalProperties: true },
296
+ render: (_args, value) => [{ type: 'text', text: typeof value?.text === 'string' ? value.text : JSON.stringify(value) }],
396
297
  },
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
- }
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
+ }))
423
304
 
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
- }
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
+ }
434
315
 
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
- }
316
+ function turnTexts(sessionId) {
317
+ if (!sessionId) return []
318
+ return sessions.get(sessionId)?.texts ?? []
319
+ }
442
320
 
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]}」。` }
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('、') + '。只提问、只在任务里使用、或出现在举例/引用里,都不算确认。')
456
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
+ }
457
401
 
458
- return { ok: false, text: `未知 action「${action}」。用 list / add / remove / classify。` }
459
- },
460
- }))
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
+ }
461
416
 
462
- console.log(`[plain-talk] host active (default ${DEFAULT_ON ? 'on' : 'off'}; section ${SECTION_NAME}@${SECTION_ORDER}; vocab ${Object.keys(userVocab.terms).length} terms)`)
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 ''
463
442
  }
464
443
 
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}。`
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
470
456
  }
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}`)
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')
477
496
  }
478
- return lines.join('\n')
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')
479
510
  }