dsh-context-compression-improved 0.5.7 → 0.5.8

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.
Files changed (61) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/package.json +16 -17
  3. package/packages/selector/dsh.plugin.json +1 -1
  4. package/packages/selector/lib/client.d.ts +59 -0
  5. package/packages/selector/lib/client.js +1012 -17
  6. package/packages/selector/lib/{advisor-state.js → config.js} +816 -65
  7. package/packages/selector/lib/index.d.ts +13 -1
  8. package/packages/selector/lib/index.js +295 -3
  9. package/packages/selector/lib/pruner.d.ts +65 -0
  10. package/packages/selector/lib/pruner.js +497 -262
  11. package/packages/selector/lib/style.css +42 -0
  12. package/packages/selector/src/client/CompressionProfileControls.tsx +67 -0
  13. package/packages/selector/src/client/CompressionProfileSelector.module.css +29 -0
  14. package/packages/selector/src/client/CompressionProfileSelector.tsx +2 -0
  15. package/packages/selector/src/client/decode.ts +10 -2
  16. package/packages/selector/src/client/index.ts +62 -0
  17. package/packages/selector/src/client/locales/de.ts +43 -0
  18. package/packages/selector/src/client/locales/es.ts +43 -0
  19. package/packages/selector/src/client/locales/fr.ts +43 -0
  20. package/packages/selector/src/client/locales/it.ts +43 -0
  21. package/packages/selector/src/client/locales/ja.ts +43 -0
  22. package/packages/selector/src/client/locales/ko.ts +43 -0
  23. package/packages/selector/src/client/locales/ru.ts +43 -0
  24. package/packages/selector/src/client/locales.ts +86 -0
  25. package/packages/selector/src/client/monitor-fab.ts +336 -0
  26. package/packages/selector/src/client/savings-card.tsx +150 -0
  27. package/packages/selector/src/client/settings-section.tsx +18 -2
  28. package/packages/selector/src/index.ts +215 -5
  29. package/packages/selector/src/profiles.ts +37 -0
  30. package/packages/selector/src/pruner/state.ts +7 -0
  31. package/packages/selector/src/pruner.ts +337 -3
  32. package/packages/selector/src/runtime/audit.ts +17 -0
  33. package/packages/selector/src/runtime/config.ts +52 -2
  34. package/packages/selector/src/runtime/monitor.ts +235 -0
  35. package/packages/selector/src/runtime/retrieve.ts +24 -2
  36. package/packages/selector/src/runtime/savings.ts +337 -0
  37. package/packages/selector/src/runtime/summary-command.ts +127 -0
  38. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +46 -1
  39. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +55 -0
  40. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
  41. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
  42. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
  43. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
  44. package/packages/selector/src/runtime/types.ts +19 -0
  45. package/packages/selector/tests/auto-compact.client.spec.tsx +2 -1
  46. package/packages/selector/tests/code-skeleton.client.spec.ts +3 -2
  47. package/packages/selector/tests/custom-contract.client.spec.ts +3 -2
  48. package/packages/selector/tests/estimator-channel.client.spec.tsx +1 -0
  49. package/packages/selector/tests/estimator-route-registration.host.spec.ts +10 -4
  50. package/packages/selector/tests/monitor-fab.client.spec.ts +138 -0
  51. package/packages/selector/tests/preset-options-write.client.spec.ts +1 -0
  52. package/packages/selector/tests/profiles.client.spec.tsx +4 -2
  53. package/packages/selector/tests/runtime/audit.spec.ts +1 -0
  54. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
  55. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
  56. package/packages/selector/tests/runtime/monitor.spec.ts +301 -0
  57. package/packages/selector/tests/runtime/savings.spec.ts +120 -0
  58. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
  59. package/packages/selector/tests/settings-seat.client.spec.ts +19 -7
  60. package/scripts/packed-install-e2e.mjs +1 -1
  61. package/scripts/verify-release.mjs +2 -1
@@ -1,4 +1,4 @@
1
- import { C as COMPRESSION_PROFILES, S as deepFreeze, _ as resolvePolicy, a as AUTO_COMPACT_THRESHOLD_LIMITS, b as resolveCustomPolicy, c as DEFAULTS, d as charsToTokens, f as codePointLength, g as resolveConfig, h as parseContextCompressionSettings, i as recordScore, l as PRUNE_MARKER, m as isValidAutoCompactThresholdPercent, n as invalidateOnTaskChange, o as CONTEXT_COMPRESSION_SETTINGS_NAMESPACE, p as isCompressionProfile, r as recordRecertified, s as ContextCompressionSettingsSchema, t as getAdvisorState, u as charsForTokens, v as CustomCompressionPolicySchema, x as assertNever, y as DEFAULT_CUSTOM_COMPRESSION_POLICY } from "./advisor-state.js";
1
+ import { B as priceOfficialDeepSeekUsage, D as evaluateIntentGate, F as recordRecertified, H as getSavingsLedger, I as recordScore, M as invalidateOnTaskChange, N as observeIntentEnabled, O as getAdvisorState, P as recordIntentFold, R as DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION, V as resolveOfficialDeepSeekPrice, _ as assertNever, a as PRUNE_MARKER, c as codePointLength, d as parseContextCompressionSettings, f as resolveConfig, g as resolveCustomPolicy, h as DEFAULT_CUSTOM_COMPRESSION_POLICY, i as DEFAULTS, j as getSummaryOverride, l as isCompressionProfile, m as CustomCompressionPolicySchema, n as CONTEXT_COMPRESSION_SETTINGS_NAMESPACE, o as charsForTokens, p as resolvePolicy, r as ContextCompressionSettingsSchema, s as charsToTokens, t as AUTO_COMPACT_THRESHOLD_LIMITS, u as isValidAutoCompactThresholdPercent, v as deepFreeze, w as observeContextUsage, y as COMPRESSION_PROFILES, z as decimalRateNanoUnits } 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";
@@ -535,6 +535,10 @@ function measureForCompaction(ctx, session) {
535
535
  countCanonicalText: counter.countText
536
536
  });
537
537
  }
538
+ /** Request-level usage exposed by official TokenMeter, without invented route attribution. */
539
+ function officialRequestUsage(view) {
540
+ return view.baseline.kind === "usage" ? view.baseline.usage : void 0;
541
+ }
538
542
  /**
539
543
  * Count one canonical content walk in canonical field order.
540
544
  *
@@ -796,11 +800,23 @@ function installContextCompressionRetrieve(ctx, config = {}) {
796
800
  const tailTrimRef = parseTailTrimRef(args.ref);
797
801
  if (match === null && tailTrimRef === null) throw new Error("context_compression_retrieve: ref must be session://<session-id>/(event|tailtrim)/<seq>");
798
802
  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");
799
- if (tailTrimRef !== null) return Promise.resolve(recoverTailTrim(exec.agent.session, args.ref, tailTrimRef.manifestSeq, args.query, args.start_line, args.max_lines, {
800
- maxChars,
801
- maxScanChars,
802
- maxQueryChars
803
- }));
803
+ if (tailTrimRef !== null) {
804
+ const sessionId = String(exec.agent.id);
805
+ return Promise.resolve(recoverTailTrim(exec.agent.session, args.ref, tailTrimRef.manifestSeq, args.query, args.start_line, args.max_lines, {
806
+ maxChars,
807
+ maxScanChars,
808
+ maxQueryChars
809
+ })).then((text) => {
810
+ getSavingsLedger().recordOffset({
811
+ sessionId,
812
+ component: "tailtrim-retrieve",
813
+ tokens: Math.ceil(codePointLength$1(text) / 4),
814
+ basis: "characters",
815
+ note: `tailtrim/${tailTrimRef.manifestSeq} 回读`
816
+ });
817
+ return text;
818
+ });
819
+ }
804
820
  const seq = Number(match?.[2]);
805
821
  const event = sessionEvents(exec.agent.session)[seq];
806
822
  if (event?.type !== "tool/result") throw new Error(`context_compression_retrieve: event ${String(seq)} is not a tool/result in the current session`);
@@ -812,7 +828,7 @@ function installContextCompressionRetrieve(ctx, config = {}) {
812
828
  if (query !== void 0 && exceedsCodePointLimit(query, maxQueryChars)) throw new Error(`context_compression_retrieve: query must be at most ${String(maxQueryChars)} Unicode code points`);
813
829
  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);
814
830
  const total = scan.complete ? String(lines.length) : `at least ${String(lines.length)}`;
815
- const output = `${[
831
+ const bounded = boundCodePoints(`${[
816
832
  `source: ${args.ref}`,
817
833
  `tool_call_id: ${event.data.message.source.callId}`,
818
834
  `status: ${event.data.message.content[0].isError === true ? "error" : "completed"}`,
@@ -821,8 +837,15 @@ function installContextCompressionRetrieve(ctx, config = {}) {
821
837
  selected.partialLine === void 0 ? "" : `note: line ${String(selected.partialLine)} is a partial prefix ending at the source scan limit`,
822
838
  selected.omitted ? query === void 0 || query === "" ? "note: additional source lines were omitted" : "note: additional matching or neighboring lines were omitted" : "",
823
839
  "--- original tool result ---"
824
- ].filter(Boolean).join("\n")}\n${selected.text}`;
825
- return Promise.resolve(boundCodePoints(output, maxChars));
840
+ ].filter(Boolean).join("\n")}\n${selected.text}`, maxChars);
841
+ getSavingsLedger().recordOffset({
842
+ sessionId: String(exec.agent.id),
843
+ component: "retrieve",
844
+ tokens: Math.ceil(codePointLength$1(bounded) / 4),
845
+ basis: "characters",
846
+ note: `event/${String(seq)} 回读`
847
+ });
848
+ return Promise.resolve(bounded);
826
849
  }
827
850
  }));
828
851
  }
@@ -1404,7 +1427,7 @@ function reduceFreshToolResult(input, ranking) {
1404
1427
  lines: normalized.folded,
1405
1428
  contentText: normalized.contentText
1406
1429
  };
1407
- const command = extractCommand(input.argumentsText);
1430
+ const command = extractCommand$1(input.argumentsText);
1408
1431
  const name = input.toolName.toLowerCase();
1409
1432
  const toolClass = classifyToolSource(input.toolName, command, normalized.contentText);
1410
1433
  const readTocFirst = toolClass === "read" && codePointLength(normalized.contentText) >= READ_TOC_MIN_CHARS;
@@ -2687,7 +2710,7 @@ function splitLines(text) {
2687
2710
  * @param argumentsText - raw JSON arguments of the tool call.
2688
2711
  * @returns the command string, or '' when absent.
2689
2712
  */
2690
- function extractCommand(argumentsText) {
2713
+ function extractCommand$1(argumentsText) {
2691
2714
  try {
2692
2715
  const parsed = JSON.parse(argumentsText);
2693
2716
  if (typeof parsed !== "object" || parsed === null) return "";
@@ -3255,6 +3278,42 @@ function parseAdvisorScores(text, validSeqs) {
3255
3278
  }
3256
3279
  return scores.size > 0 ? scores : void 0;
3257
3280
  }
3281
+ /** Hard character cap for one intent-summary answer (summary segment only). */
3282
+ const INTENT_SUMMARY_CHAR_CAP = 1600;
3283
+ /**
3284
+ * Intent-summary writer prompts (task_2.3). Input records are already
3285
+ * semantic-role-masked by intent-input-mask.ts: read-class candidates are
3286
+ * one-line "read X" records, keep-class candidates carry skeleton heads and
3287
+ * VERBATIM error lines. The model writes ONLY the summary segment — it never
3288
+ * revoices error lines, and its answer must stay inside the char cap.
3289
+ */
3290
+ function buildIntentSummarySystemPrompt() {
3291
+ return [
3292
+ "You write one concise intent summary of folded tool results for a coding agent session.",
3293
+ "Input: the session task (todolist) and per-tool slimmed records (read lines, or skeleton heads with verbatim error lines).",
3294
+ `Write ONLY what the agent DID and LEARNED in this span, as flowing prose under ${INTENT_SUMMARY_CHAR_CAP} characters.`,
3295
+ "Mention which files/areas were consulted and what changed, so a later turn can continue without the originals.",
3296
+ "Never invent files, commands, or outcomes absent from the records. Never revoice error lines; they are preserved verbatim elsewhere.",
3297
+ "Answer with ONLY one JSON object: {\"summary\":\"<prose>\"}. Never add commentary."
3298
+ ].join(" ");
3299
+ }
3300
+ function buildIntentSummaryUserPrompt(taskText, records, tailText) {
3301
+ const nl = String.fromCharCode(10);
3302
+ return [
3303
+ `task: ${taskText.replace(/\s+/gu, " ").slice(0, 600)}`,
3304
+ records.length > 0 ? `records:${nl}${records.join(nl)}` : "records: (none)",
3305
+ tailText.trim().length > 0 ? `recent tail:${nl}${tailText.trim().slice(0, 1200)}` : "recent tail: (none)"
3306
+ ].join("\n\n");
3307
+ }
3308
+ /** Fail-open parse of one intent-summary answer; `undefined` on any malformed shape. */
3309
+ function parseIntentSummaryAnswer(text) {
3310
+ const parsed = firstJsonObject(text);
3311
+ if (parsed === void 0) return void 0;
3312
+ const summary = parsed.summary;
3313
+ if (typeof summary !== "string" || summary.trim().length === 0) return void 0;
3314
+ if (summary.length > 3200) return void 0;
3315
+ return { summary: summary.trim().slice(0, INTENT_SUMMARY_CHAR_CAP) };
3316
+ }
3258
3317
  //#endregion
3259
3318
  //#region src/runtime/tokenpilot/advisor.ts
3260
3319
  /** Character cap for the recent-text fallback and the tail-text summary input. */
@@ -3556,6 +3615,162 @@ async function runSessionAdvisorPass(session, channel, emit, input) {
3556
3615
  }
3557
3616
  }
3558
3617
  //#endregion
3618
+ //#region src/runtime/tokenpilot/intent-input-mask.ts
3619
+ /**
3620
+ * Semantic-role input masking for the intent-summary writer (task_2.2).
3621
+ *
3622
+ * The intent summary records historical TASK semantics — for read-class tools
3623
+ * the semantics are "read X", never the file body, so the body is masked to a
3624
+ * one-line record before it can reach the summary prompt. Write-class results
3625
+ * (edits) ARE task semantics and keep their skeleton + verbatim error lines.
3626
+ *
3627
+ * Classification REUSES `classifyToolSource()` (reducers.ts routes on the
3628
+ * same classes): hand-rolling a name→role map here would regress its fixed
3629
+ * misclassification edges (mcp→generic, web_search/memory_search not being
3630
+ * content search, glob being path-listing, execute_sql not being shell).
3631
+ * Only the write class is layered on top — `ToolClass` has no write member.
3632
+ */
3633
+ /** Exact-token write layer, same tokenization discipline as toolclass. */
3634
+ const WRITE_NAMES = /* @__PURE__ */ new Set([
3635
+ "apply_patch",
3636
+ "multi_edit",
3637
+ "create_file",
3638
+ "write_to_file",
3639
+ "str_replace_editor"
3640
+ ]);
3641
+ const WRITE_TOKENS = /* @__PURE__ */ new Set([
3642
+ "write",
3643
+ "edit",
3644
+ "patch"
3645
+ ]);
3646
+ function hasWriteToken(name) {
3647
+ const lowered = name.toLowerCase();
3648
+ if (WRITE_NAMES.has(lowered)) return true;
3649
+ return lowered.split(/[-_/]+/).some((token) => WRITE_TOKENS.has(token));
3650
+ }
3651
+ /**
3652
+ * Role for one candidate. The write layer is consulted first; everything
3653
+ * else defers to the shared classifier. `shell`/`generic` stay conservative
3654
+ * (skeleton + error lines, never a blind mask) — a bash result can be a
3655
+ * mutation even when its name says nothing.
3656
+ */
3657
+ function classifyIntentRole(toolName, command, text) {
3658
+ if (hasWriteToken(toolName)) return "write-keep";
3659
+ const toolClass = classifyToolSource(toolName, command, text);
3660
+ if (toolClass === "read" || toolClass === "search" || toolClass === "path-listing") return "read-mask";
3661
+ return "conservative";
3662
+ }
3663
+ const ERROR_LINE_PATTERN = /\b(error|failed|failure|exception|panic|fatal|traceback|unreachable|denied)\b/i;
3664
+ const KEEP_HEAD_LINES = 40;
3665
+ const KEEP_HEAD_CHARS = 2e3;
3666
+ /** Verbatim error/warn lines kept out of the LLM's hands and into the intent block. */
3667
+ function extractErrorLines(text) {
3668
+ return text.split("\n").filter((line) => ERROR_LINE_PATTERN.test(line)).slice(0, 10);
3669
+ }
3670
+ /** Count lines and code points for the read-mask record tail. */
3671
+ function scaleOf(text) {
3672
+ return {
3673
+ lines: text.length === 0 ? 0 : text.split("\n").length,
3674
+ chars: text.length
3675
+ };
3676
+ }
3677
+ /**
3678
+ * Build the prompt face for one candidate. Read-mask output contains NONE of
3679
+ * the original body — only the tool name, the call's target argument, and
3680
+ * the dropped scale — so a hostile body can never leak into the summary.
3681
+ */
3682
+ function maskCandidateForSummary(seq, toolName, argumentsText, text) {
3683
+ const role = classifyIntentRole(toolName, extractCommand(argumentsText), text);
3684
+ if (role === "read-mask") {
3685
+ const { lines, chars } = scaleOf(text);
3686
+ return {
3687
+ seq,
3688
+ role,
3689
+ record: `${toolName} ${extractTarget(argumentsText)} -> masked (${lines} lines / ${chars} chars)`
3690
+ };
3691
+ }
3692
+ const head = text.split("\n", KEEP_HEAD_LINES).join("\n").slice(0, KEEP_HEAD_CHARS);
3693
+ const errorLines = extractErrorLines(text);
3694
+ return {
3695
+ seq,
3696
+ role,
3697
+ record: `${toolName} (seq ${seq})\n${head}${errorLines.length > 0 ? `\nerror lines (verbatim):\n${errorLines.join("\n")}` : ""}`
3698
+ };
3699
+ }
3700
+ /** Extract a short command head from a tool-call arguments JSON string. */
3701
+ function extractCommand(argumentsText) {
3702
+ try {
3703
+ const parsed = JSON.parse(argumentsText);
3704
+ if (parsed !== null && typeof parsed === "object") {
3705
+ const command = parsed.command;
3706
+ if (typeof command === "string") return command.slice(0, 200);
3707
+ }
3708
+ } catch {}
3709
+ return "";
3710
+ }
3711
+ /** Extract the most target-like string argument (path/query/url) for read-mask records. */
3712
+ function extractTarget(argumentsText) {
3713
+ try {
3714
+ const parsed = JSON.parse(argumentsText);
3715
+ if (parsed !== null && typeof parsed === "object") {
3716
+ const record = parsed;
3717
+ const target = [
3718
+ record.path,
3719
+ record.file_path,
3720
+ record.query,
3721
+ record.url,
3722
+ record.pattern,
3723
+ record.glob
3724
+ ].find((candidate) => typeof candidate === "string" && candidate.trim().length > 0);
3725
+ if (typeof target === "string") return target.slice(0, 160);
3726
+ const first = Object.values(record).find((value) => typeof value === "string");
3727
+ if (typeof first === "string") return first.slice(0, 160);
3728
+ }
3729
+ } catch {}
3730
+ return "(unparsed target)";
3731
+ }
3732
+ //#endregion
3733
+ //#region src/runtime/tokenpilot/intent-range.ts
3734
+ /**
3735
+ * Oldest-first selection of foldable candidates. Excludes the protected
3736
+ * working set and already-folded seqs; caps the batch size.
3737
+ */
3738
+ function computeIntentRange(input) {
3739
+ const unprotected = input.candidates.filter((candidate) => !input.protectedSeqs.has(candidate.seq));
3740
+ const skippedProtected = input.candidates.length - unprotected.length;
3741
+ const eligible = unprotected.filter((candidate) => !input.foldedSeqs.has(candidate.seq));
3742
+ const skippedFolded = unprotected.length - eligible.length;
3743
+ return {
3744
+ seqs: [...eligible].sort((a, b) => a.seq - b.seq).slice(0, Math.max(0, input.maxCandidates)).map((candidate) => candidate.seq),
3745
+ skippedProtected,
3746
+ skippedFolded
3747
+ };
3748
+ }
3749
+ //#endregion
3750
+ //#region src/runtime/tokenpilot/intent-fold.ts
3751
+ /** Marker written into every folded block; its presence makes a seq unfoldable again (fold-once). */
3752
+ const INTENT_FOLD_MARKER = "[Intent summary";
3753
+ /** Render the replacement text for one folded candidate. Pure. */
3754
+ function renderIntentFoldBlock(pending, seq) {
3755
+ const start = pending.startSeq;
3756
+ const end = pending.endSeq;
3757
+ if (seq === start) {
3758
+ const readLines = pending.records.filter((record) => record.role === "read-mask").map((record) => record.line);
3759
+ const consulted = readLines.length > 0 ? `Consulted: ${readLines.join("; ")}` : "";
3760
+ const errorBlock = pending.errorLines.length > 0 ? `\nError lines (verbatim):\n${pending.errorLines.join("\n")}` : "";
3761
+ return [
3762
+ `${INTENT_FOLD_MARKER} of folded tool results seq ${start}..${end}]`,
3763
+ pending.summary,
3764
+ consulted,
3765
+ errorBlock,
3766
+ "[Original content remains in the session log at the listed seq values.]"
3767
+ ].filter((part) => part.length > 0).join("\n");
3768
+ }
3769
+ const record = pending.records.find((entry) => entry.seq === seq);
3770
+ const face = record === void 0 ? `${seq}` : record.role === "read-mask" ? record.line : `${record.toolName} result folded into the batch intent summary`;
3771
+ return `${INTENT_FOLD_MARKER} folded into the batch summary above (seq ${start}..${end})] ${face}`;
3772
+ }
3773
+ //#endregion
3559
3774
  //#region src/runtime/tokenpilot/dedup.ts
3560
3775
  /**
3561
3776
  * TokenPilot-inspired A1: byte-identical repeated tool-result dedup.
@@ -3615,254 +3830,6 @@ function dedupePlaceholder(entry, originalChars) {
3615
3830
  ].join(" ");
3616
3831
  }
3617
3832
  //#endregion
3618
- //#region src/runtime/deepseek-official-pricing.ts
3619
- /** Checked-in DeepSeek official prices and fixed-point provider-usage accounting. */
3620
- const DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION = "deepseek-official-2026-08-25";
3621
- /** Wall-clock time at which the checked-in official price pages were verified. */
3622
- const DEEPSEEK_OFFICIAL_PRICE_CHECKED_AT = "2026-08-25T00:10:20+08:00";
3623
- const PRICES = Object.freeze({
3624
- "deepseek-v4-flash": modelPrices("DeepSeek-V4-Flash-0731", [
3625
- "0.007",
3626
- "0.22",
3627
- "0.66"
3628
- ], [
3629
- "0.014",
3630
- "0.44",
3631
- "1.32"
3632
- ], [
3633
- "0.05",
3634
- "1.5",
3635
- "4.5"
3636
- ], [
3637
- "0.10",
3638
- "3.0",
3639
- "9.0"
3640
- ]),
3641
- "deepseek-v4-pro": modelPrices("DeepSeek-V4-Pro-0813", [
3642
- "0.022",
3643
- "0.66",
3644
- "1.98"
3645
- ], [
3646
- "0.044",
3647
- "1.32",
3648
- "3.96"
3649
- ], [
3650
- "0.15",
3651
- "4.5",
3652
- "13.5"
3653
- ], [
3654
- "0.30",
3655
- "9.0",
3656
- "27.0"
3657
- ]),
3658
- "deepseek-v4-flash-vision-exp": modelPrices("DeepSeek-V4-Flash-Vision-Exp", [
3659
- "0.007",
3660
- "0.22",
3661
- "0.66"
3662
- ], [
3663
- "0.014",
3664
- "0.44",
3665
- "1.32"
3666
- ], [
3667
- "0.05",
3668
- "1.5",
3669
- "4.5"
3670
- ], [
3671
- "0.10",
3672
- "3.0",
3673
- "9.0"
3674
- ])
3675
- });
3676
- const PEAK_RULE = "Asia/Shanghai Mon-Fri 09:00-12:00,14:00-18:00";
3677
- const USD_SOURCE = "https://api-docs.deepseek.com/quick_start/pricing/";
3678
- const CNY_SOURCE = "https://api-docs.deepseek.com/zh-cn/quick_start/pricing/";
3679
- /**
3680
- * Resolve one immutable official price record; aliases and compatible gateways fail closed.
3681
- * @param input - exact provider, endpoint, route, model, currency, and timestamp applicability.
3682
- * @returns An immutable price record or an explicit unpriced reason.
3683
- */
3684
- function resolveOfficialDeepSeekPrice(input) {
3685
- if (input.provider !== "deepseek-official") return unpriced("unknown provider route");
3686
- if (input.baseUrlClass !== "official-public") return unpriced("unknown base-url applicability");
3687
- if (input.apiRoute !== "chat-completions" && input.apiRoute !== "responses") return unpriced("unknown API route");
3688
- if (!isOfficialModel(input.modelId)) return unpriced("unknown model id");
3689
- if (input.currency !== "USD" && input.currency !== "CNY") return unpriced("unknown currency");
3690
- const band = priceBandAt(input.at);
3691
- if (band === void 0) return unpriced("invalid price timestamp");
3692
- const model = PRICES[input.modelId];
3693
- const [inputCacheHit, inputCacheMiss, output] = model[input.currency][band];
3694
- return {
3695
- kind: "priced",
3696
- record: Object.freeze({
3697
- catalogVersion: DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION,
3698
- checkedAt: DEEPSEEK_OFFICIAL_PRICE_CHECKED_AT,
3699
- provider: "deepseek-official",
3700
- baseUrlClass: "official-public",
3701
- apiRoute: input.apiRoute,
3702
- modelId: input.modelId,
3703
- modelVersion: model.version,
3704
- currency: input.currency,
3705
- unitTokens: 1e6,
3706
- band,
3707
- inputCacheHit,
3708
- inputCacheMiss,
3709
- output,
3710
- sourceUrl: input.currency === "USD" ? USD_SOURCE : CNY_SOURCE,
3711
- sourceLocale: input.currency === "USD" ? "en" : "zh-CN",
3712
- peakRule: PEAK_RULE
3713
- })
3714
- };
3715
- }
3716
- /**
3717
- * Classify a timestamp under the published Beijing peak schedule.
3718
- * @param at - absolute request time to interpret in Asia/Shanghai.
3719
- * @returns Peak/off-peak, or undefined for an invalid timestamp.
3720
- */
3721
- function priceBandAt(at) {
3722
- if (!Number.isFinite(at.getTime())) return void 0;
3723
- const parts = new Intl.DateTimeFormat("en-US", {
3724
- timeZone: "Asia/Shanghai",
3725
- weekday: "short",
3726
- hour: "2-digit",
3727
- minute: "2-digit",
3728
- second: "2-digit",
3729
- hourCycle: "h23"
3730
- }).formatToParts(at);
3731
- const values = Object.fromEntries(parts.map((part) => [part.type, part.value]));
3732
- const weekday = values.weekday;
3733
- const hour = Number(values.hour);
3734
- const minute = Number(values.minute);
3735
- const second = Number(values.second);
3736
- if (weekday === void 0 || !Number.isInteger(hour) || !Number.isInteger(minute) || !Number.isInteger(second)) return void 0;
3737
- const workday = weekday !== "Sat" && weekday !== "Sun";
3738
- const seconds = hour * 3600 + minute * 60 + second;
3739
- return workday && (seconds >= 32400 && seconds < 43200 || seconds >= 50400 && seconds < 64800) ? "peak" : "off-peak";
3740
- }
3741
- /**
3742
- * Price one completed request, returning a range when it spans a published band boundary.
3743
- * @param input - exact applicability, request interval, and complete disjoint usage buckets.
3744
- * @returns Fixed-point exact/range cost or an explicit unpriced reason.
3745
- */
3746
- function priceOfficialDeepSeekUsage(input) {
3747
- for (const [name, value] of Object.entries(input.usage)) if (!Number.isSafeInteger(value) || value < 0) return unpriced(`invalid ${name}`);
3748
- if (input.completedAt.getTime() < input.startedAt.getTime()) return unpriced("completion timestamp precedes request start");
3749
- const start = resolveOfficialDeepSeekPrice({
3750
- ...input,
3751
- at: input.startedAt
3752
- });
3753
- if (start.kind === "unpriced") return start;
3754
- const end = resolveOfficialDeepSeekPrice({
3755
- ...input,
3756
- at: input.completedAt
3757
- });
3758
- if (end.kind === "unpriced") return end;
3759
- const startAmount = amountFor(start.record, input.usage);
3760
- if (startAmount === void 0) return unpriced("invalid decimal price record");
3761
- const crossesBoundary = spansPublishedPriceBoundary(input.startedAt, input.completedAt);
3762
- if (start.record.band === end.record.band && !crossesBoundary) return {
3763
- kind: "exact",
3764
- currency: start.record.currency,
3765
- band: start.record.band,
3766
- ...startAmount
3767
- };
3768
- const comparisonRecord = start.record.band === end.record.band ? priceRecordInBand(start.record, start.record.band === "peak" ? "off-peak" : "peak") : end.record;
3769
- const endAmount = amountFor(comparisonRecord, input.usage);
3770
- if (endAmount === void 0) return unpriced("invalid decimal price record");
3771
- const startFemto = BigInt(startAmount.femtoUnits);
3772
- const endFemto = BigInt(endAmount.femtoUnits);
3773
- return {
3774
- kind: "range",
3775
- currency: start.record.currency,
3776
- bands: [start.record.band, comparisonRecord.band],
3777
- minimum: startFemto <= endFemto ? startAmount : endAmount,
3778
- maximum: startFemto <= endFemto ? endAmount : startAmount
3779
- };
3780
- }
3781
- /** Detect any published UTC band boundary, even when both endpoints share a band. */
3782
- function spansPublishedPriceBoundary(startedAt, completedAt) {
3783
- const start = startedAt.getTime();
3784
- const end = completedAt.getTime();
3785
- if (end <= start) return false;
3786
- const dayMs = 864e5;
3787
- if (end - start >= 7 * dayMs) return true;
3788
- const firstDay = Math.floor(start / dayMs) * dayMs;
3789
- for (let day = firstDay; day <= end; day += dayMs) {
3790
- const weekday = new Date(day).getUTCDay();
3791
- if (weekday === 0 || weekday === 6) continue;
3792
- for (const hour of [
3793
- 1,
3794
- 4,
3795
- 6,
3796
- 10
3797
- ]) {
3798
- const boundary = day + hour * 60 * 60 * 1e3;
3799
- if (boundary > start && boundary <= end) return true;
3800
- }
3801
- }
3802
- return false;
3803
- }
3804
- function priceRecordInBand(record, band) {
3805
- const [inputCacheHit, inputCacheMiss, output] = PRICES[record.modelId][record.currency][band];
3806
- return Object.freeze({
3807
- ...record,
3808
- band,
3809
- inputCacheHit,
3810
- inputCacheMiss,
3811
- output
3812
- });
3813
- }
3814
- /**
3815
- * Parse a non-negative decimal rate into nano-currency units, without Number arithmetic.
3816
- * @param value - canonical non-negative decimal with at most nine fractional digits.
3817
- * @returns Integer nano-units, or undefined when the decimal is invalid.
3818
- */
3819
- function decimalRateNanoUnits(value) {
3820
- const match = /^(0|[1-9]\d*)(?:\.(\d{1,9}))?$/u.exec(value);
3821
- if (match === null) return void 0;
3822
- const whole = match[1] ?? "0";
3823
- const fraction = (match[2] ?? "").padEnd(9, "0");
3824
- return BigInt(whole) * 1000000000n + BigInt(fraction || "0");
3825
- }
3826
- function amountFor(record, usage) {
3827
- const hit = decimalRateNanoUnits(record.inputCacheHit);
3828
- const miss = decimalRateNanoUnits(record.inputCacheMiss);
3829
- const output = decimalRateNanoUnits(record.output);
3830
- if (hit === void 0 || miss === void 0 || output === void 0) return void 0;
3831
- const femtoUnits = BigInt(usage.cacheReadTokens) * hit + BigInt(usage.cacheMissTokens) * miss + BigInt(usage.outputTokens) * output;
3832
- return {
3833
- femtoUnits: femtoUnits.toString(),
3834
- decimal: formatFemto(femtoUnits)
3835
- };
3836
- }
3837
- function formatFemto(value) {
3838
- const digits = value.toString().padStart(16, "0");
3839
- const whole = digits.slice(0, -15);
3840
- const fraction = digits.slice(-15).replace(/0+$/u, "");
3841
- return fraction.length === 0 ? whole : `${whole}.${fraction}`;
3842
- }
3843
- function modelPrices(version, usdOffPeak, usdPeak, cnyOffPeak, cnyPeak) {
3844
- return Object.freeze({
3845
- version,
3846
- USD: Object.freeze({
3847
- "off-peak": usdOffPeak,
3848
- peak: usdPeak
3849
- }),
3850
- CNY: Object.freeze({
3851
- "off-peak": cnyOffPeak,
3852
- peak: cnyPeak
3853
- })
3854
- });
3855
- }
3856
- function isOfficialModel(value) {
3857
- return Object.prototype.hasOwnProperty.call(PRICES, value);
3858
- }
3859
- function unpriced(reason) {
3860
- return {
3861
- kind: "unpriced",
3862
- reason
3863
- };
3864
- }
3865
- //#endregion
3866
3833
  //#region src/runtime/adaptive-cost.ts
3867
3834
  /**
3868
3835
  * Bound Adaptive's benefit and cache-loss exposure without attributing the
@@ -4004,6 +3971,10 @@ function emitCompressionAudit(logger, record) {
4004
3971
  *
4005
3972
  * @module dsh-context-compression-improved-runtime
4006
3973
  */
3974
+ /** 节省统计配对键用原文(纯文本块才可配对;富内容返回 undefined)。 */
3975
+ function originalTextForSavings(candidate) {
3976
+ return flattenPlainText(candidate.event.data.message.content);
3977
+ }
4007
3978
  /** Mixed deterministic selector behind the existing `ctx.toolResultPruner` seam. */
4008
3979
  var ToolResultPruner = class extends Service {
4009
3980
  static inject = ["tokenMeter"];
@@ -4047,8 +4018,19 @@ var ToolResultPruner = class extends Service {
4047
4018
  policyResolutionAudits: /* @__PURE__ */ new WeakMap(),
4048
4019
  turnClocks: /* @__PURE__ */ new WeakMap(),
4049
4020
  estimatorRemainingTurns: /* @__PURE__ */ new WeakMap(),
4050
- advisorChannels: /* @__PURE__ */ new WeakMap()
4021
+ advisorChannels: /* @__PURE__ */ new WeakMap(),
4022
+ pendingIntentFolds: /* @__PURE__ */ new WeakMap(),
4023
+ intentFoldedSeqs: /* @__PURE__ */ new WeakMap(),
4024
+ intentBaselines: /* @__PURE__ */ new WeakMap()
4051
4025
  };
4026
+ try {
4027
+ ctx.on("session/disposed", (session) => {
4028
+ try {
4029
+ const line = getSavingsLedger().sessionSummaryLine(String(session.id));
4030
+ 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);
4031
+ } catch {}
4032
+ });
4033
+ } catch {}
4052
4034
  ctx.on("session/event", (session, event) => {
4053
4035
  this.scanForSeededNativeSummary(session);
4054
4036
  if (event.type === "compaction/summary") {
@@ -4089,8 +4071,12 @@ var ToolResultPruner = class extends Service {
4089
4071
  this.auditFailure(agent.session, "fresh", "terminal-pass", error);
4090
4072
  ctx.logger.warn("context-compression terminal pass failed open: %o", error);
4091
4073
  }
4074
+ try {
4075
+ observeContextUsage(String(agent.session.id), measureForCompaction(this.ctx, agent.session).totalTokens, this.contextWindowForRequest(agent.session));
4076
+ } catch {}
4092
4077
  this.postflightEstimatorPass(agent.session, signal).catch(() => void 0);
4093
4078
  this.postflightAdvisorPass(agent.session, turn, signal).catch(() => void 0);
4079
+ this.postflightIntentFoldPass(agent.session, turn, signal).catch(() => void 0);
4094
4080
  });
4095
4081
  }
4096
4082
  /**
@@ -4122,7 +4108,11 @@ var ToolResultPruner = class extends Service {
4122
4108
  if (policy === void 0) return emptyResult();
4123
4109
  const profile = policy.profile;
4124
4110
  const view = measureForCompaction(this.ctx, session);
4125
- if (stage === "fresh") return this.decideFreshStep(session, options, policy, view);
4111
+ if (stage === "fresh") {
4112
+ const usage = officialRequestUsage(view);
4113
+ if (usage !== void 0) getSavingsLedger().recordUsage(String(session.id), usage);
4114
+ return this.decideFreshStep(session, options, policy, view);
4115
+ }
4126
4116
  if (profile === "off") return emptyResult();
4127
4117
  const landed = [];
4128
4118
  if (policy.nativeToolResultEnabled) {
@@ -4420,6 +4410,185 @@ var ToolResultPruner = class extends Service {
4420
4410
  else if (outcome !== void 0) advisorState.failures = void 0;
4421
4411
  }
4422
4412
  /**
4413
+ * Fire-and-forget postflight: evaluate the growth gate, and only when it
4414
+ * passes, select the consumed increment OUTSIDE the protected working set,
4415
+ * mask it to semantic-role records, and spend ONE summary-writer call. The
4416
+ * verdict stages as a pending fold that the NEXT pressure round lands via
4417
+ * the ordinary plan/apply machinery — the synchronous decision path never
4418
+ * waits on an LLM.
4419
+ */
4420
+ async postflightIntentFoldPass(session, turn, signal) {
4421
+ const started = Date.now();
4422
+ const sessionId = String(session.id);
4423
+ const policy = this.activePolicy(session);
4424
+ const settings = this.activeSettings(session);
4425
+ const intentEnabled = settings.intentSummary.enabled;
4426
+ const override = getSummaryOverride(sessionId);
4427
+ observeIntentEnabled(sessionId, intentEnabled);
4428
+ if (policy === void 0) return;
4429
+ if (this.state.pendingIntentFolds.has(session)) return;
4430
+ const advisorState = getAdvisorState(session);
4431
+ if (advisorState.inFlight) return;
4432
+ if (isCoolingDown(advisorState.failures, Date.now())) return;
4433
+ const view = measureForCompaction(this.ctx, session);
4434
+ const thresholdPercent = settings.autoCompact.thresholdPercent;
4435
+ const contextWindow = policy.autoCompactTokens !== void 0 && thresholdPercent > 0 ? Math.round(policy.autoCompactTokens / (thresholdPercent / 100)) : void 0;
4436
+ if (!evaluateIntentGate({
4437
+ enabled: intentEnabled,
4438
+ override,
4439
+ liveTokens: view.totalTokens,
4440
+ contextWindow,
4441
+ baselineTokens: this.state.intentBaselines.get(session) ?? 0
4442
+ }).decision) return;
4443
+ const settingsPreset = settings.presetOptions;
4444
+ if (settingsPreset === void 0) return;
4445
+ if (settingsPreset.estimatorBaseUrl === void 0 || settingsPreset.estimatorBaseUrl.length === 0 || settingsPreset.estimatorModel === void 0 || settingsPreset.estimatorModel.length === 0) {
4446
+ emitCompressionAudit(this.ctx.logger, {
4447
+ schemaVersion: 1,
4448
+ kind: "intent-summary-outcome",
4449
+ sessionId,
4450
+ ok: false,
4451
+ reason: "no-direct-endpoint",
4452
+ turnIndex: turn,
4453
+ latencyMs: Date.now() - started
4454
+ });
4455
+ return;
4456
+ }
4457
+ const candidates = this.snapshot(session, view).filter((candidate) => !this.isRecoveryExempt(session, candidate));
4458
+ const range = computeIntentRange({
4459
+ candidates,
4460
+ protectedSeqs: this.protectedHistoryCandidateSeqs(candidates, policy),
4461
+ foldedSeqs: this.state.intentFoldedSeqs.get(session) ?? /* @__PURE__ */ new Set(),
4462
+ maxCandidates: 20
4463
+ });
4464
+ if (range.seqs.length === 0) return;
4465
+ const bySeq = new Map(candidates.map((candidate) => [candidate.seq, candidate]));
4466
+ const records = [];
4467
+ const errorLines = /* @__PURE__ */ new Set();
4468
+ for (const seq of range.seqs) {
4469
+ const candidate = bySeq.get(seq);
4470
+ if (candidate === void 0) continue;
4471
+ const result = candidate.event.data.message;
4472
+ const text = onlyTextBlock(result.content)?.text ?? "";
4473
+ const masked = maskCandidateForSummary(seq, candidate.call.name, candidate.call.arguments, text);
4474
+ records.push({
4475
+ seq,
4476
+ role: masked.role,
4477
+ toolName: candidate.call.name,
4478
+ line: masked.record
4479
+ });
4480
+ for (const line of extractErrorLines(text)) errorLines.add(line);
4481
+ }
4482
+ if (records.length === 0) return;
4483
+ const events = sessionEvents(session);
4484
+ const task = collectTaskSemantics(events);
4485
+ let channel = this.state.advisorChannels.get(session);
4486
+ if (channel === void 0) {
4487
+ channel = new SideChannel(this.ctx, settingsPreset, {
4488
+ mode: "direct",
4489
+ timeoutMs: 3e4,
4490
+ maxTokens: 512
4491
+ });
4492
+ this.state.advisorChannels.set(session, channel);
4493
+ }
4494
+ const answer = await channel.ask({
4495
+ system: buildIntentSummarySystemPrompt(),
4496
+ user: buildIntentSummaryUserPrompt(task?.taskText ?? "(no task semantics yet)", records.map((record) => record.line), collectTailText(events)),
4497
+ signal
4498
+ });
4499
+ const summaryCallChars = answer?.length ?? 0;
4500
+ const parsed = answer === void 0 ? void 0 : parseIntentSummaryAnswer(answer);
4501
+ if (parsed === void 0) {
4502
+ const failures = (advisorState.failures?.failures ?? 0) + 1;
4503
+ advisorState.failures = {
4504
+ failures,
4505
+ cooldownUntil: Date.now() + backoffCooldownMs(failures)
4506
+ };
4507
+ emitCompressionAudit(this.ctx.logger, {
4508
+ schemaVersion: 1,
4509
+ kind: "intent-summary-outcome",
4510
+ sessionId,
4511
+ ok: false,
4512
+ reason: answer === void 0 ? "ask-failed" : "parse-failed",
4513
+ turnIndex: turn,
4514
+ foldedCount: records.length,
4515
+ summaryCallChars,
4516
+ latencyMs: Date.now() - started
4517
+ });
4518
+ return;
4519
+ }
4520
+ this.state.pendingIntentFolds.set(session, {
4521
+ createdAt: Date.now(),
4522
+ turn,
4523
+ startSeq: range.seqs[0],
4524
+ endSeq: range.seqs[range.seqs.length - 1],
4525
+ summary: parsed.summary,
4526
+ errorLines: [...errorLines],
4527
+ records,
4528
+ summaryCallChars
4529
+ });
4530
+ emitCompressionAudit(this.ctx.logger, {
4531
+ schemaVersion: 1,
4532
+ kind: "intent-summary-outcome",
4533
+ sessionId,
4534
+ ok: true,
4535
+ reason: "staged",
4536
+ turnIndex: turn,
4537
+ foldedCount: records.length,
4538
+ summaryCallChars,
4539
+ latencyMs: Date.now() - started
4540
+ });
4541
+ }
4542
+ /**
4543
+ * Convert a staged pending fold into per-candidate planned replacements
4544
+ * (reducer `intent-summary`). Fail-open: a candidate that would grow, is
4545
+ * rich-content, or no longer exists keeps its original text. Returns
4546
+ * `undefined` when there is nothing (or no longer anything) to fold.
4547
+ */
4548
+ applyPendingIntentFold(session, policy, view, eligible) {
4549
+ const pending = this.state.pendingIntentFolds.get(session);
4550
+ if (pending === void 0) return void 0;
4551
+ const bySeq = new Map(eligible.map((candidate) => [candidate.seq, candidate]));
4552
+ const foldable = pending.records.map((record) => record.seq).filter((seq) => bySeq.has(seq)).sort((a, b) => a - b);
4553
+ if (foldable.length === 0) {
4554
+ this.state.pendingIntentFolds.delete(session);
4555
+ return;
4556
+ }
4557
+ const plans = [];
4558
+ const foldedSeqs = /* @__PURE__ */ new Set();
4559
+ let reclaim = 0;
4560
+ let charsBefore = 0;
4561
+ let charsAfter = 0;
4562
+ for (const seq of foldable) {
4563
+ const candidate = bySeq.get(seq);
4564
+ const result = candidate.event.data.message;
4565
+ const block = onlyTextBlock(result.content);
4566
+ if (block === null) continue;
4567
+ const text = renderIntentFoldBlock(pending, seq);
4568
+ const plan = this.plan(candidate, [{
4569
+ ...block,
4570
+ text
4571
+ }], rootToolResultSeq(session, candidate.seq), "intent-summary", "pressure", "history", policy.historyMode, view);
4572
+ if (plan === null || plan.charsAfter >= plan.charsBefore) continue;
4573
+ plans.push(plan);
4574
+ foldedSeqs.add(seq);
4575
+ reclaim += plan.charsBefore - plan.charsAfter;
4576
+ charsBefore += plan.charsBefore;
4577
+ charsAfter += plan.charsAfter;
4578
+ }
4579
+ if (plans.length === 0) return void 0;
4580
+ this.state.intentFoldedSeqs.get(session)?.forEach((seq) => foldedSeqs.add(seq));
4581
+ return {
4582
+ plans,
4583
+ reclaim,
4584
+ foldedSeqs,
4585
+ charsBefore,
4586
+ charsAfter,
4587
+ turn: pending.turn,
4588
+ summaryCallChars: pending.summaryCallChars
4589
+ };
4590
+ }
4591
+ /**
4423
4592
  * Monotonic per-session turn clock for advisory records. Bumped by the agent
4424
4593
  * loop payloads (`pre-step`); passes without a turn coordinate reuse the last
4425
4594
  * observed value.
@@ -4764,6 +4933,24 @@ var ToolResultPruner = class extends Service {
4764
4933
  this.auditComponent(session, policy, "aggregate", "fresh", policy.aggregateEnabled ? "skipped" : "disabled", policy.aggregateEnabled ? "no-new-tool-result-candidates" : "profile-policy");
4765
4934
  return emptyResult();
4766
4935
  }
4936
+ const ledger = getSavingsLedger();
4937
+ const sid = String(session.id);
4938
+ for (const candidate of candidates) {
4939
+ const text = flattenPlainText(candidate.event.data.message.content);
4940
+ if (text === void 0) continue;
4941
+ ledger.noteFullText({
4942
+ sessionId: sid,
4943
+ seq: candidate.seq,
4944
+ text,
4945
+ measure: () => candidate.count.kind === "exact-tokenizer" && typeof candidate.count.tokens === "number" ? {
4946
+ tokens: candidate.count.tokens,
4947
+ basis: "exact-tokenizer"
4948
+ } : {
4949
+ tokens: Math.ceil(candidate.characterPressure / 4),
4950
+ basis: "characters"
4951
+ }
4952
+ });
4953
+ }
4767
4954
  const plans = /* @__PURE__ */ new Map();
4768
4955
  let freshPlanned = 0;
4769
4956
  const dedupeEnabled = policy.presetOptions?.dedupeToolResults === true;
@@ -5011,13 +5198,41 @@ var ToolResultPruner = class extends Service {
5011
5198
  const isUnsafe = (candidate) => {
5012
5199
  if (this.isRecoveryExempt(session, candidate)) return true;
5013
5200
  const result = candidate.event.data.message.content[0];
5014
- return onlyTextBlock(result.content)?.text.includes("[Old tool result content cleared from active context]") === true;
5201
+ const block = onlyTextBlock(result.content);
5202
+ if (block?.text.includes("[Intent summary") === true) return true;
5203
+ return block?.text.includes("[Old tool result content cleared from active context]") === true;
5015
5204
  };
5016
5205
  const safe = candidates.filter((candidate) => !isUnsafe(candidate));
5017
5206
  const eligible = safe.filter((candidate) => !protectedSeqs.has(candidate.seq));
5018
5207
  if (eligible.length === 0) return safe.length === 0 ? { kind: "no-safe-candidates" } : { kind: "protected-working-set" };
5019
5208
  const planned = [];
5020
5209
  let reclaim = 0;
5210
+ const intentApplied = this.applyPendingIntentFold(session, policy, view, eligible);
5211
+ if (intentApplied !== void 0) {
5212
+ planned.push(...intentApplied.plans);
5213
+ reclaim += intentApplied.reclaim;
5214
+ this.state.intentFoldedSeqs.set(session, intentApplied.foldedSeqs);
5215
+ this.state.pendingIntentFolds.delete(session);
5216
+ this.state.intentBaselines.set(session, view.totalTokens);
5217
+ recordIntentFold(String(session.id), {
5218
+ turn: intentApplied.turn,
5219
+ startSeq: intentApplied.foldedSeqs.size > 0 ? Math.min(...intentApplied.foldedSeqs) : 0,
5220
+ endSeq: intentApplied.foldedSeqs.size > 0 ? Math.max(...intentApplied.foldedSeqs) : 0,
5221
+ liveTokensBefore: view.totalTokens,
5222
+ at: Date.now()
5223
+ });
5224
+ emitCompressionAudit(this.ctx.logger, {
5225
+ schemaVersion: 1,
5226
+ kind: "intent-summary-outcome",
5227
+ sessionId: String(session.id),
5228
+ ok: true,
5229
+ reason: "landed",
5230
+ foldedCount: intentApplied.plans.length,
5231
+ ...intentApplied.charsBefore > 0 ? { retentionRatio: intentApplied.charsAfter / intentApplied.charsBefore } : {},
5232
+ summaryCallChars: intentApplied.summaryCallChars
5233
+ });
5234
+ for (let index = eligible.length - 1; index >= 0; index -= 1) if (intentApplied.foldedSeqs.has(eligible[index].seq)) eligible.splice(index, 1);
5235
+ }
5021
5236
  const minReclaimChars = charsForTokens(policy.historyMinReclaimTokens);
5022
5237
  const microTarget = deadline === void 0 ? void 0 : Math.max(0, charsForTokens(deadline) - minReclaimChars);
5023
5238
  const required = Math.max(minReclaimChars, total - trigger, ...microTarget === void 0 ? [] : [charsForTokens(view.totalTokens) - microTarget]);
@@ -5258,6 +5473,16 @@ var ToolResultPruner = class extends Service {
5258
5473
  tokenizerId: exact === true && exactSurface !== void 0 ? exactSurface.tokenizerId : "characters",
5259
5474
  tokenizerRevision: exact === true && exactSurface !== void 0 ? exactSurface.tokenizerRevision : "chars-per-token-4.0"
5260
5475
  });
5476
+ 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");
5477
+ if (groupText.length > 0) getSavingsLedger().recordSaving({
5478
+ sessionId: String(session.id),
5479
+ component: "tail-trim",
5480
+ tokensBefore,
5481
+ tokensAfter,
5482
+ basis: exact ? "exact-tokenizer" : "characters",
5483
+ sourceSeq: manifestSeq,
5484
+ originalText: groupText
5485
+ });
5261
5486
  return;
5262
5487
  }
5263
5488
  this.auditComponent(session, policy, "tail-trim", "pressure", "skipped", "no-safe-eligible-tool-group", {
@@ -5392,6 +5617,16 @@ var ToolResultPruner = class extends Service {
5392
5617
  tokenizerRevision: plan.tokenizerRevision,
5393
5618
  ...plan.elidedLines === void 0 ? {} : { elidedLines: plan.elidedLines }
5394
5619
  });
5620
+ const pairedOriginal = originalTextForSavings(candidate);
5621
+ getSavingsLedger().recordSaving({
5622
+ sessionId: String(session.id),
5623
+ component: plan.component,
5624
+ tokensBefore: plan.tokensBefore,
5625
+ tokensAfter: plan.tokensAfter,
5626
+ basis: plan.measurementBasis,
5627
+ sourceSeq: plan.sourceSeq,
5628
+ ...pairedOriginal === void 0 ? {} : { originalText: pairedOriginal }
5629
+ });
5395
5630
  return {
5396
5631
  originalSeq: candidate.seq,
5397
5632
  sourceSeq: plan.sourceSeq,