dsh-context-compression-improved 0.7.0-beta.1 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.github/workflows/ci.yml +39 -39
- package/CHANGELOG.ja.md +217 -220
- package/CHANGELOG.ko.md +211 -214
- package/CHANGELOG.md +401 -376
- package/CHANGELOG.zh.md +196 -199
- package/README.md +97 -97
- package/README.zh.md +86 -86
- package/package.json +1 -1
- package/packages/selector/dsh.plugin.json +1 -1
- package/packages/selector/lib/client.d.ts +44 -0
- package/packages/selector/lib/client.js +1733 -6
- package/packages/selector/lib/{intent-gate.js → config.js} +799 -136
- package/packages/selector/lib/index.d.ts +13 -1
- package/packages/selector/lib/index.js +204 -3
- package/packages/selector/lib/profiles.d.ts +6 -0
- package/packages/selector/lib/pruner.d.ts +6 -0
- package/packages/selector/lib/pruner.js +90 -258
- package/packages/selector/lib/style.css +88 -46
- package/packages/selector/src/client/CompressionProfileControls.tsx +293 -226
- package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -170
- package/packages/selector/src/client/CompressionProfileSelector.tsx +85 -83
- package/packages/selector/src/client/decode.ts +57 -53
- package/packages/selector/src/client/index.ts +307 -213
- package/packages/selector/src/client/locales/de.ts +141 -0
- package/packages/selector/src/client/locales/es.ts +141 -0
- package/packages/selector/src/client/locales/fr.ts +141 -0
- package/packages/selector/src/client/locales/it.ts +141 -0
- package/packages/selector/src/client/locales/ja.ts +141 -0
- package/packages/selector/src/client/locales/ko.ts +141 -0
- package/packages/selector/src/client/locales/ru.ts +141 -0
- package/packages/selector/src/client/locales.ts +282 -196
- package/packages/selector/src/client/monitor-fab.ts +336 -0
- package/packages/selector/src/client/savings-card.tsx +150 -0
- package/packages/selector/src/client/settings-section.tsx +140 -124
- package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -205
- package/packages/selector/src/index.ts +207 -5
- package/packages/selector/src/preset-overlay.ts +629 -629
- package/packages/selector/src/profiles.ts +431 -414
- package/packages/selector/src/pruner/content.ts +198 -198
- package/packages/selector/src/pruner/state.ts +57 -57
- package/packages/selector/src/pruner.ts +2759 -2665
- package/packages/selector/src/runtime/audit.ts +303 -303
- package/packages/selector/src/runtime/config.ts +756 -731
- package/packages/selector/src/runtime/monitor.ts +235 -0
- package/packages/selector/src/runtime/reducers.ts +1674 -1674
- package/packages/selector/src/runtime/retrieve.ts +479 -457
- package/packages/selector/src/runtime/savings.ts +337 -0
- package/packages/selector/src/runtime/summary-command.ts +133 -133
- package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -233
- package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -204
- package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -53
- package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -65
- package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -125
- package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -37
- package/packages/selector/src/runtime/tokenpilot/locator.ts +128 -128
- package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +306 -306
- package/packages/selector/src/runtime/types.ts +365 -358
- package/packages/selector/tests/built/client-artifact.spec.ts +61 -61
- package/packages/selector/tests/code-skeleton.client.spec.ts +2 -2
- package/packages/selector/tests/custom-contract.client.spec.ts +2 -2
- package/packages/selector/tests/estimator-channel.client.spec.tsx +2 -0
- package/packages/selector/tests/estimator-route-registration.host.spec.ts +194 -188
- package/packages/selector/tests/helpers/legacy-settings/index.ts +15 -15
- package/packages/selector/tests/helpers/legacy-settings/legacy/provider.d.ts +41 -41
- package/packages/selector/tests/helpers/legacy-settings/legacy/provider.js +647 -647
- package/packages/selector/tests/helpers/legacy-settings/legacy/redact.js +78 -78
- package/packages/selector/tests/helpers/legacy-settings/legacy/util-values.js +234 -234
- package/packages/selector/tests/host-preset-overlay.host.spec.ts +203 -203
- package/packages/selector/tests/monitor-fab.client.spec.ts +138 -0
- package/packages/selector/tests/runtime/auto-compact-config.spec.ts +523 -523
- package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +122 -122
- package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -62
- package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -156
- package/packages/selector/tests/runtime/monitor.spec.ts +301 -0
- package/packages/selector/tests/runtime/savings.spec.ts +120 -0
- package/packages/selector/tests/runtime/summary-command.spec.ts +154 -154
- package/packages/selector/tests/settings-seat.client.spec.ts +177 -165
- package/scripts/packed-components-smoke.mjs +734 -734
- package/scripts/packed-install-e2e.mjs +1 -1
- package/scripts/verify-release.mjs +1 -1
- package/tests/TEST_INVENTORY.md +41 -41
- package/tsconfig.tests.json +17 -17
- package/vitest.config.ts +57 -57
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { B as decimalRateNanoUnits, F as recordIntentFold, H as resolveOfficialDeepSeekPrice, I as recordRecertified, L as recordScore, M as getSummaryOverride, N as invalidateOnTaskChange, O as evaluateIntentGate, P as observeIntentEnabled, T as observeContextUsage, U as getSavingsLedger, V as priceOfficialDeepSeekUsage, _ as resolveCustomPolicy, b as COMPRESSION_PROFILES, c as charsToTokens, d as isValidAutoCompactThresholdPercent, f as parseContextCompressionSettings, g as DEFAULT_CUSTOM_COMPRESSION_POLICY, h as CustomCompressionPolicySchema, i as DEFAULTS, k as getAdvisorState, l as codePointLength, m as resolvePolicy, n as CONTEXT_COMPRESSION_SETTINGS_NAMESPACE, o as PRUNE_MARKER, p as resolveConfig, r as ContextCompressionSettingsSchema, s as charsForTokens, t as AUTO_COMPACT_THRESHOLD_LIMITS, u as isCompressionProfile, v as assertNever, y as deepFreeze, z as DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION } from "./config.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
|
}
|
|
@@ -3800,254 +3823,6 @@ function dedupePlaceholder(entry, originalChars) {
|
|
|
3800
3823
|
].join(" ");
|
|
3801
3824
|
}
|
|
3802
3825
|
//#endregion
|
|
3803
|
-
//#region src/runtime/deepseek-official-pricing.ts
|
|
3804
|
-
/** Checked-in DeepSeek official prices and fixed-point provider-usage accounting. */
|
|
3805
|
-
const DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION = "deepseek-official-2026-08-25";
|
|
3806
|
-
/** Wall-clock time at which the checked-in official price pages were verified. */
|
|
3807
|
-
const DEEPSEEK_OFFICIAL_PRICE_CHECKED_AT = "2026-08-25T00:10:20+08:00";
|
|
3808
|
-
const PRICES = Object.freeze({
|
|
3809
|
-
"deepseek-v4-flash": modelPrices("DeepSeek-V4-Flash-0731", [
|
|
3810
|
-
"0.007",
|
|
3811
|
-
"0.22",
|
|
3812
|
-
"0.66"
|
|
3813
|
-
], [
|
|
3814
|
-
"0.014",
|
|
3815
|
-
"0.44",
|
|
3816
|
-
"1.32"
|
|
3817
|
-
], [
|
|
3818
|
-
"0.05",
|
|
3819
|
-
"1.5",
|
|
3820
|
-
"4.5"
|
|
3821
|
-
], [
|
|
3822
|
-
"0.10",
|
|
3823
|
-
"3.0",
|
|
3824
|
-
"9.0"
|
|
3825
|
-
]),
|
|
3826
|
-
"deepseek-v4-pro": modelPrices("DeepSeek-V4-Pro-0813", [
|
|
3827
|
-
"0.022",
|
|
3828
|
-
"0.66",
|
|
3829
|
-
"1.98"
|
|
3830
|
-
], [
|
|
3831
|
-
"0.044",
|
|
3832
|
-
"1.32",
|
|
3833
|
-
"3.96"
|
|
3834
|
-
], [
|
|
3835
|
-
"0.15",
|
|
3836
|
-
"4.5",
|
|
3837
|
-
"13.5"
|
|
3838
|
-
], [
|
|
3839
|
-
"0.30",
|
|
3840
|
-
"9.0",
|
|
3841
|
-
"27.0"
|
|
3842
|
-
]),
|
|
3843
|
-
"deepseek-v4-flash-vision-exp": modelPrices("DeepSeek-V4-Flash-Vision-Exp", [
|
|
3844
|
-
"0.007",
|
|
3845
|
-
"0.22",
|
|
3846
|
-
"0.66"
|
|
3847
|
-
], [
|
|
3848
|
-
"0.014",
|
|
3849
|
-
"0.44",
|
|
3850
|
-
"1.32"
|
|
3851
|
-
], [
|
|
3852
|
-
"0.05",
|
|
3853
|
-
"1.5",
|
|
3854
|
-
"4.5"
|
|
3855
|
-
], [
|
|
3856
|
-
"0.10",
|
|
3857
|
-
"3.0",
|
|
3858
|
-
"9.0"
|
|
3859
|
-
])
|
|
3860
|
-
});
|
|
3861
|
-
const PEAK_RULE = "Asia/Shanghai Mon-Fri 09:00-12:00,14:00-18:00";
|
|
3862
|
-
const USD_SOURCE = "https://api-docs.deepseek.com/quick_start/pricing/";
|
|
3863
|
-
const CNY_SOURCE = "https://api-docs.deepseek.com/zh-cn/quick_start/pricing/";
|
|
3864
|
-
/**
|
|
3865
|
-
* Resolve one immutable official price record; aliases and compatible gateways fail closed.
|
|
3866
|
-
* @param input - exact provider, endpoint, route, model, currency, and timestamp applicability.
|
|
3867
|
-
* @returns An immutable price record or an explicit unpriced reason.
|
|
3868
|
-
*/
|
|
3869
|
-
function resolveOfficialDeepSeekPrice(input) {
|
|
3870
|
-
if (input.provider !== "deepseek-official") return unpriced("unknown provider route");
|
|
3871
|
-
if (input.baseUrlClass !== "official-public") return unpriced("unknown base-url applicability");
|
|
3872
|
-
if (input.apiRoute !== "chat-completions" && input.apiRoute !== "responses") return unpriced("unknown API route");
|
|
3873
|
-
if (!isOfficialModel(input.modelId)) return unpriced("unknown model id");
|
|
3874
|
-
if (input.currency !== "USD" && input.currency !== "CNY") return unpriced("unknown currency");
|
|
3875
|
-
const band = priceBandAt(input.at);
|
|
3876
|
-
if (band === void 0) return unpriced("invalid price timestamp");
|
|
3877
|
-
const model = PRICES[input.modelId];
|
|
3878
|
-
const [inputCacheHit, inputCacheMiss, output] = model[input.currency][band];
|
|
3879
|
-
return {
|
|
3880
|
-
kind: "priced",
|
|
3881
|
-
record: Object.freeze({
|
|
3882
|
-
catalogVersion: DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION,
|
|
3883
|
-
checkedAt: DEEPSEEK_OFFICIAL_PRICE_CHECKED_AT,
|
|
3884
|
-
provider: "deepseek-official",
|
|
3885
|
-
baseUrlClass: "official-public",
|
|
3886
|
-
apiRoute: input.apiRoute,
|
|
3887
|
-
modelId: input.modelId,
|
|
3888
|
-
modelVersion: model.version,
|
|
3889
|
-
currency: input.currency,
|
|
3890
|
-
unitTokens: 1e6,
|
|
3891
|
-
band,
|
|
3892
|
-
inputCacheHit,
|
|
3893
|
-
inputCacheMiss,
|
|
3894
|
-
output,
|
|
3895
|
-
sourceUrl: input.currency === "USD" ? USD_SOURCE : CNY_SOURCE,
|
|
3896
|
-
sourceLocale: input.currency === "USD" ? "en" : "zh-CN",
|
|
3897
|
-
peakRule: PEAK_RULE
|
|
3898
|
-
})
|
|
3899
|
-
};
|
|
3900
|
-
}
|
|
3901
|
-
/**
|
|
3902
|
-
* Classify a timestamp under the published Beijing peak schedule.
|
|
3903
|
-
* @param at - absolute request time to interpret in Asia/Shanghai.
|
|
3904
|
-
* @returns Peak/off-peak, or undefined for an invalid timestamp.
|
|
3905
|
-
*/
|
|
3906
|
-
function priceBandAt(at) {
|
|
3907
|
-
if (!Number.isFinite(at.getTime())) return void 0;
|
|
3908
|
-
const parts = new Intl.DateTimeFormat("en-US", {
|
|
3909
|
-
timeZone: "Asia/Shanghai",
|
|
3910
|
-
weekday: "short",
|
|
3911
|
-
hour: "2-digit",
|
|
3912
|
-
minute: "2-digit",
|
|
3913
|
-
second: "2-digit",
|
|
3914
|
-
hourCycle: "h23"
|
|
3915
|
-
}).formatToParts(at);
|
|
3916
|
-
const values = Object.fromEntries(parts.map((part) => [part.type, part.value]));
|
|
3917
|
-
const weekday = values.weekday;
|
|
3918
|
-
const hour = Number(values.hour);
|
|
3919
|
-
const minute = Number(values.minute);
|
|
3920
|
-
const second = Number(values.second);
|
|
3921
|
-
if (weekday === void 0 || !Number.isInteger(hour) || !Number.isInteger(minute) || !Number.isInteger(second)) return void 0;
|
|
3922
|
-
const workday = weekday !== "Sat" && weekday !== "Sun";
|
|
3923
|
-
const seconds = hour * 3600 + minute * 60 + second;
|
|
3924
|
-
return workday && (seconds >= 32400 && seconds < 43200 || seconds >= 50400 && seconds < 64800) ? "peak" : "off-peak";
|
|
3925
|
-
}
|
|
3926
|
-
/**
|
|
3927
|
-
* Price one completed request, returning a range when it spans a published band boundary.
|
|
3928
|
-
* @param input - exact applicability, request interval, and complete disjoint usage buckets.
|
|
3929
|
-
* @returns Fixed-point exact/range cost or an explicit unpriced reason.
|
|
3930
|
-
*/
|
|
3931
|
-
function priceOfficialDeepSeekUsage(input) {
|
|
3932
|
-
for (const [name, value] of Object.entries(input.usage)) if (!Number.isSafeInteger(value) || value < 0) return unpriced(`invalid ${name}`);
|
|
3933
|
-
if (input.completedAt.getTime() < input.startedAt.getTime()) return unpriced("completion timestamp precedes request start");
|
|
3934
|
-
const start = resolveOfficialDeepSeekPrice({
|
|
3935
|
-
...input,
|
|
3936
|
-
at: input.startedAt
|
|
3937
|
-
});
|
|
3938
|
-
if (start.kind === "unpriced") return start;
|
|
3939
|
-
const end = resolveOfficialDeepSeekPrice({
|
|
3940
|
-
...input,
|
|
3941
|
-
at: input.completedAt
|
|
3942
|
-
});
|
|
3943
|
-
if (end.kind === "unpriced") return end;
|
|
3944
|
-
const startAmount = amountFor(start.record, input.usage);
|
|
3945
|
-
if (startAmount === void 0) return unpriced("invalid decimal price record");
|
|
3946
|
-
const crossesBoundary = spansPublishedPriceBoundary(input.startedAt, input.completedAt);
|
|
3947
|
-
if (start.record.band === end.record.band && !crossesBoundary) return {
|
|
3948
|
-
kind: "exact",
|
|
3949
|
-
currency: start.record.currency,
|
|
3950
|
-
band: start.record.band,
|
|
3951
|
-
...startAmount
|
|
3952
|
-
};
|
|
3953
|
-
const comparisonRecord = start.record.band === end.record.band ? priceRecordInBand(start.record, start.record.band === "peak" ? "off-peak" : "peak") : end.record;
|
|
3954
|
-
const endAmount = amountFor(comparisonRecord, input.usage);
|
|
3955
|
-
if (endAmount === void 0) return unpriced("invalid decimal price record");
|
|
3956
|
-
const startFemto = BigInt(startAmount.femtoUnits);
|
|
3957
|
-
const endFemto = BigInt(endAmount.femtoUnits);
|
|
3958
|
-
return {
|
|
3959
|
-
kind: "range",
|
|
3960
|
-
currency: start.record.currency,
|
|
3961
|
-
bands: [start.record.band, comparisonRecord.band],
|
|
3962
|
-
minimum: startFemto <= endFemto ? startAmount : endAmount,
|
|
3963
|
-
maximum: startFemto <= endFemto ? endAmount : startAmount
|
|
3964
|
-
};
|
|
3965
|
-
}
|
|
3966
|
-
/** Detect any published UTC band boundary, even when both endpoints share a band. */
|
|
3967
|
-
function spansPublishedPriceBoundary(startedAt, completedAt) {
|
|
3968
|
-
const start = startedAt.getTime();
|
|
3969
|
-
const end = completedAt.getTime();
|
|
3970
|
-
if (end <= start) return false;
|
|
3971
|
-
const dayMs = 864e5;
|
|
3972
|
-
if (end - start >= 7 * dayMs) return true;
|
|
3973
|
-
const firstDay = Math.floor(start / dayMs) * dayMs;
|
|
3974
|
-
for (let day = firstDay; day <= end; day += dayMs) {
|
|
3975
|
-
const weekday = new Date(day).getUTCDay();
|
|
3976
|
-
if (weekday === 0 || weekday === 6) continue;
|
|
3977
|
-
for (const hour of [
|
|
3978
|
-
1,
|
|
3979
|
-
4,
|
|
3980
|
-
6,
|
|
3981
|
-
10
|
|
3982
|
-
]) {
|
|
3983
|
-
const boundary = day + hour * 60 * 60 * 1e3;
|
|
3984
|
-
if (boundary > start && boundary <= end) return true;
|
|
3985
|
-
}
|
|
3986
|
-
}
|
|
3987
|
-
return false;
|
|
3988
|
-
}
|
|
3989
|
-
function priceRecordInBand(record, band) {
|
|
3990
|
-
const [inputCacheHit, inputCacheMiss, output] = PRICES[record.modelId][record.currency][band];
|
|
3991
|
-
return Object.freeze({
|
|
3992
|
-
...record,
|
|
3993
|
-
band,
|
|
3994
|
-
inputCacheHit,
|
|
3995
|
-
inputCacheMiss,
|
|
3996
|
-
output
|
|
3997
|
-
});
|
|
3998
|
-
}
|
|
3999
|
-
/**
|
|
4000
|
-
* Parse a non-negative decimal rate into nano-currency units, without Number arithmetic.
|
|
4001
|
-
* @param value - canonical non-negative decimal with at most nine fractional digits.
|
|
4002
|
-
* @returns Integer nano-units, or undefined when the decimal is invalid.
|
|
4003
|
-
*/
|
|
4004
|
-
function decimalRateNanoUnits(value) {
|
|
4005
|
-
const match = /^(0|[1-9]\d*)(?:\.(\d{1,9}))?$/u.exec(value);
|
|
4006
|
-
if (match === null) return void 0;
|
|
4007
|
-
const whole = match[1] ?? "0";
|
|
4008
|
-
const fraction = (match[2] ?? "").padEnd(9, "0");
|
|
4009
|
-
return BigInt(whole) * 1000000000n + BigInt(fraction || "0");
|
|
4010
|
-
}
|
|
4011
|
-
function amountFor(record, usage) {
|
|
4012
|
-
const hit = decimalRateNanoUnits(record.inputCacheHit);
|
|
4013
|
-
const miss = decimalRateNanoUnits(record.inputCacheMiss);
|
|
4014
|
-
const output = decimalRateNanoUnits(record.output);
|
|
4015
|
-
if (hit === void 0 || miss === void 0 || output === void 0) return void 0;
|
|
4016
|
-
const femtoUnits = BigInt(usage.cacheReadTokens) * hit + BigInt(usage.cacheMissTokens) * miss + BigInt(usage.outputTokens) * output;
|
|
4017
|
-
return {
|
|
4018
|
-
femtoUnits: femtoUnits.toString(),
|
|
4019
|
-
decimal: formatFemto(femtoUnits)
|
|
4020
|
-
};
|
|
4021
|
-
}
|
|
4022
|
-
function formatFemto(value) {
|
|
4023
|
-
const digits = value.toString().padStart(16, "0");
|
|
4024
|
-
const whole = digits.slice(0, -15);
|
|
4025
|
-
const fraction = digits.slice(-15).replace(/0+$/u, "");
|
|
4026
|
-
return fraction.length === 0 ? whole : `${whole}.${fraction}`;
|
|
4027
|
-
}
|
|
4028
|
-
function modelPrices(version, usdOffPeak, usdPeak, cnyOffPeak, cnyPeak) {
|
|
4029
|
-
return Object.freeze({
|
|
4030
|
-
version,
|
|
4031
|
-
USD: Object.freeze({
|
|
4032
|
-
"off-peak": usdOffPeak,
|
|
4033
|
-
peak: usdPeak
|
|
4034
|
-
}),
|
|
4035
|
-
CNY: Object.freeze({
|
|
4036
|
-
"off-peak": cnyOffPeak,
|
|
4037
|
-
peak: cnyPeak
|
|
4038
|
-
})
|
|
4039
|
-
});
|
|
4040
|
-
}
|
|
4041
|
-
function isOfficialModel(value) {
|
|
4042
|
-
return Object.prototype.hasOwnProperty.call(PRICES, value);
|
|
4043
|
-
}
|
|
4044
|
-
function unpriced(reason) {
|
|
4045
|
-
return {
|
|
4046
|
-
kind: "unpriced",
|
|
4047
|
-
reason
|
|
4048
|
-
};
|
|
4049
|
-
}
|
|
4050
|
-
//#endregion
|
|
4051
3826
|
//#region src/runtime/adaptive-cost.ts
|
|
4052
3827
|
/**
|
|
4053
3828
|
* Bound Adaptive's benefit and cache-loss exposure without attributing the
|
|
@@ -4189,6 +3964,10 @@ function emitCompressionAudit(logger, record) {
|
|
|
4189
3964
|
*
|
|
4190
3965
|
* @module dsh-context-compression-improved-runtime
|
|
4191
3966
|
*/
|
|
3967
|
+
/** 节省统计配对键用原文(纯文本块才可配对;富内容返回 undefined)。 */
|
|
3968
|
+
function originalTextForSavings(candidate) {
|
|
3969
|
+
return flattenPlainText(candidate.event.data.message.content);
|
|
3970
|
+
}
|
|
4192
3971
|
/** Mixed deterministic selector behind the existing `ctx.toolResultPruner` seam. */
|
|
4193
3972
|
var ToolResultPruner = class extends Service {
|
|
4194
3973
|
static inject = ["tokenMeter"];
|
|
@@ -4237,6 +4016,14 @@ var ToolResultPruner = class extends Service {
|
|
|
4237
4016
|
intentFoldedSeqs: /* @__PURE__ */ new WeakMap(),
|
|
4238
4017
|
intentBaselines: /* @__PURE__ */ new WeakMap()
|
|
4239
4018
|
};
|
|
4019
|
+
try {
|
|
4020
|
+
ctx.on("session/disposed", (session) => {
|
|
4021
|
+
try {
|
|
4022
|
+
const line = getSavingsLedger().sessionSummaryLine(String(session.id));
|
|
4023
|
+
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);
|
|
4024
|
+
} catch {}
|
|
4025
|
+
});
|
|
4026
|
+
} catch {}
|
|
4240
4027
|
ctx.on("session/event", (session, event) => {
|
|
4241
4028
|
this.scanForSeededNativeSummary(session);
|
|
4242
4029
|
if (event.type === "compaction/summary") {
|
|
@@ -4277,6 +4064,9 @@ var ToolResultPruner = class extends Service {
|
|
|
4277
4064
|
this.auditFailure(agent.session, "fresh", "terminal-pass", error);
|
|
4278
4065
|
ctx.logger.warn("context-compression terminal pass failed open: %o", error);
|
|
4279
4066
|
}
|
|
4067
|
+
try {
|
|
4068
|
+
observeContextUsage(String(agent.session.id), measureForCompaction(this.ctx, agent.session).totalTokens, this.contextWindowForRequest(agent.session));
|
|
4069
|
+
} catch {}
|
|
4280
4070
|
this.postflightEstimatorPass(agent.session, signal).catch(() => void 0);
|
|
4281
4071
|
this.postflightAdvisorPass(agent.session, turn, signal).catch(() => void 0);
|
|
4282
4072
|
this.postflightIntentFoldPass(agent.session, turn, signal).catch(() => void 0);
|
|
@@ -4311,7 +4101,11 @@ var ToolResultPruner = class extends Service {
|
|
|
4311
4101
|
if (policy === void 0) return emptyResult();
|
|
4312
4102
|
const profile = policy.profile;
|
|
4313
4103
|
const view = measureForCompaction(this.ctx, session);
|
|
4314
|
-
if (stage === "fresh")
|
|
4104
|
+
if (stage === "fresh") {
|
|
4105
|
+
const usage = officialRequestUsage(view);
|
|
4106
|
+
if (usage !== void 0) getSavingsLedger().recordUsage(String(session.id), usage);
|
|
4107
|
+
return this.decideFreshStep(session, options, policy, view);
|
|
4108
|
+
}
|
|
4315
4109
|
if (profile === "off") return emptyResult();
|
|
4316
4110
|
const landed = [];
|
|
4317
4111
|
if (policy.nativeToolResultEnabled) {
|
|
@@ -5130,6 +4924,24 @@ var ToolResultPruner = class extends Service {
|
|
|
5130
4924
|
this.auditComponent(session, policy, "aggregate", "fresh", policy.aggregateEnabled ? "skipped" : "disabled", policy.aggregateEnabled ? "no-new-tool-result-candidates" : "profile-policy");
|
|
5131
4925
|
return emptyResult();
|
|
5132
4926
|
}
|
|
4927
|
+
const ledger = getSavingsLedger();
|
|
4928
|
+
const sid = String(session.id);
|
|
4929
|
+
for (const candidate of candidates) {
|
|
4930
|
+
const text = flattenPlainText(candidate.event.data.message.content);
|
|
4931
|
+
if (text === void 0) continue;
|
|
4932
|
+
ledger.noteFullText({
|
|
4933
|
+
sessionId: sid,
|
|
4934
|
+
seq: candidate.seq,
|
|
4935
|
+
text,
|
|
4936
|
+
measure: () => candidate.count.kind === "exact-tokenizer" && typeof candidate.count.tokens === "number" ? {
|
|
4937
|
+
tokens: candidate.count.tokens,
|
|
4938
|
+
basis: "exact-tokenizer"
|
|
4939
|
+
} : {
|
|
4940
|
+
tokens: Math.ceil(candidate.characterPressure / 4),
|
|
4941
|
+
basis: "characters"
|
|
4942
|
+
}
|
|
4943
|
+
});
|
|
4944
|
+
}
|
|
5133
4945
|
const plans = /* @__PURE__ */ new Map();
|
|
5134
4946
|
let freshPlanned = 0;
|
|
5135
4947
|
const dedupeEnabled = policy.presetOptions?.dedupeToolResults === true;
|
|
@@ -5652,6 +5464,16 @@ var ToolResultPruner = class extends Service {
|
|
|
5652
5464
|
tokenizerId: exact === true && exactSurface !== void 0 ? exactSurface.tokenizerId : "characters",
|
|
5653
5465
|
tokenizerRevision: exact === true && exactSurface !== void 0 ? exactSurface.tokenizerRevision : "chars-per-token-4.0"
|
|
5654
5466
|
});
|
|
5467
|
+
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");
|
|
5468
|
+
if (groupText.length > 0) getSavingsLedger().recordSaving({
|
|
5469
|
+
sessionId: String(session.id),
|
|
5470
|
+
component: "tail-trim",
|
|
5471
|
+
tokensBefore,
|
|
5472
|
+
tokensAfter,
|
|
5473
|
+
basis: exact ? "exact-tokenizer" : "characters",
|
|
5474
|
+
sourceSeq: manifestSeq,
|
|
5475
|
+
originalText: groupText
|
|
5476
|
+
});
|
|
5655
5477
|
return;
|
|
5656
5478
|
}
|
|
5657
5479
|
this.auditComponent(session, policy, "tail-trim", "pressure", "skipped", "no-safe-eligible-tool-group", {
|
|
@@ -5782,6 +5604,16 @@ var ToolResultPruner = class extends Service {
|
|
|
5782
5604
|
tokenizerRevision: plan.tokenizerRevision,
|
|
5783
5605
|
...plan.elidedLines === void 0 ? {} : { elidedLines: plan.elidedLines }
|
|
5784
5606
|
});
|
|
5607
|
+
const pairedOriginal = originalTextForSavings(candidate);
|
|
5608
|
+
getSavingsLedger().recordSaving({
|
|
5609
|
+
sessionId: String(session.id),
|
|
5610
|
+
component: plan.component,
|
|
5611
|
+
tokensBefore: plan.tokensBefore,
|
|
5612
|
+
tokensAfter: plan.tokensAfter,
|
|
5613
|
+
basis: plan.measurementBasis,
|
|
5614
|
+
sourceSeq: plan.sourceSeq,
|
|
5615
|
+
...pairedOriginal === void 0 ? {} : { originalText: pairedOriginal }
|
|
5616
|
+
});
|
|
5785
5617
|
return {
|
|
5786
5618
|
originalSeq: candidate.seq,
|
|
5787
5619
|
sourceSeq: plan.sourceSeq,
|