dsh-context-compression-improved 0.7.0-beta.1 → 0.8.0-beta.2

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 (93) hide show
  1. package/CHANGELOG.de.md +539 -0
  2. package/CHANGELOG.es.md +547 -0
  3. package/CHANGELOG.fr.md +534 -0
  4. package/CHANGELOG.it.md +536 -0
  5. package/CHANGELOG.ja.md +226 -220
  6. package/CHANGELOG.ko.md +220 -214
  7. package/CHANGELOG.md +372 -376
  8. package/CHANGELOG.ru.md +517 -0
  9. package/CHANGELOG.zh.md +204 -199
  10. package/README.de.md +98 -0
  11. package/README.es.md +98 -0
  12. package/README.fr.md +98 -0
  13. package/README.it.md +98 -0
  14. package/README.ja.md +85 -85
  15. package/README.ko.md +85 -85
  16. package/README.md +98 -97
  17. package/README.ru.md +98 -0
  18. package/README.zh.md +85 -86
  19. package/docs/installation.de.md +104 -0
  20. package/docs/installation.es.md +104 -0
  21. package/docs/installation.fr.md +104 -0
  22. package/docs/installation.it.md +104 -0
  23. package/docs/installation.ja.md +78 -78
  24. package/docs/installation.ko.md +78 -78
  25. package/docs/installation.md +103 -103
  26. package/docs/installation.ru.md +104 -0
  27. package/docs/installation.zh.md +100 -100
  28. package/eslint.config.js +30 -76
  29. package/package.json +69 -70
  30. package/packages/selector/dsh.plugin.json +2 -2
  31. package/packages/selector/lib/{intent-gate.js → advisor-state.js} +3 -91
  32. package/packages/selector/lib/client.js +736 -14
  33. package/packages/selector/lib/index.js +1 -92
  34. package/packages/selector/lib/profiles.d.ts +0 -9
  35. package/packages/selector/lib/pruner.d.ts +0 -59
  36. package/packages/selector/lib/pruner.js +7 -410
  37. package/packages/selector/lib/style.css +46 -46
  38. package/packages/selector/package.json +114 -114
  39. package/packages/selector/src/client/decode.ts +2 -6
  40. package/packages/selector/src/client/index.ts +244 -213
  41. package/packages/selector/src/client/locales/de.ts +98 -0
  42. package/packages/selector/src/client/locales/es.ts +98 -0
  43. package/packages/selector/src/client/locales/fr.ts +98 -0
  44. package/packages/selector/src/client/locales/it.ts +98 -0
  45. package/packages/selector/src/client/locales/ja.ts +98 -0
  46. package/packages/selector/src/client/locales/ko.ts +98 -0
  47. package/packages/selector/src/client/locales/ru.ts +98 -0
  48. package/packages/selector/src/deepseek-v4-tokenizer.ts +1 -1
  49. package/packages/selector/src/index.ts +411 -418
  50. package/packages/selector/src/preset-overlay.ts +0 -3
  51. package/packages/selector/src/profiles.ts +10 -30
  52. package/packages/selector/src/pruner/content.ts +1 -1
  53. package/packages/selector/src/pruner/state.ts +0 -7
  54. package/packages/selector/src/pruner.ts +9 -253
  55. package/packages/selector/src/runtime/audit.ts +0 -17
  56. package/packages/selector/src/runtime/config.ts +11 -36
  57. package/packages/selector/src/runtime/reducers.ts +1 -1
  58. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +1 -46
  59. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +0 -55
  60. package/packages/selector/src/runtime/tokenpilot/locator.ts +2 -2
  61. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +1 -4
  62. package/packages/selector/src/runtime/types.ts +0 -12
  63. package/packages/selector/tests/auto-compact.client.spec.tsx +213 -214
  64. package/packages/selector/tests/built/client-artifact.spec.ts +59 -61
  65. package/packages/selector/tests/code-skeleton.client.spec.ts +93 -94
  66. package/packages/selector/tests/custom-contract.client.spec.ts +222 -223
  67. package/packages/selector/tests/estimator-channel.client.spec.tsx +252 -252
  68. package/packages/selector/tests/host-preset-overlay.host.spec.ts +204 -204
  69. package/packages/selector/tests/preset-options-write.client.spec.ts +187 -188
  70. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +200 -200
  71. package/packages/selector/tests/profiles.client.spec.tsx +434 -436
  72. package/packages/selector/tests/public/package-contract.client.spec.ts +78 -78
  73. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +230 -230
  74. package/packages/selector/tests/runtime/audit.spec.ts +274 -275
  75. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +3 -3
  76. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +4 -4
  77. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2731 -2736
  78. package/packages/selector/tests/standing-generation.host.spec.ts +724 -704
  79. package/pnpm-workspace.yaml +66 -66
  80. package/scripts/packed-components-smoke.mjs +0 -2
  81. package/scripts/packed-install-e2e.mjs +5 -7
  82. package/scripts/verify-release.mjs +2 -3
  83. package/tests/TEST_INVENTORY.md +41 -41
  84. package/tsconfig.tests.json +1 -3
  85. package/vitest.config.ts +0 -14
  86. package/packages/selector/src/runtime/summary-command.ts +0 -133
  87. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +0 -53
  88. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +0 -65
  89. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +0 -125
  90. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +0 -37
  91. package/packages/selector/tests/runtime/intent-gate.spec.ts +0 -62
  92. package/packages/selector/tests/runtime/intent-summary.spec.ts +0 -156
  93. package/packages/selector/tests/runtime/summary-command.spec.ts +0 -154
@@ -1,4 +1,4 @@
1
- import { A as resolveCustomPolicy, C as isCompressionProfile, D as resolvePolicy, E as resolveConfig, M as deepFreeze, N as COMPRESSION_PROFILES, O as CustomCompressionPolicySchema, 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";
1
+ import { C as deepFreeze, S as assertNever, _ as resolveConfig, a as AUTO_COMPACT_THRESHOLD_LIMITS, b as DEFAULT_CUSTOM_COMPRESSION_POLICY, c as DEFAULTS, d as charsForTokens, f as charsToTokens, g as parseContextCompressionSettings, h as isValidAutoCompactThresholdPercent, i as recordScore, m as isCompressionProfile, n as invalidateOnTaskChange, o as CONTEXT_COMPRESSION_SETTINGS_NAMESPACE, p as codePointLength, r as recordRecertified, s as ContextCompressionSettingsSchema, t as getAdvisorState, u as PRUNE_MARKER, v as resolvePolicy, w as COMPRESSION_PROFILES, x as resolveCustomPolicy, y as CustomCompressionPolicySchema } from "./advisor-state.js";
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";
@@ -439,7 +439,7 @@ function nativePruneContent(blocks, thresholdChars, headChars, tailChars, marker
439
439
  const tailStart = Math.min(points.length, Math.max(0, removedEnd - blockStart));
440
440
  const intersectsRemoved = blockStart < removedEnd && blockEnd > removedStart;
441
441
  const headText = points.slice(0, headEnd).join("");
442
- const insertion = intersectsRemoved && !markerInserted && typeof marker === "function" ? marker(1 + newlinesBefore + headText.split("\n").length - 1) : intersectsRemoved && !markerInserted && typeof marker === "string" ? marker : "";
442
+ const insertion = intersectsRemoved && !markerInserted && typeof marker === "function" ? marker(1 + newlinesBefore + headText.split("\n").length - 1) : intersectsRemoved && !markerInserted ? marker : "";
443
443
  if (insertion !== "") markerInserted = true;
444
444
  const text = points.slice(0, headEnd).join("") + insertion + points.slice(tailStart).join("");
445
445
  if (text !== "") pruned.push({
@@ -1179,7 +1179,7 @@ function buildLocatorBlock(events, shadowedRange) {
1179
1179
  const data = event.data;
1180
1180
  const content = Array.isArray(data.content) ? data.content : data.message?.content;
1181
1181
  if (!Array.isArray(content)) continue;
1182
- for (const block of content) if (block.type === "text" && typeof block.text === "string") for (const path of extractSpillPaths(block.text)) spillFiles.add(path);
1182
+ for (const block of content) if (block.type === "text") for (const path of extractSpillPaths(block.text)) spillFiles.add(path);
1183
1183
  }
1184
1184
  }
1185
1185
  if (spillFiles.size === 0 && touchedFiles.size === 0) return null;
@@ -1397,7 +1397,7 @@ function reduceFreshToolResult(input, ranking) {
1397
1397
  lines: normalized.folded,
1398
1398
  contentText: normalized.contentText
1399
1399
  };
1400
- const command = extractCommand$1(input.argumentsText);
1400
+ const command = extractCommand(input.argumentsText);
1401
1401
  const name = input.toolName.toLowerCase();
1402
1402
  const toolClass = classifyToolSource(input.toolName, command, normalized.contentText);
1403
1403
  const readTocFirst = toolClass === "read" && codePointLength(normalized.contentText) >= READ_TOC_MIN_CHARS;
@@ -2680,7 +2680,7 @@ function splitLines(text) {
2680
2680
  * @param argumentsText - raw JSON arguments of the tool call.
2681
2681
  * @returns the command string, or '' when absent.
2682
2682
  */
2683
- function extractCommand$1(argumentsText) {
2683
+ function extractCommand(argumentsText) {
2684
2684
  try {
2685
2685
  const parsed = JSON.parse(argumentsText);
2686
2686
  if (typeof parsed !== "object" || parsed === null) return "";
@@ -3248,42 +3248,6 @@ function parseAdvisorScores(text, validSeqs) {
3248
3248
  }
3249
3249
  return scores.size > 0 ? scores : void 0;
3250
3250
  }
3251
- /** Hard character cap for one intent-summary answer (summary segment only). */
3252
- const INTENT_SUMMARY_CHAR_CAP = 1600;
3253
- /**
3254
- * Intent-summary writer prompts (task_2.3). Input records are already
3255
- * semantic-role-masked by intent-input-mask.ts: read-class candidates are
3256
- * one-line "read X" records, keep-class candidates carry skeleton heads and
3257
- * VERBATIM error lines. The model writes ONLY the summary segment — it never
3258
- * revoices error lines, and its answer must stay inside the char cap.
3259
- */
3260
- function buildIntentSummarySystemPrompt() {
3261
- return [
3262
- "You write one concise intent summary of folded tool results for a coding agent session.",
3263
- "Input: the session task (todolist) and per-tool slimmed records (read lines, or skeleton heads with verbatim error lines).",
3264
- `Write ONLY what the agent DID and LEARNED in this span, as flowing prose under ${INTENT_SUMMARY_CHAR_CAP} characters.`,
3265
- "Mention which files/areas were consulted and what changed, so a later turn can continue without the originals.",
3266
- "Never invent files, commands, or outcomes absent from the records. Never revoice error lines; they are preserved verbatim elsewhere.",
3267
- "Answer with ONLY one JSON object: {\"summary\":\"<prose>\"}. Never add commentary."
3268
- ].join(" ");
3269
- }
3270
- function buildIntentSummaryUserPrompt(taskText, records, tailText) {
3271
- const nl = String.fromCharCode(10);
3272
- return [
3273
- `task: ${taskText.replace(/\s+/gu, " ").slice(0, 600)}`,
3274
- records.length > 0 ? `records:${nl}${records.join(nl)}` : "records: (none)",
3275
- tailText.trim().length > 0 ? `recent tail:${nl}${tailText.trim().slice(0, 1200)}` : "recent tail: (none)"
3276
- ].join("\n\n");
3277
- }
3278
- /** Fail-open parse of one intent-summary answer; `undefined` on any malformed shape. */
3279
- function parseIntentSummaryAnswer(text) {
3280
- const parsed = firstJsonObject(text);
3281
- if (parsed === void 0) return void 0;
3282
- const summary = parsed.summary;
3283
- if (typeof summary !== "string" || summary.trim().length === 0) return void 0;
3284
- if (summary.length > 3200) return void 0;
3285
- return { summary: summary.trim().slice(0, INTENT_SUMMARY_CHAR_CAP) };
3286
- }
3287
3251
  //#endregion
3288
3252
  //#region src/runtime/tokenpilot/advisor.ts
3289
3253
  /** Character cap for the recent-text fallback and the tail-text summary input. */
@@ -3585,162 +3549,6 @@ async function runSessionAdvisorPass(session, channel, emit, input) {
3585
3549
  }
3586
3550
  }
3587
3551
  //#endregion
3588
- //#region src/runtime/tokenpilot/intent-input-mask.ts
3589
- /**
3590
- * Semantic-role input masking for the intent-summary writer (task_2.2).
3591
- *
3592
- * The intent summary records historical TASK semantics — for read-class tools
3593
- * the semantics are "read X", never the file body, so the body is masked to a
3594
- * one-line record before it can reach the summary prompt. Write-class results
3595
- * (edits) ARE task semantics and keep their skeleton + verbatim error lines.
3596
- *
3597
- * Classification REUSES `classifyToolSource()` (reducers.ts routes on the
3598
- * same classes): hand-rolling a name→role map here would regress its fixed
3599
- * misclassification edges (mcp→generic, web_search/memory_search not being
3600
- * content search, glob being path-listing, execute_sql not being shell).
3601
- * Only the write class is layered on top — `ToolClass` has no write member.
3602
- */
3603
- /** Exact-token write layer, same tokenization discipline as toolclass. */
3604
- const WRITE_NAMES = /* @__PURE__ */ new Set([
3605
- "apply_patch",
3606
- "multi_edit",
3607
- "create_file",
3608
- "write_to_file",
3609
- "str_replace_editor"
3610
- ]);
3611
- const WRITE_TOKENS = /* @__PURE__ */ new Set([
3612
- "write",
3613
- "edit",
3614
- "patch"
3615
- ]);
3616
- function hasWriteToken(name) {
3617
- const lowered = name.toLowerCase();
3618
- if (WRITE_NAMES.has(lowered)) return true;
3619
- return lowered.split(/[-_/]+/).some((token) => WRITE_TOKENS.has(token));
3620
- }
3621
- /**
3622
- * Role for one candidate. The write layer is consulted first; everything
3623
- * else defers to the shared classifier. `shell`/`generic` stay conservative
3624
- * (skeleton + error lines, never a blind mask) — a bash result can be a
3625
- * mutation even when its name says nothing.
3626
- */
3627
- function classifyIntentRole(toolName, command, text) {
3628
- if (hasWriteToken(toolName)) return "write-keep";
3629
- const toolClass = classifyToolSource(toolName, command, text);
3630
- if (toolClass === "read" || toolClass === "search" || toolClass === "path-listing") return "read-mask";
3631
- return "conservative";
3632
- }
3633
- const ERROR_LINE_PATTERN = /\b(error|failed|failure|exception|panic|fatal|traceback|unreachable|denied)\b/i;
3634
- const KEEP_HEAD_LINES = 40;
3635
- const KEEP_HEAD_CHARS = 2e3;
3636
- /** Verbatim error/warn lines kept out of the LLM's hands and into the intent block. */
3637
- function extractErrorLines(text) {
3638
- return text.split("\n").filter((line) => ERROR_LINE_PATTERN.test(line)).slice(0, 10);
3639
- }
3640
- /** Count lines and code points for the read-mask record tail. */
3641
- function scaleOf(text) {
3642
- return {
3643
- lines: text.length === 0 ? 0 : text.split("\n").length,
3644
- chars: text.length
3645
- };
3646
- }
3647
- /**
3648
- * Build the prompt face for one candidate. Read-mask output contains NONE of
3649
- * the original body — only the tool name, the call's target argument, and
3650
- * the dropped scale — so a hostile body can never leak into the summary.
3651
- */
3652
- function maskCandidateForSummary(seq, toolName, argumentsText, text) {
3653
- const role = classifyIntentRole(toolName, extractCommand(argumentsText), text);
3654
- if (role === "read-mask") {
3655
- const { lines, chars } = scaleOf(text);
3656
- return {
3657
- seq,
3658
- role,
3659
- record: `${toolName} ${extractTarget(argumentsText)} -> masked (${lines} lines / ${chars} chars)`
3660
- };
3661
- }
3662
- const head = text.split("\n", KEEP_HEAD_LINES).join("\n").slice(0, KEEP_HEAD_CHARS);
3663
- const errorLines = extractErrorLines(text);
3664
- return {
3665
- seq,
3666
- role,
3667
- record: `${toolName} (seq ${seq})\n${head}${errorLines.length > 0 ? `\nerror lines (verbatim):\n${errorLines.join("\n")}` : ""}`
3668
- };
3669
- }
3670
- /** Extract a short command head from a tool-call arguments JSON string. */
3671
- function extractCommand(argumentsText) {
3672
- try {
3673
- const parsed = JSON.parse(argumentsText);
3674
- if (parsed !== null && typeof parsed === "object") {
3675
- const command = parsed.command;
3676
- if (typeof command === "string") return command.slice(0, 200);
3677
- }
3678
- } catch {}
3679
- return "";
3680
- }
3681
- /** Extract the most target-like string argument (path/query/url) for read-mask records. */
3682
- function extractTarget(argumentsText) {
3683
- try {
3684
- const parsed = JSON.parse(argumentsText);
3685
- if (parsed !== null && typeof parsed === "object") {
3686
- const record = parsed;
3687
- const target = [
3688
- record.path,
3689
- record.file_path,
3690
- record.query,
3691
- record.url,
3692
- record.pattern,
3693
- record.glob
3694
- ].find((candidate) => typeof candidate === "string" && candidate.trim().length > 0);
3695
- if (typeof target === "string") return target.slice(0, 160);
3696
- const first = Object.values(record).find((value) => typeof value === "string");
3697
- if (typeof first === "string") return first.slice(0, 160);
3698
- }
3699
- } catch {}
3700
- return "(unparsed target)";
3701
- }
3702
- //#endregion
3703
- //#region src/runtime/tokenpilot/intent-range.ts
3704
- /**
3705
- * Oldest-first selection of foldable candidates. Excludes the protected
3706
- * working set and already-folded seqs; caps the batch size.
3707
- */
3708
- function computeIntentRange(input) {
3709
- const unprotected = input.candidates.filter((candidate) => !input.protectedSeqs.has(candidate.seq));
3710
- const skippedProtected = input.candidates.length - unprotected.length;
3711
- const eligible = unprotected.filter((candidate) => !input.foldedSeqs.has(candidate.seq));
3712
- const skippedFolded = unprotected.length - eligible.length;
3713
- return {
3714
- seqs: [...eligible].sort((a, b) => a.seq - b.seq).slice(0, Math.max(0, input.maxCandidates)).map((candidate) => candidate.seq),
3715
- skippedProtected,
3716
- skippedFolded
3717
- };
3718
- }
3719
- //#endregion
3720
- //#region src/runtime/tokenpilot/intent-fold.ts
3721
- /** Marker written into every folded block; its presence makes a seq unfoldable again (fold-once). */
3722
- const INTENT_FOLD_MARKER = "[Intent summary";
3723
- /** Render the replacement text for one folded candidate. Pure. */
3724
- function renderIntentFoldBlock(pending, seq) {
3725
- const start = pending.startSeq;
3726
- const end = pending.endSeq;
3727
- if (seq === start) {
3728
- const readLines = pending.records.filter((record) => record.role === "read-mask").map((record) => record.line);
3729
- const consulted = readLines.length > 0 ? `Consulted: ${readLines.join("; ")}` : "";
3730
- const errorBlock = pending.errorLines.length > 0 ? `\nError lines (verbatim):\n${pending.errorLines.join("\n")}` : "";
3731
- return [
3732
- `${INTENT_FOLD_MARKER} of folded tool results seq ${start}..${end}]`,
3733
- pending.summary,
3734
- consulted,
3735
- errorBlock,
3736
- "[Original content remains in the session log at the listed seq values.]"
3737
- ].filter((part) => part.length > 0).join("\n");
3738
- }
3739
- const record = pending.records.find((entry) => entry.seq === seq);
3740
- const face = record === void 0 ? `${seq}` : record.role === "read-mask" ? record.line : `${record.toolName} result folded into the batch intent summary`;
3741
- return `${INTENT_FOLD_MARKER} folded into the batch summary above (seq ${start}..${end})] ${face}`;
3742
- }
3743
- //#endregion
3744
3552
  //#region src/runtime/tokenpilot/dedup.ts
3745
3553
  /**
3746
3554
  * TokenPilot-inspired A1: byte-identical repeated tool-result dedup.
@@ -4232,10 +4040,7 @@ var ToolResultPruner = class extends Service {
4232
4040
  policyResolutionAudits: /* @__PURE__ */ new WeakMap(),
4233
4041
  turnClocks: /* @__PURE__ */ new WeakMap(),
4234
4042
  estimatorRemainingTurns: /* @__PURE__ */ new WeakMap(),
4235
- advisorChannels: /* @__PURE__ */ new WeakMap(),
4236
- pendingIntentFolds: /* @__PURE__ */ new WeakMap(),
4237
- intentFoldedSeqs: /* @__PURE__ */ new WeakMap(),
4238
- intentBaselines: /* @__PURE__ */ new WeakMap()
4043
+ advisorChannels: /* @__PURE__ */ new WeakMap()
4239
4044
  };
4240
4045
  ctx.on("session/event", (session, event) => {
4241
4046
  this.scanForSeededNativeSummary(session);
@@ -4279,7 +4084,6 @@ var ToolResultPruner = class extends Service {
4279
4084
  }
4280
4085
  this.postflightEstimatorPass(agent.session, signal).catch(() => void 0);
4281
4086
  this.postflightAdvisorPass(agent.session, turn, signal).catch(() => void 0);
4282
- this.postflightIntentFoldPass(agent.session, turn, signal).catch(() => void 0);
4283
4087
  });
4284
4088
  }
4285
4089
  /**
@@ -4607,185 +4411,6 @@ var ToolResultPruner = class extends Service {
4607
4411
  else if (outcome !== void 0) advisorState.failures = void 0;
4608
4412
  }
4609
4413
  /**
4610
- * Fire-and-forget postflight: evaluate the growth gate, and only when it
4611
- * passes, select the consumed increment OUTSIDE the protected working set,
4612
- * mask it to semantic-role records, and spend ONE summary-writer call. The
4613
- * verdict stages as a pending fold that the NEXT pressure round lands via
4614
- * the ordinary plan/apply machinery — the synchronous decision path never
4615
- * waits on an LLM.
4616
- */
4617
- async postflightIntentFoldPass(session, turn, signal) {
4618
- const started = Date.now();
4619
- const sessionId = String(session.id);
4620
- const policy = this.activePolicy(session);
4621
- const settings = this.activeSettings(session);
4622
- const intentEnabled = settings.intentSummary.enabled;
4623
- const override = getSummaryOverride(sessionId);
4624
- observeIntentEnabled(sessionId, intentEnabled);
4625
- if (policy === void 0) return;
4626
- if (this.state.pendingIntentFolds.has(session)) return;
4627
- const advisorState = getAdvisorState(session);
4628
- if (advisorState.inFlight) return;
4629
- if (isCoolingDown(advisorState.failures, Date.now())) return;
4630
- const view = measureForCompaction(this.ctx, session);
4631
- const thresholdPercent = settings.autoCompact.thresholdPercent;
4632
- const contextWindow = policy.autoCompactTokens !== void 0 && thresholdPercent > 0 ? Math.round(policy.autoCompactTokens / (thresholdPercent / 100)) : void 0;
4633
- if (!evaluateIntentGate({
4634
- enabled: intentEnabled,
4635
- override,
4636
- liveTokens: view.totalTokens,
4637
- contextWindow,
4638
- baselineTokens: this.state.intentBaselines.get(session) ?? 0
4639
- }).decision) return;
4640
- const settingsPreset = settings.presetOptions;
4641
- if (settingsPreset === void 0) return;
4642
- if (settingsPreset.estimatorBaseUrl === void 0 || settingsPreset.estimatorBaseUrl.length === 0 || settingsPreset.estimatorModel === void 0 || settingsPreset.estimatorModel.length === 0) {
4643
- emitCompressionAudit(this.ctx.logger, {
4644
- schemaVersion: 1,
4645
- kind: "intent-summary-outcome",
4646
- sessionId,
4647
- ok: false,
4648
- reason: "no-direct-endpoint",
4649
- turnIndex: turn,
4650
- latencyMs: Date.now() - started
4651
- });
4652
- return;
4653
- }
4654
- const candidates = this.snapshot(session, view).filter((candidate) => !this.isRecoveryExempt(session, candidate));
4655
- const range = computeIntentRange({
4656
- candidates,
4657
- protectedSeqs: this.protectedHistoryCandidateSeqs(candidates, policy),
4658
- foldedSeqs: this.state.intentFoldedSeqs.get(session) ?? /* @__PURE__ */ new Set(),
4659
- maxCandidates: 20
4660
- });
4661
- if (range.seqs.length === 0) return;
4662
- const bySeq = new Map(candidates.map((candidate) => [candidate.seq, candidate]));
4663
- const records = [];
4664
- const errorLines = /* @__PURE__ */ new Set();
4665
- for (const seq of range.seqs) {
4666
- const candidate = bySeq.get(seq);
4667
- if (candidate === void 0) continue;
4668
- const result = candidate.event.data.message;
4669
- const text = onlyTextBlock(result.content)?.text ?? "";
4670
- const masked = maskCandidateForSummary(seq, candidate.call.name, candidate.call.arguments, text);
4671
- records.push({
4672
- seq,
4673
- role: masked.role,
4674
- toolName: candidate.call.name,
4675
- line: masked.record
4676
- });
4677
- for (const line of extractErrorLines(text)) errorLines.add(line);
4678
- }
4679
- if (records.length === 0) return;
4680
- const events = sessionEvents(session);
4681
- const task = collectTaskSemantics(events);
4682
- let channel = this.state.advisorChannels.get(session);
4683
- if (channel === void 0) {
4684
- channel = new SideChannel(this.ctx, settingsPreset, {
4685
- mode: "direct",
4686
- timeoutMs: 3e4,
4687
- maxTokens: 512
4688
- });
4689
- this.state.advisorChannels.set(session, channel);
4690
- }
4691
- const answer = await channel.ask({
4692
- system: buildIntentSummarySystemPrompt(),
4693
- user: buildIntentSummaryUserPrompt(task?.taskText ?? "(no task semantics yet)", records.map((record) => record.line), collectTailText(events)),
4694
- signal
4695
- });
4696
- const summaryCallChars = answer?.length ?? 0;
4697
- const parsed = answer === void 0 ? void 0 : parseIntentSummaryAnswer(answer);
4698
- if (parsed === void 0) {
4699
- const failures = (advisorState.failures?.failures ?? 0) + 1;
4700
- advisorState.failures = {
4701
- failures,
4702
- cooldownUntil: Date.now() + backoffCooldownMs(failures)
4703
- };
4704
- emitCompressionAudit(this.ctx.logger, {
4705
- schemaVersion: 1,
4706
- kind: "intent-summary-outcome",
4707
- sessionId,
4708
- ok: false,
4709
- reason: answer === void 0 ? "ask-failed" : "parse-failed",
4710
- turnIndex: turn,
4711
- foldedCount: records.length,
4712
- summaryCallChars,
4713
- latencyMs: Date.now() - started
4714
- });
4715
- return;
4716
- }
4717
- this.state.pendingIntentFolds.set(session, {
4718
- createdAt: Date.now(),
4719
- turn,
4720
- startSeq: range.seqs[0],
4721
- endSeq: range.seqs[range.seqs.length - 1],
4722
- summary: parsed.summary,
4723
- errorLines: [...errorLines],
4724
- records,
4725
- summaryCallChars
4726
- });
4727
- emitCompressionAudit(this.ctx.logger, {
4728
- schemaVersion: 1,
4729
- kind: "intent-summary-outcome",
4730
- sessionId,
4731
- ok: true,
4732
- reason: "staged",
4733
- turnIndex: turn,
4734
- foldedCount: records.length,
4735
- summaryCallChars,
4736
- latencyMs: Date.now() - started
4737
- });
4738
- }
4739
- /**
4740
- * Convert a staged pending fold into per-candidate planned replacements
4741
- * (reducer `intent-summary`). Fail-open: a candidate that would grow, is
4742
- * rich-content, or no longer exists keeps its original text. Returns
4743
- * `undefined` when there is nothing (or no longer anything) to fold.
4744
- */
4745
- applyPendingIntentFold(session, policy, view, eligible) {
4746
- const pending = this.state.pendingIntentFolds.get(session);
4747
- if (pending === void 0) return void 0;
4748
- const bySeq = new Map(eligible.map((candidate) => [candidate.seq, candidate]));
4749
- const foldable = pending.records.map((record) => record.seq).filter((seq) => bySeq.has(seq)).sort((a, b) => a - b);
4750
- if (foldable.length === 0) {
4751
- this.state.pendingIntentFolds.delete(session);
4752
- return;
4753
- }
4754
- const plans = [];
4755
- const foldedSeqs = /* @__PURE__ */ new Set();
4756
- let reclaim = 0;
4757
- let charsBefore = 0;
4758
- let charsAfter = 0;
4759
- for (const seq of foldable) {
4760
- const candidate = bySeq.get(seq);
4761
- const result = candidate.event.data.message;
4762
- const block = onlyTextBlock(result.content);
4763
- if (block === null) continue;
4764
- const text = renderIntentFoldBlock(pending, seq);
4765
- const plan = this.plan(candidate, [{
4766
- ...block,
4767
- text
4768
- }], rootToolResultSeq(session, candidate.seq), "intent-summary", "pressure", "history", policy.historyMode, view);
4769
- if (plan === null || plan.charsAfter >= plan.charsBefore) continue;
4770
- plans.push(plan);
4771
- foldedSeqs.add(seq);
4772
- reclaim += plan.charsBefore - plan.charsAfter;
4773
- charsBefore += plan.charsBefore;
4774
- charsAfter += plan.charsAfter;
4775
- }
4776
- if (plans.length === 0) return void 0;
4777
- this.state.intentFoldedSeqs.get(session)?.forEach((seq) => foldedSeqs.add(seq));
4778
- return {
4779
- plans,
4780
- reclaim,
4781
- foldedSeqs,
4782
- charsBefore,
4783
- charsAfter,
4784
- turn: pending.turn,
4785
- summaryCallChars: pending.summaryCallChars
4786
- };
4787
- }
4788
- /**
4789
4414
  * Monotonic per-session turn clock for advisory records. Bumped by the agent
4790
4415
  * loop payloads (`pre-step`); passes without a turn coordinate reuse the last
4791
4416
  * observed value.
@@ -5377,41 +5002,13 @@ var ToolResultPruner = class extends Service {
5377
5002
  const isUnsafe = (candidate) => {
5378
5003
  if (this.isRecoveryExempt(session, candidate)) return true;
5379
5004
  const result = candidate.event.data.message;
5380
- const block = onlyTextBlock(result.content);
5381
- if (block?.text.includes("[Intent summary") === true) return true;
5382
- return block?.text.includes("[Old tool result content cleared from active context]") === true;
5005
+ return onlyTextBlock(result.content)?.text.includes("[Old tool result content cleared from active context]") === true;
5383
5006
  };
5384
5007
  const safe = candidates.filter((candidate) => !isUnsafe(candidate));
5385
5008
  const eligible = safe.filter((candidate) => !protectedSeqs.has(candidate.seq));
5386
5009
  if (eligible.length === 0) return safe.length === 0 ? { kind: "no-safe-candidates" } : { kind: "protected-working-set" };
5387
5010
  const planned = [];
5388
5011
  let reclaim = 0;
5389
- const intentApplied = this.applyPendingIntentFold(session, policy, view, eligible);
5390
- if (intentApplied !== void 0) {
5391
- planned.push(...intentApplied.plans);
5392
- reclaim += intentApplied.reclaim;
5393
- this.state.intentFoldedSeqs.set(session, intentApplied.foldedSeqs);
5394
- this.state.pendingIntentFolds.delete(session);
5395
- this.state.intentBaselines.set(session, view.totalTokens);
5396
- recordIntentFold(String(session.id), {
5397
- turn: intentApplied.turn,
5398
- startSeq: intentApplied.foldedSeqs.size > 0 ? Math.min(...intentApplied.foldedSeqs) : 0,
5399
- endSeq: intentApplied.foldedSeqs.size > 0 ? Math.max(...intentApplied.foldedSeqs) : 0,
5400
- liveTokensBefore: view.totalTokens,
5401
- at: Date.now()
5402
- });
5403
- emitCompressionAudit(this.ctx.logger, {
5404
- schemaVersion: 1,
5405
- kind: "intent-summary-outcome",
5406
- sessionId: String(session.id),
5407
- ok: true,
5408
- reason: "landed",
5409
- foldedCount: intentApplied.plans.length,
5410
- ...intentApplied.charsBefore > 0 ? { retentionRatio: intentApplied.charsAfter / intentApplied.charsBefore } : {},
5411
- summaryCallChars: intentApplied.summaryCallChars
5412
- });
5413
- for (let index = eligible.length - 1; index >= 0; index -= 1) if (intentApplied.foldedSeqs.has(eligible[index].seq)) eligible.splice(index, 1);
5414
- }
5415
5012
  const minReclaimChars = charsForTokens(policy.historyMinReclaimTokens);
5416
5013
  const microTarget = deadline === void 0 ? void 0 : Math.max(0, charsForTokens(deadline) - minReclaimChars);
5417
5014
  const required = Math.max(minReclaimChars, total - trigger, ...microTarget === void 0 ? [] : [charsForTokens(view.totalTokens) - microTarget]);