dsh-context-compression-improved 0.8.0-beta.2 → 0.8.0-beta.4
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 +16 -0
- package/eslint.config.js +30 -30
- package/package.json +163 -163
- package/packages/selector/dsh.plugin.json +16 -16
- package/packages/selector/lib/client.d.ts +20 -0
- package/packages/selector/lib/client.js +433 -17
- package/packages/selector/lib/index.js +213 -2
- package/packages/selector/lib/{advisor-state.js → intent-gate.js} +593 -3
- package/packages/selector/lib/profiles.d.ts +9 -0
- package/packages/selector/lib/pruner.d.ts +59 -0
- package/packages/selector/lib/pruner.js +494 -262
- package/packages/selector/lib/style.css +42 -0
- package/packages/selector/src/client/CompressionProfileControls.tsx +34 -0
- package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -170
- package/packages/selector/src/client/CompressionProfileSelector.tsx +1 -0
- package/packages/selector/src/client/decode.ts +53 -49
- package/packages/selector/src/client/index.ts +4 -0
- package/packages/selector/src/client/locales/de.ts +20 -0
- package/packages/selector/src/client/locales/es.ts +20 -0
- package/packages/selector/src/client/locales/fr.ts +20 -0
- package/packages/selector/src/client/locales/it.ts +20 -0
- package/packages/selector/src/client/locales/ja.ts +20 -0
- package/packages/selector/src/client/locales/ko.ts +20 -0
- package/packages/selector/src/client/locales/ru.ts +20 -0
- package/packages/selector/src/client/locales.ts +236 -196
- package/packages/selector/src/client/savings-card.tsx +150 -0
- package/packages/selector/src/client/settings-section.tsx +133 -124
- package/packages/selector/src/index.ts +554 -411
- package/packages/selector/src/profiles.ts +414 -394
- package/packages/selector/src/pruner/state.ts +57 -50
- package/packages/selector/src/pruner.ts +2745 -2421
- package/packages/selector/src/runtime/audit.ts +303 -286
- package/packages/selector/src/runtime/config.ts +731 -706
- 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 +127 -0
- package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -188
- package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -149
- package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
- package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
- package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
- package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
- package/packages/selector/src/runtime/types.ts +358 -346
- package/packages/selector/tests/auto-compact.client.spec.tsx +214 -213
- package/packages/selector/tests/code-skeleton.client.spec.ts +94 -93
- package/packages/selector/tests/custom-contract.client.spec.ts +223 -222
- package/packages/selector/tests/estimator-channel.client.spec.tsx +253 -252
- package/packages/selector/tests/estimator-route-registration.host.spec.ts +192 -188
- package/packages/selector/tests/preset-options-write.client.spec.ts +188 -187
- package/packages/selector/tests/profiles.client.spec.tsx +436 -434
- package/packages/selector/tests/runtime/audit.spec.ts +275 -274
- package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
- package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
- package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2734 -2731
- package/packages/selector/tests/runtime/savings.spec.ts +120 -0
- package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
- package/packages/selector/tests/settings-seat.client.spec.ts +1 -1
- package/scripts/packed-install-e2e.mjs +1 -1
- package/scripts/verify-release.mjs +2 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { C as
|
|
1
|
+
import { A as resolveCustomPolicy, C as isCompressionProfile, D as resolvePolicy, E as resolveConfig, F as decimalRateNanoUnits, I as priceOfficialDeepSeekUsage, L as resolveOfficialDeepSeekPrice, M as deepFreeze, N as COMPRESSION_PROFILES, O as CustomCompressionPolicySchema, P as DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION, R as getSavingsLedger, S as codePointLength, T as parseContextCompressionSettings, _ as DEFAULTS, b as charsForTokens, c as invalidateOnTaskChange, d as recordRecertified, f as recordScore, g as ContextCompressionSettingsSchema, h as CONTEXT_COMPRESSION_SETTINGS_NAMESPACE, i as getAdvisorState, j as assertNever, k as DEFAULT_CUSTOM_COMPRESSION_POLICY, l as observeIntentEnabled, m as AUTO_COMPACT_THRESHOLD_LIMITS, r as evaluateIntentGate, s as getSummaryOverride, u as recordIntentFold, w as isValidAutoCompactThresholdPercent, x as charsToTokens, y as PRUNE_MARKER } from "./intent-gate.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
|
}
|
|
@@ -1397,7 +1420,7 @@ function reduceFreshToolResult(input, ranking) {
|
|
|
1397
1420
|
lines: normalized.folded,
|
|
1398
1421
|
contentText: normalized.contentText
|
|
1399
1422
|
};
|
|
1400
|
-
const command = extractCommand(input.argumentsText);
|
|
1423
|
+
const command = extractCommand$1(input.argumentsText);
|
|
1401
1424
|
const name = input.toolName.toLowerCase();
|
|
1402
1425
|
const toolClass = classifyToolSource(input.toolName, command, normalized.contentText);
|
|
1403
1426
|
const readTocFirst = toolClass === "read" && codePointLength(normalized.contentText) >= READ_TOC_MIN_CHARS;
|
|
@@ -2680,7 +2703,7 @@ function splitLines(text) {
|
|
|
2680
2703
|
* @param argumentsText - raw JSON arguments of the tool call.
|
|
2681
2704
|
* @returns the command string, or '' when absent.
|
|
2682
2705
|
*/
|
|
2683
|
-
function extractCommand(argumentsText) {
|
|
2706
|
+
function extractCommand$1(argumentsText) {
|
|
2684
2707
|
try {
|
|
2685
2708
|
const parsed = JSON.parse(argumentsText);
|
|
2686
2709
|
if (typeof parsed !== "object" || parsed === null) return "";
|
|
@@ -3248,6 +3271,42 @@ function parseAdvisorScores(text, validSeqs) {
|
|
|
3248
3271
|
}
|
|
3249
3272
|
return scores.size > 0 ? scores : void 0;
|
|
3250
3273
|
}
|
|
3274
|
+
/** Hard character cap for one intent-summary answer (summary segment only). */
|
|
3275
|
+
const INTENT_SUMMARY_CHAR_CAP = 1600;
|
|
3276
|
+
/**
|
|
3277
|
+
* Intent-summary writer prompts (task_2.3). Input records are already
|
|
3278
|
+
* semantic-role-masked by intent-input-mask.ts: read-class candidates are
|
|
3279
|
+
* one-line "read X" records, keep-class candidates carry skeleton heads and
|
|
3280
|
+
* VERBATIM error lines. The model writes ONLY the summary segment — it never
|
|
3281
|
+
* revoices error lines, and its answer must stay inside the char cap.
|
|
3282
|
+
*/
|
|
3283
|
+
function buildIntentSummarySystemPrompt() {
|
|
3284
|
+
return [
|
|
3285
|
+
"You write one concise intent summary of folded tool results for a coding agent session.",
|
|
3286
|
+
"Input: the session task (todolist) and per-tool slimmed records (read lines, or skeleton heads with verbatim error lines).",
|
|
3287
|
+
`Write ONLY what the agent DID and LEARNED in this span, as flowing prose under ${INTENT_SUMMARY_CHAR_CAP} characters.`,
|
|
3288
|
+
"Mention which files/areas were consulted and what changed, so a later turn can continue without the originals.",
|
|
3289
|
+
"Never invent files, commands, or outcomes absent from the records. Never revoice error lines; they are preserved verbatim elsewhere.",
|
|
3290
|
+
"Answer with ONLY one JSON object: {\"summary\":\"<prose>\"}. Never add commentary."
|
|
3291
|
+
].join(" ");
|
|
3292
|
+
}
|
|
3293
|
+
function buildIntentSummaryUserPrompt(taskText, records, tailText) {
|
|
3294
|
+
const nl = String.fromCharCode(10);
|
|
3295
|
+
return [
|
|
3296
|
+
`task: ${taskText.replace(/\s+/gu, " ").slice(0, 600)}`,
|
|
3297
|
+
records.length > 0 ? `records:${nl}${records.join(nl)}` : "records: (none)",
|
|
3298
|
+
tailText.trim().length > 0 ? `recent tail:${nl}${tailText.trim().slice(0, 1200)}` : "recent tail: (none)"
|
|
3299
|
+
].join("\n\n");
|
|
3300
|
+
}
|
|
3301
|
+
/** Fail-open parse of one intent-summary answer; `undefined` on any malformed shape. */
|
|
3302
|
+
function parseIntentSummaryAnswer(text) {
|
|
3303
|
+
const parsed = firstJsonObject(text);
|
|
3304
|
+
if (parsed === void 0) return void 0;
|
|
3305
|
+
const summary = parsed.summary;
|
|
3306
|
+
if (typeof summary !== "string" || summary.trim().length === 0) return void 0;
|
|
3307
|
+
if (summary.length > 3200) return void 0;
|
|
3308
|
+
return { summary: summary.trim().slice(0, INTENT_SUMMARY_CHAR_CAP) };
|
|
3309
|
+
}
|
|
3251
3310
|
//#endregion
|
|
3252
3311
|
//#region src/runtime/tokenpilot/advisor.ts
|
|
3253
3312
|
/** Character cap for the recent-text fallback and the tail-text summary input. */
|
|
@@ -3549,6 +3608,162 @@ async function runSessionAdvisorPass(session, channel, emit, input) {
|
|
|
3549
3608
|
}
|
|
3550
3609
|
}
|
|
3551
3610
|
//#endregion
|
|
3611
|
+
//#region src/runtime/tokenpilot/intent-input-mask.ts
|
|
3612
|
+
/**
|
|
3613
|
+
* Semantic-role input masking for the intent-summary writer (task_2.2).
|
|
3614
|
+
*
|
|
3615
|
+
* The intent summary records historical TASK semantics — for read-class tools
|
|
3616
|
+
* the semantics are "read X", never the file body, so the body is masked to a
|
|
3617
|
+
* one-line record before it can reach the summary prompt. Write-class results
|
|
3618
|
+
* (edits) ARE task semantics and keep their skeleton + verbatim error lines.
|
|
3619
|
+
*
|
|
3620
|
+
* Classification REUSES `classifyToolSource()` (reducers.ts routes on the
|
|
3621
|
+
* same classes): hand-rolling a name→role map here would regress its fixed
|
|
3622
|
+
* misclassification edges (mcp→generic, web_search/memory_search not being
|
|
3623
|
+
* content search, glob being path-listing, execute_sql not being shell).
|
|
3624
|
+
* Only the write class is layered on top — `ToolClass` has no write member.
|
|
3625
|
+
*/
|
|
3626
|
+
/** Exact-token write layer, same tokenization discipline as toolclass. */
|
|
3627
|
+
const WRITE_NAMES = /* @__PURE__ */ new Set([
|
|
3628
|
+
"apply_patch",
|
|
3629
|
+
"multi_edit",
|
|
3630
|
+
"create_file",
|
|
3631
|
+
"write_to_file",
|
|
3632
|
+
"str_replace_editor"
|
|
3633
|
+
]);
|
|
3634
|
+
const WRITE_TOKENS = /* @__PURE__ */ new Set([
|
|
3635
|
+
"write",
|
|
3636
|
+
"edit",
|
|
3637
|
+
"patch"
|
|
3638
|
+
]);
|
|
3639
|
+
function hasWriteToken(name) {
|
|
3640
|
+
const lowered = name.toLowerCase();
|
|
3641
|
+
if (WRITE_NAMES.has(lowered)) return true;
|
|
3642
|
+
return lowered.split(/[-_/]+/).some((token) => WRITE_TOKENS.has(token));
|
|
3643
|
+
}
|
|
3644
|
+
/**
|
|
3645
|
+
* Role for one candidate. The write layer is consulted first; everything
|
|
3646
|
+
* else defers to the shared classifier. `shell`/`generic` stay conservative
|
|
3647
|
+
* (skeleton + error lines, never a blind mask) — a bash result can be a
|
|
3648
|
+
* mutation even when its name says nothing.
|
|
3649
|
+
*/
|
|
3650
|
+
function classifyIntentRole(toolName, command, text) {
|
|
3651
|
+
if (hasWriteToken(toolName)) return "write-keep";
|
|
3652
|
+
const toolClass = classifyToolSource(toolName, command, text);
|
|
3653
|
+
if (toolClass === "read" || toolClass === "search" || toolClass === "path-listing") return "read-mask";
|
|
3654
|
+
return "conservative";
|
|
3655
|
+
}
|
|
3656
|
+
const ERROR_LINE_PATTERN = /\b(error|failed|failure|exception|panic|fatal|traceback|unreachable|denied)\b/i;
|
|
3657
|
+
const KEEP_HEAD_LINES = 40;
|
|
3658
|
+
const KEEP_HEAD_CHARS = 2e3;
|
|
3659
|
+
/** Verbatim error/warn lines kept out of the LLM's hands and into the intent block. */
|
|
3660
|
+
function extractErrorLines(text) {
|
|
3661
|
+
return text.split("\n").filter((line) => ERROR_LINE_PATTERN.test(line)).slice(0, 10);
|
|
3662
|
+
}
|
|
3663
|
+
/** Count lines and code points for the read-mask record tail. */
|
|
3664
|
+
function scaleOf(text) {
|
|
3665
|
+
return {
|
|
3666
|
+
lines: text.length === 0 ? 0 : text.split("\n").length,
|
|
3667
|
+
chars: text.length
|
|
3668
|
+
};
|
|
3669
|
+
}
|
|
3670
|
+
/**
|
|
3671
|
+
* Build the prompt face for one candidate. Read-mask output contains NONE of
|
|
3672
|
+
* the original body — only the tool name, the call's target argument, and
|
|
3673
|
+
* the dropped scale — so a hostile body can never leak into the summary.
|
|
3674
|
+
*/
|
|
3675
|
+
function maskCandidateForSummary(seq, toolName, argumentsText, text) {
|
|
3676
|
+
const role = classifyIntentRole(toolName, extractCommand(argumentsText), text);
|
|
3677
|
+
if (role === "read-mask") {
|
|
3678
|
+
const { lines, chars } = scaleOf(text);
|
|
3679
|
+
return {
|
|
3680
|
+
seq,
|
|
3681
|
+
role,
|
|
3682
|
+
record: `${toolName} ${extractTarget(argumentsText)} -> masked (${lines} lines / ${chars} chars)`
|
|
3683
|
+
};
|
|
3684
|
+
}
|
|
3685
|
+
const head = text.split("\n", KEEP_HEAD_LINES).join("\n").slice(0, KEEP_HEAD_CHARS);
|
|
3686
|
+
const errorLines = extractErrorLines(text);
|
|
3687
|
+
return {
|
|
3688
|
+
seq,
|
|
3689
|
+
role,
|
|
3690
|
+
record: `${toolName} (seq ${seq})\n${head}${errorLines.length > 0 ? `\nerror lines (verbatim):\n${errorLines.join("\n")}` : ""}`
|
|
3691
|
+
};
|
|
3692
|
+
}
|
|
3693
|
+
/** Extract a short command head from a tool-call arguments JSON string. */
|
|
3694
|
+
function extractCommand(argumentsText) {
|
|
3695
|
+
try {
|
|
3696
|
+
const parsed = JSON.parse(argumentsText);
|
|
3697
|
+
if (parsed !== null && typeof parsed === "object") {
|
|
3698
|
+
const command = parsed.command;
|
|
3699
|
+
if (typeof command === "string") return command.slice(0, 200);
|
|
3700
|
+
}
|
|
3701
|
+
} catch {}
|
|
3702
|
+
return "";
|
|
3703
|
+
}
|
|
3704
|
+
/** Extract the most target-like string argument (path/query/url) for read-mask records. */
|
|
3705
|
+
function extractTarget(argumentsText) {
|
|
3706
|
+
try {
|
|
3707
|
+
const parsed = JSON.parse(argumentsText);
|
|
3708
|
+
if (parsed !== null && typeof parsed === "object") {
|
|
3709
|
+
const record = parsed;
|
|
3710
|
+
const target = [
|
|
3711
|
+
record.path,
|
|
3712
|
+
record.file_path,
|
|
3713
|
+
record.query,
|
|
3714
|
+
record.url,
|
|
3715
|
+
record.pattern,
|
|
3716
|
+
record.glob
|
|
3717
|
+
].find((candidate) => typeof candidate === "string" && candidate.trim().length > 0);
|
|
3718
|
+
if (typeof target === "string") return target.slice(0, 160);
|
|
3719
|
+
const first = Object.values(record).find((value) => typeof value === "string");
|
|
3720
|
+
if (typeof first === "string") return first.slice(0, 160);
|
|
3721
|
+
}
|
|
3722
|
+
} catch {}
|
|
3723
|
+
return "(unparsed target)";
|
|
3724
|
+
}
|
|
3725
|
+
//#endregion
|
|
3726
|
+
//#region src/runtime/tokenpilot/intent-range.ts
|
|
3727
|
+
/**
|
|
3728
|
+
* Oldest-first selection of foldable candidates. Excludes the protected
|
|
3729
|
+
* working set and already-folded seqs; caps the batch size.
|
|
3730
|
+
*/
|
|
3731
|
+
function computeIntentRange(input) {
|
|
3732
|
+
const unprotected = input.candidates.filter((candidate) => !input.protectedSeqs.has(candidate.seq));
|
|
3733
|
+
const skippedProtected = input.candidates.length - unprotected.length;
|
|
3734
|
+
const eligible = unprotected.filter((candidate) => !input.foldedSeqs.has(candidate.seq));
|
|
3735
|
+
const skippedFolded = unprotected.length - eligible.length;
|
|
3736
|
+
return {
|
|
3737
|
+
seqs: [...eligible].sort((a, b) => a.seq - b.seq).slice(0, Math.max(0, input.maxCandidates)).map((candidate) => candidate.seq),
|
|
3738
|
+
skippedProtected,
|
|
3739
|
+
skippedFolded
|
|
3740
|
+
};
|
|
3741
|
+
}
|
|
3742
|
+
//#endregion
|
|
3743
|
+
//#region src/runtime/tokenpilot/intent-fold.ts
|
|
3744
|
+
/** Marker written into every folded block; its presence makes a seq unfoldable again (fold-once). */
|
|
3745
|
+
const INTENT_FOLD_MARKER = "[Intent summary";
|
|
3746
|
+
/** Render the replacement text for one folded candidate. Pure. */
|
|
3747
|
+
function renderIntentFoldBlock(pending, seq) {
|
|
3748
|
+
const start = pending.startSeq;
|
|
3749
|
+
const end = pending.endSeq;
|
|
3750
|
+
if (seq === start) {
|
|
3751
|
+
const readLines = pending.records.filter((record) => record.role === "read-mask").map((record) => record.line);
|
|
3752
|
+
const consulted = readLines.length > 0 ? `Consulted: ${readLines.join("; ")}` : "";
|
|
3753
|
+
const errorBlock = pending.errorLines.length > 0 ? `\nError lines (verbatim):\n${pending.errorLines.join("\n")}` : "";
|
|
3754
|
+
return [
|
|
3755
|
+
`${INTENT_FOLD_MARKER} of folded tool results seq ${start}..${end}]`,
|
|
3756
|
+
pending.summary,
|
|
3757
|
+
consulted,
|
|
3758
|
+
errorBlock,
|
|
3759
|
+
"[Original content remains in the session log at the listed seq values.]"
|
|
3760
|
+
].filter((part) => part.length > 0).join("\n");
|
|
3761
|
+
}
|
|
3762
|
+
const record = pending.records.find((entry) => entry.seq === seq);
|
|
3763
|
+
const face = record === void 0 ? `${seq}` : record.role === "read-mask" ? record.line : `${record.toolName} result folded into the batch intent summary`;
|
|
3764
|
+
return `${INTENT_FOLD_MARKER} folded into the batch summary above (seq ${start}..${end})] ${face}`;
|
|
3765
|
+
}
|
|
3766
|
+
//#endregion
|
|
3552
3767
|
//#region src/runtime/tokenpilot/dedup.ts
|
|
3553
3768
|
/**
|
|
3554
3769
|
* TokenPilot-inspired A1: byte-identical repeated tool-result dedup.
|
|
@@ -3608,254 +3823,6 @@ function dedupePlaceholder(entry, originalChars) {
|
|
|
3608
3823
|
].join(" ");
|
|
3609
3824
|
}
|
|
3610
3825
|
//#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
3826
|
//#region src/runtime/adaptive-cost.ts
|
|
3860
3827
|
/**
|
|
3861
3828
|
* Bound Adaptive's benefit and cache-loss exposure without attributing the
|
|
@@ -3997,6 +3964,10 @@ function emitCompressionAudit(logger, record) {
|
|
|
3997
3964
|
*
|
|
3998
3965
|
* @module dsh-context-compression-improved-runtime
|
|
3999
3966
|
*/
|
|
3967
|
+
/** 节省统计配对键用原文(纯文本块才可配对;富内容返回 undefined)。 */
|
|
3968
|
+
function originalTextForSavings(candidate) {
|
|
3969
|
+
return flattenPlainText(candidate.event.data.message.content);
|
|
3970
|
+
}
|
|
4000
3971
|
/** Mixed deterministic selector behind the existing `ctx.toolResultPruner` seam. */
|
|
4001
3972
|
var ToolResultPruner = class extends Service {
|
|
4002
3973
|
static inject = ["tokenMeter"];
|
|
@@ -4040,8 +4011,19 @@ var ToolResultPruner = class extends Service {
|
|
|
4040
4011
|
policyResolutionAudits: /* @__PURE__ */ new WeakMap(),
|
|
4041
4012
|
turnClocks: /* @__PURE__ */ new WeakMap(),
|
|
4042
4013
|
estimatorRemainingTurns: /* @__PURE__ */ new WeakMap(),
|
|
4043
|
-
advisorChannels: /* @__PURE__ */ new WeakMap()
|
|
4014
|
+
advisorChannels: /* @__PURE__ */ new WeakMap(),
|
|
4015
|
+
pendingIntentFolds: /* @__PURE__ */ new WeakMap(),
|
|
4016
|
+
intentFoldedSeqs: /* @__PURE__ */ new WeakMap(),
|
|
4017
|
+
intentBaselines: /* @__PURE__ */ new WeakMap()
|
|
4044
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 {}
|
|
4045
4027
|
ctx.on("session/event", (session, event) => {
|
|
4046
4028
|
this.scanForSeededNativeSummary(session);
|
|
4047
4029
|
if (event.type === "compaction/summary") {
|
|
@@ -4084,6 +4066,7 @@ var ToolResultPruner = class extends Service {
|
|
|
4084
4066
|
}
|
|
4085
4067
|
this.postflightEstimatorPass(agent.session, signal).catch(() => void 0);
|
|
4086
4068
|
this.postflightAdvisorPass(agent.session, turn, signal).catch(() => void 0);
|
|
4069
|
+
this.postflightIntentFoldPass(agent.session, turn, signal).catch(() => void 0);
|
|
4087
4070
|
});
|
|
4088
4071
|
}
|
|
4089
4072
|
/**
|
|
@@ -4115,7 +4098,11 @@ var ToolResultPruner = class extends Service {
|
|
|
4115
4098
|
if (policy === void 0) return emptyResult();
|
|
4116
4099
|
const profile = policy.profile;
|
|
4117
4100
|
const view = measureForCompaction(this.ctx, session);
|
|
4118
|
-
if (stage === "fresh")
|
|
4101
|
+
if (stage === "fresh") {
|
|
4102
|
+
const usage = officialRequestUsage(view);
|
|
4103
|
+
if (usage !== void 0) getSavingsLedger().recordUsage(String(session.id), usage);
|
|
4104
|
+
return this.decideFreshStep(session, options, policy, view);
|
|
4105
|
+
}
|
|
4119
4106
|
if (profile === "off") return emptyResult();
|
|
4120
4107
|
const landed = [];
|
|
4121
4108
|
if (policy.nativeToolResultEnabled) {
|
|
@@ -4411,6 +4398,185 @@ var ToolResultPruner = class extends Service {
|
|
|
4411
4398
|
else if (outcome !== void 0) advisorState.failures = void 0;
|
|
4412
4399
|
}
|
|
4413
4400
|
/**
|
|
4401
|
+
* Fire-and-forget postflight: evaluate the growth gate, and only when it
|
|
4402
|
+
* passes, select the consumed increment OUTSIDE the protected working set,
|
|
4403
|
+
* mask it to semantic-role records, and spend ONE summary-writer call. The
|
|
4404
|
+
* verdict stages as a pending fold that the NEXT pressure round lands via
|
|
4405
|
+
* the ordinary plan/apply machinery — the synchronous decision path never
|
|
4406
|
+
* waits on an LLM.
|
|
4407
|
+
*/
|
|
4408
|
+
async postflightIntentFoldPass(session, turn, signal) {
|
|
4409
|
+
const started = Date.now();
|
|
4410
|
+
const sessionId = String(session.id);
|
|
4411
|
+
const policy = this.activePolicy(session);
|
|
4412
|
+
const settings = this.activeSettings(session);
|
|
4413
|
+
const intentEnabled = settings.intentSummary.enabled;
|
|
4414
|
+
const override = getSummaryOverride(sessionId);
|
|
4415
|
+
observeIntentEnabled(sessionId, intentEnabled);
|
|
4416
|
+
if (policy === void 0) return;
|
|
4417
|
+
if (this.state.pendingIntentFolds.has(session)) return;
|
|
4418
|
+
const advisorState = getAdvisorState(session);
|
|
4419
|
+
if (advisorState.inFlight) return;
|
|
4420
|
+
if (isCoolingDown(advisorState.failures, Date.now())) return;
|
|
4421
|
+
const view = measureForCompaction(this.ctx, session);
|
|
4422
|
+
const thresholdPercent = settings.autoCompact.thresholdPercent;
|
|
4423
|
+
const contextWindow = policy.autoCompactTokens !== void 0 && thresholdPercent > 0 ? Math.round(policy.autoCompactTokens / (thresholdPercent / 100)) : void 0;
|
|
4424
|
+
if (!evaluateIntentGate({
|
|
4425
|
+
enabled: intentEnabled,
|
|
4426
|
+
override,
|
|
4427
|
+
liveTokens: view.totalTokens,
|
|
4428
|
+
contextWindow,
|
|
4429
|
+
baselineTokens: this.state.intentBaselines.get(session) ?? 0
|
|
4430
|
+
}).decision) return;
|
|
4431
|
+
const settingsPreset = settings.presetOptions;
|
|
4432
|
+
if (settingsPreset === void 0) return;
|
|
4433
|
+
if (settingsPreset.estimatorBaseUrl === void 0 || settingsPreset.estimatorBaseUrl.length === 0 || settingsPreset.estimatorModel === void 0 || settingsPreset.estimatorModel.length === 0) {
|
|
4434
|
+
emitCompressionAudit(this.ctx.logger, {
|
|
4435
|
+
schemaVersion: 1,
|
|
4436
|
+
kind: "intent-summary-outcome",
|
|
4437
|
+
sessionId,
|
|
4438
|
+
ok: false,
|
|
4439
|
+
reason: "no-direct-endpoint",
|
|
4440
|
+
turnIndex: turn,
|
|
4441
|
+
latencyMs: Date.now() - started
|
|
4442
|
+
});
|
|
4443
|
+
return;
|
|
4444
|
+
}
|
|
4445
|
+
const candidates = this.snapshot(session, view).filter((candidate) => !this.isRecoveryExempt(session, candidate));
|
|
4446
|
+
const range = computeIntentRange({
|
|
4447
|
+
candidates,
|
|
4448
|
+
protectedSeqs: this.protectedHistoryCandidateSeqs(candidates, policy),
|
|
4449
|
+
foldedSeqs: this.state.intentFoldedSeqs.get(session) ?? /* @__PURE__ */ new Set(),
|
|
4450
|
+
maxCandidates: 20
|
|
4451
|
+
});
|
|
4452
|
+
if (range.seqs.length === 0) return;
|
|
4453
|
+
const bySeq = new Map(candidates.map((candidate) => [candidate.seq, candidate]));
|
|
4454
|
+
const records = [];
|
|
4455
|
+
const errorLines = /* @__PURE__ */ new Set();
|
|
4456
|
+
for (const seq of range.seqs) {
|
|
4457
|
+
const candidate = bySeq.get(seq);
|
|
4458
|
+
if (candidate === void 0) continue;
|
|
4459
|
+
const result = candidate.event.data.message;
|
|
4460
|
+
const text = onlyTextBlock(result.content)?.text ?? "";
|
|
4461
|
+
const masked = maskCandidateForSummary(seq, candidate.call.name, candidate.call.arguments, text);
|
|
4462
|
+
records.push({
|
|
4463
|
+
seq,
|
|
4464
|
+
role: masked.role,
|
|
4465
|
+
toolName: candidate.call.name,
|
|
4466
|
+
line: masked.record
|
|
4467
|
+
});
|
|
4468
|
+
for (const line of extractErrorLines(text)) errorLines.add(line);
|
|
4469
|
+
}
|
|
4470
|
+
if (records.length === 0) return;
|
|
4471
|
+
const events = sessionEvents(session);
|
|
4472
|
+
const task = collectTaskSemantics(events);
|
|
4473
|
+
let channel = this.state.advisorChannels.get(session);
|
|
4474
|
+
if (channel === void 0) {
|
|
4475
|
+
channel = new SideChannel(this.ctx, settingsPreset, {
|
|
4476
|
+
mode: "direct",
|
|
4477
|
+
timeoutMs: 3e4,
|
|
4478
|
+
maxTokens: 512
|
|
4479
|
+
});
|
|
4480
|
+
this.state.advisorChannels.set(session, channel);
|
|
4481
|
+
}
|
|
4482
|
+
const answer = await channel.ask({
|
|
4483
|
+
system: buildIntentSummarySystemPrompt(),
|
|
4484
|
+
user: buildIntentSummaryUserPrompt(task?.taskText ?? "(no task semantics yet)", records.map((record) => record.line), collectTailText(events)),
|
|
4485
|
+
signal
|
|
4486
|
+
});
|
|
4487
|
+
const summaryCallChars = answer?.length ?? 0;
|
|
4488
|
+
const parsed = answer === void 0 ? void 0 : parseIntentSummaryAnswer(answer);
|
|
4489
|
+
if (parsed === void 0) {
|
|
4490
|
+
const failures = (advisorState.failures?.failures ?? 0) + 1;
|
|
4491
|
+
advisorState.failures = {
|
|
4492
|
+
failures,
|
|
4493
|
+
cooldownUntil: Date.now() + backoffCooldownMs(failures)
|
|
4494
|
+
};
|
|
4495
|
+
emitCompressionAudit(this.ctx.logger, {
|
|
4496
|
+
schemaVersion: 1,
|
|
4497
|
+
kind: "intent-summary-outcome",
|
|
4498
|
+
sessionId,
|
|
4499
|
+
ok: false,
|
|
4500
|
+
reason: answer === void 0 ? "ask-failed" : "parse-failed",
|
|
4501
|
+
turnIndex: turn,
|
|
4502
|
+
foldedCount: records.length,
|
|
4503
|
+
summaryCallChars,
|
|
4504
|
+
latencyMs: Date.now() - started
|
|
4505
|
+
});
|
|
4506
|
+
return;
|
|
4507
|
+
}
|
|
4508
|
+
this.state.pendingIntentFolds.set(session, {
|
|
4509
|
+
createdAt: Date.now(),
|
|
4510
|
+
turn,
|
|
4511
|
+
startSeq: range.seqs[0],
|
|
4512
|
+
endSeq: range.seqs[range.seqs.length - 1],
|
|
4513
|
+
summary: parsed.summary,
|
|
4514
|
+
errorLines: [...errorLines],
|
|
4515
|
+
records,
|
|
4516
|
+
summaryCallChars
|
|
4517
|
+
});
|
|
4518
|
+
emitCompressionAudit(this.ctx.logger, {
|
|
4519
|
+
schemaVersion: 1,
|
|
4520
|
+
kind: "intent-summary-outcome",
|
|
4521
|
+
sessionId,
|
|
4522
|
+
ok: true,
|
|
4523
|
+
reason: "staged",
|
|
4524
|
+
turnIndex: turn,
|
|
4525
|
+
foldedCount: records.length,
|
|
4526
|
+
summaryCallChars,
|
|
4527
|
+
latencyMs: Date.now() - started
|
|
4528
|
+
});
|
|
4529
|
+
}
|
|
4530
|
+
/**
|
|
4531
|
+
* Convert a staged pending fold into per-candidate planned replacements
|
|
4532
|
+
* (reducer `intent-summary`). Fail-open: a candidate that would grow, is
|
|
4533
|
+
* rich-content, or no longer exists keeps its original text. Returns
|
|
4534
|
+
* `undefined` when there is nothing (or no longer anything) to fold.
|
|
4535
|
+
*/
|
|
4536
|
+
applyPendingIntentFold(session, policy, view, eligible) {
|
|
4537
|
+
const pending = this.state.pendingIntentFolds.get(session);
|
|
4538
|
+
if (pending === void 0) return void 0;
|
|
4539
|
+
const bySeq = new Map(eligible.map((candidate) => [candidate.seq, candidate]));
|
|
4540
|
+
const foldable = pending.records.map((record) => record.seq).filter((seq) => bySeq.has(seq)).sort((a, b) => a - b);
|
|
4541
|
+
if (foldable.length === 0) {
|
|
4542
|
+
this.state.pendingIntentFolds.delete(session);
|
|
4543
|
+
return;
|
|
4544
|
+
}
|
|
4545
|
+
const plans = [];
|
|
4546
|
+
const foldedSeqs = /* @__PURE__ */ new Set();
|
|
4547
|
+
let reclaim = 0;
|
|
4548
|
+
let charsBefore = 0;
|
|
4549
|
+
let charsAfter = 0;
|
|
4550
|
+
for (const seq of foldable) {
|
|
4551
|
+
const candidate = bySeq.get(seq);
|
|
4552
|
+
const result = candidate.event.data.message;
|
|
4553
|
+
const block = onlyTextBlock(result.content);
|
|
4554
|
+
if (block === null) continue;
|
|
4555
|
+
const text = renderIntentFoldBlock(pending, seq);
|
|
4556
|
+
const plan = this.plan(candidate, [{
|
|
4557
|
+
...block,
|
|
4558
|
+
text
|
|
4559
|
+
}], rootToolResultSeq(session, candidate.seq), "intent-summary", "pressure", "history", policy.historyMode, view);
|
|
4560
|
+
if (plan === null || plan.charsAfter >= plan.charsBefore) continue;
|
|
4561
|
+
plans.push(plan);
|
|
4562
|
+
foldedSeqs.add(seq);
|
|
4563
|
+
reclaim += plan.charsBefore - plan.charsAfter;
|
|
4564
|
+
charsBefore += plan.charsBefore;
|
|
4565
|
+
charsAfter += plan.charsAfter;
|
|
4566
|
+
}
|
|
4567
|
+
if (plans.length === 0) return void 0;
|
|
4568
|
+
this.state.intentFoldedSeqs.get(session)?.forEach((seq) => foldedSeqs.add(seq));
|
|
4569
|
+
return {
|
|
4570
|
+
plans,
|
|
4571
|
+
reclaim,
|
|
4572
|
+
foldedSeqs,
|
|
4573
|
+
charsBefore,
|
|
4574
|
+
charsAfter,
|
|
4575
|
+
turn: pending.turn,
|
|
4576
|
+
summaryCallChars: pending.summaryCallChars
|
|
4577
|
+
};
|
|
4578
|
+
}
|
|
4579
|
+
/**
|
|
4414
4580
|
* Monotonic per-session turn clock for advisory records. Bumped by the agent
|
|
4415
4581
|
* loop payloads (`pre-step`); passes without a turn coordinate reuse the last
|
|
4416
4582
|
* observed value.
|
|
@@ -4755,6 +4921,24 @@ var ToolResultPruner = class extends Service {
|
|
|
4755
4921
|
this.auditComponent(session, policy, "aggregate", "fresh", policy.aggregateEnabled ? "skipped" : "disabled", policy.aggregateEnabled ? "no-new-tool-result-candidates" : "profile-policy");
|
|
4756
4922
|
return emptyResult();
|
|
4757
4923
|
}
|
|
4924
|
+
const ledger = getSavingsLedger();
|
|
4925
|
+
const sid = String(session.id);
|
|
4926
|
+
for (const candidate of candidates) {
|
|
4927
|
+
const text = flattenPlainText(candidate.event.data.message.content);
|
|
4928
|
+
if (text === void 0) continue;
|
|
4929
|
+
ledger.noteFullText({
|
|
4930
|
+
sessionId: sid,
|
|
4931
|
+
seq: candidate.seq,
|
|
4932
|
+
text,
|
|
4933
|
+
measure: () => candidate.count.kind === "exact-tokenizer" && typeof candidate.count.tokens === "number" ? {
|
|
4934
|
+
tokens: candidate.count.tokens,
|
|
4935
|
+
basis: "exact-tokenizer"
|
|
4936
|
+
} : {
|
|
4937
|
+
tokens: Math.ceil(candidate.characterPressure / 4),
|
|
4938
|
+
basis: "characters"
|
|
4939
|
+
}
|
|
4940
|
+
});
|
|
4941
|
+
}
|
|
4758
4942
|
const plans = /* @__PURE__ */ new Map();
|
|
4759
4943
|
let freshPlanned = 0;
|
|
4760
4944
|
const dedupeEnabled = policy.presetOptions?.dedupeToolResults === true;
|
|
@@ -5002,13 +5186,41 @@ var ToolResultPruner = class extends Service {
|
|
|
5002
5186
|
const isUnsafe = (candidate) => {
|
|
5003
5187
|
if (this.isRecoveryExempt(session, candidate)) return true;
|
|
5004
5188
|
const result = candidate.event.data.message;
|
|
5005
|
-
|
|
5189
|
+
const block = onlyTextBlock(result.content);
|
|
5190
|
+
if (block?.text.includes("[Intent summary") === true) return true;
|
|
5191
|
+
return block?.text.includes("[Old tool result content cleared from active context]") === true;
|
|
5006
5192
|
};
|
|
5007
5193
|
const safe = candidates.filter((candidate) => !isUnsafe(candidate));
|
|
5008
5194
|
const eligible = safe.filter((candidate) => !protectedSeqs.has(candidate.seq));
|
|
5009
5195
|
if (eligible.length === 0) return safe.length === 0 ? { kind: "no-safe-candidates" } : { kind: "protected-working-set" };
|
|
5010
5196
|
const planned = [];
|
|
5011
5197
|
let reclaim = 0;
|
|
5198
|
+
const intentApplied = this.applyPendingIntentFold(session, policy, view, eligible);
|
|
5199
|
+
if (intentApplied !== void 0) {
|
|
5200
|
+
planned.push(...intentApplied.plans);
|
|
5201
|
+
reclaim += intentApplied.reclaim;
|
|
5202
|
+
this.state.intentFoldedSeqs.set(session, intentApplied.foldedSeqs);
|
|
5203
|
+
this.state.pendingIntentFolds.delete(session);
|
|
5204
|
+
this.state.intentBaselines.set(session, view.totalTokens);
|
|
5205
|
+
recordIntentFold(String(session.id), {
|
|
5206
|
+
turn: intentApplied.turn,
|
|
5207
|
+
startSeq: intentApplied.foldedSeqs.size > 0 ? Math.min(...intentApplied.foldedSeqs) : 0,
|
|
5208
|
+
endSeq: intentApplied.foldedSeqs.size > 0 ? Math.max(...intentApplied.foldedSeqs) : 0,
|
|
5209
|
+
liveTokensBefore: view.totalTokens,
|
|
5210
|
+
at: Date.now()
|
|
5211
|
+
});
|
|
5212
|
+
emitCompressionAudit(this.ctx.logger, {
|
|
5213
|
+
schemaVersion: 1,
|
|
5214
|
+
kind: "intent-summary-outcome",
|
|
5215
|
+
sessionId: String(session.id),
|
|
5216
|
+
ok: true,
|
|
5217
|
+
reason: "landed",
|
|
5218
|
+
foldedCount: intentApplied.plans.length,
|
|
5219
|
+
...intentApplied.charsBefore > 0 ? { retentionRatio: intentApplied.charsAfter / intentApplied.charsBefore } : {},
|
|
5220
|
+
summaryCallChars: intentApplied.summaryCallChars
|
|
5221
|
+
});
|
|
5222
|
+
for (let index = eligible.length - 1; index >= 0; index -= 1) if (intentApplied.foldedSeqs.has(eligible[index].seq)) eligible.splice(index, 1);
|
|
5223
|
+
}
|
|
5012
5224
|
const minReclaimChars = charsForTokens(policy.historyMinReclaimTokens);
|
|
5013
5225
|
const microTarget = deadline === void 0 ? void 0 : Math.max(0, charsForTokens(deadline) - minReclaimChars);
|
|
5014
5226
|
const required = Math.max(minReclaimChars, total - trigger, ...microTarget === void 0 ? [] : [charsForTokens(view.totalTokens) - microTarget]);
|
|
@@ -5249,6 +5461,16 @@ var ToolResultPruner = class extends Service {
|
|
|
5249
5461
|
tokenizerId: exact === true && exactSurface !== void 0 ? exactSurface.tokenizerId : "characters",
|
|
5250
5462
|
tokenizerRevision: exact === true && exactSurface !== void 0 ? exactSurface.tokenizerRevision : "chars-per-token-4.0"
|
|
5251
5463
|
});
|
|
5464
|
+
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");
|
|
5465
|
+
if (groupText.length > 0) getSavingsLedger().recordSaving({
|
|
5466
|
+
sessionId: String(session.id),
|
|
5467
|
+
component: "tail-trim",
|
|
5468
|
+
tokensBefore,
|
|
5469
|
+
tokensAfter,
|
|
5470
|
+
basis: exact ? "exact-tokenizer" : "characters",
|
|
5471
|
+
sourceSeq: manifestSeq,
|
|
5472
|
+
originalText: groupText
|
|
5473
|
+
});
|
|
5252
5474
|
return;
|
|
5253
5475
|
}
|
|
5254
5476
|
this.auditComponent(session, policy, "tail-trim", "pressure", "skipped", "no-safe-eligible-tool-group", {
|
|
@@ -5379,6 +5601,16 @@ var ToolResultPruner = class extends Service {
|
|
|
5379
5601
|
tokenizerRevision: plan.tokenizerRevision,
|
|
5380
5602
|
...plan.elidedLines === void 0 ? {} : { elidedLines: plan.elidedLines }
|
|
5381
5603
|
});
|
|
5604
|
+
const pairedOriginal = originalTextForSavings(candidate);
|
|
5605
|
+
getSavingsLedger().recordSaving({
|
|
5606
|
+
sessionId: String(session.id),
|
|
5607
|
+
component: plan.component,
|
|
5608
|
+
tokensBefore: plan.tokensBefore,
|
|
5609
|
+
tokensAfter: plan.tokensAfter,
|
|
5610
|
+
basis: plan.measurementBasis,
|
|
5611
|
+
sourceSeq: plan.sourceSeq,
|
|
5612
|
+
...pairedOriginal === void 0 ? {} : { originalText: pairedOriginal }
|
|
5613
|
+
});
|
|
5382
5614
|
return {
|
|
5383
5615
|
originalSeq: candidate.seq,
|
|
5384
5616
|
sourceSeq: plan.sourceSeq,
|