dsh-context-compression-improved 0.9.0 → 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/CHANGELOG.md +56 -0
- package/package.json +2 -1
- package/packages/selector/dsh.plugin.json +1 -1
- package/packages/selector/lib/client.d.ts +1 -0
- package/packages/selector/lib/client.js +86 -32
- 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 +336 -21
- package/packages/selector/package.json +1 -1
- package/packages/selector/src/client/index.ts +55 -20
- 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 +120 -16
- package/packages/selector/src/runtime/config.ts +1 -1
- package/packages/selector/src/runtime/measurement.ts +14 -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
- package/scripts/cell-browser-e2e.mjs +354 -0
|
@@ -13,7 +13,22 @@ import type { Context } from '@deepseek-ai/cordis'
|
|
|
13
13
|
import z from '@deepseek-ai/schemastery'
|
|
14
14
|
import { createUserMessage, freezeMessage } from '@deepseek-ai/dsh-llm'
|
|
15
15
|
import type { ContentBlock, ToolCallId, UserMessage } from '@deepseek-ai/dsh-llm'
|
|
16
|
-
|
|
16
|
+
// ≤0.1.1 宿主 loader 模块表的 dsh-session 没有 SessionSeq 运行时导出——静态
|
|
17
|
+
// named import 在 ESM 链接期即炸,loader entry(tool-result-pruner)mount 失败
|
|
18
|
+
// 连累整个 standard 预设(会话 resume 全挂,2026-10-08 五格 0.1.0/0.1.1 实证)。
|
|
19
|
+
// namespace 软取(链接零失败)+ 恒等回退:老线 session 事件 seq 本就是裸 number,
|
|
20
|
+
// 身份封印仅是新线防呆。CJS interop 形态(named 挂 default 下)一并兼容。
|
|
21
|
+
import * as dshSessionNamespace from '@deepseek-ai/dsh-session'
|
|
22
|
+
import type { SessionSeq as SessionSeqBrand } from '@deepseek-ai/dsh-session'
|
|
23
|
+
const dshSessionSoft = dshSessionNamespace as unknown as {
|
|
24
|
+
SessionSeq?: (value: number) => SessionSeqBrand
|
|
25
|
+
default?: { SessionSeq?: (value: number) => SessionSeqBrand }
|
|
26
|
+
}
|
|
27
|
+
const SessionSeqImpl =
|
|
28
|
+
dshSessionSoft.SessionSeq ??
|
|
29
|
+
dshSessionSoft.default?.SessionSeq ??
|
|
30
|
+
((value: number) => value as SessionSeqBrand)
|
|
31
|
+
const SessionSeq = SessionSeqImpl as (value: number) => SessionSeqBrand
|
|
17
32
|
|
|
18
33
|
// 0.1.7-rc.2 removed the shared 'plugin' source kind — each producer declares
|
|
19
34
|
// its own kind in its own module (official pattern: compaction's
|
|
@@ -107,6 +122,7 @@ import {
|
|
|
107
122
|
flattenPlainText,
|
|
108
123
|
} from './runtime/tokenpilot/dedup.ts'
|
|
109
124
|
import { getSavingsLedger } from './runtime/savings.ts'
|
|
125
|
+
import { projectSessionSavings } from './runtime/savings-projection.ts'
|
|
110
126
|
|
|
111
127
|
/** 节省统计配对键用原文(纯文本块才可配对;富内容返回 undefined)。 */
|
|
112
128
|
function originalTextForSavings(candidate: SnapshotCandidate): string | undefined {
|
|
@@ -213,6 +229,39 @@ declare module '@deepseek-ai/cordis' {
|
|
|
213
229
|
}
|
|
214
230
|
}
|
|
215
231
|
|
|
232
|
+
/**
|
|
233
|
+
* Cross-generation adaptation (0.2.0): the host `settings` service hands back
|
|
234
|
+
* the WHOLE entry config `{ settings: <subtree> }` instead of the settings
|
|
235
|
+
* subtree directly (older lines surfaced the subtree at the top level). The
|
|
236
|
+
* parser requires `profile`+`custom` at the root, so the wrapped shape threw
|
|
237
|
+
* "missing its complete shape" → the session failed open to `profile:'off'`,
|
|
238
|
+
* silently disabling fresh/aggregate on the desktop. Descend exactly one
|
|
239
|
+
* `{settings:<obj>}` wrapper ONLY when the root has no `profile`; every other
|
|
240
|
+
* shape is passed through untouched so the "exotic Host value must fail open
|
|
241
|
+
* to off" safety contract still holds.
|
|
242
|
+
*/
|
|
243
|
+
export function unwrapSettingsEntry(value: unknown): unknown {
|
|
244
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) return value
|
|
245
|
+
const record = value as Record<string, unknown>
|
|
246
|
+
if ('profile' in record) return value
|
|
247
|
+
const inner = record.settings
|
|
248
|
+
if (inner !== null && typeof inner === 'object' && !Array.isArray(inner)) return inner
|
|
249
|
+
return value
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Whether a fresh candidate is BELOW the fresh trigger. Uses the real token
|
|
254
|
+
* count when an exact tokenizer is available (DeepSeek routes), and otherwise
|
|
255
|
+
* falls back to the 4.0 chars/token estimate — byte-for-byte the pre-existing
|
|
256
|
+
* behavior on routes without a bundled tokenizer (e.g. local Qwen).
|
|
257
|
+
*/
|
|
258
|
+
export function freshBelowTrigger(candidate: SnapshotCandidate, policy: CompressionPolicy): boolean {
|
|
259
|
+
if (candidate.count.kind === 'exact-tokenizer') {
|
|
260
|
+
return candidate.count.tokens <= policy.freshTriggerTokens
|
|
261
|
+
}
|
|
262
|
+
return candidate.characterPressure <= charsForTokens(policy.freshTriggerTokens)
|
|
263
|
+
}
|
|
264
|
+
|
|
216
265
|
/** Mixed deterministic selector behind the existing `ctx.toolResultPruner` seam. */
|
|
217
266
|
export class ToolResultPruner extends Service {
|
|
218
267
|
static inject = ['tokenMeter']
|
|
@@ -261,6 +310,8 @@ export class ToolResultPruner extends Service {
|
|
|
261
310
|
turnClocks: new WeakMap(),
|
|
262
311
|
estimatorRemainingTurns: new WeakMap(),
|
|
263
312
|
advisorChannels: new WeakMap(),
|
|
313
|
+
intentChannels: new WeakMap(),
|
|
314
|
+
projectedSavings: new WeakSet(),
|
|
264
315
|
pendingIntentFolds: new WeakMap(),
|
|
265
316
|
intentFoldedSeqs: new WeakMap(),
|
|
266
317
|
intentBaselines: new WeakMap(),
|
|
@@ -356,6 +407,15 @@ export class ToolResultPruner extends Service {
|
|
|
356
407
|
this.contextWindowForRequest(agent.session),
|
|
357
408
|
)
|
|
358
409
|
} catch { /* 观测失败静默:面板显示陈旧/空态 */ }
|
|
410
|
+
// 仪表口径:把当前 surface 存活 seq 交给账本,离开 surface 的压缩替换
|
|
411
|
+
// 即从“当前生效毛节省”中回落(数字随压缩内容进出而涨落)。
|
|
412
|
+
this.ensureSavingsProjection(agent.session)
|
|
413
|
+
try {
|
|
414
|
+
getSavingsLedger().observeActive(
|
|
415
|
+
String(agent.session.id),
|
|
416
|
+
new Set([...agent.session.surface.nodes].map(Number)),
|
|
417
|
+
)
|
|
418
|
+
} catch { /* 观测失败静默:维持上次口径 */ }
|
|
359
419
|
// TokenPilot-inspired E1: advisory estimator pass, strictly off the
|
|
360
420
|
// synchronous chain. Verdicts only feed the next pressure pass.
|
|
361
421
|
void this.postflightEstimatorPass(agent.session, signal).catch(() => undefined)
|
|
@@ -502,6 +562,7 @@ export class ToolResultPruner extends Service {
|
|
|
502
562
|
(d) => String(d.ns) === 'context-compression-improved-bundle',
|
|
503
563
|
)?.value
|
|
504
564
|
?? settingsHost?.get?.(CONTEXT_COMPRESSION_SETTINGS_NAMESPACE as never)) as ContextCompressionSettings | undefined
|
|
565
|
+
const unwrapped = unwrapSettingsEntry(settings)
|
|
505
566
|
let resolved: ContextCompressionSettings
|
|
506
567
|
let settingsSource: 'host-settings' | 'plugin-config-fallback' = settings === undefined
|
|
507
568
|
? 'plugin-config-fallback'
|
|
@@ -515,7 +576,7 @@ export class ToolResultPruner extends Service {
|
|
|
515
576
|
// Validate the Host value BEFORE cloning: structuredClone normalizes
|
|
516
577
|
// class/exotic prototypes to Object.prototype and would otherwise
|
|
517
578
|
// erase the very boundary the parser is responsible for enforcing.
|
|
518
|
-
: parseContextCompressionSettings(
|
|
579
|
+
: parseContextCompressionSettings(unwrapped as ContextCompressionSettings)
|
|
519
580
|
} catch (error: unknown) {
|
|
520
581
|
// A malformed persisted document must fail open LOSSLESSLY: freezing the
|
|
521
582
|
// deployment default could silently re-enable lossy compression the
|
|
@@ -644,7 +705,7 @@ export class ToolResultPruner extends Service {
|
|
|
644
705
|
for (const candidate of this.snapshot(session, measureForCompaction(this.ctx, session))) {
|
|
645
706
|
if (samples.length >= 3) break
|
|
646
707
|
if (candidate.event.data.turn === undefined) continue
|
|
647
|
-
if (candidate
|
|
708
|
+
if (freshBelowTrigger(candidate, policy)) continue
|
|
648
709
|
const path = toolCallPath(candidate.call.arguments)
|
|
649
710
|
if (path === undefined) continue
|
|
650
711
|
if (isSupersededRead(events, candidate.seq, path)) continue
|
|
@@ -795,6 +856,21 @@ export class ToolResultPruner extends Service {
|
|
|
795
856
|
}
|
|
796
857
|
}
|
|
797
858
|
|
|
859
|
+
/**
|
|
860
|
+
* 重进/重启会话的懒重建:首次观测某会话时,若账本尚无该会话条目,则按会话
|
|
861
|
+
* 日志投影播种(当前生效毛节省 + 每次重读惩罚 + 原文配对键)。只做一次,
|
|
862
|
+
* fail-open;同一进程内的实时增量随后在同一条目集合上继续。
|
|
863
|
+
*/
|
|
864
|
+
private ensureSavingsProjection(session: Session): void {
|
|
865
|
+
if (this.state.projectedSavings.has(session)) return
|
|
866
|
+
this.state.projectedSavings.add(session)
|
|
867
|
+
const ledger = getSavingsLedger()
|
|
868
|
+
if (ledger.hasSession(String(session.id))) return
|
|
869
|
+
try {
|
|
870
|
+
ledger.seedProjected(String(session.id), projectSessionSavings(this.ctx, session))
|
|
871
|
+
} catch { /* 投影失败静默:面板显示空态,不影响主流程 */ }
|
|
872
|
+
}
|
|
873
|
+
|
|
798
874
|
// ─────────── Turn-tail intent summary (host-driven fold, model writes text only) ───────────
|
|
799
875
|
|
|
800
876
|
/**
|
|
@@ -837,8 +913,25 @@ export class ToolResultPruner extends Service {
|
|
|
837
913
|
|
|
838
914
|
const settingsPreset = settings.presetOptions
|
|
839
915
|
if (settingsPreset === undefined) return
|
|
840
|
-
|
|
841
|
-
|
|
916
|
+
// 写手通道复用估计器通道:`host` 走宿主 llm 路由(provider/model 可省),
|
|
917
|
+
// `direct` 才需要显式 OpenAI 兼容端点。此前无条件要求直连端点,导致
|
|
918
|
+
// host 通道下每个回合都以 'no-direct-endpoint' 提前返回,fold 永不落地。
|
|
919
|
+
const estimatorMode = settingsPreset.estimatorMode ?? ''
|
|
920
|
+
if (estimatorMode !== 'host' && estimatorMode !== 'direct') {
|
|
921
|
+
emitCompressionAudit(this.ctx.logger, {
|
|
922
|
+
schemaVersion: 1,
|
|
923
|
+
kind: 'intent-summary-outcome',
|
|
924
|
+
sessionId,
|
|
925
|
+
ok: false,
|
|
926
|
+
reason: 'no-estimator-channel',
|
|
927
|
+
turnIndex: turn,
|
|
928
|
+
latencyMs: Date.now() - started,
|
|
929
|
+
})
|
|
930
|
+
return
|
|
931
|
+
}
|
|
932
|
+
if (estimatorMode === 'direct'
|
|
933
|
+
&& (settingsPreset.estimatorBaseUrl === undefined || settingsPreset.estimatorBaseUrl.length === 0
|
|
934
|
+
|| settingsPreset.estimatorModel === undefined || settingsPreset.estimatorModel.length === 0)) {
|
|
842
935
|
emitCompressionAudit(this.ctx.logger, {
|
|
843
936
|
schemaVersion: 1,
|
|
844
937
|
kind: 'intent-summary-outcome',
|
|
@@ -876,14 +969,16 @@ export class ToolResultPruner extends Service {
|
|
|
876
969
|
|
|
877
970
|
const events = sessionEvents(session)
|
|
878
971
|
const task = collectTaskSemantics(events)
|
|
879
|
-
|
|
972
|
+
// 独立通道:写手用 30s 超时,advisor 用其自身超时——两者若共享
|
|
973
|
+
// advisorChannels,先构造者会把 mode/timeout 强加给后者。
|
|
974
|
+
let channel = this.state.intentChannels.get(session)
|
|
880
975
|
if (channel === undefined) {
|
|
881
976
|
channel = new SideChannel(this.ctx, settingsPreset, {
|
|
882
|
-
mode:
|
|
977
|
+
mode: estimatorMode,
|
|
883
978
|
timeoutMs: 30_000,
|
|
884
979
|
maxTokens: 512,
|
|
885
980
|
})
|
|
886
|
-
this.state.
|
|
981
|
+
this.state.intentChannels.set(session, channel)
|
|
887
982
|
}
|
|
888
983
|
|
|
889
984
|
const answer = await channel.ask({
|
|
@@ -1455,7 +1550,8 @@ export class ToolResultPruner extends Service {
|
|
|
1455
1550
|
return emptyResult()
|
|
1456
1551
|
}
|
|
1457
1552
|
const decisions = this.decisions(session)
|
|
1458
|
-
const
|
|
1553
|
+
const snapshot = this.snapshot(session, view)
|
|
1554
|
+
const candidates = snapshot.filter(candidate =>
|
|
1459
1555
|
typeof candidate.event.surfaceOp !== 'object'
|
|
1460
1556
|
&& candidate.event.data.turn === options.freshTurn
|
|
1461
1557
|
&& candidate.event.data.step === options.freshStep
|
|
@@ -1491,8 +1587,14 @@ export class ToolResultPruner extends Service {
|
|
|
1491
1587
|
const plans = new Map<number, PlannedReplacement>()
|
|
1492
1588
|
let freshPlanned = 0
|
|
1493
1589
|
const dedupeEnabled = policy.presetOptions?.dedupeToolResults === true
|
|
1494
|
-
|
|
1495
|
-
|
|
1590
|
+
// Token-basis max, mirroring freshBelowTrigger: exact tokenizer where
|
|
1591
|
+
// available, else the 4.0 char estimate. Drives the 'at-or-below-trigger'
|
|
1592
|
+
// audit reason on the same basis the fresh gate uses.
|
|
1593
|
+
const maxCandidateTokens = candidates.length === 0
|
|
1594
|
+
? undefined
|
|
1595
|
+
: Math.max(...candidates.map(candidate => candidate.count.kind === 'exact-tokenizer'
|
|
1596
|
+
? candidate.count.tokens
|
|
1597
|
+
: charsToTokens(candidate.characterPressure)))
|
|
1496
1598
|
if (policy.freshEnabled) {
|
|
1497
1599
|
if (candidates.some(candidate => candidate.call.name !== 'context_compression_retrieve'
|
|
1498
1600
|
&& candidate.count.kind !== 'exact-tokenizer')) {
|
|
@@ -1558,12 +1660,12 @@ export class ToolResultPruner extends Service {
|
|
|
1558
1660
|
this.auditComponent(session, policy, 'fresh', 'fresh',
|
|
1559
1661
|
policy.freshEnabled ? 'skipped' : 'disabled',
|
|
1560
1662
|
!policy.freshEnabled ? 'profile-policy'
|
|
1561
|
-
: (
|
|
1663
|
+
: (maxCandidateTokens ?? 0) <= policy.freshTriggerTokens ? 'at-or-below-trigger'
|
|
1562
1664
|
: freshPlanned > 0 && aggregatePlanned > 0 ? 'superseded-by-aggregate'
|
|
1563
1665
|
: freshPlanned === 0 ? 'no-valid-reduction'
|
|
1564
1666
|
: 'recovery-tool-unavailable', {
|
|
1565
1667
|
measurementKind: 'characters',
|
|
1566
|
-
...(
|
|
1668
|
+
...(maxCandidateTokens === undefined ? {} : { currentTokens: maxCandidateTokens }),
|
|
1567
1669
|
triggerTokens: policy.freshTriggerTokens,
|
|
1568
1670
|
targetTokens: policy.freshTargetTokens,
|
|
1569
1671
|
})
|
|
@@ -1684,7 +1786,7 @@ export class ToolResultPruner extends Service {
|
|
|
1684
1786
|
if (typeof candidate.event.surfaceOp === 'object') return null
|
|
1685
1787
|
const text = flattenPlainText(viewToolResult(candidate.event.data.message).blocks as ContentBlock[])
|
|
1686
1788
|
if (text === undefined) return null
|
|
1687
|
-
if (candidate
|
|
1789
|
+
if (freshBelowTrigger(candidate, policy)) return null
|
|
1688
1790
|
let table = this.state.dedupeTables.get(session)
|
|
1689
1791
|
if (table === undefined) {
|
|
1690
1792
|
table = new DedupeTable()
|
|
@@ -1730,7 +1832,7 @@ export class ToolResultPruner extends Service {
|
|
|
1730
1832
|
// being reconsidered after their first request.
|
|
1731
1833
|
if (typeof candidate.event.surfaceOp === 'object') return null
|
|
1732
1834
|
const resultView = viewToolResult(candidate.event.data.message)
|
|
1733
|
-
if (candidate
|
|
1835
|
+
if (freshBelowTrigger(candidate, policy)) return null
|
|
1734
1836
|
const sourceSeq = candidate.seq
|
|
1735
1837
|
const sourceRef = sourceRefFn(session, sourceSeq)
|
|
1736
1838
|
const textBlock = onlyTextBlock(resultView.blocks as ContentBlock[])
|
|
@@ -1813,7 +1915,7 @@ export class ToolResultPruner extends Service {
|
|
|
1813
1915
|
'[Tool result reduced to satisfy the completed-step aggregate budget]',
|
|
1814
1916
|
`tool: ${candidate.call.name}`,
|
|
1815
1917
|
`source: ${sourceRef}`,
|
|
1816
|
-
'
|
|
1918
|
+
'Retrieve a narrow slice via context_compression_retrieve if needed.',
|
|
1817
1919
|
].join('\n')
|
|
1818
1920
|
const plan = this.plan(
|
|
1819
1921
|
candidate,
|
|
@@ -2308,6 +2410,7 @@ export class ToolResultPruner extends Service {
|
|
|
2308
2410
|
tokensAfter,
|
|
2309
2411
|
basis: exact ? 'exact-tokenizer' : 'characters',
|
|
2310
2412
|
sourceSeq: manifestSeq,
|
|
2413
|
+
replacementSeq: Number(replacement.seq),
|
|
2311
2414
|
originalText: groupText,
|
|
2312
2415
|
})
|
|
2313
2416
|
}
|
|
@@ -2477,6 +2580,7 @@ export class ToolResultPruner extends Service {
|
|
|
2477
2580
|
tokensAfter: plan.tokensAfter,
|
|
2478
2581
|
basis: plan.measurementBasis,
|
|
2479
2582
|
sourceSeq: plan.sourceSeq,
|
|
2583
|
+
replacementSeq: Number(replacement.seq),
|
|
2480
2584
|
...(pairedOriginal === undefined ? {} : { originalText: pairedOriginal }),
|
|
2481
2585
|
})
|
|
2482
2586
|
return {
|
|
@@ -677,7 +677,7 @@ export function resolvePolicy(
|
|
|
677
677
|
'tokenpilot-inspired': {
|
|
678
678
|
nativeToolResultEnabled: false, freshEnabled: true, aggregateEnabled: true, historyMode: 'routine',
|
|
679
679
|
nativeTriggerTokens: Number.MAX_SAFE_INTEGER, nativeTargetTokens: Number.MAX_SAFE_INTEGER,
|
|
680
|
-
freshTriggerTokens:
|
|
680
|
+
freshTriggerTokens: 4_096, freshTargetTokens: 1_536,
|
|
681
681
|
aggregateTriggerTokens: 32_768, aggregateTargetTokens: 12_288,
|
|
682
682
|
historyTriggerTokens: 500_000, historyKeepRecentToolCalls: 10,
|
|
683
683
|
historyKeepRecentTokens: 64_000, historyMinReclaimTokens: 96_000,
|
|
@@ -2,7 +2,20 @@
|
|
|
2
2
|
|
|
3
3
|
import type { Context } from '@deepseek-ai/cordis'
|
|
4
4
|
import type { ContentBlock, TokenUsage } from '@deepseek-ai/dsh-llm'
|
|
5
|
-
|
|
5
|
+
// ≤0.1.1 宿主 dsh-session 无 deriveEventMessage 运行时导出(SessionSeq 同因,
|
|
6
|
+
// 见 pruner.ts 顶部注):namespace 软取,缺席落恒 null——调用方 L152 已有
|
|
7
|
+
// message===null → unavailableTokenCount 的降级路径,测量退化为 unavailable
|
|
8
|
+
// 而不是炸 loader entry。
|
|
9
|
+
import * as dshSessionNamespace from '@deepseek-ai/dsh-session'
|
|
10
|
+
const dshSessionSoft = dshSessionNamespace as unknown as {
|
|
11
|
+
deriveEventMessage?: (event: never) => unknown
|
|
12
|
+
default?: { deriveEventMessage?: (event: never) => unknown }
|
|
13
|
+
}
|
|
14
|
+
const deriveEventMessageImpl =
|
|
15
|
+
dshSessionSoft.deriveEventMessage ??
|
|
16
|
+
dshSessionSoft.default?.deriveEventMessage ??
|
|
17
|
+
(() => null)
|
|
18
|
+
const deriveEventMessage = deriveEventMessageImpl as typeof import('@deepseek-ai/dsh-session').deriveEventMessage
|
|
6
19
|
import { sessionEvents } from './session-events.ts'
|
|
7
20
|
import type { Session } from '@deepseek-ai/dsh-session'
|
|
8
21
|
import type {} from '@deepseek-ai/dsh-token-meter'
|
|
@@ -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
|
+
}
|