dsh-context-compression-improved 0.2.4 → 0.2.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/.gitattributes +2 -1
- package/.githooks/pre-push +37 -0
- package/.github/workflows/ci.yml +8 -8
- package/CHANGELOG.ja.md +169 -39
- package/CHANGELOG.ko.md +167 -39
- package/CHANGELOG.md +212 -16
- package/CHANGELOG.zh.md +152 -39
- package/CONTRIBUTING.md +22 -22
- package/README.ja.md +85 -104
- package/README.ko.md +85 -103
- package/README.md +1 -19
- package/README.zh.md +85 -101
- package/THIRD_PARTY_NOTICES.md +14 -14
- package/docs/compat-0.1.5-report.md +77 -0
- package/docs/installation.ja.md +78 -76
- package/docs/installation.ko.md +78 -76
- package/docs/installation.md +103 -76
- package/docs/installation.zh.md +100 -76
- package/docs/repair-log.md +657 -582
- package/eslint.config.js +30 -30
- package/package.json +75 -54
- package/packages/selector/README.md +7 -12
- package/packages/selector/README.zh.md +6 -13
- package/packages/selector/THIRD_PARTY_NOTICES.md +32 -38
- package/packages/selector/cordis.patch.yml +27 -19
- package/packages/selector/dsh.plugin.json +16 -16
- package/packages/selector/lib/client.d.ts +97 -5
- package/packages/selector/lib/client.js +1884 -92
- package/packages/selector/lib/config.js +863 -6
- package/packages/selector/lib/index.d.ts +29 -21
- package/packages/selector/lib/index.js +424 -18
- package/packages/selector/lib/invariant.js +4 -4
- package/packages/selector/lib/pruner.d.ts +179 -4
- package/packages/selector/lib/pruner.js +1406 -371
- package/packages/selector/lib/style.css +42 -0
- package/packages/selector/lib/tail-trim.js +13 -4
- package/packages/selector/package.json +18 -27
- package/packages/selector/screenshots.json +3 -6
- package/packages/selector/src/client/CompressionProfileControls.tsx +293 -229
- package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -170
- package/packages/selector/src/client/CompressionProfileSelector.tsx +85 -79
- package/packages/selector/src/client/EstimatorControls.tsx +277 -281
- package/packages/selector/src/client/decode.ts +57 -49
- package/packages/selector/src/client/index.ts +200 -62
- package/packages/selector/src/client/locales/de.ts +141 -0
- package/packages/selector/src/client/locales/es.ts +141 -0
- package/packages/selector/src/client/locales/fr.ts +141 -0
- package/packages/selector/src/client/locales/it.ts +141 -0
- package/packages/selector/src/client/locales/ja.ts +141 -0
- package/packages/selector/src/client/locales/ko.ts +141 -0
- package/packages/selector/src/client/locales/ru.ts +141 -0
- package/packages/selector/src/client/locales.ts +282 -198
- package/packages/selector/src/client/monitor-fab.ts +336 -0
- package/packages/selector/src/client/preset-options.ts +88 -70
- package/packages/selector/src/client/savings-card.tsx +150 -0
- package/packages/selector/src/client/settings-section.tsx +140 -126
- package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -210
- package/packages/selector/src/index.ts +671 -327
- package/packages/selector/src/invariant.ts +113 -113
- package/packages/selector/src/profiles.ts +431 -342
- package/packages/selector/src/pruner/state.ts +57 -43
- package/packages/selector/src/pruner.ts +2736 -2154
- package/packages/selector/src/runtime/audit.ts +303 -231
- package/packages/selector/src/runtime/config.ts +756 -642
- package/packages/selector/src/runtime/measurement.ts +436 -432
- package/packages/selector/src/runtime/monitor.ts +235 -0
- package/packages/selector/src/runtime/retrieve.ts +479 -457
- package/packages/selector/src/runtime/savings.ts +337 -0
- package/packages/selector/src/runtime/session-events.ts +30 -17
- package/packages/selector/src/runtime/summary-command.ts +127 -0
- package/packages/selector/src/runtime/tail-trim.ts +166 -166
- package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -0
- package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -0
- package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -0
- package/packages/selector/src/runtime/tokenpilot/benefit.ts +200 -0
- package/packages/selector/src/runtime/tokenpilot/estimator.ts +151 -183
- package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
- package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
- package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
- package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
- package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +303 -275
- package/packages/selector/src/runtime/types.ts +365 -325
- package/packages/selector/tests/advisor-report.host.spec.ts +223 -0
- package/packages/selector/tests/auto-compact.client.spec.tsx +214 -226
- package/packages/selector/tests/built/client-artifact.spec.ts +59 -51
- package/packages/selector/tests/code-skeleton.client.spec.ts +91 -88
- package/packages/selector/tests/custom-contract.client.spec.ts +205 -202
- package/packages/selector/tests/estimator-channel.client.spec.tsx +253 -247
- package/packages/selector/tests/estimator-route-registration.host.spec.ts +194 -176
- package/packages/selector/tests/host-preset-overlay.host.spec.ts +206 -204
- package/packages/selector/tests/monitor-fab.client.spec.ts +138 -0
- package/packages/selector/tests/preset-options-write.client.spec.ts +207 -181
- package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +201 -196
- package/packages/selector/tests/preset-overlay.host.spec.ts +8 -18
- package/packages/selector/tests/profiles.client.spec.tsx +436 -434
- package/packages/selector/tests/public/package-contract.client.spec.ts +78 -33
- package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +232 -0
- package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -0
- package/packages/selector/tests/runtime/advisor.spec.ts +226 -0
- package/packages/selector/tests/runtime/audit.spec.ts +275 -172
- package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +96 -0
- package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
- package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
- package/packages/selector/tests/runtime/monitor.spec.ts +301 -0
- package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2724 -2702
- package/packages/selector/tests/runtime/savings.spec.ts +120 -0
- package/packages/selector/tests/runtime/session-events.spec.ts +27 -27
- package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
- package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +217 -0
- package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +79 -56
- package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +116 -100
- package/packages/selector/tests/settings-seat.client.spec.ts +130 -0
- package/packages/selector/tests/standing-generation.host.spec.ts +142 -87
- package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +253 -250
- package/pnpm-workspace.yaml +66 -19
- package/scripts/capture-profile-baseline.mjs +42 -0
- package/scripts/generate-tokenizer-fixtures.py +81 -81
- package/scripts/generate-vision-fixtures.py +208 -208
- package/scripts/{packed-components-smoke.ts → packed-components-smoke.mjs} +732 -713
- package/scripts/{packed-install-e2e.ts → packed-install-e2e.mjs} +1273 -1072
- package/scripts/toolclass-corpus-replay.mjs +281 -273
- package/scripts/{verify-release.ts → verify-release.mjs} +318 -300
- package/tests/TEST_INVENTORY.md +41 -42
- package/scripts/capture-profile-baseline.ts +0 -80
- package/tsconfig.scripts.json +0 -13
- /package/{packages/selector/assets/screenshots → docs/assets}/context-compression-selector-profiles.jpg +0 -0
- /package/{packages/selector/assets/screenshots → docs/assets}/context-compression-selector-settings.png +0 -0
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { _ as assertNever, a as PRUNE_MARKER, c as codePointLength, d as parseContextCompressionSettings, f as resolveConfig, g as resolveCustomPolicy, h as DEFAULT_CUSTOM_COMPRESSION_POLICY, i as DEFAULTS, l as isCompressionProfile, m as CustomCompressionPolicySchema, n as CONTEXT_COMPRESSION_SETTINGS_NAMESPACE, o as charsForTokens, p as resolvePolicy, r as ContextCompressionSettingsSchema, s as charsToTokens, t as AUTO_COMPACT_THRESHOLD_LIMITS, u as isValidAutoCompactThresholdPercent, v as deepFreeze, y as COMPRESSION_PROFILES } from "./config.js";
|
|
2
|
-
import { a as validatePublishedTailTrim, i as tailTrimStub, n as tailTrimMessage, o as
|
|
1
|
+
import { B as priceOfficialDeepSeekUsage, D as evaluateIntentGate, F as recordRecertified, H as getSavingsLedger, I as recordScore, M as invalidateOnTaskChange, N as observeIntentEnabled, O as getAdvisorState, P as recordIntentFold, R as DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION, V as resolveOfficialDeepSeekPrice, _ as assertNever, a as PRUNE_MARKER, c as codePointLength, d as parseContextCompressionSettings, f as resolveConfig, g as resolveCustomPolicy, h as DEFAULT_CUSTOM_COMPRESSION_POLICY, i as DEFAULTS, j as getSummaryOverride, l as isCompressionProfile, m as CustomCompressionPolicySchema, n as CONTEXT_COMPRESSION_SETTINGS_NAMESPACE, o as charsForTokens, p as resolvePolicy, r as ContextCompressionSettingsSchema, s as charsToTokens, t as AUTO_COMPACT_THRESHOLD_LIMITS, u as isValidAutoCompactThresholdPercent, v as deepFreeze, w as observeContextUsage, y as COMPRESSION_PROFILES, z as decimalRateNanoUnits } from "./config.js";
|
|
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";
|
|
5
5
|
import { Service } from "@deepseek-ai/cordis";
|
|
6
6
|
import { createUserMessage, freezeMessage } from "@deepseek-ai/dsh-llm";
|
|
7
|
-
import { deriveEventMessage } from "@deepseek-ai/dsh-session";
|
|
7
|
+
import { SessionSeq, deriveEventMessage } from "@deepseek-ai/dsh-session";
|
|
8
8
|
import { readFileSync } from "node:fs";
|
|
9
9
|
import { Tokenizer } from "@huggingface/tokenizers";
|
|
10
10
|
import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
@@ -45,11 +45,6 @@ const DEEPSEEK_VISION_TOKENIZER_ARTIFACT = Object.freeze({
|
|
|
45
45
|
* Every bundled artifact is registered with independent asset roots, integrity
|
|
46
46
|
* manifests, and cache entries: one corrupted artifact must never disable the
|
|
47
47
|
* tokenizer serving the other model family.
|
|
48
|
-
*
|
|
49
|
-
* This module deliberately sits at the package's `src/` root rather than in
|
|
50
|
-
* `src/runtime/`: the build flattens the runtime into `lib/*.js`, so only a
|
|
51
|
-
* module one level below the package root resolves `../assets/` identically
|
|
52
|
-
* from source and from the published artifact.
|
|
53
48
|
*/
|
|
54
49
|
const ARTIFACTS = Object.freeze([Object.freeze({
|
|
55
50
|
origin: DEEPSEEK_V4_TOKENIZER_ARTIFACT,
|
|
@@ -501,8 +496,9 @@ function measureForCompaction(ctx, session) {
|
|
|
501
496
|
const target = header?.config;
|
|
502
497
|
const counter = bindCounter(target?.provider, target?.model);
|
|
503
498
|
const events = sessionEvents(session);
|
|
499
|
+
const eventsBySeq = new Map(events.map((event) => [Number(event.seq), event]));
|
|
504
500
|
const measuredNodes = measurement.nodes.map((node) => {
|
|
505
|
-
const event =
|
|
501
|
+
const event = eventsBySeq.get(Number(node.seq));
|
|
506
502
|
if (event === void 0) return {
|
|
507
503
|
seq: node.seq,
|
|
508
504
|
count: unavailableTokenCount(`surface node ${String(node.seq)} is missing`),
|
|
@@ -539,6 +535,10 @@ function measureForCompaction(ctx, session) {
|
|
|
539
535
|
countCanonicalText: counter.countText
|
|
540
536
|
});
|
|
541
537
|
}
|
|
538
|
+
/** Request-level usage exposed by official TokenMeter, without invented route attribution. */
|
|
539
|
+
function officialRequestUsage(view) {
|
|
540
|
+
return view.baseline.kind === "usage" ? view.baseline.usage : void 0;
|
|
541
|
+
}
|
|
542
542
|
/**
|
|
543
543
|
* Count one canonical content walk in canonical field order.
|
|
544
544
|
*
|
|
@@ -800,11 +800,23 @@ function installContextCompressionRetrieve(ctx, config = {}) {
|
|
|
800
800
|
const tailTrimRef = parseTailTrimRef(args.ref);
|
|
801
801
|
if (match === null && tailTrimRef === null) throw new Error("context_compression_retrieve: ref must be session://<session-id>/(event|tailtrim)/<seq>");
|
|
802
802
|
if ((match?.[1] ?? tailTrimRef?.sessionId) !== String(exec.agent.id)) throw new Error("context_compression_retrieve: a compression reference may only read the caller's current session");
|
|
803
|
-
if (tailTrimRef !== null)
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
803
|
+
if (tailTrimRef !== null) {
|
|
804
|
+
const sessionId = String(exec.agent.id);
|
|
805
|
+
return Promise.resolve(recoverTailTrim(exec.agent.session, args.ref, tailTrimRef.manifestSeq, args.query, args.start_line, args.max_lines, {
|
|
806
|
+
maxChars,
|
|
807
|
+
maxScanChars,
|
|
808
|
+
maxQueryChars
|
|
809
|
+
})).then((text) => {
|
|
810
|
+
getSavingsLedger().recordOffset({
|
|
811
|
+
sessionId,
|
|
812
|
+
component: "tailtrim-retrieve",
|
|
813
|
+
tokens: Math.ceil(codePointLength$1(text) / 4),
|
|
814
|
+
basis: "characters",
|
|
815
|
+
note: `tailtrim/${tailTrimRef.manifestSeq} 回读`
|
|
816
|
+
});
|
|
817
|
+
return text;
|
|
818
|
+
});
|
|
819
|
+
}
|
|
808
820
|
const seq = Number(match?.[2]);
|
|
809
821
|
const event = sessionEvents(exec.agent.session)[seq];
|
|
810
822
|
if (event?.type !== "tool/result") throw new Error(`context_compression_retrieve: event ${String(seq)} is not a tool/result in the current session`);
|
|
@@ -816,7 +828,7 @@ function installContextCompressionRetrieve(ctx, config = {}) {
|
|
|
816
828
|
if (query !== void 0 && exceedsCodePointLimit(query, maxQueryChars)) throw new Error(`context_compression_retrieve: query must be at most ${String(maxQueryChars)} Unicode code points`);
|
|
817
829
|
const selected = query === void 0 || query === "" ? directSlice(lines, args.start_line ?? 1, maxLines, scan.complete, scannedLines.partialTail) : querySlice(lines, query, maxLines, scan.complete, scannedLines.partialTail);
|
|
818
830
|
const total = scan.complete ? String(lines.length) : `at least ${String(lines.length)}`;
|
|
819
|
-
const
|
|
831
|
+
const bounded = boundCodePoints(`${[
|
|
820
832
|
`source: ${args.ref}`,
|
|
821
833
|
`tool_call_id: ${event.data.message.source.callId}`,
|
|
822
834
|
`status: ${event.data.message.content[0].isError === true ? "error" : "completed"}`,
|
|
@@ -825,8 +837,15 @@ function installContextCompressionRetrieve(ctx, config = {}) {
|
|
|
825
837
|
selected.partialLine === void 0 ? "" : `note: line ${String(selected.partialLine)} is a partial prefix ending at the source scan limit`,
|
|
826
838
|
selected.omitted ? query === void 0 || query === "" ? "note: additional source lines were omitted" : "note: additional matching or neighboring lines were omitted" : "",
|
|
827
839
|
"--- original tool result ---"
|
|
828
|
-
].filter(Boolean).join("\n")}\n${selected.text}
|
|
829
|
-
|
|
840
|
+
].filter(Boolean).join("\n")}\n${selected.text}`, maxChars);
|
|
841
|
+
getSavingsLedger().recordOffset({
|
|
842
|
+
sessionId: String(exec.agent.id),
|
|
843
|
+
component: "retrieve",
|
|
844
|
+
tokens: Math.ceil(codePointLength$1(bounded) / 4),
|
|
845
|
+
basis: "characters",
|
|
846
|
+
note: `event/${String(seq)} 回读`
|
|
847
|
+
});
|
|
848
|
+
return Promise.resolve(bounded);
|
|
830
849
|
}
|
|
831
850
|
}));
|
|
832
851
|
}
|
|
@@ -1408,7 +1427,7 @@ function reduceFreshToolResult(input, ranking) {
|
|
|
1408
1427
|
lines: normalized.folded,
|
|
1409
1428
|
contentText: normalized.contentText
|
|
1410
1429
|
};
|
|
1411
|
-
const command = extractCommand(input.argumentsText);
|
|
1430
|
+
const command = extractCommand$1(input.argumentsText);
|
|
1412
1431
|
const name = input.toolName.toLowerCase();
|
|
1413
1432
|
const toolClass = classifyToolSource(input.toolName, command, normalized.contentText);
|
|
1414
1433
|
const readTocFirst = toolClass === "read" && codePointLength(normalized.contentText) >= READ_TOC_MIN_CHARS;
|
|
@@ -2691,7 +2710,7 @@ function splitLines(text) {
|
|
|
2691
2710
|
* @param argumentsText - raw JSON arguments of the tool call.
|
|
2692
2711
|
* @returns the command string, or '' when absent.
|
|
2693
2712
|
*/
|
|
2694
|
-
function extractCommand(argumentsText) {
|
|
2713
|
+
function extractCommand$1(argumentsText) {
|
|
2695
2714
|
try {
|
|
2696
2715
|
const parsed = JSON.parse(argumentsText);
|
|
2697
2716
|
if (typeof parsed !== "object" || parsed === null) return "";
|
|
@@ -2809,72 +2828,81 @@ function documentCensus(text, omittedLines) {
|
|
|
2809
2828
|
return `${String(omittedLines)} lines omitted (sections: ${summary})`;
|
|
2810
2829
|
}
|
|
2811
2830
|
//#endregion
|
|
2812
|
-
//#region src/runtime/tokenpilot/
|
|
2813
|
-
/**
|
|
2814
|
-
|
|
2815
|
-
return Math.min(3e5, 1e3 * 2 ** Math.max(0, failures - 1));
|
|
2816
|
-
}
|
|
2817
|
-
function isCoolingDown(state, now) {
|
|
2818
|
-
return state !== void 0 && state.cooldownUntil > now;
|
|
2819
|
-
}
|
|
2820
|
-
function buildEstimatorSystemPrompt() {
|
|
2821
|
-
return [
|
|
2822
|
-
"You are a session residual-utility estimator.",
|
|
2823
|
-
"For each numbered historical file read, decide whether the live agent is likely to",
|
|
2824
|
-
"reference that exact file state again later in the session. Reads whose file was",
|
|
2825
|
-
"already rewritten, or whose task has visibly moved on, are expired.",
|
|
2826
|
-
"Answer with ONLY a JSON array: [{\"seq\":<number>,\"expired\":<boolean>}]."
|
|
2827
|
-
].join(" ");
|
|
2828
|
-
}
|
|
2829
|
-
function buildEstimatorUserPrompt(samples) {
|
|
2830
|
-
return samples.map((sample) => `{"seq":${String(sample.seq)},"path":${JSON.stringify(sample.path)},"turn":${String(sample.turn)}}`).join("\n");
|
|
2831
|
-
}
|
|
2832
|
-
/** Parse the estimator answer; anything malformed yields no verdicts. */
|
|
2833
|
-
function parseEstimatorAnswer(text) {
|
|
2834
|
-
const start = text.indexOf("[");
|
|
2835
|
-
const end = text.lastIndexOf("]");
|
|
2836
|
-
if (start < 0 || end <= start) return [];
|
|
2837
|
-
try {
|
|
2838
|
-
const parsed = JSON.parse(text.slice(start, end + 1));
|
|
2839
|
-
if (!Array.isArray(parsed)) return [];
|
|
2840
|
-
const verdicts = [];
|
|
2841
|
-
for (const entry of parsed) {
|
|
2842
|
-
if (typeof entry !== "object" || entry === null) continue;
|
|
2843
|
-
const record = entry;
|
|
2844
|
-
if (typeof record.seq !== "number" || typeof record.expired !== "boolean") continue;
|
|
2845
|
-
verdicts.push({
|
|
2846
|
-
seq: record.seq,
|
|
2847
|
-
expired: record.expired
|
|
2848
|
-
});
|
|
2849
|
-
}
|
|
2850
|
-
return verdicts;
|
|
2851
|
-
} catch {
|
|
2852
|
-
return [];
|
|
2853
|
-
}
|
|
2854
|
-
}
|
|
2855
|
-
/** One channel-bound estimator. `ask` resolves undefined on any failure. */
|
|
2856
|
-
var Estimator = class {
|
|
2831
|
+
//#region src/runtime/tokenpilot/sidechannel.ts
|
|
2832
|
+
/** One bound side channel. `ask` resolves `undefined` on ANY failure. */
|
|
2833
|
+
var SideChannel = class {
|
|
2857
2834
|
ctx;
|
|
2858
2835
|
options;
|
|
2859
|
-
|
|
2836
|
+
overrides;
|
|
2837
|
+
/**
|
|
2838
|
+
* @param overrides - per-consumer overrides of the estimator-named options.
|
|
2839
|
+
* The estimator itself never passes them (byte-identical behavior); the
|
|
2840
|
+
* advisory advisor passes its own mode/timeout/output budget so both
|
|
2841
|
+
* consumers share one transport without sharing one configuration.
|
|
2842
|
+
*/
|
|
2843
|
+
constructor(ctx, options, overrides) {
|
|
2860
2844
|
this.ctx = ctx;
|
|
2861
2845
|
this.options = options;
|
|
2846
|
+
this.overrides = overrides;
|
|
2847
|
+
}
|
|
2848
|
+
get mode() {
|
|
2849
|
+
return this.overrides?.mode ?? this.options.estimatorMode ?? "";
|
|
2862
2850
|
}
|
|
2863
2851
|
get enabled() {
|
|
2864
|
-
return this.
|
|
2852
|
+
return this.mode === "host" || this.mode === "direct";
|
|
2865
2853
|
}
|
|
2866
|
-
async ask(
|
|
2867
|
-
const timeoutMs = this.options.estimatorTimeoutMs ?? 3e3;
|
|
2854
|
+
async ask(request) {
|
|
2855
|
+
const timeoutMs = this.overrides?.timeoutMs ?? this.options.estimatorTimeoutMs ?? 3e3;
|
|
2868
2856
|
const timeout = AbortSignal.timeout(timeoutMs);
|
|
2869
|
-
const
|
|
2857
|
+
const signal = typeof AbortSignal.any === "function" ? AbortSignal.any([request.signal, timeout]) : timeout;
|
|
2870
2858
|
try {
|
|
2871
|
-
if (this.
|
|
2872
|
-
if (this.
|
|
2859
|
+
if (this.mode === "host") return await this.askHost(request.system, request.user, signal);
|
|
2860
|
+
if (this.mode === "direct") return await this.askDirect(request.system, request.user, signal);
|
|
2873
2861
|
return;
|
|
2874
2862
|
} catch {
|
|
2875
2863
|
return;
|
|
2876
2864
|
}
|
|
2877
2865
|
}
|
|
2866
|
+
/** Failure-open wrapper that also records one audit record per call. */
|
|
2867
|
+
async askAudited(request) {
|
|
2868
|
+
const now = Date.now();
|
|
2869
|
+
const text = await this.ask(request);
|
|
2870
|
+
const audit = {
|
|
2871
|
+
ok: text !== void 0,
|
|
2872
|
+
latencyMs: Date.now() - now,
|
|
2873
|
+
...this.identity() !== void 0 ? { channel: this.identity() } : {},
|
|
2874
|
+
...text === void 0 ? { reason: "channel returned no content (timeout, non-2xx, parse failure, or reasoning ate the output-token budget)" } : {}
|
|
2875
|
+
};
|
|
2876
|
+
return {
|
|
2877
|
+
...text === void 0 ? {} : { text },
|
|
2878
|
+
audit
|
|
2879
|
+
};
|
|
2880
|
+
}
|
|
2881
|
+
identity() {
|
|
2882
|
+
if (this.mode === "direct") return `direct:${this.options.estimatorModel ?? ""}`;
|
|
2883
|
+
if (this.mode === "host") {
|
|
2884
|
+
const route = this.resolveHostRoute();
|
|
2885
|
+
return route === void 0 ? "host" : `host:${route.provider}/${route.model}`;
|
|
2886
|
+
}
|
|
2887
|
+
}
|
|
2888
|
+
/** Same host-route resolution as the estimator: explicit, then host default. */
|
|
2889
|
+
resolveHostRoute() {
|
|
2890
|
+
const provider = this.options.estimatorProvider ?? "";
|
|
2891
|
+
const model = this.options.estimatorModel ?? "";
|
|
2892
|
+
if (provider.length > 0 && model.length > 0) return {
|
|
2893
|
+
provider,
|
|
2894
|
+
model
|
|
2895
|
+
};
|
|
2896
|
+
try {
|
|
2897
|
+
const selected = this.ctx.get("agentDefaultModel")?.currentSelection?.();
|
|
2898
|
+
const selectedProvider = selected?.provider ?? "";
|
|
2899
|
+
const selectedModel = selected?.model ?? "";
|
|
2900
|
+
if (selectedProvider.length > 0 && selectedModel.length > 0) return {
|
|
2901
|
+
provider: provider.length > 0 ? provider : selectedProvider,
|
|
2902
|
+
model: model.length > 0 ? model : selectedModel
|
|
2903
|
+
};
|
|
2904
|
+
} catch {}
|
|
2905
|
+
}
|
|
2878
2906
|
async askHost(system, user, signal) {
|
|
2879
2907
|
let llm;
|
|
2880
2908
|
try {
|
|
@@ -2883,13 +2911,12 @@ var Estimator = class {
|
|
|
2883
2911
|
return;
|
|
2884
2912
|
}
|
|
2885
2913
|
if (llm?.stream === void 0) return void 0;
|
|
2886
|
-
const
|
|
2887
|
-
|
|
2888
|
-
if (provider.length === 0 || model.length === 0) return void 0;
|
|
2914
|
+
const route = this.resolveHostRoute();
|
|
2915
|
+
if (route === void 0) return void 0;
|
|
2889
2916
|
let text = "";
|
|
2890
2917
|
const stream = llm.stream({
|
|
2891
|
-
provider,
|
|
2892
|
-
model,
|
|
2918
|
+
provider: route.provider,
|
|
2919
|
+
model: route.model,
|
|
2893
2920
|
messages: [{
|
|
2894
2921
|
role: "user",
|
|
2895
2922
|
content: [{
|
|
@@ -2900,10 +2927,10 @@ var Estimator = class {
|
|
|
2900
2927
|
system,
|
|
2901
2928
|
temperature: 0,
|
|
2902
2929
|
reasoningEffort: "off",
|
|
2903
|
-
maxTokens: 256,
|
|
2930
|
+
maxTokens: this.overrides?.maxTokens ?? 256,
|
|
2904
2931
|
signal
|
|
2905
2932
|
});
|
|
2906
|
-
for await (const chunk of stream) if (
|
|
2933
|
+
for await (const chunk of stream) if (chunk.type === "text-delta" && typeof chunk.text === "string") text += chunk.text;
|
|
2907
2934
|
else if (chunk.type === "finish" && chunk.text === void 0) break;
|
|
2908
2935
|
return text.trim().length > 0 ? text : void 0;
|
|
2909
2936
|
}
|
|
@@ -2927,7 +2954,7 @@ var Estimator = class {
|
|
|
2927
2954
|
content: user
|
|
2928
2955
|
}],
|
|
2929
2956
|
temperature: 0,
|
|
2930
|
-
max_tokens: 256
|
|
2957
|
+
max_tokens: this.overrides?.maxTokens ?? 256
|
|
2931
2958
|
}),
|
|
2932
2959
|
signal
|
|
2933
2960
|
});
|
|
@@ -2937,6 +2964,813 @@ var Estimator = class {
|
|
|
2937
2964
|
}
|
|
2938
2965
|
};
|
|
2939
2966
|
//#endregion
|
|
2967
|
+
//#region src/runtime/tokenpilot/estimator.ts
|
|
2968
|
+
/** Exponential backoff with a 5-minute cap: 1s, 2s, 4s, … */
|
|
2969
|
+
function backoffCooldownMs(failures) {
|
|
2970
|
+
return Math.min(3e5, 1e3 * 2 ** Math.max(0, failures - 1));
|
|
2971
|
+
}
|
|
2972
|
+
function isCoolingDown(state, now) {
|
|
2973
|
+
return state !== void 0 && state.cooldownUntil > now;
|
|
2974
|
+
}
|
|
2975
|
+
function buildEstimatorSystemPrompt() {
|
|
2976
|
+
return [
|
|
2977
|
+
"You are a session residual-utility estimator.",
|
|
2978
|
+
"For each numbered historical file read, decide whether the live agent is likely to",
|
|
2979
|
+
"reference that exact file state again later in the session. Reads whose file was",
|
|
2980
|
+
"already rewritten, or whose task has visibly moved on, are expired.",
|
|
2981
|
+
"Answer with ONLY a JSON array: [{\"seq\":<number>,\"expired\":<boolean>}].",
|
|
2982
|
+
"Optionally, if you can estimate how many user turns remain in this session, answer",
|
|
2983
|
+
"with {\"expectedRemainingTurns\":<number>,\"items\":[{\"seq\":<number>,\"expired\":<boolean>}]}",
|
|
2984
|
+
"instead; omit the field when you cannot estimate it."
|
|
2985
|
+
].join(" ");
|
|
2986
|
+
}
|
|
2987
|
+
function buildEstimatorUserPrompt(samples) {
|
|
2988
|
+
return samples.map((sample) => `{"seq":${String(sample.seq)},"path":${JSON.stringify(sample.path)},"turn":${String(sample.turn)}}`).join("\n");
|
|
2989
|
+
}
|
|
2990
|
+
function parseVerdictArray(value) {
|
|
2991
|
+
if (!Array.isArray(value)) return [];
|
|
2992
|
+
const verdicts = [];
|
|
2993
|
+
for (const entry of value) {
|
|
2994
|
+
if (typeof entry !== "object" || entry === null) continue;
|
|
2995
|
+
const record = entry;
|
|
2996
|
+
if (typeof record.seq !== "number" || typeof record.expired !== "boolean") continue;
|
|
2997
|
+
verdicts.push({
|
|
2998
|
+
seq: record.seq,
|
|
2999
|
+
expired: record.expired
|
|
3000
|
+
});
|
|
3001
|
+
}
|
|
3002
|
+
return verdicts;
|
|
3003
|
+
}
|
|
3004
|
+
/**
|
|
3005
|
+
* Parse the estimator answer including the optional session-level
|
|
3006
|
+
* `expectedRemainingTurns`. Accepts both the legacy bare verdict array and the
|
|
3007
|
+
* extended object form; anything malformed yields no verdicts and no Ŝ.
|
|
3008
|
+
*/
|
|
3009
|
+
function parseEstimatorAnswerDetailed(text) {
|
|
3010
|
+
const objectStart = text.indexOf("{");
|
|
3011
|
+
const objectEnd = text.lastIndexOf("}");
|
|
3012
|
+
if (objectStart >= 0 && objectEnd > objectStart) try {
|
|
3013
|
+
const parsed = JSON.parse(text.slice(objectStart, objectEnd + 1));
|
|
3014
|
+
if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
|
|
3015
|
+
const record = parsed;
|
|
3016
|
+
const verdicts = parseVerdictArray(record.verdicts ?? record.items);
|
|
3017
|
+
if (verdicts.length > 0) {
|
|
3018
|
+
const turns = record.expectedRemainingTurns;
|
|
3019
|
+
if (typeof turns === "number" && Number.isFinite(turns) && turns >= 0) return {
|
|
3020
|
+
verdicts,
|
|
3021
|
+
expectedRemainingTurns: Math.floor(turns)
|
|
3022
|
+
};
|
|
3023
|
+
return { verdicts };
|
|
3024
|
+
}
|
|
3025
|
+
}
|
|
3026
|
+
} catch {}
|
|
3027
|
+
const start = text.indexOf("[");
|
|
3028
|
+
const end = text.lastIndexOf("]");
|
|
3029
|
+
if (start < 0 || end <= start) return { verdicts: [] };
|
|
3030
|
+
try {
|
|
3031
|
+
return { verdicts: parseVerdictArray(JSON.parse(text.slice(start, end + 1))) };
|
|
3032
|
+
} catch {
|
|
3033
|
+
return { verdicts: [] };
|
|
3034
|
+
}
|
|
3035
|
+
}
|
|
3036
|
+
/** One channel-bound estimator. `ask` resolves undefined on any failure. */
|
|
3037
|
+
var Estimator = class {
|
|
3038
|
+
ctx;
|
|
3039
|
+
options;
|
|
3040
|
+
channel;
|
|
3041
|
+
constructor(ctx, options) {
|
|
3042
|
+
this.ctx = ctx;
|
|
3043
|
+
this.options = options;
|
|
3044
|
+
this.channel = new SideChannel(ctx, options);
|
|
3045
|
+
}
|
|
3046
|
+
get enabled() {
|
|
3047
|
+
return this.options.estimatorMode === "host" || this.options.estimatorMode === "direct";
|
|
3048
|
+
}
|
|
3049
|
+
async ask(system, user, signal) {
|
|
3050
|
+
return this.channel.ask({
|
|
3051
|
+
system,
|
|
3052
|
+
user,
|
|
3053
|
+
signal
|
|
3054
|
+
});
|
|
3055
|
+
}
|
|
3056
|
+
};
|
|
3057
|
+
//#endregion
|
|
3058
|
+
//#region src/runtime/tokenpilot/benefit.ts
|
|
3059
|
+
/**
|
|
3060
|
+
* Shipped defaults of the advisory model. They are constants rather than
|
|
3061
|
+
* settings keys because the machine no longer acts on them: after the review
|
|
3062
|
+
* gate was retired these numbers only shape a label, so exposing them as
|
|
3063
|
+
* tunable configuration would advertise a control that changes no behavior.
|
|
3064
|
+
*/
|
|
3065
|
+
const DEFAULT_ADVICE_ALPHA = .1;
|
|
3066
|
+
const DEFAULT_ADVICE_HIGH_IMPACT_TOKENS = 4e3;
|
|
3067
|
+
/**
|
|
3068
|
+
* Aggregate the batch-level benefit of a set of reduction candidates.
|
|
3069
|
+
*
|
|
3070
|
+
* Individual candidates whose replacement would grow the context contribute
|
|
3071
|
+
* zero recovery (they never make a batch look better than dropping them).
|
|
3072
|
+
*/
|
|
3073
|
+
function computeBenefit(candidates, input) {
|
|
3074
|
+
const { alpha, tailTokens, remainingTurns } = input;
|
|
3075
|
+
let recoveredTokens = 0;
|
|
3076
|
+
for (const candidate of candidates) recoveredTokens += Math.max(0, candidate.tokensBefore - candidate.tokensAfter);
|
|
3077
|
+
const penaltyTokens = input.refillPenaltyExempt === true ? 0 : (1 - alpha) * tailTokens;
|
|
3078
|
+
const perTurnSaving = alpha * recoveredTokens;
|
|
3079
|
+
if (perTurnSaving <= 0) return remainingTurns === void 0 ? {
|
|
3080
|
+
recoveredTokens,
|
|
3081
|
+
penaltyTokens
|
|
3082
|
+
} : {
|
|
3083
|
+
recoveredTokens,
|
|
3084
|
+
penaltyTokens,
|
|
3085
|
+
expectedSaving: -penaltyTokens
|
|
3086
|
+
};
|
|
3087
|
+
const paybackTurns = penaltyTokens / perTurnSaving;
|
|
3088
|
+
if (remainingTurns === void 0) return {
|
|
3089
|
+
recoveredTokens,
|
|
3090
|
+
penaltyTokens,
|
|
3091
|
+
paybackTurns
|
|
3092
|
+
};
|
|
3093
|
+
return {
|
|
3094
|
+
recoveredTokens,
|
|
3095
|
+
penaltyTokens,
|
|
3096
|
+
paybackTurns,
|
|
3097
|
+
expectedSaving: perTurnSaving * Math.max(0, remainingTurns - paybackTurns)
|
|
3098
|
+
};
|
|
3099
|
+
}
|
|
3100
|
+
/**
|
|
3101
|
+
* Label one batch of planned replacements.
|
|
3102
|
+
*
|
|
3103
|
+
* Pipeline: zero/negative-recovery candidates are priced out first (they never
|
|
3104
|
+
* make a batch look better), the surviving batch is priced once through
|
|
3105
|
+
* `computeBenefit`, and the band is a batch decision — the refill penalty is a
|
|
3106
|
+
* property of the landing event, not of any single candidate, so pricing per
|
|
3107
|
+
* candidate would overstate payback N-fold.
|
|
3108
|
+
*
|
|
3109
|
+
* Band precedence (identical thresholds to the retired triage model):
|
|
3110
|
+
* - α too small to price a payback → `unpriceable`;
|
|
3111
|
+
* - any candidate at `highImpactTokens` → `high-impact`;
|
|
3112
|
+
* - `paybackTurns ≤ 1`, or Ŝ known and `paybackTurns ≤ 0.25·Ŝ` → `profitable`;
|
|
3113
|
+
* - Ŝ known and `paybackTurns ∈ (1, 3]` → `slow-payback`;
|
|
3114
|
+
* - everything else → `not-worth-it`.
|
|
3115
|
+
*
|
|
3116
|
+
* @param candidates - planned replacements of one pass, in any order.
|
|
3117
|
+
* @param input - pricing inputs and the stage of the batch.
|
|
3118
|
+
* @returns the advice, or `undefined` when nothing carried a positive recovery.
|
|
3119
|
+
*/
|
|
3120
|
+
function adviseCandidates(candidates, input) {
|
|
3121
|
+
const usable = [];
|
|
3122
|
+
for (const candidate of candidates) {
|
|
3123
|
+
if (Math.max(0, candidate.tokensBefore - candidate.tokensAfter) <= 0) continue;
|
|
3124
|
+
usable.push(candidate);
|
|
3125
|
+
}
|
|
3126
|
+
if (usable.length === 0) return void 0;
|
|
3127
|
+
const benefit = computeBenefit(usable, {
|
|
3128
|
+
alpha: input.alpha,
|
|
3129
|
+
tailTokens: input.tailTokens,
|
|
3130
|
+
...input.remainingTurns !== void 0 ? { remainingTurns: input.remainingTurns } : {},
|
|
3131
|
+
refillPenaltyExempt: input.stage === "fresh"
|
|
3132
|
+
});
|
|
3133
|
+
const payback = benefit.paybackTurns;
|
|
3134
|
+
const maxTokensBefore = usable.reduce((max, candidate) => Math.max(max, candidate.tokensBefore), 0);
|
|
3135
|
+
return {
|
|
3136
|
+
band: payback === void 0 ? "unpriceable" : maxTokensBefore >= input.highImpactTokens ? "high-impact" : payback <= 1 || input.remainingTurns !== void 0 && payback <= .25 * input.remainingTurns ? "profitable" : input.remainingTurns !== void 0 && payback <= 3 ? "slow-payback" : "not-worth-it",
|
|
3137
|
+
benefit,
|
|
3138
|
+
priced: usable.length,
|
|
3139
|
+
maxTokensBefore
|
|
3140
|
+
};
|
|
3141
|
+
}
|
|
3142
|
+
//#endregion
|
|
3143
|
+
//#region src/runtime/tokenpilot/advisor-prompt.ts
|
|
3144
|
+
function buildAdvisorSummarySystemPrompt() {
|
|
3145
|
+
return [
|
|
3146
|
+
"You summarize what an agent session is working on, for relevance statistics only.",
|
|
3147
|
+
"Input: the session todolist snapshot and a recent tail of assistant narration.",
|
|
3148
|
+
"Answer with ONLY one JSON object:",
|
|
3149
|
+
"{\"overallTask\":\"<one sentence>\",\"activeSubtasks\":[\"<subtask>\"],\"keywords\":[\"<task keyword>\"]}.",
|
|
3150
|
+
"keywords must be 3-10 short distinctive words describing the CURRENT task.",
|
|
3151
|
+
"Never add commentary; never invent tasks that the input does not support."
|
|
3152
|
+
].join(" ");
|
|
3153
|
+
}
|
|
3154
|
+
function buildAdvisorSummaryUserPrompt(taskText, tailText) {
|
|
3155
|
+
return [`todolist:\n${taskText}`, tailText.trim().length > 0 ? `recent tail:\n${tailText.trim()}` : "recent tail: (none)"].join("\n\n");
|
|
3156
|
+
}
|
|
3157
|
+
function buildAdvisorScoringSystemPrompt() {
|
|
3158
|
+
return [
|
|
3159
|
+
"You score how relevant each historical session artifact is to the current task,",
|
|
3160
|
+
"for statistics only. Relevance covers both the artifact content and its comments",
|
|
3161
|
+
"(comment semantics count too). 0 means unrelated, 1 means the live agent will",
|
|
3162
|
+
"very likely need this exact content again.",
|
|
3163
|
+
"Answer with ONLY one JSON object per input line:",
|
|
3164
|
+
"{\"seq\":<number>,\"score\":<number between 0 and 1>,\"reason\":\"<short>\"}",
|
|
3165
|
+
"one per line, same order as the input. Never invent seq values; never add commentary."
|
|
3166
|
+
].join(" ");
|
|
3167
|
+
}
|
|
3168
|
+
function buildAdvisorScoringUserPrompt(taskText, activeSubtasks, candidates) {
|
|
3169
|
+
return [
|
|
3170
|
+
`task: ${taskText.replace(/\s+/gu, " ").slice(0, 600)}`,
|
|
3171
|
+
activeSubtasks.length > 0 ? `active subtasks: ${activeSubtasks.join("; ").slice(0, 300)}` : "active subtasks: (none)",
|
|
3172
|
+
"",
|
|
3173
|
+
...candidates.map((candidate) => `seq=${String(candidate.seq)} | ${candidate.preview.replace(/\s+/gu, " ")}`)
|
|
3174
|
+
].join("\n");
|
|
3175
|
+
}
|
|
3176
|
+
/** Pull the first balanced JSON object out of a possibly chatty answer. */
|
|
3177
|
+
function firstJsonObject(text) {
|
|
3178
|
+
const start = text.indexOf("{");
|
|
3179
|
+
if (start < 0) return void 0;
|
|
3180
|
+
let depth = 0;
|
|
3181
|
+
let inString = false;
|
|
3182
|
+
let escaped = false;
|
|
3183
|
+
for (let index = start; index < text.length; index += 1) {
|
|
3184
|
+
const char = text[index];
|
|
3185
|
+
if (inString) {
|
|
3186
|
+
if (escaped) escaped = false;
|
|
3187
|
+
else if (char === "\\") escaped = true;
|
|
3188
|
+
else if (char === "\"") inString = false;
|
|
3189
|
+
continue;
|
|
3190
|
+
}
|
|
3191
|
+
if (char === "\"") inString = true;
|
|
3192
|
+
else if (char === "{") depth += 1;
|
|
3193
|
+
else if (char === "}") {
|
|
3194
|
+
depth -= 1;
|
|
3195
|
+
if (depth === 0) try {
|
|
3196
|
+
const parsed = JSON.parse(text.slice(start, index + 1));
|
|
3197
|
+
return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
|
|
3198
|
+
} catch {
|
|
3199
|
+
return;
|
|
3200
|
+
}
|
|
3201
|
+
}
|
|
3202
|
+
}
|
|
3203
|
+
}
|
|
3204
|
+
function stringList(value, limit) {
|
|
3205
|
+
if (!Array.isArray(value)) return [];
|
|
3206
|
+
return value.filter((entry) => typeof entry === "string" && entry.trim().length > 0).slice(0, limit).map((entry) => entry.trim());
|
|
3207
|
+
}
|
|
3208
|
+
/**
|
|
3209
|
+
* Parse one summary answer. Fail-open: `undefined` on any malformed or
|
|
3210
|
+
* missing field, so a broken channel can never poison the cached summary.
|
|
3211
|
+
*/
|
|
3212
|
+
function parseAdvisorSummary(text) {
|
|
3213
|
+
if (text === void 0 || text.trim().length === 0) return void 0;
|
|
3214
|
+
const object = firstJsonObject(text);
|
|
3215
|
+
if (object === void 0) return void 0;
|
|
3216
|
+
const overallTask = object.overallTask;
|
|
3217
|
+
if (typeof overallTask !== "string" || overallTask.trim().length === 0) return void 0;
|
|
3218
|
+
const activeSubtasks = stringList(object.activeSubtasks, 12);
|
|
3219
|
+
const keywords = stringList(object.keywords, 12);
|
|
3220
|
+
if (keywords.length === 0 && activeSubtasks.length === 0) return void 0;
|
|
3221
|
+
return {
|
|
3222
|
+
overallTask: overallTask.trim(),
|
|
3223
|
+
activeSubtasks,
|
|
3224
|
+
keywords
|
|
3225
|
+
};
|
|
3226
|
+
}
|
|
3227
|
+
/** Extract every balanced JSON object from a JSON-lines or chatty answer. */
|
|
3228
|
+
function jsonObjects(text) {
|
|
3229
|
+
const objects = [];
|
|
3230
|
+
let depth = 0;
|
|
3231
|
+
let start = -1;
|
|
3232
|
+
let inString = false;
|
|
3233
|
+
let escaped = false;
|
|
3234
|
+
for (let index = 0; index < text.length; index += 1) {
|
|
3235
|
+
const char = text[index];
|
|
3236
|
+
if (inString) {
|
|
3237
|
+
if (escaped) escaped = false;
|
|
3238
|
+
else if (char === "\\") escaped = true;
|
|
3239
|
+
else if (char === "\"") inString = false;
|
|
3240
|
+
continue;
|
|
3241
|
+
}
|
|
3242
|
+
if (char === "\"") inString = true;
|
|
3243
|
+
else if (char === "{") {
|
|
3244
|
+
if (depth === 0) start = index;
|
|
3245
|
+
depth += 1;
|
|
3246
|
+
} else if (char === "}") {
|
|
3247
|
+
depth -= 1;
|
|
3248
|
+
if (depth === 0 && start >= 0) {
|
|
3249
|
+
try {
|
|
3250
|
+
const parsed = JSON.parse(text.slice(start, index + 1));
|
|
3251
|
+
if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) objects.push(parsed);
|
|
3252
|
+
} catch {}
|
|
3253
|
+
start = -1;
|
|
3254
|
+
}
|
|
3255
|
+
}
|
|
3256
|
+
}
|
|
3257
|
+
return objects;
|
|
3258
|
+
}
|
|
3259
|
+
/**
|
|
3260
|
+
* Parse one scoring answer. Fail-open: returns the valid rows it could read
|
|
3261
|
+
* (`undefined` when nothing valid remains) — a partially garbage answer still
|
|
3262
|
+
* contributes its good rows, mirroring the estimator's per-item tolerance.
|
|
3263
|
+
*/
|
|
3264
|
+
function parseAdvisorScores(text, validSeqs) {
|
|
3265
|
+
if (text === void 0 || text.trim().length === 0) return void 0;
|
|
3266
|
+
const scores = /* @__PURE__ */ new Map();
|
|
3267
|
+
for (const object of jsonObjects(text)) {
|
|
3268
|
+
const seq = object.seq;
|
|
3269
|
+
const score = object.score;
|
|
3270
|
+
if (typeof seq !== "number" || !Number.isSafeInteger(seq) || !validSeqs.has(seq)) continue;
|
|
3271
|
+
if (typeof score !== "number" || !Number.isFinite(score) || score < 0 || score > 1) continue;
|
|
3272
|
+
const reason = typeof object.reason === "string" && object.reason.trim().length > 0 ? object.reason.trim() : void 0;
|
|
3273
|
+
scores.set(seq, {
|
|
3274
|
+
seq,
|
|
3275
|
+
score,
|
|
3276
|
+
...reason !== void 0 ? { reason } : {}
|
|
3277
|
+
});
|
|
3278
|
+
}
|
|
3279
|
+
return scores.size > 0 ? scores : void 0;
|
|
3280
|
+
}
|
|
3281
|
+
/** Hard character cap for one intent-summary answer (summary segment only). */
|
|
3282
|
+
const INTENT_SUMMARY_CHAR_CAP = 1600;
|
|
3283
|
+
/**
|
|
3284
|
+
* Intent-summary writer prompts (task_2.3). Input records are already
|
|
3285
|
+
* semantic-role-masked by intent-input-mask.ts: read-class candidates are
|
|
3286
|
+
* one-line "read X" records, keep-class candidates carry skeleton heads and
|
|
3287
|
+
* VERBATIM error lines. The model writes ONLY the summary segment — it never
|
|
3288
|
+
* revoices error lines, and its answer must stay inside the char cap.
|
|
3289
|
+
*/
|
|
3290
|
+
function buildIntentSummarySystemPrompt() {
|
|
3291
|
+
return [
|
|
3292
|
+
"You write one concise intent summary of folded tool results for a coding agent session.",
|
|
3293
|
+
"Input: the session task (todolist) and per-tool slimmed records (read lines, or skeleton heads with verbatim error lines).",
|
|
3294
|
+
`Write ONLY what the agent DID and LEARNED in this span, as flowing prose under ${INTENT_SUMMARY_CHAR_CAP} characters.`,
|
|
3295
|
+
"Mention which files/areas were consulted and what changed, so a later turn can continue without the originals.",
|
|
3296
|
+
"Never invent files, commands, or outcomes absent from the records. Never revoice error lines; they are preserved verbatim elsewhere.",
|
|
3297
|
+
"Answer with ONLY one JSON object: {\"summary\":\"<prose>\"}. Never add commentary."
|
|
3298
|
+
].join(" ");
|
|
3299
|
+
}
|
|
3300
|
+
function buildIntentSummaryUserPrompt(taskText, records, tailText) {
|
|
3301
|
+
const nl = String.fromCharCode(10);
|
|
3302
|
+
return [
|
|
3303
|
+
`task: ${taskText.replace(/\s+/gu, " ").slice(0, 600)}`,
|
|
3304
|
+
records.length > 0 ? `records:${nl}${records.join(nl)}` : "records: (none)",
|
|
3305
|
+
tailText.trim().length > 0 ? `recent tail:${nl}${tailText.trim().slice(0, 1200)}` : "recent tail: (none)"
|
|
3306
|
+
].join("\n\n");
|
|
3307
|
+
}
|
|
3308
|
+
/** Fail-open parse of one intent-summary answer; `undefined` on any malformed shape. */
|
|
3309
|
+
function parseIntentSummaryAnswer(text) {
|
|
3310
|
+
const parsed = firstJsonObject(text);
|
|
3311
|
+
if (parsed === void 0) return void 0;
|
|
3312
|
+
const summary = parsed.summary;
|
|
3313
|
+
if (typeof summary !== "string" || summary.trim().length === 0) return void 0;
|
|
3314
|
+
if (summary.length > 3200) return void 0;
|
|
3315
|
+
return { summary: summary.trim().slice(0, INTENT_SUMMARY_CHAR_CAP) };
|
|
3316
|
+
}
|
|
3317
|
+
//#endregion
|
|
3318
|
+
//#region src/runtime/tokenpilot/advisor.ts
|
|
3319
|
+
/** Character cap for the recent-text fallback and the tail-text summary input. */
|
|
3320
|
+
const TAIL_TEXT_CHAR_BUDGET = 4e3;
|
|
3321
|
+
/** Score the advisor assigns to candidates it has no answer for. */
|
|
3322
|
+
const NEUTRAL_RELEVANCE = .5;
|
|
3323
|
+
/** Deterministic djb2-derived hex digest for task-semantics versioning. */
|
|
3324
|
+
function versionDigest(text) {
|
|
3325
|
+
let hash = 5381;
|
|
3326
|
+
for (let index = 0; index < text.length; index += 1) hash = (hash * 33 ^ text.charCodeAt(index)) >>> 0;
|
|
3327
|
+
return hash.toString(16).padStart(8, "0");
|
|
3328
|
+
}
|
|
3329
|
+
/** Truncate on the character basis (Unicode code points), never UTF-16 units. */
|
|
3330
|
+
function truncateChars(text, budget) {
|
|
3331
|
+
if (codePointLength(text) <= budget) return text;
|
|
3332
|
+
return Array.from(text).slice(0, budget).join("");
|
|
3333
|
+
}
|
|
3334
|
+
/** Character cap of one candidate preview line offered to the scoring prompt. */
|
|
3335
|
+
const PREVIEW_CHAR_BUDGET = 200;
|
|
3336
|
+
/**
|
|
3337
|
+
* One candidate face for the scoring prompt: tool-call name plus the head of
|
|
3338
|
+
* the result text. Pure and shape-defensive.
|
|
3339
|
+
*/
|
|
3340
|
+
function advisorCandidatePreview(callName, blocks) {
|
|
3341
|
+
return truncateChars(`${callName} ${textBlocks(blocks)}`.trim(), PREVIEW_CHAR_BUDGET);
|
|
3342
|
+
}
|
|
3343
|
+
/**
|
|
3344
|
+
* Collect the recent assistant narration tail (bounded, oldest-first join) as
|
|
3345
|
+
* summary-prompt context. Pure.
|
|
3346
|
+
*/
|
|
3347
|
+
function collectTailText(events, budget = TAIL_TEXT_CHAR_BUDGET) {
|
|
3348
|
+
const parts = [];
|
|
3349
|
+
let size = 0;
|
|
3350
|
+
for (let index = events.length - 1; index >= 0; index -= 1) {
|
|
3351
|
+
const event = events[index];
|
|
3352
|
+
if (event?.type !== "assistant/message") continue;
|
|
3353
|
+
const text = textBlocks(event.data).trim();
|
|
3354
|
+
if (text.length === 0) continue;
|
|
3355
|
+
parts.unshift(text);
|
|
3356
|
+
size += codePointLength(text);
|
|
3357
|
+
if (size >= budget) break;
|
|
3358
|
+
}
|
|
3359
|
+
return truncateChars(parts.join("\n"), budget);
|
|
3360
|
+
}
|
|
3361
|
+
function textBlocks(data) {
|
|
3362
|
+
const content = data?.content;
|
|
3363
|
+
if (!Array.isArray(content)) return "";
|
|
3364
|
+
const parts = [];
|
|
3365
|
+
for (const block of content) if (block?.type === "text" && typeof block.text === "string") parts.push(block.text);
|
|
3366
|
+
return parts.join("\n");
|
|
3367
|
+
}
|
|
3368
|
+
/** Structured probe of one `todo/write` payload: the list of task strings, or undefined. */
|
|
3369
|
+
function extractTodoItems(data) {
|
|
3370
|
+
const todos = data?.todos;
|
|
3371
|
+
const list = Array.isArray(todos) ? todos : Array.isArray(data) ? data : void 0;
|
|
3372
|
+
if (list === void 0 || list.length === 0) return void 0;
|
|
3373
|
+
const items = [];
|
|
3374
|
+
for (const entry of list) {
|
|
3375
|
+
if (typeof entry === "string") {
|
|
3376
|
+
if (entry.trim().length > 0) items.push(entry.trim());
|
|
3377
|
+
continue;
|
|
3378
|
+
}
|
|
3379
|
+
if (entry !== null && typeof entry === "object") {
|
|
3380
|
+
const record = entry;
|
|
3381
|
+
const text = [
|
|
3382
|
+
record.content,
|
|
3383
|
+
record.text,
|
|
3384
|
+
record.title,
|
|
3385
|
+
record.name
|
|
3386
|
+
].find((candidate) => typeof candidate === "string" && candidate.trim().length > 0);
|
|
3387
|
+
if (typeof text === "string") {
|
|
3388
|
+
items.push(text.trim());
|
|
3389
|
+
continue;
|
|
3390
|
+
}
|
|
3391
|
+
items.push(JSON.stringify(record));
|
|
3392
|
+
}
|
|
3393
|
+
}
|
|
3394
|
+
return items.length > 0 ? items : void 0;
|
|
3395
|
+
}
|
|
3396
|
+
/**
|
|
3397
|
+
* Harvest task semantics for the summary/scoring prompts: the most recent
|
|
3398
|
+
* `todo/write` event (structured probe first, then the raw JSON string),
|
|
3399
|
+
* falling back to recent user/message text. Pure — log in, semantics out.
|
|
3400
|
+
*/
|
|
3401
|
+
function collectTaskSemantics(events) {
|
|
3402
|
+
for (let index = events.length - 1; index >= 0; index -= 1) {
|
|
3403
|
+
const event = events[index];
|
|
3404
|
+
if (event === void 0 || event.type !== "todo/write") continue;
|
|
3405
|
+
const data = event.data;
|
|
3406
|
+
const items = extractTodoItems(data);
|
|
3407
|
+
if (items !== void 0) {
|
|
3408
|
+
const taskText = truncateChars(items.join("\n"), TAIL_TEXT_CHAR_BUDGET);
|
|
3409
|
+
return {
|
|
3410
|
+
source: "todos",
|
|
3411
|
+
todoVersion: versionDigest(taskText),
|
|
3412
|
+
taskText
|
|
3413
|
+
};
|
|
3414
|
+
}
|
|
3415
|
+
const raw = truncateChars(JSON.stringify(event.data) ?? "", TAIL_TEXT_CHAR_BUDGET);
|
|
3416
|
+
if (raw.length > 2) return {
|
|
3417
|
+
source: "raw-todo",
|
|
3418
|
+
todoVersion: versionDigest(raw),
|
|
3419
|
+
taskText: raw
|
|
3420
|
+
};
|
|
3421
|
+
}
|
|
3422
|
+
for (let index = events.length - 1; index >= 0; index -= 1) {
|
|
3423
|
+
const event = events[index];
|
|
3424
|
+
if (event?.type !== "user/message") continue;
|
|
3425
|
+
const text = truncateChars(textBlocks(event.data).trim(), TAIL_TEXT_CHAR_BUDGET);
|
|
3426
|
+
if (text.length === 0) continue;
|
|
3427
|
+
return {
|
|
3428
|
+
source: "messages",
|
|
3429
|
+
todoVersion: versionDigest(text),
|
|
3430
|
+
taskText: text
|
|
3431
|
+
};
|
|
3432
|
+
}
|
|
3433
|
+
}
|
|
3434
|
+
/**
|
|
3435
|
+
* Prefix-decay figure: 1 minus the character-pressure-weighted mean relevance
|
|
3436
|
+
* of the prefix candidates. Unscored candidates count as neutral 0.5. Pure,
|
|
3437
|
+
* deterministic, no LLM and no I/O.
|
|
3438
|
+
*/
|
|
3439
|
+
function prefixDecay(candidates, scores) {
|
|
3440
|
+
let totalWeight = 0;
|
|
3441
|
+
let weightedRelevance = 0;
|
|
3442
|
+
for (const candidate of candidates) {
|
|
3443
|
+
const weight = candidate.characterPressure > 0 ? candidate.characterPressure : 0;
|
|
3444
|
+
if (weight === 0) continue;
|
|
3445
|
+
totalWeight += weight;
|
|
3446
|
+
weightedRelevance += weight * (scores.get(candidate.seq)?.score ?? NEUTRAL_RELEVANCE);
|
|
3447
|
+
}
|
|
3448
|
+
if (totalWeight === 0) return {
|
|
3449
|
+
decay: 0,
|
|
3450
|
+
weightedChars: 0
|
|
3451
|
+
};
|
|
3452
|
+
return {
|
|
3453
|
+
decay: 1 - weightedRelevance / totalWeight,
|
|
3454
|
+
weightedChars: totalWeight
|
|
3455
|
+
};
|
|
3456
|
+
}
|
|
3457
|
+
/** Lowercase word tokens used by the local keyword-overlap prescreen. */
|
|
3458
|
+
function keywordsOf(text) {
|
|
3459
|
+
const matches = text.toLowerCase().match(/[\p{L}\p{N}_-]{3,}/gu) ?? [];
|
|
3460
|
+
return new Set(matches);
|
|
3461
|
+
}
|
|
3462
|
+
function overlapCount(left, right) {
|
|
3463
|
+
let count = 0;
|
|
3464
|
+
for (const token of right) if (left.has(token)) count += 1;
|
|
3465
|
+
return count;
|
|
3466
|
+
}
|
|
3467
|
+
/**
|
|
3468
|
+
* Incremental scoring selection: candidates newer than the watermark whose
|
|
3469
|
+
* character pressure reaches the token-named floor, ranked by local keyword
|
|
3470
|
+
* overlap with the task semantics and cut at the sample limit. When the task
|
|
3471
|
+
* semantics changed, the watermark is ignored so every eligible candidate can
|
|
3472
|
+
* rescore. Pure.
|
|
3473
|
+
*/
|
|
3474
|
+
function selectScoringCandidates(candidates, state, input) {
|
|
3475
|
+
const eligible = [];
|
|
3476
|
+
for (const candidate of candidates) {
|
|
3477
|
+
if (!input.taskChanged && candidate.seq <= state.watermarkSeq) continue;
|
|
3478
|
+
if (candidate.characterPressure < input.minChars) continue;
|
|
3479
|
+
eligible.push({
|
|
3480
|
+
...candidate,
|
|
3481
|
+
overlap: overlapCount(input.taskKeywords, keywordsOf(candidate.preview))
|
|
3482
|
+
});
|
|
3483
|
+
}
|
|
3484
|
+
eligible.sort((left, right) => right.overlap - left.overlap || right.characterPressure - left.characterPressure);
|
|
3485
|
+
return eligible.slice(0, input.sampleLimit).map(({ overlap: _overlap, ...candidate }) => candidate);
|
|
3486
|
+
}
|
|
3487
|
+
function advisorAudit(input, phase, fields) {
|
|
3488
|
+
return {
|
|
3489
|
+
schemaVersion: 1,
|
|
3490
|
+
kind: "advisor-outcome",
|
|
3491
|
+
sessionId: input.sessionId,
|
|
3492
|
+
phase,
|
|
3493
|
+
turnIndex: input.turn,
|
|
3494
|
+
...fields
|
|
3495
|
+
};
|
|
3496
|
+
}
|
|
3497
|
+
/**
|
|
3498
|
+
* One full advisor pass: summary refresh (todo change or every refreshTurns),
|
|
3499
|
+
* incremental batch scoring with recertification marks, then the decay
|
|
3500
|
+
* figure. State is written only on success; any failure leaves state
|
|
3501
|
+
* untouched, emits ok:false audits with reason codes, and never throws.
|
|
3502
|
+
*/
|
|
3503
|
+
async function runAdvisorPass(state, channel, emit, input) {
|
|
3504
|
+
if (input.task === void 0) return void 0;
|
|
3505
|
+
const taskChanged = invalidateOnTaskChange(state, input.task.todoVersion);
|
|
3506
|
+
const turn = input.turn;
|
|
3507
|
+
if (state.summary === void 0 || turn - state.lastSummaryTurn >= input.advisor.refreshTurns) {
|
|
3508
|
+
const summaryStarted = Date.now();
|
|
3509
|
+
const summaryText = await channel.ask({
|
|
3510
|
+
system: buildAdvisorSummarySystemPrompt(),
|
|
3511
|
+
user: buildAdvisorSummaryUserPrompt(input.task.taskText, input.tailText),
|
|
3512
|
+
signal: input.signal
|
|
3513
|
+
});
|
|
3514
|
+
const summaryLatencyMs = Date.now() - summaryStarted;
|
|
3515
|
+
const summary = input.signal.aborted ? void 0 : parseAdvisorSummary(summaryText);
|
|
3516
|
+
if (summary === void 0) {
|
|
3517
|
+
emit(advisorAudit(input, "summary", {
|
|
3518
|
+
ok: false,
|
|
3519
|
+
latencyMs: summaryLatencyMs,
|
|
3520
|
+
...input.signal.aborted ? { reason: "aborted" } : summaryText === void 0 ? { reason: "channel-empty" } : { reason: "parse-failed" }
|
|
3521
|
+
}));
|
|
3522
|
+
return;
|
|
3523
|
+
}
|
|
3524
|
+
state.summary = {
|
|
3525
|
+
...summary,
|
|
3526
|
+
todoVersion: input.task.todoVersion,
|
|
3527
|
+
turn
|
|
3528
|
+
};
|
|
3529
|
+
state.lastSummaryTurn = turn;
|
|
3530
|
+
emit(advisorAudit(input, "summary", {
|
|
3531
|
+
ok: true,
|
|
3532
|
+
latencyMs: summaryLatencyMs
|
|
3533
|
+
}));
|
|
3534
|
+
}
|
|
3535
|
+
const summary = state.summary;
|
|
3536
|
+
if (summary === void 0) return void 0;
|
|
3537
|
+
const sampled = selectScoringCandidates(input.candidates, state, {
|
|
3538
|
+
taskKeywords: keywordsOf(`${input.task.taskText}\n${summary.keywords.join(" ")}`),
|
|
3539
|
+
minChars: charsForTokens(input.advisor.minTokens),
|
|
3540
|
+
sampleLimit: input.advisor.sampleLimit,
|
|
3541
|
+
taskChanged
|
|
3542
|
+
});
|
|
3543
|
+
let scored = 0;
|
|
3544
|
+
let highestScored = 0;
|
|
3545
|
+
if (sampled.length > 0) {
|
|
3546
|
+
const scoringStarted = Date.now();
|
|
3547
|
+
const scoresText = await channel.ask({
|
|
3548
|
+
system: buildAdvisorScoringSystemPrompt(),
|
|
3549
|
+
user: buildAdvisorScoringUserPrompt(input.task.taskText, summary.activeSubtasks, sampled),
|
|
3550
|
+
signal: input.signal
|
|
3551
|
+
});
|
|
3552
|
+
const scoringLatencyMs = Date.now() - scoringStarted;
|
|
3553
|
+
const scores = input.signal.aborted ? void 0 : parseAdvisorScores(scoresText, new Set(sampled.map((item) => item.seq)));
|
|
3554
|
+
if (scores === void 0 || scores.size === 0) {
|
|
3555
|
+
emit(advisorAudit(input, "scoring", {
|
|
3556
|
+
ok: false,
|
|
3557
|
+
sampledCount: sampled.length,
|
|
3558
|
+
latencyMs: scoringLatencyMs,
|
|
3559
|
+
...input.signal.aborted ? { reason: "aborted" } : scoresText === void 0 ? { reason: "channel-empty" } : { reason: "parse-failed" }
|
|
3560
|
+
}));
|
|
3561
|
+
return;
|
|
3562
|
+
}
|
|
3563
|
+
for (const candidate of sampled) {
|
|
3564
|
+
const answer = scores.get(candidate.seq);
|
|
3565
|
+
if (answer === void 0) continue;
|
|
3566
|
+
recordScore(state, candidate.seq, {
|
|
3567
|
+
score: answer.score,
|
|
3568
|
+
turn
|
|
3569
|
+
});
|
|
3570
|
+
scored += 1;
|
|
3571
|
+
if (candidate.seq > highestScored) highestScored = candidate.seq;
|
|
3572
|
+
if (answer.score < input.advisor.scoreThreshold) recordRecertified(state, candidate.seq, turn);
|
|
3573
|
+
}
|
|
3574
|
+
emit(advisorAudit(input, "scoring", {
|
|
3575
|
+
ok: true,
|
|
3576
|
+
sampledCount: sampled.length,
|
|
3577
|
+
latencyMs: scoringLatencyMs
|
|
3578
|
+
}));
|
|
3579
|
+
if (highestScored > state.watermarkSeq) state.watermarkSeq = highestScored;
|
|
3580
|
+
}
|
|
3581
|
+
const decay = prefixDecay(input.candidates, state.scores);
|
|
3582
|
+
state.lastDecay = {
|
|
3583
|
+
decay: decay.decay,
|
|
3584
|
+
weightedChars: decay.weightedChars,
|
|
3585
|
+
turn
|
|
3586
|
+
};
|
|
3587
|
+
emit(advisorAudit(input, "decay", {
|
|
3588
|
+
ok: true,
|
|
3589
|
+
sampledCount: scored,
|
|
3590
|
+
decay: decay.decay,
|
|
3591
|
+
weightedChars: decay.weightedChars,
|
|
3592
|
+
latencyMs: 0
|
|
3593
|
+
}));
|
|
3594
|
+
return {
|
|
3595
|
+
decay: decay.decay,
|
|
3596
|
+
weightedChars: decay.weightedChars,
|
|
3597
|
+
sampled: sampled.length
|
|
3598
|
+
};
|
|
3599
|
+
}
|
|
3600
|
+
/**
|
|
3601
|
+
* Convenience entry used by the pruner: fetch-or-create the session state and
|
|
3602
|
+
* run one pass against it.
|
|
3603
|
+
*/
|
|
3604
|
+
async function runSessionAdvisorPass(session, channel, emit, input) {
|
|
3605
|
+
const state = getAdvisorState(session);
|
|
3606
|
+
if (state.inFlight) return void 0;
|
|
3607
|
+
state.inFlight = true;
|
|
3608
|
+
try {
|
|
3609
|
+
return await runAdvisorPass(state, channel, emit, {
|
|
3610
|
+
...input,
|
|
3611
|
+
sessionId: input.sessionId ?? String(session.id)
|
|
3612
|
+
});
|
|
3613
|
+
} finally {
|
|
3614
|
+
state.inFlight = false;
|
|
3615
|
+
}
|
|
3616
|
+
}
|
|
3617
|
+
//#endregion
|
|
3618
|
+
//#region src/runtime/tokenpilot/intent-input-mask.ts
|
|
3619
|
+
/**
|
|
3620
|
+
* Semantic-role input masking for the intent-summary writer (task_2.2).
|
|
3621
|
+
*
|
|
3622
|
+
* The intent summary records historical TASK semantics — for read-class tools
|
|
3623
|
+
* the semantics are "read X", never the file body, so the body is masked to a
|
|
3624
|
+
* one-line record before it can reach the summary prompt. Write-class results
|
|
3625
|
+
* (edits) ARE task semantics and keep their skeleton + verbatim error lines.
|
|
3626
|
+
*
|
|
3627
|
+
* Classification REUSES `classifyToolSource()` (reducers.ts routes on the
|
|
3628
|
+
* same classes): hand-rolling a name→role map here would regress its fixed
|
|
3629
|
+
* misclassification edges (mcp→generic, web_search/memory_search not being
|
|
3630
|
+
* content search, glob being path-listing, execute_sql not being shell).
|
|
3631
|
+
* Only the write class is layered on top — `ToolClass` has no write member.
|
|
3632
|
+
*/
|
|
3633
|
+
/** Exact-token write layer, same tokenization discipline as toolclass. */
|
|
3634
|
+
const WRITE_NAMES = /* @__PURE__ */ new Set([
|
|
3635
|
+
"apply_patch",
|
|
3636
|
+
"multi_edit",
|
|
3637
|
+
"create_file",
|
|
3638
|
+
"write_to_file",
|
|
3639
|
+
"str_replace_editor"
|
|
3640
|
+
]);
|
|
3641
|
+
const WRITE_TOKENS = /* @__PURE__ */ new Set([
|
|
3642
|
+
"write",
|
|
3643
|
+
"edit",
|
|
3644
|
+
"patch"
|
|
3645
|
+
]);
|
|
3646
|
+
function hasWriteToken(name) {
|
|
3647
|
+
const lowered = name.toLowerCase();
|
|
3648
|
+
if (WRITE_NAMES.has(lowered)) return true;
|
|
3649
|
+
return lowered.split(/[-_/]+/).some((token) => WRITE_TOKENS.has(token));
|
|
3650
|
+
}
|
|
3651
|
+
/**
|
|
3652
|
+
* Role for one candidate. The write layer is consulted first; everything
|
|
3653
|
+
* else defers to the shared classifier. `shell`/`generic` stay conservative
|
|
3654
|
+
* (skeleton + error lines, never a blind mask) — a bash result can be a
|
|
3655
|
+
* mutation even when its name says nothing.
|
|
3656
|
+
*/
|
|
3657
|
+
function classifyIntentRole(toolName, command, text) {
|
|
3658
|
+
if (hasWriteToken(toolName)) return "write-keep";
|
|
3659
|
+
const toolClass = classifyToolSource(toolName, command, text);
|
|
3660
|
+
if (toolClass === "read" || toolClass === "search" || toolClass === "path-listing") return "read-mask";
|
|
3661
|
+
return "conservative";
|
|
3662
|
+
}
|
|
3663
|
+
const ERROR_LINE_PATTERN = /\b(error|failed|failure|exception|panic|fatal|traceback|unreachable|denied)\b/i;
|
|
3664
|
+
const KEEP_HEAD_LINES = 40;
|
|
3665
|
+
const KEEP_HEAD_CHARS = 2e3;
|
|
3666
|
+
/** Verbatim error/warn lines kept out of the LLM's hands and into the intent block. */
|
|
3667
|
+
function extractErrorLines(text) {
|
|
3668
|
+
return text.split("\n").filter((line) => ERROR_LINE_PATTERN.test(line)).slice(0, 10);
|
|
3669
|
+
}
|
|
3670
|
+
/** Count lines and code points for the read-mask record tail. */
|
|
3671
|
+
function scaleOf(text) {
|
|
3672
|
+
return {
|
|
3673
|
+
lines: text.length === 0 ? 0 : text.split("\n").length,
|
|
3674
|
+
chars: text.length
|
|
3675
|
+
};
|
|
3676
|
+
}
|
|
3677
|
+
/**
|
|
3678
|
+
* Build the prompt face for one candidate. Read-mask output contains NONE of
|
|
3679
|
+
* the original body — only the tool name, the call's target argument, and
|
|
3680
|
+
* the dropped scale — so a hostile body can never leak into the summary.
|
|
3681
|
+
*/
|
|
3682
|
+
function maskCandidateForSummary(seq, toolName, argumentsText, text) {
|
|
3683
|
+
const role = classifyIntentRole(toolName, extractCommand(argumentsText), text);
|
|
3684
|
+
if (role === "read-mask") {
|
|
3685
|
+
const { lines, chars } = scaleOf(text);
|
|
3686
|
+
return {
|
|
3687
|
+
seq,
|
|
3688
|
+
role,
|
|
3689
|
+
record: `${toolName} ${extractTarget(argumentsText)} -> masked (${lines} lines / ${chars} chars)`
|
|
3690
|
+
};
|
|
3691
|
+
}
|
|
3692
|
+
const head = text.split("\n", KEEP_HEAD_LINES).join("\n").slice(0, KEEP_HEAD_CHARS);
|
|
3693
|
+
const errorLines = extractErrorLines(text);
|
|
3694
|
+
return {
|
|
3695
|
+
seq,
|
|
3696
|
+
role,
|
|
3697
|
+
record: `${toolName} (seq ${seq})\n${head}${errorLines.length > 0 ? `\nerror lines (verbatim):\n${errorLines.join("\n")}` : ""}`
|
|
3698
|
+
};
|
|
3699
|
+
}
|
|
3700
|
+
/** Extract a short command head from a tool-call arguments JSON string. */
|
|
3701
|
+
function extractCommand(argumentsText) {
|
|
3702
|
+
try {
|
|
3703
|
+
const parsed = JSON.parse(argumentsText);
|
|
3704
|
+
if (parsed !== null && typeof parsed === "object") {
|
|
3705
|
+
const command = parsed.command;
|
|
3706
|
+
if (typeof command === "string") return command.slice(0, 200);
|
|
3707
|
+
}
|
|
3708
|
+
} catch {}
|
|
3709
|
+
return "";
|
|
3710
|
+
}
|
|
3711
|
+
/** Extract the most target-like string argument (path/query/url) for read-mask records. */
|
|
3712
|
+
function extractTarget(argumentsText) {
|
|
3713
|
+
try {
|
|
3714
|
+
const parsed = JSON.parse(argumentsText);
|
|
3715
|
+
if (parsed !== null && typeof parsed === "object") {
|
|
3716
|
+
const record = parsed;
|
|
3717
|
+
const target = [
|
|
3718
|
+
record.path,
|
|
3719
|
+
record.file_path,
|
|
3720
|
+
record.query,
|
|
3721
|
+
record.url,
|
|
3722
|
+
record.pattern,
|
|
3723
|
+
record.glob
|
|
3724
|
+
].find((candidate) => typeof candidate === "string" && candidate.trim().length > 0);
|
|
3725
|
+
if (typeof target === "string") return target.slice(0, 160);
|
|
3726
|
+
const first = Object.values(record).find((value) => typeof value === "string");
|
|
3727
|
+
if (typeof first === "string") return first.slice(0, 160);
|
|
3728
|
+
}
|
|
3729
|
+
} catch {}
|
|
3730
|
+
return "(unparsed target)";
|
|
3731
|
+
}
|
|
3732
|
+
//#endregion
|
|
3733
|
+
//#region src/runtime/tokenpilot/intent-range.ts
|
|
3734
|
+
/**
|
|
3735
|
+
* Oldest-first selection of foldable candidates. Excludes the protected
|
|
3736
|
+
* working set and already-folded seqs; caps the batch size.
|
|
3737
|
+
*/
|
|
3738
|
+
function computeIntentRange(input) {
|
|
3739
|
+
const unprotected = input.candidates.filter((candidate) => !input.protectedSeqs.has(candidate.seq));
|
|
3740
|
+
const skippedProtected = input.candidates.length - unprotected.length;
|
|
3741
|
+
const eligible = unprotected.filter((candidate) => !input.foldedSeqs.has(candidate.seq));
|
|
3742
|
+
const skippedFolded = unprotected.length - eligible.length;
|
|
3743
|
+
return {
|
|
3744
|
+
seqs: [...eligible].sort((a, b) => a.seq - b.seq).slice(0, Math.max(0, input.maxCandidates)).map((candidate) => candidate.seq),
|
|
3745
|
+
skippedProtected,
|
|
3746
|
+
skippedFolded
|
|
3747
|
+
};
|
|
3748
|
+
}
|
|
3749
|
+
//#endregion
|
|
3750
|
+
//#region src/runtime/tokenpilot/intent-fold.ts
|
|
3751
|
+
/** Marker written into every folded block; its presence makes a seq unfoldable again (fold-once). */
|
|
3752
|
+
const INTENT_FOLD_MARKER = "[Intent summary";
|
|
3753
|
+
/** Render the replacement text for one folded candidate. Pure. */
|
|
3754
|
+
function renderIntentFoldBlock(pending, seq) {
|
|
3755
|
+
const start = pending.startSeq;
|
|
3756
|
+
const end = pending.endSeq;
|
|
3757
|
+
if (seq === start) {
|
|
3758
|
+
const readLines = pending.records.filter((record) => record.role === "read-mask").map((record) => record.line);
|
|
3759
|
+
const consulted = readLines.length > 0 ? `Consulted: ${readLines.join("; ")}` : "";
|
|
3760
|
+
const errorBlock = pending.errorLines.length > 0 ? `\nError lines (verbatim):\n${pending.errorLines.join("\n")}` : "";
|
|
3761
|
+
return [
|
|
3762
|
+
`${INTENT_FOLD_MARKER} of folded tool results seq ${start}..${end}]`,
|
|
3763
|
+
pending.summary,
|
|
3764
|
+
consulted,
|
|
3765
|
+
errorBlock,
|
|
3766
|
+
"[Original content remains in the session log at the listed seq values.]"
|
|
3767
|
+
].filter((part) => part.length > 0).join("\n");
|
|
3768
|
+
}
|
|
3769
|
+
const record = pending.records.find((entry) => entry.seq === seq);
|
|
3770
|
+
const face = record === void 0 ? `${seq}` : record.role === "read-mask" ? record.line : `${record.toolName} result folded into the batch intent summary`;
|
|
3771
|
+
return `${INTENT_FOLD_MARKER} folded into the batch summary above (seq ${start}..${end})] ${face}`;
|
|
3772
|
+
}
|
|
3773
|
+
//#endregion
|
|
2940
3774
|
//#region src/runtime/tokenpilot/dedup.ts
|
|
2941
3775
|
/**
|
|
2942
3776
|
* TokenPilot-inspired A1: byte-identical repeated tool-result dedup.
|
|
@@ -2996,254 +3830,6 @@ function dedupePlaceholder(entry, originalChars) {
|
|
|
2996
3830
|
].join(" ");
|
|
2997
3831
|
}
|
|
2998
3832
|
//#endregion
|
|
2999
|
-
//#region src/runtime/deepseek-official-pricing.ts
|
|
3000
|
-
/** Checked-in DeepSeek official prices and fixed-point provider-usage accounting. */
|
|
3001
|
-
const DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION = "deepseek-official-2026-08-25";
|
|
3002
|
-
/** Wall-clock time at which the checked-in official price pages were verified. */
|
|
3003
|
-
const DEEPSEEK_OFFICIAL_PRICE_CHECKED_AT = "2026-08-25T00:10:20+08:00";
|
|
3004
|
-
const PRICES = Object.freeze({
|
|
3005
|
-
"deepseek-v4-flash": modelPrices("DeepSeek-V4-Flash-0731", [
|
|
3006
|
-
"0.007",
|
|
3007
|
-
"0.22",
|
|
3008
|
-
"0.66"
|
|
3009
|
-
], [
|
|
3010
|
-
"0.014",
|
|
3011
|
-
"0.44",
|
|
3012
|
-
"1.32"
|
|
3013
|
-
], [
|
|
3014
|
-
"0.05",
|
|
3015
|
-
"1.5",
|
|
3016
|
-
"4.5"
|
|
3017
|
-
], [
|
|
3018
|
-
"0.10",
|
|
3019
|
-
"3.0",
|
|
3020
|
-
"9.0"
|
|
3021
|
-
]),
|
|
3022
|
-
"deepseek-v4-pro": modelPrices("DeepSeek-V4-Pro-0813", [
|
|
3023
|
-
"0.022",
|
|
3024
|
-
"0.66",
|
|
3025
|
-
"1.98"
|
|
3026
|
-
], [
|
|
3027
|
-
"0.044",
|
|
3028
|
-
"1.32",
|
|
3029
|
-
"3.96"
|
|
3030
|
-
], [
|
|
3031
|
-
"0.15",
|
|
3032
|
-
"4.5",
|
|
3033
|
-
"13.5"
|
|
3034
|
-
], [
|
|
3035
|
-
"0.30",
|
|
3036
|
-
"9.0",
|
|
3037
|
-
"27.0"
|
|
3038
|
-
]),
|
|
3039
|
-
"deepseek-v4-flash-vision-exp": modelPrices("DeepSeek-V4-Flash-Vision-Exp", [
|
|
3040
|
-
"0.007",
|
|
3041
|
-
"0.22",
|
|
3042
|
-
"0.66"
|
|
3043
|
-
], [
|
|
3044
|
-
"0.014",
|
|
3045
|
-
"0.44",
|
|
3046
|
-
"1.32"
|
|
3047
|
-
], [
|
|
3048
|
-
"0.05",
|
|
3049
|
-
"1.5",
|
|
3050
|
-
"4.5"
|
|
3051
|
-
], [
|
|
3052
|
-
"0.10",
|
|
3053
|
-
"3.0",
|
|
3054
|
-
"9.0"
|
|
3055
|
-
])
|
|
3056
|
-
});
|
|
3057
|
-
const PEAK_RULE = "Asia/Shanghai Mon-Fri 09:00-12:00,14:00-18:00";
|
|
3058
|
-
const USD_SOURCE = "https://api-docs.deepseek.com/quick_start/pricing/";
|
|
3059
|
-
const CNY_SOURCE = "https://api-docs.deepseek.com/zh-cn/quick_start/pricing/";
|
|
3060
|
-
/**
|
|
3061
|
-
* Resolve one immutable official price record; aliases and compatible gateways fail closed.
|
|
3062
|
-
* @param input - exact provider, endpoint, route, model, currency, and timestamp applicability.
|
|
3063
|
-
* @returns An immutable price record or an explicit unpriced reason.
|
|
3064
|
-
*/
|
|
3065
|
-
function resolveOfficialDeepSeekPrice(input) {
|
|
3066
|
-
if (input.provider !== "deepseek-official") return unpriced("unknown provider route");
|
|
3067
|
-
if (input.baseUrlClass !== "official-public") return unpriced("unknown base-url applicability");
|
|
3068
|
-
if (input.apiRoute !== "chat-completions" && input.apiRoute !== "responses") return unpriced("unknown API route");
|
|
3069
|
-
if (!isOfficialModel(input.modelId)) return unpriced("unknown model id");
|
|
3070
|
-
if (input.currency !== "USD" && input.currency !== "CNY") return unpriced("unknown currency");
|
|
3071
|
-
const band = priceBandAt(input.at);
|
|
3072
|
-
if (band === void 0) return unpriced("invalid price timestamp");
|
|
3073
|
-
const model = PRICES[input.modelId];
|
|
3074
|
-
const [inputCacheHit, inputCacheMiss, output] = model[input.currency][band];
|
|
3075
|
-
return {
|
|
3076
|
-
kind: "priced",
|
|
3077
|
-
record: Object.freeze({
|
|
3078
|
-
catalogVersion: DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION,
|
|
3079
|
-
checkedAt: DEEPSEEK_OFFICIAL_PRICE_CHECKED_AT,
|
|
3080
|
-
provider: "deepseek-official",
|
|
3081
|
-
baseUrlClass: "official-public",
|
|
3082
|
-
apiRoute: input.apiRoute,
|
|
3083
|
-
modelId: input.modelId,
|
|
3084
|
-
modelVersion: model.version,
|
|
3085
|
-
currency: input.currency,
|
|
3086
|
-
unitTokens: 1e6,
|
|
3087
|
-
band,
|
|
3088
|
-
inputCacheHit,
|
|
3089
|
-
inputCacheMiss,
|
|
3090
|
-
output,
|
|
3091
|
-
sourceUrl: input.currency === "USD" ? USD_SOURCE : CNY_SOURCE,
|
|
3092
|
-
sourceLocale: input.currency === "USD" ? "en" : "zh-CN",
|
|
3093
|
-
peakRule: PEAK_RULE
|
|
3094
|
-
})
|
|
3095
|
-
};
|
|
3096
|
-
}
|
|
3097
|
-
/**
|
|
3098
|
-
* Classify a timestamp under the published Beijing peak schedule.
|
|
3099
|
-
* @param at - absolute request time to interpret in Asia/Shanghai.
|
|
3100
|
-
* @returns Peak/off-peak, or undefined for an invalid timestamp.
|
|
3101
|
-
*/
|
|
3102
|
-
function priceBandAt(at) {
|
|
3103
|
-
if (!Number.isFinite(at.getTime())) return void 0;
|
|
3104
|
-
const parts = new Intl.DateTimeFormat("en-US", {
|
|
3105
|
-
timeZone: "Asia/Shanghai",
|
|
3106
|
-
weekday: "short",
|
|
3107
|
-
hour: "2-digit",
|
|
3108
|
-
minute: "2-digit",
|
|
3109
|
-
second: "2-digit",
|
|
3110
|
-
hourCycle: "h23"
|
|
3111
|
-
}).formatToParts(at);
|
|
3112
|
-
const values = Object.fromEntries(parts.map((part) => [part.type, part.value]));
|
|
3113
|
-
const weekday = values.weekday;
|
|
3114
|
-
const hour = Number(values.hour);
|
|
3115
|
-
const minute = Number(values.minute);
|
|
3116
|
-
const second = Number(values.second);
|
|
3117
|
-
if (weekday === void 0 || !Number.isInteger(hour) || !Number.isInteger(minute) || !Number.isInteger(second)) return void 0;
|
|
3118
|
-
const workday = weekday !== "Sat" && weekday !== "Sun";
|
|
3119
|
-
const seconds = hour * 3600 + minute * 60 + second;
|
|
3120
|
-
return workday && (seconds >= 32400 && seconds < 43200 || seconds >= 50400 && seconds < 64800) ? "peak" : "off-peak";
|
|
3121
|
-
}
|
|
3122
|
-
/**
|
|
3123
|
-
* Price one completed request, returning a range when it spans a published band boundary.
|
|
3124
|
-
* @param input - exact applicability, request interval, and complete disjoint usage buckets.
|
|
3125
|
-
* @returns Fixed-point exact/range cost or an explicit unpriced reason.
|
|
3126
|
-
*/
|
|
3127
|
-
function priceOfficialDeepSeekUsage(input) {
|
|
3128
|
-
for (const [name, value] of Object.entries(input.usage)) if (!Number.isSafeInteger(value) || value < 0) return unpriced(`invalid ${name}`);
|
|
3129
|
-
if (input.completedAt.getTime() < input.startedAt.getTime()) return unpriced("completion timestamp precedes request start");
|
|
3130
|
-
const start = resolveOfficialDeepSeekPrice({
|
|
3131
|
-
...input,
|
|
3132
|
-
at: input.startedAt
|
|
3133
|
-
});
|
|
3134
|
-
if (start.kind === "unpriced") return start;
|
|
3135
|
-
const end = resolveOfficialDeepSeekPrice({
|
|
3136
|
-
...input,
|
|
3137
|
-
at: input.completedAt
|
|
3138
|
-
});
|
|
3139
|
-
if (end.kind === "unpriced") return end;
|
|
3140
|
-
const startAmount = amountFor(start.record, input.usage);
|
|
3141
|
-
if (startAmount === void 0) return unpriced("invalid decimal price record");
|
|
3142
|
-
const crossesBoundary = spansPublishedPriceBoundary(input.startedAt, input.completedAt);
|
|
3143
|
-
if (start.record.band === end.record.band && !crossesBoundary) return {
|
|
3144
|
-
kind: "exact",
|
|
3145
|
-
currency: start.record.currency,
|
|
3146
|
-
band: start.record.band,
|
|
3147
|
-
...startAmount
|
|
3148
|
-
};
|
|
3149
|
-
const comparisonRecord = start.record.band === end.record.band ? priceRecordInBand(start.record, start.record.band === "peak" ? "off-peak" : "peak") : end.record;
|
|
3150
|
-
const endAmount = amountFor(comparisonRecord, input.usage);
|
|
3151
|
-
if (endAmount === void 0) return unpriced("invalid decimal price record");
|
|
3152
|
-
const startFemto = BigInt(startAmount.femtoUnits);
|
|
3153
|
-
const endFemto = BigInt(endAmount.femtoUnits);
|
|
3154
|
-
return {
|
|
3155
|
-
kind: "range",
|
|
3156
|
-
currency: start.record.currency,
|
|
3157
|
-
bands: [start.record.band, comparisonRecord.band],
|
|
3158
|
-
minimum: startFemto <= endFemto ? startAmount : endAmount,
|
|
3159
|
-
maximum: startFemto <= endFemto ? endAmount : startAmount
|
|
3160
|
-
};
|
|
3161
|
-
}
|
|
3162
|
-
/** Detect any published UTC band boundary, even when both endpoints share a band. */
|
|
3163
|
-
function spansPublishedPriceBoundary(startedAt, completedAt) {
|
|
3164
|
-
const start = startedAt.getTime();
|
|
3165
|
-
const end = completedAt.getTime();
|
|
3166
|
-
if (end <= start) return false;
|
|
3167
|
-
const dayMs = 864e5;
|
|
3168
|
-
if (end - start >= 7 * dayMs) return true;
|
|
3169
|
-
const firstDay = Math.floor(start / dayMs) * dayMs;
|
|
3170
|
-
for (let day = firstDay; day <= end; day += dayMs) {
|
|
3171
|
-
const weekday = new Date(day).getUTCDay();
|
|
3172
|
-
if (weekday === 0 || weekday === 6) continue;
|
|
3173
|
-
for (const hour of [
|
|
3174
|
-
1,
|
|
3175
|
-
4,
|
|
3176
|
-
6,
|
|
3177
|
-
10
|
|
3178
|
-
]) {
|
|
3179
|
-
const boundary = day + hour * 60 * 60 * 1e3;
|
|
3180
|
-
if (boundary > start && boundary <= end) return true;
|
|
3181
|
-
}
|
|
3182
|
-
}
|
|
3183
|
-
return false;
|
|
3184
|
-
}
|
|
3185
|
-
function priceRecordInBand(record, band) {
|
|
3186
|
-
const [inputCacheHit, inputCacheMiss, output] = PRICES[record.modelId][record.currency][band];
|
|
3187
|
-
return Object.freeze({
|
|
3188
|
-
...record,
|
|
3189
|
-
band,
|
|
3190
|
-
inputCacheHit,
|
|
3191
|
-
inputCacheMiss,
|
|
3192
|
-
output
|
|
3193
|
-
});
|
|
3194
|
-
}
|
|
3195
|
-
/**
|
|
3196
|
-
* Parse a non-negative decimal rate into nano-currency units, without Number arithmetic.
|
|
3197
|
-
* @param value - canonical non-negative decimal with at most nine fractional digits.
|
|
3198
|
-
* @returns Integer nano-units, or undefined when the decimal is invalid.
|
|
3199
|
-
*/
|
|
3200
|
-
function decimalRateNanoUnits(value) {
|
|
3201
|
-
const match = /^(0|[1-9]\d*)(?:\.(\d{1,9}))?$/u.exec(value);
|
|
3202
|
-
if (match === null) return void 0;
|
|
3203
|
-
const whole = match[1] ?? "0";
|
|
3204
|
-
const fraction = (match[2] ?? "").padEnd(9, "0");
|
|
3205
|
-
return BigInt(whole) * 1000000000n + BigInt(fraction || "0");
|
|
3206
|
-
}
|
|
3207
|
-
function amountFor(record, usage) {
|
|
3208
|
-
const hit = decimalRateNanoUnits(record.inputCacheHit);
|
|
3209
|
-
const miss = decimalRateNanoUnits(record.inputCacheMiss);
|
|
3210
|
-
const output = decimalRateNanoUnits(record.output);
|
|
3211
|
-
if (hit === void 0 || miss === void 0 || output === void 0) return void 0;
|
|
3212
|
-
const femtoUnits = BigInt(usage.cacheReadTokens) * hit + BigInt(usage.cacheMissTokens) * miss + BigInt(usage.outputTokens) * output;
|
|
3213
|
-
return {
|
|
3214
|
-
femtoUnits: femtoUnits.toString(),
|
|
3215
|
-
decimal: formatFemto(femtoUnits)
|
|
3216
|
-
};
|
|
3217
|
-
}
|
|
3218
|
-
function formatFemto(value) {
|
|
3219
|
-
const digits = value.toString().padStart(16, "0");
|
|
3220
|
-
const whole = digits.slice(0, -15);
|
|
3221
|
-
const fraction = digits.slice(-15).replace(/0+$/u, "");
|
|
3222
|
-
return fraction.length === 0 ? whole : `${whole}.${fraction}`;
|
|
3223
|
-
}
|
|
3224
|
-
function modelPrices(version, usdOffPeak, usdPeak, cnyOffPeak, cnyPeak) {
|
|
3225
|
-
return Object.freeze({
|
|
3226
|
-
version,
|
|
3227
|
-
USD: Object.freeze({
|
|
3228
|
-
"off-peak": usdOffPeak,
|
|
3229
|
-
peak: usdPeak
|
|
3230
|
-
}),
|
|
3231
|
-
CNY: Object.freeze({
|
|
3232
|
-
"off-peak": cnyOffPeak,
|
|
3233
|
-
peak: cnyPeak
|
|
3234
|
-
})
|
|
3235
|
-
});
|
|
3236
|
-
}
|
|
3237
|
-
function isOfficialModel(value) {
|
|
3238
|
-
return Object.prototype.hasOwnProperty.call(PRICES, value);
|
|
3239
|
-
}
|
|
3240
|
-
function unpriced(reason) {
|
|
3241
|
-
return {
|
|
3242
|
-
kind: "unpriced",
|
|
3243
|
-
reason
|
|
3244
|
-
};
|
|
3245
|
-
}
|
|
3246
|
-
//#endregion
|
|
3247
3833
|
//#region src/runtime/adaptive-cost.ts
|
|
3248
3834
|
/**
|
|
3249
3835
|
* Bound Adaptive's benefit and cache-loss exposure without attributing the
|
|
@@ -3385,6 +3971,10 @@ function emitCompressionAudit(logger, record) {
|
|
|
3385
3971
|
*
|
|
3386
3972
|
* @module dsh-context-compression-improved-runtime
|
|
3387
3973
|
*/
|
|
3974
|
+
/** 节省统计配对键用原文(纯文本块才可配对;富内容返回 undefined)。 */
|
|
3975
|
+
function originalTextForSavings(candidate) {
|
|
3976
|
+
return flattenPlainText(candidate.event.data.message.content);
|
|
3977
|
+
}
|
|
3388
3978
|
/** Mixed deterministic selector behind the existing `ctx.toolResultPruner` seam. */
|
|
3389
3979
|
var ToolResultPruner = class extends Service {
|
|
3390
3980
|
static inject = ["tokenMeter"];
|
|
@@ -3406,6 +3996,8 @@ var ToolResultPruner = class extends Service {
|
|
|
3406
3996
|
});
|
|
3407
3997
|
/** Consolidated per-session mutable state. */
|
|
3408
3998
|
state;
|
|
3999
|
+
/** 0.1.5-specific: per-session sets of already-audited native summary seqs. */
|
|
4000
|
+
auditedNativeSummaries = /* @__PURE__ */ new WeakMap();
|
|
3409
4001
|
constructor(ctx, config = {}) {
|
|
3410
4002
|
super(ctx, "toolResultPruner");
|
|
3411
4003
|
ctx.inject(["tools", "systemPrompt"], (recoveryCtx) => {
|
|
@@ -3423,22 +4015,26 @@ var ToolResultPruner = class extends Service {
|
|
|
3423
4015
|
postflightDiagnostics: /* @__PURE__ */ new WeakMap(),
|
|
3424
4016
|
activeRequestBoundaries: /* @__PURE__ */ new WeakMap(),
|
|
3425
4017
|
tailTrimBoundaryAttempts: /* @__PURE__ */ new WeakMap(),
|
|
3426
|
-
policyResolutionAudits: /* @__PURE__ */ new WeakMap()
|
|
4018
|
+
policyResolutionAudits: /* @__PURE__ */ new WeakMap(),
|
|
4019
|
+
turnClocks: /* @__PURE__ */ new WeakMap(),
|
|
4020
|
+
estimatorRemainingTurns: /* @__PURE__ */ new WeakMap(),
|
|
4021
|
+
advisorChannels: /* @__PURE__ */ new WeakMap(),
|
|
4022
|
+
pendingIntentFolds: /* @__PURE__ */ new WeakMap(),
|
|
4023
|
+
intentFoldedSeqs: /* @__PURE__ */ new WeakMap(),
|
|
4024
|
+
intentBaselines: /* @__PURE__ */ new WeakMap()
|
|
3427
4025
|
};
|
|
4026
|
+
try {
|
|
4027
|
+
ctx.on("session/disposed", (session) => {
|
|
4028
|
+
try {
|
|
4029
|
+
const line = getSavingsLedger().sessionSummaryLine(String(session.id));
|
|
4030
|
+
if (line.includes("requests=0") === false || line.includes("net=0(exact)/0(est)") === false) ctx.logger.info("context-compression session savings (%s): %s", String(session.id), line);
|
|
4031
|
+
} catch {}
|
|
4032
|
+
});
|
|
4033
|
+
} catch {}
|
|
3428
4034
|
ctx.on("session/event", (session, event) => {
|
|
4035
|
+
this.scanForSeededNativeSummary(session);
|
|
3429
4036
|
if (event.type === "compaction/summary") {
|
|
3430
|
-
|
|
3431
|
-
schemaVersion: 1,
|
|
3432
|
-
kind: "native-auto-compact",
|
|
3433
|
-
sessionId: String(session.id),
|
|
3434
|
-
manifestEventType: "compaction/summary",
|
|
3435
|
-
manifestSeq: event.seq,
|
|
3436
|
-
reducer: "llm-summary",
|
|
3437
|
-
provider: event.data.provider,
|
|
3438
|
-
model: event.data.model,
|
|
3439
|
-
tokensBefore: event.data.shadowedTokenCount,
|
|
3440
|
-
tokensAfter: null
|
|
3441
|
-
});
|
|
4037
|
+
this.emitNativeSummaryAudit(session, event.seq, event.data);
|
|
3442
4038
|
return;
|
|
3443
4039
|
}
|
|
3444
4040
|
if (event.type === "compaction/end") try {
|
|
@@ -3453,12 +4049,15 @@ var ToolResultPruner = class extends Service {
|
|
|
3453
4049
|
this.state.activeRequestBoundaries.set(agent.session, boundary);
|
|
3454
4050
|
try {
|
|
3455
4051
|
if (!signal.aborted) try {
|
|
4052
|
+
this.turnClock(agent.session, turn);
|
|
3456
4053
|
this.runRequestBoundary(agent.session, turn, step - 1, signal);
|
|
3457
4054
|
} catch (error) {
|
|
3458
4055
|
this.auditFailure(agent.session, "fresh", "request-boundary", error);
|
|
3459
4056
|
ctx.logger.warn("context-compression fresh pass failed open: %o", error);
|
|
3460
4057
|
}
|
|
3461
|
-
|
|
4058
|
+
const outcome = await next();
|
|
4059
|
+
this.scanForSeededNativeSummary(agent.session);
|
|
4060
|
+
return outcome;
|
|
3462
4061
|
} finally {
|
|
3463
4062
|
if (this.state.activeRequestBoundaries.get(agent.session) === boundary) this.state.activeRequestBoundaries.delete(agent.session);
|
|
3464
4063
|
}
|
|
@@ -3472,7 +4071,12 @@ var ToolResultPruner = class extends Service {
|
|
|
3472
4071
|
this.auditFailure(agent.session, "fresh", "terminal-pass", error);
|
|
3473
4072
|
ctx.logger.warn("context-compression terminal pass failed open: %o", error);
|
|
3474
4073
|
}
|
|
4074
|
+
try {
|
|
4075
|
+
observeContextUsage(String(agent.session.id), measureForCompaction(this.ctx, agent.session).totalTokens, this.contextWindowForRequest(agent.session));
|
|
4076
|
+
} catch {}
|
|
3475
4077
|
this.postflightEstimatorPass(agent.session, signal).catch(() => void 0);
|
|
4078
|
+
this.postflightAdvisorPass(agent.session, turn, signal).catch(() => void 0);
|
|
4079
|
+
this.postflightIntentFoldPass(agent.session, turn, signal).catch(() => void 0);
|
|
3476
4080
|
});
|
|
3477
4081
|
}
|
|
3478
4082
|
/**
|
|
@@ -3480,9 +4084,6 @@ var ToolResultPruner = class extends Service {
|
|
|
3480
4084
|
* @param blocks - tool-result content to measure.
|
|
3481
4085
|
* @returns total Unicode code points across text blocks.
|
|
3482
4086
|
*/
|
|
3483
|
-
measureContent(blocks) {
|
|
3484
|
-
return measureContent(blocks);
|
|
3485
|
-
}
|
|
3486
4087
|
/**
|
|
3487
4088
|
* Apply the configured native head/middle/tail transform.
|
|
3488
4089
|
* @param blocks - original tool-result content.
|
|
@@ -3500,20 +4101,25 @@ var ToolResultPruner = class extends Service {
|
|
|
3500
4101
|
* @returns landed replacements and aggregate Unicode-code-point savings.
|
|
3501
4102
|
*/
|
|
3502
4103
|
pruneSession(session, options = {}) {
|
|
4104
|
+
this.scanForSeededNativeSummary(session);
|
|
3503
4105
|
const stage = options.stage ?? "pressure";
|
|
3504
4106
|
const contextWindowTokens = options.contextWindowTokens ?? this.contextWindowForRequest(session);
|
|
3505
4107
|
const policy = this.activePolicy(session, contextWindowTokens, stage);
|
|
3506
4108
|
if (policy === void 0) return emptyResult();
|
|
3507
4109
|
const profile = policy.profile;
|
|
3508
4110
|
const view = measureForCompaction(this.ctx, session);
|
|
3509
|
-
if (stage === "fresh")
|
|
4111
|
+
if (stage === "fresh") {
|
|
4112
|
+
const usage = officialRequestUsage(view);
|
|
4113
|
+
if (usage !== void 0) getSavingsLedger().recordUsage(String(session.id), usage);
|
|
4114
|
+
return this.decideFreshStep(session, options, policy, view);
|
|
4115
|
+
}
|
|
3510
4116
|
if (profile === "off") return emptyResult();
|
|
3511
4117
|
const landed = [];
|
|
3512
4118
|
if (policy.nativeToolResultEnabled) {
|
|
3513
4119
|
const eligible = this.snapshot(session, view).filter((candidate) => !this.isRecoveryExempt(session, candidate));
|
|
3514
4120
|
if (eligible.some((candidate) => candidate.count.kind !== "exact-tokenizer")) this.warnExactUnavailable(session, view, "native");
|
|
3515
4121
|
const planned = eligible.map((candidate) => this.planNative(candidate, session, stage, policy, view)).filter((entry) => entry !== null);
|
|
3516
|
-
landed.push(...this.landAll(session, planned));
|
|
4122
|
+
landed.push(...this.landAll(session, this.adviseReplacements(session, policy, planned, "history")));
|
|
3517
4123
|
if (landed.length === 0) {
|
|
3518
4124
|
const chars = eligible.map((candidate) => candidate.characterPressure);
|
|
3519
4125
|
this.auditComponent(session, policy, "native-tool-result", "pressure", "skipped", chars.length === 0 ? "no-tool-result-candidates" : Math.max(...chars) <= charsForTokens(policy.nativeTriggerTokens) ? "at-or-below-trigger" : planned.length === 0 ? "no-valid-reduction" : "recovery-tool-unavailable", {
|
|
@@ -3535,13 +4141,13 @@ var ToolResultPruner = class extends Service {
|
|
|
3535
4141
|
if (historyOutcome.kind === "planned") {
|
|
3536
4142
|
const capacityPressure = this.capacityPressureActive(session, view, policy);
|
|
3537
4143
|
historyAllowed = this.adaptiveHistoryAllowed(session, view, historyOutcome.plans, capacityPressure);
|
|
3538
|
-
if (historyAllowed) landed.push(...this.landAll(session, historyOutcome.plans));
|
|
4144
|
+
if (historyAllowed) landed.push(...this.landAll(session, this.adviseReplacements(session, policy, historyOutcome.plans, "history")));
|
|
3539
4145
|
}
|
|
3540
4146
|
} else {
|
|
3541
4147
|
historyAllowed = this.historyAllowed(session, policy, view);
|
|
3542
4148
|
if (historyAllowed) {
|
|
3543
4149
|
historyOutcome = this.planHistoricalAging(session, policy, view);
|
|
3544
|
-
if (historyOutcome.kind === "planned") landed.push(...this.landAll(session, historyOutcome.plans));
|
|
4150
|
+
if (historyOutcome.kind === "planned") landed.push(...this.landAll(session, this.adviseReplacements(session, policy, historyOutcome.plans, "history")));
|
|
3545
4151
|
}
|
|
3546
4152
|
}
|
|
3547
4153
|
if (!landed.some((entry) => entry.stage === "pressure")) this.auditHistoryEvaluation(session, policy, view, historyAllowed, historyOutcome);
|
|
@@ -3608,7 +4214,7 @@ var ToolResultPruner = class extends Service {
|
|
|
3608
4214
|
const block = located.text;
|
|
3609
4215
|
let checkpointSeq;
|
|
3610
4216
|
for (const seq of [...session.surface.nodes].reverse()) {
|
|
3611
|
-
const event = events
|
|
4217
|
+
const event = eventBySeq(events, seq);
|
|
3612
4218
|
if (event === void 0 || event.type !== "user/message") continue;
|
|
3613
4219
|
const source = event.data.source;
|
|
3614
4220
|
if (source === void 0 || source === null) continue;
|
|
@@ -3635,10 +4241,10 @@ var ToolResultPruner = class extends Service {
|
|
|
3635
4241
|
session.append("user/message", replacement, {
|
|
3636
4242
|
surfaceOp: {
|
|
3637
4243
|
op: "replace",
|
|
3638
|
-
|
|
3639
|
-
|
|
4244
|
+
startSeq: SessionSeq(checkpointSeq),
|
|
4245
|
+
endSeq: SessionSeq(checkpointSeq)
|
|
3640
4246
|
},
|
|
3641
|
-
sourceEventSeqs: [checkpointSeq]
|
|
4247
|
+
sourceEventSeqs: [SessionSeq(checkpointSeq)]
|
|
3642
4248
|
});
|
|
3643
4249
|
emitCompressionAudit(this.ctx.logger, {
|
|
3644
4250
|
schemaVersion: 1,
|
|
@@ -3695,7 +4301,9 @@ var ToolResultPruner = class extends Service {
|
|
|
3695
4301
|
verdicts = /* @__PURE__ */ new Map();
|
|
3696
4302
|
this.state.estimatorVerdicts.set(session, verdicts);
|
|
3697
4303
|
}
|
|
3698
|
-
|
|
4304
|
+
const detailed = parseEstimatorAnswerDetailed(answer);
|
|
4305
|
+
if (detailed.expectedRemainingTurns !== void 0) this.state.estimatorRemainingTurns.set(session, detailed.expectedRemainingTurns);
|
|
4306
|
+
for (const verdict of detailed.verdicts) {
|
|
3699
4307
|
if (verdicts.has(verdict.seq)) continue;
|
|
3700
4308
|
verdicts.set(verdict.seq, verdict.expired);
|
|
3701
4309
|
if (verdict.expired) expired += 1;
|
|
@@ -3719,10 +4327,338 @@ var ToolResultPruner = class extends Service {
|
|
|
3719
4327
|
ok
|
|
3720
4328
|
});
|
|
3721
4329
|
}
|
|
4330
|
+
/**
|
|
4331
|
+
* Advisory advisor pass at the turn boundary, strictly fire-and-forget.
|
|
4332
|
+
* Produces todolist-bound tail-task summaries, incremental relevance
|
|
4333
|
+
* scores, and a prefix-decay figure — all observational. Every short
|
|
4334
|
+
* circuit below (mode off, re-entry, cooldown, no task semantics, no
|
|
4335
|
+
* direct endpoint) returns without touching any state the pruning chain
|
|
4336
|
+
* reads, so the default configuration adds exactly zero behavior.
|
|
4337
|
+
*/
|
|
4338
|
+
async postflightAdvisorPass(session, turn, signal) {
|
|
4339
|
+
const policy = this.activePolicy(session);
|
|
4340
|
+
const presetOptions = policy?.presetOptions;
|
|
4341
|
+
const advisor = presetOptions?.advisor;
|
|
4342
|
+
if (policy === void 0 || presetOptions === void 0 || advisor === void 0 || advisor.mode === "") return;
|
|
4343
|
+
const advisorState = getAdvisorState(session);
|
|
4344
|
+
if (advisorState.inFlight) return;
|
|
4345
|
+
if (isCoolingDown(advisorState.failures, Date.now())) return;
|
|
4346
|
+
const events = sessionEvents(session);
|
|
4347
|
+
const task = collectTaskSemantics(events);
|
|
4348
|
+
if (task === void 0) return;
|
|
4349
|
+
const settings = this.activeSettings(session).presetOptions ?? {};
|
|
4350
|
+
if (advisor.mode === "direct" && (settings.estimatorBaseUrl === void 0 || settings.estimatorBaseUrl.length === 0 || settings.estimatorModel === void 0 || settings.estimatorModel.length === 0)) {
|
|
4351
|
+
emitCompressionAudit(this.ctx.logger, {
|
|
4352
|
+
schemaVersion: 1,
|
|
4353
|
+
kind: "advisor-outcome",
|
|
4354
|
+
sessionId: String(session.id),
|
|
4355
|
+
phase: "summary",
|
|
4356
|
+
channel: "direct",
|
|
4357
|
+
ok: false,
|
|
4358
|
+
turnIndex: turn,
|
|
4359
|
+
reason: "no-direct-endpoint",
|
|
4360
|
+
latencyMs: 0
|
|
4361
|
+
});
|
|
4362
|
+
advisorState.failures = {
|
|
4363
|
+
failures: (advisorState.failures?.failures ?? 0) + 1,
|
|
4364
|
+
cooldownUntil: Date.now() + backoffCooldownMs((advisorState.failures?.failures ?? 0) + 1)
|
|
4365
|
+
};
|
|
4366
|
+
return;
|
|
4367
|
+
}
|
|
4368
|
+
let channel = this.state.advisorChannels.get(session);
|
|
4369
|
+
if (channel === void 0) {
|
|
4370
|
+
channel = new SideChannel(this.ctx, settings, {
|
|
4371
|
+
mode: advisor.mode,
|
|
4372
|
+
timeoutMs: advisor.timeoutMs,
|
|
4373
|
+
maxTokens: 512
|
|
4374
|
+
});
|
|
4375
|
+
this.state.advisorChannels.set(session, channel);
|
|
4376
|
+
}
|
|
4377
|
+
const view = measureForCompaction(this.ctx, session);
|
|
4378
|
+
const candidates = this.snapshot(session, view).filter((candidate) => !this.isRecoveryExempt(session, candidate)).map((candidate) => ({
|
|
4379
|
+
seq: candidate.seq,
|
|
4380
|
+
characterPressure: candidate.characterPressure,
|
|
4381
|
+
preview: advisorCandidatePreview(candidate.call.name, candidate.event.data.message.content)
|
|
4382
|
+
}));
|
|
4383
|
+
let sawFailure = false;
|
|
4384
|
+
const outcome = await runSessionAdvisorPass(session, channel, (record) => {
|
|
4385
|
+
if (record.ok === false) sawFailure = true;
|
|
4386
|
+
emitCompressionAudit(this.ctx.logger, record);
|
|
4387
|
+
}, {
|
|
4388
|
+
profile: policy.profile,
|
|
4389
|
+
sessionId: String(session.id),
|
|
4390
|
+
turn,
|
|
4391
|
+
candidates,
|
|
4392
|
+
task: {
|
|
4393
|
+
source: task.source,
|
|
4394
|
+
todoVersion: task.todoVersion,
|
|
4395
|
+
taskText: task.taskText
|
|
4396
|
+
},
|
|
4397
|
+
advisor: {
|
|
4398
|
+
refreshTurns: advisor.refreshTurns,
|
|
4399
|
+
scoreThreshold: advisor.scoreThreshold,
|
|
4400
|
+
sampleLimit: advisor.sampleLimit,
|
|
4401
|
+
minTokens: advisor.minTokens
|
|
4402
|
+
},
|
|
4403
|
+
tailText: collectTailText(events),
|
|
4404
|
+
signal
|
|
4405
|
+
});
|
|
4406
|
+
if (outcome === void 0 && sawFailure && signal.aborted === false) advisorState.failures = {
|
|
4407
|
+
failures: (advisorState.failures?.failures ?? 0) + 1,
|
|
4408
|
+
cooldownUntil: Date.now() + backoffCooldownMs((advisorState.failures?.failures ?? 0) + 1)
|
|
4409
|
+
};
|
|
4410
|
+
else if (outcome !== void 0) advisorState.failures = void 0;
|
|
4411
|
+
}
|
|
4412
|
+
/**
|
|
4413
|
+
* Fire-and-forget postflight: evaluate the growth gate, and only when it
|
|
4414
|
+
* passes, select the consumed increment OUTSIDE the protected working set,
|
|
4415
|
+
* mask it to semantic-role records, and spend ONE summary-writer call. The
|
|
4416
|
+
* verdict stages as a pending fold that the NEXT pressure round lands via
|
|
4417
|
+
* the ordinary plan/apply machinery — the synchronous decision path never
|
|
4418
|
+
* waits on an LLM.
|
|
4419
|
+
*/
|
|
4420
|
+
async postflightIntentFoldPass(session, turn, signal) {
|
|
4421
|
+
const started = Date.now();
|
|
4422
|
+
const sessionId = String(session.id);
|
|
4423
|
+
const policy = this.activePolicy(session);
|
|
4424
|
+
const settings = this.activeSettings(session);
|
|
4425
|
+
const intentEnabled = settings.intentSummary.enabled;
|
|
4426
|
+
const override = getSummaryOverride(sessionId);
|
|
4427
|
+
observeIntentEnabled(sessionId, intentEnabled);
|
|
4428
|
+
if (policy === void 0) return;
|
|
4429
|
+
if (this.state.pendingIntentFolds.has(session)) return;
|
|
4430
|
+
const advisorState = getAdvisorState(session);
|
|
4431
|
+
if (advisorState.inFlight) return;
|
|
4432
|
+
if (isCoolingDown(advisorState.failures, Date.now())) return;
|
|
4433
|
+
const view = measureForCompaction(this.ctx, session);
|
|
4434
|
+
const thresholdPercent = settings.autoCompact.thresholdPercent;
|
|
4435
|
+
const contextWindow = policy.autoCompactTokens !== void 0 && thresholdPercent > 0 ? Math.round(policy.autoCompactTokens / (thresholdPercent / 100)) : void 0;
|
|
4436
|
+
if (!evaluateIntentGate({
|
|
4437
|
+
enabled: intentEnabled,
|
|
4438
|
+
override,
|
|
4439
|
+
liveTokens: view.totalTokens,
|
|
4440
|
+
contextWindow,
|
|
4441
|
+
baselineTokens: this.state.intentBaselines.get(session) ?? 0
|
|
4442
|
+
}).decision) return;
|
|
4443
|
+
const settingsPreset = settings.presetOptions;
|
|
4444
|
+
if (settingsPreset === void 0) return;
|
|
4445
|
+
if (settingsPreset.estimatorBaseUrl === void 0 || settingsPreset.estimatorBaseUrl.length === 0 || settingsPreset.estimatorModel === void 0 || settingsPreset.estimatorModel.length === 0) {
|
|
4446
|
+
emitCompressionAudit(this.ctx.logger, {
|
|
4447
|
+
schemaVersion: 1,
|
|
4448
|
+
kind: "intent-summary-outcome",
|
|
4449
|
+
sessionId,
|
|
4450
|
+
ok: false,
|
|
4451
|
+
reason: "no-direct-endpoint",
|
|
4452
|
+
turnIndex: turn,
|
|
4453
|
+
latencyMs: Date.now() - started
|
|
4454
|
+
});
|
|
4455
|
+
return;
|
|
4456
|
+
}
|
|
4457
|
+
const candidates = this.snapshot(session, view).filter((candidate) => !this.isRecoveryExempt(session, candidate));
|
|
4458
|
+
const range = computeIntentRange({
|
|
4459
|
+
candidates,
|
|
4460
|
+
protectedSeqs: this.protectedHistoryCandidateSeqs(candidates, policy),
|
|
4461
|
+
foldedSeqs: this.state.intentFoldedSeqs.get(session) ?? /* @__PURE__ */ new Set(),
|
|
4462
|
+
maxCandidates: 20
|
|
4463
|
+
});
|
|
4464
|
+
if (range.seqs.length === 0) return;
|
|
4465
|
+
const bySeq = new Map(candidates.map((candidate) => [candidate.seq, candidate]));
|
|
4466
|
+
const records = [];
|
|
4467
|
+
const errorLines = /* @__PURE__ */ new Set();
|
|
4468
|
+
for (const seq of range.seqs) {
|
|
4469
|
+
const candidate = bySeq.get(seq);
|
|
4470
|
+
if (candidate === void 0) continue;
|
|
4471
|
+
const result = candidate.event.data.message;
|
|
4472
|
+
const text = onlyTextBlock(result.content)?.text ?? "";
|
|
4473
|
+
const masked = maskCandidateForSummary(seq, candidate.call.name, candidate.call.arguments, text);
|
|
4474
|
+
records.push({
|
|
4475
|
+
seq,
|
|
4476
|
+
role: masked.role,
|
|
4477
|
+
toolName: candidate.call.name,
|
|
4478
|
+
line: masked.record
|
|
4479
|
+
});
|
|
4480
|
+
for (const line of extractErrorLines(text)) errorLines.add(line);
|
|
4481
|
+
}
|
|
4482
|
+
if (records.length === 0) return;
|
|
4483
|
+
const events = sessionEvents(session);
|
|
4484
|
+
const task = collectTaskSemantics(events);
|
|
4485
|
+
let channel = this.state.advisorChannels.get(session);
|
|
4486
|
+
if (channel === void 0) {
|
|
4487
|
+
channel = new SideChannel(this.ctx, settingsPreset, {
|
|
4488
|
+
mode: "direct",
|
|
4489
|
+
timeoutMs: 3e4,
|
|
4490
|
+
maxTokens: 512
|
|
4491
|
+
});
|
|
4492
|
+
this.state.advisorChannels.set(session, channel);
|
|
4493
|
+
}
|
|
4494
|
+
const answer = await channel.ask({
|
|
4495
|
+
system: buildIntentSummarySystemPrompt(),
|
|
4496
|
+
user: buildIntentSummaryUserPrompt(task?.taskText ?? "(no task semantics yet)", records.map((record) => record.line), collectTailText(events)),
|
|
4497
|
+
signal
|
|
4498
|
+
});
|
|
4499
|
+
const summaryCallChars = answer?.length ?? 0;
|
|
4500
|
+
const parsed = answer === void 0 ? void 0 : parseIntentSummaryAnswer(answer);
|
|
4501
|
+
if (parsed === void 0) {
|
|
4502
|
+
const failures = (advisorState.failures?.failures ?? 0) + 1;
|
|
4503
|
+
advisorState.failures = {
|
|
4504
|
+
failures,
|
|
4505
|
+
cooldownUntil: Date.now() + backoffCooldownMs(failures)
|
|
4506
|
+
};
|
|
4507
|
+
emitCompressionAudit(this.ctx.logger, {
|
|
4508
|
+
schemaVersion: 1,
|
|
4509
|
+
kind: "intent-summary-outcome",
|
|
4510
|
+
sessionId,
|
|
4511
|
+
ok: false,
|
|
4512
|
+
reason: answer === void 0 ? "ask-failed" : "parse-failed",
|
|
4513
|
+
turnIndex: turn,
|
|
4514
|
+
foldedCount: records.length,
|
|
4515
|
+
summaryCallChars,
|
|
4516
|
+
latencyMs: Date.now() - started
|
|
4517
|
+
});
|
|
4518
|
+
return;
|
|
4519
|
+
}
|
|
4520
|
+
this.state.pendingIntentFolds.set(session, {
|
|
4521
|
+
createdAt: Date.now(),
|
|
4522
|
+
turn,
|
|
4523
|
+
startSeq: range.seqs[0],
|
|
4524
|
+
endSeq: range.seqs[range.seqs.length - 1],
|
|
4525
|
+
summary: parsed.summary,
|
|
4526
|
+
errorLines: [...errorLines],
|
|
4527
|
+
records,
|
|
4528
|
+
summaryCallChars
|
|
4529
|
+
});
|
|
4530
|
+
emitCompressionAudit(this.ctx.logger, {
|
|
4531
|
+
schemaVersion: 1,
|
|
4532
|
+
kind: "intent-summary-outcome",
|
|
4533
|
+
sessionId,
|
|
4534
|
+
ok: true,
|
|
4535
|
+
reason: "staged",
|
|
4536
|
+
turnIndex: turn,
|
|
4537
|
+
foldedCount: records.length,
|
|
4538
|
+
summaryCallChars,
|
|
4539
|
+
latencyMs: Date.now() - started
|
|
4540
|
+
});
|
|
4541
|
+
}
|
|
4542
|
+
/**
|
|
4543
|
+
* Convert a staged pending fold into per-candidate planned replacements
|
|
4544
|
+
* (reducer `intent-summary`). Fail-open: a candidate that would grow, is
|
|
4545
|
+
* rich-content, or no longer exists keeps its original text. Returns
|
|
4546
|
+
* `undefined` when there is nothing (or no longer anything) to fold.
|
|
4547
|
+
*/
|
|
4548
|
+
applyPendingIntentFold(session, policy, view, eligible) {
|
|
4549
|
+
const pending = this.state.pendingIntentFolds.get(session);
|
|
4550
|
+
if (pending === void 0) return void 0;
|
|
4551
|
+
const bySeq = new Map(eligible.map((candidate) => [candidate.seq, candidate]));
|
|
4552
|
+
const foldable = pending.records.map((record) => record.seq).filter((seq) => bySeq.has(seq)).sort((a, b) => a - b);
|
|
4553
|
+
if (foldable.length === 0) {
|
|
4554
|
+
this.state.pendingIntentFolds.delete(session);
|
|
4555
|
+
return;
|
|
4556
|
+
}
|
|
4557
|
+
const plans = [];
|
|
4558
|
+
const foldedSeqs = /* @__PURE__ */ new Set();
|
|
4559
|
+
let reclaim = 0;
|
|
4560
|
+
let charsBefore = 0;
|
|
4561
|
+
let charsAfter = 0;
|
|
4562
|
+
for (const seq of foldable) {
|
|
4563
|
+
const candidate = bySeq.get(seq);
|
|
4564
|
+
const result = candidate.event.data.message;
|
|
4565
|
+
const block = onlyTextBlock(result.content);
|
|
4566
|
+
if (block === null) continue;
|
|
4567
|
+
const text = renderIntentFoldBlock(pending, seq);
|
|
4568
|
+
const plan = this.plan(candidate, [{
|
|
4569
|
+
...block,
|
|
4570
|
+
text
|
|
4571
|
+
}], rootToolResultSeq(session, candidate.seq), "intent-summary", "pressure", "history", policy.historyMode, view);
|
|
4572
|
+
if (plan === null || plan.charsAfter >= plan.charsBefore) continue;
|
|
4573
|
+
plans.push(plan);
|
|
4574
|
+
foldedSeqs.add(seq);
|
|
4575
|
+
reclaim += plan.charsBefore - plan.charsAfter;
|
|
4576
|
+
charsBefore += plan.charsBefore;
|
|
4577
|
+
charsAfter += plan.charsAfter;
|
|
4578
|
+
}
|
|
4579
|
+
if (plans.length === 0) return void 0;
|
|
4580
|
+
this.state.intentFoldedSeqs.get(session)?.forEach((seq) => foldedSeqs.add(seq));
|
|
4581
|
+
return {
|
|
4582
|
+
plans,
|
|
4583
|
+
reclaim,
|
|
4584
|
+
foldedSeqs,
|
|
4585
|
+
charsBefore,
|
|
4586
|
+
charsAfter,
|
|
4587
|
+
turn: pending.turn,
|
|
4588
|
+
summaryCallChars: pending.summaryCallChars
|
|
4589
|
+
};
|
|
4590
|
+
}
|
|
4591
|
+
/**
|
|
4592
|
+
* Monotonic per-session turn clock for advisory records. Bumped by the agent
|
|
4593
|
+
* loop payloads (`pre-step`); passes without a turn coordinate reuse the last
|
|
4594
|
+
* observed value.
|
|
4595
|
+
*/
|
|
4596
|
+
turnClock(session, turn) {
|
|
4597
|
+
const previous = this.state.turnClocks.get(session) ?? 0;
|
|
4598
|
+
const next = typeof turn === "number" && Number.isSafeInteger(turn) && turn > previous ? turn : previous;
|
|
4599
|
+
this.state.turnClocks.set(session, next);
|
|
4600
|
+
return next;
|
|
4601
|
+
}
|
|
4602
|
+
/**
|
|
4603
|
+
* Advisory benefit-model hook — what the retired human-gated review pipeline
|
|
4604
|
+
* left behind. It is the IDENTITY on the landing path: every plan it is given
|
|
4605
|
+
* comes back unchanged, because a reduction must never block automatic
|
|
4606
|
+
* processing. The model's band is published as a `reduction-advice` audit and
|
|
4607
|
+
* snapshotted onto the advisor state for the read-only report route, so the
|
|
4608
|
+
* cache-accounting insight survives without a gate.
|
|
4609
|
+
*/
|
|
4610
|
+
adviseReplacements(session, policy, plans, stage = "history") {
|
|
4611
|
+
if (plans.length === 0) return plans;
|
|
4612
|
+
const remainingTurns = this.state.estimatorRemainingTurns.get(session);
|
|
4613
|
+
const advice = adviseCandidates(plans.map((plan) => ({
|
|
4614
|
+
sourceSeq: plan.sourceSeq,
|
|
4615
|
+
tokensBefore: plan.tokensBefore,
|
|
4616
|
+
tokensAfter: plan.tokensAfter
|
|
4617
|
+
})), {
|
|
4618
|
+
alpha: DEFAULT_ADVICE_ALPHA,
|
|
4619
|
+
tailTokens: Math.max(1, policy.historyKeepRecentTokens),
|
|
4620
|
+
highImpactTokens: DEFAULT_ADVICE_HIGH_IMPACT_TOKENS,
|
|
4621
|
+
...remainingTurns === void 0 ? {} : { remainingTurns },
|
|
4622
|
+
stage
|
|
4623
|
+
});
|
|
4624
|
+
if (advice === void 0) return plans;
|
|
4625
|
+
const turn = this.turnClock(session);
|
|
4626
|
+
const itemSeqs = plans.map((plan) => plan.sourceSeq);
|
|
4627
|
+
getAdvisorState(session).lastAdvice = {
|
|
4628
|
+
band: advice.band,
|
|
4629
|
+
turn,
|
|
4630
|
+
itemSeqs,
|
|
4631
|
+
recoveredTokens: advice.benefit.recoveredTokens,
|
|
4632
|
+
penaltyTokens: advice.benefit.penaltyTokens,
|
|
4633
|
+
...advice.benefit.paybackTurns === void 0 ? {} : { paybackTurns: advice.benefit.paybackTurns }
|
|
4634
|
+
};
|
|
4635
|
+
emitCompressionAudit(this.ctx.logger, {
|
|
4636
|
+
schemaVersion: 1,
|
|
4637
|
+
kind: "reduction-advice",
|
|
4638
|
+
sessionId: String(session.id),
|
|
4639
|
+
profile: policy.profile,
|
|
4640
|
+
band: advice.band,
|
|
4641
|
+
stage,
|
|
4642
|
+
itemSeqs,
|
|
4643
|
+
pricedCandidates: advice.priced,
|
|
4644
|
+
maxTokensBefore: advice.maxTokensBefore,
|
|
4645
|
+
tokensBefore: plans.reduce((sum, plan) => sum + plan.tokensBefore, 0),
|
|
4646
|
+
tokensAfter: plans.reduce((sum, plan) => sum + plan.tokensAfter, 0),
|
|
4647
|
+
recoveredTokens: advice.benefit.recoveredTokens,
|
|
4648
|
+
penaltyTokens: advice.benefit.penaltyTokens,
|
|
4649
|
+
...advice.benefit.paybackTurns === void 0 ? {} : { paybackTurns: advice.benefit.paybackTurns },
|
|
4650
|
+
...advice.benefit.expectedSaving === void 0 ? {} : { expectedSaving: advice.benefit.expectedSaving },
|
|
4651
|
+
turnIndex: turn
|
|
4652
|
+
});
|
|
4653
|
+
return plans;
|
|
4654
|
+
}
|
|
3722
4655
|
activePolicy(session, contextWindowTokens, stage = "pressure") {
|
|
3723
4656
|
const settings = this.activeSettings(session);
|
|
3724
4657
|
try {
|
|
3725
|
-
const policy = resolvePolicy(this.state.config
|
|
4658
|
+
const policy = resolvePolicy(settings.presetOptions === void 0 ? this.state.config : {
|
|
4659
|
+
...this.state.config,
|
|
4660
|
+
presetOptions: settings.presetOptions
|
|
4661
|
+
}, settings.profile, settings.custom, {
|
|
3726
4662
|
...contextWindowTokens === void 0 ? {} : { contextWindowTokens },
|
|
3727
4663
|
autoCompactThresholdPercent: settings.autoCompact.thresholdPercent
|
|
3728
4664
|
});
|
|
@@ -3997,6 +4933,24 @@ var ToolResultPruner = class extends Service {
|
|
|
3997
4933
|
this.auditComponent(session, policy, "aggregate", "fresh", policy.aggregateEnabled ? "skipped" : "disabled", policy.aggregateEnabled ? "no-new-tool-result-candidates" : "profile-policy");
|
|
3998
4934
|
return emptyResult();
|
|
3999
4935
|
}
|
|
4936
|
+
const ledger = getSavingsLedger();
|
|
4937
|
+
const sid = String(session.id);
|
|
4938
|
+
for (const candidate of candidates) {
|
|
4939
|
+
const text = flattenPlainText(candidate.event.data.message.content);
|
|
4940
|
+
if (text === void 0) continue;
|
|
4941
|
+
ledger.noteFullText({
|
|
4942
|
+
sessionId: sid,
|
|
4943
|
+
seq: candidate.seq,
|
|
4944
|
+
text,
|
|
4945
|
+
measure: () => candidate.count.kind === "exact-tokenizer" && typeof candidate.count.tokens === "number" ? {
|
|
4946
|
+
tokens: candidate.count.tokens,
|
|
4947
|
+
basis: "exact-tokenizer"
|
|
4948
|
+
} : {
|
|
4949
|
+
tokens: Math.ceil(candidate.characterPressure / 4),
|
|
4950
|
+
basis: "characters"
|
|
4951
|
+
}
|
|
4952
|
+
});
|
|
4953
|
+
}
|
|
4000
4954
|
const plans = /* @__PURE__ */ new Map();
|
|
4001
4955
|
let freshPlanned = 0;
|
|
4002
4956
|
const dedupeEnabled = policy.presetOptions?.dedupeToolResults === true;
|
|
@@ -4040,7 +4994,8 @@ var ToolResultPruner = class extends Service {
|
|
|
4040
4994
|
if (total > charsForTokens(policy.aggregateTargetTokens)) this.ctx.logger.warn("context-compression fresh aggregate residual: %d characters exceed target %d", total, charsForTokens(policy.aggregateTargetTokens));
|
|
4041
4995
|
}
|
|
4042
4996
|
}
|
|
4043
|
-
const
|
|
4997
|
+
const freshCandidates = candidates.map((candidate) => plans.get(candidate.seq)).filter((plan) => plan !== void 0);
|
|
4998
|
+
const landed = this.landAll(session, this.adviseReplacements(session, policy, freshCandidates, "fresh"));
|
|
4044
4999
|
const freshLanded = landed.some((entry) => entry.stage === "fresh" && plans.get(entry.originalSeq)?.component === "fresh");
|
|
4045
5000
|
const aggregateLanded = landed.some((entry) => entry.stage === "fresh" && plans.get(entry.originalSeq)?.component === "aggregate");
|
|
4046
5001
|
if (!freshLanded) this.auditComponent(session, policy, "fresh", "fresh", policy.freshEnabled ? "skipped" : "disabled", !policy.freshEnabled ? "profile-policy" : (maxCandidateChars ?? 0) <= charsForTokens(policy.freshTriggerTokens) ? "at-or-below-trigger" : freshPlanned > 0 && aggregatePlanned > 0 ? "superseded-by-aggregate" : freshPlanned === 0 ? "no-valid-reduction" : "recovery-tool-unavailable", {
|
|
@@ -4069,7 +5024,7 @@ var ToolResultPruner = class extends Service {
|
|
|
4069
5024
|
const measured = new Map(view.measuredNodes.map((node) => [node.seq, node.count]));
|
|
4070
5025
|
const projectionPrices = new Map(view.nodes.map((node) => [node.seq, node.tokens]));
|
|
4071
5026
|
for (const seq of [...session.surface.nodes]) {
|
|
4072
|
-
const event = events
|
|
5027
|
+
const event = eventBySeq(events, seq);
|
|
4073
5028
|
if (event?.type !== "tool/result") continue;
|
|
4074
5029
|
const shadowedHeuristicTokenCount = projectionPrices.get(seq);
|
|
4075
5030
|
if (shadowedHeuristicTokenCount === void 0) throw new Error(`surface node ${String(seq)} is absent from the atomic legacy projection`);
|
|
@@ -4243,13 +5198,41 @@ var ToolResultPruner = class extends Service {
|
|
|
4243
5198
|
const isUnsafe = (candidate) => {
|
|
4244
5199
|
if (this.isRecoveryExempt(session, candidate)) return true;
|
|
4245
5200
|
const result = candidate.event.data.message.content[0];
|
|
4246
|
-
|
|
5201
|
+
const block = onlyTextBlock(result.content);
|
|
5202
|
+
if (block?.text.includes("[Intent summary") === true) return true;
|
|
5203
|
+
return block?.text.includes("[Old tool result content cleared from active context]") === true;
|
|
4247
5204
|
};
|
|
4248
5205
|
const safe = candidates.filter((candidate) => !isUnsafe(candidate));
|
|
4249
5206
|
const eligible = safe.filter((candidate) => !protectedSeqs.has(candidate.seq));
|
|
4250
5207
|
if (eligible.length === 0) return safe.length === 0 ? { kind: "no-safe-candidates" } : { kind: "protected-working-set" };
|
|
4251
5208
|
const planned = [];
|
|
4252
5209
|
let reclaim = 0;
|
|
5210
|
+
const intentApplied = this.applyPendingIntentFold(session, policy, view, eligible);
|
|
5211
|
+
if (intentApplied !== void 0) {
|
|
5212
|
+
planned.push(...intentApplied.plans);
|
|
5213
|
+
reclaim += intentApplied.reclaim;
|
|
5214
|
+
this.state.intentFoldedSeqs.set(session, intentApplied.foldedSeqs);
|
|
5215
|
+
this.state.pendingIntentFolds.delete(session);
|
|
5216
|
+
this.state.intentBaselines.set(session, view.totalTokens);
|
|
5217
|
+
recordIntentFold(String(session.id), {
|
|
5218
|
+
turn: intentApplied.turn,
|
|
5219
|
+
startSeq: intentApplied.foldedSeqs.size > 0 ? Math.min(...intentApplied.foldedSeqs) : 0,
|
|
5220
|
+
endSeq: intentApplied.foldedSeqs.size > 0 ? Math.max(...intentApplied.foldedSeqs) : 0,
|
|
5221
|
+
liveTokensBefore: view.totalTokens,
|
|
5222
|
+
at: Date.now()
|
|
5223
|
+
});
|
|
5224
|
+
emitCompressionAudit(this.ctx.logger, {
|
|
5225
|
+
schemaVersion: 1,
|
|
5226
|
+
kind: "intent-summary-outcome",
|
|
5227
|
+
sessionId: String(session.id),
|
|
5228
|
+
ok: true,
|
|
5229
|
+
reason: "landed",
|
|
5230
|
+
foldedCount: intentApplied.plans.length,
|
|
5231
|
+
...intentApplied.charsBefore > 0 ? { retentionRatio: intentApplied.charsAfter / intentApplied.charsBefore } : {},
|
|
5232
|
+
summaryCallChars: intentApplied.summaryCallChars
|
|
5233
|
+
});
|
|
5234
|
+
for (let index = eligible.length - 1; index >= 0; index -= 1) if (intentApplied.foldedSeqs.has(eligible[index].seq)) eligible.splice(index, 1);
|
|
5235
|
+
}
|
|
4253
5236
|
const minReclaimChars = charsForTokens(policy.historyMinReclaimTokens);
|
|
4254
5237
|
const microTarget = deadline === void 0 ? void 0 : Math.max(0, charsForTokens(deadline) - minReclaimChars);
|
|
4255
5238
|
const required = Math.max(minReclaimChars, total - trigger, ...microTarget === void 0 ? [] : [charsForTokens(view.totalTokens) - microTarget]);
|
|
@@ -4380,12 +5363,12 @@ var ToolResultPruner = class extends Service {
|
|
|
4380
5363
|
const completedSteps = /* @__PURE__ */ new Set();
|
|
4381
5364
|
for (const event of events) if (event.type === "turn/end") completedTurns.add(event.data.turn);
|
|
4382
5365
|
else if (event.type === "step/end") completedSteps.add(`${String(event.data.turn)}:${String(event.data.step)}`);
|
|
4383
|
-
const firstCompletedSurfaceTurn = session.surface.nodes.map((seq) => events
|
|
5366
|
+
const firstCompletedSurfaceTurn = session.surface.nodes.map((seq) => eventBySeq(events, seq)).filter((event) => (event?.type === "assistant/message" || event?.type === "tool/result") && completedTurns.has(event.data.turn)).reduce((first, event) => first === void 0 ? event.data.turn : Math.min(first, event.data.turn), void 0);
|
|
4384
5367
|
const nodes = [...session.surface.nodes];
|
|
4385
5368
|
for (let index = 0; index < nodes.length; index++) {
|
|
4386
5369
|
const assistantSeq = nodes[index];
|
|
4387
5370
|
if (assistantSeq === void 0) continue;
|
|
4388
|
-
const assistant = events
|
|
5371
|
+
const assistant = eventBySeq(events, assistantSeq);
|
|
4389
5372
|
if (assistant?.type !== "assistant/message" || assistant.data.interrupted === true || assistant.data.message.content.length === 0 || assistant.data.message.content.some((block) => block.type !== "tool-call") || assistant.data.turn === firstCompletedSurfaceTurn || !completedTurns.has(assistant.data.turn) || !completedSteps.has(`${String(assistant.data.turn)}:${String(assistant.data.step)}`)) continue;
|
|
4390
5373
|
const calls = assistant.data.message.content;
|
|
4391
5374
|
if (calls.some((call) => call.name === "context_compression_retrieve")) continue;
|
|
@@ -4440,8 +5423,13 @@ var ToolResultPruner = class extends Service {
|
|
|
4440
5423
|
const tokensAfter = exactTokensAfter ?? charsToTokens(stubChars);
|
|
4441
5424
|
const heuristicTokens = shadowedSeqs.reduce((sum, seq) => sum + (heuristic.get(seq) ?? 0), 0);
|
|
4442
5425
|
const range = {
|
|
4443
|
-
start: assistantSeq,
|
|
4444
|
-
end: resultSeqs.at(-1) ?? assistantSeq
|
|
5426
|
+
start: SessionSeq(assistantSeq),
|
|
5427
|
+
end: SessionSeq(resultSeqs.at(-1) ?? assistantSeq)
|
|
5428
|
+
};
|
|
5429
|
+
const surfaceRange = {
|
|
5430
|
+
op: "replace",
|
|
5431
|
+
startSeq: range.start,
|
|
5432
|
+
endSeq: range.end
|
|
4445
5433
|
};
|
|
4446
5434
|
if (!this.reserveTailTrimBoundaryAttempt(session)) {
|
|
4447
5435
|
this.auditComponent(session, policy, "tail-trim", "pressure", "skipped", "already-attempted-at-request-boundary", {
|
|
@@ -4459,10 +5447,7 @@ var ToolResultPruner = class extends Service {
|
|
|
4459
5447
|
let replacement;
|
|
4460
5448
|
try {
|
|
4461
5449
|
replacement = session.append("user/message", tailTrimMessage(stub), {
|
|
4462
|
-
surfaceOp:
|
|
4463
|
-
op: "replace",
|
|
4464
|
-
...range
|
|
4465
|
-
},
|
|
5450
|
+
surfaceOp: surfaceRange,
|
|
4466
5451
|
sourceEventSeqs: [manifest.seq, ...shadowedSeqs]
|
|
4467
5452
|
});
|
|
4468
5453
|
} catch (error) {
|
|
@@ -4488,6 +5473,16 @@ var ToolResultPruner = class extends Service {
|
|
|
4488
5473
|
tokenizerId: exact === true && exactSurface !== void 0 ? exactSurface.tokenizerId : "characters",
|
|
4489
5474
|
tokenizerRevision: exact === true && exactSurface !== void 0 ? exactSurface.tokenizerRevision : "chars-per-token-4.0"
|
|
4490
5475
|
});
|
|
5476
|
+
const groupText = shadowedSeqs.map((seq) => sessionEvents(session)[seq]).filter((event) => event?.type === "tool/result").map((event) => flattenPlainText(event.data.message.content)).filter((text) => text !== void 0).join("\n");
|
|
5477
|
+
if (groupText.length > 0) getSavingsLedger().recordSaving({
|
|
5478
|
+
sessionId: String(session.id),
|
|
5479
|
+
component: "tail-trim",
|
|
5480
|
+
tokensBefore,
|
|
5481
|
+
tokensAfter,
|
|
5482
|
+
basis: exact ? "exact-tokenizer" : "characters",
|
|
5483
|
+
sourceSeq: manifestSeq,
|
|
5484
|
+
originalText: groupText
|
|
5485
|
+
});
|
|
4491
5486
|
return;
|
|
4492
5487
|
}
|
|
4493
5488
|
this.auditComponent(session, policy, "tail-trim", "pressure", "skipped", "no-safe-eligible-tool-group", {
|
|
@@ -4578,10 +5573,10 @@ var ToolResultPruner = class extends Service {
|
|
|
4578
5573
|
});
|
|
4579
5574
|
const manifest = session.append("compaction/prune", {
|
|
4580
5575
|
shadowedRange: {
|
|
4581
|
-
start: candidate.seq,
|
|
4582
|
-
end: candidate.seq
|
|
5576
|
+
start: SessionSeq(candidate.seq),
|
|
5577
|
+
end: SessionSeq(candidate.seq)
|
|
4583
5578
|
},
|
|
4584
|
-
shadowedSeqs: [candidate.seq],
|
|
5579
|
+
shadowedSeqs: [SessionSeq(candidate.seq)],
|
|
4585
5580
|
shadowedTokenCount: candidate.shadowedHeuristicTokenCount
|
|
4586
5581
|
});
|
|
4587
5582
|
let replacement;
|
|
@@ -4592,10 +5587,10 @@ var ToolResultPruner = class extends Service {
|
|
|
4592
5587
|
}, {
|
|
4593
5588
|
surfaceOp: {
|
|
4594
5589
|
op: "replace",
|
|
4595
|
-
|
|
4596
|
-
|
|
5590
|
+
startSeq: SessionSeq(candidate.seq),
|
|
5591
|
+
endSeq: SessionSeq(candidate.seq)
|
|
4597
5592
|
},
|
|
4598
|
-
sourceEventSeqs: [candidate.seq]
|
|
5593
|
+
sourceEventSeqs: [SessionSeq(candidate.seq)]
|
|
4599
5594
|
});
|
|
4600
5595
|
} catch (error) {
|
|
4601
5596
|
this.auditPublicationFailure(session, plan.stage, plan.component, manifest.seq, error);
|
|
@@ -4622,6 +5617,16 @@ var ToolResultPruner = class extends Service {
|
|
|
4622
5617
|
tokenizerRevision: plan.tokenizerRevision,
|
|
4623
5618
|
...plan.elidedLines === void 0 ? {} : { elidedLines: plan.elidedLines }
|
|
4624
5619
|
});
|
|
5620
|
+
const pairedOriginal = originalTextForSavings(candidate);
|
|
5621
|
+
getSavingsLedger().recordSaving({
|
|
5622
|
+
sessionId: String(session.id),
|
|
5623
|
+
component: plan.component,
|
|
5624
|
+
tokensBefore: plan.tokensBefore,
|
|
5625
|
+
tokensAfter: plan.tokensAfter,
|
|
5626
|
+
basis: plan.measurementBasis,
|
|
5627
|
+
sourceSeq: plan.sourceSeq,
|
|
5628
|
+
...pairedOriginal === void 0 ? {} : { originalText: pairedOriginal }
|
|
5629
|
+
});
|
|
4625
5630
|
return {
|
|
4626
5631
|
originalSeq: candidate.seq,
|
|
4627
5632
|
sourceSeq: plan.sourceSeq,
|
|
@@ -4721,6 +5726,36 @@ var ToolResultPruner = class extends Service {
|
|
|
4721
5726
|
...detail
|
|
4722
5727
|
});
|
|
4723
5728
|
}
|
|
5729
|
+
/** Emit the native-auto-compact audit for one summary manifest, once. */
|
|
5730
|
+
emitNativeSummaryAudit(session, manifestSeq, data) {
|
|
5731
|
+
let audited = this.auditedNativeSummaries.get(session);
|
|
5732
|
+
if (audited === void 0) {
|
|
5733
|
+
audited = /* @__PURE__ */ new Set();
|
|
5734
|
+
this.auditedNativeSummaries.set(session, audited);
|
|
5735
|
+
}
|
|
5736
|
+
if (audited.has(manifestSeq)) return;
|
|
5737
|
+
audited.add(manifestSeq);
|
|
5738
|
+
emitCompressionAudit(this.ctx.logger, {
|
|
5739
|
+
schemaVersion: 1,
|
|
5740
|
+
kind: "native-auto-compact",
|
|
5741
|
+
sessionId: String(session.id),
|
|
5742
|
+
manifestEventType: "compaction/summary",
|
|
5743
|
+
manifestSeq,
|
|
5744
|
+
reducer: "llm-summary",
|
|
5745
|
+
provider: data.provider === void 0 ? "unknown" : String(data.provider),
|
|
5746
|
+
model: data.model === void 0 ? "unknown" : String(data.model),
|
|
5747
|
+
tokensBefore: typeof data.shadowedTokenCount === "number" ? data.shadowedTokenCount : null,
|
|
5748
|
+
tokensAfter: null
|
|
5749
|
+
});
|
|
5750
|
+
}
|
|
5751
|
+
/**
|
|
5752
|
+
* 0.1.5 commits Native auto-compact by reopening the Session with a seed
|
|
5753
|
+
* log; seed events never reach the `session/event` firehose, so scan the
|
|
5754
|
+
* snapshot for summary manifests the live listener could not observe.
|
|
5755
|
+
*/
|
|
5756
|
+
scanForSeededNativeSummary(session) {
|
|
5757
|
+
for (const event of sessionEvents(session)) if (event.type === "compaction/summary") this.emitNativeSummaryAudit(session, event.seq, event.data);
|
|
5758
|
+
}
|
|
4724
5759
|
auditFailure(session, stage, operation, error) {
|
|
4725
5760
|
emitCompressionAudit(this.ctx.logger, {
|
|
4726
5761
|
schemaVersion: 1,
|