dsh-context-compression-improved 0.5.7 → 0.5.8
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 +9 -0
- package/package.json +16 -17
- package/packages/selector/dsh.plugin.json +1 -1
- package/packages/selector/lib/client.d.ts +59 -0
- package/packages/selector/lib/client.js +1012 -17
- package/packages/selector/lib/{advisor-state.js → config.js} +816 -65
- package/packages/selector/lib/index.d.ts +13 -1
- package/packages/selector/lib/index.js +295 -3
- package/packages/selector/lib/pruner.d.ts +65 -0
- package/packages/selector/lib/pruner.js +497 -262
- package/packages/selector/lib/style.css +42 -0
- package/packages/selector/src/client/CompressionProfileControls.tsx +67 -0
- package/packages/selector/src/client/CompressionProfileSelector.module.css +29 -0
- package/packages/selector/src/client/CompressionProfileSelector.tsx +2 -0
- package/packages/selector/src/client/decode.ts +10 -2
- package/packages/selector/src/client/index.ts +62 -0
- package/packages/selector/src/client/locales/de.ts +43 -0
- package/packages/selector/src/client/locales/es.ts +43 -0
- package/packages/selector/src/client/locales/fr.ts +43 -0
- package/packages/selector/src/client/locales/it.ts +43 -0
- package/packages/selector/src/client/locales/ja.ts +43 -0
- package/packages/selector/src/client/locales/ko.ts +43 -0
- package/packages/selector/src/client/locales/ru.ts +43 -0
- package/packages/selector/src/client/locales.ts +86 -0
- package/packages/selector/src/client/monitor-fab.ts +336 -0
- package/packages/selector/src/client/savings-card.tsx +150 -0
- package/packages/selector/src/client/settings-section.tsx +18 -2
- package/packages/selector/src/index.ts +215 -5
- package/packages/selector/src/profiles.ts +37 -0
- package/packages/selector/src/pruner/state.ts +7 -0
- package/packages/selector/src/pruner.ts +337 -3
- package/packages/selector/src/runtime/audit.ts +17 -0
- package/packages/selector/src/runtime/config.ts +52 -2
- package/packages/selector/src/runtime/monitor.ts +235 -0
- package/packages/selector/src/runtime/retrieve.ts +24 -2
- package/packages/selector/src/runtime/savings.ts +337 -0
- package/packages/selector/src/runtime/summary-command.ts +127 -0
- package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +46 -1
- package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +55 -0
- package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
- package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
- package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
- package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
- package/packages/selector/src/runtime/types.ts +19 -0
- package/packages/selector/tests/auto-compact.client.spec.tsx +2 -1
- package/packages/selector/tests/code-skeleton.client.spec.ts +3 -2
- package/packages/selector/tests/custom-contract.client.spec.ts +3 -2
- package/packages/selector/tests/estimator-channel.client.spec.tsx +1 -0
- package/packages/selector/tests/estimator-route-registration.host.spec.ts +10 -4
- package/packages/selector/tests/monitor-fab.client.spec.ts +138 -0
- package/packages/selector/tests/preset-options-write.client.spec.ts +1 -0
- package/packages/selector/tests/profiles.client.spec.tsx +4 -2
- package/packages/selector/tests/runtime/audit.spec.ts +1 -0
- package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
- package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
- package/packages/selector/tests/runtime/monitor.spec.ts +301 -0
- package/packages/selector/tests/runtime/savings.spec.ts +120 -0
- package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
- package/packages/selector/tests/settings-seat.client.spec.ts +19 -7
- package/scripts/packed-install-e2e.mjs +1 -1
- package/scripts/verify-release.mjs +2 -1
|
@@ -22,7 +22,7 @@ import type {
|
|
|
22
22
|
CompactionTokenView,
|
|
23
23
|
ObservedPromptUsage,
|
|
24
24
|
} from './runtime/measurement.ts'
|
|
25
|
-
import { measureForCompaction } from './runtime/measurement.ts'
|
|
25
|
+
import { measureForCompaction, officialRequestUsage } from './runtime/measurement.ts'
|
|
26
26
|
import { eventBySeq, sessionEvents } from './runtime/session-events.ts'
|
|
27
27
|
import { countExactCanonicalTextFields } from './runtime/token-count.ts'
|
|
28
28
|
import type {} from '@deepseek-ai/dsh-tools'
|
|
@@ -82,6 +82,13 @@ import {
|
|
|
82
82
|
runSessionAdvisorPass,
|
|
83
83
|
} from './runtime/tokenpilot/advisor.ts'
|
|
84
84
|
import { getAdvisorState } from './runtime/tokenpilot/advisor-state.ts'
|
|
85
|
+
import { evaluateIntentGate } from './runtime/tokenpilot/intent-gate.ts'
|
|
86
|
+
import { extractErrorLines, maskCandidateForSummary, type IntentRole } from './runtime/tokenpilot/intent-input-mask.ts'
|
|
87
|
+
import { computeIntentRange, INTENT_RANGE_MAX_CANDIDATES } from './runtime/tokenpilot/intent-range.ts'
|
|
88
|
+
import { INTENT_FOLD_MARKER, renderIntentFoldBlock } from './runtime/tokenpilot/intent-fold.ts'
|
|
89
|
+
import { buildIntentSummarySystemPrompt, buildIntentSummaryUserPrompt, parseIntentSummaryAnswer } from './runtime/tokenpilot/advisor-prompt.ts'
|
|
90
|
+
import { getSummaryOverride, observeIntentEnabled, recordIntentFold } from './runtime/tokenpilot/advisor-state.ts'
|
|
91
|
+
import { observeContextUsage } from './runtime/monitor.ts'
|
|
85
92
|
|
|
86
93
|
import {
|
|
87
94
|
DedupeTable,
|
|
@@ -89,6 +96,12 @@ import {
|
|
|
89
96
|
dedupePlaceholder,
|
|
90
97
|
flattenPlainText,
|
|
91
98
|
} from './runtime/tokenpilot/dedup.ts'
|
|
99
|
+
import { getSavingsLedger } from './runtime/savings.ts'
|
|
100
|
+
|
|
101
|
+
/** 节省统计配对键用原文(纯文本块才可配对;富内容返回 undefined)。 */
|
|
102
|
+
function originalTextForSavings(candidate: SnapshotCandidate): string | undefined {
|
|
103
|
+
return flattenPlainText(candidate.event.data.message.content)
|
|
104
|
+
}
|
|
92
105
|
import {
|
|
93
106
|
charsForTokens,
|
|
94
107
|
charsToTokens,
|
|
@@ -238,6 +251,30 @@ export class ToolResultPruner extends Service {
|
|
|
238
251
|
turnClocks: new WeakMap(),
|
|
239
252
|
estimatorRemainingTurns: new WeakMap(),
|
|
240
253
|
advisorChannels: new WeakMap(),
|
|
254
|
+
pendingIntentFolds: new WeakMap(),
|
|
255
|
+
intentFoldedSeqs: new WeakMap(),
|
|
256
|
+
intentBaselines: new WeakMap(),
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// 会话结束汇总(dsh-token-optimizer monitor 模式的同款体验):输出该会话的
|
|
260
|
+
// 净节省/缓存命中率一行账。事件名探测式注册——老代际不发 session/disposed
|
|
261
|
+
// 时监听器静默闲置,不构成任何行为差异。
|
|
262
|
+
try {
|
|
263
|
+
;(ctx as unknown as { on: (name: string, handler: (session: Session) => void) => unknown }).on(
|
|
264
|
+
'session/disposed',
|
|
265
|
+
(session) => {
|
|
266
|
+
try {
|
|
267
|
+
const line = getSavingsLedger().sessionSummaryLine(String(session.id))
|
|
268
|
+
if (line.includes('requests=0') === false || line.includes('net=0(exact)/0(est)') === false) {
|
|
269
|
+
ctx.logger.info('context-compression session savings (%s): %s', String(session.id), line)
|
|
270
|
+
}
|
|
271
|
+
} catch {
|
|
272
|
+
/* 汇总失败不影响 dispose */
|
|
273
|
+
}
|
|
274
|
+
},
|
|
275
|
+
)
|
|
276
|
+
} catch {
|
|
277
|
+
/* 宿主不支持该事件名:静默 */
|
|
241
278
|
}
|
|
242
279
|
|
|
243
280
|
ctx.on('session/event', (session, event) => {
|
|
@@ -300,6 +337,15 @@ export class ToolResultPruner extends Service {
|
|
|
300
337
|
this.auditFailure(agent.session, 'fresh', 'terminal-pass', error)
|
|
301
338
|
ctx.logger.warn('context-compression terminal pass failed open: %o', error)
|
|
302
339
|
}
|
|
340
|
+
// 压缩监控观测:每回合无条件记录上下文占用——面板占用条与
|
|
341
|
+
// 灾难性遗忘区建议的数据源,与 intentSummary 门控解耦(门关也可观测)。
|
|
342
|
+
try {
|
|
343
|
+
observeContextUsage(
|
|
344
|
+
String(agent.session.id),
|
|
345
|
+
measureForCompaction(this.ctx, agent.session).totalTokens,
|
|
346
|
+
this.contextWindowForRequest(agent.session),
|
|
347
|
+
)
|
|
348
|
+
} catch { /* 观测失败静默:面板显示陈旧/空态 */ }
|
|
303
349
|
// TokenPilot-inspired E1: advisory estimator pass, strictly off the
|
|
304
350
|
// synchronous chain. Verdicts only feed the next pressure pass.
|
|
305
351
|
void this.postflightEstimatorPass(agent.session, signal).catch(() => undefined)
|
|
@@ -307,6 +353,9 @@ export class ToolResultPruner extends Service {
|
|
|
307
353
|
// summaries, scores, and decay figure never touch any decision path.
|
|
308
354
|
// Strictly fire-and-forget, with its own backoff state.
|
|
309
355
|
void this.postflightAdvisorPass(agent.session, turn, signal).catch(() => undefined)
|
|
356
|
+
// Turn-tail intent summary: strictly fire-and-forget like the advisor;
|
|
357
|
+
// the growth gate inside decides whether a summary call is even spent.
|
|
358
|
+
void this.postflightIntentFoldPass(agent.session, turn, signal).catch(() => undefined)
|
|
310
359
|
})
|
|
311
360
|
}
|
|
312
361
|
|
|
@@ -348,7 +397,15 @@ export class ToolResultPruner extends Service {
|
|
|
348
397
|
if (policy === undefined) return emptyResult()
|
|
349
398
|
const profile = policy.profile
|
|
350
399
|
const view = measureForCompaction(this.ctx, session)
|
|
351
|
-
if (stage === 'fresh')
|
|
400
|
+
if (stage === 'fresh') {
|
|
401
|
+
// 真实 usage 聚合(monitor 口径):官方 TokenMeter 的上一已完成请求,
|
|
402
|
+
// 每 fresh 边界入账一次;pressure pass 读到同一 baseline,不重复计。
|
|
403
|
+
const usage = officialRequestUsage(view)
|
|
404
|
+
if (usage !== undefined) {
|
|
405
|
+
getSavingsLedger().recordUsage(String(session.id), usage)
|
|
406
|
+
}
|
|
407
|
+
return this.decideFreshStep(session, options, policy, view)
|
|
408
|
+
}
|
|
352
409
|
if (profile === 'off') return emptyResult()
|
|
353
410
|
|
|
354
411
|
const landed: PrunedEntry[] = []
|
|
@@ -718,6 +775,200 @@ export class ToolResultPruner extends Service {
|
|
|
718
775
|
}
|
|
719
776
|
}
|
|
720
777
|
|
|
778
|
+
// ─────────── Turn-tail intent summary (host-driven fold, model writes text only) ───────────
|
|
779
|
+
|
|
780
|
+
/**
|
|
781
|
+
* Fire-and-forget postflight: evaluate the growth gate, and only when it
|
|
782
|
+
* passes, select the consumed increment OUTSIDE the protected working set,
|
|
783
|
+
* mask it to semantic-role records, and spend ONE summary-writer call. The
|
|
784
|
+
* verdict stages as a pending fold that the NEXT pressure round lands via
|
|
785
|
+
* the ordinary plan/apply machinery — the synchronous decision path never
|
|
786
|
+
* waits on an LLM.
|
|
787
|
+
*/
|
|
788
|
+
private async postflightIntentFoldPass(session: Session, turn: number, signal: AbortSignal): Promise<void> {
|
|
789
|
+
const started = Date.now()
|
|
790
|
+
const sessionId = String(session.id)
|
|
791
|
+
const policy = this.activePolicy(session)
|
|
792
|
+
const settings = this.activeSettings(session)
|
|
793
|
+
const intentEnabled = settings.intentSummary.enabled
|
|
794
|
+
const override = getSummaryOverride(sessionId)
|
|
795
|
+
observeIntentEnabled(sessionId, intentEnabled)
|
|
796
|
+
if (policy === undefined) return
|
|
797
|
+
if (this.state.pendingIntentFolds.has(session)) return
|
|
798
|
+
const advisorState = getAdvisorState(session)
|
|
799
|
+
if (advisorState.inFlight) return
|
|
800
|
+
if (isCoolingDown(advisorState.failures, Date.now())) return
|
|
801
|
+
|
|
802
|
+
const view = measureForCompaction(this.ctx, session)
|
|
803
|
+
// The window is the Auto Compact linkage input: policy.autoCompactTokens
|
|
804
|
+
// == floor(window * threshold/100); invert for the gate floor.
|
|
805
|
+
const thresholdPercent = settings.autoCompact.thresholdPercent
|
|
806
|
+
const contextWindow = policy.autoCompactTokens !== undefined && thresholdPercent > 0
|
|
807
|
+
? Math.round(policy.autoCompactTokens / (thresholdPercent / 100))
|
|
808
|
+
: undefined
|
|
809
|
+
const gate = evaluateIntentGate({
|
|
810
|
+
enabled: intentEnabled,
|
|
811
|
+
override,
|
|
812
|
+
liveTokens: view.totalTokens,
|
|
813
|
+
contextWindow,
|
|
814
|
+
baselineTokens: this.state.intentBaselines.get(session) ?? 0,
|
|
815
|
+
})
|
|
816
|
+
if (!gate.decision) return
|
|
817
|
+
|
|
818
|
+
const settingsPreset = settings.presetOptions
|
|
819
|
+
if (settingsPreset === undefined) return
|
|
820
|
+
if (settingsPreset.estimatorBaseUrl === undefined || settingsPreset.estimatorBaseUrl.length === 0
|
|
821
|
+
|| settingsPreset.estimatorModel === undefined || settingsPreset.estimatorModel.length === 0) {
|
|
822
|
+
emitCompressionAudit(this.ctx.logger, {
|
|
823
|
+
schemaVersion: 1,
|
|
824
|
+
kind: 'intent-summary-outcome',
|
|
825
|
+
sessionId,
|
|
826
|
+
ok: false,
|
|
827
|
+
reason: 'no-direct-endpoint',
|
|
828
|
+
turnIndex: turn,
|
|
829
|
+
latencyMs: Date.now() - started,
|
|
830
|
+
})
|
|
831
|
+
return
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
const candidates = this.snapshot(session, view).filter(candidate => !this.isRecoveryExempt(session, candidate))
|
|
835
|
+
const protectedSeqs = this.protectedHistoryCandidateSeqs(candidates, policy)
|
|
836
|
+
const range = computeIntentRange({
|
|
837
|
+
candidates,
|
|
838
|
+
protectedSeqs,
|
|
839
|
+
foldedSeqs: this.state.intentFoldedSeqs.get(session) ?? new Set<number>(),
|
|
840
|
+
maxCandidates: INTENT_RANGE_MAX_CANDIDATES,
|
|
841
|
+
})
|
|
842
|
+
if (range.seqs.length === 0) return
|
|
843
|
+
|
|
844
|
+
const bySeq = new Map(candidates.map(candidate => [candidate.seq, candidate]))
|
|
845
|
+
const records: { seq: number, role: IntentRole, toolName: string, line: string }[] = []
|
|
846
|
+
const errorLines = new Set<string>()
|
|
847
|
+
for (const seq of range.seqs) {
|
|
848
|
+
const candidate = bySeq.get(seq)
|
|
849
|
+
if (candidate === undefined) continue
|
|
850
|
+
const result = candidate.event.data.message as ToolResultMessage
|
|
851
|
+
const text = onlyTextBlock(result.content)?.text ?? ''
|
|
852
|
+
const masked = maskCandidateForSummary(seq, candidate.call.name, candidate.call.arguments, text)
|
|
853
|
+
records.push({ seq, role: masked.role, toolName: candidate.call.name, line: masked.record })
|
|
854
|
+
for (const line of extractErrorLines(text)) errorLines.add(line)
|
|
855
|
+
}
|
|
856
|
+
if (records.length === 0) return
|
|
857
|
+
|
|
858
|
+
const events = sessionEvents(session)
|
|
859
|
+
const task = collectTaskSemantics(events)
|
|
860
|
+
let channel = this.state.advisorChannels.get(session)
|
|
861
|
+
if (channel === undefined) {
|
|
862
|
+
channel = new SideChannel(this.ctx, settingsPreset, {
|
|
863
|
+
mode: 'direct',
|
|
864
|
+
timeoutMs: 30_000,
|
|
865
|
+
maxTokens: 512,
|
|
866
|
+
})
|
|
867
|
+
this.state.advisorChannels.set(session, channel)
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
const answer = await channel.ask({
|
|
871
|
+
system: buildIntentSummarySystemPrompt(),
|
|
872
|
+
user: buildIntentSummaryUserPrompt(task?.taskText ?? '(no task semantics yet)', records.map(record => record.line), collectTailText(events)),
|
|
873
|
+
signal,
|
|
874
|
+
})
|
|
875
|
+
const summaryCallChars = answer?.length ?? 0
|
|
876
|
+
const parsed = answer === undefined ? undefined : parseIntentSummaryAnswer(answer)
|
|
877
|
+
if (parsed === undefined) {
|
|
878
|
+
const failures = (advisorState.failures?.failures ?? 0) + 1
|
|
879
|
+
advisorState.failures = { failures, cooldownUntil: Date.now() + backoffCooldownMs(failures) }
|
|
880
|
+
emitCompressionAudit(this.ctx.logger, {
|
|
881
|
+
schemaVersion: 1,
|
|
882
|
+
kind: 'intent-summary-outcome',
|
|
883
|
+
sessionId,
|
|
884
|
+
ok: false,
|
|
885
|
+
reason: answer === undefined ? 'ask-failed' : 'parse-failed',
|
|
886
|
+
turnIndex: turn,
|
|
887
|
+
foldedCount: records.length,
|
|
888
|
+
summaryCallChars,
|
|
889
|
+
latencyMs: Date.now() - started,
|
|
890
|
+
})
|
|
891
|
+
return
|
|
892
|
+
}
|
|
893
|
+
this.state.pendingIntentFolds.set(session, {
|
|
894
|
+
createdAt: Date.now(),
|
|
895
|
+
turn,
|
|
896
|
+
startSeq: range.seqs[0]!,
|
|
897
|
+
endSeq: range.seqs[range.seqs.length - 1]!,
|
|
898
|
+
summary: parsed.summary,
|
|
899
|
+
errorLines: [...errorLines],
|
|
900
|
+
records,
|
|
901
|
+
summaryCallChars,
|
|
902
|
+
})
|
|
903
|
+
emitCompressionAudit(this.ctx.logger, {
|
|
904
|
+
schemaVersion: 1,
|
|
905
|
+
kind: 'intent-summary-outcome',
|
|
906
|
+
sessionId,
|
|
907
|
+
ok: true,
|
|
908
|
+
reason: 'staged',
|
|
909
|
+
turnIndex: turn,
|
|
910
|
+
foldedCount: records.length,
|
|
911
|
+
summaryCallChars,
|
|
912
|
+
latencyMs: Date.now() - started,
|
|
913
|
+
})
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
/**
|
|
917
|
+
* Convert a staged pending fold into per-candidate planned replacements
|
|
918
|
+
* (reducer `intent-summary`). Fail-open: a candidate that would grow, is
|
|
919
|
+
* rich-content, or no longer exists keeps its original text. Returns
|
|
920
|
+
* `undefined` when there is nothing (or no longer anything) to fold.
|
|
921
|
+
*/
|
|
922
|
+
private applyPendingIntentFold(
|
|
923
|
+
session: Session,
|
|
924
|
+
policy: CompressionPolicy,
|
|
925
|
+
view: CompactionTokenView,
|
|
926
|
+
eligible: readonly SnapshotCandidate[],
|
|
927
|
+
): { plans: PlannedReplacement[], reclaim: number, foldedSeqs: Set<number>, charsBefore: number, charsAfter: number, turn: number, summaryCallChars: number } | undefined {
|
|
928
|
+
const pending = this.state.pendingIntentFolds.get(session)
|
|
929
|
+
if (pending === undefined) return undefined
|
|
930
|
+
const bySeq = new Map(eligible.map(candidate => [candidate.seq, candidate]))
|
|
931
|
+
const foldable = pending.records
|
|
932
|
+
.map(record => record.seq)
|
|
933
|
+
.filter(seq => bySeq.has(seq))
|
|
934
|
+
.sort((a, b) => a - b)
|
|
935
|
+
if (foldable.length === 0) {
|
|
936
|
+
this.state.pendingIntentFolds.delete(session)
|
|
937
|
+
return undefined
|
|
938
|
+
}
|
|
939
|
+
const plans: PlannedReplacement[] = []
|
|
940
|
+
const foldedSeqs = new Set<number>()
|
|
941
|
+
let reclaim = 0
|
|
942
|
+
let charsBefore = 0
|
|
943
|
+
let charsAfter = 0
|
|
944
|
+
for (const seq of foldable) {
|
|
945
|
+
const candidate = bySeq.get(seq)!
|
|
946
|
+
const result = candidate.event.data.message as ToolResultMessage
|
|
947
|
+
const block = onlyTextBlock(result.content)
|
|
948
|
+
if (block === null) continue
|
|
949
|
+
const text = renderIntentFoldBlock(pending, seq)
|
|
950
|
+
const plan = this.plan(
|
|
951
|
+
candidate,
|
|
952
|
+
[{ ...block, text }],
|
|
953
|
+
rootToolResultSeq(session, candidate.seq),
|
|
954
|
+
'intent-summary',
|
|
955
|
+
'pressure',
|
|
956
|
+
'history',
|
|
957
|
+
policy.historyMode,
|
|
958
|
+
view,
|
|
959
|
+
)
|
|
960
|
+
if (plan === null || plan.charsAfter >= plan.charsBefore) continue
|
|
961
|
+
plans.push(plan)
|
|
962
|
+
foldedSeqs.add(seq)
|
|
963
|
+
reclaim += plan.charsBefore - plan.charsAfter
|
|
964
|
+
charsBefore += plan.charsBefore
|
|
965
|
+
charsAfter += plan.charsAfter
|
|
966
|
+
}
|
|
967
|
+
if (plans.length === 0) return undefined
|
|
968
|
+
this.state.intentFoldedSeqs.get(session)?.forEach(seq => foldedSeqs.add(seq))
|
|
969
|
+
return { plans, reclaim, foldedSeqs, charsBefore, charsAfter, turn: pending.turn, summaryCallChars: pending.summaryCallChars }
|
|
970
|
+
}
|
|
971
|
+
|
|
721
972
|
// ─────────── Advisory benefit model (statistics & suggestions only) ───────────
|
|
722
973
|
|
|
723
974
|
/**
|
|
@@ -1200,6 +1451,24 @@ export class ToolResultPruner extends Service {
|
|
|
1200
1451
|
policy.aggregateEnabled ? 'no-new-tool-result-candidates' : 'profile-policy')
|
|
1201
1452
|
return emptyResult()
|
|
1202
1453
|
}
|
|
1454
|
+
// 节省统计(负节省配对):新全文工具结果按 (session,seq) 一次性过账——
|
|
1455
|
+
// 命中"此前压缩过的原文哈希"即记抵消。挂在压力门控之前:全文重读无论
|
|
1456
|
+
// 本轮是否再次压缩,都使原声称的节省不再成立(先骨架后全文 = 负节省)。
|
|
1457
|
+
const ledger = getSavingsLedger()
|
|
1458
|
+
const sid = String(session.id)
|
|
1459
|
+
for (const candidate of candidates) {
|
|
1460
|
+
const text = flattenPlainText(candidate.event.data.message.content)
|
|
1461
|
+
if (text === undefined) continue
|
|
1462
|
+
ledger.noteFullText({
|
|
1463
|
+
sessionId: sid,
|
|
1464
|
+
seq: candidate.seq,
|
|
1465
|
+
text,
|
|
1466
|
+
measure: () =>
|
|
1467
|
+
candidate.count.kind === 'exact-tokenizer' && typeof candidate.count.tokens === 'number'
|
|
1468
|
+
? { tokens: candidate.count.tokens, basis: 'exact-tokenizer' }
|
|
1469
|
+
: { tokens: Math.ceil(candidate.characterPressure / 4), basis: 'characters' },
|
|
1470
|
+
})
|
|
1471
|
+
}
|
|
1203
1472
|
|
|
1204
1473
|
const plans = new Map<number, PlannedReplacement>()
|
|
1205
1474
|
let freshPlanned = 0
|
|
@@ -1612,13 +1881,15 @@ export class ToolResultPruner extends Service {
|
|
|
1612
1881
|
if (this.isRecoveryExempt(session, candidate)) return true
|
|
1613
1882
|
const result = candidate.event.data.message.content[0]
|
|
1614
1883
|
const block = onlyTextBlock(result.content)
|
|
1884
|
+
// Fold-once: an already-folded intent block is never re-candidated.
|
|
1885
|
+
if (block?.text.includes(INTENT_FOLD_MARKER) === true) return true
|
|
1615
1886
|
return block?.text.includes('[Old tool result content cleared from active context]') === true
|
|
1616
1887
|
}
|
|
1617
1888
|
// Distinguish "nothing safe to touch" (recovery tool output or already
|
|
1618
1889
|
// cleared) from "everything left is inside the protected working set":
|
|
1619
1890
|
// both skip, but they are different operational facts.
|
|
1620
1891
|
const safe = candidates.filter(candidate => !isUnsafe(candidate))
|
|
1621
|
-
const eligible = safe.filter(candidate => !protectedSeqs.has(candidate.seq))
|
|
1892
|
+
const eligible: SnapshotCandidate[] = safe.filter(candidate => !protectedSeqs.has(candidate.seq))
|
|
1622
1893
|
if (eligible.length === 0) {
|
|
1623
1894
|
return safe.length === 0
|
|
1624
1895
|
? { kind: 'no-safe-candidates' }
|
|
@@ -1626,6 +1897,38 @@ export class ToolResultPruner extends Service {
|
|
|
1626
1897
|
}
|
|
1627
1898
|
const planned: PlannedReplacement[] = []
|
|
1628
1899
|
let reclaim = 0
|
|
1900
|
+
// Turn-tail intent summary (task_2.5): a fold staged by a previous turn's
|
|
1901
|
+
// postflight lands FIRST, through the same plan pipeline as every other
|
|
1902
|
+
// reducer; its reclaim counts toward the batch target and its seqs are
|
|
1903
|
+
// removed from the ordinary loop (fold-once).
|
|
1904
|
+
const intentApplied = this.applyPendingIntentFold(session, policy, view, eligible)
|
|
1905
|
+
if (intentApplied !== undefined) {
|
|
1906
|
+
planned.push(...intentApplied.plans)
|
|
1907
|
+
reclaim += intentApplied.reclaim
|
|
1908
|
+
this.state.intentFoldedSeqs.set(session, intentApplied.foldedSeqs)
|
|
1909
|
+
this.state.pendingIntentFolds.delete(session)
|
|
1910
|
+
this.state.intentBaselines.set(session, view.totalTokens)
|
|
1911
|
+
recordIntentFold(String(session.id), {
|
|
1912
|
+
turn: intentApplied.turn,
|
|
1913
|
+
startSeq: intentApplied.foldedSeqs.size > 0 ? Math.min(...intentApplied.foldedSeqs) : 0,
|
|
1914
|
+
endSeq: intentApplied.foldedSeqs.size > 0 ? Math.max(...intentApplied.foldedSeqs) : 0,
|
|
1915
|
+
liveTokensBefore: view.totalTokens,
|
|
1916
|
+
at: Date.now(),
|
|
1917
|
+
})
|
|
1918
|
+
emitCompressionAudit(this.ctx.logger, {
|
|
1919
|
+
schemaVersion: 1,
|
|
1920
|
+
kind: 'intent-summary-outcome',
|
|
1921
|
+
sessionId: String(session.id),
|
|
1922
|
+
ok: true,
|
|
1923
|
+
reason: 'landed',
|
|
1924
|
+
foldedCount: intentApplied.plans.length,
|
|
1925
|
+
...(intentApplied.charsBefore > 0 ? { retentionRatio: intentApplied.charsAfter / intentApplied.charsBefore } : {}),
|
|
1926
|
+
summaryCallChars: intentApplied.summaryCallChars,
|
|
1927
|
+
})
|
|
1928
|
+
for (let index = eligible.length - 1; index >= 0; index -= 1) {
|
|
1929
|
+
if (intentApplied.foldedSeqs.has(eligible[index]!.seq)) eligible.splice(index, 1)
|
|
1930
|
+
}
|
|
1931
|
+
}
|
|
1629
1932
|
// Linked batches must reach the deadline target; unlinked batches keep
|
|
1630
1933
|
// the traditional minimum-reclaim commit threshold. All arithmetic runs on
|
|
1631
1934
|
// the character basis: token-named thresholds enter via charsForTokens.
|
|
@@ -1968,6 +2271,25 @@ export class ToolResultPruner extends Service {
|
|
|
1968
2271
|
? exactSurface.tokenizerRevision
|
|
1969
2272
|
: 'chars-per-token-4.0',
|
|
1970
2273
|
})
|
|
2274
|
+
// 节省统计:tail-trim 组的原文配对键(纯文本结果才登记,富内容跳过——
|
|
2275
|
+
// 与 land() 同口径:只记已落盘、可配对者)。
|
|
2276
|
+
const groupText = shadowedSeqs
|
|
2277
|
+
.map(seq => sessionEvents(session)[seq])
|
|
2278
|
+
.filter((event): event is SessionEvent<'tool/result'> => event?.type === 'tool/result')
|
|
2279
|
+
.map(event => flattenPlainText(event.data.message.content))
|
|
2280
|
+
.filter((text): text is string => text !== undefined)
|
|
2281
|
+
.join('\n')
|
|
2282
|
+
if (groupText.length > 0) {
|
|
2283
|
+
getSavingsLedger().recordSaving({
|
|
2284
|
+
sessionId: String(session.id),
|
|
2285
|
+
component: 'tail-trim',
|
|
2286
|
+
tokensBefore,
|
|
2287
|
+
tokensAfter,
|
|
2288
|
+
basis: exact ? 'exact-tokenizer' : 'characters',
|
|
2289
|
+
sourceSeq: manifestSeq,
|
|
2290
|
+
originalText: groupText,
|
|
2291
|
+
})
|
|
2292
|
+
}
|
|
1971
2293
|
return
|
|
1972
2294
|
}
|
|
1973
2295
|
this.auditComponent(session, policy, 'tail-trim', 'pressure', 'skipped',
|
|
@@ -2121,6 +2443,18 @@ export class ToolResultPruner extends Service {
|
|
|
2121
2443
|
// record ONLY — the replacement content is untouched by this field.
|
|
2122
2444
|
...plan.elidedLines === undefined ? {} : { elidedLines: plan.elidedLines },
|
|
2123
2445
|
})
|
|
2446
|
+
// 节省统计:已实现的削减才入账(tokensBefore−tokensAfter,审计同源同口径);
|
|
2447
|
+
// 原文哈希登记,供后续全文重读/retrieve 抵消配对。
|
|
2448
|
+
const pairedOriginal = originalTextForSavings(candidate)
|
|
2449
|
+
getSavingsLedger().recordSaving({
|
|
2450
|
+
sessionId: String(session.id),
|
|
2451
|
+
component: plan.component,
|
|
2452
|
+
tokensBefore: plan.tokensBefore,
|
|
2453
|
+
tokensAfter: plan.tokensAfter,
|
|
2454
|
+
basis: plan.measurementBasis,
|
|
2455
|
+
sourceSeq: plan.sourceSeq,
|
|
2456
|
+
...(pairedOriginal === undefined ? {} : { originalText: pairedOriginal }),
|
|
2457
|
+
})
|
|
2124
2458
|
return {
|
|
2125
2459
|
originalSeq: candidate.seq,
|
|
2126
2460
|
sourceSeq: plan.sourceSeq,
|
|
@@ -205,6 +205,22 @@ export interface AdvisorOutcomeAuditRecord extends CompressionAuditBase {
|
|
|
205
205
|
readonly latencyMs: number
|
|
206
206
|
}
|
|
207
207
|
|
|
208
|
+
/** One turn-tail intent-summary pass: gate decision, ask outcome, or landing. Numeric metadata only. */
|
|
209
|
+
export interface IntentSummaryOutcomeAuditRecord extends CompressionAuditBase {
|
|
210
|
+
readonly kind: 'intent-summary-outcome'
|
|
211
|
+
readonly ok: boolean
|
|
212
|
+
/** Aligned decision/reason code (gate reason, 'parse-failed', 'landed', 'expired'...). */
|
|
213
|
+
readonly reason: string
|
|
214
|
+
readonly turnIndex?: number
|
|
215
|
+
/** Folded candidate count when a range was selected or landed. */
|
|
216
|
+
readonly foldedCount?: number
|
|
217
|
+
/** Aggregate retention ratio of the landed batch (charsAfter / charsBefore). */
|
|
218
|
+
readonly retentionRatio?: number
|
|
219
|
+
/** Characters spent on the summary-writer call itself (credit accounting). */
|
|
220
|
+
readonly summaryCallChars?: number
|
|
221
|
+
readonly latencyMs?: number
|
|
222
|
+
}
|
|
223
|
+
|
|
208
224
|
/**
|
|
209
225
|
* One advisory benefit-model label for a batch that LANDED. The retired review
|
|
210
226
|
* gate used these bands to withhold a batch; a reduction must never block
|
|
@@ -247,6 +263,7 @@ export type CompressionAuditRecord =
|
|
|
247
263
|
| SummaryLocatorAuditRecord
|
|
248
264
|
| EstimatorOutcomeAuditRecord
|
|
249
265
|
| AdvisorOutcomeAuditRecord
|
|
266
|
+
| IntentSummaryOutcomeAuditRecord
|
|
250
267
|
| ReductionAdviceAuditRecord
|
|
251
268
|
|
|
252
269
|
/** Minimal logger method consumed by the audit publisher. */
|
|
@@ -5,6 +5,8 @@ import type {
|
|
|
5
5
|
AutoCompactSettings,
|
|
6
6
|
CodeSkeletonSettings,
|
|
7
7
|
CompressionPolicy,
|
|
8
|
+
IntentSummarySettings,
|
|
9
|
+
MonitorPanelSettings,
|
|
8
10
|
CompressionProfile,
|
|
9
11
|
CustomCompressionPolicy,
|
|
10
12
|
PresetOptions,
|
|
@@ -114,6 +116,48 @@ function parseCodeSkeletonSettings(value: unknown): CodeSkeletonSettings {
|
|
|
114
116
|
return { enabled }
|
|
115
117
|
}
|
|
116
118
|
|
|
119
|
+
/**
|
|
120
|
+
* Strictly parse the persisted intentSummary section. Mirrors the codeSkeleton
|
|
121
|
+
* section semantics: absent inherits the lossless `false` default, while a
|
|
122
|
+
* present-but-invalid section is an explicitly invalid document.
|
|
123
|
+
*/
|
|
124
|
+
function parseIntentSummarySettings(value: unknown): IntentSummarySettings {
|
|
125
|
+
if (value === undefined) return { enabled: false }
|
|
126
|
+
if (!isPlainRecord(value)) {
|
|
127
|
+
throw new TypeError('Context-compression intentSummary must be a plain object')
|
|
128
|
+
}
|
|
129
|
+
const keys = Object.keys(value)
|
|
130
|
+
if (keys.length !== 1 || keys[0] !== 'enabled') {
|
|
131
|
+
throw new TypeError(`Context-compression intentSummary: expected exactly "enabled", got "${keys.join('", "')}"`)
|
|
132
|
+
}
|
|
133
|
+
const enabled = (value as Record<string, unknown>).enabled
|
|
134
|
+
if (typeof enabled !== 'boolean') {
|
|
135
|
+
throw new TypeError('Context-compression intentSummary.enabled must be a boolean')
|
|
136
|
+
}
|
|
137
|
+
return { enabled }
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Strictly parse the persisted monitorPanel section. Mirrors the intentSummary
|
|
142
|
+
* section semantics: absent inherits the hidden default, while a
|
|
143
|
+
* present-but-invalid section is an explicitly invalid document.
|
|
144
|
+
*/
|
|
145
|
+
function parseMonitorPanelSettings(value: unknown): MonitorPanelSettings {
|
|
146
|
+
if (value === undefined) return { enabled: false }
|
|
147
|
+
if (!isPlainRecord(value)) {
|
|
148
|
+
throw new TypeError('Context-compression monitorPanel must be a plain object')
|
|
149
|
+
}
|
|
150
|
+
const keys = Object.keys(value)
|
|
151
|
+
if (keys.length !== 1 || keys[0] !== 'enabled') {
|
|
152
|
+
throw new TypeError(`Context-compression monitorPanel: expected exactly "enabled", got "${keys.join('", "')}"`)
|
|
153
|
+
}
|
|
154
|
+
const enabled = (value as Record<string, unknown>).enabled
|
|
155
|
+
if (typeof enabled !== 'boolean') {
|
|
156
|
+
throw new TypeError('Context-compression monitorPanel.enabled must be a boolean')
|
|
157
|
+
}
|
|
158
|
+
return { enabled }
|
|
159
|
+
}
|
|
160
|
+
|
|
117
161
|
/**
|
|
118
162
|
* Parse the optional tokenpilot-inspired preset sub-capability section. Absent
|
|
119
163
|
* inherits the preset defaults; present-but-invalid is rejected, mirroring the
|
|
@@ -248,11 +292,13 @@ const isSupportedProfile = (value: unknown): boolean =>
|
|
|
248
292
|
const isUsableCustomDocument = (value: unknown): boolean =>
|
|
249
293
|
isPlainRecord(value)
|
|
250
294
|
|
|
251
|
-
const DEFAULT_CONTEXT_COMPRESSION_SETTINGS: ContextCompressionSettings = {
|
|
295
|
+
export const DEFAULT_CONTEXT_COMPRESSION_SETTINGS: ContextCompressionSettings = {
|
|
252
296
|
profile: 'balanced',
|
|
253
297
|
custom: structuredClone(DEFAULT_CUSTOM_COMPRESSION_POLICY),
|
|
254
298
|
autoCompact: { thresholdPercent: AUTO_COMPACT_THRESHOLD_LIMITS.default },
|
|
255
299
|
codeSkeleton: { enabled: false },
|
|
300
|
+
intentSummary: { enabled: false },
|
|
301
|
+
monitorPanel: { enabled: false },
|
|
256
302
|
}
|
|
257
303
|
|
|
258
304
|
/**
|
|
@@ -290,7 +336,7 @@ export const ContextCompressionSettingsSchema: z<ContextCompressionSettings> = z
|
|
|
290
336
|
// remain valid and inherit their defaults; the sections themselves stay
|
|
291
337
|
// strictly shaped.
|
|
292
338
|
const unknown = Object.keys(candidate).find(key =>
|
|
293
|
-
key !== 'profile' && key !== 'custom' && key !== 'autoCompact' && key !== 'codeSkeleton' && key !== 'presetOptions')
|
|
339
|
+
key !== 'profile' && key !== 'custom' && key !== 'autoCompact' && key !== 'codeSkeleton' && key !== 'intentSummary' && key !== 'monitorPanel' && key !== 'presetOptions')
|
|
294
340
|
if (unknown !== undefined) {
|
|
295
341
|
throw new TypeError(`Context-compression settings: unknown key "${unknown}"`)
|
|
296
342
|
}
|
|
@@ -302,11 +348,15 @@ export const ContextCompressionSettingsSchema: z<ContextCompressionSettings> = z
|
|
|
302
348
|
assertPresentSection(candidate, 'custom', isUsableCustomDocument)
|
|
303
349
|
const autoCompact = parseAutoCompactSettings(candidate.autoCompact)
|
|
304
350
|
const codeSkeleton = parseCodeSkeletonSettings(candidate.codeSkeleton)
|
|
351
|
+
const intentSummary = parseIntentSummarySettings(candidate.intentSummary)
|
|
352
|
+
const monitorPanel = parseMonitorPanelSettings(candidate.monitorPanel)
|
|
305
353
|
const presetOptions = parsePresetOptionsSettings(candidate.presetOptions)
|
|
306
354
|
return {
|
|
307
355
|
...contextCompressionSettingsInputSchema(candidate),
|
|
308
356
|
autoCompact,
|
|
309
357
|
codeSkeleton,
|
|
358
|
+
intentSummary,
|
|
359
|
+
monitorPanel,
|
|
310
360
|
...presetOptions === undefined ? {} : { presetOptions },
|
|
311
361
|
}
|
|
312
362
|
},
|