advisers 0.2.2 → 0.2.3

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/lib/mcp-server.js CHANGED
@@ -368,8 +368,27 @@ export function readReceiptDirectory(dir) {
368
368
  * @param {Function|Date} [options.now] Clock used by reminders (defaults to new Date()).
369
369
  * @returns {{protocolVersion: string, handle: Function, handleLine: Function, serve: Function, tools: Function, resources: Function}}
370
370
  */
371
- export function createMcpServer({ store, ledger, version = '0.0.0', audit, readPack, now = () => new Date() } = {}) {
371
+ export function createMcpServer({ store, ledger, loadLedger, loadStore, version = '0.0.0', audit, readPack, now = () => new Date() } = {}) {
372
372
  const serverVersion = String(version ?? '0.0.0')
373
+ // 0.2.3 P0-2: the CLI wires lazy loaders instead of a preloaded ledger/store so
374
+ // `initialize` stays protocol-only (200k-row ledgers used to cost ~2s before the
375
+ // first response). Anything that needs data resolves it on first use; an
376
+ // explicit ledger/store object (tests, embedders) still wins, and the resolved
377
+ // value is cached per table subset. kind: 'commitments' | 'matters' | 'full'.
378
+ let resolvedLedger = ledger
379
+ let resolvedStore = store
380
+ const ledgerCache = new Map()
381
+ function ledgerFor(kind = 'full') {
382
+ if (resolvedLedger !== undefined) return resolvedLedger
383
+ if (ledgerCache.has(kind)) return ledgerCache.get(kind)
384
+ const loaded = typeof loadLedger === 'function' ? loadLedger(kind) : undefined
385
+ ledgerCache.set(kind, loaded)
386
+ return loaded
387
+ }
388
+ function storeFor() {
389
+ if (resolvedStore === undefined && typeof loadStore === 'function') resolvedStore = loadStore()
390
+ return resolvedStore
391
+ }
373
392
 
374
393
  function nowDate() {
375
394
  const value = typeof now === 'function' ? now() : now
@@ -377,22 +396,24 @@ export function createMcpServer({ store, ledger, version = '0.0.0', audit, readP
377
396
  return Number.isNaN(date.getTime()) ? new Date() : date
378
397
  }
379
398
 
380
- function requireLedger() {
381
- if (!ledger || typeof ledger.openCommitments !== 'function' || typeof ledger.listCommitments !== 'function') {
399
+ function requireLedger(kind = 'full') {
400
+ const ledgerApi = ledgerFor(kind)
401
+ if (!ledgerApi || typeof ledgerApi.openCommitments !== 'function' || typeof ledgerApi.listCommitments !== 'function') {
382
402
  throw new ToolError('ledger unavailable')
383
403
  }
384
- return ledger
404
+ return ledgerApi
385
405
  }
386
406
 
387
407
  function requireStore() {
388
- if (!store || typeof store.proposeCandidate !== 'function') throw new ToolError('candidate store unavailable')
389
- return store
408
+ const storeApi = storeFor()
409
+ if (!storeApi || typeof storeApi.proposeCandidate !== 'function') throw new ToolError('candidate store unavailable')
410
+ return storeApi
390
411
  }
391
412
 
392
413
  /* ------------------------------ read models ------------------------------ */
393
414
 
394
415
  function todayData() {
395
- const open = requireLedger().openCommitments()
416
+ const open = requireLedger('commitments').openCommitments()
396
417
  return {
397
418
  open: open.length,
398
419
  commitments: open.map((c) => ({ id: c.id, debtor: c.debtor, creditor: c.creditor, action: c.action, dueAt: c.dueAt })),
@@ -400,14 +421,14 @@ export function createMcpServer({ store, ledger, version = '0.0.0', audit, readP
400
421
  }
401
422
 
402
423
  function commitRows(all) {
403
- return requireLedger()
424
+ return requireLedger('commitments')
404
425
  .listCommitments()
405
426
  .filter((c) => all || c.status === 'open')
406
427
  .map((c) => ({ id: c.id, status: c.status, action: c.action, dueAt: c.dueAt, creditor: c.creditor }))
407
428
  }
408
429
 
409
430
  function whoData() {
410
- const open = requireLedger().openCommitments()
431
+ const open = requireLedger('commitments').openCommitments()
411
432
  return {
412
433
  mine: open.filter((c) => c.debtor === 'user' || c.debtor === 'agent'),
413
434
  waiting: open.filter((c) => c.debtor === 'third' || String(c.debtor).startsWith('third:')),
@@ -416,22 +437,24 @@ export function createMcpServer({ store, ledger, version = '0.0.0', audit, readP
416
437
 
417
438
  function remindData() {
418
439
  try {
419
- return buildReminders(requireLedger(), { now: nowDate() })
440
+ return buildReminders(requireLedger('commitments'), { now: nowDate() })
420
441
  } catch {
421
442
  throw new ToolError('reminder planning failed')
422
443
  }
423
444
  }
424
445
 
425
446
  function evidenceData(id) {
426
- const ledgerApi = requireLedger()
427
- if (id.startsWith('cm_')) return evidenceForCommitment(store, ledgerApi, id)
428
- if (id.startsWith('fact_')) return evidenceForFact(store, ledgerApi, id)
429
- if (id.startsWith('pref_')) return evidenceForPreference(store, ledgerApi, id)
447
+ const ledgerApi = requireLedger('full')
448
+ const storeApi = storeFor()
449
+ if (id.startsWith('cm_')) return evidenceForCommitment(storeApi, ledgerApi, id)
450
+ if (id.startsWith('fact_')) return evidenceForFact(storeApi, ledgerApi, id)
451
+ if (id.startsWith('pref_')) return evidenceForPreference(storeApi, ledgerApi, id)
430
452
  throw new ToolError('unknown evidence id prefix (want cm_/fact_/pref_)')
431
453
  }
432
454
 
433
455
  function evidenceIndex() {
434
- const ledgerApi = requireLedger()
456
+ const ledgerApi = requireLedger('full')
457
+ const storeApi = storeFor()
435
458
  const limit = 50
436
459
  const summarize = (kind, id, result) => ({
437
460
  kind,
@@ -443,13 +466,13 @@ export function createMcpServer({ store, ledger, version = '0.0.0', audit, readP
443
466
  const commitments = ledgerApi
444
467
  .listCommitments()
445
468
  .slice(0, limit)
446
- .map((c) => summarize('commitment', c.id, evidenceForCommitment(store, ledgerApi, c.id)))
469
+ .map((c) => summarize('commitment', c.id, evidenceForCommitment(storeApi, ledgerApi, c.id)))
447
470
  const facts = (typeof ledgerApi.listFacts === 'function' ? ledgerApi.listFacts() : [])
448
471
  .slice(0, limit)
449
- .map((f) => summarize('fact', f.id, evidenceForFact(store, ledgerApi, f.id)))
472
+ .map((f) => summarize('fact', f.id, evidenceForFact(storeApi, ledgerApi, f.id)))
450
473
  const preferences = (typeof ledgerApi.listPreferences === 'function' ? ledgerApi.listPreferences({ includeCandidates: false }) : [])
451
474
  .slice(0, limit)
452
- .map((p) => summarize('preference', p.id, evidenceForPreference(store, ledgerApi, p.id)))
475
+ .map((p) => summarize('preference', p.id, evidenceForPreference(storeApi, ledgerApi, p.id)))
453
476
  return { limits: { perKind: limit }, commitments, facts, preferences }
454
477
  }
455
478
 
@@ -466,11 +489,12 @@ export function createMcpServer({ store, ledger, version = '0.0.0', audit, readP
466
489
  const debtor = optionalEnum(args, 'debtor', ['user', 'agent', 'third'], 'user')
467
490
  const creditor = optionalString(args, 'creditor', { max: 200 }) ?? 'someone'
468
491
  const dueAt = optionalIsoDate(args, 'dueAt')
492
+ const mattersLedger = ledgerFor('matters')
469
493
  let matterId = optionalString(args, 'matterId', { max: 120 })
470
494
  if (matterId !== undefined) {
471
- if (typeof ledger?.getMatter !== 'function' || !ledger.getMatter(matterId)) throw invalidParams('unknown matter id')
495
+ if (typeof mattersLedger?.getMatter !== 'function' || !mattersLedger.getMatter(matterId)) throw invalidParams('unknown matter id')
472
496
  } else {
473
- matterId = typeof ledger?.listMatters === 'function' ? ledger.listMatters()[0]?.id : undefined
497
+ matterId = typeof mattersLedger?.listMatters === 'function' ? mattersLedger.listMatters()[0]?.id : undefined
474
498
  }
475
499
 
476
500
  const payload = { debtor, creditor: redact(creditor).text, action: redact(action).text, capability: 'none' }
@@ -494,7 +518,8 @@ export function createMcpServer({ store, ledger, version = '0.0.0', audit, readP
494
518
 
495
519
  function rollbackCandidate(id) {
496
520
  try {
497
- if (store && typeof store.reviewCandidate === 'function') store.reviewCandidate(id, 'rejected', 'audit_failed')
521
+ const storeApi = storeFor()
522
+ if (storeApi && typeof storeApi.reviewCandidate === 'function') storeApi.reviewCandidate(id, 'rejected', 'audit_failed')
498
523
  } catch {
499
524
  // best effort compensation only
500
525
  }
package/lib/model.js CHANGED
@@ -10,6 +10,7 @@ import {
10
10
  safetyErrorFrom,
11
11
  buildAuditReason,
12
12
  } from './safety/index.js'
13
+ import { redact } from './safety/redact.js'
13
14
 
14
15
  const RETRY_STATUS = new Set([429, 500, 502, 503, 504])
15
16
  const EFFORTS = new Set(['low', 'high', 'max'])
@@ -50,6 +51,71 @@ const TASK_EFFORT = {
50
51
  // docs/CONTENT-SAFETY.md section 8.
51
52
  // ---------------------------------------------------------------------------
52
53
  const SAFETY_SURFACE = 'model.output'
54
+ /** Coarse severity for a warning aggregate (inspectMessages keeps action only). */
55
+ function warningSeverityForAction(action) {
56
+ if (action === 'block' || action === 'confirm') return 'high'
57
+ if (action === 'warn' || action === 'redact') return 'medium'
58
+ return 'none'
59
+ }
60
+
61
+ /**
62
+ * Outbound secret/PII redaction (security audit SEC3-03, 2026-11-18).
63
+ *
64
+ * `redact`-classified strings (single-value PII and credentials) must never
65
+ * leave the machine verbatim. When the pre-flight classification found at
66
+ * least one redact-level hit, the request body is built from a redacted deep
67
+ * copy of the messages; the caller's array and the local ledger originals stay
68
+ * untouched. Redaction is one-way and text-only (no raw value is kept).
69
+ */
70
+ function redactEgressMessages(messages) {
71
+ const state = { messages, changed: false, count: 0 }
72
+ const kinds = new Set()
73
+ const clean = (value) => {
74
+ const result = redact(value)
75
+ if (!result.redacted) return value
76
+ state.changed = true
77
+ state.count += result.count
78
+ for (const kind of result.kinds) kinds.add(kind)
79
+ return result.text
80
+ }
81
+ if (!messages.some((message) => message && typeof message === 'object' && hasRedactableText(message))) return null
82
+ const next = messages.map((message) => {
83
+ if (!message || typeof message !== 'object') return message
84
+ const copy = { ...message }
85
+ if (typeof message.content === 'string') copy.content = clean(message.content)
86
+ else if (Array.isArray(message.content)) {
87
+ copy.content = message.content.map((part) => (part && typeof part === 'object' && typeof part.text === 'string' ? { ...part, text: clean(part.text) } : part))
88
+ }
89
+ if (Array.isArray(message.tool_calls)) {
90
+ copy.tool_calls = message.tool_calls.map((call) => {
91
+ if (!call || typeof call !== 'object' || !call.function || typeof call.function.arguments !== 'string') return call
92
+ return { ...call, function: { ...call.function, arguments: clean(call.function.arguments) } }
93
+ })
94
+ }
95
+ return copy
96
+ })
97
+ if (!state.changed) return null
98
+ return { messages: next, count: state.count, kinds: [...kinds] }
99
+ }
100
+
101
+ function hasRedactableText(message) {
102
+ if (typeof message.content === 'string' && message.content) return true
103
+ if (Array.isArray(message.content) && message.content.some((part) => part && typeof part === 'object' && typeof part.text === 'string' && part.text)) return true
104
+ if (Array.isArray(message.tool_calls) && message.tool_calls.some((call) => call && call.function && typeof call.function.arguments === 'string' && call.function.arguments)) return true
105
+ return false
106
+ }
107
+
108
+ /**
109
+ * A redact-level hit can be outranked by an unrelated warn/confirm hit in the
110
+ * same payload (action ordering), so never rely on the aggregate action alone:
111
+ * scan for redaction whenever the request is not a clean allow. Blocking
112
+ * requests throw before this point and never reach the network anyway.
113
+ */
114
+ function requestNeedsEgressRedaction(requestSafety) {
115
+ if (!requestSafety) return false
116
+ return requestSafety.action !== 'allow'
117
+ }
118
+
53
119
  /** Disable the optional DeepSeek safety_check network-side gate with '0'. */
54
120
  const SAFETY_CLOUD_ENV = 'ADVISERS_SAFETY_CLOUD'
55
121
 
@@ -75,6 +141,9 @@ function safetyWarningOf(result, direction) {
75
141
  rulesetVersion: result.rulesetVersion,
76
142
  evidenceHash: result.evidenceHash || null,
77
143
  crisis: Boolean(result.crisis),
144
+ severity: result.severity || warningSeverityForAction(result.action),
145
+ confidence: typeof result.confidence === 'number' ? result.confidence : 0,
146
+ reason: result.reason || result.code,
78
147
  auditReason,
79
148
  }
80
149
  }
@@ -190,6 +259,7 @@ export async function chatCompletion({
190
259
  signal,
191
260
  safetyKey,
192
261
  safetyCheck,
262
+ redactEgress = true,
193
263
  }) {
194
264
  if (!apiKey) throw new ModelError('missing API key', { code: 'MISSING_API_KEY' })
195
265
  const policy = thinking === false ? { enabled: false } : { enabled: true, ...resolveThinking({ task, explicit: effort }) }
@@ -201,7 +271,8 @@ export async function chatCompletion({
201
271
  throwIfBlocked(requestSafety, provider, 'input')
202
272
  const safetyWarnings = safetyWarningsOf(requestSafety, 'input')
203
273
 
204
- const body = { model, messages, max_tokens: maxTokens }
274
+ const egress = redactEgress === false || !requestNeedsEgressRedaction(requestSafety) ? null : redactEgressMessages(messages)
275
+ const body = { model, messages: egress ? egress.messages : messages, max_tokens: maxTokens }
205
276
  if (tools?.length) body.tools = tools
206
277
  if (provider === 'deepseek') {
207
278
  // Optional network-side second net (DeepSeek supports safety_check on the
@@ -278,6 +349,7 @@ export async function chatCompletion({
278
349
  thinking: policy,
279
350
  model,
280
351
  ...(safetyWarnings.length ? { safetyWarnings } : {}),
352
+ ...(egress ? { egressRedaction: { count: egress.count, kinds: egress.kinds } } : {}),
281
353
  }
282
354
  }
283
355
  } catch (error) {
package/lib/ocr.js CHANGED
@@ -8,7 +8,7 @@
8
8
  * silently treated as empty/valid text.
9
9
  */
10
10
  import { spawn } from 'node:child_process'
11
- import { statSync } from 'node:fs'
11
+ import { realpathSync, statSync } from 'node:fs'
12
12
  import { resolve, isAbsolute, relative } from 'node:path'
13
13
 
14
14
  /**
@@ -43,16 +43,36 @@ export function ocrConfigured() {
43
43
  return Boolean(process.env.ADVISERS_OCR_CMD)
44
44
  }
45
45
 
46
- export function assertOcrPath(file, cwd = process.cwd()) {
47
- const abs = resolve(cwd, file)
48
- const rel = relative(resolve(cwd), abs)
49
- if (rel.startsWith('..') || isAbsolute(rel)) throw new Error(`OCR file escapes workspace: ${file}`)
50
- const info = statSync(abs)
51
- if (!info.isFile()) throw new Error(`not a file: ${file}`)
52
- if (info.size > 10 * 1024 * 1024) throw new Error('OCR file is larger than 10 MB')
53
- return abs
46
+ function resolveContainedFile(file, cwd, label) {
47
+ if (typeof file !== 'string' || !file) throw new Error(label + ' path is required')
48
+ const rootLexical = resolve(cwd)
49
+ let root
50
+ try {
51
+ root = realpathSync(rootLexical)
52
+ } catch {
53
+ throw new Error(label + ' workspace does not exist: ' + cwd)
54
+ }
55
+ const abs = resolve(rootLexical, file)
56
+ const lexicalRel = relative(rootLexical, abs)
57
+ if (lexicalRel.startsWith('..') || isAbsolute(lexicalRel)) throw new Error(label + ' file escapes workspace: ' + file)
58
+ let real
59
+ try {
60
+ real = realpathSync(abs)
61
+ } catch (error) {
62
+ if (error && error.code === 'ENOENT') throw new Error(label + ' file not found: ' + file)
63
+ throw error
64
+ }
65
+ const realRel = relative(root, real)
66
+ if (realRel.startsWith('..') || isAbsolute(realRel)) throw new Error(label + ' file escapes workspace through a symlink: ' + file)
67
+ const info = statSync(real)
68
+ if (!info.isFile()) throw new Error('not a file: ' + file)
69
+ if (info.size > 10 * 1024 * 1024) throw new Error(label + ' file is larger than 10 MB')
70
+ return real
54
71
  }
55
72
 
73
+ export function assertOcrPath(file, cwd = process.cwd()) {
74
+ return resolveContainedFile(file, cwd, 'OCR')
75
+ }
56
76
  export async function runLocalOcr(file, { cmd = process.env.ADVISERS_OCR_CMD, timeoutMs = MAX_OCR_MS, cwd = process.cwd() } = {}) {
57
77
  if (!cmd) throw new Error('OCR is not configured; set ADVISERS_OCR_CMD to a local OCR executable (no cloud OCR is used)')
58
78
  const abs = assertOcrPath(file, cwd)
package/lib/pet-brief.js CHANGED
@@ -14,9 +14,8 @@
14
14
  * - `displayPolicy` states who may see the brief (public/private/none); it
15
15
  * defaults to `private` and is never `public` unless explicitly requested.
16
16
  */
17
- import { chmodSync, closeSync, fsyncSync, mkdirSync, openSync, renameSync, unlinkSync, writeSync } from 'node:fs'
18
- import { basename, dirname, join } from 'node:path'
19
17
  import { localDay } from './remind.js'
18
+ import { atomicWriteFileSync } from './fs-safe.js'
20
19
  import { classify } from './safety/index.js'
21
20
 
22
21
  export const PET_BRIEF_SCHEMA_VERSION = 2
@@ -205,6 +204,18 @@ export function buildPetBrief(ledger, options = {}) {
205
204
 
206
205
  // Public open commitments: matter must be active with secrecy < 2.
207
206
  const publicOpen = openCommitments.filter((commitment) => publicMatterIds.has(commitment.matterId))
207
+ // 0.2.3 P1a/B3: never drop a commitment silently. A public active matter (in
208
+ // particular a NON-default matter created with `matter add`) is projected by
209
+ // the arrays below; anything that cannot be projected is counted and disclosed
210
+ // in `redactions` instead of making counts quietly smaller.
211
+ const excludedOpen = { secrecy: 0, inactive: 0, dangling: 0 }
212
+ for (const commitment of openCommitments) {
213
+ if (publicMatterIds.has(commitment.matterId)) continue
214
+ const matter = matterById.get(commitment.matterId)
215
+ if (!matter) excludedOpen.dangling += 1
216
+ else if (matterSecrecy(matter) >= 2) excludedOpen.secrecy += 1
217
+ else excludedOpen.inactive += 1
218
+ }
208
219
  const dueMsOf = (commitment) => {
209
220
  if (!commitment.dueAt) return null
210
221
  const ms = Date.parse(commitment.dueAt)
@@ -357,6 +368,9 @@ export function buildPetBrief(ledger, options = {}) {
357
368
  redactions.push('不含模型推理、系统提示或原始提示词')
358
369
  const excludedSecrecy = allMatters.filter((matter) => matterSecrecy(matter) >= 2).length
359
370
  if (excludedSecrecy > 0) redactions.push(clip(`已排除保密等级≥2 的事项(${excludedSecrecy} 个)`, 80))
371
+ if (excludedOpen.secrecy > 0) redactions.push(clip(`已排除保密事项下的承诺(${excludedOpen.secrecy} 条)`, 80))
372
+ if (excludedOpen.inactive > 0) redactions.push(clip(`已排除已归档/暂停事项的承诺(${excludedOpen.inactive} 条)`, 80))
373
+ if (excludedOpen.dangling > 0) redactions.push(clip(`已排除无法归属的承诺(${excludedOpen.dangling} 条,matter 不存在)`, 80))
360
374
  const droppedTotal = dropped.risks + dropped.lines
361
375
  if (droppedTotal > 0) redactions.push(clip(`已丢弃 ${droppedTotal} 条不安全内容(不展示原文)`, 80))
362
376
  if (!redactions.some((note) => note.startsWith('联系人')) && !redactions.some((note) => note.includes('客户名'))) {
@@ -611,8 +625,12 @@ function parseIsoWithZone(value, path, errors) {
611
625
  }
612
626
 
613
627
  /**
614
- * Atomically write a brief: temp file in the same directory, fsync, rename,
615
- * then chmod 600. Atomic rename means a reader never sees a half-written file.
628
+ * Atomically write a brief.
629
+ *
630
+ * 0.2.3 Wave 1: delegates to lib/fs-safe.js so the write uses the short-write
631
+ * loop, fsync, size verification and an atomic same-directory rename. A short
632
+ * write/ENOSPC can no longer install a truncated brief (robustness audit P1-2),
633
+ * and a failed write removes its temp file instead of leaving it behind.
616
634
  *
617
635
  * @param {string} filePath destination path
618
636
  * @param {object} brief brief object
@@ -620,25 +638,6 @@ function parseIsoWithZone(value, path, errors) {
620
638
  */
621
639
  export function writePetBriefAtomic(filePath, brief) {
622
640
  const target = String(filePath)
623
- const dir = dirname(target)
624
- mkdirSync(dir, { recursive: true, mode: 0o700 })
625
- const data = `${JSON.stringify(brief, null, 2)}\n`
626
- const tmp = join(dir, `.${basename(target)}.${process.pid}.${Date.now().toString(36)}.tmp`)
627
- let fd
628
- try {
629
- fd = openSync(tmp, 'wx', 0o600)
630
- writeSync(fd, data)
631
- fsyncSync(fd)
632
- closeSync(fd)
633
- fd = undefined
634
- renameSync(tmp, target)
635
- chmodSync(target, 0o600)
636
- return target
637
- } catch (error) {
638
- if (fd !== undefined) {
639
- try { closeSync(fd) } catch {}
640
- }
641
- try { unlinkSync(tmp) } catch {}
642
- throw error
643
- }
641
+ atomicWriteFileSync(target, `${JSON.stringify(brief, null, 2)}\n`, { mode: 0o600 })
642
+ return target
644
643
  }
@@ -22,6 +22,10 @@
22
22
  * crisis: boolean, // self-harm: show crisis hint, never block
23
23
  * downgraded: boolean,
24
24
  * truncated: boolean, // true when only the first maxChars were scanned
25
+ * injection?: { // additive prompt-injection view (warn only)
26
+ * detected, highConfidence, severity, code, reason, subtype, confidence,
27
+ * ruleIds, action, surface
28
+ * }
25
29
  * hits: [{ ruleId, category, subtype, code, severity, action, confidence,
26
30
  * hardBlock, crisis, downgraded }]
27
31
  * }
@@ -38,7 +42,7 @@
38
42
  */
39
43
 
40
44
  import { createHmac } from 'node:crypto'
41
- import { DEFAULT_RULESET, actionRank, resolveRuleset } from './rules.js'
45
+ import { DEFAULT_RULESET, INJECTION_HIGH_CONFIDENCE, INJECTION_REASONS, actionRank, resolveRuleset } from './rules.js'
42
46
  import { detectPiiInternal } from './redact.js'
43
47
 
44
48
  export const DEFAULT_SURFACE = 'chat.input'
@@ -220,6 +224,7 @@ function buildHit(rule, snippet, actionOverride) {
220
224
  blockable: Boolean(rule.blockable),
221
225
  downgraded: null,
222
226
  snippet: snippet || rule.id,
227
+ reason: rule.category === 'injection' ? (INJECTION_REASONS[rule.subtype] || INJECTION_REASONS.default) : null,
223
228
  }
224
229
  }
225
230
 
@@ -384,9 +389,28 @@ function runClassify(ruleset, text, options = {}) {
384
389
  hardBlock: hit.hardBlock,
385
390
  crisis: hit.crisis,
386
391
  downgraded: hit.downgraded,
392
+ ...(hit.reason ? { reason: hit.reason } : {}),
387
393
  })),
388
394
  }
389
- return applyTruncationFailClosed(result, policy)
395
+ const final = applyTruncationFailClosed(result, policy)
396
+ const injectionHits = ordered.filter((hit) => hit.category === 'injection')
397
+ if (injectionHits.length) {
398
+ const maxConfidence = Math.max(...injectionHits.map((hit) => hit.confidence))
399
+ const primary = injectionHits[0]
400
+ final.injection = {
401
+ detected: true,
402
+ highConfidence: maxConfidence >= INJECTION_HIGH_CONFIDENCE,
403
+ severity: primary.severity,
404
+ code: primary.code,
405
+ reason: primary.reason || INJECTION_REASONS.default,
406
+ subtype: primary.subtype,
407
+ confidence: Math.round(maxConfidence * 100) / 100,
408
+ ruleIds: [...new Set(injectionHits.map((hit) => hit.ruleId))],
409
+ action: final.action,
410
+ surface,
411
+ }
412
+ }
413
+ return final
390
414
  }
391
415
 
392
416
  /**
@@ -425,6 +449,35 @@ export function classify(text, options = {}) {
425
449
  }
426
450
  }
427
451
 
452
+ /**
453
+ * Structured injection view of any classify() result (allow results included).
454
+ * The rule action stays warn; this view is what policy callers (lib/agent.js)
455
+ * use to block/confirm a model call that would carry untrusted instructions.
456
+ * It never contains the matched text.
457
+ */
458
+ export function injectionAssessment(result) {
459
+ const injection = result && result.injection && result.injection.detected ? result.injection : null
460
+ return {
461
+ detected: Boolean(injection),
462
+ highConfidence: Boolean(injection && injection.highConfidence),
463
+ severity: injection ? injection.severity : 'none',
464
+ code: injection ? injection.code : 'NONE',
465
+ reason: injection ? injection.reason : null,
466
+ subtype: injection ? injection.subtype : null,
467
+ confidence: injection ? injection.confidence : 0,
468
+ ruleIds: injection && Array.isArray(injection.ruleIds) ? [...injection.ruleIds] : [],
469
+ action: result ? result.action : 'allow',
470
+ surface: result ? result.surface : 'unknown',
471
+ truncated: Boolean(result && result.truncated),
472
+ }
473
+ }
474
+
475
+ /** classify() + injectionAssessment() in one call. */
476
+ export function inspectInjection(text, options = {}) {
477
+ return injectionAssessment(classify(text, options))
478
+ }
479
+
480
+ export { INJECTION_HIGH_CONFIDENCE }
428
481
  /** Bind a ruleset (and default options such as hmacKey) to a classify function. */
429
482
  export function createClassifier(config = {}) {
430
483
  let ruleset = DEFAULT_RULESET
@@ -24,6 +24,34 @@ export const RULESET_VERSION = 'advisers-content-1'
24
24
  /** Actions a rule/result may carry. `allow` is only ever a classifier result. */
25
25
  export const ACTIONS = Object.freeze(['allow', 'warn', 'confirm', 'redact', 'block'])
26
26
  export const SEVERITIES = Object.freeze(['low', 'medium', 'high', 'critical'])
27
+ /**
28
+ * Structured prompt-injection metadata (engineering risk, never block).
29
+ *
30
+ * The injection category is a local engineering warning, not a legal
31
+ * violation: classify() keeps action=warn for it and callers decide how to
32
+ * contain the content (see lib/agent.js, which blocks/confirms a model call
33
+ * when untrusted data contains a high-confidence instruction override).
34
+ * The reason strings are safe to print: they never contain the matched text.
35
+ */
36
+ export const INJECTION_REASONS = Object.freeze({
37
+ instruction_override: '内容试图忽略或覆盖系统/安全指令',
38
+ instruction_override_en: 'content tries to override system instructions',
39
+ prompt_leak: '内容试图获取系统提示或隐藏指令',
40
+ jailbreak_role: '内容试图切换为越狱/无限制角色',
41
+ secret_exfiltration: '内容试图诱导输出密钥或凭据',
42
+ tool_output_injection: '内容声称工具输出/检索结果应被当作指令',
43
+ safety_bypass: '内容试图关闭或绕过安全规则',
44
+ privileged_command: '内容试图诱导越权命令或删除审计/系统数据',
45
+ unrestricted_persona: '内容试图塑造不受限制的人设',
46
+ default: '内容包含提示注入或越权指令特征',
47
+ })
48
+
49
+ /**
50
+ * Hit confidence at or above this is "high confidence" instruction
51
+ * injection for the agent's pre-model gate (block/confirm). Deliberately a
52
+ * named constant so the policy is auditable and testable.
53
+ */
54
+ export const INJECTION_HIGH_CONFIDENCE = 0.8
27
55
 
28
56
  /**
29
57
  * Categories that are allowed to carry a block rule at all. Inside these