advisers 0.1.0-preview.4 → 0.2.0

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.
Files changed (53) hide show
  1. package/LICENSE +131 -21
  2. package/NOTICE +34 -0
  3. package/README-zh.md +40 -9
  4. package/README.md +53 -10
  5. package/THIRD-PARTY-NOTICES.md +277 -0
  6. package/bin/advisers.js +4230 -122
  7. package/index.js +1 -1
  8. package/lib/agent.js +414 -0
  9. package/lib/attachments.js +283 -0
  10. package/lib/capture.js +168 -0
  11. package/lib/context-window.js +123 -0
  12. package/lib/digest.js +27 -0
  13. package/lib/doc-review.js +30 -0
  14. package/lib/egress.js +27 -0
  15. package/lib/evidence.js +1995 -0
  16. package/lib/ical.js +542 -0
  17. package/lib/imap.js +181 -0
  18. package/lib/importers.js +1001 -0
  19. package/lib/learning.js +46 -0
  20. package/lib/mcp-server.js +869 -0
  21. package/lib/model.js +307 -0
  22. package/lib/notify.js +189 -0
  23. package/lib/nudge.js +10 -0
  24. package/lib/ocr.js +47 -0
  25. package/lib/pdf.js +105 -0
  26. package/lib/pet-brief-store.js +51 -0
  27. package/lib/pet-brief.js +644 -0
  28. package/lib/receipt-verify.js +624 -0
  29. package/lib/relative-date.js +393 -0
  30. package/lib/remind.js +690 -0
  31. package/lib/research.js +193 -0
  32. package/lib/review.js +88 -0
  33. package/lib/routine.js +22 -0
  34. package/lib/safety/classifier.js +392 -0
  35. package/lib/safety/explain.js +157 -0
  36. package/lib/safety/index.js +333 -0
  37. package/lib/safety/redact.js +212 -0
  38. package/lib/safety/rules.js +824 -0
  39. package/lib/scheduler.js +399 -0
  40. package/lib/source.js +294 -0
  41. package/lib/sqlite.js +1022 -0
  42. package/lib/sync.js +129 -0
  43. package/lib/timestamp.js +45 -0
  44. package/lib/tos/index.js +332 -0
  45. package/lib/tos/manifest.json +32 -0
  46. package/lib/tos/privacy.zh-CN.md +136 -0
  47. package/lib/tos/safety.zh-CN.md +101 -0
  48. package/lib/tos/summary.zh-CN.md +12 -0
  49. package/lib/tos/terms.zh-CN.md +439 -0
  50. package/lib/ui.js +49 -0
  51. package/lib/undo.js +83 -0
  52. package/lib/vault.js +51 -0
  53. package/package.json +26 -4
@@ -0,0 +1,392 @@
1
+ /**
2
+ * Local content-safety classifier.
3
+ *
4
+ * Pure function over text: no network, no filesystem, no third-party deps.
5
+ * It normalizes (NFKC / zero-width / traditional-to-simplified / whitespace),
6
+ * runs the 14-category rule matrix from rules.js, applies the narrow block
7
+ * allowlist and surface/context downgrades, and returns a structured decision
8
+ * that NEVER contains the original text.
9
+ *
10
+ * Result shape:
11
+ * {
12
+ * action: 'allow' | 'warn' | 'confirm' | 'redact' | 'block',
13
+ * categories: string[], // category ids, highest priority first
14
+ * ruleIds: string[], // stable rule ids, highest priority first
15
+ * confidence: number, // 0..1 (0 for allow)
16
+ * evidenceHash: string | null, // HMAC-SHA256(key, hit snippets)[0..16]
17
+ * code: string, // stable audit code, 'NONE' for allow
18
+ * rulesetVersion: string,
19
+ * rulesetDigest: string,
20
+ * surface: string,
21
+ * severity: 'none' | 'low' | 'medium' | 'high' | 'critical',
22
+ * crisis: boolean, // self-harm: show crisis hint, never block
23
+ * downgraded: boolean,
24
+ * truncated: boolean,
25
+ * hits: [{ ruleId, category, subtype, code, severity, action, confidence,
26
+ * hardBlock, crisis, downgraded }]
27
+ * }
28
+ *
29
+ * The caller owns the audit key: pass { hmacKey } to get an evidenceHash.
30
+ * Without a key evidenceHash is null (never a plaintext or unkeyed fallback).
31
+ */
32
+
33
+ import { createHmac } from 'node:crypto'
34
+ import { DEFAULT_RULESET, actionRank, resolveRuleset } from './rules.js'
35
+ import { detectPiiInternal } from './redact.js'
36
+
37
+ export const DEFAULT_SURFACE = 'chat.input'
38
+ export const MAX_SCAN_CHARS = 100_000
39
+ export const MAX_EVIDENCE_SNIPPETS = 20
40
+ export const MAX_EVIDENCE_SNIPPET_CHARS = 64
41
+
42
+ /** Surface policy table. localFile surfaces downgrade non-CSAM blocks. */
43
+ export const SURFACES = Object.freeze({
44
+ 'safety.check': { egress: true, localFile: false },
45
+ 'chat.input': { egress: true, localFile: false },
46
+ 'chat.output': { egress: true, localFile: false },
47
+ 'agent.input': { egress: true, localFile: false },
48
+ 'agent.output': { egress: true, localFile: false },
49
+ 'model.output': { egress: true, localFile: false },
50
+ 'research.query': { egress: true, localFile: false },
51
+ 'research.output': { egress: true, localFile: false },
52
+ 'capture.input': { egress: false, localFile: true },
53
+ 'attachments.text': { egress: false, localFile: true },
54
+ 'doc-review.text': { egress: false, localFile: true },
55
+ 'office.spec': { egress: false, localFile: true },
56
+ 'office.output': { egress: true, localFile: false },
57
+ deliverable: { egress: true, localFile: false },
58
+ 'pet-brief': { egress: true, localFile: false },
59
+ 'mcp.tool': { egress: true, localFile: false },
60
+ 'dsh.tool': { egress: true, localFile: false },
61
+ unknown: { egress: true, localFile: false },
62
+ })
63
+
64
+ const SURFACE_ALIASES = Object.freeze({
65
+ chat: 'chat.input',
66
+ agent: 'agent.input',
67
+ capture: 'capture.input',
68
+ attachments: 'attachments.text',
69
+ attachment: 'attachments.text',
70
+ docreview: 'doc-review.text',
71
+ review: 'doc-review.text',
72
+ office: 'office.spec',
73
+ research: 'research.query',
74
+ pet: 'pet-brief',
75
+ mcp: 'mcp.tool',
76
+ dsh: 'dsh.tool',
77
+ safety: 'safety.check',
78
+ })
79
+
80
+ /** Normalize a surface name; unknown names fail closed to the generic surface. */
81
+ export function normalizeSurface(surface) {
82
+ if (surface == null || surface === '') return DEFAULT_SURFACE
83
+ const raw = String(surface).trim().toLowerCase()
84
+ const key = SURFACE_ALIASES[raw] || raw
85
+ return SURFACES[key] ? key : 'unknown'
86
+ }
87
+
88
+ /** Policy for a normalized surface (local files are reviewed, not hard-blocked). */
89
+ export function surfacePolicy(surface) {
90
+ const key = normalizeSurface(surface)
91
+ return SURFACES[key] || SURFACES.unknown
92
+ }
93
+
94
+ // ---------------------------------------------------------------------------
95
+ // normalization: NFKC, zero-width, traditional -> simplified, whitespace
96
+ // ---------------------------------------------------------------------------
97
+
98
+ const ZERO_WIDTH_RE = /[\u00AD\u034F\u061C\u115F\u1160\u17B4\u17B5\u180B-\u180E\u200B-\u200F\u202A-\u202E\u2060-\u2064\u206A-\u206F\uFE00-\uFE0F\uFEFF\u{E0100}-\u{E01EF}]/gu
99
+
100
+ // Only characters needed by the rule matrix. This is normalization for
101
+ // MATCHING only; the original text is never rewritten for the caller.
102
+ const TRAD_TO_SIMP = Object.freeze({
103
+ '兒': '儿', '槍': '枪', '彈': '弹', '藥': '药', '殺': '杀', '竊': '窃',
104
+ '騙': '骗', '賭': '赌', '錢': '钱', '貸': '贷', '證': '证', '駕': '驾',
105
+ '齡': '龄', '賣': '卖', '買': '买', '傷': '伤', '襲': '袭', '擊': '击',
106
+ '軍': '军', '獨': '独', '國': '国', '愛': '爱', '亂': '乱', '華': '华',
107
+ '極': '极', '網': '网', '絡': '络', '組': '组', '織': '织', '揚': '扬',
108
+ '動': '动', '顛': '颠', '製': '制', '販': '贩', '穢': '秽', '強': '强',
109
+ '姦': '奸', '褻': '亵', '視': '视', '殘': '残', '廢': '废', '碼': '码',
110
+ '鑰': '钥', '賬': '账', '帳': '账', '戶': '户', '轉': '转', '詐': '诈',
111
+ '單': '单', '發': '发', '個': '个', '訊': '讯', '錄': '录', '惡': '恶',
112
+ '馬': '马', '驟': '骤', '換': '换', '臉': '脸', '擬': '拟', '聲': '声',
113
+ '偽': '伪', '學': '学', '約': '约', '見': '见', '戀': '恋', '無': '无',
114
+ '統': '统', '開': '开', '戲': '戏', '誘': '诱', '脅': '胁', '嚇': '吓',
115
+ '搶': '抢', '綁': '绑', '撥': '拨', '號': '号', '兇': '凶', '屍': '尸',
116
+ '體': '体', '腦': '脑', '炰': '炮', '菸': '烟', '紋': '纹', '輟': '辍',
117
+ '複': '复', '鍊': '炼', '燒': '烧', '慫': '怂', '慾': '欲', '蕩': '荡',
118
+ '艷': '艳', '親': '亲', '權': '权', '員': '员', '會': '会', '區': '区',
119
+ '縣': '县', '鄉': '乡', '鎮': '镇', '門': '门', '車': '车', '團': '团',
120
+ '夥': '伙', '僱': '雇', '傭': '佣',
121
+ })
122
+
123
+ const HAN_RE = /[\u4e00-\u9fff]/g
124
+
125
+ function toSimplified(text) {
126
+ return text.replace(HAN_RE, (char) => TRAD_TO_SIMP[char] || char)
127
+ }
128
+
129
+ /**
130
+ * Whitespace/punctuation insensitive view for CJK combo rules. Removing
131
+ * separators defeats "制 作 炸 弹" / "制作,炸弹" style evasions.
132
+ */
133
+ const COMPACT_STRIP_RE = /[\s\u3000\u00A0,。、;:!?…—~·“”‘’「」『』()()《》〈〉【】〔〕\[\]{}<>,.!?;:'"`~!@#$%^&*_+=|\\/\-]/gu
134
+
135
+ /**
136
+ * Normalize without changing semantics: NFKC (full/half width), zero-width
137
+ * removal, traditional -> simplified for matching, lowercase, collapsed spaces.
138
+ */
139
+ export function normalizeText(input) {
140
+ const original = String(input == null ? '' : input)
141
+ const base = original.normalize('NFKC').replace(ZERO_WIDTH_RE, '')
142
+ const normalized = toSimplified(base).toLowerCase().replace(/\s+/gu, ' ').trim()
143
+ const compact = normalized.replace(COMPACT_STRIP_RE, '')
144
+ return { original, normalized, compact }
145
+ }
146
+
147
+ /** Negation window check, compact view only (e.g. "禁止传播儿童裸照"). */
148
+ function isNegated(compactText, index) {
149
+ const window = compactText.slice(Math.max(0, index - 6), index)
150
+ return /(不要|不得|严禁|禁止|防止|避免|警惕|防范|预防|拒绝|切勿|勿|反对|反诈|反家暴|反暴力|打击|查处|严惩)$/u.test(window)
151
+ }
152
+
153
+ // ---------------------------------------------------------------------------
154
+ // policy heuristics
155
+ // ---------------------------------------------------------------------------
156
+
157
+ // Quoted/legal/news/academic contexts downgrade a non-hard block one step.
158
+ const CONTEXT_MARKERS = /(普法|法律|刑法|民法典|法规|法条|条文|判刑|判决|案例|新闻|报道|通报|公告|依据|根据|引用|学术|论文|研究|教学|教材|课堂|培训|防范|预防|应对|自救|求助|支持|志愿者|干预|保护|反诈|维权|举报|打击|查处|严惩|治理|宣传|警示|警示教育|安全研究|渗透测试|授权|应急响应|样本分析|加固|修复|漏洞|通知|声明)/u
159
+ // First-person solicitation cancels the context downgrade (anti-bypass).
160
+ const HARD_SOLICIT = /(教我|告诉我|指导我|帮我|给我|我要|我想|我需要|求|请给|麻烦给)/u
161
+
162
+ function hasContextDowngrade(views) {
163
+ return CONTEXT_MARKERS.test(views.compact) && !HARD_SOLICIT.test(views.compact)
164
+ }
165
+
166
+ function rankOf(action) {
167
+ return actionRank(action)
168
+ }
169
+
170
+ function hmacEvidence(snippets, hmacKey) {
171
+ if (!hmacKey || (typeof hmacKey !== 'string' && !Buffer.isBuffer(hmacKey) && !(hmacKey instanceof Uint8Array))) {
172
+ return null
173
+ }
174
+ const unique = [...new Set(snippets)].slice(0, MAX_EVIDENCE_SNIPPETS)
175
+ if (!unique.length) return null
176
+ const material = unique.map((snippet) => String(snippet).slice(0, MAX_EVIDENCE_SNIPPET_CHARS)).sort().join('\u0000')
177
+ try {
178
+ return createHmac('sha256', hmacKey).update(material, 'utf8').digest('hex').slice(0, 16)
179
+ } catch {
180
+ return null
181
+ }
182
+ }
183
+
184
+ // ---------------------------------------------------------------------------
185
+ // core scan
186
+ // ---------------------------------------------------------------------------
187
+
188
+ function scanRule(rule, views) {
189
+ for (const view of rule.views) {
190
+ const text = view === 'normalized' ? views.normalized : views.compact
191
+ if (!text) continue
192
+ for (const pattern of rule.patterns) {
193
+ const match = pattern.exec(text)
194
+ if (!match) continue
195
+ if (rule.negationSensitive && view === 'compact' && isNegated(text, match.index)) continue
196
+ return { view, snippet: match[0] }
197
+ }
198
+ }
199
+ return null
200
+ }
201
+
202
+ function buildHit(rule, snippet, actionOverride) {
203
+ return {
204
+ ruleId: rule.id,
205
+ category: rule.category,
206
+ subtype: rule.subtype,
207
+ code: rule.code,
208
+ severity: rule.severity,
209
+ action: actionOverride || rule.action,
210
+ confidence: rule.confidence,
211
+ hardBlock: Boolean(rule.hardBlock),
212
+ crisis: Boolean(rule.crisis),
213
+ blockable: Boolean(rule.blockable),
214
+ downgraded: null,
215
+ snippet: snippet || rule.id,
216
+ }
217
+ }
218
+
219
+ const SEVERITY_ORDER = { critical: 4, high: 3, medium: 2, low: 1 }
220
+
221
+ function allowResult(views, surface, ruleset, truncated) {
222
+ return {
223
+ action: 'allow',
224
+ categories: [],
225
+ ruleIds: [],
226
+ confidence: 0,
227
+ evidenceHash: null,
228
+ code: 'NONE',
229
+ rulesetVersion: ruleset.version,
230
+ rulesetDigest: ruleset.digest,
231
+ surface,
232
+ severity: 'none',
233
+ crisis: false,
234
+ downgraded: false,
235
+ truncated,
236
+ hits: [],
237
+ }
238
+ }
239
+
240
+ function runClassify(ruleset, text, options = {}) {
241
+ const surface = normalizeSurface(options.surface)
242
+ const policy = SURFACES[surface] || SURFACES.unknown
243
+ const maxChars = Number.isInteger(options.maxChars) && options.maxChars > 0 ? options.maxChars : MAX_SCAN_CHARS
244
+ const raw = String(text == null ? '' : text)
245
+ const truncated = raw.length > maxChars
246
+ const views = normalizeText(truncated ? raw.slice(0, maxChars) : raw)
247
+ if (!views.compact) return allowResult(views, surface, ruleset, truncated)
248
+
249
+ const contextDowngrade = hasContextDowngrade(views)
250
+ const hits = []
251
+ const piiHits = detectPiiInternal(views.original, { ruleset })
252
+
253
+ for (const rule of ruleset.rules) {
254
+ if (rule.detector === 'pii') {
255
+ const first = piiHits.filter((hit) => hit.ruleId === rule.id)
256
+ if (!first.length) continue
257
+ const hit = buildHit(rule, first.map((item) => item.raw).join(' '))
258
+ hit.pii = true
259
+ hits.push(hit)
260
+ continue
261
+ }
262
+ if (rule.detector === 'pii-bulk') {
263
+ const enough = piiHits.length >= (rule.minPiiHits || 6)
264
+ const exfil = rule.exfilPattern ? rule.exfilPattern.exec(views.compact) : null
265
+ const quantity = rule.quantityPattern ? rule.quantityPattern.exec(views.compact) : null
266
+ if (!enough || !exfil || !quantity) continue
267
+ hits.push(buildHit(rule, exfil[0] + quantity[0]))
268
+ continue
269
+ }
270
+ const found = scanRule(rule, views)
271
+ if (!found) continue
272
+ hits.push(buildHit(rule, found.snippet))
273
+ }
274
+
275
+ // Block is narrow: only explicit block rules can block; the CSAM hard block
276
+ // is never downgraded. Everything else may be softened by context/surface.
277
+ for (const hit of hits) {
278
+ if (hit.action !== 'block' || hit.hardBlock) continue
279
+ if (contextDowngrade) {
280
+ hit.action = 'confirm'
281
+ hit.downgraded = 'context'
282
+ }
283
+ if (policy.localFile && hit.action === 'block') {
284
+ hit.action = 'confirm'
285
+ hit.downgraded = 'surface'
286
+ } else if (policy.localFile && hit.action === 'confirm') {
287
+ hit.action = 'warn'
288
+ hit.downgraded = 'surface'
289
+ }
290
+ }
291
+
292
+ const crisis = hits.some((hit) => hit.crisis)
293
+ if (crisis) {
294
+ for (const hit of hits) {
295
+ if (hit.crisis && rankOf(hit.action) < rankOf('warn')) hit.action = 'warn'
296
+ }
297
+ }
298
+
299
+ // Deterministic ordering: action rank desc, then ruleset order (id sorted).
300
+ // Array.prototype.sort is stable, so equal-rank hits keep ruleset order.
301
+ const ordered = [...hits].sort((a, b) => rankOf(b.action) - rankOf(a.action))
302
+ const categories = [...new Set(ordered.map((hit) => hit.category))]
303
+ const ruleIds = [...new Set(ordered.map((hit) => hit.ruleId))]
304
+ const action = ordered.length ? ordered[0].action : 'allow'
305
+ const primary = ordered[0]
306
+ const baseConfidence = ordered.length
307
+ ? Math.min(0.99, Math.max(...ordered.map((hit) => hit.confidence)) + 0.02 * Math.max(0, categories.length - 1))
308
+ : 0
309
+ const evidenceHash = hmacEvidence(ordered.map((hit) => hit.snippet), options.hmacKey)
310
+
311
+ return {
312
+ action,
313
+ categories,
314
+ ruleIds,
315
+ confidence: Math.round(baseConfidence * 100) / 100,
316
+ evidenceHash,
317
+ code: ordered.length ? ordered[0].code : 'NONE',
318
+ rulesetVersion: ruleset.version,
319
+ rulesetDigest: ruleset.digest,
320
+ surface,
321
+ severity: ordered.length ? ordered[0].severity : 'none',
322
+ crisis,
323
+ downgraded: ordered.some((hit) => Boolean(hit.downgraded)),
324
+ truncated,
325
+ hits: ordered.map((hit) => ({
326
+ ruleId: hit.ruleId,
327
+ category: hit.category,
328
+ subtype: hit.subtype,
329
+ code: hit.code,
330
+ severity: hit.severity,
331
+ action: hit.action,
332
+ confidence: hit.confidence,
333
+ hardBlock: hit.hardBlock,
334
+ crisis: hit.crisis,
335
+ downgraded: hit.downgraded,
336
+ })),
337
+ }
338
+ }
339
+
340
+ /**
341
+ * Classify text locally. Never throws on caller text; invalid options degrade
342
+ * safely (no hmacKey means no evidenceHash; unknown surface means generic).
343
+ */
344
+ export function classify(text, options = {}) {
345
+ let ruleset = DEFAULT_RULESET
346
+ if (options.ruleset) {
347
+ try {
348
+ ruleset = options.ruleset.__compiled ? options.ruleset : resolveRuleset(options.ruleset)
349
+ } catch {
350
+ ruleset = DEFAULT_RULESET
351
+ }
352
+ }
353
+ try {
354
+ return runClassify(ruleset, text, options)
355
+ } catch {
356
+ // Fail closed on an internal bug: never let ordinary text slip past as allow.
357
+ return {
358
+ action: 'confirm',
359
+ categories: [],
360
+ ruleIds: [],
361
+ confidence: 0.5,
362
+ evidenceHash: null,
363
+ code: 'SAFETY_INTERNAL_ERROR',
364
+ rulesetVersion: ruleset.version,
365
+ rulesetDigest: ruleset.digest,
366
+ surface: normalizeSurface(options.surface),
367
+ severity: 'medium',
368
+ crisis: false,
369
+ downgraded: false,
370
+ truncated: false,
371
+ hits: [],
372
+ }
373
+ }
374
+ }
375
+
376
+ /** Bind a ruleset (and default options such as hmacKey) to a classify function. */
377
+ export function createClassifier(config = {}) {
378
+ let ruleset = DEFAULT_RULESET
379
+ if (config.ruleset != null) ruleset = resolveRuleset(config.ruleset)
380
+ const defaults = {
381
+ surface: config.surface,
382
+ hmacKey: config.hmacKey,
383
+ maxChars: config.maxChars,
384
+ }
385
+ return (text, options = {}) => {
386
+ const merged = { ...defaults, ...options, ruleset }
387
+ return runClassify(ruleset, text, merged)
388
+ }
389
+ }
390
+
391
+ // Kept for tests and for callers that want the severity ordering.
392
+ export const SEVERITY_RANK = Object.freeze(SEVERITY_ORDER)
@@ -0,0 +1,157 @@
1
+ /**
2
+ * Human-readable safety explanations (the copy behind `advisers safety explain`).
3
+ *
4
+ * Contract: the public explanation may reveal the CATEGORY, action, ruleset
5
+ * version and evidence-hash prefix, but never the matched text or the rule
6
+ * keywords. Full rule tables stay private to reduce evasion.
7
+ */
8
+
9
+ import { CATEGORY_BY_ID, RULESET_VERSION } from './rules.js'
10
+
11
+ export const EXPLAIN_FORMAT = 'advisers-safety-explain'
12
+ export const NOTICE_VERSION = 1
13
+
14
+ /** Crisis resources; self-harm is never blocked, only escalated. */
15
+ export const CRISIS_RESOURCES = Object.freeze({
16
+ mainlandHotline: '12356',
17
+ emergency: '120',
18
+ police: '110',
19
+ international: Object.freeze(['US 988', 'UK 116 123']),
20
+ })
21
+
22
+ const CODE_HINTS = Object.freeze({
23
+ CSAM: '检测到涉及未成年人的性剥削内容,已阻止处理。',
24
+ TERRORISM_OPERATIONS: '检测到恐怖主义操作指引,已阻止处理。',
25
+ ILLEGAL_INSTRUCTION: '检测到直接违法教唆(制毒、制爆、武器改装等),已阻止处理。',
26
+ MALWARE_WEAPONIZED: '检测到恶意代码或网络攻击武器化内容,已阻止处理。',
27
+ PII_BULK_EXFIL: '检测到批量个人信息外泄内容,已阻止处理。',
28
+ SELFHARM_CRISIS: '检测到自伤风险,已触发危机提示(内容未被阻断)。',
29
+ PII: '检测到个人信息或密钥,已按脱敏处理(原文不落盘)。',
30
+ PROMPT_INJECTION: '检测到提示注入或越权指令,已提示风险并加固系统边界。',
31
+ SAFETY_INTERNAL_ERROR: '本地审核出现异常,已按保守策略处理。',
32
+ })
33
+
34
+ const ACTION_LABELS = Object.freeze({
35
+ allow: '允许',
36
+ warn: '提醒',
37
+ confirm: '需确认',
38
+ redact: '脱敏',
39
+ block: '已拦截',
40
+ })
41
+
42
+ /** Public category label; no rule keywords are exposed. */
43
+ export function categoryLabel(categoryId) {
44
+ const category = CATEGORY_BY_ID[categoryId]
45
+ return category ? category.labelZh : '未分类风险'
46
+ }
47
+
48
+ /** Evidence hashes are keyed one-way digests; show only a short prefix. */
49
+ export function formatEvidenceHash(hash) {
50
+ if (!hash) return '不可用(未配置审计密钥)'
51
+ return String(hash).slice(0, 8) + '…'
52
+ }
53
+
54
+ function categoriesText(result) {
55
+ const list = (result && result.categories) || []
56
+ if (!list.length) return '未分类风险'
57
+ return list.map(categoryLabel).join('、')
58
+ }
59
+
60
+ function seqText(seq) {
61
+ return seq == null ? '当前事件' : '事件 #' + String(seq)
62
+ }
63
+
64
+ function reportHint(seq) {
65
+ return seq == null ? 'advisers safety report' : 'advisers safety report ' + String(seq)
66
+ }
67
+
68
+ function explainHint(seq) {
69
+ return seq == null ? 'advisers safety explain' : 'advisers safety explain ' + String(seq)
70
+ }
71
+
72
+ /**
73
+ * Why did this happen? Used by `advisers safety explain <seq>`.
74
+ * Accepts the audit-row shape; never includes the original text.
75
+ */
76
+ export function explainAudit(event = {}) {
77
+ const seq = event.seq
78
+ const surface = event.surface || 'unknown'
79
+ const action = event.action || 'warn'
80
+ const code = event.code || 'NONE'
81
+ const categories = event.categories && event.categories.length
82
+ ? event.categories
83
+ : (event.category ? [event.category] : [])
84
+ const ruleIds = event.ruleIds || []
85
+ const evidenceHash = event.evidenceHash || null
86
+ const rulesetVersion = event.rulesetVersion || RULESET_VERSION
87
+ const at = event.at || ''
88
+ const hint = CODE_HINTS[code]
89
+ const lines = []
90
+ lines.push(seqText(seq) + (at ? ' · ' + at : ''))
91
+ lines.push('surface=' + surface + ' · 动作=' + (ACTION_LABELS[action] || action) + ' · 类别=' + categories.map(categoryLabel).join('、'))
92
+ lines.push('规则版本=' + rulesetVersion + ' · 规则=' + (ruleIds.length ? ruleIds.join(',') : '—'))
93
+ lines.push('证据哈希=' + formatEvidenceHash(evidenceHash) + '(不可逆)')
94
+ if (hint) lines.push('说明:' + hint)
95
+ lines.push('误判?' + reportHint(seq) + '。' + explainHint(seq) + '。完整规则表不公开,以避免被规避。')
96
+ return lines.join('\n')
97
+ }
98
+
99
+ /** Copy shown when a block decision stops a request. */
100
+ export function blockNotice(result = {}, options = {}) {
101
+ const seq = options.seq
102
+ const lines = []
103
+ lines.push('已拦截:这段内容可能涉及' + categoriesText(result) + ',Advisers 不能生成或代为处理。')
104
+ lines.push('你可以:改写需求(' + explainHint(seq) + ' 查看原因);如果是误判,' + reportHint(seq) + ' 反馈。')
105
+ if (result.crisis) lines.push(crisisNotice())
106
+ else lines.push('涉及未成年人或即时危险,请拨 110;紧急医疗请拨 120。')
107
+ return lines.join('\n')
108
+ }
109
+
110
+ /** Copy shown when a warn decision lets the request continue with a notice. */
111
+ export function warnNotice(result = {}, options = {}) {
112
+ const seq = options.seq
113
+ const lines = []
114
+ lines.push('提醒:检测到可能的风险(' + categoriesText(result) + ')。内容已保留,请自行判断是否继续。')
115
+ lines.push('继续使用可能违反法律或平台规则;误判可执行 ' + reportHint(seq) + ' 反馈。')
116
+ return lines.join('\n')
117
+ }
118
+
119
+ /** Copy shown when the user must explicitly confirm a risk (confirm action). */
120
+ export function confirmNotice(result = {}, options = {}) {
121
+ const seq = options.seq
122
+ const lines = []
123
+ lines.push('需要确认:检测到可能的风险(' + categoriesText(result) + ')。')
124
+ lines.push('继续意味着你自行承担相应责任;输入 y 继续,输入 n 取消。')
125
+ lines.push('如需了解原因:' + explainHint(seq) + ';误判反馈:' + reportHint(seq) + '。')
126
+ return lines.join('\n')
127
+ }
128
+
129
+ /** Self-harm: never blocked, always escalate to crisis resources. */
130
+ export function crisisNotice() {
131
+ return [
132
+ '我很在意你现在的安全。先不要一个人扛着:请联系身边可信任的人,或拨打当地急救/心理援助热线。',
133
+ '中国大陆可拨 ' + CRISIS_RESOURCES.mainlandHotline + ';紧急医疗 ' + CRISIS_RESOURCES.emergency + ';报警 ' + CRISIS_RESOURCES.police + '。',
134
+ '如果你现在有立即伤害自己的打算,请直接拨打 ' + CRISIS_RESOURCES.emergency + '/' + CRISIS_RESOURCES.police + '。',
135
+ '(国际:' + CRISIS_RESOURCES.international.join(' / ') + '。)',
136
+ ].join('\n')
137
+ }
138
+
139
+ /** Pick the notice matching a classify() result. */
140
+ export function explainResult(result = {}, options = {}) {
141
+ switch (result.action) {
142
+ case 'block':
143
+ return blockNotice(result, options)
144
+ case 'confirm':
145
+ return confirmNotice(result, options)
146
+ case 'warn':
147
+ return result.crisis ? crisisNotice() : warnNotice(result, options)
148
+ case 'redact': {
149
+ const labels = (result.categories || []).map(categoryLabel).filter(Boolean)
150
+ return labels.length
151
+ ? '已按个人信息保护要求脱敏(' + labels.join('、') + ')。'
152
+ : '已按个人信息保护要求脱敏。'
153
+ }
154
+ default:
155
+ return ''
156
+ }
157
+ }