dsh-context-compression-improved 0.9.3 → 0.9.5
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/package.json +1 -1
- package/packages/selector/dsh.plugin.json +1 -1
- package/packages/selector/lib/client.d.ts +1 -0
- package/packages/selector/lib/client.js +63 -10
- package/packages/selector/lib/config.js +71 -7
- package/packages/selector/lib/index.js +120 -20
- package/packages/selector/lib/pruner.d.ts +158 -107
- package/packages/selector/lib/pruner.js +331 -20
- package/packages/selector/package.json +1 -1
- package/packages/selector/src/client/index.ts +29 -2
- package/packages/selector/src/client/locales/de.ts +1 -0
- package/packages/selector/src/client/locales/es.ts +1 -0
- package/packages/selector/src/client/locales/fr.ts +1 -0
- package/packages/selector/src/client/locales/it.ts +1 -0
- package/packages/selector/src/client/locales/ja.ts +1 -0
- package/packages/selector/src/client/locales/ko.ts +1 -0
- package/packages/selector/src/client/locales/ru.ts +1 -0
- package/packages/selector/src/client/locales.ts +2 -0
- package/packages/selector/src/client/monitor-fab.ts +19 -4
- package/packages/selector/src/preset-overlay.ts +145 -22
- package/packages/selector/src/pruner/content.ts +1 -1
- package/packages/selector/src/pruner/state.ts +4 -0
- package/packages/selector/src/pruner.ts +104 -15
- package/packages/selector/src/runtime/config.ts +1 -1
- package/packages/selector/src/runtime/reducers.ts +81 -1
- package/packages/selector/src/runtime/retrieve.ts +4 -3
- package/packages/selector/src/runtime/savings-projection.ts +226 -0
- package/packages/selector/src/runtime/savings.ts +83 -3
- package/packages/selector/tests/runtime/fresh-gate.spec.ts +43 -0
- package/packages/selector/tests/runtime/jsonl-reducer.spec.ts +79 -0
- package/packages/selector/tests/runtime/public/public-runtime.spec.ts +48 -0
- package/packages/selector/tests/runtime/savings-projection.spec.ts +89 -0
- package/packages/selector/tests/runtime/savings.spec.ts +22 -3
- package/packages/selector/tests/runtime/settings-unwrap.spec.ts +58 -0
- package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +5 -2
|
@@ -155,6 +155,11 @@ const ADJACENT_REPEAT_MARKER = '[previous line repeated'
|
|
|
155
155
|
const NON_ADJACENT_FOLD_THRESHOLD = 3
|
|
156
156
|
/** Read-output line-number gutter added unconditionally by the host's `formatReadOutput`. */
|
|
157
157
|
const READ_GUTTER_PATTERN = /^(\d+): ?/
|
|
158
|
+
/** JSONL/NDJSON preview: records kept from the head and tail of the stream. */
|
|
159
|
+
const JSONL_HEAD_RECORDS = 3
|
|
160
|
+
const JSONL_TAIL_RECORDS = 2
|
|
161
|
+
/** JSONL detection validates a bounded prefix so a multi-MB stream stays cheap. */
|
|
162
|
+
const JSONL_DETECT_SCAN = 512
|
|
158
163
|
|
|
159
164
|
/**
|
|
160
165
|
* Block-level read-gutter detection (GF-1). The host prefixes read output with
|
|
@@ -220,7 +225,12 @@ export function reduceFreshToolResult(input: ReducerInput, ranking?: ReductionRa
|
|
|
220
225
|
const readTocFirst = toolClass === 'read' && codePointLength(normalized.contentText) >= READ_TOC_MIN_CHARS
|
|
221
226
|
const candidates: Array<() => ReducerOutput | null> = []
|
|
222
227
|
|
|
223
|
-
|
|
228
|
+
// JSONL first: a line-delimited stream also passes `looksLikeJson` (its first
|
|
229
|
+
// and last chars are braces) yet `JSON.parse` of the whole blob fails, so the
|
|
230
|
+
// single-value branch would bail and silently drop it to head/tail. Detect the
|
|
231
|
+
// line form explicitly and give it a record-sampling preview.
|
|
232
|
+
if (looksLikeJsonl(normalized.contentText)) candidates.push(() => reduceJsonl(prepared))
|
|
233
|
+
else if (looksLikeJson(normalized.contentText)) candidates.push(() => reduceJson(prepared))
|
|
224
234
|
// R10-B (bundled/minified JS): must sit before every line-anchored candidate
|
|
225
235
|
// — a bundle's statement structure lives INSIDE lines, not at line starts.
|
|
226
236
|
if (looksLikeMinified(normalized.contentText)) candidates.push(() => reduceBundledJs(prepared))
|
|
@@ -647,6 +657,76 @@ function reduceJson(input: PreparedInput): ReducerOutput | null {
|
|
|
647
657
|
return null
|
|
648
658
|
}
|
|
649
659
|
|
|
660
|
+
/**
|
|
661
|
+
* Reduce line-delimited JSON (JSONL/NDJSON): keep a head and tail sample of
|
|
662
|
+
* records — each run through the same `shrinkJson` as the single-value branch —
|
|
663
|
+
* and collapse the middle into an omitted-record count. Reads the gutter-
|
|
664
|
+
* stripped content view so a host read listing (`N: ` prefix) still resolves.
|
|
665
|
+
* Returns null when the sampled envelope cannot fit the budget (or when there
|
|
666
|
+
* are too few records to omit anything), letting head/tail take over.
|
|
667
|
+
*/
|
|
668
|
+
function reduceJsonl(input: PreparedInput): ReducerOutput | null {
|
|
669
|
+
const recordLines: string[] = []
|
|
670
|
+
for (const line of input.contentText.split('\n')) {
|
|
671
|
+
const trimmed = line.trim()
|
|
672
|
+
if (trimmed !== '' && (trimmed.startsWith('{') || trimmed.startsWith('['))) recordLines.push(trimmed)
|
|
673
|
+
}
|
|
674
|
+
const total = recordLines.length
|
|
675
|
+
if (total < 2) return null
|
|
676
|
+
const parseRecord = (text: string): unknown => {
|
|
677
|
+
try {
|
|
678
|
+
return JSON.parse(text) as unknown
|
|
679
|
+
} catch {
|
|
680
|
+
return text
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
const headCount = Math.min(JSONL_HEAD_RECORDS, total)
|
|
684
|
+
const tailCount = total > headCount ? Math.min(JSONL_TAIL_RECORDS, total - headCount) : 0
|
|
685
|
+
const head = recordLines.slice(0, headCount).map(entry => shrinkJson(parseRecord(entry), 0))
|
|
686
|
+
const tail = tailCount > 0
|
|
687
|
+
? recordLines.slice(total - tailCount).map(entry => shrinkJson(parseRecord(entry), 0))
|
|
688
|
+
: []
|
|
689
|
+
const omitted = total - headCount - tailCount
|
|
690
|
+
const envelope: Record<string, unknown> = {
|
|
691
|
+
$dsh_compression: {
|
|
692
|
+
kind: 'jsonl-preview',
|
|
693
|
+
source: input.sourceRef,
|
|
694
|
+
original_chars: codePointLength(input.text),
|
|
695
|
+
records: total,
|
|
696
|
+
},
|
|
697
|
+
head,
|
|
698
|
+
}
|
|
699
|
+
if (omitted > 0) envelope.$dsh_omitted_records = omitted
|
|
700
|
+
if (tail.length > 0) envelope.tail = tail
|
|
701
|
+
const text = JSON.stringify(envelope, null, 2)
|
|
702
|
+
if (codePointLength(text) >= codePointLength(input.text) || codePointLength(text) > input.budgetChars) return null
|
|
703
|
+
return { text, reducer: 'jsonl-structure-preview', lossy: true }
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
/**
|
|
707
|
+
* Detect JSONL/NDJSON: at least two non-empty lines, each of which parses on
|
|
708
|
+
* its own as a JSON object or array. A pretty-printed single JSON fails this
|
|
709
|
+
* (its interior lines are not standalone values), so the two forms never
|
|
710
|
+
* collide. Only a bounded prefix is validated to keep multi-MB streams cheap.
|
|
711
|
+
*/
|
|
712
|
+
function looksLikeJsonl(text: string): boolean {
|
|
713
|
+
let records = 0
|
|
714
|
+
for (const line of text.split('\n')) {
|
|
715
|
+
const trimmed = line.trim()
|
|
716
|
+
if (trimmed === '') continue
|
|
717
|
+
if (!(trimmed.startsWith('{') || trimmed.startsWith('['))) return false
|
|
718
|
+
try {
|
|
719
|
+
const parsed = JSON.parse(trimmed) as unknown
|
|
720
|
+
if (typeof parsed !== 'object' || parsed === null) return false
|
|
721
|
+
records += 1
|
|
722
|
+
} catch {
|
|
723
|
+
return false
|
|
724
|
+
}
|
|
725
|
+
if (records >= JSONL_DETECT_SCAN) break
|
|
726
|
+
}
|
|
727
|
+
return records >= 2
|
|
728
|
+
}
|
|
729
|
+
|
|
650
730
|
function shrinkJson(value: unknown, depth: number): unknown {
|
|
651
731
|
if (depth >= 5) {
|
|
652
732
|
if (Array.isArray(value)) return `[array length=${String(value.length)} omitted]`
|
|
@@ -27,7 +27,7 @@ export const inject = ['tools', 'systemPrompt']
|
|
|
27
27
|
|
|
28
28
|
/** Maximum text returned by one recovery call. */
|
|
29
29
|
export interface Config {
|
|
30
|
-
/** Hard response bound in Unicode code points. Defaults to
|
|
30
|
+
/** Hard response bound in Unicode code points. Defaults to 12000. */
|
|
31
31
|
maxChars?: number
|
|
32
32
|
/** Maximum source text inspected by one call. Defaults to 250000. */
|
|
33
33
|
maxScanChars?: number
|
|
@@ -37,20 +37,21 @@ export interface Config {
|
|
|
37
37
|
|
|
38
38
|
/** Loader schema for the recovery tool's bounded runtime configuration. */
|
|
39
39
|
export const Config: z<Config> = z.object({
|
|
40
|
-
maxChars: z.number().step(1).min(1).default(
|
|
40
|
+
maxChars: z.number().step(1).min(1).default(12_000),
|
|
41
41
|
maxScanChars: z.number().step(1).min(1).default(250_000),
|
|
42
42
|
maxQueryChars: z.number().step(1).min(1).default(256),
|
|
43
43
|
})
|
|
44
44
|
|
|
45
45
|
const REF_PATTERN = /^session:\/\/([^/]+)\/event\/(\d+)$/
|
|
46
46
|
const MAX_LINES = 1_000
|
|
47
|
-
const DEFAULT_MAX_CHARS =
|
|
47
|
+
const DEFAULT_MAX_CHARS = 12_000
|
|
48
48
|
const DEFAULT_MAX_SCAN_CHARS = 250_000
|
|
49
49
|
const DEFAULT_MAX_QUERY_CHARS = 256
|
|
50
50
|
const TRUNCATION_MARKER = '\n[context_compression_retrieve output truncated; reported lines describe the selected source range]\n'
|
|
51
51
|
const PROMPT = 'When a compacted tool result contains a session://<session-id>/event/<seq> reference, '
|
|
52
52
|
+ 'or TailTrim contains a session://<session-id>/tailtrim/<seq> reference, use context_compression_retrieve with that exact ref '
|
|
53
53
|
+ 'and a narrow line range or query if the omitted evidence is necessary. '
|
|
54
|
+
+ 'Prefer a query or a tight start_line/max_lines over re-reading the whole result: every recovery re-enters the context and is charged against the savings, so a targeted slice keeps the rest of the reduction. '
|
|
54
55
|
+ 'The returned event content comes from the append-only session log, which is the source of truth.'
|
|
55
56
|
|
|
56
57
|
const OUTPUT = {
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 会话日志投影:重进/重启会话后按 JSON 重建节省账。
|
|
3
|
+
*
|
|
4
|
+
* 内存账本随进程重启归零;但每次压缩都 durable 地留在 append-only 的 Session
|
|
5
|
+
* 日志里:
|
|
6
|
+
* - 替换事件带 `surfaceOp { op:'replace', startSeq, endSeq }`("保留在会话里
|
|
7
|
+
* 的内容");
|
|
8
|
+
* - 被替换的原始事件仍在日志中(只是移出 surface),可原样定价。
|
|
9
|
+
*
|
|
10
|
+
* 本模块只读地重算与实时账本同口径的两样东西:
|
|
11
|
+
* - **当前生效毛节省(仪表)**:遍历当前 surface 的替换节点,累加
|
|
12
|
+
* `price(原始) − price(替换)`;替换已离开 surface 的自然不计。
|
|
13
|
+
* - **每次重读惩罚**:按 seq 顺序走日志,凡命中"此前被压缩过的原文"的普通
|
|
14
|
+
* 工具结果都记一条 `full-read` 负项(不去重、不一次性消费)。
|
|
15
|
+
*
|
|
16
|
+
* fail-open:无法定价(富内容、缺 tokenizer)的节点跳过,绝不抛给主流程。
|
|
17
|
+
*/
|
|
18
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
19
|
+
import type { ContentBlock } from '@deepseek-ai/dsh-llm'
|
|
20
|
+
import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
|
|
21
|
+
import { sessionEvents } from './session-events.ts'
|
|
22
|
+
import { measureForCompaction } from './measurement.ts'
|
|
23
|
+
import { countExactCanonicalTextFields, type TokenCount } from './token-count.ts'
|
|
24
|
+
import { pressureCost } from '../pruner/content.ts'
|
|
25
|
+
import { viewToolResult } from '../compat/tool-result.ts'
|
|
26
|
+
import { flattenPlainText } from './tokenpilot/dedup.ts'
|
|
27
|
+
import { charsToTokens } from './config.ts'
|
|
28
|
+
import { savingsHash, type SavingsBasis } from './savings.ts'
|
|
29
|
+
|
|
30
|
+
/** 最小计价面:只需一个把文本换成 TokenCount 的规范化计数器。 */
|
|
31
|
+
export type SavingsTextCounter = (text: string) => TokenCount
|
|
32
|
+
|
|
33
|
+
export interface ProjectedSaving {
|
|
34
|
+
component: string
|
|
35
|
+
tokens: number
|
|
36
|
+
basis: SavingsBasis
|
|
37
|
+
at: number
|
|
38
|
+
replacementSeq: number
|
|
39
|
+
}
|
|
40
|
+
export interface ProjectedOffset {
|
|
41
|
+
component: 'full-read'
|
|
42
|
+
tokens: number
|
|
43
|
+
basis: SavingsBasis
|
|
44
|
+
at: number
|
|
45
|
+
note: string
|
|
46
|
+
}
|
|
47
|
+
export interface ProjectedRegistryItem {
|
|
48
|
+
hash: string
|
|
49
|
+
claimedTokens: number
|
|
50
|
+
basis: SavingsBasis
|
|
51
|
+
sourceSeq: number
|
|
52
|
+
}
|
|
53
|
+
export interface SessionSavingsProjection {
|
|
54
|
+
savings: ProjectedSaving[]
|
|
55
|
+
offsets: ProjectedOffset[]
|
|
56
|
+
registry: ProjectedRegistryItem[]
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
interface Priced {
|
|
60
|
+
tokens: number
|
|
61
|
+
basis: SavingsBasis
|
|
62
|
+
chars: number
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const EMPTY: SessionSavingsProjection = Object.freeze({ savings: [], offsets: [], registry: [] })
|
|
66
|
+
|
|
67
|
+
function blocksOf(event: SessionEvent): readonly ContentBlock[] | undefined {
|
|
68
|
+
if (event.type !== 'tool/result') return undefined
|
|
69
|
+
return viewToolResult(event.data.message).blocks as ContentBlock[]
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function textOf(event: SessionEvent): string | undefined {
|
|
73
|
+
const blocks = blocksOf(event)
|
|
74
|
+
return blocks === undefined ? undefined : flattenPlainText(blocks)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** 与 pruner 的 `plan()` 同口径定价:全文本块可精确,否则字符口径。 */
|
|
78
|
+
function priceEvent(event: SessionEvent, countText: SavingsTextCounter): Priced | undefined {
|
|
79
|
+
const blocks = blocksOf(event)
|
|
80
|
+
if (blocks === undefined) return undefined
|
|
81
|
+
const chars = pressureCost(blocks)
|
|
82
|
+
if (chars <= 0) return undefined
|
|
83
|
+
const texts = blocks.map(block => (block.type === 'text' ? block.text : undefined))
|
|
84
|
+
if (texts.every((text): text is string => text !== undefined)) {
|
|
85
|
+
const count = countExactCanonicalTextFields(texts, countText, 'savings projection')
|
|
86
|
+
if (count.kind === 'exact-tokenizer') return { tokens: count.tokens, basis: 'exact-tokenizer', chars }
|
|
87
|
+
}
|
|
88
|
+
return { tokens: Math.max(1, charsToTokens(chars)), basis: 'characters', chars }
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** 替换事件的被替换 span;非替换节点(或畸形 op)返回 undefined。 */
|
|
92
|
+
function replacedSpan(event: SessionEvent): { start: number; end: number } | undefined {
|
|
93
|
+
const op = event.surfaceOp as { op?: unknown; startSeq?: unknown; endSeq?: unknown } | 'append' | undefined
|
|
94
|
+
if (typeof op !== 'object' || op === null || op.op !== 'replace') return undefined
|
|
95
|
+
const start = Number(op.startSeq)
|
|
96
|
+
const end = Number(op.endSeq)
|
|
97
|
+
if (!Number.isFinite(start) || !Number.isFinite(end) || end < start) return undefined
|
|
98
|
+
return { start, end }
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function originalText(bySeq: ReadonlyMap<number, SessionEvent>, span: { start: number; end: number }): string {
|
|
102
|
+
const parts: string[] = []
|
|
103
|
+
for (let seq = span.start; seq <= span.end; seq++) {
|
|
104
|
+
const event = bySeq.get(seq)
|
|
105
|
+
const text = event === undefined ? undefined : textOf(event)
|
|
106
|
+
if (text !== undefined && text.length > 0) parts.push(text)
|
|
107
|
+
}
|
|
108
|
+
return parts.join('\n')
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* 一个替换节点"压掉了多少"(与实时 `plan()` 同口径:差额>0 才算)。
|
|
113
|
+
* 原始价 = span 内原始事件之和;替换价 = 替换事件。
|
|
114
|
+
*/
|
|
115
|
+
function computeDelta(
|
|
116
|
+
bySeq: ReadonlyMap<number, SessionEvent>,
|
|
117
|
+
replacement: SessionEvent,
|
|
118
|
+
span: { start: number; end: number },
|
|
119
|
+
counter: SavingsTextCounter,
|
|
120
|
+
): { tokens: number; basis: SavingsBasis } | undefined {
|
|
121
|
+
const after = priceEvent(replacement, counter)
|
|
122
|
+
if (after === undefined) return undefined
|
|
123
|
+
let beforeChars = 0
|
|
124
|
+
let beforeExactTokens = 0
|
|
125
|
+
let beforeExact = true
|
|
126
|
+
let any = false
|
|
127
|
+
for (let seq = span.start; seq <= span.end; seq++) {
|
|
128
|
+
const original = bySeq.get(seq)
|
|
129
|
+
const priced = original === undefined ? undefined : priceEvent(original, counter)
|
|
130
|
+
if (priced === undefined) continue
|
|
131
|
+
any = true
|
|
132
|
+
beforeChars += priced.chars
|
|
133
|
+
beforeExactTokens += priced.tokens
|
|
134
|
+
if (priced.basis !== 'exact-tokenizer') beforeExact = false
|
|
135
|
+
}
|
|
136
|
+
if (!any) return undefined
|
|
137
|
+
const exact = after.basis === 'exact-tokenizer' && beforeExact
|
|
138
|
+
const basis: SavingsBasis = exact ? 'exact-tokenizer' : 'characters'
|
|
139
|
+
const before = exact ? beforeExactTokens : charsToTokens(beforeChars)
|
|
140
|
+
const afterTokens = exact ? after.tokens : charsToTokens(after.chars)
|
|
141
|
+
const delta = before - afterTokens
|
|
142
|
+
if (delta <= 0) return undefined
|
|
143
|
+
return { tokens: delta, basis }
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* 纯核心:给定事件流、当前 surface 节点与计价计数器,重算节省投影。
|
|
148
|
+
* @param input - events/surfaceNodes/counter,均为实时路径的只读快照。
|
|
149
|
+
* @returns savings(当前生效毛节省)/ offsets(每次重读惩罚)/ registry(原文配对键)。
|
|
150
|
+
*/
|
|
151
|
+
export function projectSavingsCore(input: {
|
|
152
|
+
events: readonly SessionEvent[]
|
|
153
|
+
surfaceNodes: Iterable<number | bigint | { valueOf(): number }>
|
|
154
|
+
counter: SavingsTextCounter
|
|
155
|
+
}): SessionSavingsProjection {
|
|
156
|
+
const { events, surfaceNodes, counter } = input
|
|
157
|
+
if (events.length === 0) return EMPTY
|
|
158
|
+
const bySeq = new Map<number, SessionEvent>()
|
|
159
|
+
for (const event of events) bySeq.set(Number(event.seq), event)
|
|
160
|
+
|
|
161
|
+
// 1) 当前生效毛节省(仪表):只算仍在 surface 中的替换节点。
|
|
162
|
+
const savings: ProjectedSaving[] = []
|
|
163
|
+
for (const rawSeq of surfaceNodes) {
|
|
164
|
+
const seq = Number(rawSeq)
|
|
165
|
+
const replacement = bySeq.get(seq)
|
|
166
|
+
if (replacement === undefined) continue
|
|
167
|
+
const span = replacedSpan(replacement)
|
|
168
|
+
if (span === undefined) continue
|
|
169
|
+
const delta = computeDelta(bySeq, replacement, span, counter)
|
|
170
|
+
if (delta === undefined) continue
|
|
171
|
+
savings.push({
|
|
172
|
+
component: 'projection',
|
|
173
|
+
tokens: delta.tokens,
|
|
174
|
+
basis: delta.basis,
|
|
175
|
+
at: Number(replacement.time) || 0,
|
|
176
|
+
replacementSeq: seq,
|
|
177
|
+
})
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// 2) 每次重读惩罚:按 seq 顺序,登记每个压缩的原文,其后每次同原文重读都记负项。
|
|
181
|
+
const offsets: ProjectedOffset[] = []
|
|
182
|
+
const registry: ProjectedRegistryItem[] = []
|
|
183
|
+
const owned = new Map<string, { claimedTokens: number; basis: SavingsBasis; sourceSeq: number }>()
|
|
184
|
+
for (const event of events) {
|
|
185
|
+
if (event.type !== 'tool/result') continue
|
|
186
|
+
const span = replacedSpan(event)
|
|
187
|
+
if (span !== undefined) {
|
|
188
|
+
const groupText = originalText(bySeq, span)
|
|
189
|
+
if (groupText.length === 0) continue
|
|
190
|
+
const delta = computeDelta(bySeq, event, span, counter)
|
|
191
|
+
if (delta === undefined) continue
|
|
192
|
+
const hash = savingsHash(groupText)
|
|
193
|
+
owned.set(hash, { claimedTokens: delta.tokens, basis: delta.basis, sourceSeq: span.start })
|
|
194
|
+
registry.push({ hash, claimedTokens: delta.tokens, basis: delta.basis, sourceSeq: span.start })
|
|
195
|
+
continue
|
|
196
|
+
}
|
|
197
|
+
const text = textOf(event)
|
|
198
|
+
if (text === undefined || text.length === 0) continue
|
|
199
|
+
const hit = owned.get(savingsHash(text))
|
|
200
|
+
if (hit === undefined) continue
|
|
201
|
+
const priced = priceEvent(event, counter)
|
|
202
|
+
if (priced === undefined) continue
|
|
203
|
+
offsets.push({
|
|
204
|
+
component: 'full-read',
|
|
205
|
+
tokens: priced.tokens,
|
|
206
|
+
basis: priced.basis,
|
|
207
|
+
at: Number(event.time) || 0,
|
|
208
|
+
note: `#${hit.sourceSeq} 的原文被全文重读(投影重建)`,
|
|
209
|
+
})
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
return { savings, offsets, registry }
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* 从会话快照投影节省账。`measureForCompaction` 提供与实时同口径的 tokenizer
|
|
217
|
+
* 计数器;失败时向上抛,由调用方 fail-open。
|
|
218
|
+
*/
|
|
219
|
+
export function projectSessionSavings(ctx: Context, session: Session): SessionSavingsProjection {
|
|
220
|
+
const view = measureForCompaction(ctx, session)
|
|
221
|
+
return projectSavingsCore({
|
|
222
|
+
events: sessionEvents(session),
|
|
223
|
+
surfaceNodes: session.surface.nodes as Iterable<number | bigint | { valueOf(): number }>,
|
|
224
|
+
counter: candidate => view.countCanonicalText(candidate),
|
|
225
|
+
})
|
|
226
|
+
}
|
|
@@ -27,6 +27,8 @@ export interface SavingsEntry {
|
|
|
27
27
|
tokens: number
|
|
28
28
|
basis: SavingsBasis
|
|
29
29
|
at: number
|
|
30
|
+
/** 落盘替换事件的 seq;'saving' 条目靠它判定"当前是否仍在 surface 中生效"。 */
|
|
31
|
+
replacementSeq?: number
|
|
30
32
|
note?: string
|
|
31
33
|
}
|
|
32
34
|
|
|
@@ -95,7 +97,12 @@ export class SavingsLedger {
|
|
|
95
97
|
`requests=${snap.usage.requests} cacheHit=${hit === null ? '–' : `${Math.round(hit * 100)}%`}`
|
|
96
98
|
}
|
|
97
99
|
|
|
98
|
-
/**
|
|
100
|
+
/**
|
|
101
|
+
* 记录一次已落盘的压缩节省(land 成功后调用;tokensRemoved ≤ 0 忽略)。
|
|
102
|
+
*
|
|
103
|
+
* 仪表口径:该条目在替换事件离开当前 surface 前一直计入"当前生效毛节省"
|
|
104
|
+
* (由 {@link observeActive} 每回合收敛),不再一次性永久累加。
|
|
105
|
+
*/
|
|
99
106
|
recordSaving(input: {
|
|
100
107
|
sessionId: string
|
|
101
108
|
component: string
|
|
@@ -103,6 +110,8 @@ export class SavingsLedger {
|
|
|
103
110
|
tokensAfter: number
|
|
104
111
|
basis: SavingsBasis
|
|
105
112
|
sourceSeq: number
|
|
113
|
+
/** 落盘替换事件的 seq;仪表口径用它判定"当前是否仍生效"。 */
|
|
114
|
+
replacementSeq?: number
|
|
106
115
|
/** 原文全文(配对键;哈希后不存原文)。 */
|
|
107
116
|
originalText?: string
|
|
108
117
|
}): void {
|
|
@@ -114,6 +123,7 @@ export class SavingsLedger {
|
|
|
114
123
|
tokens: removed,
|
|
115
124
|
basis: input.basis,
|
|
116
125
|
at: Date.now(),
|
|
126
|
+
...(input.replacementSeq === undefined ? {} : { replacementSeq: input.replacementSeq }),
|
|
117
127
|
})
|
|
118
128
|
if (typeof input.originalText === 'string' && input.originalText.length > 0) {
|
|
119
129
|
const hash = savingsHash(input.originalText)
|
|
@@ -153,8 +163,9 @@ export class SavingsLedger {
|
|
|
153
163
|
this.seenFullText.add(seenKey)
|
|
154
164
|
}
|
|
155
165
|
const hit = this.registry.get(savingsHash(input.text))
|
|
156
|
-
if (hit === undefined || hit.
|
|
157
|
-
|
|
166
|
+
if (hit === undefined || hit.sessionId !== input.sessionId) return
|
|
167
|
+
// 每次重读都罚:不再一次性消费——只要首次压缩(骨架/老化/去重/尾裁)存在,
|
|
168
|
+
// 之后每次把该原文全文重新读入上下文都记一条负项。
|
|
158
169
|
const { tokens, basis } = input.measure(input.text)
|
|
159
170
|
if (tokens <= 0) return
|
|
160
171
|
this.push(input.sessionId, {
|
|
@@ -200,6 +211,75 @@ export class SavingsLedger {
|
|
|
200
211
|
if (list.length > MAX_ENTRIES_PER_SESSION) list.splice(0, list.length - MAX_ENTRIES_PER_SESSION)
|
|
201
212
|
}
|
|
202
213
|
|
|
214
|
+
/**
|
|
215
|
+
* 仪表口径收敛:一个 'saving' 条目只在其替换事件仍位于当前 surface 时计为
|
|
216
|
+
* "当前生效毛节省"。pruner 每回合传入存活 seq 集合,离开 surface 的替换
|
|
217
|
+
* (被后续压缩/裁剪替换)即从毛节省中扣除,数字随压缩内容进出而涨落。
|
|
218
|
+
* 无 replacementSeq 的条目保持原样(无法追踪者不收敛)。
|
|
219
|
+
*/
|
|
220
|
+
observeActive(sessionId: string, liveSeqs: ReadonlySet<number>): void {
|
|
221
|
+
const list = this.entries.get(sessionId)
|
|
222
|
+
if (list === undefined) return
|
|
223
|
+
const kept = list.filter(entry =>
|
|
224
|
+
entry.kind !== 'saving'
|
|
225
|
+
|| entry.replacementSeq === undefined
|
|
226
|
+
|| liveSeqs.has(entry.replacementSeq))
|
|
227
|
+
if (kept.length !== list.length) this.entries.set(sessionId, kept)
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** 该会话是否已有账本条目(重进会话时用于避免投影与实时叠加)。 */
|
|
231
|
+
hasSession(sessionId: string): boolean {
|
|
232
|
+
return this.entries.has(sessionId)
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* 用会话日志投影播种一个会话的账本(重进/重启会话时调用一次)。写入
|
|
237
|
+
* savings/offsets 条目及其原文配对 registry,后续实时增量(observeActive /
|
|
238
|
+
* noteFullText)在同一条目集合上继续工作。调用方负责只播种一次。
|
|
239
|
+
*/
|
|
240
|
+
seedProjected(sessionId: string, projection: {
|
|
241
|
+
savings: readonly { component: string; tokens: number; basis: SavingsBasis; at: number; replacementSeq: number }[]
|
|
242
|
+
offsets: readonly { component: string; tokens: number; basis: SavingsBasis; at: number; note?: string }[]
|
|
243
|
+
registry: readonly { hash: string; claimedTokens: number; basis: SavingsBasis; sourceSeq: number }[]
|
|
244
|
+
}): void {
|
|
245
|
+
for (const entry of projection.savings) {
|
|
246
|
+
if (!Number.isFinite(entry.tokens) || entry.tokens <= 0) continue
|
|
247
|
+
this.push(sessionId, {
|
|
248
|
+
kind: 'saving',
|
|
249
|
+
component: entry.component,
|
|
250
|
+
tokens: entry.tokens,
|
|
251
|
+
basis: entry.basis,
|
|
252
|
+
at: entry.at,
|
|
253
|
+
replacementSeq: entry.replacementSeq,
|
|
254
|
+
})
|
|
255
|
+
}
|
|
256
|
+
for (const entry of projection.offsets) {
|
|
257
|
+
if (!Number.isFinite(entry.tokens) || entry.tokens <= 0) continue
|
|
258
|
+
this.push(sessionId, {
|
|
259
|
+
kind: 'offset',
|
|
260
|
+
component: entry.component,
|
|
261
|
+
tokens: entry.tokens,
|
|
262
|
+
basis: entry.basis,
|
|
263
|
+
at: entry.at,
|
|
264
|
+
...(entry.note === undefined ? {} : { note: entry.note }),
|
|
265
|
+
})
|
|
266
|
+
}
|
|
267
|
+
for (const item of projection.registry) {
|
|
268
|
+
if (this.registry.size >= MAX_REGISTRY && !this.registry.has(item.hash)) {
|
|
269
|
+
const oldest = this.registry.keys().next().value
|
|
270
|
+
if (oldest !== undefined) this.registry.delete(oldest)
|
|
271
|
+
}
|
|
272
|
+
this.registry.set(item.hash, {
|
|
273
|
+
sessionId,
|
|
274
|
+
component: 'projection',
|
|
275
|
+
claimedTokens: item.claimedTokens,
|
|
276
|
+
basis: item.basis,
|
|
277
|
+
sourceSeq: item.sourceSeq,
|
|
278
|
+
consumed: false,
|
|
279
|
+
})
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
203
283
|
/** 汇总快照。sessionId 缺省 = 全会话聚合。两个 basis 分列,永不合并。 */
|
|
204
284
|
snapshot(sessionId?: string): SavingsSnapshot {
|
|
205
285
|
const scope = sessionId === undefined ? [...this.entries.keys()] : [sessionId]
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { freshBelowTrigger } from '../../src/pruner.ts'
|
|
3
|
+
import { charsForTokens } from '../../src/runtime/config.ts'
|
|
4
|
+
import type { SnapshotCandidate } from '../../src/pruner/types.ts'
|
|
5
|
+
import type { CompressionPolicy } from '../../src/runtime/types.ts'
|
|
6
|
+
|
|
7
|
+
const TRIGGER = 4_096
|
|
8
|
+
const policy = { freshTriggerTokens: TRIGGER } as unknown as CompressionPolicy
|
|
9
|
+
|
|
10
|
+
const exact = (tokens: number, characterPressure: number): SnapshotCandidate =>
|
|
11
|
+
({ count: { kind: 'exact-tokenizer', tokens }, characterPressure }) as unknown as SnapshotCandidate
|
|
12
|
+
const unavailable = (characterPressure: number): SnapshotCandidate =>
|
|
13
|
+
({ count: { kind: 'unavailable', reason: 'no tokenizer' }, characterPressure }) as unknown as SnapshotCandidate
|
|
14
|
+
const estimate = (characterPressure: number): SnapshotCandidate =>
|
|
15
|
+
({ count: { kind: 'tokenizer-estimate', tokens: 999_999 }, characterPressure }) as unknown as SnapshotCandidate
|
|
16
|
+
|
|
17
|
+
describe('freshBelowTrigger (real-token fresh gate with char fallback)', () => {
|
|
18
|
+
it('exact tokenizer: triggers on CJK where the 4.0 char estimate would NOT', () => {
|
|
19
|
+
// 8,000 chars is below charsForTokens(4096)=16,384, but 5,000 real tokens
|
|
20
|
+
// is above the 4,096 trigger → must trigger (return false = not below).
|
|
21
|
+
expect(charsForTokens(TRIGGER)).toBe(16_384)
|
|
22
|
+
expect(freshBelowTrigger(exact(5_000, 8_000), policy)).toBe(false)
|
|
23
|
+
})
|
|
24
|
+
|
|
25
|
+
it('exact tokenizer: below trigger when real tokens do not exceed it', () => {
|
|
26
|
+
expect(freshBelowTrigger(exact(3_000, 20_000), policy)).toBe(true)
|
|
27
|
+
expect(freshBelowTrigger(exact(TRIGGER, 20_000), policy)).toBe(true) // boundary: <= is below
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
it('unavailable (local Qwen): falls back to the char basis, byte-for-byte old behavior', () => {
|
|
31
|
+
for (const chars of [10_000, 16_384, 20_000, 40_000]) {
|
|
32
|
+
expect(freshBelowTrigger(unavailable(chars), policy)).toBe(chars <= charsForTokens(TRIGGER))
|
|
33
|
+
}
|
|
34
|
+
expect(freshBelowTrigger(unavailable(20_000), policy)).toBe(false) // > 16,384 → triggers
|
|
35
|
+
expect(freshBelowTrigger(unavailable(10_000), policy)).toBe(true) // <= 16,384 → skipped
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
it('tokenizer-estimate is NOT treated as exact; uses the char fallback', () => {
|
|
39
|
+
// tokens field is huge but kind !== 'exact-tokenizer', so the char basis decides.
|
|
40
|
+
expect(freshBelowTrigger(estimate(10_000), policy)).toBe(true)
|
|
41
|
+
expect(freshBelowTrigger(estimate(20_000), policy)).toBe(false)
|
|
42
|
+
})
|
|
43
|
+
})
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { reduceFreshToolResult, type ReducerInput } from '../../src/runtime/reducers.ts'
|
|
3
|
+
|
|
4
|
+
const SOURCE_REF = 'session://s1/event/7'
|
|
5
|
+
|
|
6
|
+
function input(text: string, budgetChars: number, toolName = 'bash'): ReducerInput {
|
|
7
|
+
return {
|
|
8
|
+
toolName,
|
|
9
|
+
argumentsText: toolName === 'read_file' ? '{"path":"logs.jsonl"}' : '{"command":"cat logs.jsonl"}',
|
|
10
|
+
text,
|
|
11
|
+
budgetChars,
|
|
12
|
+
sourceRef: SOURCE_REF,
|
|
13
|
+
isError: false,
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function jsonlStream(count: number, pad = 120): string {
|
|
18
|
+
return Array.from({ length: count }, (_, index) =>
|
|
19
|
+
JSON.stringify({ seq: index, status: 'ok', payload: 'x'.repeat(pad), note: `record ${String(index)}` }))
|
|
20
|
+
.join('\n')
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
describe('JSONL / NDJSON reducer (jsonl-structure-preview)', () => {
|
|
24
|
+
it('samples head + tail records and collapses the middle into an omitted count', () => {
|
|
25
|
+
const output = reduceFreshToolResult(input(jsonlStream(50), 2_000))
|
|
26
|
+
expect(output).not.toBeNull()
|
|
27
|
+
expect(output!.reducer).toBe('jsonl-structure-preview')
|
|
28
|
+
expect(output!.text).toContain(SOURCE_REF)
|
|
29
|
+
expect(output!.text).toContain('"$dsh_omitted_records"')
|
|
30
|
+
expect(output!.text).toContain('"seq": 0')
|
|
31
|
+
expect(output!.text).toContain('"seq": 49')
|
|
32
|
+
expect(output!.text).not.toContain('"seq": 25')
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
it('still fires through the host read gutter (N: prefix) via the content view', () => {
|
|
36
|
+
const gutted = jsonlStream(40)
|
|
37
|
+
.split('\n')
|
|
38
|
+
.map((line, index) => `${String(index + 1)}: ${line}`)
|
|
39
|
+
.join('\n')
|
|
40
|
+
const output = reduceFreshToolResult(input(gutted, 2_000, 'read_file'))
|
|
41
|
+
expect(output).not.toBeNull()
|
|
42
|
+
expect(output!.reducer).toBe('jsonl-structure-preview')
|
|
43
|
+
expect(output!.text).toContain('"seq": 0')
|
|
44
|
+
expect(output!.text).toContain('"seq": 39')
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
it('does not steal a pretty-printed single JSON (regression: json-* branch intact)', () => {
|
|
48
|
+
// Unique-key lines so the adjacent/non-adjacent fold leaves the blob intact
|
|
49
|
+
// and reduceJson actually parses it (repeating structural lines would fold
|
|
50
|
+
// into markers and is a pre-existing, unrelated bail).
|
|
51
|
+
const record: Record<string, string> = { fetched_at: '2026-10-15T15:26:14Z' }
|
|
52
|
+
for (let index = 0; index < 200; index += 1) record[`field_${String(index)}`] = 'v'.repeat(60)
|
|
53
|
+
const pretty = JSON.stringify(record, null, 2)
|
|
54
|
+
const output = reduceFreshToolResult(input(pretty, 2_000))
|
|
55
|
+
expect(output).not.toBeNull()
|
|
56
|
+
expect(output!.reducer).not.toBe('jsonl-structure-preview')
|
|
57
|
+
expect(output!.reducer).toMatch(/^json-/)
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
it('treats a multi-record stream as JSONL but a one-line array as single JSON', () => {
|
|
61
|
+
const many = jsonlStream(20)
|
|
62
|
+
expect(reduceFreshToolResult(input(many, 2_000))?.reducer).toBe('jsonl-structure-preview')
|
|
63
|
+
const oneLine = JSON.stringify(Array.from({ length: 20 }, (_, index) => ({ seq: index, payload: 'x'.repeat(120) })))
|
|
64
|
+
expect(reduceFreshToolResult(input(oneLine, 2_000))?.reducer).not.toBe('jsonl-structure-preview')
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
it('fails open (no jsonl preview) when the sampled envelope cannot fit the budget', () => {
|
|
68
|
+
const wide = jsonlStream(30, 900)
|
|
69
|
+
const output = reduceFreshToolResult(input(wide, 1_200))
|
|
70
|
+
// Must not throw, and must never land a jsonl preview that busts the budget.
|
|
71
|
+
expect(output === null || output.reducer !== 'jsonl-structure-preview' || output.text.length <= 1_200).toBe(true)
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
it('leaves a two-record stream alone (nothing to omit) rather than inflating it', () => {
|
|
75
|
+
const two = `${JSON.stringify({ a: 'x'.repeat(200) })}\n${JSON.stringify({ b: 'y'.repeat(200) })}`
|
|
76
|
+
const output = reduceFreshToolResult(input(two, 1_200))
|
|
77
|
+
expect(output?.reducer ?? 'none').not.toBe('jsonl-structure-preview')
|
|
78
|
+
})
|
|
79
|
+
})
|
|
@@ -417,6 +417,54 @@ describe('standalone runtime on published Harness APIs', () => {
|
|
|
417
417
|
expect(record?.tokensRemoved).toBe((record?.tokensBefore ?? 0) - (record?.tokensAfter ?? 0))
|
|
418
418
|
})
|
|
419
419
|
|
|
420
|
+
it('tokenpilot-inspired default threshold lands a fresh replace end-to-end (no explicit override)', async () => {
|
|
421
|
+
const ctx = await runtimeContext()
|
|
422
|
+
const audit = captureAudit(ctx)
|
|
423
|
+
// No freshTriggerTokens passed → the profile default governs. The lowered
|
|
424
|
+
// default (4096) must reduce a large fresh result through the real cordis
|
|
425
|
+
// path, mirroring what the desktop panel observes at turn tail.
|
|
426
|
+
await ctx.plugin(ToolResultPruner, { profile: 'tokenpilot-inspired' }).await()
|
|
427
|
+
const session = Session.create(SessionId('public-tokenpilot-default-fresh'))
|
|
428
|
+
const fixture = Array.from({ length: 1_200 }, (_, index) =>
|
|
429
|
+
`row ${String(index)} :: ${['alpha', 'bravo', 'charlie', 'delta', 'echo'][index % 5]}-${String((index * 7) % 997)} payload ${String(index)}`).join('\n')
|
|
430
|
+
appendToolTurn(session, 1, fixture, false, undefined, 'deepseek-official')
|
|
431
|
+
|
|
432
|
+
const result = ctx.toolResultPruner.pruneSession(session, {
|
|
433
|
+
stage: 'fresh',
|
|
434
|
+
freshTurn: 1,
|
|
435
|
+
freshStep: 1,
|
|
436
|
+
})
|
|
437
|
+
|
|
438
|
+
expect(result.pruned.length).toBeGreaterThanOrEqual(1)
|
|
439
|
+
const record = rewrites(audit.records()).find(entry => entry.component === 'fresh')
|
|
440
|
+
expect(record).toBeDefined()
|
|
441
|
+
expect(record?.reducer).toEqual(expect.any(String))
|
|
442
|
+
})
|
|
443
|
+
|
|
444
|
+
it('tokenpilot-inspired lands a fresh replace on an UNAVAILABLE-tokenizer route (local Qwen)', async () => {
|
|
445
|
+
const ctx = await runtimeContext()
|
|
446
|
+
const audit = captureAudit(ctx)
|
|
447
|
+
await ctx.plugin(ToolResultPruner, { profile: 'tokenpilot-inspired' }).await()
|
|
448
|
+
const session = Session.create(SessionId('public-tokenpilot-qwen-fresh'))
|
|
449
|
+
// A ~40KB JSONL result — the exact shape the desktop test feeds. local-35 has
|
|
450
|
+
// no bundled tokenizer, so every node count is 'unavailable' and the fresh
|
|
451
|
+
// gate + land must run entirely on the character basis.
|
|
452
|
+
const jsonl = Array.from({ length: 150 }, (_, index) =>
|
|
453
|
+
JSON.stringify({ qid: index, question: `Janet's ducks lay ${index} eggs. How many remain after ${index + 3}?`, answer: `step ${index} ... #### ${index * 2}` })).join('\n')
|
|
454
|
+
appendToolTurn(session, 1, jsonl, false, undefined, 'local-35', 'Qwen3.6-35B-A3B')
|
|
455
|
+
|
|
456
|
+
const result = ctx.toolResultPruner.pruneSession(session, {
|
|
457
|
+
stage: 'fresh',
|
|
458
|
+
freshTurn: 1,
|
|
459
|
+
freshStep: 1,
|
|
460
|
+
})
|
|
461
|
+
|
|
462
|
+
const record = rewrites(audit.records()).find(entry => entry.component === 'fresh')
|
|
463
|
+
// eslint-disable-next-line no-console
|
|
464
|
+
console.log('QWEN_FRESH pruned=', result.pruned.length, 'reducer=', record?.reducer ?? 'none', 'basis=', record?.measurementBasis ?? 'none')
|
|
465
|
+
expect(result.pruned.length).toBeGreaterThanOrEqual(1)
|
|
466
|
+
})
|
|
467
|
+
|
|
420
468
|
it('threads the reducer elided-line count from a fresh plan into the rewrite audit', async () => {
|
|
421
469
|
// The skeleton reducer counts the lines it hid behind elision markers; that
|
|
422
470
|
// count must survive the whole planning middle (plan options → planned
|