dsh-context-compression-improved 0.9.3 → 0.9.7
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/README.de.md +3 -3
- package/README.es.md +3 -3
- package/README.fr.md +3 -3
- package/README.it.md +3 -3
- package/README.ja.md +16 -3
- package/README.ko.md +16 -3
- package/README.md +16 -3
- package/README.ru.md +3 -3
- package/README.zh.md +16 -3
- package/assets/board.png +0 -0
- package/assets/context.png +0 -0
- package/docs/installation.de.md +2 -2
- package/docs/installation.es.md +2 -2
- package/docs/installation.fr.md +2 -2
- package/docs/installation.it.md +2 -2
- package/docs/installation.ja.md +2 -2
- package/docs/installation.ko.md +2 -2
- package/docs/installation.md +2 -2
- package/docs/installation.ru.md +2 -2
- package/docs/installation.zh.md +2 -2
- package/package.json +7 -6
- package/packages/selector/dsh.plugin.json +2 -2
- package/packages/selector/lib/client.d.ts +1 -0
- package/packages/selector/lib/client.js +63 -10
- package/packages/selector/lib/config.js +71 -7
- package/packages/selector/lib/index.js +145 -20
- package/packages/selector/lib/pruner.d.ts +158 -107
- package/packages/selector/lib/pruner.js +332 -22
- package/packages/selector/lib/tail-trim.js +25 -2
- package/packages/selector/package.json +22 -21
- package/packages/selector/src/client/index.ts +29 -2
- package/packages/selector/src/client/locales/de.ts +1 -0
- package/packages/selector/src/client/locales/es.ts +1 -0
- package/packages/selector/src/client/locales/fr.ts +1 -0
- package/packages/selector/src/client/locales/it.ts +1 -0
- package/packages/selector/src/client/locales/ja.ts +1 -0
- package/packages/selector/src/client/locales/ko.ts +1 -0
- package/packages/selector/src/client/locales/ru.ts +1 -0
- package/packages/selector/src/client/locales.ts +2 -0
- package/packages/selector/src/client/monitor-fab.ts +19 -4
- package/packages/selector/src/compat/llm-messages.ts +50 -0
- package/packages/selector/src/index.ts +27 -0
- 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 +109 -16
- package/packages/selector/src/runtime/config.ts +1 -1
- package/packages/selector/src/runtime/reducers.ts +81 -1
- package/packages/selector/src/runtime/retrieve.ts +4 -3
- package/packages/selector/src/runtime/savings-projection.ts +226 -0
- package/packages/selector/src/runtime/savings.ts +83 -3
- package/packages/selector/src/runtime/tail-trim.ts +2 -1
- package/packages/selector/tests/public/package-contract.client.spec.ts +4 -4
- 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/pnpm-workspace.yaml +6 -0
- package/screenshots.json +6 -0
- package/scripts/hosts.mjs +5 -2
- package/scripts/packed-install-e2e.mjs +19 -3
- package/scripts/sync-hosts.mjs +2 -2
- package/scripts/verify-release.mjs +6 -6
|
@@ -11,7 +11,11 @@
|
|
|
11
11
|
import { Service } from '@deepseek-ai/cordis'
|
|
12
12
|
import type { Context } from '@deepseek-ai/cordis'
|
|
13
13
|
import z from '@deepseek-ai/schemastery'
|
|
14
|
-
|
|
14
|
+
// dsh-llm 是 optional peer:official-clone profile 的模块图解析不到它,静态
|
|
15
|
+
// value import 在 ESM 链接期直接 ERR_MODULE_NOT_FOUND 拖死整个插件挂载(
|
|
16
|
+
// packed-install e2e seedSettings 实证,2026-10-16)。工厂语义极小且稳定
|
|
17
|
+
// (clone → brand id → deepFreeze),携带本地副本,与 0.9.3 SessionSeq 软取同族。
|
|
18
|
+
import { createUserMessage, freezeMessage } from './compat/llm-messages.ts'
|
|
15
19
|
import type { ContentBlock, ToolCallId, UserMessage } from '@deepseek-ai/dsh-llm'
|
|
16
20
|
// ≤0.1.1 宿主 loader 模块表的 dsh-session 没有 SessionSeq 运行时导出——静态
|
|
17
21
|
// named import 在 ESM 链接期即炸,loader entry(tool-result-pruner)mount 失败
|
|
@@ -122,6 +126,7 @@ import {
|
|
|
122
126
|
flattenPlainText,
|
|
123
127
|
} from './runtime/tokenpilot/dedup.ts'
|
|
124
128
|
import { getSavingsLedger } from './runtime/savings.ts'
|
|
129
|
+
import { projectSessionSavings } from './runtime/savings-projection.ts'
|
|
125
130
|
|
|
126
131
|
/** 节省统计配对键用原文(纯文本块才可配对;富内容返回 undefined)。 */
|
|
127
132
|
function originalTextForSavings(candidate: SnapshotCandidate): string | undefined {
|
|
@@ -228,6 +233,39 @@ declare module '@deepseek-ai/cordis' {
|
|
|
228
233
|
}
|
|
229
234
|
}
|
|
230
235
|
|
|
236
|
+
/**
|
|
237
|
+
* Cross-generation adaptation (0.2.0): the host `settings` service hands back
|
|
238
|
+
* the WHOLE entry config `{ settings: <subtree> }` instead of the settings
|
|
239
|
+
* subtree directly (older lines surfaced the subtree at the top level). The
|
|
240
|
+
* parser requires `profile`+`custom` at the root, so the wrapped shape threw
|
|
241
|
+
* "missing its complete shape" → the session failed open to `profile:'off'`,
|
|
242
|
+
* silently disabling fresh/aggregate on the desktop. Descend exactly one
|
|
243
|
+
* `{settings:<obj>}` wrapper ONLY when the root has no `profile`; every other
|
|
244
|
+
* shape is passed through untouched so the "exotic Host value must fail open
|
|
245
|
+
* to off" safety contract still holds.
|
|
246
|
+
*/
|
|
247
|
+
export function unwrapSettingsEntry(value: unknown): unknown {
|
|
248
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) return value
|
|
249
|
+
const record = value as Record<string, unknown>
|
|
250
|
+
if ('profile' in record) return value
|
|
251
|
+
const inner = record.settings
|
|
252
|
+
if (inner !== null && typeof inner === 'object' && !Array.isArray(inner)) return inner
|
|
253
|
+
return value
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* Whether a fresh candidate is BELOW the fresh trigger. Uses the real token
|
|
258
|
+
* count when an exact tokenizer is available (DeepSeek routes), and otherwise
|
|
259
|
+
* falls back to the 4.0 chars/token estimate — byte-for-byte the pre-existing
|
|
260
|
+
* behavior on routes without a bundled tokenizer (e.g. local Qwen).
|
|
261
|
+
*/
|
|
262
|
+
export function freshBelowTrigger(candidate: SnapshotCandidate, policy: CompressionPolicy): boolean {
|
|
263
|
+
if (candidate.count.kind === 'exact-tokenizer') {
|
|
264
|
+
return candidate.count.tokens <= policy.freshTriggerTokens
|
|
265
|
+
}
|
|
266
|
+
return candidate.characterPressure <= charsForTokens(policy.freshTriggerTokens)
|
|
267
|
+
}
|
|
268
|
+
|
|
231
269
|
/** Mixed deterministic selector behind the existing `ctx.toolResultPruner` seam. */
|
|
232
270
|
export class ToolResultPruner extends Service {
|
|
233
271
|
static inject = ['tokenMeter']
|
|
@@ -276,6 +314,8 @@ export class ToolResultPruner extends Service {
|
|
|
276
314
|
turnClocks: new WeakMap(),
|
|
277
315
|
estimatorRemainingTurns: new WeakMap(),
|
|
278
316
|
advisorChannels: new WeakMap(),
|
|
317
|
+
intentChannels: new WeakMap(),
|
|
318
|
+
projectedSavings: new WeakSet(),
|
|
279
319
|
pendingIntentFolds: new WeakMap(),
|
|
280
320
|
intentFoldedSeqs: new WeakMap(),
|
|
281
321
|
intentBaselines: new WeakMap(),
|
|
@@ -371,6 +411,15 @@ export class ToolResultPruner extends Service {
|
|
|
371
411
|
this.contextWindowForRequest(agent.session),
|
|
372
412
|
)
|
|
373
413
|
} catch { /* 观测失败静默:面板显示陈旧/空态 */ }
|
|
414
|
+
// 仪表口径:把当前 surface 存活 seq 交给账本,离开 surface 的压缩替换
|
|
415
|
+
// 即从“当前生效毛节省”中回落(数字随压缩内容进出而涨落)。
|
|
416
|
+
this.ensureSavingsProjection(agent.session)
|
|
417
|
+
try {
|
|
418
|
+
getSavingsLedger().observeActive(
|
|
419
|
+
String(agent.session.id),
|
|
420
|
+
new Set([...agent.session.surface.nodes].map(Number)),
|
|
421
|
+
)
|
|
422
|
+
} catch { /* 观测失败静默:维持上次口径 */ }
|
|
374
423
|
// TokenPilot-inspired E1: advisory estimator pass, strictly off the
|
|
375
424
|
// synchronous chain. Verdicts only feed the next pressure pass.
|
|
376
425
|
void this.postflightEstimatorPass(agent.session, signal).catch(() => undefined)
|
|
@@ -517,6 +566,7 @@ export class ToolResultPruner extends Service {
|
|
|
517
566
|
(d) => String(d.ns) === 'context-compression-improved-bundle',
|
|
518
567
|
)?.value
|
|
519
568
|
?? settingsHost?.get?.(CONTEXT_COMPRESSION_SETTINGS_NAMESPACE as never)) as ContextCompressionSettings | undefined
|
|
569
|
+
const unwrapped = unwrapSettingsEntry(settings)
|
|
520
570
|
let resolved: ContextCompressionSettings
|
|
521
571
|
let settingsSource: 'host-settings' | 'plugin-config-fallback' = settings === undefined
|
|
522
572
|
? 'plugin-config-fallback'
|
|
@@ -530,7 +580,7 @@ export class ToolResultPruner extends Service {
|
|
|
530
580
|
// Validate the Host value BEFORE cloning: structuredClone normalizes
|
|
531
581
|
// class/exotic prototypes to Object.prototype and would otherwise
|
|
532
582
|
// erase the very boundary the parser is responsible for enforcing.
|
|
533
|
-
: parseContextCompressionSettings(
|
|
583
|
+
: parseContextCompressionSettings(unwrapped as ContextCompressionSettings)
|
|
534
584
|
} catch (error: unknown) {
|
|
535
585
|
// A malformed persisted document must fail open LOSSLESSLY: freezing the
|
|
536
586
|
// deployment default could silently re-enable lossy compression the
|
|
@@ -659,7 +709,7 @@ export class ToolResultPruner extends Service {
|
|
|
659
709
|
for (const candidate of this.snapshot(session, measureForCompaction(this.ctx, session))) {
|
|
660
710
|
if (samples.length >= 3) break
|
|
661
711
|
if (candidate.event.data.turn === undefined) continue
|
|
662
|
-
if (candidate
|
|
712
|
+
if (freshBelowTrigger(candidate, policy)) continue
|
|
663
713
|
const path = toolCallPath(candidate.call.arguments)
|
|
664
714
|
if (path === undefined) continue
|
|
665
715
|
if (isSupersededRead(events, candidate.seq, path)) continue
|
|
@@ -810,6 +860,21 @@ export class ToolResultPruner extends Service {
|
|
|
810
860
|
}
|
|
811
861
|
}
|
|
812
862
|
|
|
863
|
+
/**
|
|
864
|
+
* 重进/重启会话的懒重建:首次观测某会话时,若账本尚无该会话条目,则按会话
|
|
865
|
+
* 日志投影播种(当前生效毛节省 + 每次重读惩罚 + 原文配对键)。只做一次,
|
|
866
|
+
* fail-open;同一进程内的实时增量随后在同一条目集合上继续。
|
|
867
|
+
*/
|
|
868
|
+
private ensureSavingsProjection(session: Session): void {
|
|
869
|
+
if (this.state.projectedSavings.has(session)) return
|
|
870
|
+
this.state.projectedSavings.add(session)
|
|
871
|
+
const ledger = getSavingsLedger()
|
|
872
|
+
if (ledger.hasSession(String(session.id))) return
|
|
873
|
+
try {
|
|
874
|
+
ledger.seedProjected(String(session.id), projectSessionSavings(this.ctx, session))
|
|
875
|
+
} catch { /* 投影失败静默:面板显示空态,不影响主流程 */ }
|
|
876
|
+
}
|
|
877
|
+
|
|
813
878
|
// ─────────── Turn-tail intent summary (host-driven fold, model writes text only) ───────────
|
|
814
879
|
|
|
815
880
|
/**
|
|
@@ -852,8 +917,25 @@ export class ToolResultPruner extends Service {
|
|
|
852
917
|
|
|
853
918
|
const settingsPreset = settings.presetOptions
|
|
854
919
|
if (settingsPreset === undefined) return
|
|
855
|
-
|
|
856
|
-
|
|
920
|
+
// 写手通道复用估计器通道:`host` 走宿主 llm 路由(provider/model 可省),
|
|
921
|
+
// `direct` 才需要显式 OpenAI 兼容端点。此前无条件要求直连端点,导致
|
|
922
|
+
// host 通道下每个回合都以 'no-direct-endpoint' 提前返回,fold 永不落地。
|
|
923
|
+
const estimatorMode = settingsPreset.estimatorMode ?? ''
|
|
924
|
+
if (estimatorMode !== 'host' && estimatorMode !== 'direct') {
|
|
925
|
+
emitCompressionAudit(this.ctx.logger, {
|
|
926
|
+
schemaVersion: 1,
|
|
927
|
+
kind: 'intent-summary-outcome',
|
|
928
|
+
sessionId,
|
|
929
|
+
ok: false,
|
|
930
|
+
reason: 'no-estimator-channel',
|
|
931
|
+
turnIndex: turn,
|
|
932
|
+
latencyMs: Date.now() - started,
|
|
933
|
+
})
|
|
934
|
+
return
|
|
935
|
+
}
|
|
936
|
+
if (estimatorMode === 'direct'
|
|
937
|
+
&& (settingsPreset.estimatorBaseUrl === undefined || settingsPreset.estimatorBaseUrl.length === 0
|
|
938
|
+
|| settingsPreset.estimatorModel === undefined || settingsPreset.estimatorModel.length === 0)) {
|
|
857
939
|
emitCompressionAudit(this.ctx.logger, {
|
|
858
940
|
schemaVersion: 1,
|
|
859
941
|
kind: 'intent-summary-outcome',
|
|
@@ -891,14 +973,16 @@ export class ToolResultPruner extends Service {
|
|
|
891
973
|
|
|
892
974
|
const events = sessionEvents(session)
|
|
893
975
|
const task = collectTaskSemantics(events)
|
|
894
|
-
|
|
976
|
+
// 独立通道:写手用 30s 超时,advisor 用其自身超时——两者若共享
|
|
977
|
+
// advisorChannels,先构造者会把 mode/timeout 强加给后者。
|
|
978
|
+
let channel = this.state.intentChannels.get(session)
|
|
895
979
|
if (channel === undefined) {
|
|
896
980
|
channel = new SideChannel(this.ctx, settingsPreset, {
|
|
897
|
-
mode:
|
|
981
|
+
mode: estimatorMode,
|
|
898
982
|
timeoutMs: 30_000,
|
|
899
983
|
maxTokens: 512,
|
|
900
984
|
})
|
|
901
|
-
this.state.
|
|
985
|
+
this.state.intentChannels.set(session, channel)
|
|
902
986
|
}
|
|
903
987
|
|
|
904
988
|
const answer = await channel.ask({
|
|
@@ -1470,7 +1554,8 @@ export class ToolResultPruner extends Service {
|
|
|
1470
1554
|
return emptyResult()
|
|
1471
1555
|
}
|
|
1472
1556
|
const decisions = this.decisions(session)
|
|
1473
|
-
const
|
|
1557
|
+
const snapshot = this.snapshot(session, view)
|
|
1558
|
+
const candidates = snapshot.filter(candidate =>
|
|
1474
1559
|
typeof candidate.event.surfaceOp !== 'object'
|
|
1475
1560
|
&& candidate.event.data.turn === options.freshTurn
|
|
1476
1561
|
&& candidate.event.data.step === options.freshStep
|
|
@@ -1506,8 +1591,14 @@ export class ToolResultPruner extends Service {
|
|
|
1506
1591
|
const plans = new Map<number, PlannedReplacement>()
|
|
1507
1592
|
let freshPlanned = 0
|
|
1508
1593
|
const dedupeEnabled = policy.presetOptions?.dedupeToolResults === true
|
|
1509
|
-
|
|
1510
|
-
|
|
1594
|
+
// Token-basis max, mirroring freshBelowTrigger: exact tokenizer where
|
|
1595
|
+
// available, else the 4.0 char estimate. Drives the 'at-or-below-trigger'
|
|
1596
|
+
// audit reason on the same basis the fresh gate uses.
|
|
1597
|
+
const maxCandidateTokens = candidates.length === 0
|
|
1598
|
+
? undefined
|
|
1599
|
+
: Math.max(...candidates.map(candidate => candidate.count.kind === 'exact-tokenizer'
|
|
1600
|
+
? candidate.count.tokens
|
|
1601
|
+
: charsToTokens(candidate.characterPressure)))
|
|
1511
1602
|
if (policy.freshEnabled) {
|
|
1512
1603
|
if (candidates.some(candidate => candidate.call.name !== 'context_compression_retrieve'
|
|
1513
1604
|
&& candidate.count.kind !== 'exact-tokenizer')) {
|
|
@@ -1573,12 +1664,12 @@ export class ToolResultPruner extends Service {
|
|
|
1573
1664
|
this.auditComponent(session, policy, 'fresh', 'fresh',
|
|
1574
1665
|
policy.freshEnabled ? 'skipped' : 'disabled',
|
|
1575
1666
|
!policy.freshEnabled ? 'profile-policy'
|
|
1576
|
-
: (
|
|
1667
|
+
: (maxCandidateTokens ?? 0) <= policy.freshTriggerTokens ? 'at-or-below-trigger'
|
|
1577
1668
|
: freshPlanned > 0 && aggregatePlanned > 0 ? 'superseded-by-aggregate'
|
|
1578
1669
|
: freshPlanned === 0 ? 'no-valid-reduction'
|
|
1579
1670
|
: 'recovery-tool-unavailable', {
|
|
1580
1671
|
measurementKind: 'characters',
|
|
1581
|
-
...(
|
|
1672
|
+
...(maxCandidateTokens === undefined ? {} : { currentTokens: maxCandidateTokens }),
|
|
1582
1673
|
triggerTokens: policy.freshTriggerTokens,
|
|
1583
1674
|
targetTokens: policy.freshTargetTokens,
|
|
1584
1675
|
})
|
|
@@ -1699,7 +1790,7 @@ export class ToolResultPruner extends Service {
|
|
|
1699
1790
|
if (typeof candidate.event.surfaceOp === 'object') return null
|
|
1700
1791
|
const text = flattenPlainText(viewToolResult(candidate.event.data.message).blocks as ContentBlock[])
|
|
1701
1792
|
if (text === undefined) return null
|
|
1702
|
-
if (candidate
|
|
1793
|
+
if (freshBelowTrigger(candidate, policy)) return null
|
|
1703
1794
|
let table = this.state.dedupeTables.get(session)
|
|
1704
1795
|
if (table === undefined) {
|
|
1705
1796
|
table = new DedupeTable()
|
|
@@ -1745,7 +1836,7 @@ export class ToolResultPruner extends Service {
|
|
|
1745
1836
|
// being reconsidered after their first request.
|
|
1746
1837
|
if (typeof candidate.event.surfaceOp === 'object') return null
|
|
1747
1838
|
const resultView = viewToolResult(candidate.event.data.message)
|
|
1748
|
-
if (candidate
|
|
1839
|
+
if (freshBelowTrigger(candidate, policy)) return null
|
|
1749
1840
|
const sourceSeq = candidate.seq
|
|
1750
1841
|
const sourceRef = sourceRefFn(session, sourceSeq)
|
|
1751
1842
|
const textBlock = onlyTextBlock(resultView.blocks as ContentBlock[])
|
|
@@ -1828,7 +1919,7 @@ export class ToolResultPruner extends Service {
|
|
|
1828
1919
|
'[Tool result reduced to satisfy the completed-step aggregate budget]',
|
|
1829
1920
|
`tool: ${candidate.call.name}`,
|
|
1830
1921
|
`source: ${sourceRef}`,
|
|
1831
|
-
'
|
|
1922
|
+
'Retrieve a narrow slice via context_compression_retrieve if needed.',
|
|
1832
1923
|
].join('\n')
|
|
1833
1924
|
const plan = this.plan(
|
|
1834
1925
|
candidate,
|
|
@@ -2323,6 +2414,7 @@ export class ToolResultPruner extends Service {
|
|
|
2323
2414
|
tokensAfter,
|
|
2324
2415
|
basis: exact ? 'exact-tokenizer' : 'characters',
|
|
2325
2416
|
sourceSeq: manifestSeq,
|
|
2417
|
+
replacementSeq: Number(replacement.seq),
|
|
2326
2418
|
originalText: groupText,
|
|
2327
2419
|
})
|
|
2328
2420
|
}
|
|
@@ -2492,6 +2584,7 @@ export class ToolResultPruner extends Service {
|
|
|
2492
2584
|
tokensAfter: plan.tokensAfter,
|
|
2493
2585
|
basis: plan.measurementBasis,
|
|
2494
2586
|
sourceSeq: plan.sourceSeq,
|
|
2587
|
+
replacementSeq: Number(replacement.seq),
|
|
2495
2588
|
...(pairedOriginal === undefined ? {} : { originalText: pairedOriginal }),
|
|
2496
2589
|
})
|
|
2497
2590
|
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,
|
|
@@ -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
|
+
}
|