dsh-context-compression-improved 0.8.0-beta.2 → 0.8.0-beta.3
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 +9 -0
- package/package.json +1 -1
- package/packages/selector/dsh.plugin.json +1 -1
- package/packages/selector/lib/advisor-state.js +503 -1
- package/packages/selector/lib/client.d.ts +14 -0
- package/packages/selector/lib/client.js +327 -10
- package/packages/selector/lib/index.js +122 -2
- package/packages/selector/lib/pruner.js +87 -258
- package/packages/selector/lib/style.css +42 -0
- package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -170
- package/packages/selector/src/client/locales/de.ts +15 -0
- package/packages/selector/src/client/locales/es.ts +15 -0
- package/packages/selector/src/client/locales/fr.ts +15 -0
- package/packages/selector/src/client/locales/it.ts +15 -0
- package/packages/selector/src/client/locales/ja.ts +15 -0
- package/packages/selector/src/client/locales/ko.ts +15 -0
- package/packages/selector/src/client/locales/ru.ts +15 -0
- package/packages/selector/src/client/locales.ts +226 -196
- package/packages/selector/src/client/savings-card.tsx +150 -0
- package/packages/selector/src/client/settings-section.tsx +126 -124
- package/packages/selector/src/index.ts +547 -411
- package/packages/selector/src/pruner.ts +2505 -2421
- package/packages/selector/src/runtime/retrieve.ts +479 -457
- package/packages/selector/src/runtime/savings.ts +337 -0
- package/packages/selector/tests/estimator-route-registration.host.spec.ts +192 -188
- package/packages/selector/tests/runtime/savings.spec.ts +120 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { C as deepFreeze, S as assertNever, _ as resolveConfig, a as AUTO_COMPACT_THRESHOLD_LIMITS, b as DEFAULT_CUSTOM_COMPRESSION_POLICY, c as DEFAULTS, d as charsForTokens, f as charsToTokens, g as parseContextCompressionSettings, h as isValidAutoCompactThresholdPercent, i as recordScore, m as isCompressionProfile, n as invalidateOnTaskChange, o as CONTEXT_COMPRESSION_SETTINGS_NAMESPACE, p as codePointLength, r as recordRecertified, s as ContextCompressionSettingsSchema, t as getAdvisorState, u as PRUNE_MARKER, v as resolvePolicy, w as COMPRESSION_PROFILES, x as resolveCustomPolicy, y as CustomCompressionPolicySchema } from "./advisor-state.js";
|
|
1
|
+
import { C as deepFreeze, D as priceOfficialDeepSeekUsage, E as decimalRateNanoUnits, O as resolveOfficialDeepSeekPrice, S as assertNever, T as DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION, _ as resolveConfig, a as AUTO_COMPACT_THRESHOLD_LIMITS, b as DEFAULT_CUSTOM_COMPRESSION_POLICY, c as DEFAULTS, d as charsForTokens, f as charsToTokens, g as parseContextCompressionSettings, h as isValidAutoCompactThresholdPercent, i as recordScore, k as getSavingsLedger, m as isCompressionProfile, n as invalidateOnTaskChange, o as CONTEXT_COMPRESSION_SETTINGS_NAMESPACE, p as codePointLength, r as recordRecertified, s as ContextCompressionSettingsSchema, t as getAdvisorState, u as PRUNE_MARKER, v as resolvePolicy, w as COMPRESSION_PROFILES, x as resolveCustomPolicy, y as CustomCompressionPolicySchema } from "./advisor-state.js";
|
|
2
2
|
import { a as validatePublishedTailTrim, i as tailTrimStub, n as tailTrimMessage, o as eventBySeq, r as tailTrimRef, s as sessionEvents, t as parseTailTrimRef } from "./tail-trim.js";
|
|
3
3
|
import z from "@deepseek-ai/schemastery";
|
|
4
4
|
import { createHash } from "node:crypto";
|
|
@@ -531,6 +531,10 @@ function measureForCompaction(ctx, session) {
|
|
|
531
531
|
countCanonicalText: counter.countText
|
|
532
532
|
});
|
|
533
533
|
}
|
|
534
|
+
/** Request-level usage exposed by official TokenMeter, without invented route attribution. */
|
|
535
|
+
function officialRequestUsage(view) {
|
|
536
|
+
return view.baseline.kind === "usage" ? view.baseline.usage : void 0;
|
|
537
|
+
}
|
|
534
538
|
/**
|
|
535
539
|
* Count one canonical content walk in canonical field order.
|
|
536
540
|
*
|
|
@@ -789,11 +793,23 @@ function installContextCompressionRetrieve(ctx, config = {}) {
|
|
|
789
793
|
const tailTrimRef = parseTailTrimRef(args.ref);
|
|
790
794
|
if (match === null && tailTrimRef === null) throw new Error("context_compression_retrieve: ref must be session://<session-id>/(event|tailtrim)/<seq>");
|
|
791
795
|
if ((match?.[1] ?? tailTrimRef?.sessionId) !== String(exec.agent.id)) throw new Error("context_compression_retrieve: a compression reference may only read the caller's current session");
|
|
792
|
-
if (tailTrimRef !== null)
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
796
|
+
if (tailTrimRef !== null) {
|
|
797
|
+
const sessionId = String(exec.agent.id);
|
|
798
|
+
return Promise.resolve(recoverTailTrim(exec.agent.session, args.ref, tailTrimRef.manifestSeq, args.query, args.start_line, args.max_lines, {
|
|
799
|
+
maxChars,
|
|
800
|
+
maxScanChars,
|
|
801
|
+
maxQueryChars
|
|
802
|
+
})).then((text) => {
|
|
803
|
+
getSavingsLedger().recordOffset({
|
|
804
|
+
sessionId,
|
|
805
|
+
component: "tailtrim-retrieve",
|
|
806
|
+
tokens: Math.ceil(codePointLength$1(text) / 4),
|
|
807
|
+
basis: "characters",
|
|
808
|
+
note: `tailtrim/${tailTrimRef.manifestSeq} 回读`
|
|
809
|
+
});
|
|
810
|
+
return text;
|
|
811
|
+
});
|
|
812
|
+
}
|
|
797
813
|
const seq = Number(match?.[2]);
|
|
798
814
|
const event = sessionEvents(exec.agent.session)[seq];
|
|
799
815
|
if (event?.type !== "tool/result") throw new Error(`context_compression_retrieve: event ${String(seq)} is not a tool/result in the current session`);
|
|
@@ -805,7 +821,7 @@ function installContextCompressionRetrieve(ctx, config = {}) {
|
|
|
805
821
|
if (query !== void 0 && exceedsCodePointLimit(query, maxQueryChars)) throw new Error(`context_compression_retrieve: query must be at most ${String(maxQueryChars)} Unicode code points`);
|
|
806
822
|
const selected = query === void 0 || query === "" ? directSlice(lines, args.start_line ?? 1, maxLines, scan.complete, scannedLines.partialTail) : querySlice(lines, query, maxLines, scan.complete, scannedLines.partialTail);
|
|
807
823
|
const total = scan.complete ? String(lines.length) : `at least ${String(lines.length)}`;
|
|
808
|
-
const
|
|
824
|
+
const bounded = boundCodePoints(`${[
|
|
809
825
|
`source: ${args.ref}`,
|
|
810
826
|
`tool_call_id: ${event.data.message.toolCallId}`,
|
|
811
827
|
`status: ${event.data.message.isError === true ? "error" : "completed"}`,
|
|
@@ -814,8 +830,15 @@ function installContextCompressionRetrieve(ctx, config = {}) {
|
|
|
814
830
|
selected.partialLine === void 0 ? "" : `note: line ${String(selected.partialLine)} is a partial prefix ending at the source scan limit`,
|
|
815
831
|
selected.omitted ? query === void 0 || query === "" ? "note: additional source lines were omitted" : "note: additional matching or neighboring lines were omitted" : "",
|
|
816
832
|
"--- original tool result ---"
|
|
817
|
-
].filter(Boolean).join("\n")}\n${selected.text}
|
|
818
|
-
|
|
833
|
+
].filter(Boolean).join("\n")}\n${selected.text}`, maxChars);
|
|
834
|
+
getSavingsLedger().recordOffset({
|
|
835
|
+
sessionId: String(exec.agent.id),
|
|
836
|
+
component: "retrieve",
|
|
837
|
+
tokens: Math.ceil(codePointLength$1(bounded) / 4),
|
|
838
|
+
basis: "characters",
|
|
839
|
+
note: `event/${String(seq)} 回读`
|
|
840
|
+
});
|
|
841
|
+
return Promise.resolve(bounded);
|
|
819
842
|
}
|
|
820
843
|
}));
|
|
821
844
|
}
|
|
@@ -3608,254 +3631,6 @@ function dedupePlaceholder(entry, originalChars) {
|
|
|
3608
3631
|
].join(" ");
|
|
3609
3632
|
}
|
|
3610
3633
|
//#endregion
|
|
3611
|
-
//#region src/runtime/deepseek-official-pricing.ts
|
|
3612
|
-
/** Checked-in DeepSeek official prices and fixed-point provider-usage accounting. */
|
|
3613
|
-
const DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION = "deepseek-official-2026-08-25";
|
|
3614
|
-
/** Wall-clock time at which the checked-in official price pages were verified. */
|
|
3615
|
-
const DEEPSEEK_OFFICIAL_PRICE_CHECKED_AT = "2026-08-25T00:10:20+08:00";
|
|
3616
|
-
const PRICES = Object.freeze({
|
|
3617
|
-
"deepseek-v4-flash": modelPrices("DeepSeek-V4-Flash-0731", [
|
|
3618
|
-
"0.007",
|
|
3619
|
-
"0.22",
|
|
3620
|
-
"0.66"
|
|
3621
|
-
], [
|
|
3622
|
-
"0.014",
|
|
3623
|
-
"0.44",
|
|
3624
|
-
"1.32"
|
|
3625
|
-
], [
|
|
3626
|
-
"0.05",
|
|
3627
|
-
"1.5",
|
|
3628
|
-
"4.5"
|
|
3629
|
-
], [
|
|
3630
|
-
"0.10",
|
|
3631
|
-
"3.0",
|
|
3632
|
-
"9.0"
|
|
3633
|
-
]),
|
|
3634
|
-
"deepseek-v4-pro": modelPrices("DeepSeek-V4-Pro-0813", [
|
|
3635
|
-
"0.022",
|
|
3636
|
-
"0.66",
|
|
3637
|
-
"1.98"
|
|
3638
|
-
], [
|
|
3639
|
-
"0.044",
|
|
3640
|
-
"1.32",
|
|
3641
|
-
"3.96"
|
|
3642
|
-
], [
|
|
3643
|
-
"0.15",
|
|
3644
|
-
"4.5",
|
|
3645
|
-
"13.5"
|
|
3646
|
-
], [
|
|
3647
|
-
"0.30",
|
|
3648
|
-
"9.0",
|
|
3649
|
-
"27.0"
|
|
3650
|
-
]),
|
|
3651
|
-
"deepseek-v4-flash-vision-exp": modelPrices("DeepSeek-V4-Flash-Vision-Exp", [
|
|
3652
|
-
"0.007",
|
|
3653
|
-
"0.22",
|
|
3654
|
-
"0.66"
|
|
3655
|
-
], [
|
|
3656
|
-
"0.014",
|
|
3657
|
-
"0.44",
|
|
3658
|
-
"1.32"
|
|
3659
|
-
], [
|
|
3660
|
-
"0.05",
|
|
3661
|
-
"1.5",
|
|
3662
|
-
"4.5"
|
|
3663
|
-
], [
|
|
3664
|
-
"0.10",
|
|
3665
|
-
"3.0",
|
|
3666
|
-
"9.0"
|
|
3667
|
-
])
|
|
3668
|
-
});
|
|
3669
|
-
const PEAK_RULE = "Asia/Shanghai Mon-Fri 09:00-12:00,14:00-18:00";
|
|
3670
|
-
const USD_SOURCE = "https://api-docs.deepseek.com/quick_start/pricing/";
|
|
3671
|
-
const CNY_SOURCE = "https://api-docs.deepseek.com/zh-cn/quick_start/pricing/";
|
|
3672
|
-
/**
|
|
3673
|
-
* Resolve one immutable official price record; aliases and compatible gateways fail closed.
|
|
3674
|
-
* @param input - exact provider, endpoint, route, model, currency, and timestamp applicability.
|
|
3675
|
-
* @returns An immutable price record or an explicit unpriced reason.
|
|
3676
|
-
*/
|
|
3677
|
-
function resolveOfficialDeepSeekPrice(input) {
|
|
3678
|
-
if (input.provider !== "deepseek-official") return unpriced("unknown provider route");
|
|
3679
|
-
if (input.baseUrlClass !== "official-public") return unpriced("unknown base-url applicability");
|
|
3680
|
-
if (input.apiRoute !== "chat-completions" && input.apiRoute !== "responses") return unpriced("unknown API route");
|
|
3681
|
-
if (!isOfficialModel(input.modelId)) return unpriced("unknown model id");
|
|
3682
|
-
if (input.currency !== "USD" && input.currency !== "CNY") return unpriced("unknown currency");
|
|
3683
|
-
const band = priceBandAt(input.at);
|
|
3684
|
-
if (band === void 0) return unpriced("invalid price timestamp");
|
|
3685
|
-
const model = PRICES[input.modelId];
|
|
3686
|
-
const [inputCacheHit, inputCacheMiss, output] = model[input.currency][band];
|
|
3687
|
-
return {
|
|
3688
|
-
kind: "priced",
|
|
3689
|
-
record: Object.freeze({
|
|
3690
|
-
catalogVersion: DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION,
|
|
3691
|
-
checkedAt: DEEPSEEK_OFFICIAL_PRICE_CHECKED_AT,
|
|
3692
|
-
provider: "deepseek-official",
|
|
3693
|
-
baseUrlClass: "official-public",
|
|
3694
|
-
apiRoute: input.apiRoute,
|
|
3695
|
-
modelId: input.modelId,
|
|
3696
|
-
modelVersion: model.version,
|
|
3697
|
-
currency: input.currency,
|
|
3698
|
-
unitTokens: 1e6,
|
|
3699
|
-
band,
|
|
3700
|
-
inputCacheHit,
|
|
3701
|
-
inputCacheMiss,
|
|
3702
|
-
output,
|
|
3703
|
-
sourceUrl: input.currency === "USD" ? USD_SOURCE : CNY_SOURCE,
|
|
3704
|
-
sourceLocale: input.currency === "USD" ? "en" : "zh-CN",
|
|
3705
|
-
peakRule: PEAK_RULE
|
|
3706
|
-
})
|
|
3707
|
-
};
|
|
3708
|
-
}
|
|
3709
|
-
/**
|
|
3710
|
-
* Classify a timestamp under the published Beijing peak schedule.
|
|
3711
|
-
* @param at - absolute request time to interpret in Asia/Shanghai.
|
|
3712
|
-
* @returns Peak/off-peak, or undefined for an invalid timestamp.
|
|
3713
|
-
*/
|
|
3714
|
-
function priceBandAt(at) {
|
|
3715
|
-
if (!Number.isFinite(at.getTime())) return void 0;
|
|
3716
|
-
const parts = new Intl.DateTimeFormat("en-US", {
|
|
3717
|
-
timeZone: "Asia/Shanghai",
|
|
3718
|
-
weekday: "short",
|
|
3719
|
-
hour: "2-digit",
|
|
3720
|
-
minute: "2-digit",
|
|
3721
|
-
second: "2-digit",
|
|
3722
|
-
hourCycle: "h23"
|
|
3723
|
-
}).formatToParts(at);
|
|
3724
|
-
const values = Object.fromEntries(parts.map((part) => [part.type, part.value]));
|
|
3725
|
-
const weekday = values.weekday;
|
|
3726
|
-
const hour = Number(values.hour);
|
|
3727
|
-
const minute = Number(values.minute);
|
|
3728
|
-
const second = Number(values.second);
|
|
3729
|
-
if (weekday === void 0 || !Number.isInteger(hour) || !Number.isInteger(minute) || !Number.isInteger(second)) return void 0;
|
|
3730
|
-
const workday = weekday !== "Sat" && weekday !== "Sun";
|
|
3731
|
-
const seconds = hour * 3600 + minute * 60 + second;
|
|
3732
|
-
return workday && (seconds >= 32400 && seconds < 43200 || seconds >= 50400 && seconds < 64800) ? "peak" : "off-peak";
|
|
3733
|
-
}
|
|
3734
|
-
/**
|
|
3735
|
-
* Price one completed request, returning a range when it spans a published band boundary.
|
|
3736
|
-
* @param input - exact applicability, request interval, and complete disjoint usage buckets.
|
|
3737
|
-
* @returns Fixed-point exact/range cost or an explicit unpriced reason.
|
|
3738
|
-
*/
|
|
3739
|
-
function priceOfficialDeepSeekUsage(input) {
|
|
3740
|
-
for (const [name, value] of Object.entries(input.usage)) if (!Number.isSafeInteger(value) || value < 0) return unpriced(`invalid ${name}`);
|
|
3741
|
-
if (input.completedAt.getTime() < input.startedAt.getTime()) return unpriced("completion timestamp precedes request start");
|
|
3742
|
-
const start = resolveOfficialDeepSeekPrice({
|
|
3743
|
-
...input,
|
|
3744
|
-
at: input.startedAt
|
|
3745
|
-
});
|
|
3746
|
-
if (start.kind === "unpriced") return start;
|
|
3747
|
-
const end = resolveOfficialDeepSeekPrice({
|
|
3748
|
-
...input,
|
|
3749
|
-
at: input.completedAt
|
|
3750
|
-
});
|
|
3751
|
-
if (end.kind === "unpriced") return end;
|
|
3752
|
-
const startAmount = amountFor(start.record, input.usage);
|
|
3753
|
-
if (startAmount === void 0) return unpriced("invalid decimal price record");
|
|
3754
|
-
const crossesBoundary = spansPublishedPriceBoundary(input.startedAt, input.completedAt);
|
|
3755
|
-
if (start.record.band === end.record.band && !crossesBoundary) return {
|
|
3756
|
-
kind: "exact",
|
|
3757
|
-
currency: start.record.currency,
|
|
3758
|
-
band: start.record.band,
|
|
3759
|
-
...startAmount
|
|
3760
|
-
};
|
|
3761
|
-
const comparisonRecord = start.record.band === end.record.band ? priceRecordInBand(start.record, start.record.band === "peak" ? "off-peak" : "peak") : end.record;
|
|
3762
|
-
const endAmount = amountFor(comparisonRecord, input.usage);
|
|
3763
|
-
if (endAmount === void 0) return unpriced("invalid decimal price record");
|
|
3764
|
-
const startFemto = BigInt(startAmount.femtoUnits);
|
|
3765
|
-
const endFemto = BigInt(endAmount.femtoUnits);
|
|
3766
|
-
return {
|
|
3767
|
-
kind: "range",
|
|
3768
|
-
currency: start.record.currency,
|
|
3769
|
-
bands: [start.record.band, comparisonRecord.band],
|
|
3770
|
-
minimum: startFemto <= endFemto ? startAmount : endAmount,
|
|
3771
|
-
maximum: startFemto <= endFemto ? endAmount : startAmount
|
|
3772
|
-
};
|
|
3773
|
-
}
|
|
3774
|
-
/** Detect any published UTC band boundary, even when both endpoints share a band. */
|
|
3775
|
-
function spansPublishedPriceBoundary(startedAt, completedAt) {
|
|
3776
|
-
const start = startedAt.getTime();
|
|
3777
|
-
const end = completedAt.getTime();
|
|
3778
|
-
if (end <= start) return false;
|
|
3779
|
-
const dayMs = 864e5;
|
|
3780
|
-
if (end - start >= 7 * dayMs) return true;
|
|
3781
|
-
const firstDay = Math.floor(start / dayMs) * dayMs;
|
|
3782
|
-
for (let day = firstDay; day <= end; day += dayMs) {
|
|
3783
|
-
const weekday = new Date(day).getUTCDay();
|
|
3784
|
-
if (weekday === 0 || weekday === 6) continue;
|
|
3785
|
-
for (const hour of [
|
|
3786
|
-
1,
|
|
3787
|
-
4,
|
|
3788
|
-
6,
|
|
3789
|
-
10
|
|
3790
|
-
]) {
|
|
3791
|
-
const boundary = day + hour * 60 * 60 * 1e3;
|
|
3792
|
-
if (boundary > start && boundary <= end) return true;
|
|
3793
|
-
}
|
|
3794
|
-
}
|
|
3795
|
-
return false;
|
|
3796
|
-
}
|
|
3797
|
-
function priceRecordInBand(record, band) {
|
|
3798
|
-
const [inputCacheHit, inputCacheMiss, output] = PRICES[record.modelId][record.currency][band];
|
|
3799
|
-
return Object.freeze({
|
|
3800
|
-
...record,
|
|
3801
|
-
band,
|
|
3802
|
-
inputCacheHit,
|
|
3803
|
-
inputCacheMiss,
|
|
3804
|
-
output
|
|
3805
|
-
});
|
|
3806
|
-
}
|
|
3807
|
-
/**
|
|
3808
|
-
* Parse a non-negative decimal rate into nano-currency units, without Number arithmetic.
|
|
3809
|
-
* @param value - canonical non-negative decimal with at most nine fractional digits.
|
|
3810
|
-
* @returns Integer nano-units, or undefined when the decimal is invalid.
|
|
3811
|
-
*/
|
|
3812
|
-
function decimalRateNanoUnits(value) {
|
|
3813
|
-
const match = /^(0|[1-9]\d*)(?:\.(\d{1,9}))?$/u.exec(value);
|
|
3814
|
-
if (match === null) return void 0;
|
|
3815
|
-
const whole = match[1] ?? "0";
|
|
3816
|
-
const fraction = (match[2] ?? "").padEnd(9, "0");
|
|
3817
|
-
return BigInt(whole) * 1000000000n + BigInt(fraction || "0");
|
|
3818
|
-
}
|
|
3819
|
-
function amountFor(record, usage) {
|
|
3820
|
-
const hit = decimalRateNanoUnits(record.inputCacheHit);
|
|
3821
|
-
const miss = decimalRateNanoUnits(record.inputCacheMiss);
|
|
3822
|
-
const output = decimalRateNanoUnits(record.output);
|
|
3823
|
-
if (hit === void 0 || miss === void 0 || output === void 0) return void 0;
|
|
3824
|
-
const femtoUnits = BigInt(usage.cacheReadTokens) * hit + BigInt(usage.cacheMissTokens) * miss + BigInt(usage.outputTokens) * output;
|
|
3825
|
-
return {
|
|
3826
|
-
femtoUnits: femtoUnits.toString(),
|
|
3827
|
-
decimal: formatFemto(femtoUnits)
|
|
3828
|
-
};
|
|
3829
|
-
}
|
|
3830
|
-
function formatFemto(value) {
|
|
3831
|
-
const digits = value.toString().padStart(16, "0");
|
|
3832
|
-
const whole = digits.slice(0, -15);
|
|
3833
|
-
const fraction = digits.slice(-15).replace(/0+$/u, "");
|
|
3834
|
-
return fraction.length === 0 ? whole : `${whole}.${fraction}`;
|
|
3835
|
-
}
|
|
3836
|
-
function modelPrices(version, usdOffPeak, usdPeak, cnyOffPeak, cnyPeak) {
|
|
3837
|
-
return Object.freeze({
|
|
3838
|
-
version,
|
|
3839
|
-
USD: Object.freeze({
|
|
3840
|
-
"off-peak": usdOffPeak,
|
|
3841
|
-
peak: usdPeak
|
|
3842
|
-
}),
|
|
3843
|
-
CNY: Object.freeze({
|
|
3844
|
-
"off-peak": cnyOffPeak,
|
|
3845
|
-
peak: cnyPeak
|
|
3846
|
-
})
|
|
3847
|
-
});
|
|
3848
|
-
}
|
|
3849
|
-
function isOfficialModel(value) {
|
|
3850
|
-
return Object.prototype.hasOwnProperty.call(PRICES, value);
|
|
3851
|
-
}
|
|
3852
|
-
function unpriced(reason) {
|
|
3853
|
-
return {
|
|
3854
|
-
kind: "unpriced",
|
|
3855
|
-
reason
|
|
3856
|
-
};
|
|
3857
|
-
}
|
|
3858
|
-
//#endregion
|
|
3859
3634
|
//#region src/runtime/adaptive-cost.ts
|
|
3860
3635
|
/**
|
|
3861
3636
|
* Bound Adaptive's benefit and cache-loss exposure without attributing the
|
|
@@ -3997,6 +3772,10 @@ function emitCompressionAudit(logger, record) {
|
|
|
3997
3772
|
*
|
|
3998
3773
|
* @module dsh-context-compression-improved-runtime
|
|
3999
3774
|
*/
|
|
3775
|
+
/** 节省统计配对键用原文(纯文本块才可配对;富内容返回 undefined)。 */
|
|
3776
|
+
function originalTextForSavings(candidate) {
|
|
3777
|
+
return flattenPlainText(candidate.event.data.message.content);
|
|
3778
|
+
}
|
|
4000
3779
|
/** Mixed deterministic selector behind the existing `ctx.toolResultPruner` seam. */
|
|
4001
3780
|
var ToolResultPruner = class extends Service {
|
|
4002
3781
|
static inject = ["tokenMeter"];
|
|
@@ -4042,6 +3821,14 @@ var ToolResultPruner = class extends Service {
|
|
|
4042
3821
|
estimatorRemainingTurns: /* @__PURE__ */ new WeakMap(),
|
|
4043
3822
|
advisorChannels: /* @__PURE__ */ new WeakMap()
|
|
4044
3823
|
};
|
|
3824
|
+
try {
|
|
3825
|
+
ctx.on("session/disposed", (session) => {
|
|
3826
|
+
try {
|
|
3827
|
+
const line = getSavingsLedger().sessionSummaryLine(String(session.id));
|
|
3828
|
+
if (line.includes("requests=0") === false || line.includes("net=0(exact)/0(est)") === false) ctx.logger.info("context-compression session savings (%s): %s", String(session.id), line);
|
|
3829
|
+
} catch {}
|
|
3830
|
+
});
|
|
3831
|
+
} catch {}
|
|
4045
3832
|
ctx.on("session/event", (session, event) => {
|
|
4046
3833
|
this.scanForSeededNativeSummary(session);
|
|
4047
3834
|
if (event.type === "compaction/summary") {
|
|
@@ -4115,7 +3902,11 @@ var ToolResultPruner = class extends Service {
|
|
|
4115
3902
|
if (policy === void 0) return emptyResult();
|
|
4116
3903
|
const profile = policy.profile;
|
|
4117
3904
|
const view = measureForCompaction(this.ctx, session);
|
|
4118
|
-
if (stage === "fresh")
|
|
3905
|
+
if (stage === "fresh") {
|
|
3906
|
+
const usage = officialRequestUsage(view);
|
|
3907
|
+
if (usage !== void 0) getSavingsLedger().recordUsage(String(session.id), usage);
|
|
3908
|
+
return this.decideFreshStep(session, options, policy, view);
|
|
3909
|
+
}
|
|
4119
3910
|
if (profile === "off") return emptyResult();
|
|
4120
3911
|
const landed = [];
|
|
4121
3912
|
if (policy.nativeToolResultEnabled) {
|
|
@@ -4755,6 +4546,24 @@ var ToolResultPruner = class extends Service {
|
|
|
4755
4546
|
this.auditComponent(session, policy, "aggregate", "fresh", policy.aggregateEnabled ? "skipped" : "disabled", policy.aggregateEnabled ? "no-new-tool-result-candidates" : "profile-policy");
|
|
4756
4547
|
return emptyResult();
|
|
4757
4548
|
}
|
|
4549
|
+
const ledger = getSavingsLedger();
|
|
4550
|
+
const sid = String(session.id);
|
|
4551
|
+
for (const candidate of candidates) {
|
|
4552
|
+
const text = flattenPlainText(candidate.event.data.message.content);
|
|
4553
|
+
if (text === void 0) continue;
|
|
4554
|
+
ledger.noteFullText({
|
|
4555
|
+
sessionId: sid,
|
|
4556
|
+
seq: candidate.seq,
|
|
4557
|
+
text,
|
|
4558
|
+
measure: () => candidate.count.kind === "exact-tokenizer" && typeof candidate.count.tokens === "number" ? {
|
|
4559
|
+
tokens: candidate.count.tokens,
|
|
4560
|
+
basis: "exact-tokenizer"
|
|
4561
|
+
} : {
|
|
4562
|
+
tokens: Math.ceil(candidate.characterPressure / 4),
|
|
4563
|
+
basis: "characters"
|
|
4564
|
+
}
|
|
4565
|
+
});
|
|
4566
|
+
}
|
|
4758
4567
|
const plans = /* @__PURE__ */ new Map();
|
|
4759
4568
|
let freshPlanned = 0;
|
|
4760
4569
|
const dedupeEnabled = policy.presetOptions?.dedupeToolResults === true;
|
|
@@ -5249,6 +5058,16 @@ var ToolResultPruner = class extends Service {
|
|
|
5249
5058
|
tokenizerId: exact === true && exactSurface !== void 0 ? exactSurface.tokenizerId : "characters",
|
|
5250
5059
|
tokenizerRevision: exact === true && exactSurface !== void 0 ? exactSurface.tokenizerRevision : "chars-per-token-4.0"
|
|
5251
5060
|
});
|
|
5061
|
+
const groupText = shadowedSeqs.map((seq) => sessionEvents(session)[seq]).filter((event) => event?.type === "tool/result").map((event) => flattenPlainText(event.data.message.content)).filter((text) => text !== void 0).join("\n");
|
|
5062
|
+
if (groupText.length > 0) getSavingsLedger().recordSaving({
|
|
5063
|
+
sessionId: String(session.id),
|
|
5064
|
+
component: "tail-trim",
|
|
5065
|
+
tokensBefore,
|
|
5066
|
+
tokensAfter,
|
|
5067
|
+
basis: exact ? "exact-tokenizer" : "characters",
|
|
5068
|
+
sourceSeq: manifestSeq,
|
|
5069
|
+
originalText: groupText
|
|
5070
|
+
});
|
|
5252
5071
|
return;
|
|
5253
5072
|
}
|
|
5254
5073
|
this.auditComponent(session, policy, "tail-trim", "pressure", "skipped", "no-safe-eligible-tool-group", {
|
|
@@ -5379,6 +5198,16 @@ var ToolResultPruner = class extends Service {
|
|
|
5379
5198
|
tokenizerRevision: plan.tokenizerRevision,
|
|
5380
5199
|
...plan.elidedLines === void 0 ? {} : { elidedLines: plan.elidedLines }
|
|
5381
5200
|
});
|
|
5201
|
+
const pairedOriginal = originalTextForSavings(candidate);
|
|
5202
|
+
getSavingsLedger().recordSaving({
|
|
5203
|
+
sessionId: String(session.id),
|
|
5204
|
+
component: plan.component,
|
|
5205
|
+
tokensBefore: plan.tokensBefore,
|
|
5206
|
+
tokensAfter: plan.tokensAfter,
|
|
5207
|
+
basis: plan.measurementBasis,
|
|
5208
|
+
sourceSeq: plan.sourceSeq,
|
|
5209
|
+
...pairedOriginal === void 0 ? {} : { originalText: pairedOriginal }
|
|
5210
|
+
});
|
|
5382
5211
|
return {
|
|
5383
5212
|
originalSeq: candidate.seq,
|
|
5384
5213
|
sourceSeq: plan.sourceSeq,
|
|
@@ -306,3 +306,45 @@
|
|
|
306
306
|
margin: 8px 0 0;
|
|
307
307
|
font-size: 12px;
|
|
308
308
|
}
|
|
309
|
+
|
|
310
|
+
._3-mAqa_savingsCard {
|
|
311
|
+
border: 1px solid #ffffff1a;
|
|
312
|
+
border-radius: 8px;
|
|
313
|
+
flex-direction: column;
|
|
314
|
+
gap: 4px;
|
|
315
|
+
margin-top: 14px;
|
|
316
|
+
padding: 10px 12px;
|
|
317
|
+
display: flex;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
._3-mAqa_savingsRow {
|
|
321
|
+
justify-content: space-between;
|
|
322
|
+
align-items: baseline;
|
|
323
|
+
gap: 12px;
|
|
324
|
+
display: flex;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
._3-mAqa_savingsNetPositive strong {
|
|
328
|
+
color: #30d158;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
._3-mAqa_savingsNetNegative strong {
|
|
332
|
+
color: #ff9f0a;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
._3-mAqa_savingsMuted {
|
|
336
|
+
opacity: .66;
|
|
337
|
+
font-size: .92em;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
._3-mAqa_savingsBreakdown {
|
|
341
|
+
border-top: 1px solid #ffffff14;
|
|
342
|
+
margin-top: 4px;
|
|
343
|
+
padding-top: 4px;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
._3-mAqa_savingsNote {
|
|
347
|
+
opacity: .5;
|
|
348
|
+
margin-top: 4px;
|
|
349
|
+
font-size: .85em;
|
|
350
|
+
}
|