dsh-context-compression-improved 0.6.5 → 0.7.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.ja.md +9 -0
- package/CHANGELOG.ko.md +9 -0
- package/CHANGELOG.md +26 -0
- package/CHANGELOG.zh.md +9 -0
- package/README.md +1 -0
- package/README.zh.md +1 -0
- package/eslint.config.js +76 -30
- package/package.json +18 -17
- package/packages/selector/dsh.plugin.json +1 -1
- package/packages/selector/lib/client.js +14 -3
- package/packages/selector/lib/index.js +92 -1
- package/packages/selector/lib/{advisor-state.js → intent-gate.js} +91 -3
- package/packages/selector/lib/profiles.d.ts +9 -0
- package/packages/selector/lib/pruner.d.ts +59 -0
- package/packages/selector/lib/pruner.js +410 -8
- package/packages/selector/lib/style.css +46 -46
- package/packages/selector/src/client/decode.ts +6 -2
- package/packages/selector/src/deepseek-v4-tokenizer.ts +1 -1
- package/packages/selector/src/index.ts +418 -411
- package/packages/selector/src/preset-overlay.ts +3 -0
- package/packages/selector/src/profiles.ts +30 -10
- package/packages/selector/src/pruner/content.ts +1 -1
- package/packages/selector/src/pruner/state.ts +7 -0
- package/packages/selector/src/pruner.ts +253 -9
- package/packages/selector/src/runtime/audit.ts +17 -0
- package/packages/selector/src/runtime/config.ts +36 -11
- package/packages/selector/src/runtime/reducers.ts +1 -1
- package/packages/selector/src/runtime/summary-command.ts +133 -0
- package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +46 -1
- package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +55 -0
- 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/locator.ts +2 -2
- package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +4 -1
- package/packages/selector/src/runtime/types.ts +12 -0
- package/packages/selector/tests/auto-compact.client.spec.tsx +214 -213
- package/packages/selector/tests/built/client-artifact.spec.ts +2 -0
- package/packages/selector/tests/code-skeleton.client.spec.ts +94 -93
- package/packages/selector/tests/custom-contract.client.spec.ts +223 -222
- package/packages/selector/tests/estimator-channel.client.spec.tsx +252 -252
- package/packages/selector/tests/helpers/legacy-settings/index.ts +15 -15
- package/packages/selector/tests/helpers/legacy-settings/legacy/provider.d.ts +41 -41
- package/packages/selector/tests/helpers/legacy-settings/legacy/provider.js +647 -647
- package/packages/selector/tests/helpers/legacy-settings/legacy/redact.js +78 -78
- package/packages/selector/tests/helpers/legacy-settings/legacy/util-values.js +234 -234
- package/packages/selector/tests/host-preset-overlay.host.spec.ts +203 -203
- package/packages/selector/tests/preset-options-write.client.spec.ts +188 -187
- package/packages/selector/tests/profiles.client.spec.tsx +436 -434
- package/packages/selector/tests/runtime/audit.spec.ts +275 -274
- package/packages/selector/tests/runtime/auto-compact-config.spec.ts +3 -3
- package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +4 -4
- 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/public/public-runtime.spec.ts +5 -0
- package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
- package/packages/selector/tests/standing-generation.host.spec.ts +15 -35
- package/scripts/packed-components-smoke.mjs +2 -0
- package/scripts/packed-install-e2e.mjs +1275 -1273
- package/scripts/verify-release.mjs +318 -317
- package/tsconfig.tests.json +3 -1
- package/vitest.config.ts +14 -0
- package/.agents-stash-064.patch +0 -39
- package/_dsh_devdeps.json +0 -50
- package/_verify064/package/package.json +0 -162
- package/_verify064/package/packages/selector/src/client/index.ts +0 -232
|
@@ -134,6 +134,15 @@ interface AutoCompactSettings {
|
|
|
134
134
|
interface CodeSkeletonSettings {
|
|
135
135
|
enabled: boolean;
|
|
136
136
|
}
|
|
137
|
+
/**
|
|
138
|
+
* Orthogonal turn-tail intent-summary gate. Independent of every profile:
|
|
139
|
+
* when enabled, the turn-boundary growth gate may fold consumed-increment
|
|
140
|
+
* tool results into an LLM-written intent block (skeleton + verbatim error
|
|
141
|
+
* lines are kept; the model only ever writes the summary segment).
|
|
142
|
+
*/
|
|
143
|
+
interface IntentSummarySettings {
|
|
144
|
+
enabled: boolean;
|
|
145
|
+
}
|
|
137
146
|
/**
|
|
138
147
|
* Persisted sub-capability overrides for the `tokenpilot-inspired` preset.
|
|
139
148
|
* Absent fields inherit the preset defaults; the section is only meaningful
|
|
@@ -173,6 +182,8 @@ interface ContextCompressionSettings {
|
|
|
173
182
|
autoCompact: AutoCompactSettings;
|
|
174
183
|
/** Code-skeleton reducer gate snapped independently of `profile`. */
|
|
175
184
|
codeSkeleton: CodeSkeletonSettings;
|
|
185
|
+
/** Turn-tail intent-summary gate snapped independently of `profile`. */
|
|
186
|
+
intentSummary: IntentSummarySettings;
|
|
176
187
|
/** Optional tokenpilot-inspired sub-capability overrides; absent inherits preset defaults. */
|
|
177
188
|
presetOptions?: PresetOptionsSettings;
|
|
178
189
|
}
|
|
@@ -397,6 +408,32 @@ interface EstimatorFailures {
|
|
|
397
408
|
cooldownUntil: number;
|
|
398
409
|
}
|
|
399
410
|
//#endregion
|
|
411
|
+
//#region src/runtime/tokenpilot/intent-input-mask.d.ts
|
|
412
|
+
type IntentRole = 'read-mask' | 'write-keep' | 'conservative';
|
|
413
|
+
//#endregion
|
|
414
|
+
//#region src/runtime/tokenpilot/intent-fold.d.ts
|
|
415
|
+
/** One staged fold awaiting the next pressure round. */
|
|
416
|
+
interface PendingIntentFold {
|
|
417
|
+
readonly createdAt: number;
|
|
418
|
+
readonly turn: number;
|
|
419
|
+
/** Inclusive seq span of the folded candidates. */
|
|
420
|
+
readonly startSeq: number;
|
|
421
|
+
readonly endSeq: number;
|
|
422
|
+
/** LLM-written summary segment (fail-open parsed, char-capped). */
|
|
423
|
+
readonly summary: string;
|
|
424
|
+
/** Verbatim error lines collected across the batch (never LLM-revoiced). */
|
|
425
|
+
readonly errorLines: readonly string[];
|
|
426
|
+
/** Per-candidate faces: read-mask single lines ride the block, keep-class lines prompt-only. */
|
|
427
|
+
readonly records: ReadonlyArray<{
|
|
428
|
+
readonly seq: number;
|
|
429
|
+
readonly role: IntentRole;
|
|
430
|
+
readonly toolName: string;
|
|
431
|
+
readonly line: string;
|
|
432
|
+
}>;
|
|
433
|
+
/** Characters consumed by the summary-writer call (credit accounting). */
|
|
434
|
+
readonly summaryCallChars: number;
|
|
435
|
+
}
|
|
436
|
+
//#endregion
|
|
400
437
|
//#region src/pruner/state.d.ts
|
|
401
438
|
/** Mutable per-session state bag used inside {@link ToolResultPruner}. */
|
|
402
439
|
interface PrunerState {
|
|
@@ -430,6 +467,12 @@ interface PrunerState {
|
|
|
430
467
|
readonly estimatorRemainingTurns: WeakMap<Session, number>;
|
|
431
468
|
/** Per-session advisor side channel, constructed once with the advisor overrides. */
|
|
432
469
|
readonly advisorChannels: WeakMap<Session, SideChannel>;
|
|
470
|
+
/** Staged intent fold awaiting the next pressure round (at most one per session). */
|
|
471
|
+
readonly pendingIntentFolds: WeakMap<Session, PendingIntentFold>;
|
|
472
|
+
/** Landed intent-fold seqs: fold-once, never reconsidered by any later stage. */
|
|
473
|
+
readonly intentFoldedSeqs: WeakMap<Session, Set<number>>;
|
|
474
|
+
/** Live-surface tokens when the last intent fold landed (growth-gate baseline). */
|
|
475
|
+
readonly intentBaselines: WeakMap<Session, number>;
|
|
433
476
|
}
|
|
434
477
|
//#endregion
|
|
435
478
|
//#region src/runtime/custom-policy.d.ts
|
|
@@ -759,6 +802,22 @@ declare class ToolResultPruner extends Service {
|
|
|
759
802
|
* reads, so the default configuration adds exactly zero behavior.
|
|
760
803
|
*/
|
|
761
804
|
private postflightAdvisorPass;
|
|
805
|
+
/**
|
|
806
|
+
* Fire-and-forget postflight: evaluate the growth gate, and only when it
|
|
807
|
+
* passes, select the consumed increment OUTSIDE the protected working set,
|
|
808
|
+
* mask it to semantic-role records, and spend ONE summary-writer call. The
|
|
809
|
+
* verdict stages as a pending fold that the NEXT pressure round lands via
|
|
810
|
+
* the ordinary plan/apply machinery — the synchronous decision path never
|
|
811
|
+
* waits on an LLM.
|
|
812
|
+
*/
|
|
813
|
+
private postflightIntentFoldPass;
|
|
814
|
+
/**
|
|
815
|
+
* Convert a staged pending fold into per-candidate planned replacements
|
|
816
|
+
* (reducer `intent-summary`). Fail-open: a candidate that would grow, is
|
|
817
|
+
* rich-content, or no longer exists keeps its original text. Returns
|
|
818
|
+
* `undefined` when there is nothing (or no longer anything) to fold.
|
|
819
|
+
*/
|
|
820
|
+
private applyPendingIntentFold;
|
|
762
821
|
/**
|
|
763
822
|
* Monotonic per-session turn clock for advisory records. Bumped by the agent
|
|
764
823
|
* loop payloads (`pre-step`); passes without a turn coordinate reuse the last
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { C as
|
|
1
|
+
import { A as resolveCustomPolicy, C as isCompressionProfile, D as resolvePolicy, E as resolveConfig, M as deepFreeze, N as COMPRESSION_PROFILES, O as CustomCompressionPolicySchema, S as codePointLength, T as parseContextCompressionSettings, _ as DEFAULTS, b as charsForTokens, c as invalidateOnTaskChange, d as recordRecertified, f as recordScore, g as ContextCompressionSettingsSchema, h as CONTEXT_COMPRESSION_SETTINGS_NAMESPACE, i as getAdvisorState, j as assertNever, k as DEFAULT_CUSTOM_COMPRESSION_POLICY, l as observeIntentEnabled, m as AUTO_COMPACT_THRESHOLD_LIMITS, r as evaluateIntentGate, s as getSummaryOverride, u as recordIntentFold, w as isValidAutoCompactThresholdPercent, x as charsToTokens, y as PRUNE_MARKER } from "./intent-gate.js";
|
|
2
2
|
import { a as validatePublishedTailTrim, i as tailTrimStub, n as tailTrimMessage, o as eventBySeq, r as tailTrimRef, s as sessionEvents, t as parseTailTrimRef } from "./tail-trim.js";
|
|
3
3
|
import z from "@deepseek-ai/schemastery";
|
|
4
4
|
import { createHash } from "node:crypto";
|
|
@@ -439,7 +439,7 @@ function nativePruneContent(blocks, thresholdChars, headChars, tailChars, marker
|
|
|
439
439
|
const tailStart = Math.min(points.length, Math.max(0, removedEnd - blockStart));
|
|
440
440
|
const intersectsRemoved = blockStart < removedEnd && blockEnd > removedStart;
|
|
441
441
|
const headText = points.slice(0, headEnd).join("");
|
|
442
|
-
const insertion = intersectsRemoved && !markerInserted && typeof marker === "function" ? marker(1 + newlinesBefore + headText.split("\n").length - 1) : intersectsRemoved && !markerInserted ? marker : "";
|
|
442
|
+
const insertion = intersectsRemoved && !markerInserted && typeof marker === "function" ? marker(1 + newlinesBefore + headText.split("\n").length - 1) : intersectsRemoved && !markerInserted && typeof marker === "string" ? marker : "";
|
|
443
443
|
if (insertion !== "") markerInserted = true;
|
|
444
444
|
const text = points.slice(0, headEnd).join("") + insertion + points.slice(tailStart).join("");
|
|
445
445
|
if (text !== "") pruned.push({
|
|
@@ -1179,7 +1179,7 @@ function buildLocatorBlock(events, shadowedRange) {
|
|
|
1179
1179
|
const data = event.data;
|
|
1180
1180
|
const content = Array.isArray(data.content) ? data.content : data.message?.content;
|
|
1181
1181
|
if (!Array.isArray(content)) continue;
|
|
1182
|
-
for (const block of content) if (block.type === "text") for (const path of extractSpillPaths(block.text)) spillFiles.add(path);
|
|
1182
|
+
for (const block of content) if (block.type === "text" && typeof block.text === "string") for (const path of extractSpillPaths(block.text)) spillFiles.add(path);
|
|
1183
1183
|
}
|
|
1184
1184
|
}
|
|
1185
1185
|
if (spillFiles.size === 0 && touchedFiles.size === 0) return null;
|
|
@@ -1397,7 +1397,7 @@ function reduceFreshToolResult(input, ranking) {
|
|
|
1397
1397
|
lines: normalized.folded,
|
|
1398
1398
|
contentText: normalized.contentText
|
|
1399
1399
|
};
|
|
1400
|
-
const command = extractCommand(input.argumentsText);
|
|
1400
|
+
const command = extractCommand$1(input.argumentsText);
|
|
1401
1401
|
const name = input.toolName.toLowerCase();
|
|
1402
1402
|
const toolClass = classifyToolSource(input.toolName, command, normalized.contentText);
|
|
1403
1403
|
const readTocFirst = toolClass === "read" && codePointLength(normalized.contentText) >= READ_TOC_MIN_CHARS;
|
|
@@ -2680,7 +2680,7 @@ function splitLines(text) {
|
|
|
2680
2680
|
* @param argumentsText - raw JSON arguments of the tool call.
|
|
2681
2681
|
* @returns the command string, or '' when absent.
|
|
2682
2682
|
*/
|
|
2683
|
-
function extractCommand(argumentsText) {
|
|
2683
|
+
function extractCommand$1(argumentsText) {
|
|
2684
2684
|
try {
|
|
2685
2685
|
const parsed = JSON.parse(argumentsText);
|
|
2686
2686
|
if (typeof parsed !== "object" || parsed === null) return "";
|
|
@@ -3248,6 +3248,42 @@ function parseAdvisorScores(text, validSeqs) {
|
|
|
3248
3248
|
}
|
|
3249
3249
|
return scores.size > 0 ? scores : void 0;
|
|
3250
3250
|
}
|
|
3251
|
+
/** Hard character cap for one intent-summary answer (summary segment only). */
|
|
3252
|
+
const INTENT_SUMMARY_CHAR_CAP = 1600;
|
|
3253
|
+
/**
|
|
3254
|
+
* Intent-summary writer prompts (task_2.3). Input records are already
|
|
3255
|
+
* semantic-role-masked by intent-input-mask.ts: read-class candidates are
|
|
3256
|
+
* one-line "read X" records, keep-class candidates carry skeleton heads and
|
|
3257
|
+
* VERBATIM error lines. The model writes ONLY the summary segment — it never
|
|
3258
|
+
* revoices error lines, and its answer must stay inside the char cap.
|
|
3259
|
+
*/
|
|
3260
|
+
function buildIntentSummarySystemPrompt() {
|
|
3261
|
+
return [
|
|
3262
|
+
"You write one concise intent summary of folded tool results for a coding agent session.",
|
|
3263
|
+
"Input: the session task (todolist) and per-tool slimmed records (read lines, or skeleton heads with verbatim error lines).",
|
|
3264
|
+
`Write ONLY what the agent DID and LEARNED in this span, as flowing prose under ${INTENT_SUMMARY_CHAR_CAP} characters.`,
|
|
3265
|
+
"Mention which files/areas were consulted and what changed, so a later turn can continue without the originals.",
|
|
3266
|
+
"Never invent files, commands, or outcomes absent from the records. Never revoice error lines; they are preserved verbatim elsewhere.",
|
|
3267
|
+
"Answer with ONLY one JSON object: {\"summary\":\"<prose>\"}. Never add commentary."
|
|
3268
|
+
].join(" ");
|
|
3269
|
+
}
|
|
3270
|
+
function buildIntentSummaryUserPrompt(taskText, records, tailText) {
|
|
3271
|
+
const nl = String.fromCharCode(10);
|
|
3272
|
+
return [
|
|
3273
|
+
`task: ${taskText.replace(/\s+/gu, " ").slice(0, 600)}`,
|
|
3274
|
+
records.length > 0 ? `records:${nl}${records.join(nl)}` : "records: (none)",
|
|
3275
|
+
tailText.trim().length > 0 ? `recent tail:${nl}${tailText.trim().slice(0, 1200)}` : "recent tail: (none)"
|
|
3276
|
+
].join("\n\n");
|
|
3277
|
+
}
|
|
3278
|
+
/** Fail-open parse of one intent-summary answer; `undefined` on any malformed shape. */
|
|
3279
|
+
function parseIntentSummaryAnswer(text) {
|
|
3280
|
+
const parsed = firstJsonObject(text);
|
|
3281
|
+
if (parsed === void 0) return void 0;
|
|
3282
|
+
const summary = parsed.summary;
|
|
3283
|
+
if (typeof summary !== "string" || summary.trim().length === 0) return void 0;
|
|
3284
|
+
if (summary.length > 3200) return void 0;
|
|
3285
|
+
return { summary: summary.trim().slice(0, INTENT_SUMMARY_CHAR_CAP) };
|
|
3286
|
+
}
|
|
3251
3287
|
//#endregion
|
|
3252
3288
|
//#region src/runtime/tokenpilot/advisor.ts
|
|
3253
3289
|
/** Character cap for the recent-text fallback and the tail-text summary input. */
|
|
@@ -3549,6 +3585,162 @@ async function runSessionAdvisorPass(session, channel, emit, input) {
|
|
|
3549
3585
|
}
|
|
3550
3586
|
}
|
|
3551
3587
|
//#endregion
|
|
3588
|
+
//#region src/runtime/tokenpilot/intent-input-mask.ts
|
|
3589
|
+
/**
|
|
3590
|
+
* Semantic-role input masking for the intent-summary writer (task_2.2).
|
|
3591
|
+
*
|
|
3592
|
+
* The intent summary records historical TASK semantics — for read-class tools
|
|
3593
|
+
* the semantics are "read X", never the file body, so the body is masked to a
|
|
3594
|
+
* one-line record before it can reach the summary prompt. Write-class results
|
|
3595
|
+
* (edits) ARE task semantics and keep their skeleton + verbatim error lines.
|
|
3596
|
+
*
|
|
3597
|
+
* Classification REUSES `classifyToolSource()` (reducers.ts routes on the
|
|
3598
|
+
* same classes): hand-rolling a name→role map here would regress its fixed
|
|
3599
|
+
* misclassification edges (mcp→generic, web_search/memory_search not being
|
|
3600
|
+
* content search, glob being path-listing, execute_sql not being shell).
|
|
3601
|
+
* Only the write class is layered on top — `ToolClass` has no write member.
|
|
3602
|
+
*/
|
|
3603
|
+
/** Exact-token write layer, same tokenization discipline as toolclass. */
|
|
3604
|
+
const WRITE_NAMES = /* @__PURE__ */ new Set([
|
|
3605
|
+
"apply_patch",
|
|
3606
|
+
"multi_edit",
|
|
3607
|
+
"create_file",
|
|
3608
|
+
"write_to_file",
|
|
3609
|
+
"str_replace_editor"
|
|
3610
|
+
]);
|
|
3611
|
+
const WRITE_TOKENS = /* @__PURE__ */ new Set([
|
|
3612
|
+
"write",
|
|
3613
|
+
"edit",
|
|
3614
|
+
"patch"
|
|
3615
|
+
]);
|
|
3616
|
+
function hasWriteToken(name) {
|
|
3617
|
+
const lowered = name.toLowerCase();
|
|
3618
|
+
if (WRITE_NAMES.has(lowered)) return true;
|
|
3619
|
+
return lowered.split(/[-_/]+/).some((token) => WRITE_TOKENS.has(token));
|
|
3620
|
+
}
|
|
3621
|
+
/**
|
|
3622
|
+
* Role for one candidate. The write layer is consulted first; everything
|
|
3623
|
+
* else defers to the shared classifier. `shell`/`generic` stay conservative
|
|
3624
|
+
* (skeleton + error lines, never a blind mask) — a bash result can be a
|
|
3625
|
+
* mutation even when its name says nothing.
|
|
3626
|
+
*/
|
|
3627
|
+
function classifyIntentRole(toolName, command, text) {
|
|
3628
|
+
if (hasWriteToken(toolName)) return "write-keep";
|
|
3629
|
+
const toolClass = classifyToolSource(toolName, command, text);
|
|
3630
|
+
if (toolClass === "read" || toolClass === "search" || toolClass === "path-listing") return "read-mask";
|
|
3631
|
+
return "conservative";
|
|
3632
|
+
}
|
|
3633
|
+
const ERROR_LINE_PATTERN = /\b(error|failed|failure|exception|panic|fatal|traceback|unreachable|denied)\b/i;
|
|
3634
|
+
const KEEP_HEAD_LINES = 40;
|
|
3635
|
+
const KEEP_HEAD_CHARS = 2e3;
|
|
3636
|
+
/** Verbatim error/warn lines kept out of the LLM's hands and into the intent block. */
|
|
3637
|
+
function extractErrorLines(text) {
|
|
3638
|
+
return text.split("\n").filter((line) => ERROR_LINE_PATTERN.test(line)).slice(0, 10);
|
|
3639
|
+
}
|
|
3640
|
+
/** Count lines and code points for the read-mask record tail. */
|
|
3641
|
+
function scaleOf(text) {
|
|
3642
|
+
return {
|
|
3643
|
+
lines: text.length === 0 ? 0 : text.split("\n").length,
|
|
3644
|
+
chars: text.length
|
|
3645
|
+
};
|
|
3646
|
+
}
|
|
3647
|
+
/**
|
|
3648
|
+
* Build the prompt face for one candidate. Read-mask output contains NONE of
|
|
3649
|
+
* the original body — only the tool name, the call's target argument, and
|
|
3650
|
+
* the dropped scale — so a hostile body can never leak into the summary.
|
|
3651
|
+
*/
|
|
3652
|
+
function maskCandidateForSummary(seq, toolName, argumentsText, text) {
|
|
3653
|
+
const role = classifyIntentRole(toolName, extractCommand(argumentsText), text);
|
|
3654
|
+
if (role === "read-mask") {
|
|
3655
|
+
const { lines, chars } = scaleOf(text);
|
|
3656
|
+
return {
|
|
3657
|
+
seq,
|
|
3658
|
+
role,
|
|
3659
|
+
record: `${toolName} ${extractTarget(argumentsText)} -> masked (${lines} lines / ${chars} chars)`
|
|
3660
|
+
};
|
|
3661
|
+
}
|
|
3662
|
+
const head = text.split("\n", KEEP_HEAD_LINES).join("\n").slice(0, KEEP_HEAD_CHARS);
|
|
3663
|
+
const errorLines = extractErrorLines(text);
|
|
3664
|
+
return {
|
|
3665
|
+
seq,
|
|
3666
|
+
role,
|
|
3667
|
+
record: `${toolName} (seq ${seq})\n${head}${errorLines.length > 0 ? `\nerror lines (verbatim):\n${errorLines.join("\n")}` : ""}`
|
|
3668
|
+
};
|
|
3669
|
+
}
|
|
3670
|
+
/** Extract a short command head from a tool-call arguments JSON string. */
|
|
3671
|
+
function extractCommand(argumentsText) {
|
|
3672
|
+
try {
|
|
3673
|
+
const parsed = JSON.parse(argumentsText);
|
|
3674
|
+
if (parsed !== null && typeof parsed === "object") {
|
|
3675
|
+
const command = parsed.command;
|
|
3676
|
+
if (typeof command === "string") return command.slice(0, 200);
|
|
3677
|
+
}
|
|
3678
|
+
} catch {}
|
|
3679
|
+
return "";
|
|
3680
|
+
}
|
|
3681
|
+
/** Extract the most target-like string argument (path/query/url) for read-mask records. */
|
|
3682
|
+
function extractTarget(argumentsText) {
|
|
3683
|
+
try {
|
|
3684
|
+
const parsed = JSON.parse(argumentsText);
|
|
3685
|
+
if (parsed !== null && typeof parsed === "object") {
|
|
3686
|
+
const record = parsed;
|
|
3687
|
+
const target = [
|
|
3688
|
+
record.path,
|
|
3689
|
+
record.file_path,
|
|
3690
|
+
record.query,
|
|
3691
|
+
record.url,
|
|
3692
|
+
record.pattern,
|
|
3693
|
+
record.glob
|
|
3694
|
+
].find((candidate) => typeof candidate === "string" && candidate.trim().length > 0);
|
|
3695
|
+
if (typeof target === "string") return target.slice(0, 160);
|
|
3696
|
+
const first = Object.values(record).find((value) => typeof value === "string");
|
|
3697
|
+
if (typeof first === "string") return first.slice(0, 160);
|
|
3698
|
+
}
|
|
3699
|
+
} catch {}
|
|
3700
|
+
return "(unparsed target)";
|
|
3701
|
+
}
|
|
3702
|
+
//#endregion
|
|
3703
|
+
//#region src/runtime/tokenpilot/intent-range.ts
|
|
3704
|
+
/**
|
|
3705
|
+
* Oldest-first selection of foldable candidates. Excludes the protected
|
|
3706
|
+
* working set and already-folded seqs; caps the batch size.
|
|
3707
|
+
*/
|
|
3708
|
+
function computeIntentRange(input) {
|
|
3709
|
+
const unprotected = input.candidates.filter((candidate) => !input.protectedSeqs.has(candidate.seq));
|
|
3710
|
+
const skippedProtected = input.candidates.length - unprotected.length;
|
|
3711
|
+
const eligible = unprotected.filter((candidate) => !input.foldedSeqs.has(candidate.seq));
|
|
3712
|
+
const skippedFolded = unprotected.length - eligible.length;
|
|
3713
|
+
return {
|
|
3714
|
+
seqs: [...eligible].sort((a, b) => a.seq - b.seq).slice(0, Math.max(0, input.maxCandidates)).map((candidate) => candidate.seq),
|
|
3715
|
+
skippedProtected,
|
|
3716
|
+
skippedFolded
|
|
3717
|
+
};
|
|
3718
|
+
}
|
|
3719
|
+
//#endregion
|
|
3720
|
+
//#region src/runtime/tokenpilot/intent-fold.ts
|
|
3721
|
+
/** Marker written into every folded block; its presence makes a seq unfoldable again (fold-once). */
|
|
3722
|
+
const INTENT_FOLD_MARKER = "[Intent summary";
|
|
3723
|
+
/** Render the replacement text for one folded candidate. Pure. */
|
|
3724
|
+
function renderIntentFoldBlock(pending, seq) {
|
|
3725
|
+
const start = pending.startSeq;
|
|
3726
|
+
const end = pending.endSeq;
|
|
3727
|
+
if (seq === start) {
|
|
3728
|
+
const readLines = pending.records.filter((record) => record.role === "read-mask").map((record) => record.line);
|
|
3729
|
+
const consulted = readLines.length > 0 ? `Consulted: ${readLines.join("; ")}` : "";
|
|
3730
|
+
const errorBlock = pending.errorLines.length > 0 ? `\nError lines (verbatim):\n${pending.errorLines.join("\n")}` : "";
|
|
3731
|
+
return [
|
|
3732
|
+
`${INTENT_FOLD_MARKER} of folded tool results seq ${start}..${end}]`,
|
|
3733
|
+
pending.summary,
|
|
3734
|
+
consulted,
|
|
3735
|
+
errorBlock,
|
|
3736
|
+
"[Original content remains in the session log at the listed seq values.]"
|
|
3737
|
+
].filter((part) => part.length > 0).join("\n");
|
|
3738
|
+
}
|
|
3739
|
+
const record = pending.records.find((entry) => entry.seq === seq);
|
|
3740
|
+
const face = record === void 0 ? `${seq}` : record.role === "read-mask" ? record.line : `${record.toolName} result folded into the batch intent summary`;
|
|
3741
|
+
return `${INTENT_FOLD_MARKER} folded into the batch summary above (seq ${start}..${end})] ${face}`;
|
|
3742
|
+
}
|
|
3743
|
+
//#endregion
|
|
3552
3744
|
//#region src/runtime/tokenpilot/dedup.ts
|
|
3553
3745
|
/**
|
|
3554
3746
|
* TokenPilot-inspired A1: byte-identical repeated tool-result dedup.
|
|
@@ -4040,7 +4232,10 @@ var ToolResultPruner = class extends Service {
|
|
|
4040
4232
|
policyResolutionAudits: /* @__PURE__ */ new WeakMap(),
|
|
4041
4233
|
turnClocks: /* @__PURE__ */ new WeakMap(),
|
|
4042
4234
|
estimatorRemainingTurns: /* @__PURE__ */ new WeakMap(),
|
|
4043
|
-
advisorChannels: /* @__PURE__ */ new WeakMap()
|
|
4235
|
+
advisorChannels: /* @__PURE__ */ new WeakMap(),
|
|
4236
|
+
pendingIntentFolds: /* @__PURE__ */ new WeakMap(),
|
|
4237
|
+
intentFoldedSeqs: /* @__PURE__ */ new WeakMap(),
|
|
4238
|
+
intentBaselines: /* @__PURE__ */ new WeakMap()
|
|
4044
4239
|
};
|
|
4045
4240
|
ctx.on("session/event", (session, event) => {
|
|
4046
4241
|
this.scanForSeededNativeSummary(session);
|
|
@@ -4084,6 +4279,7 @@ var ToolResultPruner = class extends Service {
|
|
|
4084
4279
|
}
|
|
4085
4280
|
this.postflightEstimatorPass(agent.session, signal).catch(() => void 0);
|
|
4086
4281
|
this.postflightAdvisorPass(agent.session, turn, signal).catch(() => void 0);
|
|
4282
|
+
this.postflightIntentFoldPass(agent.session, turn, signal).catch(() => void 0);
|
|
4087
4283
|
});
|
|
4088
4284
|
}
|
|
4089
4285
|
/**
|
|
@@ -4411,6 +4607,185 @@ var ToolResultPruner = class extends Service {
|
|
|
4411
4607
|
else if (outcome !== void 0) advisorState.failures = void 0;
|
|
4412
4608
|
}
|
|
4413
4609
|
/**
|
|
4610
|
+
* Fire-and-forget postflight: evaluate the growth gate, and only when it
|
|
4611
|
+
* passes, select the consumed increment OUTSIDE the protected working set,
|
|
4612
|
+
* mask it to semantic-role records, and spend ONE summary-writer call. The
|
|
4613
|
+
* verdict stages as a pending fold that the NEXT pressure round lands via
|
|
4614
|
+
* the ordinary plan/apply machinery — the synchronous decision path never
|
|
4615
|
+
* waits on an LLM.
|
|
4616
|
+
*/
|
|
4617
|
+
async postflightIntentFoldPass(session, turn, signal) {
|
|
4618
|
+
const started = Date.now();
|
|
4619
|
+
const sessionId = String(session.id);
|
|
4620
|
+
const policy = this.activePolicy(session);
|
|
4621
|
+
const settings = this.activeSettings(session);
|
|
4622
|
+
const intentEnabled = settings.intentSummary.enabled;
|
|
4623
|
+
const override = getSummaryOverride(sessionId);
|
|
4624
|
+
observeIntentEnabled(sessionId, intentEnabled);
|
|
4625
|
+
if (policy === void 0) return;
|
|
4626
|
+
if (this.state.pendingIntentFolds.has(session)) return;
|
|
4627
|
+
const advisorState = getAdvisorState(session);
|
|
4628
|
+
if (advisorState.inFlight) return;
|
|
4629
|
+
if (isCoolingDown(advisorState.failures, Date.now())) return;
|
|
4630
|
+
const view = measureForCompaction(this.ctx, session);
|
|
4631
|
+
const thresholdPercent = settings.autoCompact.thresholdPercent;
|
|
4632
|
+
const contextWindow = policy.autoCompactTokens !== void 0 && thresholdPercent > 0 ? Math.round(policy.autoCompactTokens / (thresholdPercent / 100)) : void 0;
|
|
4633
|
+
if (!evaluateIntentGate({
|
|
4634
|
+
enabled: intentEnabled,
|
|
4635
|
+
override,
|
|
4636
|
+
liveTokens: view.totalTokens,
|
|
4637
|
+
contextWindow,
|
|
4638
|
+
baselineTokens: this.state.intentBaselines.get(session) ?? 0
|
|
4639
|
+
}).decision) return;
|
|
4640
|
+
const settingsPreset = settings.presetOptions;
|
|
4641
|
+
if (settingsPreset === void 0) return;
|
|
4642
|
+
if (settingsPreset.estimatorBaseUrl === void 0 || settingsPreset.estimatorBaseUrl.length === 0 || settingsPreset.estimatorModel === void 0 || settingsPreset.estimatorModel.length === 0) {
|
|
4643
|
+
emitCompressionAudit(this.ctx.logger, {
|
|
4644
|
+
schemaVersion: 1,
|
|
4645
|
+
kind: "intent-summary-outcome",
|
|
4646
|
+
sessionId,
|
|
4647
|
+
ok: false,
|
|
4648
|
+
reason: "no-direct-endpoint",
|
|
4649
|
+
turnIndex: turn,
|
|
4650
|
+
latencyMs: Date.now() - started
|
|
4651
|
+
});
|
|
4652
|
+
return;
|
|
4653
|
+
}
|
|
4654
|
+
const candidates = this.snapshot(session, view).filter((candidate) => !this.isRecoveryExempt(session, candidate));
|
|
4655
|
+
const range = computeIntentRange({
|
|
4656
|
+
candidates,
|
|
4657
|
+
protectedSeqs: this.protectedHistoryCandidateSeqs(candidates, policy),
|
|
4658
|
+
foldedSeqs: this.state.intentFoldedSeqs.get(session) ?? /* @__PURE__ */ new Set(),
|
|
4659
|
+
maxCandidates: 20
|
|
4660
|
+
});
|
|
4661
|
+
if (range.seqs.length === 0) return;
|
|
4662
|
+
const bySeq = new Map(candidates.map((candidate) => [candidate.seq, candidate]));
|
|
4663
|
+
const records = [];
|
|
4664
|
+
const errorLines = /* @__PURE__ */ new Set();
|
|
4665
|
+
for (const seq of range.seqs) {
|
|
4666
|
+
const candidate = bySeq.get(seq);
|
|
4667
|
+
if (candidate === void 0) continue;
|
|
4668
|
+
const result = candidate.event.data.message;
|
|
4669
|
+
const text = onlyTextBlock(result.content)?.text ?? "";
|
|
4670
|
+
const masked = maskCandidateForSummary(seq, candidate.call.name, candidate.call.arguments, text);
|
|
4671
|
+
records.push({
|
|
4672
|
+
seq,
|
|
4673
|
+
role: masked.role,
|
|
4674
|
+
toolName: candidate.call.name,
|
|
4675
|
+
line: masked.record
|
|
4676
|
+
});
|
|
4677
|
+
for (const line of extractErrorLines(text)) errorLines.add(line);
|
|
4678
|
+
}
|
|
4679
|
+
if (records.length === 0) return;
|
|
4680
|
+
const events = sessionEvents(session);
|
|
4681
|
+
const task = collectTaskSemantics(events);
|
|
4682
|
+
let channel = this.state.advisorChannels.get(session);
|
|
4683
|
+
if (channel === void 0) {
|
|
4684
|
+
channel = new SideChannel(this.ctx, settingsPreset, {
|
|
4685
|
+
mode: "direct",
|
|
4686
|
+
timeoutMs: 3e4,
|
|
4687
|
+
maxTokens: 512
|
|
4688
|
+
});
|
|
4689
|
+
this.state.advisorChannels.set(session, channel);
|
|
4690
|
+
}
|
|
4691
|
+
const answer = await channel.ask({
|
|
4692
|
+
system: buildIntentSummarySystemPrompt(),
|
|
4693
|
+
user: buildIntentSummaryUserPrompt(task?.taskText ?? "(no task semantics yet)", records.map((record) => record.line), collectTailText(events)),
|
|
4694
|
+
signal
|
|
4695
|
+
});
|
|
4696
|
+
const summaryCallChars = answer?.length ?? 0;
|
|
4697
|
+
const parsed = answer === void 0 ? void 0 : parseIntentSummaryAnswer(answer);
|
|
4698
|
+
if (parsed === void 0) {
|
|
4699
|
+
const failures = (advisorState.failures?.failures ?? 0) + 1;
|
|
4700
|
+
advisorState.failures = {
|
|
4701
|
+
failures,
|
|
4702
|
+
cooldownUntil: Date.now() + backoffCooldownMs(failures)
|
|
4703
|
+
};
|
|
4704
|
+
emitCompressionAudit(this.ctx.logger, {
|
|
4705
|
+
schemaVersion: 1,
|
|
4706
|
+
kind: "intent-summary-outcome",
|
|
4707
|
+
sessionId,
|
|
4708
|
+
ok: false,
|
|
4709
|
+
reason: answer === void 0 ? "ask-failed" : "parse-failed",
|
|
4710
|
+
turnIndex: turn,
|
|
4711
|
+
foldedCount: records.length,
|
|
4712
|
+
summaryCallChars,
|
|
4713
|
+
latencyMs: Date.now() - started
|
|
4714
|
+
});
|
|
4715
|
+
return;
|
|
4716
|
+
}
|
|
4717
|
+
this.state.pendingIntentFolds.set(session, {
|
|
4718
|
+
createdAt: Date.now(),
|
|
4719
|
+
turn,
|
|
4720
|
+
startSeq: range.seqs[0],
|
|
4721
|
+
endSeq: range.seqs[range.seqs.length - 1],
|
|
4722
|
+
summary: parsed.summary,
|
|
4723
|
+
errorLines: [...errorLines],
|
|
4724
|
+
records,
|
|
4725
|
+
summaryCallChars
|
|
4726
|
+
});
|
|
4727
|
+
emitCompressionAudit(this.ctx.logger, {
|
|
4728
|
+
schemaVersion: 1,
|
|
4729
|
+
kind: "intent-summary-outcome",
|
|
4730
|
+
sessionId,
|
|
4731
|
+
ok: true,
|
|
4732
|
+
reason: "staged",
|
|
4733
|
+
turnIndex: turn,
|
|
4734
|
+
foldedCount: records.length,
|
|
4735
|
+
summaryCallChars,
|
|
4736
|
+
latencyMs: Date.now() - started
|
|
4737
|
+
});
|
|
4738
|
+
}
|
|
4739
|
+
/**
|
|
4740
|
+
* Convert a staged pending fold into per-candidate planned replacements
|
|
4741
|
+
* (reducer `intent-summary`). Fail-open: a candidate that would grow, is
|
|
4742
|
+
* rich-content, or no longer exists keeps its original text. Returns
|
|
4743
|
+
* `undefined` when there is nothing (or no longer anything) to fold.
|
|
4744
|
+
*/
|
|
4745
|
+
applyPendingIntentFold(session, policy, view, eligible) {
|
|
4746
|
+
const pending = this.state.pendingIntentFolds.get(session);
|
|
4747
|
+
if (pending === void 0) return void 0;
|
|
4748
|
+
const bySeq = new Map(eligible.map((candidate) => [candidate.seq, candidate]));
|
|
4749
|
+
const foldable = pending.records.map((record) => record.seq).filter((seq) => bySeq.has(seq)).sort((a, b) => a - b);
|
|
4750
|
+
if (foldable.length === 0) {
|
|
4751
|
+
this.state.pendingIntentFolds.delete(session);
|
|
4752
|
+
return;
|
|
4753
|
+
}
|
|
4754
|
+
const plans = [];
|
|
4755
|
+
const foldedSeqs = /* @__PURE__ */ new Set();
|
|
4756
|
+
let reclaim = 0;
|
|
4757
|
+
let charsBefore = 0;
|
|
4758
|
+
let charsAfter = 0;
|
|
4759
|
+
for (const seq of foldable) {
|
|
4760
|
+
const candidate = bySeq.get(seq);
|
|
4761
|
+
const result = candidate.event.data.message;
|
|
4762
|
+
const block = onlyTextBlock(result.content);
|
|
4763
|
+
if (block === null) continue;
|
|
4764
|
+
const text = renderIntentFoldBlock(pending, seq);
|
|
4765
|
+
const plan = this.plan(candidate, [{
|
|
4766
|
+
...block,
|
|
4767
|
+
text
|
|
4768
|
+
}], rootToolResultSeq(session, candidate.seq), "intent-summary", "pressure", "history", policy.historyMode, view);
|
|
4769
|
+
if (plan === null || plan.charsAfter >= plan.charsBefore) continue;
|
|
4770
|
+
plans.push(plan);
|
|
4771
|
+
foldedSeqs.add(seq);
|
|
4772
|
+
reclaim += plan.charsBefore - plan.charsAfter;
|
|
4773
|
+
charsBefore += plan.charsBefore;
|
|
4774
|
+
charsAfter += plan.charsAfter;
|
|
4775
|
+
}
|
|
4776
|
+
if (plans.length === 0) return void 0;
|
|
4777
|
+
this.state.intentFoldedSeqs.get(session)?.forEach((seq) => foldedSeqs.add(seq));
|
|
4778
|
+
return {
|
|
4779
|
+
plans,
|
|
4780
|
+
reclaim,
|
|
4781
|
+
foldedSeqs,
|
|
4782
|
+
charsBefore,
|
|
4783
|
+
charsAfter,
|
|
4784
|
+
turn: pending.turn,
|
|
4785
|
+
summaryCallChars: pending.summaryCallChars
|
|
4786
|
+
};
|
|
4787
|
+
}
|
|
4788
|
+
/**
|
|
4414
4789
|
* Monotonic per-session turn clock for advisory records. Bumped by the agent
|
|
4415
4790
|
* loop payloads (`pre-step`); passes without a turn coordinate reuse the last
|
|
4416
4791
|
* observed value.
|
|
@@ -5002,13 +5377,41 @@ var ToolResultPruner = class extends Service {
|
|
|
5002
5377
|
const isUnsafe = (candidate) => {
|
|
5003
5378
|
if (this.isRecoveryExempt(session, candidate)) return true;
|
|
5004
5379
|
const result = candidate.event.data.message;
|
|
5005
|
-
|
|
5380
|
+
const block = onlyTextBlock(result.content);
|
|
5381
|
+
if (block?.text.includes("[Intent summary") === true) return true;
|
|
5382
|
+
return block?.text.includes("[Old tool result content cleared from active context]") === true;
|
|
5006
5383
|
};
|
|
5007
5384
|
const safe = candidates.filter((candidate) => !isUnsafe(candidate));
|
|
5008
5385
|
const eligible = safe.filter((candidate) => !protectedSeqs.has(candidate.seq));
|
|
5009
5386
|
if (eligible.length === 0) return safe.length === 0 ? { kind: "no-safe-candidates" } : { kind: "protected-working-set" };
|
|
5010
5387
|
const planned = [];
|
|
5011
5388
|
let reclaim = 0;
|
|
5389
|
+
const intentApplied = this.applyPendingIntentFold(session, policy, view, eligible);
|
|
5390
|
+
if (intentApplied !== void 0) {
|
|
5391
|
+
planned.push(...intentApplied.plans);
|
|
5392
|
+
reclaim += intentApplied.reclaim;
|
|
5393
|
+
this.state.intentFoldedSeqs.set(session, intentApplied.foldedSeqs);
|
|
5394
|
+
this.state.pendingIntentFolds.delete(session);
|
|
5395
|
+
this.state.intentBaselines.set(session, view.totalTokens);
|
|
5396
|
+
recordIntentFold(String(session.id), {
|
|
5397
|
+
turn: intentApplied.turn,
|
|
5398
|
+
startSeq: intentApplied.foldedSeqs.size > 0 ? Math.min(...intentApplied.foldedSeqs) : 0,
|
|
5399
|
+
endSeq: intentApplied.foldedSeqs.size > 0 ? Math.max(...intentApplied.foldedSeqs) : 0,
|
|
5400
|
+
liveTokensBefore: view.totalTokens,
|
|
5401
|
+
at: Date.now()
|
|
5402
|
+
});
|
|
5403
|
+
emitCompressionAudit(this.ctx.logger, {
|
|
5404
|
+
schemaVersion: 1,
|
|
5405
|
+
kind: "intent-summary-outcome",
|
|
5406
|
+
sessionId: String(session.id),
|
|
5407
|
+
ok: true,
|
|
5408
|
+
reason: "landed",
|
|
5409
|
+
foldedCount: intentApplied.plans.length,
|
|
5410
|
+
...intentApplied.charsBefore > 0 ? { retentionRatio: intentApplied.charsAfter / intentApplied.charsBefore } : {},
|
|
5411
|
+
summaryCallChars: intentApplied.summaryCallChars
|
|
5412
|
+
});
|
|
5413
|
+
for (let index = eligible.length - 1; index >= 0; index -= 1) if (intentApplied.foldedSeqs.has(eligible[index].seq)) eligible.splice(index, 1);
|
|
5414
|
+
}
|
|
5012
5415
|
const minReclaimChars = charsForTokens(policy.historyMinReclaimTokens);
|
|
5013
5416
|
const microTarget = deadline === void 0 ? void 0 : Math.max(0, charsForTokens(deadline) - minReclaimChars);
|
|
5014
5417
|
const required = Math.max(minReclaimChars, total - trigger, ...microTarget === void 0 ? [] : [charsForTokens(view.totalTokens) - microTarget]);
|
|
@@ -5329,7 +5732,6 @@ var ToolResultPruner = class extends Service {
|
|
|
5329
5732
|
}
|
|
5330
5733
|
land(session, plan) {
|
|
5331
5734
|
const { candidate } = plan;
|
|
5332
|
-
candidate.event.data.message;
|
|
5333
5735
|
const message = freezeMessage({
|
|
5334
5736
|
...candidate.event.data.message,
|
|
5335
5737
|
content: plan.content
|