@restregular/dsh-memory 0.11.1 → 0.12.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.
- package/CHANGELOG.md +24 -0
- package/README.md +35 -2
- package/lib/client.js +481 -1
- package/lib/inject/apply.js +406 -114
- package/lib/inject/audit-types.js +219 -0
- package/lib/inject/audit.js +298 -55
- package/lib/inject/inject.js +72 -10
- package/lib/inject/rules-delta.js +58 -33
- package/lib/inject/rules.js +43 -23
- package/lib/panel.js +206 -6
- package/lib/provider/index.js +65 -4
- package/package.json +1 -1
package/lib/inject/apply.js
CHANGED
|
@@ -40,11 +40,20 @@ import {
|
|
|
40
40
|
|
|
41
41
|
} from './inject.js'
|
|
42
42
|
import { renderDigest, } from './digest.js'
|
|
43
|
-
import { renderRules,
|
|
43
|
+
import { renderRules, } from './rules.js'
|
|
44
44
|
import { RulesDeltaInjector } from './rules-delta.js'
|
|
45
45
|
import { POLICY_TEXT } from './policy.js'
|
|
46
46
|
import { InjectionState } from './state.js'
|
|
47
|
-
import {
|
|
47
|
+
import {
|
|
48
|
+
InjectAuditStore,
|
|
49
|
+
auditBudget,
|
|
50
|
+
hashAuditText,
|
|
51
|
+
sanitizeAuditTags,
|
|
52
|
+
sanitizeAuditText,
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
} from './audit.js'
|
|
48
57
|
import {
|
|
49
58
|
BehaviorSignalStore,
|
|
50
59
|
assistantVisibleText,
|
|
@@ -74,7 +83,8 @@ import { normalizeInjectSettings, } from '../provider/inject
|
|
|
74
83
|
|
|
75
84
|
|
|
76
85
|
|
|
77
|
-
|
|
86
|
+
|
|
87
|
+
|
|
78
88
|
|
|
79
89
|
|
|
80
90
|
/** 轮末提醒的文案:短、祈使句,不占预算。 */
|
|
@@ -119,6 +129,10 @@ export function apply(ctx , config = {}) {
|
|
|
119
129
|
const sessionScopes = new Map ()
|
|
120
130
|
const sessionAutoScopes = new Map ()
|
|
121
131
|
const tagCache = new Map ()
|
|
132
|
+
/** 系统提示 rules 段的同源渲染缓存:pre-step 算一次,section 回调复用。 */
|
|
133
|
+
const rulesCache = new Map ()
|
|
134
|
+
const rulesStepStart = new Map ()
|
|
135
|
+
let systemPromptReady = false
|
|
122
136
|
let attachedMemory = null
|
|
123
137
|
|
|
124
138
|
const attachAudit = (memory ) => {
|
|
@@ -130,8 +144,46 @@ export function apply(ctx , config = {}) {
|
|
|
130
144
|
} catch { /* 审计是可选增强 */ }
|
|
131
145
|
}
|
|
132
146
|
|
|
133
|
-
|
|
134
|
-
|
|
147
|
+
// 插件半边卸载时解绑并释放内存;provider 若已切换到新实例,detachInjectAudit
|
|
148
|
+
// 会按 sink 身份判断,不会误清掉后来者的 sink。
|
|
149
|
+
try {
|
|
150
|
+
ctx.effect(() => () => {
|
|
151
|
+
const memory = ctx.get('memory')
|
|
152
|
+
try {
|
|
153
|
+
if (typeof memory?.detachInjectAudit === 'function') memory.detachInjectAudit(audit)
|
|
154
|
+
else memory?.attachInjectAudit?.(null)
|
|
155
|
+
} catch { /* 解绑失败不影响卸载 */ }
|
|
156
|
+
attachedMemory = null
|
|
157
|
+
audit.dispose()
|
|
158
|
+
}, 'dsh-memory: audit sink')
|
|
159
|
+
} catch { /* 老宿主没有 ctx.effect */ }
|
|
160
|
+
|
|
161
|
+
const recordAudit = (entry ) => {
|
|
162
|
+
audit.record(entry)
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** 系统提示 rules 段实际使用的 scope(与 section 回调保持同一口径)。 */
|
|
166
|
+
const promptScopesFor = (memory , agent ) => {
|
|
167
|
+
try {
|
|
168
|
+
const resolved = memory.resolveReadScopes?.(agent)
|
|
169
|
+
if (Array.isArray(resolved) && resolved.length > 0) return resolved
|
|
170
|
+
} catch { /* fallthrough */ }
|
|
171
|
+
return ['global']
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const sameScopes = (a , b ) =>
|
|
175
|
+
a.length === b.length && a.every((scope, index) => scope === b[index])
|
|
176
|
+
|
|
177
|
+
const renderRulesFor = (
|
|
178
|
+
memory ,
|
|
179
|
+
scopes ,
|
|
180
|
+
cfg ,
|
|
181
|
+
) => {
|
|
182
|
+
try {
|
|
183
|
+
return { ok: true, render: renderRules(memory.listSync?.({ scopes: [...scopes], kind: 'rule', limit: 100 }) ?? [], cfg) }
|
|
184
|
+
} catch {
|
|
185
|
+
return { ok: false, errorCode: 'source_load_failed' }
|
|
186
|
+
}
|
|
135
187
|
}
|
|
136
188
|
|
|
137
189
|
const rememberCallMeta = (callId , name , description ) => {
|
|
@@ -226,14 +278,19 @@ export function apply(ctx , config = {}) {
|
|
|
226
278
|
|
|
227
279
|
const observeSignal = (sessionId , signal ) => {
|
|
228
280
|
if (!signal || !signals.note(sessionId, signal)) return
|
|
281
|
+
const query = sanitizeAuditText(signal.query)
|
|
229
282
|
recordAudit({
|
|
283
|
+
kind: 'signal',
|
|
284
|
+
channel: 'signal',
|
|
285
|
+
stage: 'signal_queued',
|
|
286
|
+
outcome: 'success',
|
|
287
|
+
reasonCode: 'queued',
|
|
230
288
|
sessionId,
|
|
231
289
|
trigger: signal.reason,
|
|
232
290
|
phase: signal.phase,
|
|
233
|
-
query:
|
|
234
|
-
candidates: 0, contentIds: [], hintIds: [], omitted: [], dedupSkipped: 0, budgets: {},
|
|
235
|
-
retrieval: { ok: true, count: 0 },
|
|
291
|
+
...(query !== undefined ? { query } : {}),
|
|
236
292
|
signal: {
|
|
293
|
+
key: signal.key,
|
|
237
294
|
reason: signal.reason,
|
|
238
295
|
...(signal.errorClass ? { errorClass: signal.errorClass } : {}),
|
|
239
296
|
...(signal.tool ? { tool: signal.tool } : {}),
|
|
@@ -288,11 +345,18 @@ export function apply(ctx , config = {}) {
|
|
|
288
345
|
|
|
289
346
|
if (type === 'compaction/start' || type === 'compaction/end') {
|
|
290
347
|
// 上下文重建:旧去重状态不再可信,允许摘要/正文重新进入。
|
|
348
|
+
// 审计也要留下分界,否则压缩前后的记录会被误读成同一段上下文。
|
|
349
|
+
recordAudit({
|
|
350
|
+
kind: 'lifecycle', channel: 'lifecycle', stage: 'compaction',
|
|
351
|
+
outcome: 'success', reasonCode: 'context_compacted', sessionId,
|
|
352
|
+
})
|
|
291
353
|
injectionState.clear(sessionId)
|
|
292
354
|
signals.clear(sessionId)
|
|
293
355
|
digester.reset(sessionId)
|
|
294
356
|
sessionScopes.delete(sessionId)
|
|
295
357
|
sessionAutoScopes.delete(sessionId)
|
|
358
|
+
rulesCache.delete(sessionId)
|
|
359
|
+
rulesStepStart.delete(sessionId)
|
|
296
360
|
for (const key of tagCache.keys()) if (key.startsWith(`${sessionId}|`)) tagCache.delete(key)
|
|
297
361
|
callMeta.clear()
|
|
298
362
|
return
|
|
@@ -372,19 +436,24 @@ export function apply(ctx , config = {}) {
|
|
|
372
436
|
if (!enabled || !settingsOf().rules.enabled) return ''
|
|
373
437
|
const memory = ctx.get('memory')
|
|
374
438
|
if (!memory?.listSync) return ''
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
return ''
|
|
439
|
+
const scopes = promptScopesFor(memory, context?.agent)
|
|
440
|
+
const sessionId = sessionIdOf(context?.agent)
|
|
441
|
+
const started = sessionId === undefined ? undefined : rulesStepStart.get(sessionId)
|
|
442
|
+
const cached = sessionId === undefined ? undefined : rulesCache.get(sessionId)
|
|
443
|
+
// pre-step 已经算过同一份渲染时直接复用:审计与系统提示必须是同一份文本。
|
|
444
|
+
if (cached !== undefined && started !== undefined && cached.at >= started && sameScopes(cached.scopes, scopes)) {
|
|
445
|
+
return cached.render.text
|
|
383
446
|
}
|
|
447
|
+
const rendered = renderRulesFor(memory, scopes, settingsOf().rules)
|
|
448
|
+
if (!rendered.ok) return ''
|
|
449
|
+
if (sessionId !== undefined) rulesCache.set(sessionId, { at: Date.now(), scopes, render: rendered.render })
|
|
450
|
+
return rendered.render.text
|
|
384
451
|
},
|
|
385
452
|
})
|
|
453
|
+
systemPromptReady = true
|
|
386
454
|
} catch {
|
|
387
455
|
/* 重复注册或老宿主没有 section 契约:规则段缺席不影响注入 */
|
|
456
|
+
systemPromptReady = false
|
|
388
457
|
}
|
|
389
458
|
})
|
|
390
459
|
|
|
@@ -408,10 +477,14 @@ export function apply(ctx , config = {}) {
|
|
|
408
477
|
|
|
409
478
|
const agent = (input ).agent
|
|
410
479
|
const step = (input ).step ?? 1
|
|
480
|
+
const turnValue = (input ).turn
|
|
481
|
+
const turn = typeof turnValue === 'number' && Number.isFinite(turnValue) ? turnValue : undefined
|
|
482
|
+
const stepStartedAt = Date.now()
|
|
411
483
|
if (step === 1) maxStep = 0
|
|
412
484
|
maxStep = Math.max(maxStep, step)
|
|
413
485
|
|
|
414
486
|
const sessionId = sessionIdOf(agent)
|
|
487
|
+
if (sessionId !== undefined) rulesStepStart.set(sessionId, stepStartedAt)
|
|
415
488
|
const scopes = readScopesFor(memory, agent)
|
|
416
489
|
if (sessionId !== undefined && scopes !== undefined) sessionScopes.set(sessionId, [...scopes])
|
|
417
490
|
let autoScopes
|
|
@@ -423,131 +496,350 @@ export function apply(ctx , config = {}) {
|
|
|
423
496
|
const signal = sessionId === undefined ? undefined : signals.take(sessionId)
|
|
424
497
|
const usableSignal = autoScopes === undefined ? undefined : signal
|
|
425
498
|
const userQuery = pickQueryText(input.messages )
|
|
499
|
+
const phase = detectPhase(userQuery)
|
|
500
|
+
const userQueryField = sanitizeAuditText(userQuery)
|
|
501
|
+
const auditBase = (channel , extra ) => ({
|
|
502
|
+
...(sessionId !== undefined ? { sessionId } : {}),
|
|
503
|
+
...(turn !== undefined ? { turn } : {}),
|
|
504
|
+
...(step !== undefined ? { step } : {}),
|
|
505
|
+
phase,
|
|
506
|
+
channel,
|
|
507
|
+
...extra,
|
|
508
|
+
})
|
|
509
|
+
|
|
510
|
+
if (!enabled) {
|
|
511
|
+
if (step === 1) {
|
|
512
|
+
recordAudit(auditBase('lifecycle', {
|
|
513
|
+
kind: 'lifecycle', stage: 'disabled', outcome: 'skipped', reasonCode: 'injection_disabled',
|
|
514
|
+
}))
|
|
515
|
+
}
|
|
516
|
+
return decision
|
|
517
|
+
}
|
|
518
|
+
const settings = settingsOf()
|
|
426
519
|
|
|
427
|
-
//
|
|
428
|
-
//
|
|
429
|
-
const
|
|
520
|
+
// 本步的评估先收集,等最终消息组装/校验完成后再统一写 evaluation + delivery。
|
|
521
|
+
// 这样可以准确表达“评估选中了 X”与“消息真的追加了吗”两件不同的事。
|
|
522
|
+
const staged = []
|
|
430
523
|
const parts = []
|
|
524
|
+
const messageChannels = new Set ()
|
|
525
|
+
const stage = (entry ) => { staged.push(entry) }
|
|
526
|
+
|
|
527
|
+
if (signal !== undefined && usableSignal === undefined) {
|
|
528
|
+
recordAudit(auditBase('signal', {
|
|
529
|
+
kind: 'signal', stage: 'signal_dropped', outcome: 'skipped', reasonCode: 'auto_scope_unavailable',
|
|
530
|
+
trigger: signal.reason, phase: signal.phase,
|
|
531
|
+
signal: { key: signal.key, reason: signal.reason, ...(signal.tag ? { tag: signal.tag } : {}), ...(signal.tool ? { tool: signal.tool } : {}) },
|
|
532
|
+
}))
|
|
533
|
+
}
|
|
534
|
+
if (usableSignal !== undefined) {
|
|
535
|
+
recordAudit(auditBase('signal', {
|
|
536
|
+
kind: 'signal', stage: 'signal_consumed', outcome: 'success', reasonCode: 'consumed',
|
|
537
|
+
trigger: usableSignal.reason, phase: usableSignal.phase,
|
|
538
|
+
signal: { key: usableSignal.key, reason: usableSignal.reason, ...(usableSignal.tag ? { tag: usableSignal.tag } : {}), ...(usableSignal.tool ? { tool: usableSignal.tool } : {}), ...(usableSignal.errorClass ? { errorClass: usableSignal.errorClass } : {}), ...(usableSignal.source ? { source: usableSignal.source } : {}) },
|
|
539
|
+
}))
|
|
540
|
+
}
|
|
541
|
+
|
|
431
542
|
// 规则增量:别的会话新加/改过的规则,在本轮第一步给旧会话补一次。
|
|
432
543
|
// `delta !== false` 而不是 `=== true`:老 provider 的 settings 快照没有这个
|
|
433
544
|
// 字段时要按"开"处理,否则升级当天等于静默关掉。
|
|
434
|
-
if (
|
|
435
|
-
|
|
436
|
-
|
|
545
|
+
if (step === 1 && settings.rules.enabled) {
|
|
546
|
+
if (settings.rules.delta === false) {
|
|
547
|
+
stage(auditBase('rules_delta', {
|
|
548
|
+
kind: 'evaluation', stage: 'skipped', outcome: 'skipped', reasonCode: 'disabled',
|
|
549
|
+
}))
|
|
550
|
+
} else {
|
|
551
|
+
const delta = rulesDelta.maybeInjectDetailed(agent, memory, settings.rules)
|
|
552
|
+
if (delta.text !== undefined) {
|
|
553
|
+
parts.push(delta.text)
|
|
554
|
+
messageChannels.add('rules_delta')
|
|
555
|
+
stage(auditBase('rules_delta', {
|
|
556
|
+
kind: 'evaluation', stage: 'rendered', outcome: 'success', reasonCode: 'delta_rendered',
|
|
557
|
+
selected: { contentIds: delta.changes.map((change) => change.id), hintIds: [], count: delta.records.length },
|
|
558
|
+
budgets: { rules_delta: auditBudget(Math.max(settings.rules.tokenBudget, 600), delta.tokens ?? 0) },
|
|
559
|
+
limits: { maxItems: settings.rules.maxItems, budgets: { rules: settings.rules.tokenBudget } },
|
|
560
|
+
}))
|
|
561
|
+
} else {
|
|
562
|
+
stage(auditBase('rules_delta', {
|
|
563
|
+
kind: 'evaluation', stage: 'skipped', outcome: 'skipped',
|
|
564
|
+
reasonCode: delta.changes.length === 0 ? 'no_changes' : 'nothing_to_render',
|
|
565
|
+
}))
|
|
566
|
+
}
|
|
567
|
+
}
|
|
437
568
|
}
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
569
|
+
|
|
570
|
+
// 轮末提醒:下一轮第一步附带一句提醒。
|
|
571
|
+
if (step === 1) {
|
|
572
|
+
if (!settings.turnEnd.enabled) {
|
|
573
|
+
stage(auditBase('nudge', { kind: 'evaluation', stage: 'skipped', outcome: 'skipped', reasonCode: 'disabled' }))
|
|
574
|
+
} else if (pendingNudge) {
|
|
575
|
+
pendingNudge = false
|
|
576
|
+
parts.push(NUDGE_TEXT)
|
|
577
|
+
messageChannels.add('nudge')
|
|
578
|
+
stage(auditBase('nudge', {
|
|
579
|
+
kind: 'evaluation', stage: 'rendered', outcome: 'success', reasonCode: 'turn_end',
|
|
580
|
+
delivery: { status: 'unknown', appended: null, textChars: NUDGE_TEXT.length, textHash: hashAuditText(NUDGE_TEXT) },
|
|
581
|
+
}))
|
|
582
|
+
} else {
|
|
583
|
+
stage(auditBase('nudge', { kind: 'evaluation', stage: 'skipped', outcome: 'skipped', reasonCode: 'not_due' }))
|
|
584
|
+
}
|
|
441
585
|
}
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
})
|
|
471
|
-
}
|
|
586
|
+
|
|
587
|
+
// 摘要(每个会话一次)。
|
|
588
|
+
if (settings.digest.enabled) {
|
|
589
|
+
let digestStats
|
|
590
|
+
const outcome = await digester.maybeDigestOutcome(sessionId, scopes, (records) => {
|
|
591
|
+
const rendered = renderDigest(records, settings.digest)
|
|
592
|
+
digestStats = rendered?.stats
|
|
593
|
+
return rendered
|
|
594
|
+
})
|
|
595
|
+
if (outcome.status === 'failed') {
|
|
596
|
+
stage(auditBase('digest', {
|
|
597
|
+
kind: 'evaluation', stage: 'source_load', outcome: 'failed', reasonCode: outcome.errorCode,
|
|
598
|
+
trigger: 'turn_start',
|
|
599
|
+
sourceLoad: { ok: false, errorCode: outcome.errorCode },
|
|
600
|
+
error: { stage: 'source_load', code: outcome.errorCode },
|
|
601
|
+
}))
|
|
602
|
+
} else if (outcome.status === 'ok' && outcome.empty) {
|
|
603
|
+
stage(auditBase('digest', {
|
|
604
|
+
kind: 'evaluation', stage: 'source_load', outcome: 'skipped', reasonCode: 'no_candidates',
|
|
605
|
+
trigger: 'turn_start',
|
|
606
|
+
candidates: outcome.candidates,
|
|
607
|
+
sourceLoad: { ok: true, count: outcome.candidates },
|
|
608
|
+
limits: { topK: settings.digest.topK, budgets: { digest: settings.digest.tokenBudget, hints: settings.digest.hintBudget } },
|
|
609
|
+
}))
|
|
610
|
+
} else if (outcome.status === 'ok' && outcome.value !== undefined && digestStats !== undefined) {
|
|
611
|
+
if (sessionId !== undefined) {
|
|
612
|
+
injectionState.markContent(sessionId, digestStats.bodyEntries)
|
|
613
|
+
injectionState.markHint(sessionId, digestStats.hintEntries)
|
|
472
614
|
}
|
|
615
|
+
parts.push(outcome.value.text)
|
|
616
|
+
messageChannels.add('digest')
|
|
617
|
+
stage(auditBase('digest', {
|
|
618
|
+
kind: 'evaluation', stage: 'rendered', outcome: 'success', reasonCode: 'rendered',
|
|
619
|
+
trigger: 'turn_start',
|
|
620
|
+
candidates: digestStats.candidates,
|
|
621
|
+
selected: {
|
|
622
|
+
contentIds: digestStats.bodyIds,
|
|
623
|
+
hintIds: digestStats.hintIds,
|
|
624
|
+
count: digestStats.bodyIds.length,
|
|
625
|
+
},
|
|
626
|
+
omitted: digestStats.omitted.map((entry) => ({
|
|
627
|
+
id: entry.id,
|
|
628
|
+
reason: entry.reason,
|
|
629
|
+
...(entry.kind !== undefined ? { kind: entry.kind } : {}),
|
|
630
|
+
...(entry.tags !== undefined ? { tags: sanitizeAuditTags(entry.tags) } : {}),
|
|
631
|
+
})),
|
|
632
|
+
budgets: {
|
|
633
|
+
digest: auditBudget(settings.digest.tokenBudget, outcome.value.tokens),
|
|
634
|
+
hints: auditBudget(settings.digest.hintBudget, digestStats.hint.tokens),
|
|
635
|
+
},
|
|
636
|
+
sourceLoad: { ok: true, count: digestStats.candidates },
|
|
637
|
+
limits: { topK: settings.digest.topK, budgets: { digest: settings.digest.tokenBudget, hints: settings.digest.hintBudget } },
|
|
638
|
+
scopes: scopes !== undefined ? [...scopes] : undefined,
|
|
639
|
+
}))
|
|
473
640
|
}
|
|
641
|
+
} else if (step === 1) {
|
|
642
|
+
stage(auditBase('digest', { kind: 'evaluation', stage: 'skipped', outcome: 'skipped', reasonCode: 'disabled' }))
|
|
643
|
+
}
|
|
474
644
|
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
645
|
+
// 规则段:只做一次渲染,并把同一份结果交给系统提示(若宿主先跑 pre-step 再 assemble)。
|
|
646
|
+
if (step === 1) {
|
|
647
|
+
if (!settings.rules.enabled) {
|
|
648
|
+
stage(auditBase('rules', { kind: 'evaluation', stage: 'skipped', outcome: 'skipped', reasonCode: 'disabled' }))
|
|
649
|
+
} else if (!systemPromptReady) {
|
|
650
|
+
stage(auditBase('rules', { kind: 'evaluation', stage: 'skipped', outcome: 'skipped', reasonCode: 'system_prompt_unavailable' }))
|
|
651
|
+
} else {
|
|
652
|
+
const promptScopes = promptScopesFor(memory, agent)
|
|
653
|
+
const rendered = renderRulesFor(memory, promptScopes, settings.rules)
|
|
654
|
+
if (!rendered.ok) {
|
|
655
|
+
stage(auditBase('rules', {
|
|
656
|
+
kind: 'evaluation', stage: 'source_load', outcome: 'failed', reasonCode: rendered.errorCode,
|
|
657
|
+
scopes: promptScopes,
|
|
658
|
+
error: { stage: 'source_load', code: rendered.errorCode },
|
|
659
|
+
}))
|
|
660
|
+
} else {
|
|
661
|
+
if (sessionId !== undefined) rulesCache.set(sessionId, { at: Date.now(), scopes: promptScopes, render: rendered.render })
|
|
662
|
+
const rulesStats = rendered.render.stats
|
|
663
|
+
const rulesOutcome = rulesStats.candidates === 0 ? 'skipped' : rulesStats.injected === 0 ? 'partial' : 'success'
|
|
664
|
+
const rulesReason = rulesStats.candidates === 0 ? 'no_candidates' : rulesStats.injected === 0 ? 'all_omitted' : 'system_prompt_shared_render'
|
|
665
|
+
stage(auditBase('rules', {
|
|
666
|
+
kind: 'evaluation', stage: 'rendered', outcome: rulesOutcome, reasonCode: rulesReason,
|
|
667
|
+
scopes: promptScopes,
|
|
668
|
+
candidates: rulesStats.candidates,
|
|
669
|
+
selected: {
|
|
670
|
+
contentIds: rulesStats.injectedIds,
|
|
671
|
+
hintIds: [],
|
|
672
|
+
count: rulesStats.injected,
|
|
673
|
+
},
|
|
674
|
+
omitted: rulesStats.omitted.map((entry) => ({ id: entry.id, reason: entry.reason })),
|
|
675
|
+
budgets: { rules: auditBudget(settings.rules.tokenBudget, rendered.render.tokens) },
|
|
676
|
+
limits: { maxItems: settings.rules.maxItems, budgets: { rules: settings.rules.tokenBudget } },
|
|
677
|
+
rules: {
|
|
678
|
+
active: rulesStats.active,
|
|
679
|
+
injected: rulesStats.injected,
|
|
680
|
+
mandatory: rulesStats.mandatory,
|
|
681
|
+
mandatoryInjected: rulesStats.mandatoryInjected,
|
|
682
|
+
mandatoryOmitted: rulesStats.mandatoryOmitted,
|
|
683
|
+
injectedIds: rulesStats.injectedIds,
|
|
684
|
+
omittedIds: rulesStats.omittedIds,
|
|
685
|
+
},
|
|
686
|
+
delivery: { status: 'unknown', appended: null, textChars: rendered.render.text.length, textHash: hashAuditText(rendered.render.text) },
|
|
687
|
+
}))
|
|
688
|
+
}
|
|
498
689
|
}
|
|
690
|
+
}
|
|
499
691
|
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
692
|
+
// 策略段是常量系统提示;只记录它存在,不声称“模型读了”。
|
|
693
|
+
if (step === 1) {
|
|
694
|
+
if (settings.policy.enabled) {
|
|
695
|
+
stage(auditBase('policy', {
|
|
696
|
+
kind: 'evaluation', stage: 'system_prompt', outcome: 'success', reasonCode: 'constant_text',
|
|
697
|
+
delivery: { status: 'unknown', appended: null, textChars: POLICY_TEXT.length, textHash: hashAuditText(POLICY_TEXT) },
|
|
698
|
+
}))
|
|
699
|
+
} else {
|
|
700
|
+
stage(auditBase('policy', { kind: 'evaluation', stage: 'skipped', outcome: 'skipped', reasonCode: 'disabled' }))
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
// 行为信号优先:发布/推送/失败事件触发定向查询;没有信号才走普通用户消息召回。
|
|
705
|
+
// 同一轮普通 query 已处理过时跳过重复检索(去重状态仍会兜底)。
|
|
706
|
+
const skipNormalRecall = usableSignal === undefined && step > 1 && sessionId !== undefined
|
|
707
|
+
&& userQuery !== '' && injectionState.lastQueryOf(sessionId) === userQuery
|
|
708
|
+
if (!settings.recall.enabled) {
|
|
709
|
+
if (step === 1) {
|
|
710
|
+
stage(auditBase('recall', {
|
|
711
|
+
kind: 'evaluation', stage: 'skipped', outcome: 'skipped', reasonCode: 'disabled',
|
|
712
|
+
...(userQueryField !== undefined ? { query: userQueryField } : {}),
|
|
713
|
+
}))
|
|
714
|
+
}
|
|
715
|
+
} else if (usableSignal === undefined && userQuery === '') {
|
|
716
|
+
stage(auditBase('recall', {
|
|
717
|
+
kind: 'evaluation', stage: 'skipped', outcome: 'skipped', reasonCode: 'no_query',
|
|
718
|
+
}))
|
|
719
|
+
} else if (skipNormalRecall) {
|
|
720
|
+
stage(auditBase('recall', {
|
|
721
|
+
kind: 'evaluation', stage: 'skipped', outcome: 'skipped', reasonCode: 'same_query_dedup',
|
|
722
|
+
...(userQueryField !== undefined ? { query: userQueryField } : {}),
|
|
723
|
+
}))
|
|
724
|
+
} else {
|
|
725
|
+
const recallScopes = usableSignal === undefined ? scopes : autoScopes
|
|
726
|
+
const recallExclude = usableSignal === undefined ? exclude : excludeAuto
|
|
727
|
+
const recall = await injector.maybeInjectDetailed(
|
|
728
|
+
{ messages: input.messages , signal: input.signal, ...(recallScopes !== undefined ? { scopes: recallScopes } : {}), ...(sessionId !== undefined ? { sessionId } : {}) },
|
|
729
|
+
{ messages: decision.messages },
|
|
730
|
+
{
|
|
731
|
+
...(sessionId !== undefined ? { sessionId } : {}),
|
|
732
|
+
...(usableSignal !== undefined ? { query: usableSignal.query, trigger: usableSignal.reason, force: true } : { trigger: 'turn_start' }),
|
|
733
|
+
...(usableSignal?.tag ? { tag: usableSignal.tag, requireTag: true } : {}),
|
|
734
|
+
excludeIds: recallExclude,
|
|
735
|
+
},
|
|
736
|
+
)
|
|
737
|
+
if (recall?.text) {
|
|
738
|
+
parts.push(recall.text)
|
|
739
|
+
messageChannels.add('recall')
|
|
740
|
+
}
|
|
741
|
+
if (recall !== undefined) {
|
|
742
|
+
const queryField = sanitizeAuditText(recall.query)
|
|
743
|
+
const omitted = recall.omitted.map((entry) => ({ id: entry.id, reason: entry.reason }))
|
|
744
|
+
const failed = !recall.retrieval.ok
|
|
745
|
+
const outcome = failed ? 'failed' : recall.text !== undefined ? 'success' : omitted.length > 0 ? 'partial' : 'skipped'
|
|
746
|
+
const reasonCode = failed ? 'retrieval_failed'
|
|
747
|
+
: recall.text !== undefined ? 'injected'
|
|
748
|
+
: omitted.length > 0 ? 'all_omitted'
|
|
749
|
+
: recall.dedupSkipped > 0 ? 'deduped'
|
|
750
|
+
: 'no_candidates'
|
|
751
|
+
stage(auditBase('recall', {
|
|
752
|
+
kind: 'evaluation', stage: 'searched', outcome, reasonCode,
|
|
753
|
+
trigger: usableSignal?.reason ?? 'turn_start',
|
|
754
|
+
...(usableSignal !== undefined ? { phase: usableSignal.phase } : {}),
|
|
755
|
+
...(queryField !== undefined ? { query: queryField } : {}),
|
|
756
|
+
candidates: recall.candidates,
|
|
757
|
+
filter: {
|
|
758
|
+
rawHits: recall.rawHits ?? recall.retrieval.count,
|
|
759
|
+
tagFiltered: recall.tagFiltered ?? 0,
|
|
760
|
+
supersededExcluded: recall.supersededExcluded ?? 0,
|
|
524
761
|
candidates: recall.candidates,
|
|
762
|
+
},
|
|
763
|
+
selected: {
|
|
525
764
|
contentIds: recall.ids,
|
|
526
765
|
hintIds: [],
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
766
|
+
newlyAddedIds: recall.newlyAddedIds ?? [],
|
|
767
|
+
count: recall.ids.length,
|
|
768
|
+
},
|
|
769
|
+
omitted,
|
|
770
|
+
dedup: {
|
|
771
|
+
skipped: recall.dedupSkipped,
|
|
772
|
+
updated: recall.updated.length,
|
|
773
|
+
lastTextSame: recall.lastTextSame === true,
|
|
774
|
+
...(recall.dedupIds !== undefined ? { ids: recall.dedupIds } : {}),
|
|
775
|
+
},
|
|
776
|
+
budgets: { recall: auditBudget(settings.recall.tokenBudget, recall.tokens) },
|
|
777
|
+
retrieval: {
|
|
778
|
+
ok: recall.retrieval.ok,
|
|
779
|
+
count: recall.retrieval.count,
|
|
780
|
+
...(recall.retrieval.errorCode !== undefined ? { errorCode: recall.retrieval.errorCode } : {}),
|
|
781
|
+
},
|
|
782
|
+
...(recallScopes !== undefined ? { scopes: [...recallScopes] } : {}),
|
|
783
|
+
limits: { topK: settings.recall.topK, maxQueryChars: settings.autoRecall.maxQueryChars },
|
|
784
|
+
...(usableSignal !== undefined
|
|
785
|
+
? { signal: { key: usableSignal.key, reason: usableSignal.reason, ...(usableSignal.errorClass ? { errorClass: usableSignal.errorClass } : {}), ...(usableSignal.tool ? { tool: usableSignal.tool } : {}), ...(usableSignal.tag ? { tag: usableSignal.tag } : {}), ...(usableSignal.source ? { source: usableSignal.source } : {}) } }
|
|
786
|
+
: {}),
|
|
787
|
+
}))
|
|
536
788
|
}
|
|
537
789
|
}
|
|
538
790
|
|
|
539
791
|
const text = parts.join('\n\n')
|
|
540
|
-
|
|
792
|
+
const channels = [...messageChannels]
|
|
793
|
+
const writeDelivery = (status , appended , suppressedBy ) => {
|
|
794
|
+
for (const entry of staged) audit.record(entry)
|
|
795
|
+
if (staged.length === 0 && text === '') return
|
|
796
|
+
const outcome = status === 'appended' ? 'success'
|
|
797
|
+
: status === 'rejected' ? 'failed'
|
|
798
|
+
: status === 'unknown' ? 'unknown' : 'skipped'
|
|
799
|
+
recordAudit({
|
|
800
|
+
...(sessionId !== undefined ? { sessionId } : {}),
|
|
801
|
+
step,
|
|
802
|
+
kind: 'delivery',
|
|
803
|
+
channel: 'lifecycle',
|
|
804
|
+
stage: status === 'unknown' ? 'delivery_prepared' : 'delivery',
|
|
805
|
+
outcome,
|
|
806
|
+
reasonCode: status === 'appended' ? 'appended'
|
|
807
|
+
: status === 'suppressed' ? 'duplicate_message'
|
|
808
|
+
: status === 'rejected' ? 'malformed_message'
|
|
809
|
+
: status === 'unknown' ? 'prepared' : 'empty',
|
|
810
|
+
...(channels.length > 0 ? { channels } : {}),
|
|
811
|
+
delivery: {
|
|
812
|
+
status,
|
|
813
|
+
appended,
|
|
814
|
+
...(suppressedBy !== undefined ? { suppressedBy } : {}),
|
|
815
|
+
...(text !== '' ? { textChars: text.length, textHash: hashAuditText(text) } : {}),
|
|
816
|
+
},
|
|
817
|
+
})
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
if (!text) {
|
|
821
|
+
writeDelivery('not_attempted', false, 'empty')
|
|
822
|
+
return decision
|
|
823
|
+
}
|
|
541
824
|
// 幂等:同一段内容已经在 decision 里(另一个激活实例放进去的),不再追加。
|
|
542
825
|
// 宿主把 entry 应用两次时,两个注入器会各自注入一条逐字相同的消息。
|
|
543
|
-
if (hasRecallMessage(decision.messages , text))
|
|
826
|
+
if (hasRecallMessage(decision.messages , text)) {
|
|
827
|
+
writeDelivery('suppressed', false, 'dedup')
|
|
828
|
+
return decision
|
|
829
|
+
}
|
|
544
830
|
const message = createUserMessage({
|
|
545
831
|
content: [{ type: 'text', text }],
|
|
546
832
|
source: { kind: 'memory', form: 'recall' },
|
|
547
833
|
})
|
|
548
834
|
// Last-resort guard: a malformed message aborts the whole turn downstream
|
|
549
835
|
// (consumers read message.source.kind), so never publish one.
|
|
550
|
-
if (!isWellFormedMessage(message))
|
|
836
|
+
if (!isWellFormedMessage(message)) {
|
|
837
|
+
writeDelivery('rejected', false, 'malformed')
|
|
838
|
+
return decision
|
|
839
|
+
}
|
|
840
|
+
// 宿主没有向 middleware 回执“消息已被接受”:这里只能证明已通过本地保护并
|
|
841
|
+
// 放进 decision,不能证明宿主最终采纳。按方案口径记 unknown,不乐观推断 appended。
|
|
842
|
+
writeDelivery('unknown', null)
|
|
551
843
|
return { ...decision, messages: [...decision.messages, message] }
|
|
552
844
|
}, { prepend: true })
|
|
553
845
|
}
|