dsh-context-compression-improved 0.6.5 → 0.7.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 (70) hide show
  1. package/.github/workflows/ci.yml +39 -39
  2. package/CHANGELOG.ja.md +217 -211
  3. package/CHANGELOG.ko.md +211 -205
  4. package/CHANGELOG.md +392 -350
  5. package/CHANGELOG.zh.md +196 -190
  6. package/README.md +97 -96
  7. package/README.zh.md +86 -85
  8. package/eslint.config.js +76 -30
  9. package/package.json +3 -1
  10. package/packages/selector/dsh.plugin.json +1 -1
  11. package/packages/selector/lib/client.js +747 -3
  12. package/packages/selector/lib/index.js +92 -1
  13. package/packages/selector/lib/{advisor-state.js → intent-gate.js} +91 -3
  14. package/packages/selector/lib/profiles.d.ts +9 -0
  15. package/packages/selector/lib/pruner.d.ts +59 -0
  16. package/packages/selector/lib/pruner.js +410 -8
  17. package/packages/selector/src/client/decode.ts +53 -49
  18. package/packages/selector/src/client/index.ts +30 -0
  19. package/packages/selector/src/client/locales/de.ts +98 -0
  20. package/packages/selector/src/client/locales/es.ts +98 -0
  21. package/packages/selector/src/client/locales/fr.ts +98 -0
  22. package/packages/selector/src/client/locales/it.ts +98 -0
  23. package/packages/selector/src/client/locales/ja.ts +98 -0
  24. package/packages/selector/src/client/locales/ko.ts +98 -0
  25. package/packages/selector/src/client/locales/ru.ts +98 -0
  26. package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -205
  27. package/packages/selector/src/index.ts +418 -411
  28. package/packages/selector/src/preset-overlay.ts +629 -626
  29. package/packages/selector/src/profiles.ts +414 -394
  30. package/packages/selector/src/pruner/content.ts +198 -198
  31. package/packages/selector/src/pruner/state.ts +57 -50
  32. package/packages/selector/src/pruner.ts +2665 -2421
  33. package/packages/selector/src/runtime/audit.ts +303 -286
  34. package/packages/selector/src/runtime/config.ts +731 -706
  35. package/packages/selector/src/runtime/reducers.ts +1674 -1674
  36. package/packages/selector/src/runtime/summary-command.ts +133 -0
  37. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -188
  38. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -149
  39. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
  40. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
  41. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
  42. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
  43. package/packages/selector/src/runtime/tokenpilot/locator.ts +128 -128
  44. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +306 -303
  45. package/packages/selector/src/runtime/types.ts +358 -346
  46. package/packages/selector/tests/auto-compact.client.spec.tsx +214 -213
  47. package/packages/selector/tests/built/client-artifact.spec.ts +61 -59
  48. package/packages/selector/tests/code-skeleton.client.spec.ts +94 -93
  49. package/packages/selector/tests/custom-contract.client.spec.ts +223 -222
  50. package/packages/selector/tests/estimator-channel.client.spec.tsx +252 -252
  51. package/packages/selector/tests/preset-options-write.client.spec.ts +188 -187
  52. package/packages/selector/tests/profiles.client.spec.tsx +436 -434
  53. package/packages/selector/tests/runtime/audit.spec.ts +275 -274
  54. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +523 -523
  55. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +122 -122
  56. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
  57. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
  58. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +5 -0
  59. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
  60. package/packages/selector/tests/standing-generation.host.spec.ts +15 -35
  61. package/scripts/packed-components-smoke.mjs +734 -732
  62. package/scripts/packed-install-e2e.mjs +1275 -1273
  63. package/scripts/verify-release.mjs +318 -317
  64. package/tests/TEST_INVENTORY.md +41 -41
  65. package/tsconfig.tests.json +17 -15
  66. package/vitest.config.ts +57 -43
  67. package/.agents-stash-064.patch +0 -39
  68. package/_dsh_devdeps.json +0 -50
  69. package/_verify064/package/package.json +0 -162
  70. package/_verify064/package/packages/selector/src/client/index.ts +0 -232
@@ -1,4 +1,4 @@
1
- import { C as deepFreeze, S as assertNever, _ as resolveConfig, a as AUTO_COMPACT_THRESHOLD_LIMITS, b as DEFAULT_CUSTOM_COMPRESSION_POLICY, c as DEFAULTS, d as charsForTokens, f as charsToTokens, g as parseContextCompressionSettings, h as isValidAutoCompactThresholdPercent, i as recordScore, m as isCompressionProfile, n as invalidateOnTaskChange, o as CONTEXT_COMPRESSION_SETTINGS_NAMESPACE, p as codePointLength, r as recordRecertified, s as ContextCompressionSettingsSchema, t as getAdvisorState, u as PRUNE_MARKER, v as resolvePolicy, w as COMPRESSION_PROFILES, x as resolveCustomPolicy, y as CustomCompressionPolicySchema } from "./advisor-state.js";
1
+ import { 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";
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 ? marker : "";
442
+ const insertion = intersectsRemoved && !markerInserted && typeof marker === "function" ? marker(1 + newlinesBefore + headText.split("\n").length - 1) : intersectsRemoved && !markerInserted && typeof marker === "string" ? 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") for (const path of extractSpillPaths(block.text)) spillFiles.add(path);
1182
+ for (const block of content) if (block.type === "text" && typeof block.text === "string") 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(input.argumentsText);
1400
+ const command = extractCommand$1(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(argumentsText) {
2683
+ function extractCommand$1(argumentsText) {
2684
2684
  try {
2685
2685
  const parsed = JSON.parse(argumentsText);
2686
2686
  if (typeof parsed !== "object" || parsed === null) return "";
@@ -3248,6 +3248,42 @@ 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
+ }
3251
3287
  //#endregion
3252
3288
  //#region src/runtime/tokenpilot/advisor.ts
3253
3289
  /** Character cap for the recent-text fallback and the tail-text summary input. */
@@ -3549,6 +3585,162 @@ async function runSessionAdvisorPass(session, channel, emit, input) {
3549
3585
  }
3550
3586
  }
3551
3587
  //#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
3552
3744
  //#region src/runtime/tokenpilot/dedup.ts
3553
3745
  /**
3554
3746
  * TokenPilot-inspired A1: byte-identical repeated tool-result dedup.
@@ -4040,7 +4232,10 @@ var ToolResultPruner = class extends Service {
4040
4232
  policyResolutionAudits: /* @__PURE__ */ new WeakMap(),
4041
4233
  turnClocks: /* @__PURE__ */ new WeakMap(),
4042
4234
  estimatorRemainingTurns: /* @__PURE__ */ new WeakMap(),
4043
- advisorChannels: /* @__PURE__ */ new WeakMap()
4235
+ advisorChannels: /* @__PURE__ */ new WeakMap(),
4236
+ pendingIntentFolds: /* @__PURE__ */ new WeakMap(),
4237
+ intentFoldedSeqs: /* @__PURE__ */ new WeakMap(),
4238
+ intentBaselines: /* @__PURE__ */ new WeakMap()
4044
4239
  };
4045
4240
  ctx.on("session/event", (session, event) => {
4046
4241
  this.scanForSeededNativeSummary(session);
@@ -4084,6 +4279,7 @@ var ToolResultPruner = class extends Service {
4084
4279
  }
4085
4280
  this.postflightEstimatorPass(agent.session, signal).catch(() => void 0);
4086
4281
  this.postflightAdvisorPass(agent.session, turn, signal).catch(() => void 0);
4282
+ this.postflightIntentFoldPass(agent.session, turn, signal).catch(() => void 0);
4087
4283
  });
4088
4284
  }
4089
4285
  /**
@@ -4411,6 +4607,185 @@ var ToolResultPruner = class extends Service {
4411
4607
  else if (outcome !== void 0) advisorState.failures = void 0;
4412
4608
  }
4413
4609
  /**
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
+ /**
4414
4789
  * Monotonic per-session turn clock for advisory records. Bumped by the agent
4415
4790
  * loop payloads (`pre-step`); passes without a turn coordinate reuse the last
4416
4791
  * observed value.
@@ -5002,13 +5377,41 @@ var ToolResultPruner = class extends Service {
5002
5377
  const isUnsafe = (candidate) => {
5003
5378
  if (this.isRecoveryExempt(session, candidate)) return true;
5004
5379
  const result = candidate.event.data.message;
5005
- return onlyTextBlock(result.content)?.text.includes("[Old tool result content cleared from active context]") === true;
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;
5006
5383
  };
5007
5384
  const safe = candidates.filter((candidate) => !isUnsafe(candidate));
5008
5385
  const eligible = safe.filter((candidate) => !protectedSeqs.has(candidate.seq));
5009
5386
  if (eligible.length === 0) return safe.length === 0 ? { kind: "no-safe-candidates" } : { kind: "protected-working-set" };
5010
5387
  const planned = [];
5011
5388
  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
+ }
5012
5415
  const minReclaimChars = charsForTokens(policy.historyMinReclaimTokens);
5013
5416
  const microTarget = deadline === void 0 ? void 0 : Math.max(0, charsForTokens(deadline) - minReclaimChars);
5014
5417
  const required = Math.max(minReclaimChars, total - trigger, ...microTarget === void 0 ? [] : [charsForTokens(view.totalTokens) - microTarget]);
@@ -5329,7 +5732,6 @@ var ToolResultPruner = class extends Service {
5329
5732
  }
5330
5733
  land(session, plan) {
5331
5734
  const { candidate } = plan;
5332
- candidate.event.data.message;
5333
5735
  const message = freezeMessage({
5334
5736
  ...candidate.event.data.message,
5335
5737
  content: plan.content
@@ -1,49 +1,53 @@
1
- /** Browser-safe settings decoding shared by the client entry and node tests. */
2
-
3
- import {
4
- canonicalizeCustomPolicy,
5
- COMPRESSION_PROFILES,
6
- decodeAutoCompactSettings,
7
- decodeCodeSkeletonSettings,
8
- decodePresetOptionsSettings,
9
- isCustomCompressionPolicy,
10
- isPlainRecord,
11
- type CompressionProfile,
12
- type ContextCompressionSettings,
13
- } from '../profiles.ts'
14
-
15
- /**
16
- * Decode one stored context-compression settings document with exactly the
17
- * runtime schema's strictness: a plain object with only `profile`, `custom`,
18
- * `autoCompact`, and `codeSkeleton` keys, a supported profile, a valid Custom
19
- * document canonicalized to v3 exactly as the runtime resolver would, a
20
- * strictly-shaped autoCompact section (absent inherits the 80% default), and
21
- * a strictly-shaped codeSkeleton gate (absent inherits off). Anything else
22
- * decodes to `undefined` so the UI reports the document as unreadable instead
23
- * of silently disagreeing with the runtime.
24
- */
25
- export function decodeSettings(value: unknown): ContextCompressionSettings | undefined {
26
- if (!isPlainRecord(value)) return undefined
27
- const keys = Object.keys(value)
28
- if (keys.some(key => key !== 'profile' && key !== 'custom' && key !== 'autoCompact' && key !== 'codeSkeleton' && key !== 'presetOptions')) {
29
- return undefined
30
- }
31
- const profile = (value as { profile?: unknown }).profile
32
- const custom = (value as { custom?: unknown }).custom
33
- const autoCompact = decodeAutoCompactSettings((value as { autoCompact?: unknown }).autoCompact)
34
- const codeSkeleton = decodeCodeSkeletonSettings((value as { codeSkeleton?: unknown }).codeSkeleton)
35
- const presetOptions = decodePresetOptionsSettings((value as { presetOptions?: unknown }).presetOptions)
36
- return typeof profile === 'string'
37
- && (COMPRESSION_PROFILES as readonly string[]).includes(profile)
38
- && isCustomCompressionPolicy(custom)
39
- && autoCompact !== undefined
40
- && codeSkeleton !== undefined
41
- ? {
42
- profile: profile as CompressionProfile,
43
- custom: canonicalizeCustomPolicy(custom),
44
- autoCompact,
45
- codeSkeleton,
46
- ...presetOptions === undefined ? {} : { presetOptions },
47
- }
48
- : undefined
49
- }
1
+ /** Browser-safe settings decoding shared by the client entry and node tests. */
2
+
3
+ import {
4
+ canonicalizeCustomPolicy,
5
+ COMPRESSION_PROFILES,
6
+ decodeAutoCompactSettings,
7
+ decodeCodeSkeletonSettings,
8
+ decodeIntentSummarySettings,
9
+ decodePresetOptionsSettings,
10
+ isCustomCompressionPolicy,
11
+ isPlainRecord,
12
+ type CompressionProfile,
13
+ type ContextCompressionSettings,
14
+ } from '../profiles.ts'
15
+
16
+ /**
17
+ * Decode one stored context-compression settings document with exactly the
18
+ * runtime schema's strictness: a plain object with only `profile`, `custom`,
19
+ * `autoCompact`, `codeSkeleton`, and `intentSummary` keys, a supported profile, a valid Custom
20
+ * document canonicalized to v3 exactly as the runtime resolver would, a
21
+ * strictly-shaped autoCompact section (absent inherits the 80% default), and
22
+ * a strictly-shaped codeSkeleton gate (absent inherits off). Anything else
23
+ * decodes to `undefined` so the UI reports the document as unreadable instead
24
+ * of silently disagreeing with the runtime.
25
+ */
26
+ export function decodeSettings(value: unknown): ContextCompressionSettings | undefined {
27
+ if (!isPlainRecord(value)) return undefined
28
+ const keys = Object.keys(value)
29
+ if (keys.some(key => key !== 'profile' && key !== 'custom' && key !== 'autoCompact' && key !== 'codeSkeleton' && key !== 'intentSummary' && key !== 'presetOptions')) {
30
+ return undefined
31
+ }
32
+ const profile = (value as { profile?: unknown }).profile
33
+ const custom = (value as { custom?: unknown }).custom
34
+ const autoCompact = decodeAutoCompactSettings((value as { autoCompact?: unknown }).autoCompact)
35
+ const codeSkeleton = decodeCodeSkeletonSettings((value as { codeSkeleton?: unknown }).codeSkeleton)
36
+ const intentSummary = decodeIntentSummarySettings((value as { intentSummary?: unknown }).intentSummary)
37
+ const presetOptions = decodePresetOptionsSettings((value as { presetOptions?: unknown }).presetOptions)
38
+ return typeof profile === 'string'
39
+ && (COMPRESSION_PROFILES as readonly string[]).includes(profile)
40
+ && isCustomCompressionPolicy(custom)
41
+ && autoCompact !== undefined
42
+ && codeSkeleton !== undefined
43
+ && intentSummary !== undefined
44
+ ? {
45
+ profile: profile as CompressionProfile,
46
+ custom: canonicalizeCustomPolicy(custom),
47
+ autoCompact,
48
+ codeSkeleton,
49
+ intentSummary,
50
+ ...presetOptions === undefined ? {} : { presetOptions },
51
+ }
52
+ : undefined
53
+ }
@@ -11,6 +11,13 @@ import {
11
11
  import { DEFAULT_CUSTOM_COMPRESSION_POLICY } from '../profiles.ts'
12
12
  import { decodeSettings } from './decode.ts'
13
13
  import { en, zh } from './locales.ts'
14
+ import { de } from './locales/de.ts'
15
+ import { es } from './locales/es.ts'
16
+ import { fr } from './locales/fr.ts'
17
+ import { it } from './locales/it.ts'
18
+ import { ja } from './locales/ja.ts'
19
+ import { ko } from './locales/ko.ts'
20
+ import { ru } from './locales/ru.ts'
14
21
  import { planPresetOptionsOps, presetOptionsOpsAccepted } from './preset-options.ts'
15
22
  import type { ScopeSnapshot, SettingsScope } from './scope-face.ts'
16
23
 
@@ -69,6 +76,29 @@ function sameCustomPolicy(
69
76
 
70
77
  export function apply(ctx: ClientContext): void {
71
78
  ctx.locale.register(NS, { zh, en })
79
+ // de/es/fr/it/ja/ko/ru are not host built-ins (`BuiltInLocaleId` is zh|en), so
80
+ // their dictionaries ride the single-locale untyped register overload, and each
81
+ // needs an `addLanguage` definition to become selectable — the catalog owns
82
+ // setLocale and the Language settings row, and a definition's fallback chain
83
+ // must end at English. Labels are self-described in their own language. One
84
+ // occupied locale must not sink activation, hence the per-language guard.
85
+ const languages = [
86
+ { id: 'de', label: 'Deutsch', dict: de },
87
+ { id: 'es', label: 'Español', dict: es },
88
+ { id: 'fr', label: 'Français', dict: fr },
89
+ { id: 'it', label: 'Italiano', dict: it },
90
+ { id: 'ja', label: '日本語', dict: ja },
91
+ { id: 'ko', label: '한국어', dict: ko },
92
+ { id: 'ru', label: 'Русский', dict: ru },
93
+ ] as const
94
+ for (const language of languages) {
95
+ try {
96
+ ctx.locale.register(NS, language.id, language.dict)
97
+ ctx.locale.addLanguage({ id: language.id, label: language.label, fallback: 'en' })
98
+ } catch (error) {
99
+ console.warn(`[dsh-context-compression-improved] locale "${language.id}" registration failed:`, error)
100
+ }
101
+ }
72
102
  // Section label translator, captured EAGERLY: the settings shell evaluates
73
103
  // `label()` during its own render; a lazy ctx.locale accessor inside the
74
104
  // thunk would throw there if `locale` ever left this module's inject list