dsh-context-compression-improved 0.8.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.gitattributes +2 -2
- package/.githooks/pre-push +37 -37
- package/.github/workflows/ci.yml +39 -39
- package/CHANGELOG.de.md +41 -0
- package/CHANGELOG.es.md +41 -0
- package/CHANGELOG.fr.md +42 -0
- package/CHANGELOG.it.md +41 -0
- package/CHANGELOG.ja.md +35 -0
- package/CHANGELOG.ko.md +34 -0
- package/CHANGELOG.md +40 -0
- package/CHANGELOG.ru.md +37 -0
- package/CHANGELOG.zh.md +32 -0
- package/CONTRIBUTING.md +22 -22
- package/LICENSE +21 -21
- package/README.de.md +7 -9
- package/README.es.md +7 -9
- package/README.fr.md +7 -9
- package/README.it.md +7 -9
- package/README.ja.md +6 -2
- package/README.ko.md +6 -2
- package/README.md +96 -98
- package/README.ru.md +7 -9
- package/README.zh.md +89 -85
- package/SECURITY.md +18 -18
- package/THIRD_PARTY_NOTICES.md +14 -14
- package/docs/compat-0.1.5-report.md +77 -77
- package/docs/installation.de.md +5 -5
- package/docs/installation.es.md +5 -5
- package/docs/installation.fr.md +5 -5
- package/docs/installation.it.md +5 -5
- package/docs/installation.ja.md +5 -5
- package/docs/installation.ko.md +5 -5
- package/docs/installation.md +5 -5
- package/docs/installation.ru.md +5 -5
- package/docs/installation.zh.md +5 -5
- package/docs/repair-log.md +657 -657
- package/package.json +23 -22
- package/packages/selector/LICENSE +21 -21
- package/packages/selector/README.md +26 -26
- package/packages/selector/README.zh.md +24 -24
- package/packages/selector/THIRD_PARTY_NOTICES.md +32 -32
- package/packages/selector/cordis.patch.yml +27 -27
- package/packages/selector/docs/history-tool-call-working-set-spec.md +112 -112
- package/packages/selector/docs/native-tool-result-selector-spec.md +34 -34
- package/packages/selector/docs/subagent-cache-reuse-spec.md +46 -46
- package/packages/selector/dsh.plugin.json +16 -16
- package/packages/selector/lib/client.js +178 -21
- package/packages/selector/lib/host-generation.js +62 -0
- package/packages/selector/lib/index.js +208 -1
- package/packages/selector/lib/invariant.js +1 -1
- package/packages/selector/lib/pruner.js +41 -43
- package/packages/selector/lib/style.css +53 -53
- package/packages/selector/lib/tail-trim.js +73 -4
- package/packages/selector/package.json +80 -21
- package/packages/selector/screenshots.json +3 -3
- package/packages/selector/src/client/CustomPolicyEditor.tsx +216 -216
- package/packages/selector/src/client/EstimatorControls.tsx +277 -277
- package/packages/selector/src/client/bridge-scope.ts +125 -0
- package/packages/selector/src/client/index.ts +109 -31
- package/packages/selector/src/client/monitor-fab.ts +0 -2
- package/packages/selector/src/client/preset-options.ts +88 -88
- package/packages/selector/src/client/scope-face.ts +24 -24
- package/packages/selector/src/compat/host-generation.ts +96 -0
- package/packages/selector/src/compat/settings-lease.ts +108 -0
- package/packages/selector/src/compat/tool-result.ts +91 -0
- package/packages/selector/src/css-modules.d.ts +6 -6
- package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -205
- package/packages/selector/src/estimator-catalog.ts +104 -104
- package/packages/selector/src/index.ts +8 -0
- package/packages/selector/src/invariant.ts +113 -113
- package/packages/selector/src/preset-overlay.ts +626 -626
- package/packages/selector/src/pruner/content.ts +198 -198
- package/packages/selector/src/pruner/session.ts +97 -96
- package/packages/selector/src/pruner/tuning.ts +23 -23
- package/packages/selector/src/pruner/types.ts +78 -78
- package/packages/selector/src/pruner.ts +45 -40
- package/packages/selector/src/runtime/adaptive-cost.ts +205 -205
- package/packages/selector/src/runtime/custom-policy.ts +278 -278
- package/packages/selector/src/runtime/deepseek-official-pricing.ts +298 -298
- package/packages/selector/src/runtime/deepseek-v4-vision-tokens.ts +254 -254
- package/packages/selector/src/runtime/measurement.ts +431 -431
- package/packages/selector/src/runtime/reducers.ts +1674 -1674
- package/packages/selector/src/runtime/retrieve.ts +7 -3
- package/packages/selector/src/runtime/session-events.ts +30 -30
- package/packages/selector/src/runtime/tail-trim.ts +175 -165
- package/packages/selector/src/runtime/token-count.ts +72 -72
- package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -419
- package/packages/selector/src/runtime/tokenpilot/benefit.ts +200 -200
- package/packages/selector/src/runtime/tokenpilot/dedup.ts +81 -81
- package/packages/selector/src/runtime/tokenpilot/estimator.ts +151 -151
- package/packages/selector/src/runtime/tokenpilot/locator.ts +128 -128
- package/packages/selector/src/runtime/tokenpilot/read-state.ts +98 -98
- package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +303 -303
- package/packages/selector/src/runtime/toolclass.ts +103 -103
- package/packages/selector/src/runtime/value.ts +48 -48
- package/packages/selector/src/settings-bridge.ts +175 -0
- package/packages/selector/tests/advisor-report.host.spec.ts +223 -223
- package/packages/selector/tests/built/client-artifact.spec.ts +6 -9
- package/packages/selector/tests/cache-prefix-audit.spec.ts +123 -123
- package/packages/selector/tests/code-skeleton.client.spec.ts +98 -94
- package/packages/selector/tests/compat/compat-narrow-waist.spec.ts +150 -0
- package/packages/selector/tests/custom-contract.client.spec.ts +226 -223
- package/packages/selector/tests/estimator-catalog.spec.ts +70 -70
- package/packages/selector/tests/estimator-route-registration.host.spec.ts +199 -194
- package/packages/selector/tests/helpers/legacy-namespace.ts +35 -35
- package/packages/selector/tests/helpers/legacy-settings/index.ts +15 -15
- package/packages/selector/tests/helpers/legacy-settings/legacy/provider.d.ts +41 -41
- package/packages/selector/tests/helpers/legacy-settings/legacy/provider.js +647 -647
- package/packages/selector/tests/helpers/legacy-settings/legacy/redact.js +78 -78
- package/packages/selector/tests/helpers/legacy-settings/legacy/util-values.js +234 -234
- package/packages/selector/tests/host-preset-overlay.host.spec.ts +204 -204
- package/packages/selector/tests/preset-options-write.client.spec.ts +192 -188
- package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +200 -200
- package/packages/selector/tests/preset-overlay.host.spec.ts +246 -246
- package/packages/selector/tests/public/package-contract.client.spec.ts +11 -3
- package/packages/selector/tests/runtime/adaptive-cost.spec.ts +167 -167
- package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +230 -230
- package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -272
- package/packages/selector/tests/runtime/advisor.spec.ts +226 -226
- package/packages/selector/tests/runtime/auto-compact-config.spec.ts +523 -523
- package/packages/selector/tests/runtime/char-basis.spec.ts +30 -30
- package/packages/selector/tests/runtime/code-skeleton.spec.ts +152 -152
- package/packages/selector/tests/runtime/deepseek-official-pricing.spec.ts +186 -186
- package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +122 -122
- package/packages/selector/tests/runtime/deepseek-v4-vision-tokens.spec.ts +122 -122
- package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +96 -96
- package/packages/selector/tests/runtime/fixtures/profile-baseline.json +273 -273
- package/packages/selector/tests/runtime/fixtures/tokenizer-golden.json +106 -106
- package/packages/selector/tests/runtime/fixtures/vision-golden.json +459 -459
- package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +74 -74
- package/packages/selector/tests/runtime/html-reducer.spec.ts +212 -212
- package/packages/selector/tests/runtime/line-mapping.spec.ts +153 -153
- package/packages/selector/tests/runtime/prose-reducers.spec.ts +133 -133
- package/packages/selector/tests/runtime/public/public-runtime.spec.ts +3 -3
- package/packages/selector/tests/runtime/read-input-cap.spec.ts +33 -33
- package/packages/selector/tests/runtime/search-reducer.spec.ts +110 -110
- package/packages/selector/tests/runtime/session-events.spec.ts +27 -27
- package/packages/selector/tests/runtime/sidechannel.spec.ts +241 -241
- package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +159 -159
- package/packages/selector/tests/runtime/tokenizer-golden.spec.ts +53 -53
- package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +217 -217
- package/packages/selector/tests/runtime/tokenpilot/dedup.spec.ts +52 -52
- package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +79 -79
- package/packages/selector/tests/runtime/tokenpilot/locator.spec.ts +76 -76
- package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +116 -116
- package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +82 -82
- package/packages/selector/tests/runtime/toolclass.spec.ts +156 -156
- package/packages/selector/tests/runtime/value.spec.ts +23 -23
- package/packages/selector/tests/settings-seat.client.spec.ts +45 -7
- package/packages/selector/tests/standing-generation.host.spec.ts +724 -724
- package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +269 -269
- package/packages/selector/tests/support/cache-prefix-audit.ts +105 -105
- package/packages/selector/tests/support/mock-adapter.ts +37 -37
- package/packages/selector/tests/support/ui-primitives.tsx +34 -34
- package/packages/selector/tsconfig.json +11 -11
- package/packages/selector/tsdown.client.config.ts +102 -102
- package/packages/selector/tsdown.config.ts +20 -20
- package/scripts/capture-profile-baseline.mjs +42 -42
- package/scripts/generate-tokenizer-fixtures.py +81 -81
- package/scripts/generate-vision-fixtures.py +208 -208
- package/scripts/hosts.mjs +74 -0
- package/scripts/packed-components-smoke.mjs +763 -732
- package/scripts/packed-install-e2e.mjs +1330 -1273
- package/scripts/sync-hosts.mjs +174 -0
- package/scripts/toolclass-corpus-replay.mjs +281 -281
- package/scripts/verify-release.mjs +335 -318
- package/tsconfig.base.json +18 -18
- package/tsconfig.json +7 -7
- package/tsconfig.tests.json +15 -15
- package/vitest.built.config.ts +9 -9
- package/vitest.config.ts +46 -43
|
@@ -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 ? 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,96 +1,97 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Pure session-scanning functions extracted from ToolResultPruner.
|
|
3
|
-
*
|
|
4
|
-
* Every function here has ZERO `this` dependency — they receive all inputs
|
|
5
|
-
* as explicit arguments and only read session events.
|
|
6
|
-
*
|
|
7
|
-
* @module dsh-context-compression-improved/pruner/session
|
|
8
|
-
*/
|
|
9
|
-
|
|
10
|
-
import type { Session } from '@deepseek-ai/dsh-session'
|
|
11
|
-
import { sessionEvents } from '../runtime/session-events.ts'
|
|
12
|
-
import { deepSeekV4TokenizerForModel } from '../deepseek-v4-tokenizer.ts'
|
|
13
|
-
import
|
|
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
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
//
|
|
66
|
-
|
|
67
|
-
const
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
//
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Pure session-scanning functions extracted from ToolResultPruner.
|
|
3
|
+
*
|
|
4
|
+
* Every function here has ZERO `this` dependency — they receive all inputs
|
|
5
|
+
* as explicit arguments and only read session events.
|
|
6
|
+
*
|
|
7
|
+
* @module dsh-context-compression-improved/pruner/session
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type { Session } from '@deepseek-ai/dsh-session'
|
|
11
|
+
import { sessionEvents } from '../runtime/session-events.ts'
|
|
12
|
+
import { deepSeekV4TokenizerForModel } from '../deepseek-v4-tokenizer.ts'
|
|
13
|
+
import { viewToolResult } from '../compat/tool-result.ts'
|
|
14
|
+
import type { SnapshotCandidate, PlannedReplacement, HistoryPlanOutcome } from './types.ts'
|
|
15
|
+
|
|
16
|
+
/** Check whether the session currently has an open (unterminated) turn. */
|
|
17
|
+
function hasOpenTurn(session: Session): boolean {
|
|
18
|
+
let open = false
|
|
19
|
+
for (const event of sessionEvents(session)) {
|
|
20
|
+
if (event.type === 'turn/start') open = true
|
|
21
|
+
else if (event.type === 'turn/end') open = false
|
|
22
|
+
}
|
|
23
|
+
return open
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Walk the tool-result source chain to find the root result seq. */
|
|
27
|
+
function rootToolResultSeq(session: Session, seq: number): number {
|
|
28
|
+
const events = sessionEvents(session)
|
|
29
|
+
let current = seq
|
|
30
|
+
const seen = new Set<number>()
|
|
31
|
+
while (!seen.has(current)) {
|
|
32
|
+
seen.add(current)
|
|
33
|
+
const event = events[current]
|
|
34
|
+
if (event?.type !== 'tool/result' || typeof event.surfaceOp !== 'object') return current
|
|
35
|
+
const previous = event.sourceEventSeqs?.[0]
|
|
36
|
+
if (previous === undefined) return current
|
|
37
|
+
current = previous
|
|
38
|
+
}
|
|
39
|
+
return seq
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Build a session:// event reference string for a given seq. */
|
|
43
|
+
function sourceRef(session: Session, seq: number): string {
|
|
44
|
+
return `session://${session.id}/event/${String(seq)}`
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Find the latest completed step number for a given turn. */
|
|
48
|
+
function latestCompletedToolStep(session: Session, turn: number): number | undefined {
|
|
49
|
+
let latest: number | undefined
|
|
50
|
+
for (const event of sessionEvents(session)) {
|
|
51
|
+
if (event.type === 'step/end' && event.data.turn === turn) latest = event.data.step
|
|
52
|
+
}
|
|
53
|
+
return latest
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Routed provider/model when the durable request header names one route. */
|
|
57
|
+
function routeAuditFact(session: Session): { provider: string, model: string } | undefined {
|
|
58
|
+
const header = session.requestHeader()?.config
|
|
59
|
+
if (header === undefined || header.provider.length === 0 || header.model.length === 0) return undefined
|
|
60
|
+
return { provider: header.provider, model: header.model }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Bundled tokenizer identity for one route, when the route is eligible. */
|
|
64
|
+
function tokenizerAuditFact(route: { provider: string, model: string }): { tokenizer: { repository: string, revision: string } } {
|
|
65
|
+
// Reuse the measurement eligibility boundary: a DeepSeek model id routed
|
|
66
|
+
// through another provider never used the bundled tokenizer.
|
|
67
|
+
const eligible = route.provider === 'deepseek' || route.provider === 'deepseek-official'
|
|
68
|
+
const identity = eligible ? deepSeekV4TokenizerForModel(route.model)?.countText('') : undefined
|
|
69
|
+
if (identity?.kind === 'exact-tokenizer') {
|
|
70
|
+
return { tokenizer: { repository: identity.tokenizerId, revision: identity.tokenizerRevision } }
|
|
71
|
+
}
|
|
72
|
+
return { tokenizer: { repository: 'unavailable', revision: 'unavailable' } }
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Check whether a snapshot candidate represents an error result. */
|
|
76
|
+
function isError(candidate: SnapshotCandidate): boolean {
|
|
77
|
+
// 0.1.7-rc.2: tool results are first-class `tool`-role messages — `isError`
|
|
78
|
+
// moved from the result block onto the message itself. The generation-
|
|
79
|
+
// gated triple view resolves the axis (legacy envelope: the wrapper block).
|
|
80
|
+
return viewToolResult(candidate.event.data.message).isError || candidate.event.data.error !== undefined
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Wrap a plan list into a HistoryPlanOutcome. */
|
|
84
|
+
function historyOutcome(plans: readonly PlannedReplacement[]): HistoryPlanOutcome {
|
|
85
|
+
return { kind: 'planned', plans: [...plans] }
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export {
|
|
89
|
+
hasOpenTurn,
|
|
90
|
+
rootToolResultSeq,
|
|
91
|
+
sourceRef,
|
|
92
|
+
latestCompletedToolStep,
|
|
93
|
+
routeAuditFact,
|
|
94
|
+
tokenizerAuditFact,
|
|
95
|
+
isError,
|
|
96
|
+
historyOutcome,
|
|
97
|
+
}
|
|
@@ -1,23 +1,23 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Tuning constants and pure helper functions for the context-compression pruner.
|
|
3
|
-
*
|
|
4
|
-
* These are stateless, session-independent, and safe to import from any
|
|
5
|
-
* pruner sub-module without creating circular dependencies.
|
|
6
|
-
*/
|
|
7
|
-
|
|
8
|
-
/** Line-feed character used as the canonical newline separator. */
|
|
9
|
-
export const BS = String.fromCharCode(10)
|
|
10
|
-
|
|
11
|
-
/** Count the lines present in the original but absent from the replacement. */
|
|
12
|
-
export function countOmittedLines(original: string, replacement: string): number | undefined {
|
|
13
|
-
const originalLines = original.split(BS).length
|
|
14
|
-
const replacementLines = replacement.split(BS).length
|
|
15
|
-
const omitted = originalLines - replacementLines
|
|
16
|
-
return omitted > 0 ? omitted : undefined
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
/** Minimum token-equivalent cost charged for every rich content block. */
|
|
20
|
-
export const RICH_BLOCK_PRESSURE_COST = 256
|
|
21
|
-
|
|
22
|
-
/** Routed-context utilization required before capacity-pressure History may age sent history. */
|
|
23
|
-
export const CAPACITY_PRESSURE_RATIO = 0.7
|
|
1
|
+
/**
|
|
2
|
+
* Tuning constants and pure helper functions for the context-compression pruner.
|
|
3
|
+
*
|
|
4
|
+
* These are stateless, session-independent, and safe to import from any
|
|
5
|
+
* pruner sub-module without creating circular dependencies.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/** Line-feed character used as the canonical newline separator. */
|
|
9
|
+
export const BS = String.fromCharCode(10)
|
|
10
|
+
|
|
11
|
+
/** Count the lines present in the original but absent from the replacement. */
|
|
12
|
+
export function countOmittedLines(original: string, replacement: string): number | undefined {
|
|
13
|
+
const originalLines = original.split(BS).length
|
|
14
|
+
const replacementLines = replacement.split(BS).length
|
|
15
|
+
const omitted = originalLines - replacementLines
|
|
16
|
+
return omitted > 0 ? omitted : undefined
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Minimum token-equivalent cost charged for every rich content block. */
|
|
20
|
+
export const RICH_BLOCK_PRESSURE_COST = 256
|
|
21
|
+
|
|
22
|
+
/** Routed-context utilization required before capacity-pressure History may age sent history. */
|
|
23
|
+
export const CAPACITY_PRESSURE_RATIO = 0.7
|