dsh-context-compression-improved 0.8.0-beta.4 → 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.
- package/CHANGELOG.md +13 -0
- package/package.json +1 -1
- package/packages/selector/dsh.plugin.json +1 -1
- package/packages/selector/lib/client.d.ts +22 -0
- package/packages/selector/lib/client.js +528 -3
- package/packages/selector/lib/{intent-gate.js → config.js} +153 -136
- package/packages/selector/lib/index.d.ts +13 -1
- package/packages/selector/lib/index.js +215 -50
- package/packages/selector/lib/profiles.d.ts +6 -0
- package/packages/selector/lib/pruner.d.ts +6 -0
- package/packages/selector/lib/pruner.js +1 -1
- package/packages/selector/src/client/CompressionProfileControls.tsx +33 -0
- package/packages/selector/src/client/CompressionProfileSelector.tsx +1 -0
- package/packages/selector/src/client/decode.ts +5 -1
- package/packages/selector/src/client/index.ts +37 -0
- package/packages/selector/src/client/locales/de.ts +21 -0
- package/packages/selector/src/client/locales/es.ts +21 -0
- package/packages/selector/src/client/locales/fr.ts +21 -0
- package/packages/selector/src/client/locales/it.ts +21 -0
- package/packages/selector/src/client/locales/ja.ts +21 -0
- package/packages/selector/src/client/locales/ko.ts +21 -0
- package/packages/selector/src/client/locales/ru.ts +21 -0
- package/packages/selector/src/client/locales.ts +42 -0
- package/packages/selector/src/client/monitor-fab.ts +307 -0
- package/packages/selector/src/client/settings-section.tsx +9 -2
- package/packages/selector/src/index.ts +126 -60
- package/packages/selector/src/profiles.ts +17 -0
- package/packages/selector/src/runtime/config.ts +26 -1
- package/packages/selector/src/runtime/monitor.ts +149 -0
- package/packages/selector/src/runtime/types.ts +7 -0
- package/packages/selector/tests/estimator-route-registration.host.spec.ts +8 -6
- package/packages/selector/tests/monitor-fab.client.spec.ts +117 -0
- package/packages/selector/tests/runtime/monitor.spec.ts +236 -0
- package/packages/selector/tests/settings-seat.client.spec.ts +1 -1
- package/scripts/packed-install-e2e.mjs +1 -1
- package/scripts/verify-release.mjs +1 -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. */
|
|
@@ -889,6 +1022,20 @@ function parseIntentSummarySettings(value) {
|
|
|
889
1022
|
return { enabled };
|
|
890
1023
|
}
|
|
891
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
|
+
/**
|
|
892
1039
|
* Parse the optional tokenpilot-inspired preset sub-capability section. Absent
|
|
893
1040
|
* inherits the preset defaults; present-but-invalid is rejected, mirroring the
|
|
894
1041
|
* codeSkeleton section semantics.
|
|
@@ -996,7 +1143,8 @@ const DEFAULT_CONTEXT_COMPRESSION_SETTINGS = {
|
|
|
996
1143
|
custom: structuredClone(DEFAULT_CUSTOM_COMPRESSION_POLICY),
|
|
997
1144
|
autoCompact: { thresholdPercent: AUTO_COMPACT_THRESHOLD_LIMITS.default },
|
|
998
1145
|
codeSkeleton: { enabled: false },
|
|
999
|
-
intentSummary: { enabled: false }
|
|
1146
|
+
intentSummary: { enabled: false },
|
|
1147
|
+
monitorPanel: { enabled: false }
|
|
1000
1148
|
};
|
|
1001
1149
|
/**
|
|
1002
1150
|
* Parse one settings document with the persisted-section semantics: `undefined`
|
|
@@ -1014,19 +1162,21 @@ const ContextCompressionSettingsSchema = z.transform(z.any().required(), (value)
|
|
|
1014
1162
|
if (!isPlainRecord(value)) throw new TypeError("Context-compression settings must be a plain object");
|
|
1015
1163
|
assertPlainDataTree(value);
|
|
1016
1164
|
const candidate = structuredClone(value);
|
|
1017
|
-
const unknown = Object.keys(candidate).find((key) => key !== "profile" && key !== "custom" && key !== "autoCompact" && key !== "codeSkeleton" && key !== "intentSummary" && key !== "presetOptions");
|
|
1165
|
+
const unknown = Object.keys(candidate).find((key) => key !== "profile" && key !== "custom" && key !== "autoCompact" && key !== "codeSkeleton" && key !== "intentSummary" && key !== "monitorPanel" && key !== "presetOptions");
|
|
1018
1166
|
if (unknown !== void 0) throw new TypeError(`Context-compression settings: unknown key "${unknown}"`);
|
|
1019
1167
|
assertPresentSection(candidate, "profile", isSupportedProfile);
|
|
1020
1168
|
assertPresentSection(candidate, "custom", isUsableCustomDocument);
|
|
1021
1169
|
const autoCompact = parseAutoCompactSettings(candidate.autoCompact);
|
|
1022
1170
|
const codeSkeleton = parseCodeSkeletonSettings(candidate.codeSkeleton);
|
|
1023
1171
|
const intentSummary = parseIntentSummarySettings(candidate.intentSummary);
|
|
1172
|
+
const monitorPanel = parseMonitorPanelSettings(candidate.monitorPanel);
|
|
1024
1173
|
const presetOptions = parsePresetOptionsSettings(candidate.presetOptions);
|
|
1025
1174
|
return {
|
|
1026
1175
|
...contextCompressionSettingsInputSchema(candidate),
|
|
1027
1176
|
autoCompact,
|
|
1028
1177
|
codeSkeleton,
|
|
1029
1178
|
intentSummary,
|
|
1179
|
+
monitorPanel,
|
|
1030
1180
|
...presetOptions === void 0 ? {} : { presetOptions }
|
|
1031
1181
|
};
|
|
1032
1182
|
}).default(DEFAULT_CONTEXT_COMPRESSION_SETTINGS);
|
|
@@ -1415,138 +1565,5 @@ function assertPositiveInteger(name, value) {
|
|
|
1415
1565
|
function assertNonNegativeInteger(name, value) {
|
|
1416
1566
|
if (!Number.isSafeInteger(value) || value < 0) throw new Error(`ToolResultPruneConfig: ${name} (${String(value)}) must be a non-negative safe integer`);
|
|
1417
1567
|
}
|
|
1418
|
-
const advisorStates = /* @__PURE__ */ new WeakMap();
|
|
1419
|
-
/**
|
|
1420
|
-
* The per-session advisor state, created on first touch.
|
|
1421
|
-
* @param session - the session to key the state on (by object identity).
|
|
1422
|
-
*/
|
|
1423
|
-
function getAdvisorState(session) {
|
|
1424
|
-
let state = advisorStates.get(session);
|
|
1425
|
-
if (state === void 0) {
|
|
1426
|
-
state = {
|
|
1427
|
-
todoVersion: void 0,
|
|
1428
|
-
summary: void 0,
|
|
1429
|
-
lastSummaryTurn: -1,
|
|
1430
|
-
watermarkSeq: 0,
|
|
1431
|
-
scores: /* @__PURE__ */ new Map(),
|
|
1432
|
-
recertified: /* @__PURE__ */ new Map(),
|
|
1433
|
-
failures: void 0,
|
|
1434
|
-
inFlight: false,
|
|
1435
|
-
lastDecay: void 0,
|
|
1436
|
-
lastAdvice: void 0
|
|
1437
|
-
};
|
|
1438
|
-
advisorStates.set(session, state);
|
|
1439
|
-
}
|
|
1440
|
-
return state;
|
|
1441
|
-
}
|
|
1442
|
-
/**
|
|
1443
|
-
* Insert or refresh one score with LRU semantics: a re-touched seq moves to
|
|
1444
|
-
* the newest position, and the oldest entry is evicted once the map exceeds
|
|
1445
|
-
* {@link ADVISOR_SCORES_LIMIT}.
|
|
1446
|
-
*/
|
|
1447
|
-
function recordScore(state, seq, entry) {
|
|
1448
|
-
state.scores.delete(seq);
|
|
1449
|
-
state.scores.set(seq, entry);
|
|
1450
|
-
if (state.scores.size > 64) {
|
|
1451
|
-
const oldest = state.scores.keys().next();
|
|
1452
|
-
if (oldest.done !== true) state.scores.delete(oldest.value);
|
|
1453
|
-
}
|
|
1454
|
-
}
|
|
1455
|
-
/**
|
|
1456
|
-
* Mark one seq as LLM-recertified low relevance (a suggestion for later
|
|
1457
|
-
* history-aggressiveness decisions, consumed by nothing in this round).
|
|
1458
|
-
* Bounded at {@link ADVISOR_RECERTIFIED_LIMIT} with the same LRU eviction.
|
|
1459
|
-
*/
|
|
1460
|
-
function recordRecertified(state, seq, turn) {
|
|
1461
|
-
state.recertified.delete(seq);
|
|
1462
|
-
state.recertified.set(seq, turn);
|
|
1463
|
-
if (state.recertified.size > 64) {
|
|
1464
|
-
const oldest = state.recertified.keys().next();
|
|
1465
|
-
if (oldest.done !== true) state.recertified.delete(oldest.value);
|
|
1466
|
-
}
|
|
1467
|
-
}
|
|
1468
|
-
/**
|
|
1469
|
-
* Drop every cached artifact that depends on the task semantics: a changed
|
|
1470
|
-
* todo version invalidates the summary and makes all eligible candidates
|
|
1471
|
-
* rescore-worthy (the watermark alone would otherwise hide them).
|
|
1472
|
-
*/
|
|
1473
|
-
function invalidateOnTaskChange(state, todoVersion) {
|
|
1474
|
-
if (state.todoVersion === todoVersion) return false;
|
|
1475
|
-
state.todoVersion = todoVersion;
|
|
1476
|
-
state.summary = void 0;
|
|
1477
|
-
state.lastSummaryTurn = -1;
|
|
1478
|
-
return true;
|
|
1479
|
-
}
|
|
1480
|
-
/**
|
|
1481
|
-
* `/ctx-summary off|on` overrides, keyed by session id (string). The command
|
|
1482
|
-
* handler only sees `invocation.agent.session.id`, not the pruner's Session
|
|
1483
|
-
* object, so these are id-keyed rather than WeakMap'd. Entries are two-char
|
|
1484
|
-
* strings per session and cleared whenever the override is lifted.
|
|
1485
|
-
*/
|
|
1486
|
-
const summaryOverrides = /* @__PURE__ */ new Map();
|
|
1487
|
-
/** Read the session's `/ctx-summary` override; `undefined` = default (settings-driven). */
|
|
1488
|
-
function getSummaryOverride(sessionId) {
|
|
1489
|
-
return summaryOverrides.get(sessionId);
|
|
1490
|
-
}
|
|
1491
|
-
/** Set or clear (`undefined`) the session's `/ctx-summary` override. */
|
|
1492
|
-
function setSummaryOverride(sessionId, value) {
|
|
1493
|
-
if (value === void 0) summaryOverrides.delete(sessionId);
|
|
1494
|
-
else summaryOverrides.set(sessionId, value);
|
|
1495
|
-
}
|
|
1496
|
-
/** Last observed `intentSummary.enabled` for a session, for `/ctx-summary status`. */
|
|
1497
|
-
const lastObservedIntentEnabled = /* @__PURE__ */ new Map();
|
|
1498
|
-
/** Record the gate input the pass last evaluated for this session. */
|
|
1499
|
-
function observeIntentEnabled(sessionId, enabled) {
|
|
1500
|
-
lastObservedIntentEnabled.set(sessionId, enabled);
|
|
1501
|
-
}
|
|
1502
|
-
/** The settings-side enabled flag last observed for the session, if any. */
|
|
1503
|
-
function getObservedIntentEnabled(sessionId) {
|
|
1504
|
-
return lastObservedIntentEnabled.get(sessionId);
|
|
1505
|
-
}
|
|
1506
|
-
const lastIntentFolds = /* @__PURE__ */ new Map();
|
|
1507
|
-
/** Record a landed intent fold for the session (newest wins). */
|
|
1508
|
-
function recordIntentFold(sessionId, record) {
|
|
1509
|
-
lastIntentFolds.set(sessionId, record);
|
|
1510
|
-
}
|
|
1511
|
-
/** The most recent landed intent fold for the session, if any. */
|
|
1512
|
-
function getLastIntentFold(sessionId) {
|
|
1513
|
-
return lastIntentFolds.get(sessionId);
|
|
1514
|
-
}
|
|
1515
|
-
//#endregion
|
|
1516
|
-
//#region src/runtime/tokenpilot/intent-gate.ts
|
|
1517
|
-
/**
|
|
1518
|
-
* Turn-tail intent-summary growth gate (TokenPilot-inspired E2).
|
|
1519
|
-
*
|
|
1520
|
-
* Pure decision helper evaluated at the turn-boundary postflight: it decides
|
|
1521
|
-
* whether this turn may spend a summary-writer LLM call and stage a fold for
|
|
1522
|
-
* the next pressure round. The gate is deliberately conservative — every
|
|
1523
|
-
* unresolved input (unknown context window, non-finite counters) fails closed
|
|
1524
|
-
* toward "do not run", because a skipped fold is free while a wasted summary
|
|
1525
|
-
* call is not. Content safety is unaffected either way: fail-open semantics
|
|
1526
|
-
* live in the fold landing path, not here.
|
|
1527
|
-
*/
|
|
1528
|
-
/** Floor: the live surface must exceed this fraction of the context window. */
|
|
1529
|
-
const INTENT_GATE_FLOOR_FRACTION = .45;
|
|
1530
|
-
/** Growth: the live surface must have grown by more than this since the last landed fold. */
|
|
1531
|
-
const INTENT_GATE_GROWTH_TOKENS = 5e4;
|
|
1532
|
-
function isUsableNumber(value) {
|
|
1533
|
-
return Number.isFinite(value) && value >= 0;
|
|
1534
|
-
}
|
|
1535
|
-
/** Same evaluation with the reason attached, for audits and `/ctx-summary status`. */
|
|
1536
|
-
function evaluateIntentGate(input) {
|
|
1537
|
-
const snapshot = (decision, reason) => ({
|
|
1538
|
-
...input,
|
|
1539
|
-
decision,
|
|
1540
|
-
reason
|
|
1541
|
-
});
|
|
1542
|
-
if (!input.enabled) return snapshot(false, "disabled");
|
|
1543
|
-
if (input.override === "off") return snapshot(false, "override-off");
|
|
1544
|
-
if (!isUsableNumber(input.liveTokens)) return snapshot(false, "below-floor");
|
|
1545
|
-
if (input.contextWindow === void 0 || !isUsableNumber(input.contextWindow)) return snapshot(false, "no-window");
|
|
1546
|
-
if (!(input.liveTokens > input.contextWindow * .45)) return snapshot(false, "below-floor");
|
|
1547
|
-
if (!isUsableNumber(input.baselineTokens)) return snapshot(false, "below-growth");
|
|
1548
|
-
if (!(input.liveTokens - input.baselineTokens > 5e4)) return snapshot(false, "below-growth");
|
|
1549
|
-
return snapshot(true, "passed");
|
|
1550
|
-
}
|
|
1551
1568
|
//#endregion
|
|
1552
|
-
export {
|
|
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 };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { D as getSummaryOverride, E as getObservedIntentEnabled, I as priceOfficialDeepSeekUsage, N as setSummaryOverride, R as getSavingsLedger, S as INTENT_GATE_GROWTH_TOKENS, T as getLastIntentFold, a as DEFAULT_CONTEXT_COMPRESSION_SETTINGS, w as getAdvisorState, x as INTENT_GATE_FLOOR_FRACTION } from "./config.js";
|
|
2
2
|
import z from "@deepseek-ai/schemastery";
|
|
3
3
|
import { createHash } from "node:crypto";
|
|
4
4
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
@@ -75,6 +75,90 @@ async function buildEstimatorCatalog(deps) {
|
|
|
75
75
|
};
|
|
76
76
|
}
|
|
77
77
|
//#endregion
|
|
78
|
+
//#region src/runtime/monitor.ts
|
|
79
|
+
/**
|
|
80
|
+
* Savings snapshot plus the intent-summary control block. Ledger is
|
|
81
|
+
* injectable so tests seed a private instance instead of the process
|
|
82
|
+
* singleton.
|
|
83
|
+
*/
|
|
84
|
+
function buildMonitorSnapshot(sessionId, ledger = getSavingsLedger()) {
|
|
85
|
+
const override = getSummaryOverride(sessionId ?? "");
|
|
86
|
+
return {
|
|
87
|
+
...ledger.snapshot(sessionId),
|
|
88
|
+
intent: {
|
|
89
|
+
override,
|
|
90
|
+
observedEnabled: getObservedIntentEnabled(sessionId ?? ""),
|
|
91
|
+
gate: {
|
|
92
|
+
floorFraction: INTENT_GATE_FLOOR_FRACTION,
|
|
93
|
+
growthTokens: INTENT_GATE_GROWTH_TOKENS
|
|
94
|
+
},
|
|
95
|
+
lastFold: getLastIntentFold(sessionId ?? "")
|
|
96
|
+
},
|
|
97
|
+
sessionScope: sessionId ?? null
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
function isSessionOverrideAction(value) {
|
|
101
|
+
return value === "on" || value === "off" || value === "clear";
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Drive the `/ctx-summary` override state machine: `on`/`off` pin the
|
|
105
|
+
* session, `clear` returns it to settings-driven. The resulting override is
|
|
106
|
+
* handed back so the route can echo the post-action truth.
|
|
107
|
+
*/
|
|
108
|
+
function applySessionOverride(sessionId, action) {
|
|
109
|
+
setSummaryOverride(sessionId, action === "clear" ? void 0 : action);
|
|
110
|
+
return { override: getSummaryOverride(sessionId) };
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* 金额估算(monitor 口径的 token/金额估算,结合官方牌价):
|
|
114
|
+
* - actualCost:本进程累计真实 usage 的官方牌价(exact/range);
|
|
115
|
+
* - estimatedSavedCost:净节省(精确口径)按 cache-miss 输入价折算——
|
|
116
|
+
* 基线假设"这些 token 不压缩就要全价进上下文",标注估算。
|
|
117
|
+
* 仅官方 deepseek-official 路由可解;第三方/未知模型 fail-closed 为 undefined。
|
|
118
|
+
* (自入口迁入: savings 路由与 monitor 路由共享,避免 runtime → entry 回环。)
|
|
119
|
+
*/
|
|
120
|
+
function estimateSavingsPricing(readService, snapshot) {
|
|
121
|
+
if (snapshot.usage.requests === 0 && snapshot.net.exact === 0) return void 0;
|
|
122
|
+
const selection = readService("agentDefaultModel")?.currentSelection?.();
|
|
123
|
+
const provider = typeof selection?.provider === "string" ? selection.provider : "";
|
|
124
|
+
const modelId = typeof selection?.model === "string" ? selection.model : "";
|
|
125
|
+
if (provider !== "deepseek-official") return void 0;
|
|
126
|
+
const now = /* @__PURE__ */ new Date();
|
|
127
|
+
const startedAt = new Date(snapshot.startedAt);
|
|
128
|
+
const base = {
|
|
129
|
+
provider,
|
|
130
|
+
baseUrlClass: "official-public",
|
|
131
|
+
apiRoute: "chat-completions",
|
|
132
|
+
modelId,
|
|
133
|
+
currency: "USD",
|
|
134
|
+
startedAt,
|
|
135
|
+
completedAt: now.getTime() > startedAt.getTime() ? now : new Date(startedAt.getTime() + 1)
|
|
136
|
+
};
|
|
137
|
+
const actual = priceOfficialDeepSeekUsage({
|
|
138
|
+
...base,
|
|
139
|
+
usage: {
|
|
140
|
+
cacheReadTokens: Math.max(0, Math.round(snapshot.usage.cacheReadTokens)),
|
|
141
|
+
cacheMissTokens: Math.max(0, Math.round(snapshot.usage.inputTokens)),
|
|
142
|
+
outputTokens: Math.max(0, Math.round(snapshot.usage.outputTokens))
|
|
143
|
+
}
|
|
144
|
+
});
|
|
145
|
+
const saved = snapshot.net.exact > 0 ? priceOfficialDeepSeekUsage({
|
|
146
|
+
...base,
|
|
147
|
+
usage: {
|
|
148
|
+
cacheReadTokens: 0,
|
|
149
|
+
cacheMissTokens: Math.round(snapshot.net.exact),
|
|
150
|
+
outputTokens: 0
|
|
151
|
+
}
|
|
152
|
+
}) : void 0;
|
|
153
|
+
const decimalOf = (cost) => cost.kind === "exact" ? cost.decimal : cost.kind === "range" ? cost.minimum.decimal : void 0;
|
|
154
|
+
if (actual.kind === "unpriced" && (saved === void 0 || saved.kind === "unpriced")) return void 0;
|
|
155
|
+
return {
|
|
156
|
+
currency: "USD",
|
|
157
|
+
...actual.kind === "unpriced" ? {} : { actualCost: decimalOf(actual) },
|
|
158
|
+
...saved === void 0 || saved.kind === "unpriced" ? {} : { estimatedSavedCost: decimalOf(saved) }
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
//#endregion
|
|
78
162
|
//#region src/runtime/summary-command.ts
|
|
79
163
|
const SUMMARY_COMMAND_NAME = "ctx-summary";
|
|
80
164
|
const USAGE = "Usage: /ctx-summary off|on|status";
|
|
@@ -595,6 +679,7 @@ function restoreMethod(presets, snapshot) {
|
|
|
595
679
|
const ESTIMATOR_CATALOG_ROUTES = ["/endpoint/dsh-context-compression-improved/estimator-catalog", "/api/dsh-context-compression-improved/estimator-catalog"];
|
|
596
680
|
const ADVISOR_REPORT_ROUTES = ["/endpoint/dsh-context-compression-improved/advisor-report", "/api/dsh-context-compression-improved/advisor-report"];
|
|
597
681
|
const SAVINGS_ROUTES = ["/endpoint/dsh-context-compression-improved/savings", "/api/dsh-context-compression-improved/savings"];
|
|
682
|
+
const MONITOR_ROUTES = ["/endpoint/dsh-context-compression-improved/monitor", "/api/dsh-context-compression-improved/monitor"];
|
|
598
683
|
function sessionFor(readService, sessionId) {
|
|
599
684
|
const agents = readService("agents");
|
|
600
685
|
return typeof agents?.get === "function" ? agents.get(sessionId)?.session : void 0;
|
|
@@ -717,6 +802,7 @@ function registerAdvisorReportRoute(ctx) {
|
|
|
717
802
|
* never reasons to withhold the route.
|
|
718
803
|
*/
|
|
719
804
|
const ESTIMATOR_CATALOG_ROUTE_DEPS = ["webServer"];
|
|
805
|
+
/** The estimator-side service the catalog handler enriches its response with. */
|
|
720
806
|
function asWebServer(value) {
|
|
721
807
|
if (typeof value !== "object" || value === null) return void 0;
|
|
722
808
|
return typeof value.register === "function" ? value : void 0;
|
|
@@ -810,54 +896,6 @@ function registerEstimatorCatalogRoute(ctx) {
|
|
|
810
896
|
log("warn", "context-compression webServer not active yet — estimator catalog route pending: %s", ESTIMATOR_CATALOG_ROUTES.join(", "));
|
|
811
897
|
}
|
|
812
898
|
/**
|
|
813
|
-
* 金额估算(monitor 口径的 token/金额估算,结合官方牌价):
|
|
814
|
-
* - actualCost:本进程累计真实 usage 的官方牌价(exact/range);
|
|
815
|
-
* - estimatedSavedCost:净节省(精确口径)按 cache-miss 输入价折算——
|
|
816
|
-
* 基线假设"这些 token 不压缩就要全价进上下文",标注估算。
|
|
817
|
-
* 仅官方 deepseek-official 路由可解;第三方/未知模型 fail-closed 为 undefined。
|
|
818
|
-
*/
|
|
819
|
-
function estimateSavingsPricing(readService, snapshot) {
|
|
820
|
-
if (snapshot.usage.requests === 0 && snapshot.net.exact === 0) return void 0;
|
|
821
|
-
const selection = readService("agentDefaultModel")?.currentSelection?.();
|
|
822
|
-
const provider = typeof selection?.provider === "string" ? selection.provider : "";
|
|
823
|
-
const modelId = typeof selection?.model === "string" ? selection.model : "";
|
|
824
|
-
if (provider !== "deepseek-official") return void 0;
|
|
825
|
-
const now = /* @__PURE__ */ new Date();
|
|
826
|
-
const startedAt = new Date(snapshot.startedAt);
|
|
827
|
-
const base = {
|
|
828
|
-
provider,
|
|
829
|
-
baseUrlClass: "official-public",
|
|
830
|
-
apiRoute: "chat-completions",
|
|
831
|
-
modelId,
|
|
832
|
-
currency: "USD",
|
|
833
|
-
startedAt,
|
|
834
|
-
completedAt: now.getTime() > startedAt.getTime() ? now : new Date(startedAt.getTime() + 1)
|
|
835
|
-
};
|
|
836
|
-
const actual = priceOfficialDeepSeekUsage({
|
|
837
|
-
...base,
|
|
838
|
-
usage: {
|
|
839
|
-
cacheReadTokens: Math.max(0, Math.round(snapshot.usage.cacheReadTokens)),
|
|
840
|
-
cacheMissTokens: Math.max(0, Math.round(snapshot.usage.inputTokens)),
|
|
841
|
-
outputTokens: Math.max(0, Math.round(snapshot.usage.outputTokens))
|
|
842
|
-
}
|
|
843
|
-
});
|
|
844
|
-
const saved = snapshot.net.exact > 0 ? priceOfficialDeepSeekUsage({
|
|
845
|
-
...base,
|
|
846
|
-
usage: {
|
|
847
|
-
cacheReadTokens: 0,
|
|
848
|
-
cacheMissTokens: Math.round(snapshot.net.exact),
|
|
849
|
-
outputTokens: 0
|
|
850
|
-
}
|
|
851
|
-
}) : void 0;
|
|
852
|
-
const decimalOf = (cost) => cost.kind === "exact" ? cost.decimal : cost.kind === "range" ? cost.minimum.decimal : void 0;
|
|
853
|
-
if (actual.kind === "unpriced" && (saved === void 0 || saved.kind === "unpriced")) return void 0;
|
|
854
|
-
return {
|
|
855
|
-
currency: "USD",
|
|
856
|
-
...actual.kind === "unpriced" ? {} : { actualCost: decimalOf(actual) },
|
|
857
|
-
...saved === void 0 || saved.kind === "unpriced" ? {} : { estimatedSavedCost: decimalOf(saved) }
|
|
858
|
-
};
|
|
859
|
-
}
|
|
860
|
-
/**
|
|
861
899
|
* Read-only savings snapshot route (`GET .../savings?sessionId=…`): gross saved,
|
|
862
900
|
* offsets (negative savings — compressed content later re-read in full), and net,
|
|
863
901
|
* with exact-tokenizer and chars/4 bases reported separately and never merged.
|
|
@@ -928,6 +966,132 @@ function registerSavingsRoute(ctx) {
|
|
|
928
966
|
});
|
|
929
967
|
}
|
|
930
968
|
/**
|
|
969
|
+
* Floating-panel monitor route (`GET|POST .../monitor?sessionId=…`):
|
|
970
|
+
* - GET → the monitor snapshot (savings aggregate + intent control block +
|
|
971
|
+
* pricing) — the payload shape the panel polls;
|
|
972
|
+
* - POST → session override action (`{"action":"on"|"off"|"clear"}`),
|
|
973
|
+
* driving the exact state machine `/ctx-summary` drives.
|
|
974
|
+
* Registration mirrors the savings route (webServer gate alone, dual channels,
|
|
975
|
+
* single guarded registration); the handler branches on `req.method` because
|
|
976
|
+
* the registration surface is method-agnostic.
|
|
977
|
+
*/
|
|
978
|
+
/** Exported for the runtime monitor spec; the entry owns all webServer wiring. */
|
|
979
|
+
function registerMonitorRoute(ctx) {
|
|
980
|
+
const readService = (name) => {
|
|
981
|
+
try {
|
|
982
|
+
return ctx.get(name);
|
|
983
|
+
} catch {
|
|
984
|
+
return;
|
|
985
|
+
}
|
|
986
|
+
};
|
|
987
|
+
const log = (level, message, ...args) => {
|
|
988
|
+
console[level](message, ...args);
|
|
989
|
+
};
|
|
990
|
+
let registered = false;
|
|
991
|
+
const register = (webServer, channel) => {
|
|
992
|
+
if (registered) return;
|
|
993
|
+
const handler = (req, res) => {
|
|
994
|
+
const resTyped = res;
|
|
995
|
+
if (typeof resTyped?.writeHead !== "function" || typeof resTyped?.end !== "function") return;
|
|
996
|
+
let sessionId;
|
|
997
|
+
try {
|
|
998
|
+
const raw = new URL(String(req?.url ?? "/"), "http://localhost").searchParams.get("sessionId");
|
|
999
|
+
if (typeof raw === "string" && raw.length > 0 && raw.length <= 512) sessionId = raw;
|
|
1000
|
+
} catch {}
|
|
1001
|
+
if (String(req?.method ?? "GET").toUpperCase() === "POST") {
|
|
1002
|
+
const chunks = [];
|
|
1003
|
+
let size = 0;
|
|
1004
|
+
let done = false;
|
|
1005
|
+
const respond = (status, body) => {
|
|
1006
|
+
if (done) return;
|
|
1007
|
+
done = true;
|
|
1008
|
+
resTyped.writeHead(status, {
|
|
1009
|
+
"content-type": "application/json; charset=utf-8",
|
|
1010
|
+
"cache-control": "no-cache"
|
|
1011
|
+
});
|
|
1012
|
+
resTyped.end(JSON.stringify(body));
|
|
1013
|
+
};
|
|
1014
|
+
const reqTyped = req;
|
|
1015
|
+
if (typeof reqTyped?.on !== "function") {
|
|
1016
|
+
respond(400, {
|
|
1017
|
+
ok: false,
|
|
1018
|
+
error: "unreadable request body"
|
|
1019
|
+
});
|
|
1020
|
+
return;
|
|
1021
|
+
}
|
|
1022
|
+
reqTyped.on("data", (chunk) => {
|
|
1023
|
+
size += chunk?.length ?? 0;
|
|
1024
|
+
if (size <= 4096) chunks.push(Buffer.from(chunk ?? /* @__PURE__ */ new Uint8Array()));
|
|
1025
|
+
});
|
|
1026
|
+
reqTyped.on("end", () => {
|
|
1027
|
+
let action;
|
|
1028
|
+
try {
|
|
1029
|
+
action = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}").action;
|
|
1030
|
+
} catch {
|
|
1031
|
+
respond(400, {
|
|
1032
|
+
ok: false,
|
|
1033
|
+
error: "monitor override action must be JSON"
|
|
1034
|
+
});
|
|
1035
|
+
return;
|
|
1036
|
+
}
|
|
1037
|
+
if (!isSessionOverrideAction(action)) {
|
|
1038
|
+
respond(400, {
|
|
1039
|
+
ok: false,
|
|
1040
|
+
error: "monitor override action must be \"on\" | \"off\" | \"clear\""
|
|
1041
|
+
});
|
|
1042
|
+
return;
|
|
1043
|
+
}
|
|
1044
|
+
const { override } = applySessionOverride(sessionId ?? "", action);
|
|
1045
|
+
respond(200, {
|
|
1046
|
+
ok: true,
|
|
1047
|
+
override: override ?? null,
|
|
1048
|
+
sessionScope: sessionId ?? null
|
|
1049
|
+
});
|
|
1050
|
+
});
|
|
1051
|
+
return;
|
|
1052
|
+
}
|
|
1053
|
+
const snapshot = buildMonitorSnapshot(sessionId);
|
|
1054
|
+
const pricing = estimateSavingsPricing(readService, snapshot);
|
|
1055
|
+
resTyped.writeHead(200, {
|
|
1056
|
+
"content-type": "application/json; charset=utf-8",
|
|
1057
|
+
"cache-control": "no-cache"
|
|
1058
|
+
});
|
|
1059
|
+
resTyped.end(JSON.stringify({
|
|
1060
|
+
ok: true,
|
|
1061
|
+
...snapshot,
|
|
1062
|
+
...pricing === void 0 ? {} : { pricing }
|
|
1063
|
+
}));
|
|
1064
|
+
};
|
|
1065
|
+
try {
|
|
1066
|
+
const disposers = MONITOR_ROUTES.map((path) => webServer.register({
|
|
1067
|
+
kind: "exact",
|
|
1068
|
+
path,
|
|
1069
|
+
handler
|
|
1070
|
+
})).filter((off) => typeof off === "function");
|
|
1071
|
+
registered = true;
|
|
1072
|
+
ctx.effect(() => () => {
|
|
1073
|
+
for (const off of disposers) off();
|
|
1074
|
+
}, "contextCompressionSelector.monitor route");
|
|
1075
|
+
log("info", "context-compression monitor route registered (%s): %s", channel, MONITOR_ROUTES.join(", "));
|
|
1076
|
+
} catch (error) {
|
|
1077
|
+
log("warn", "context-compression monitor route registration failed (%s): %o", channel, error);
|
|
1078
|
+
}
|
|
1079
|
+
};
|
|
1080
|
+
const active = asWebServer(readService("webServer"));
|
|
1081
|
+
if (active !== void 0) {
|
|
1082
|
+
register(active, "direct");
|
|
1083
|
+
if (registered) return;
|
|
1084
|
+
}
|
|
1085
|
+
ctx.inject(["webServer"], (injected) => {
|
|
1086
|
+
const webServer = asWebServer(injected.webServer);
|
|
1087
|
+
if (webServer === void 0) {
|
|
1088
|
+
log("warn", "context-compression webServer exposes no register() — monitor route not registered");
|
|
1089
|
+
return;
|
|
1090
|
+
}
|
|
1091
|
+
register(webServer, "inject");
|
|
1092
|
+
});
|
|
1093
|
+
}
|
|
1094
|
+
/**
|
|
931
1095
|
* Resolve one possibly-volatile field: a live ref on 0.1.7+, a plain value
|
|
932
1096
|
* otherwise (0.1.7 hands `.volatile()` fields to `apply()` as live refs).
|
|
933
1097
|
*/
|
|
@@ -951,6 +1115,7 @@ function apply(ctx, config = {}) {
|
|
|
951
1115
|
try {
|
|
952
1116
|
if (config.estimatorCatalogRoute === true) registerEstimatorCatalogRoute(ctx);
|
|
953
1117
|
registerSavingsRoute(ctx);
|
|
1118
|
+
registerMonitorRoute(ctx);
|
|
954
1119
|
if (config.advisorReportRoute === true) registerAdvisorReportRoute(ctx);
|
|
955
1120
|
registerSummaryCommand(ctx);
|
|
956
1121
|
if (config.presetOverlay !== true) return;
|
|
@@ -983,4 +1148,4 @@ function resolveAutoCompactThresholdPercent(config, presetsCtx) {
|
|
|
983
1148
|
}
|
|
984
1149
|
}
|
|
985
1150
|
//#endregion
|
|
986
|
-
export { Config, apply };
|
|
1151
|
+
export { Config, apply, registerMonitorRoute };
|