dsh-context-compression-improved 0.8.0-beta.3 → 0.8.0-beta.5

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 (58) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/eslint.config.js +30 -30
  3. package/package.json +163 -163
  4. package/packages/selector/dsh.plugin.json +16 -16
  5. package/packages/selector/lib/client.d.ts +28 -0
  6. package/packages/selector/lib/client.js +631 -7
  7. package/packages/selector/lib/{advisor-state.js → config.js} +170 -65
  8. package/packages/selector/lib/index.d.ts +13 -1
  9. package/packages/selector/lib/index.js +306 -50
  10. package/packages/selector/lib/profiles.d.ts +15 -0
  11. package/packages/selector/lib/pruner.d.ts +65 -0
  12. package/packages/selector/lib/pruner.js +408 -5
  13. package/packages/selector/src/client/CompressionProfileControls.tsx +67 -0
  14. package/packages/selector/src/client/CompressionProfileSelector.tsx +2 -0
  15. package/packages/selector/src/client/decode.ts +57 -49
  16. package/packages/selector/src/client/index.ts +41 -0
  17. package/packages/selector/src/client/locales/de.ts +26 -0
  18. package/packages/selector/src/client/locales/es.ts +26 -0
  19. package/packages/selector/src/client/locales/fr.ts +26 -0
  20. package/packages/selector/src/client/locales/it.ts +26 -0
  21. package/packages/selector/src/client/locales/ja.ts +26 -0
  22. package/packages/selector/src/client/locales/ko.ts +26 -0
  23. package/packages/selector/src/client/locales/ru.ts +26 -0
  24. package/packages/selector/src/client/locales.ts +52 -0
  25. package/packages/selector/src/client/monitor-fab.ts +307 -0
  26. package/packages/selector/src/client/settings-section.tsx +16 -2
  27. package/packages/selector/src/index.ts +133 -60
  28. package/packages/selector/src/profiles.ts +431 -394
  29. package/packages/selector/src/pruner/state.ts +57 -50
  30. package/packages/selector/src/pruner.ts +241 -1
  31. package/packages/selector/src/runtime/audit.ts +303 -286
  32. package/packages/selector/src/runtime/config.ts +756 -706
  33. package/packages/selector/src/runtime/monitor.ts +149 -0
  34. package/packages/selector/src/runtime/summary-command.ts +127 -0
  35. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -188
  36. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -149
  37. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
  38. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
  39. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
  40. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
  41. package/packages/selector/src/runtime/types.ts +365 -346
  42. package/packages/selector/tests/auto-compact.client.spec.tsx +214 -213
  43. package/packages/selector/tests/code-skeleton.client.spec.ts +94 -93
  44. package/packages/selector/tests/custom-contract.client.spec.ts +223 -222
  45. package/packages/selector/tests/estimator-channel.client.spec.tsx +253 -252
  46. package/packages/selector/tests/estimator-route-registration.host.spec.ts +8 -6
  47. package/packages/selector/tests/monitor-fab.client.spec.ts +117 -0
  48. package/packages/selector/tests/preset-options-write.client.spec.ts +188 -187
  49. package/packages/selector/tests/profiles.client.spec.tsx +436 -434
  50. package/packages/selector/tests/runtime/audit.spec.ts +275 -274
  51. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
  52. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
  53. package/packages/selector/tests/runtime/monitor.spec.ts +236 -0
  54. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2734 -2731
  55. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
  56. package/packages/selector/tests/settings-seat.client.spec.ts +1 -1
  57. package/scripts/packed-install-e2e.mjs +1 -1
  58. package/scripts/verify-release.mjs +2 -1
@@ -1,4 +1,4 @@
1
- import { C as deepFreeze, D as priceOfficialDeepSeekUsage, E as decimalRateNanoUnits, O as resolveOfficialDeepSeekPrice, S as assertNever, T as DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION, _ 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, k as getSavingsLedger, 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 recordIntentFold, C as evaluateIntentGate, D as getSummaryOverride, F as decimalRateNanoUnits, I as priceOfficialDeepSeekUsage, L as resolveOfficialDeepSeekPrice, M as recordScore, O as invalidateOnTaskChange, P as DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION, R as getSavingsLedger, _ as resolveCustomPolicy, b as COMPRESSION_PROFILES, c as charsToTokens, d as isValidAutoCompactThresholdPercent, f as parseContextCompressionSettings, g as DEFAULT_CUSTOM_COMPRESSION_POLICY, h as CustomCompressionPolicySchema, i as DEFAULTS, j as recordRecertified, k as observeIntentEnabled, l as codePointLength, m as resolvePolicy, n as CONTEXT_COMPRESSION_SETTINGS_NAMESPACE, o as PRUNE_MARKER, p as resolveConfig, r as ContextCompressionSettingsSchema, s as charsForTokens, t as AUTO_COMPACT_THRESHOLD_LIMITS, u as isCompressionProfile, v as assertNever, w as getAdvisorState, y as deepFreeze } 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";
@@ -1420,7 +1420,7 @@ function reduceFreshToolResult(input, ranking) {
1420
1420
  lines: normalized.folded,
1421
1421
  contentText: normalized.contentText
1422
1422
  };
1423
- const command = extractCommand(input.argumentsText);
1423
+ const command = extractCommand$1(input.argumentsText);
1424
1424
  const name = input.toolName.toLowerCase();
1425
1425
  const toolClass = classifyToolSource(input.toolName, command, normalized.contentText);
1426
1426
  const readTocFirst = toolClass === "read" && codePointLength(normalized.contentText) >= READ_TOC_MIN_CHARS;
@@ -2703,7 +2703,7 @@ function splitLines(text) {
2703
2703
  * @param argumentsText - raw JSON arguments of the tool call.
2704
2704
  * @returns the command string, or '' when absent.
2705
2705
  */
2706
- function extractCommand(argumentsText) {
2706
+ function extractCommand$1(argumentsText) {
2707
2707
  try {
2708
2708
  const parsed = JSON.parse(argumentsText);
2709
2709
  if (typeof parsed !== "object" || parsed === null) return "";
@@ -3271,6 +3271,42 @@ function parseAdvisorScores(text, validSeqs) {
3271
3271
  }
3272
3272
  return scores.size > 0 ? scores : void 0;
3273
3273
  }
3274
+ /** Hard character cap for one intent-summary answer (summary segment only). */
3275
+ const INTENT_SUMMARY_CHAR_CAP = 1600;
3276
+ /**
3277
+ * Intent-summary writer prompts (task_2.3). Input records are already
3278
+ * semantic-role-masked by intent-input-mask.ts: read-class candidates are
3279
+ * one-line "read X" records, keep-class candidates carry skeleton heads and
3280
+ * VERBATIM error lines. The model writes ONLY the summary segment — it never
3281
+ * revoices error lines, and its answer must stay inside the char cap.
3282
+ */
3283
+ function buildIntentSummarySystemPrompt() {
3284
+ return [
3285
+ "You write one concise intent summary of folded tool results for a coding agent session.",
3286
+ "Input: the session task (todolist) and per-tool slimmed records (read lines, or skeleton heads with verbatim error lines).",
3287
+ `Write ONLY what the agent DID and LEARNED in this span, as flowing prose under ${INTENT_SUMMARY_CHAR_CAP} characters.`,
3288
+ "Mention which files/areas were consulted and what changed, so a later turn can continue without the originals.",
3289
+ "Never invent files, commands, or outcomes absent from the records. Never revoice error lines; they are preserved verbatim elsewhere.",
3290
+ "Answer with ONLY one JSON object: {\"summary\":\"<prose>\"}. Never add commentary."
3291
+ ].join(" ");
3292
+ }
3293
+ function buildIntentSummaryUserPrompt(taskText, records, tailText) {
3294
+ const nl = String.fromCharCode(10);
3295
+ return [
3296
+ `task: ${taskText.replace(/\s+/gu, " ").slice(0, 600)}`,
3297
+ records.length > 0 ? `records:${nl}${records.join(nl)}` : "records: (none)",
3298
+ tailText.trim().length > 0 ? `recent tail:${nl}${tailText.trim().slice(0, 1200)}` : "recent tail: (none)"
3299
+ ].join("\n\n");
3300
+ }
3301
+ /** Fail-open parse of one intent-summary answer; `undefined` on any malformed shape. */
3302
+ function parseIntentSummaryAnswer(text) {
3303
+ const parsed = firstJsonObject(text);
3304
+ if (parsed === void 0) return void 0;
3305
+ const summary = parsed.summary;
3306
+ if (typeof summary !== "string" || summary.trim().length === 0) return void 0;
3307
+ if (summary.length > 3200) return void 0;
3308
+ return { summary: summary.trim().slice(0, INTENT_SUMMARY_CHAR_CAP) };
3309
+ }
3274
3310
  //#endregion
3275
3311
  //#region src/runtime/tokenpilot/advisor.ts
3276
3312
  /** Character cap for the recent-text fallback and the tail-text summary input. */
@@ -3572,6 +3608,162 @@ async function runSessionAdvisorPass(session, channel, emit, input) {
3572
3608
  }
3573
3609
  }
3574
3610
  //#endregion
3611
+ //#region src/runtime/tokenpilot/intent-input-mask.ts
3612
+ /**
3613
+ * Semantic-role input masking for the intent-summary writer (task_2.2).
3614
+ *
3615
+ * The intent summary records historical TASK semantics — for read-class tools
3616
+ * the semantics are "read X", never the file body, so the body is masked to a
3617
+ * one-line record before it can reach the summary prompt. Write-class results
3618
+ * (edits) ARE task semantics and keep their skeleton + verbatim error lines.
3619
+ *
3620
+ * Classification REUSES `classifyToolSource()` (reducers.ts routes on the
3621
+ * same classes): hand-rolling a name→role map here would regress its fixed
3622
+ * misclassification edges (mcp→generic, web_search/memory_search not being
3623
+ * content search, glob being path-listing, execute_sql not being shell).
3624
+ * Only the write class is layered on top — `ToolClass` has no write member.
3625
+ */
3626
+ /** Exact-token write layer, same tokenization discipline as toolclass. */
3627
+ const WRITE_NAMES = /* @__PURE__ */ new Set([
3628
+ "apply_patch",
3629
+ "multi_edit",
3630
+ "create_file",
3631
+ "write_to_file",
3632
+ "str_replace_editor"
3633
+ ]);
3634
+ const WRITE_TOKENS = /* @__PURE__ */ new Set([
3635
+ "write",
3636
+ "edit",
3637
+ "patch"
3638
+ ]);
3639
+ function hasWriteToken(name) {
3640
+ const lowered = name.toLowerCase();
3641
+ if (WRITE_NAMES.has(lowered)) return true;
3642
+ return lowered.split(/[-_/]+/).some((token) => WRITE_TOKENS.has(token));
3643
+ }
3644
+ /**
3645
+ * Role for one candidate. The write layer is consulted first; everything
3646
+ * else defers to the shared classifier. `shell`/`generic` stay conservative
3647
+ * (skeleton + error lines, never a blind mask) — a bash result can be a
3648
+ * mutation even when its name says nothing.
3649
+ */
3650
+ function classifyIntentRole(toolName, command, text) {
3651
+ if (hasWriteToken(toolName)) return "write-keep";
3652
+ const toolClass = classifyToolSource(toolName, command, text);
3653
+ if (toolClass === "read" || toolClass === "search" || toolClass === "path-listing") return "read-mask";
3654
+ return "conservative";
3655
+ }
3656
+ const ERROR_LINE_PATTERN = /\b(error|failed|failure|exception|panic|fatal|traceback|unreachable|denied)\b/i;
3657
+ const KEEP_HEAD_LINES = 40;
3658
+ const KEEP_HEAD_CHARS = 2e3;
3659
+ /** Verbatim error/warn lines kept out of the LLM's hands and into the intent block. */
3660
+ function extractErrorLines(text) {
3661
+ return text.split("\n").filter((line) => ERROR_LINE_PATTERN.test(line)).slice(0, 10);
3662
+ }
3663
+ /** Count lines and code points for the read-mask record tail. */
3664
+ function scaleOf(text) {
3665
+ return {
3666
+ lines: text.length === 0 ? 0 : text.split("\n").length,
3667
+ chars: text.length
3668
+ };
3669
+ }
3670
+ /**
3671
+ * Build the prompt face for one candidate. Read-mask output contains NONE of
3672
+ * the original body — only the tool name, the call's target argument, and
3673
+ * the dropped scale — so a hostile body can never leak into the summary.
3674
+ */
3675
+ function maskCandidateForSummary(seq, toolName, argumentsText, text) {
3676
+ const role = classifyIntentRole(toolName, extractCommand(argumentsText), text);
3677
+ if (role === "read-mask") {
3678
+ const { lines, chars } = scaleOf(text);
3679
+ return {
3680
+ seq,
3681
+ role,
3682
+ record: `${toolName} ${extractTarget(argumentsText)} -> masked (${lines} lines / ${chars} chars)`
3683
+ };
3684
+ }
3685
+ const head = text.split("\n", KEEP_HEAD_LINES).join("\n").slice(0, KEEP_HEAD_CHARS);
3686
+ const errorLines = extractErrorLines(text);
3687
+ return {
3688
+ seq,
3689
+ role,
3690
+ record: `${toolName} (seq ${seq})\n${head}${errorLines.length > 0 ? `\nerror lines (verbatim):\n${errorLines.join("\n")}` : ""}`
3691
+ };
3692
+ }
3693
+ /** Extract a short command head from a tool-call arguments JSON string. */
3694
+ function extractCommand(argumentsText) {
3695
+ try {
3696
+ const parsed = JSON.parse(argumentsText);
3697
+ if (parsed !== null && typeof parsed === "object") {
3698
+ const command = parsed.command;
3699
+ if (typeof command === "string") return command.slice(0, 200);
3700
+ }
3701
+ } catch {}
3702
+ return "";
3703
+ }
3704
+ /** Extract the most target-like string argument (path/query/url) for read-mask records. */
3705
+ function extractTarget(argumentsText) {
3706
+ try {
3707
+ const parsed = JSON.parse(argumentsText);
3708
+ if (parsed !== null && typeof parsed === "object") {
3709
+ const record = parsed;
3710
+ const target = [
3711
+ record.path,
3712
+ record.file_path,
3713
+ record.query,
3714
+ record.url,
3715
+ record.pattern,
3716
+ record.glob
3717
+ ].find((candidate) => typeof candidate === "string" && candidate.trim().length > 0);
3718
+ if (typeof target === "string") return target.slice(0, 160);
3719
+ const first = Object.values(record).find((value) => typeof value === "string");
3720
+ if (typeof first === "string") return first.slice(0, 160);
3721
+ }
3722
+ } catch {}
3723
+ return "(unparsed target)";
3724
+ }
3725
+ //#endregion
3726
+ //#region src/runtime/tokenpilot/intent-range.ts
3727
+ /**
3728
+ * Oldest-first selection of foldable candidates. Excludes the protected
3729
+ * working set and already-folded seqs; caps the batch size.
3730
+ */
3731
+ function computeIntentRange(input) {
3732
+ const unprotected = input.candidates.filter((candidate) => !input.protectedSeqs.has(candidate.seq));
3733
+ const skippedProtected = input.candidates.length - unprotected.length;
3734
+ const eligible = unprotected.filter((candidate) => !input.foldedSeqs.has(candidate.seq));
3735
+ const skippedFolded = unprotected.length - eligible.length;
3736
+ return {
3737
+ seqs: [...eligible].sort((a, b) => a.seq - b.seq).slice(0, Math.max(0, input.maxCandidates)).map((candidate) => candidate.seq),
3738
+ skippedProtected,
3739
+ skippedFolded
3740
+ };
3741
+ }
3742
+ //#endregion
3743
+ //#region src/runtime/tokenpilot/intent-fold.ts
3744
+ /** Marker written into every folded block; its presence makes a seq unfoldable again (fold-once). */
3745
+ const INTENT_FOLD_MARKER = "[Intent summary";
3746
+ /** Render the replacement text for one folded candidate. Pure. */
3747
+ function renderIntentFoldBlock(pending, seq) {
3748
+ const start = pending.startSeq;
3749
+ const end = pending.endSeq;
3750
+ if (seq === start) {
3751
+ const readLines = pending.records.filter((record) => record.role === "read-mask").map((record) => record.line);
3752
+ const consulted = readLines.length > 0 ? `Consulted: ${readLines.join("; ")}` : "";
3753
+ const errorBlock = pending.errorLines.length > 0 ? `\nError lines (verbatim):\n${pending.errorLines.join("\n")}` : "";
3754
+ return [
3755
+ `${INTENT_FOLD_MARKER} of folded tool results seq ${start}..${end}]`,
3756
+ pending.summary,
3757
+ consulted,
3758
+ errorBlock,
3759
+ "[Original content remains in the session log at the listed seq values.]"
3760
+ ].filter((part) => part.length > 0).join("\n");
3761
+ }
3762
+ const record = pending.records.find((entry) => entry.seq === seq);
3763
+ const face = record === void 0 ? `${seq}` : record.role === "read-mask" ? record.line : `${record.toolName} result folded into the batch intent summary`;
3764
+ return `${INTENT_FOLD_MARKER} folded into the batch summary above (seq ${start}..${end})] ${face}`;
3765
+ }
3766
+ //#endregion
3575
3767
  //#region src/runtime/tokenpilot/dedup.ts
3576
3768
  /**
3577
3769
  * TokenPilot-inspired A1: byte-identical repeated tool-result dedup.
@@ -3819,7 +4011,10 @@ var ToolResultPruner = class extends Service {
3819
4011
  policyResolutionAudits: /* @__PURE__ */ new WeakMap(),
3820
4012
  turnClocks: /* @__PURE__ */ new WeakMap(),
3821
4013
  estimatorRemainingTurns: /* @__PURE__ */ new WeakMap(),
3822
- advisorChannels: /* @__PURE__ */ new WeakMap()
4014
+ advisorChannels: /* @__PURE__ */ new WeakMap(),
4015
+ pendingIntentFolds: /* @__PURE__ */ new WeakMap(),
4016
+ intentFoldedSeqs: /* @__PURE__ */ new WeakMap(),
4017
+ intentBaselines: /* @__PURE__ */ new WeakMap()
3823
4018
  };
3824
4019
  try {
3825
4020
  ctx.on("session/disposed", (session) => {
@@ -3871,6 +4066,7 @@ var ToolResultPruner = class extends Service {
3871
4066
  }
3872
4067
  this.postflightEstimatorPass(agent.session, signal).catch(() => void 0);
3873
4068
  this.postflightAdvisorPass(agent.session, turn, signal).catch(() => void 0);
4069
+ this.postflightIntentFoldPass(agent.session, turn, signal).catch(() => void 0);
3874
4070
  });
3875
4071
  }
3876
4072
  /**
@@ -4202,6 +4398,185 @@ var ToolResultPruner = class extends Service {
4202
4398
  else if (outcome !== void 0) advisorState.failures = void 0;
4203
4399
  }
4204
4400
  /**
4401
+ * Fire-and-forget postflight: evaluate the growth gate, and only when it
4402
+ * passes, select the consumed increment OUTSIDE the protected working set,
4403
+ * mask it to semantic-role records, and spend ONE summary-writer call. The
4404
+ * verdict stages as a pending fold that the NEXT pressure round lands via
4405
+ * the ordinary plan/apply machinery — the synchronous decision path never
4406
+ * waits on an LLM.
4407
+ */
4408
+ async postflightIntentFoldPass(session, turn, signal) {
4409
+ const started = Date.now();
4410
+ const sessionId = String(session.id);
4411
+ const policy = this.activePolicy(session);
4412
+ const settings = this.activeSettings(session);
4413
+ const intentEnabled = settings.intentSummary.enabled;
4414
+ const override = getSummaryOverride(sessionId);
4415
+ observeIntentEnabled(sessionId, intentEnabled);
4416
+ if (policy === void 0) return;
4417
+ if (this.state.pendingIntentFolds.has(session)) return;
4418
+ const advisorState = getAdvisorState(session);
4419
+ if (advisorState.inFlight) return;
4420
+ if (isCoolingDown(advisorState.failures, Date.now())) return;
4421
+ const view = measureForCompaction(this.ctx, session);
4422
+ const thresholdPercent = settings.autoCompact.thresholdPercent;
4423
+ const contextWindow = policy.autoCompactTokens !== void 0 && thresholdPercent > 0 ? Math.round(policy.autoCompactTokens / (thresholdPercent / 100)) : void 0;
4424
+ if (!evaluateIntentGate({
4425
+ enabled: intentEnabled,
4426
+ override,
4427
+ liveTokens: view.totalTokens,
4428
+ contextWindow,
4429
+ baselineTokens: this.state.intentBaselines.get(session) ?? 0
4430
+ }).decision) return;
4431
+ const settingsPreset = settings.presetOptions;
4432
+ if (settingsPreset === void 0) return;
4433
+ if (settingsPreset.estimatorBaseUrl === void 0 || settingsPreset.estimatorBaseUrl.length === 0 || settingsPreset.estimatorModel === void 0 || settingsPreset.estimatorModel.length === 0) {
4434
+ emitCompressionAudit(this.ctx.logger, {
4435
+ schemaVersion: 1,
4436
+ kind: "intent-summary-outcome",
4437
+ sessionId,
4438
+ ok: false,
4439
+ reason: "no-direct-endpoint",
4440
+ turnIndex: turn,
4441
+ latencyMs: Date.now() - started
4442
+ });
4443
+ return;
4444
+ }
4445
+ const candidates = this.snapshot(session, view).filter((candidate) => !this.isRecoveryExempt(session, candidate));
4446
+ const range = computeIntentRange({
4447
+ candidates,
4448
+ protectedSeqs: this.protectedHistoryCandidateSeqs(candidates, policy),
4449
+ foldedSeqs: this.state.intentFoldedSeqs.get(session) ?? /* @__PURE__ */ new Set(),
4450
+ maxCandidates: 20
4451
+ });
4452
+ if (range.seqs.length === 0) return;
4453
+ const bySeq = new Map(candidates.map((candidate) => [candidate.seq, candidate]));
4454
+ const records = [];
4455
+ const errorLines = /* @__PURE__ */ new Set();
4456
+ for (const seq of range.seqs) {
4457
+ const candidate = bySeq.get(seq);
4458
+ if (candidate === void 0) continue;
4459
+ const result = candidate.event.data.message;
4460
+ const text = onlyTextBlock(result.content)?.text ?? "";
4461
+ const masked = maskCandidateForSummary(seq, candidate.call.name, candidate.call.arguments, text);
4462
+ records.push({
4463
+ seq,
4464
+ role: masked.role,
4465
+ toolName: candidate.call.name,
4466
+ line: masked.record
4467
+ });
4468
+ for (const line of extractErrorLines(text)) errorLines.add(line);
4469
+ }
4470
+ if (records.length === 0) return;
4471
+ const events = sessionEvents(session);
4472
+ const task = collectTaskSemantics(events);
4473
+ let channel = this.state.advisorChannels.get(session);
4474
+ if (channel === void 0) {
4475
+ channel = new SideChannel(this.ctx, settingsPreset, {
4476
+ mode: "direct",
4477
+ timeoutMs: 3e4,
4478
+ maxTokens: 512
4479
+ });
4480
+ this.state.advisorChannels.set(session, channel);
4481
+ }
4482
+ const answer = await channel.ask({
4483
+ system: buildIntentSummarySystemPrompt(),
4484
+ user: buildIntentSummaryUserPrompt(task?.taskText ?? "(no task semantics yet)", records.map((record) => record.line), collectTailText(events)),
4485
+ signal
4486
+ });
4487
+ const summaryCallChars = answer?.length ?? 0;
4488
+ const parsed = answer === void 0 ? void 0 : parseIntentSummaryAnswer(answer);
4489
+ if (parsed === void 0) {
4490
+ const failures = (advisorState.failures?.failures ?? 0) + 1;
4491
+ advisorState.failures = {
4492
+ failures,
4493
+ cooldownUntil: Date.now() + backoffCooldownMs(failures)
4494
+ };
4495
+ emitCompressionAudit(this.ctx.logger, {
4496
+ schemaVersion: 1,
4497
+ kind: "intent-summary-outcome",
4498
+ sessionId,
4499
+ ok: false,
4500
+ reason: answer === void 0 ? "ask-failed" : "parse-failed",
4501
+ turnIndex: turn,
4502
+ foldedCount: records.length,
4503
+ summaryCallChars,
4504
+ latencyMs: Date.now() - started
4505
+ });
4506
+ return;
4507
+ }
4508
+ this.state.pendingIntentFolds.set(session, {
4509
+ createdAt: Date.now(),
4510
+ turn,
4511
+ startSeq: range.seqs[0],
4512
+ endSeq: range.seqs[range.seqs.length - 1],
4513
+ summary: parsed.summary,
4514
+ errorLines: [...errorLines],
4515
+ records,
4516
+ summaryCallChars
4517
+ });
4518
+ emitCompressionAudit(this.ctx.logger, {
4519
+ schemaVersion: 1,
4520
+ kind: "intent-summary-outcome",
4521
+ sessionId,
4522
+ ok: true,
4523
+ reason: "staged",
4524
+ turnIndex: turn,
4525
+ foldedCount: records.length,
4526
+ summaryCallChars,
4527
+ latencyMs: Date.now() - started
4528
+ });
4529
+ }
4530
+ /**
4531
+ * Convert a staged pending fold into per-candidate planned replacements
4532
+ * (reducer `intent-summary`). Fail-open: a candidate that would grow, is
4533
+ * rich-content, or no longer exists keeps its original text. Returns
4534
+ * `undefined` when there is nothing (or no longer anything) to fold.
4535
+ */
4536
+ applyPendingIntentFold(session, policy, view, eligible) {
4537
+ const pending = this.state.pendingIntentFolds.get(session);
4538
+ if (pending === void 0) return void 0;
4539
+ const bySeq = new Map(eligible.map((candidate) => [candidate.seq, candidate]));
4540
+ const foldable = pending.records.map((record) => record.seq).filter((seq) => bySeq.has(seq)).sort((a, b) => a - b);
4541
+ if (foldable.length === 0) {
4542
+ this.state.pendingIntentFolds.delete(session);
4543
+ return;
4544
+ }
4545
+ const plans = [];
4546
+ const foldedSeqs = /* @__PURE__ */ new Set();
4547
+ let reclaim = 0;
4548
+ let charsBefore = 0;
4549
+ let charsAfter = 0;
4550
+ for (const seq of foldable) {
4551
+ const candidate = bySeq.get(seq);
4552
+ const result = candidate.event.data.message;
4553
+ const block = onlyTextBlock(result.content);
4554
+ if (block === null) continue;
4555
+ const text = renderIntentFoldBlock(pending, seq);
4556
+ const plan = this.plan(candidate, [{
4557
+ ...block,
4558
+ text
4559
+ }], rootToolResultSeq(session, candidate.seq), "intent-summary", "pressure", "history", policy.historyMode, view);
4560
+ if (plan === null || plan.charsAfter >= plan.charsBefore) continue;
4561
+ plans.push(plan);
4562
+ foldedSeqs.add(seq);
4563
+ reclaim += plan.charsBefore - plan.charsAfter;
4564
+ charsBefore += plan.charsBefore;
4565
+ charsAfter += plan.charsAfter;
4566
+ }
4567
+ if (plans.length === 0) return void 0;
4568
+ this.state.intentFoldedSeqs.get(session)?.forEach((seq) => foldedSeqs.add(seq));
4569
+ return {
4570
+ plans,
4571
+ reclaim,
4572
+ foldedSeqs,
4573
+ charsBefore,
4574
+ charsAfter,
4575
+ turn: pending.turn,
4576
+ summaryCallChars: pending.summaryCallChars
4577
+ };
4578
+ }
4579
+ /**
4205
4580
  * Monotonic per-session turn clock for advisory records. Bumped by the agent
4206
4581
  * loop payloads (`pre-step`); passes without a turn coordinate reuse the last
4207
4582
  * observed value.
@@ -4811,13 +5186,41 @@ var ToolResultPruner = class extends Service {
4811
5186
  const isUnsafe = (candidate) => {
4812
5187
  if (this.isRecoveryExempt(session, candidate)) return true;
4813
5188
  const result = candidate.event.data.message;
4814
- return onlyTextBlock(result.content)?.text.includes("[Old tool result content cleared from active context]") === true;
5189
+ const block = onlyTextBlock(result.content);
5190
+ if (block?.text.includes("[Intent summary") === true) return true;
5191
+ return block?.text.includes("[Old tool result content cleared from active context]") === true;
4815
5192
  };
4816
5193
  const safe = candidates.filter((candidate) => !isUnsafe(candidate));
4817
5194
  const eligible = safe.filter((candidate) => !protectedSeqs.has(candidate.seq));
4818
5195
  if (eligible.length === 0) return safe.length === 0 ? { kind: "no-safe-candidates" } : { kind: "protected-working-set" };
4819
5196
  const planned = [];
4820
5197
  let reclaim = 0;
5198
+ const intentApplied = this.applyPendingIntentFold(session, policy, view, eligible);
5199
+ if (intentApplied !== void 0) {
5200
+ planned.push(...intentApplied.plans);
5201
+ reclaim += intentApplied.reclaim;
5202
+ this.state.intentFoldedSeqs.set(session, intentApplied.foldedSeqs);
5203
+ this.state.pendingIntentFolds.delete(session);
5204
+ this.state.intentBaselines.set(session, view.totalTokens);
5205
+ recordIntentFold(String(session.id), {
5206
+ turn: intentApplied.turn,
5207
+ startSeq: intentApplied.foldedSeqs.size > 0 ? Math.min(...intentApplied.foldedSeqs) : 0,
5208
+ endSeq: intentApplied.foldedSeqs.size > 0 ? Math.max(...intentApplied.foldedSeqs) : 0,
5209
+ liveTokensBefore: view.totalTokens,
5210
+ at: Date.now()
5211
+ });
5212
+ emitCompressionAudit(this.ctx.logger, {
5213
+ schemaVersion: 1,
5214
+ kind: "intent-summary-outcome",
5215
+ sessionId: String(session.id),
5216
+ ok: true,
5217
+ reason: "landed",
5218
+ foldedCount: intentApplied.plans.length,
5219
+ ...intentApplied.charsBefore > 0 ? { retentionRatio: intentApplied.charsAfter / intentApplied.charsBefore } : {},
5220
+ summaryCallChars: intentApplied.summaryCallChars
5221
+ });
5222
+ for (let index = eligible.length - 1; index >= 0; index -= 1) if (intentApplied.foldedSeqs.has(eligible[index].seq)) eligible.splice(index, 1);
5223
+ }
4821
5224
  const minReclaimChars = charsForTokens(policy.historyMinReclaimTokens);
4822
5225
  const microTarget = deadline === void 0 ? void 0 : Math.max(0, charsForTokens(deadline) - minReclaimChars);
4823
5226
  const required = Math.max(minReclaimChars, total - trigger, ...microTarget === void 0 ? [] : [charsForTokens(view.totalTokens) - microTarget]);
@@ -205,6 +205,73 @@ interface CodeSkeletonControlsProps {
205
205
  * section. Deliberately minimal — an on/off select plus its own save path —
206
206
  * because the gate is orthogonal to every profile and carries no parameters.
207
207
  */
208
+ interface IntentSummaryControlsProps {
209
+ value: boolean
210
+ disabled: boolean
211
+ save: (enabled: boolean) => Promise<void>
212
+ settle: (operation: () => Promise<void>) => void
213
+ t: (key: ContextCompressionLocaleKey) => string
214
+ }
215
+
216
+ /**
217
+ * The turn-tail intent summary fold gate. Same deliberately minimal shape as
218
+ * the code-skeleton gate: an on/off select with its own save path; the fold
219
+ * itself is gated by the growth constants and the per-session /ctx-summary
220
+ * override, none of which belong in this card.
221
+ */
222
+ export function IntentSummaryControls({ value, disabled, save, settle, t }: IntentSummaryControlsProps) {
223
+ return (
224
+ <section className={css.autoCompact} aria-labelledby="context-compression-intentsummary-title">
225
+ <h3 id="context-compression-intentsummary-title" className={css.autoCompactTitle}>{t('intentSummary.title')}</h3>
226
+ <p className={css.customNote}>{t('intentSummary.description')}</p>
227
+ <label className={css.field}>
228
+ <span>{t('intentSummary.enabled')}</span>
229
+ <select
230
+ value={value ? 'on' : 'off'}
231
+ disabled={disabled}
232
+ onChange={(event) => { settle(() => save(event.currentTarget.value === 'on')) }}
233
+ >
234
+ <option value="on">{t('intentSummary.enabled.on')}</option>
235
+ <option value="off">{t('intentSummary.enabled.off')}</option>
236
+ </select>
237
+ </label>
238
+ </section>
239
+ )
240
+ }
241
+
242
+ interface MonitorPanelControlsProps {
243
+ value: boolean
244
+ disabled: boolean
245
+ save: (enabled: boolean) => Promise<void>
246
+ settle: (operation: () => Promise<void>) => void
247
+ t: (key: ContextCompressionLocaleKey) => string
248
+ }
249
+
250
+ /**
251
+ * Visibility switch of the floating compression-monitor panel (FAB). The
252
+ * panel itself is a body-level overlay driven by the monitor route; this card
253
+ * only decides whether it mounts.
254
+ */
255
+ export function MonitorPanelControls({ value, disabled, save, settle, t }: MonitorPanelControlsProps) {
256
+ return (
257
+ <section className={css.autoCompact} aria-labelledby="context-compression-monitorpanel-title">
258
+ <h3 id="context-compression-monitorpanel-title" className={css.autoCompactTitle}>{t('monitorPanel.title')}</h3>
259
+ <p className={css.customNote}>{t('monitorPanel.description')}</p>
260
+ <label className={css.field}>
261
+ <span>{t('monitorPanel.enabled')}</span>
262
+ <select
263
+ value={value ? 'on' : 'off'}
264
+ disabled={disabled}
265
+ onChange={(event) => { settle(() => save(event.currentTarget.value === 'on')) }}
266
+ >
267
+ <option value="on">{t('monitorPanel.enabled.on')}</option>
268
+ <option value="off">{t('monitorPanel.enabled.off')}</option>
269
+ </select>
270
+ </label>
271
+ </section>
272
+ )
273
+ }
274
+
208
275
  export function CodeSkeletonControls({ value, disabled, save, settle, t }: CodeSkeletonControlsProps) {
209
276
  return (
210
277
  <section className={css.autoCompact} aria-labelledby="context-compression-codeskeleton-title">
@@ -29,6 +29,8 @@ export interface CompressionSelectorInjected {
29
29
  resetCustom: () => Promise<void>
30
30
  saveAutoCompact: (thresholdPercent: number) => Promise<void>
31
31
  saveCodeSkeleton: (enabled: boolean) => Promise<void>
32
+ saveIntentSummary: (enabled: boolean) => Promise<void>
33
+ saveMonitorPanel: (enabled: boolean) => Promise<void>
32
34
  /** Patch of `presetOptions` members; an explicit `undefined` clears that field. */
33
35
  savePresetOptions: (options: import('./preset-options.ts').PresetOptionsPatch) => Promise<void>
34
36
  }
@@ -1,49 +1,57 @@
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
+ decodeMonitorPanelSettings,
10
+ decodePresetOptionsSettings,
11
+ isCustomCompressionPolicy,
12
+ isPlainRecord,
13
+ type CompressionProfile,
14
+ type ContextCompressionSettings,
15
+ } from '../profiles.ts'
16
+
17
+ /**
18
+ * Decode one stored context-compression settings document with exactly the
19
+ * runtime schema's strictness: a plain object with only `profile`, `custom`,
20
+ * `autoCompact`, `codeSkeleton`, and `intentSummary` keys, a supported profile, a valid Custom
21
+ * document canonicalized to v3 exactly as the runtime resolver would, a
22
+ * strictly-shaped autoCompact section (absent inherits the 80% default), and
23
+ * a strictly-shaped codeSkeleton gate (absent inherits off). Anything else
24
+ * decodes to `undefined` so the UI reports the document as unreadable instead
25
+ * of silently disagreeing with the runtime.
26
+ */
27
+ export function decodeSettings(value: unknown): ContextCompressionSettings | undefined {
28
+ if (!isPlainRecord(value)) return undefined
29
+ const keys = Object.keys(value)
30
+ if (keys.some(key => key !== 'profile' && key !== 'custom' && key !== 'autoCompact' && key !== 'codeSkeleton' && key !== 'intentSummary' && key !== 'monitorPanel' && key !== 'presetOptions')) {
31
+ return undefined
32
+ }
33
+ const profile = (value as { profile?: unknown }).profile
34
+ const custom = (value as { custom?: unknown }).custom
35
+ const autoCompact = decodeAutoCompactSettings((value as { autoCompact?: unknown }).autoCompact)
36
+ const codeSkeleton = decodeCodeSkeletonSettings((value as { codeSkeleton?: unknown }).codeSkeleton)
37
+ const intentSummary = decodeIntentSummarySettings((value as { intentSummary?: unknown }).intentSummary)
38
+ const monitorPanel = decodeMonitorPanelSettings((value as { monitorPanel?: unknown }).monitorPanel)
39
+ const presetOptions = decodePresetOptionsSettings((value as { presetOptions?: unknown }).presetOptions)
40
+ return typeof profile === 'string'
41
+ && (COMPRESSION_PROFILES as readonly string[]).includes(profile)
42
+ && isCustomCompressionPolicy(custom)
43
+ && autoCompact !== undefined
44
+ && codeSkeleton !== undefined
45
+ && intentSummary !== undefined
46
+ && monitorPanel !== undefined
47
+ ? {
48
+ profile: profile as CompressionProfile,
49
+ custom: canonicalizeCustomPolicy(custom),
50
+ autoCompact,
51
+ codeSkeleton,
52
+ intentSummary,
53
+ ...monitorPanel === undefined ? {} : { monitorPanel },
54
+ ...presetOptions === undefined ? {} : { presetOptions },
55
+ }
56
+ : undefined
57
+ }