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
@@ -500,6 +500,139 @@ function unpriced(reason) {
500
500
  reason
501
501
  };
502
502
  }
503
+ const advisorStates = /* @__PURE__ */ new WeakMap();
504
+ /**
505
+ * The per-session advisor state, created on first touch.
506
+ * @param session - the session to key the state on (by object identity).
507
+ */
508
+ function getAdvisorState(session) {
509
+ let state = advisorStates.get(session);
510
+ if (state === void 0) {
511
+ state = {
512
+ todoVersion: void 0,
513
+ summary: void 0,
514
+ lastSummaryTurn: -1,
515
+ watermarkSeq: 0,
516
+ scores: /* @__PURE__ */ new Map(),
517
+ recertified: /* @__PURE__ */ new Map(),
518
+ failures: void 0,
519
+ inFlight: false,
520
+ lastDecay: void 0,
521
+ lastAdvice: void 0
522
+ };
523
+ advisorStates.set(session, state);
524
+ }
525
+ return state;
526
+ }
527
+ /**
528
+ * Insert or refresh one score with LRU semantics: a re-touched seq moves to
529
+ * the newest position, and the oldest entry is evicted once the map exceeds
530
+ * {@link ADVISOR_SCORES_LIMIT}.
531
+ */
532
+ function recordScore(state, seq, entry) {
533
+ state.scores.delete(seq);
534
+ state.scores.set(seq, entry);
535
+ if (state.scores.size > 64) {
536
+ const oldest = state.scores.keys().next();
537
+ if (oldest.done !== true) state.scores.delete(oldest.value);
538
+ }
539
+ }
540
+ /**
541
+ * Mark one seq as LLM-recertified low relevance (a suggestion for later
542
+ * history-aggressiveness decisions, consumed by nothing in this round).
543
+ * Bounded at {@link ADVISOR_RECERTIFIED_LIMIT} with the same LRU eviction.
544
+ */
545
+ function recordRecertified(state, seq, turn) {
546
+ state.recertified.delete(seq);
547
+ state.recertified.set(seq, turn);
548
+ if (state.recertified.size > 64) {
549
+ const oldest = state.recertified.keys().next();
550
+ if (oldest.done !== true) state.recertified.delete(oldest.value);
551
+ }
552
+ }
553
+ /**
554
+ * Drop every cached artifact that depends on the task semantics: a changed
555
+ * todo version invalidates the summary and makes all eligible candidates
556
+ * rescore-worthy (the watermark alone would otherwise hide them).
557
+ */
558
+ function invalidateOnTaskChange(state, todoVersion) {
559
+ if (state.todoVersion === todoVersion) return false;
560
+ state.todoVersion = todoVersion;
561
+ state.summary = void 0;
562
+ state.lastSummaryTurn = -1;
563
+ return true;
564
+ }
565
+ /**
566
+ * `/ctx-summary off|on` overrides, keyed by session id (string). The command
567
+ * handler only sees `invocation.agent.session.id`, not the pruner's Session
568
+ * object, so these are id-keyed rather than WeakMap'd. Entries are two-char
569
+ * strings per session and cleared whenever the override is lifted.
570
+ */
571
+ const summaryOverrides = /* @__PURE__ */ new Map();
572
+ /** Read the session's `/ctx-summary` override; `undefined` = default (settings-driven). */
573
+ function getSummaryOverride(sessionId) {
574
+ return summaryOverrides.get(sessionId);
575
+ }
576
+ /** Set or clear (`undefined`) the session's `/ctx-summary` override. */
577
+ function setSummaryOverride(sessionId, value) {
578
+ if (value === void 0) summaryOverrides.delete(sessionId);
579
+ else summaryOverrides.set(sessionId, value);
580
+ }
581
+ /** Last observed `intentSummary.enabled` for a session, for `/ctx-summary status`. */
582
+ const lastObservedIntentEnabled = /* @__PURE__ */ new Map();
583
+ /** Record the gate input the pass last evaluated for this session. */
584
+ function observeIntentEnabled(sessionId, enabled) {
585
+ lastObservedIntentEnabled.set(sessionId, enabled);
586
+ }
587
+ /** The settings-side enabled flag last observed for the session, if any. */
588
+ function getObservedIntentEnabled(sessionId) {
589
+ return lastObservedIntentEnabled.get(sessionId);
590
+ }
591
+ const lastIntentFolds = /* @__PURE__ */ new Map();
592
+ /** Record a landed intent fold for the session (newest wins). */
593
+ function recordIntentFold(sessionId, record) {
594
+ lastIntentFolds.set(sessionId, record);
595
+ }
596
+ /** The most recent landed intent fold for the session, if any. */
597
+ function getLastIntentFold(sessionId) {
598
+ return lastIntentFolds.get(sessionId);
599
+ }
600
+ //#endregion
601
+ //#region src/runtime/tokenpilot/intent-gate.ts
602
+ /**
603
+ * Turn-tail intent-summary growth gate (TokenPilot-inspired E2).
604
+ *
605
+ * Pure decision helper evaluated at the turn-boundary postflight: it decides
606
+ * whether this turn may spend a summary-writer LLM call and stage a fold for
607
+ * the next pressure round. The gate is deliberately conservative — every
608
+ * unresolved input (unknown context window, non-finite counters) fails closed
609
+ * toward "do not run", because a skipped fold is free while a wasted summary
610
+ * call is not. Content safety is unaffected either way: fail-open semantics
611
+ * live in the fold landing path, not here.
612
+ */
613
+ /** Floor: the live surface must exceed this fraction of the context window. */
614
+ const INTENT_GATE_FLOOR_FRACTION = .45;
615
+ /** Growth: the live surface must have grown by more than this since the last landed fold. */
616
+ const INTENT_GATE_GROWTH_TOKENS = 5e4;
617
+ function isUsableNumber(value) {
618
+ return Number.isFinite(value) && value >= 0;
619
+ }
620
+ /** Same evaluation with the reason attached, for audits and `/ctx-summary status`. */
621
+ function evaluateIntentGate(input) {
622
+ const snapshot = (decision, reason) => ({
623
+ ...input,
624
+ decision,
625
+ reason
626
+ });
627
+ if (!input.enabled) return snapshot(false, "disabled");
628
+ if (input.override === "off") return snapshot(false, "override-off");
629
+ if (!isUsableNumber(input.liveTokens)) return snapshot(false, "below-floor");
630
+ if (input.contextWindow === void 0 || !isUsableNumber(input.contextWindow)) return snapshot(false, "no-window");
631
+ if (!(input.liveTokens > input.contextWindow * .45)) return snapshot(false, "below-floor");
632
+ if (!isUsableNumber(input.baselineTokens)) return snapshot(false, "below-growth");
633
+ if (!(input.liveTokens - input.baselineTokens > 5e4)) return snapshot(false, "below-growth");
634
+ return snapshot(true, "passed");
635
+ }
503
636
  //#endregion
504
637
  //#region src/runtime/types.ts
505
638
  /** User-facing mixed strategy profile. */
@@ -875,6 +1008,34 @@ function parseCodeSkeletonSettings(value) {
875
1008
  return { enabled };
876
1009
  }
877
1010
  /**
1011
+ * Strictly parse the persisted intentSummary section. Mirrors the codeSkeleton
1012
+ * section semantics: absent inherits the lossless `false` default, while a
1013
+ * present-but-invalid section is an explicitly invalid document.
1014
+ */
1015
+ function parseIntentSummarySettings(value) {
1016
+ if (value === void 0) return { enabled: false };
1017
+ if (!isPlainRecord(value)) throw new TypeError("Context-compression intentSummary must be a plain object");
1018
+ const keys = Object.keys(value);
1019
+ if (keys.length !== 1 || keys[0] !== "enabled") throw new TypeError(`Context-compression intentSummary: expected exactly "enabled", got "${keys.join("\", \"")}"`);
1020
+ const enabled = value.enabled;
1021
+ if (typeof enabled !== "boolean") throw new TypeError("Context-compression intentSummary.enabled must be a boolean");
1022
+ return { enabled };
1023
+ }
1024
+ /**
1025
+ * Strictly parse the persisted monitorPanel section. Mirrors the intentSummary
1026
+ * section semantics: absent inherits the hidden default, while a
1027
+ * present-but-invalid section is an explicitly invalid document.
1028
+ */
1029
+ function parseMonitorPanelSettings(value) {
1030
+ if (value === void 0) return { enabled: false };
1031
+ if (!isPlainRecord(value)) throw new TypeError("Context-compression monitorPanel must be a plain object");
1032
+ const keys = Object.keys(value);
1033
+ if (keys.length !== 1 || keys[0] !== "enabled") throw new TypeError(`Context-compression monitorPanel: expected exactly "enabled", got "${keys.join("\", \"")}"`);
1034
+ const enabled = value.enabled;
1035
+ if (typeof enabled !== "boolean") throw new TypeError("Context-compression monitorPanel.enabled must be a boolean");
1036
+ return { enabled };
1037
+ }
1038
+ /**
878
1039
  * Parse the optional tokenpilot-inspired preset sub-capability section. Absent
879
1040
  * inherits the preset defaults; present-but-invalid is rejected, mirroring the
880
1041
  * codeSkeleton section semantics.
@@ -981,7 +1142,9 @@ const DEFAULT_CONTEXT_COMPRESSION_SETTINGS = {
981
1142
  profile: "balanced",
982
1143
  custom: structuredClone(DEFAULT_CUSTOM_COMPRESSION_POLICY),
983
1144
  autoCompact: { thresholdPercent: AUTO_COMPACT_THRESHOLD_LIMITS.default },
984
- codeSkeleton: { enabled: false }
1145
+ codeSkeleton: { enabled: false },
1146
+ intentSummary: { enabled: false },
1147
+ monitorPanel: { enabled: false }
985
1148
  };
986
1149
  /**
987
1150
  * Parse one settings document with the persisted-section semantics: `undefined`
@@ -999,17 +1162,21 @@ const ContextCompressionSettingsSchema = z.transform(z.any().required(), (value)
999
1162
  if (!isPlainRecord(value)) throw new TypeError("Context-compression settings must be a plain object");
1000
1163
  assertPlainDataTree(value);
1001
1164
  const candidate = structuredClone(value);
1002
- const unknown = Object.keys(candidate).find((key) => key !== "profile" && key !== "custom" && key !== "autoCompact" && key !== "codeSkeleton" && key !== "presetOptions");
1165
+ const unknown = Object.keys(candidate).find((key) => key !== "profile" && key !== "custom" && key !== "autoCompact" && key !== "codeSkeleton" && key !== "intentSummary" && key !== "monitorPanel" && key !== "presetOptions");
1003
1166
  if (unknown !== void 0) throw new TypeError(`Context-compression settings: unknown key "${unknown}"`);
1004
1167
  assertPresentSection(candidate, "profile", isSupportedProfile);
1005
1168
  assertPresentSection(candidate, "custom", isUsableCustomDocument);
1006
1169
  const autoCompact = parseAutoCompactSettings(candidate.autoCompact);
1007
1170
  const codeSkeleton = parseCodeSkeletonSettings(candidate.codeSkeleton);
1171
+ const intentSummary = parseIntentSummarySettings(candidate.intentSummary);
1172
+ const monitorPanel = parseMonitorPanelSettings(candidate.monitorPanel);
1008
1173
  const presetOptions = parsePresetOptionsSettings(candidate.presetOptions);
1009
1174
  return {
1010
1175
  ...contextCompressionSettingsInputSchema(candidate),
1011
1176
  autoCompact,
1012
1177
  codeSkeleton,
1178
+ intentSummary,
1179
+ monitorPanel,
1013
1180
  ...presetOptions === void 0 ? {} : { presetOptions }
1014
1181
  };
1015
1182
  }).default(DEFAULT_CONTEXT_COMPRESSION_SETTINGS);
@@ -1398,67 +1565,5 @@ function assertPositiveInteger(name, value) {
1398
1565
  function assertNonNegativeInteger(name, value) {
1399
1566
  if (!Number.isSafeInteger(value) || value < 0) throw new Error(`ToolResultPruneConfig: ${name} (${String(value)}) must be a non-negative safe integer`);
1400
1567
  }
1401
- const advisorStates = /* @__PURE__ */ new WeakMap();
1402
- /**
1403
- * The per-session advisor state, created on first touch.
1404
- * @param session - the session to key the state on (by object identity).
1405
- */
1406
- function getAdvisorState(session) {
1407
- let state = advisorStates.get(session);
1408
- if (state === void 0) {
1409
- state = {
1410
- todoVersion: void 0,
1411
- summary: void 0,
1412
- lastSummaryTurn: -1,
1413
- watermarkSeq: 0,
1414
- scores: /* @__PURE__ */ new Map(),
1415
- recertified: /* @__PURE__ */ new Map(),
1416
- failures: void 0,
1417
- inFlight: false,
1418
- lastDecay: void 0,
1419
- lastAdvice: void 0
1420
- };
1421
- advisorStates.set(session, state);
1422
- }
1423
- return state;
1424
- }
1425
- /**
1426
- * Insert or refresh one score with LRU semantics: a re-touched seq moves to
1427
- * the newest position, and the oldest entry is evicted once the map exceeds
1428
- * {@link ADVISOR_SCORES_LIMIT}.
1429
- */
1430
- function recordScore(state, seq, entry) {
1431
- state.scores.delete(seq);
1432
- state.scores.set(seq, entry);
1433
- if (state.scores.size > 64) {
1434
- const oldest = state.scores.keys().next();
1435
- if (oldest.done !== true) state.scores.delete(oldest.value);
1436
- }
1437
- }
1438
- /**
1439
- * Mark one seq as LLM-recertified low relevance (a suggestion for later
1440
- * history-aggressiveness decisions, consumed by nothing in this round).
1441
- * Bounded at {@link ADVISOR_RECERTIFIED_LIMIT} with the same LRU eviction.
1442
- */
1443
- function recordRecertified(state, seq, turn) {
1444
- state.recertified.delete(seq);
1445
- state.recertified.set(seq, turn);
1446
- if (state.recertified.size > 64) {
1447
- const oldest = state.recertified.keys().next();
1448
- if (oldest.done !== true) state.recertified.delete(oldest.value);
1449
- }
1450
- }
1451
- /**
1452
- * Drop every cached artifact that depends on the task semantics: a changed
1453
- * todo version invalidates the summary and makes all eligible candidates
1454
- * rescore-worthy (the watermark alone would otherwise hide them).
1455
- */
1456
- function invalidateOnTaskChange(state, todoVersion) {
1457
- if (state.todoVersion === todoVersion) return false;
1458
- state.todoVersion = todoVersion;
1459
- state.summary = void 0;
1460
- state.lastSummaryTurn = -1;
1461
- return true;
1462
- }
1463
1568
  //#endregion
1464
- export { deepFreeze as C, priceOfficialDeepSeekUsage as D, decimalRateNanoUnits as E, resolveOfficialDeepSeekPrice as O, assertNever as S, DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION as T, resolveConfig as _, AUTO_COMPACT_THRESHOLD_LIMITS as a, DEFAULT_CUSTOM_COMPRESSION_POLICY as b, DEFAULTS as c, charsForTokens as d, charsToTokens as f, parseContextCompressionSettings as g, isValidAutoCompactThresholdPercent as h, recordScore as i, getSavingsLedger as k, DEFAULT_CONTEXT_COMPRESSION_SETTINGS as l, isCompressionProfile as m, invalidateOnTaskChange as n, CONTEXT_COMPRESSION_SETTINGS_NAMESPACE as o, codePointLength as p, recordRecertified as r, ContextCompressionSettingsSchema as s, getAdvisorState as t, PRUNE_MARKER as u, resolvePolicy as v, COMPRESSION_PROFILES as w, resolveCustomPolicy as x, CustomCompressionPolicySchema as y };
1569
+ export { recordIntentFold as A, evaluateIntentGate as C, getSummaryOverride as D, getObservedIntentEnabled as E, decimalRateNanoUnits as F, priceOfficialDeepSeekUsage as I, resolveOfficialDeepSeekPrice as L, recordScore as M, setSummaryOverride as N, invalidateOnTaskChange as O, DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION as P, getSavingsLedger as R, INTENT_GATE_GROWTH_TOKENS as S, getLastIntentFold as T, resolveCustomPolicy as _, DEFAULT_CONTEXT_COMPRESSION_SETTINGS as a, COMPRESSION_PROFILES as b, charsToTokens as c, isValidAutoCompactThresholdPercent as d, parseContextCompressionSettings as f, DEFAULT_CUSTOM_COMPRESSION_POLICY as g, CustomCompressionPolicySchema as h, DEFAULTS as i, recordRecertified as j, observeIntentEnabled as k, codePointLength as l, resolvePolicy as m, CONTEXT_COMPRESSION_SETTINGS_NAMESPACE as n, PRUNE_MARKER as o, resolveConfig as p, ContextCompressionSettingsSchema as r, charsForTokens as s, AUTO_COMPACT_THRESHOLD_LIMITS as t, isCompressionProfile as u, assertNever as v, getAdvisorState as w, INTENT_GATE_FLOOR_FRACTION as x, deepFreeze as y };
@@ -2,6 +2,18 @@ import { n as ContextCompressionSettings } from "./profiles.js";
2
2
  import z from "@deepseek-ai/schemastery";
3
3
  import { Context } from "@deepseek-ai/cordis";
4
4
  //#region src/index.d.ts
5
+ /**
6
+ * Floating-panel monitor route (`GET|POST .../monitor?sessionId=…`):
7
+ * - GET → the monitor snapshot (savings aggregate + intent control block +
8
+ * pricing) — the payload shape the panel polls;
9
+ * - POST → session override action (`{"action":"on"|"off"|"clear"}`),
10
+ * driving the exact state machine `/ctx-summary` drives.
11
+ * Registration mirrors the savings route (webServer gate alone, dual channels,
12
+ * single guarded registration); the handler branches on `req.method` because
13
+ * the registration surface is method-agnostic.
14
+ */
15
+ /** Exported for the runtime monitor spec; the entry owns all webServer wiring. */
16
+ declare function registerMonitorRoute(ctx: Context): void;
5
17
  /** Standalone Bundle behavior; the settings/UI owner remains safe when false. */
6
18
  interface Config {
7
19
  /** Add the canonical compression stack to every non-Minimal preset. */
@@ -40,4 +52,4 @@ declare const Config: z<Config>;
40
52
  /** Register the persisted default read by the currently mounted root pruner. */
41
53
  declare function apply(ctx: Context, config?: Config): void;
42
54
  //#endregion
43
- export { Config, apply };
55
+ export { Config, apply, registerMonitorRoute };