dsh-context-compression-improved 0.6.5 → 0.7.0-beta.2
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/.github/workflows/ci.yml +39 -39
- package/CHANGELOG.ja.md +217 -211
- package/CHANGELOG.ko.md +211 -205
- package/CHANGELOG.md +392 -350
- package/CHANGELOG.zh.md +196 -190
- package/README.md +97 -96
- package/README.zh.md +86 -85
- package/eslint.config.js +76 -30
- package/package.json +3 -1
- package/packages/selector/dsh.plugin.json +1 -1
- package/packages/selector/lib/client.js +747 -3
- package/packages/selector/lib/index.js +92 -1
- package/packages/selector/lib/{advisor-state.js → intent-gate.js} +91 -3
- package/packages/selector/lib/profiles.d.ts +9 -0
- package/packages/selector/lib/pruner.d.ts +59 -0
- package/packages/selector/lib/pruner.js +410 -8
- package/packages/selector/src/client/decode.ts +53 -49
- package/packages/selector/src/client/index.ts +30 -0
- package/packages/selector/src/client/locales/de.ts +98 -0
- package/packages/selector/src/client/locales/es.ts +98 -0
- package/packages/selector/src/client/locales/fr.ts +98 -0
- package/packages/selector/src/client/locales/it.ts +98 -0
- package/packages/selector/src/client/locales/ja.ts +98 -0
- package/packages/selector/src/client/locales/ko.ts +98 -0
- package/packages/selector/src/client/locales/ru.ts +98 -0
- package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -205
- package/packages/selector/src/index.ts +418 -411
- package/packages/selector/src/preset-overlay.ts +629 -626
- package/packages/selector/src/profiles.ts +414 -394
- package/packages/selector/src/pruner/content.ts +198 -198
- package/packages/selector/src/pruner/state.ts +57 -50
- package/packages/selector/src/pruner.ts +2665 -2421
- package/packages/selector/src/runtime/audit.ts +303 -286
- package/packages/selector/src/runtime/config.ts +731 -706
- package/packages/selector/src/runtime/reducers.ts +1674 -1674
- package/packages/selector/src/runtime/summary-command.ts +133 -0
- package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -188
- package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -149
- 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/tokenpilot/locator.ts +128 -128
- package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +306 -303
- package/packages/selector/src/runtime/types.ts +358 -346
- package/packages/selector/tests/auto-compact.client.spec.tsx +214 -213
- package/packages/selector/tests/built/client-artifact.spec.ts +61 -59
- package/packages/selector/tests/code-skeleton.client.spec.ts +94 -93
- package/packages/selector/tests/custom-contract.client.spec.ts +223 -222
- package/packages/selector/tests/estimator-channel.client.spec.tsx +252 -252
- package/packages/selector/tests/preset-options-write.client.spec.ts +188 -187
- package/packages/selector/tests/profiles.client.spec.tsx +436 -434
- package/packages/selector/tests/runtime/audit.spec.ts +275 -274
- package/packages/selector/tests/runtime/auto-compact-config.spec.ts +523 -523
- package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +122 -122
- 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/public/public-runtime.spec.ts +5 -0
- package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
- package/packages/selector/tests/standing-generation.host.spec.ts +15 -35
- package/scripts/packed-components-smoke.mjs +734 -732
- package/scripts/packed-install-e2e.mjs +1275 -1273
- package/scripts/verify-release.mjs +318 -317
- package/tests/TEST_INVENTORY.md +41 -41
- package/tsconfig.tests.json +17 -15
- package/vitest.config.ts +57 -43
- package/.agents-stash-064.patch +0 -39
- package/_dsh_devdeps.json +0 -50
- package/_verify064/package/package.json +0 -162
- package/_verify064/package/packages/selector/src/client/index.ts +0 -232
|
@@ -1,198 +1,198 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Pure content-analysis functions extracted from ToolResultPruner.
|
|
3
|
-
*
|
|
4
|
-
* Every function here has ZERO `this` dependency — they receive all inputs
|
|
5
|
-
* as explicit arguments. Grouped by natural cohesion (content blocks →
|
|
6
|
-
* token counting → recovery helpers).
|
|
7
|
-
*
|
|
8
|
-
* @module dsh-context-compression-improved/pruner/content
|
|
9
|
-
*/
|
|
10
|
-
|
|
11
|
-
import type { ContentBlock } from '@deepseek-ai/dsh-llm'
|
|
12
|
-
import type {
|
|
13
|
-
CompactionTokenView,
|
|
14
|
-
ProviderMeasurementKey,
|
|
15
|
-
TokenCount,
|
|
16
|
-
} from '../runtime/measurement.ts'
|
|
17
|
-
import { countExactCanonicalTextFields } from '../runtime/token-count.ts'
|
|
18
|
-
import { codePointLength, PRUNE_MARKER } from '../runtime/config.ts'
|
|
19
|
-
import type { PrunedEntry, PruneResult } from '../runtime/types.ts'
|
|
20
|
-
import { RICH_BLOCK_PRESSURE_COST } from './tuning.ts'
|
|
21
|
-
|
|
22
|
-
// ── Content-block predicates ────────────────────────────────────────────
|
|
23
|
-
|
|
24
|
-
function onlyTextBlock(blocks: readonly ContentBlock[]): Extract<ContentBlock, { type: 'text' }> | null {
|
|
25
|
-
return blocks.length === 1 && blocks[0]?.type === 'text' ? blocks[0] : null
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
function onlyTextBlocks(blocks: readonly ContentBlock[]): readonly Extract<ContentBlock, { type: 'text' }>[] | null {
|
|
29
|
-
return blocks.every((block): block is Extract<ContentBlock, { type: 'text' }> => block.type === 'text')
|
|
30
|
-
? blocks
|
|
31
|
-
: null
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
// ── Token counting ──────────────────────────────────────────────────────
|
|
35
|
-
|
|
36
|
-
function countToolContent(blocks: readonly ContentBlock[], view: CompactionTokenView): TokenCount {
|
|
37
|
-
const text = onlyTextBlocks(blocks)
|
|
38
|
-
if (text === null) return unavailableCount('tool result contains unsupported rich content')
|
|
39
|
-
return countExactCanonicalTextFields(
|
|
40
|
-
text.map(block => block.text),
|
|
41
|
-
candidate => view.countCanonicalText(candidate),
|
|
42
|
-
'tool result replacement',
|
|
43
|
-
)
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
function exactTokens(count: TokenCount): number | undefined {
|
|
47
|
-
return count.kind === 'exact-tokenizer' ? count.tokens : undefined
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
// ── Provider measurement key comparison ─────────────────────────────────
|
|
51
|
-
|
|
52
|
-
function sameProviderMeasurementKey(
|
|
53
|
-
left: Readonly<ProviderMeasurementKey>,
|
|
54
|
-
right: Readonly<ProviderMeasurementKey>,
|
|
55
|
-
): boolean {
|
|
56
|
-
return left.provider === right.provider
|
|
57
|
-
&& left.baseUrlClass === right.baseUrlClass
|
|
58
|
-
&& left.apiRoute === right.apiRoute
|
|
59
|
-
&& left.modelId === right.modelId
|
|
60
|
-
&& left.requestTemplateRevision === right.requestTemplateRevision
|
|
61
|
-
&& left.tokenizerRevision === right.tokenizerRevision
|
|
62
|
-
&& left.modality === right.modality
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
// ── Token helpers ───────────────────────────────────────────────────────
|
|
66
|
-
|
|
67
|
-
function unavailableCount(reason: string): TokenCount {
|
|
68
|
-
return Object.freeze({ kind: 'unavailable', reason })
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
// ── Recovery markers ────────────────────────────────────────────────────
|
|
72
|
-
|
|
73
|
-
function recoveryMarker(sourceRef: string, label: string, startLine?: number): string {
|
|
74
|
-
const hint = startLine === undefined
|
|
75
|
-
? 'use context_compression_retrieve if needed'
|
|
76
|
-
: `retrieve with context_compression_retrieve({"ref":"${sourceRef}","start_line":${String(startLine)},"max_lines":80})`
|
|
77
|
-
return `\n\n[... ${label}; source=${sourceRef}; ${hint} ...]\n\n`
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
// ── Content measurement ─────────────────────────────────────────────────
|
|
81
|
-
|
|
82
|
-
/**
|
|
83
|
-
* Measure text content in Unicode code points; non-text blocks cost zero.
|
|
84
|
-
* @param blocks - tool-result content to measure.
|
|
85
|
-
* @returns total Unicode code points across text blocks.
|
|
86
|
-
*/
|
|
87
|
-
function measureContent(blocks: readonly ContentBlock[]): number {
|
|
88
|
-
let chars = 0
|
|
89
|
-
for (const block of blocks) {
|
|
90
|
-
if (block.type === 'text') chars += codePointLength(block.text)
|
|
91
|
-
}
|
|
92
|
-
return chars
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
function pressureCost(blocks: readonly ContentBlock[]): number {
|
|
96
|
-
let cost = 0
|
|
97
|
-
for (const block of blocks) {
|
|
98
|
-
switch (block.type) {
|
|
99
|
-
case 'text':
|
|
100
|
-
case 'reasoning':
|
|
101
|
-
cost += codePointLength(block.text)
|
|
102
|
-
break
|
|
103
|
-
case 'tool-call':
|
|
104
|
-
cost += RICH_BLOCK_PRESSURE_COST
|
|
105
|
-
+ codePointLength(block.name)
|
|
106
|
-
+ codePointLength(block.arguments)
|
|
107
|
-
break
|
|
108
|
-
default: {
|
|
109
|
-
// ContentBlockMap is merge-extensible. Unknown model-visible blocks
|
|
110
|
-
// scale with their durable JSON payload instead of receiving a fixed
|
|
111
|
-
// token that a large provider block could bypass.
|
|
112
|
-
const serialized = JSON.stringify(block)
|
|
113
|
-
cost += Math.max(RICH_BLOCK_PRESSURE_COST, codePointLength(serialized))
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
return cost
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
// ── Native content pruning ──────────────────────────────────────────────
|
|
121
|
-
|
|
122
|
-
function nativePruneContent(
|
|
123
|
-
blocks: readonly ContentBlock[],
|
|
124
|
-
thresholdChars: number,
|
|
125
|
-
headChars: number,
|
|
126
|
-
tailChars: number,
|
|
127
|
-
marker: string | ((startLine: number) => string) = PRUNE_MARKER,
|
|
128
|
-
): ContentBlock[] | null {
|
|
129
|
-
const totalChars = measureContent(blocks)
|
|
130
|
-
if (totalChars <= thresholdChars) return null
|
|
131
|
-
const markerChars = codePointLength(typeof marker === 'function' ? marker(1) : marker)
|
|
132
|
-
const safeHead = Math.max(0, Math.min(headChars, thresholdChars - markerChars))
|
|
133
|
-
const safeTail = Math.max(0, Math.min(tailChars, thresholdChars - markerChars - safeHead))
|
|
134
|
-
const removedStart = safeHead
|
|
135
|
-
const removedEnd = totalChars - safeTail
|
|
136
|
-
const pruned: ContentBlock[] = []
|
|
137
|
-
let consumed = 0
|
|
138
|
-
let markerInserted = false
|
|
139
|
-
// '\n' count in the RAW event text before the current block (retrieve scans
|
|
140
|
-
// the original event; blocks are joined with '\n'). Line numbers therefore
|
|
141
|
-
// never depend on what the pruning removed.
|
|
142
|
-
let newlinesBefore = 0
|
|
143
|
-
for (const block of blocks) {
|
|
144
|
-
if (block.type !== 'text') {
|
|
145
|
-
pruned.push(block)
|
|
146
|
-
newlinesBefore += 1
|
|
147
|
-
continue
|
|
148
|
-
}
|
|
149
|
-
const points = Array.from(block.text)
|
|
150
|
-
const blockStart = consumed
|
|
151
|
-
const blockEnd = blockStart + points.length
|
|
152
|
-
const headEnd = Math.min(points.length, Math.max(0, removedStart - blockStart))
|
|
153
|
-
const tailStart = Math.min(points.length, Math.max(0, removedEnd - blockStart))
|
|
154
|
-
const intersectsRemoved = blockStart < removedEnd && blockEnd > removedStart
|
|
155
|
-
// The elided region starts on the event line after the retained head.
|
|
156
|
-
const headText = points.slice(0, headEnd).join('')
|
|
157
|
-
const insertion = intersectsRemoved && !markerInserted && typeof marker === 'function'
|
|
158
|
-
? marker(1 + newlinesBefore + headText.split('\n').length - 1)
|
|
159
|
-
: intersectsRemoved && !markerInserted ? marker : ''
|
|
160
|
-
if (insertion !== '') markerInserted = true
|
|
161
|
-
const text = points.slice(0, headEnd).join('') + insertion + points.slice(tailStart).join('')
|
|
162
|
-
if (text !== '') pruned.push({ ...block, text })
|
|
163
|
-
newlinesBefore += block.text.split('\n').length - 1 + 1
|
|
164
|
-
consumed = blockEnd
|
|
165
|
-
}
|
|
166
|
-
if (!markerInserted) return null
|
|
167
|
-
const charsAfter = measureContent(pruned)
|
|
168
|
-
return charsAfter <= thresholdChars && charsAfter < totalChars ? pruned : null
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
// ── Result aggregation ──────────────────────────────────────────────────
|
|
172
|
-
|
|
173
|
-
function summarize(entries: readonly PrunedEntry[]): PruneResult {
|
|
174
|
-
return {
|
|
175
|
-
pruned: entries,
|
|
176
|
-
charsRemoved: entries.reduce((sum, entry) => sum + entry.charsBefore - entry.charsAfter, 0),
|
|
177
|
-
tokensRemoved: entries.reduce((sum, entry) => sum + entry.tokensBefore - entry.tokensAfter, 0),
|
|
178
|
-
}
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
function emptyResult(): PruneResult {
|
|
182
|
-
return { pruned: [], charsRemoved: 0, tokensRemoved: 0 }
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
export {
|
|
186
|
-
onlyTextBlock,
|
|
187
|
-
onlyTextBlocks,
|
|
188
|
-
countToolContent,
|
|
189
|
-
exactTokens,
|
|
190
|
-
sameProviderMeasurementKey,
|
|
191
|
-
unavailableCount,
|
|
192
|
-
recoveryMarker,
|
|
193
|
-
summarize,
|
|
194
|
-
emptyResult,
|
|
195
|
-
measureContent,
|
|
196
|
-
pressureCost,
|
|
197
|
-
nativePruneContent,
|
|
198
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* Pure content-analysis functions extracted from ToolResultPruner.
|
|
3
|
+
*
|
|
4
|
+
* Every function here has ZERO `this` dependency — they receive all inputs
|
|
5
|
+
* as explicit arguments. Grouped by natural cohesion (content blocks →
|
|
6
|
+
* token counting → recovery helpers).
|
|
7
|
+
*
|
|
8
|
+
* @module dsh-context-compression-improved/pruner/content
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type { ContentBlock } from '@deepseek-ai/dsh-llm'
|
|
12
|
+
import type {
|
|
13
|
+
CompactionTokenView,
|
|
14
|
+
ProviderMeasurementKey,
|
|
15
|
+
TokenCount,
|
|
16
|
+
} from '../runtime/measurement.ts'
|
|
17
|
+
import { countExactCanonicalTextFields } from '../runtime/token-count.ts'
|
|
18
|
+
import { codePointLength, PRUNE_MARKER } from '../runtime/config.ts'
|
|
19
|
+
import type { PrunedEntry, PruneResult } from '../runtime/types.ts'
|
|
20
|
+
import { RICH_BLOCK_PRESSURE_COST } from './tuning.ts'
|
|
21
|
+
|
|
22
|
+
// ── Content-block predicates ────────────────────────────────────────────
|
|
23
|
+
|
|
24
|
+
function onlyTextBlock(blocks: readonly ContentBlock[]): Extract<ContentBlock, { type: 'text' }> | null {
|
|
25
|
+
return blocks.length === 1 && blocks[0]?.type === 'text' ? blocks[0] : null
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function onlyTextBlocks(blocks: readonly ContentBlock[]): readonly Extract<ContentBlock, { type: 'text' }>[] | null {
|
|
29
|
+
return blocks.every((block): block is Extract<ContentBlock, { type: 'text' }> => block.type === 'text')
|
|
30
|
+
? blocks
|
|
31
|
+
: null
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// ── Token counting ──────────────────────────────────────────────────────
|
|
35
|
+
|
|
36
|
+
function countToolContent(blocks: readonly ContentBlock[], view: CompactionTokenView): TokenCount {
|
|
37
|
+
const text = onlyTextBlocks(blocks)
|
|
38
|
+
if (text === null) return unavailableCount('tool result contains unsupported rich content')
|
|
39
|
+
return countExactCanonicalTextFields(
|
|
40
|
+
text.map(block => block.text),
|
|
41
|
+
candidate => view.countCanonicalText(candidate),
|
|
42
|
+
'tool result replacement',
|
|
43
|
+
)
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function exactTokens(count: TokenCount): number | undefined {
|
|
47
|
+
return count.kind === 'exact-tokenizer' ? count.tokens : undefined
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// ── Provider measurement key comparison ─────────────────────────────────
|
|
51
|
+
|
|
52
|
+
function sameProviderMeasurementKey(
|
|
53
|
+
left: Readonly<ProviderMeasurementKey>,
|
|
54
|
+
right: Readonly<ProviderMeasurementKey>,
|
|
55
|
+
): boolean {
|
|
56
|
+
return left.provider === right.provider
|
|
57
|
+
&& left.baseUrlClass === right.baseUrlClass
|
|
58
|
+
&& left.apiRoute === right.apiRoute
|
|
59
|
+
&& left.modelId === right.modelId
|
|
60
|
+
&& left.requestTemplateRevision === right.requestTemplateRevision
|
|
61
|
+
&& left.tokenizerRevision === right.tokenizerRevision
|
|
62
|
+
&& left.modality === right.modality
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// ── Token helpers ───────────────────────────────────────────────────────
|
|
66
|
+
|
|
67
|
+
function unavailableCount(reason: string): TokenCount {
|
|
68
|
+
return Object.freeze({ kind: 'unavailable', reason })
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// ── Recovery markers ────────────────────────────────────────────────────
|
|
72
|
+
|
|
73
|
+
function recoveryMarker(sourceRef: string, label: string, startLine?: number): string {
|
|
74
|
+
const hint = startLine === undefined
|
|
75
|
+
? 'use context_compression_retrieve if needed'
|
|
76
|
+
: `retrieve with context_compression_retrieve({"ref":"${sourceRef}","start_line":${String(startLine)},"max_lines":80})`
|
|
77
|
+
return `\n\n[... ${label}; source=${sourceRef}; ${hint} ...]\n\n`
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// ── Content measurement ─────────────────────────────────────────────────
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Measure text content in Unicode code points; non-text blocks cost zero.
|
|
84
|
+
* @param blocks - tool-result content to measure.
|
|
85
|
+
* @returns total Unicode code points across text blocks.
|
|
86
|
+
*/
|
|
87
|
+
function measureContent(blocks: readonly ContentBlock[]): number {
|
|
88
|
+
let chars = 0
|
|
89
|
+
for (const block of blocks) {
|
|
90
|
+
if (block.type === 'text') chars += codePointLength(block.text)
|
|
91
|
+
}
|
|
92
|
+
return chars
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function pressureCost(blocks: readonly ContentBlock[]): number {
|
|
96
|
+
let cost = 0
|
|
97
|
+
for (const block of blocks) {
|
|
98
|
+
switch (block.type) {
|
|
99
|
+
case 'text':
|
|
100
|
+
case 'reasoning':
|
|
101
|
+
cost += codePointLength(block.text)
|
|
102
|
+
break
|
|
103
|
+
case 'tool-call':
|
|
104
|
+
cost += RICH_BLOCK_PRESSURE_COST
|
|
105
|
+
+ codePointLength(block.name)
|
|
106
|
+
+ codePointLength(block.arguments)
|
|
107
|
+
break
|
|
108
|
+
default: {
|
|
109
|
+
// ContentBlockMap is merge-extensible. Unknown model-visible blocks
|
|
110
|
+
// scale with their durable JSON payload instead of receiving a fixed
|
|
111
|
+
// token that a large provider block could bypass.
|
|
112
|
+
const serialized = JSON.stringify(block)
|
|
113
|
+
cost += Math.max(RICH_BLOCK_PRESSURE_COST, codePointLength(serialized))
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return cost
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// ── Native content pruning ──────────────────────────────────────────────
|
|
121
|
+
|
|
122
|
+
function nativePruneContent(
|
|
123
|
+
blocks: readonly ContentBlock[],
|
|
124
|
+
thresholdChars: number,
|
|
125
|
+
headChars: number,
|
|
126
|
+
tailChars: number,
|
|
127
|
+
marker: string | ((startLine: number) => string) = PRUNE_MARKER,
|
|
128
|
+
): ContentBlock[] | null {
|
|
129
|
+
const totalChars = measureContent(blocks)
|
|
130
|
+
if (totalChars <= thresholdChars) return null
|
|
131
|
+
const markerChars = codePointLength(typeof marker === 'function' ? marker(1) : marker)
|
|
132
|
+
const safeHead = Math.max(0, Math.min(headChars, thresholdChars - markerChars))
|
|
133
|
+
const safeTail = Math.max(0, Math.min(tailChars, thresholdChars - markerChars - safeHead))
|
|
134
|
+
const removedStart = safeHead
|
|
135
|
+
const removedEnd = totalChars - safeTail
|
|
136
|
+
const pruned: ContentBlock[] = []
|
|
137
|
+
let consumed = 0
|
|
138
|
+
let markerInserted = false
|
|
139
|
+
// '\n' count in the RAW event text before the current block (retrieve scans
|
|
140
|
+
// the original event; blocks are joined with '\n'). Line numbers therefore
|
|
141
|
+
// never depend on what the pruning removed.
|
|
142
|
+
let newlinesBefore = 0
|
|
143
|
+
for (const block of blocks) {
|
|
144
|
+
if (block.type !== 'text') {
|
|
145
|
+
pruned.push(block)
|
|
146
|
+
newlinesBefore += 1
|
|
147
|
+
continue
|
|
148
|
+
}
|
|
149
|
+
const points = Array.from(block.text)
|
|
150
|
+
const blockStart = consumed
|
|
151
|
+
const blockEnd = blockStart + points.length
|
|
152
|
+
const headEnd = Math.min(points.length, Math.max(0, removedStart - blockStart))
|
|
153
|
+
const tailStart = Math.min(points.length, Math.max(0, removedEnd - blockStart))
|
|
154
|
+
const intersectsRemoved = blockStart < removedEnd && blockEnd > removedStart
|
|
155
|
+
// The elided region starts on the event line after the retained head.
|
|
156
|
+
const headText = points.slice(0, headEnd).join('')
|
|
157
|
+
const insertion = intersectsRemoved && !markerInserted && typeof marker === 'function'
|
|
158
|
+
? marker(1 + newlinesBefore + headText.split('\n').length - 1)
|
|
159
|
+
: intersectsRemoved && !markerInserted && typeof marker === 'string' ? marker : ''
|
|
160
|
+
if (insertion !== '') markerInserted = true
|
|
161
|
+
const text = points.slice(0, headEnd).join('') + insertion + points.slice(tailStart).join('')
|
|
162
|
+
if (text !== '') pruned.push({ ...block, text })
|
|
163
|
+
newlinesBefore += block.text.split('\n').length - 1 + 1
|
|
164
|
+
consumed = blockEnd
|
|
165
|
+
}
|
|
166
|
+
if (!markerInserted) return null
|
|
167
|
+
const charsAfter = measureContent(pruned)
|
|
168
|
+
return charsAfter <= thresholdChars && charsAfter < totalChars ? pruned : null
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// ── Result aggregation ──────────────────────────────────────────────────
|
|
172
|
+
|
|
173
|
+
function summarize(entries: readonly PrunedEntry[]): PruneResult {
|
|
174
|
+
return {
|
|
175
|
+
pruned: entries,
|
|
176
|
+
charsRemoved: entries.reduce((sum, entry) => sum + entry.charsBefore - entry.charsAfter, 0),
|
|
177
|
+
tokensRemoved: entries.reduce((sum, entry) => sum + entry.tokensBefore - entry.tokensAfter, 0),
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function emptyResult(): PruneResult {
|
|
182
|
+
return { pruned: [], charsRemoved: 0, tokensRemoved: 0 }
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export {
|
|
186
|
+
onlyTextBlock,
|
|
187
|
+
onlyTextBlocks,
|
|
188
|
+
countToolContent,
|
|
189
|
+
exactTokens,
|
|
190
|
+
sameProviderMeasurementKey,
|
|
191
|
+
unavailableCount,
|
|
192
|
+
recoveryMarker,
|
|
193
|
+
summarize,
|
|
194
|
+
emptyResult,
|
|
195
|
+
measureContent,
|
|
196
|
+
pressureCost,
|
|
197
|
+
nativePruneContent,
|
|
198
|
+
}
|
|
@@ -1,50 +1,57 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Consolidated per-session mutable state for {@link ToolResultPruner}.
|
|
3
|
-
*
|
|
4
|
-
* Every field is a WeakMap keyed by Session, keeping the service
|
|
5
|
-
* stateless across sessions and safe under GC.
|
|
6
|
-
*/
|
|
7
|
-
|
|
8
|
-
import type { Session } from '@deepseek-ai/dsh-session'
|
|
9
|
-
import type { DedupeTable } from '../runtime/tokenpilot/dedup.ts'
|
|
10
|
-
import type { EstimatorFailures } from '../runtime/tokenpilot/estimator.ts'
|
|
11
|
-
import type { SideChannel } from '../runtime/tokenpilot/sidechannel.ts'
|
|
12
|
-
import type {
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Consolidated per-session mutable state for {@link ToolResultPruner}.
|
|
3
|
+
*
|
|
4
|
+
* Every field is a WeakMap keyed by Session, keeping the service
|
|
5
|
+
* stateless across sessions and safe under GC.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type { Session } from '@deepseek-ai/dsh-session'
|
|
9
|
+
import type { DedupeTable } from '../runtime/tokenpilot/dedup.ts'
|
|
10
|
+
import type { EstimatorFailures } from '../runtime/tokenpilot/estimator.ts'
|
|
11
|
+
import type { SideChannel } from '../runtime/tokenpilot/sidechannel.ts'
|
|
12
|
+
import type { PendingIntentFold } from '../runtime/tokenpilot/intent-fold.ts'
|
|
13
|
+
import type {
|
|
14
|
+
ContextCompressionSettings,
|
|
15
|
+
ResolvedConfig,
|
|
16
|
+
} from '../runtime/types.ts'
|
|
17
|
+
|
|
18
|
+
/** Mutable per-session state bag used inside {@link ToolResultPruner}. */
|
|
19
|
+
export interface PrunerState {
|
|
20
|
+
/** Resolved immutable deployment configuration. */
|
|
21
|
+
readonly config: ResolvedConfig
|
|
22
|
+
|
|
23
|
+
/** Complete canonical setting document frozen when each Session first reaches this root service. */
|
|
24
|
+
readonly sessionSettings: WeakMap<Session, ContextCompressionSettings>
|
|
25
|
+
/** Original result seqs whose first-exposure KEEP/REDUCE decision has committed. */
|
|
26
|
+
readonly firstExposure: WeakMap<Session, Set<number>>
|
|
27
|
+
/** Result seqs permanently exempt from further reduction (recovery outputs and registered equivalents). */
|
|
28
|
+
readonly recoveryExemptions: WeakMap<Session, Set<number>>
|
|
29
|
+
/** Per-session canonical-content hash index backing tokenpilot-inspired dedupe. */
|
|
30
|
+
readonly dedupeTables: WeakMap<Session, DedupeTable>
|
|
31
|
+
/** Advisory estimator verdicts consumed by the read-state classification. */
|
|
32
|
+
readonly estimatorVerdicts: WeakMap<Session, Map<number, boolean>>
|
|
33
|
+
/** Per-session estimator failure backoff state. */
|
|
34
|
+
readonly estimatorFailures: WeakMap<Session, EstimatorFailures>
|
|
35
|
+
/** Runtime prerequisite warnings deduplicated per Session and failure key. */
|
|
36
|
+
readonly warnedFailures: WeakMap<Session, Set<string>>
|
|
37
|
+
/** Last Adaptive postflight attempt emitted per Session; keeps diagnostics bounded and independent. */
|
|
38
|
+
readonly postflightDiagnostics: WeakMap<Session, string>
|
|
39
|
+
/** Current pre-step chain identity, shared by this producer and downstream compaction-basic. */
|
|
40
|
+
readonly activeRequestBoundaries: WeakMap<Session, object>
|
|
41
|
+
/** Boundary identity that already attempted one fully preflighted TailTrim publication. */
|
|
42
|
+
readonly tailTrimBoundaryAttempts: WeakMap<Session, object>
|
|
43
|
+
/** Last effective policy audit key emitted for each Session. */
|
|
44
|
+
readonly policyResolutionAudits: WeakMap<Session, string>
|
|
45
|
+
/** Last observed turn index per Session: the monotonic clock for advisory records. */
|
|
46
|
+
readonly turnClocks: WeakMap<Session, number>
|
|
47
|
+
/** Estimator-reported remaining turns Ŝ per Session; advisory only. */
|
|
48
|
+
readonly estimatorRemainingTurns: WeakMap<Session, number>
|
|
49
|
+
/** Per-session advisor side channel, constructed once with the advisor overrides. */
|
|
50
|
+
readonly advisorChannels: WeakMap<Session, SideChannel>
|
|
51
|
+
/** Staged intent fold awaiting the next pressure round (at most one per session). */
|
|
52
|
+
readonly pendingIntentFolds: WeakMap<Session, PendingIntentFold>
|
|
53
|
+
/** Landed intent-fold seqs: fold-once, never reconsidered by any later stage. */
|
|
54
|
+
readonly intentFoldedSeqs: WeakMap<Session, Set<number>>
|
|
55
|
+
/** Live-surface tokens when the last intent fold landed (growth-gate baseline). */
|
|
56
|
+
readonly intentBaselines: WeakMap<Session, number>
|
|
57
|
+
}
|