dsh-context-compression-improved 0.8.0-beta.3 → 0.8.0-beta.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/eslint.config.js +30 -30
- package/package.json +163 -163
- package/packages/selector/dsh.plugin.json +16 -16
- package/packages/selector/lib/client.d.ts +6 -0
- package/packages/selector/lib/client.js +106 -7
- 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 +408 -5
- package/packages/selector/src/client/CompressionProfileControls.tsx +34 -0
- package/packages/selector/src/client/CompressionProfileSelector.tsx +1 -0
- package/packages/selector/src/client/decode.ts +53 -49
- package/packages/selector/src/client/index.ts +4 -0
- package/packages/selector/src/client/locales/de.ts +5 -0
- package/packages/selector/src/client/locales/es.ts +5 -0
- package/packages/selector/src/client/locales/fr.ts +5 -0
- package/packages/selector/src/client/locales/it.ts +5 -0
- package/packages/selector/src/client/locales/ja.ts +5 -0
- package/packages/selector/src/client/locales/ko.ts +5 -0
- package/packages/selector/src/client/locales/ru.ts +5 -0
- package/packages/selector/src/client/locales.ts +10 -0
- package/packages/selector/src/client/settings-section.tsx +9 -2
- package/packages/selector/src/index.ts +7 -0
- package/packages/selector/src/profiles.ts +414 -394
- package/packages/selector/src/pruner/state.ts +57 -50
- package/packages/selector/src/pruner.ts +241 -1
- package/packages/selector/src/runtime/audit.ts +303 -286
- package/packages/selector/src/runtime/config.ts +731 -706
- package/packages/selector/src/runtime/summary-command.ts +127 -0
- package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -188
- package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -149
- 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/types.ts +358 -346
- package/packages/selector/tests/auto-compact.client.spec.tsx +214 -213
- 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 +253 -252
- 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/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 +2734 -2731
- package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
- package/packages/selector/tests/settings-seat.client.spec.ts +1 -1
- package/scripts/packed-install-e2e.mjs +1 -1
- package/scripts/verify-release.mjs +2 -1
|
@@ -1,50 +1,57 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Consolidated per-session mutable state for {@link ToolResultPruner}.
|
|
3
|
-
*
|
|
4
|
-
* Every field is a WeakMap keyed by Session, keeping the service
|
|
5
|
-
* stateless across sessions and safe under GC.
|
|
6
|
-
*/
|
|
7
|
-
|
|
8
|
-
import type { Session } from '@deepseek-ai/dsh-session'
|
|
9
|
-
import type { DedupeTable } from '../runtime/tokenpilot/dedup.ts'
|
|
10
|
-
import type { EstimatorFailures } from '../runtime/tokenpilot/estimator.ts'
|
|
11
|
-
import type { SideChannel } from '../runtime/tokenpilot/sidechannel.ts'
|
|
12
|
-
import type {
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Consolidated per-session mutable state for {@link ToolResultPruner}.
|
|
3
|
+
*
|
|
4
|
+
* Every field is a WeakMap keyed by Session, keeping the service
|
|
5
|
+
* stateless across sessions and safe under GC.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type { Session } from '@deepseek-ai/dsh-session'
|
|
9
|
+
import type { DedupeTable } from '../runtime/tokenpilot/dedup.ts'
|
|
10
|
+
import type { EstimatorFailures } from '../runtime/tokenpilot/estimator.ts'
|
|
11
|
+
import type { SideChannel } from '../runtime/tokenpilot/sidechannel.ts'
|
|
12
|
+
import type { PendingIntentFold } from '../runtime/tokenpilot/intent-fold.ts'
|
|
13
|
+
import type {
|
|
14
|
+
ContextCompressionSettings,
|
|
15
|
+
ResolvedConfig,
|
|
16
|
+
} from '../runtime/types.ts'
|
|
17
|
+
|
|
18
|
+
/** Mutable per-session state bag used inside {@link ToolResultPruner}. */
|
|
19
|
+
export interface PrunerState {
|
|
20
|
+
/** Resolved immutable deployment configuration. */
|
|
21
|
+
readonly config: ResolvedConfig
|
|
22
|
+
|
|
23
|
+
/** Complete canonical setting document frozen when each Session first reaches this root service. */
|
|
24
|
+
readonly sessionSettings: WeakMap<Session, ContextCompressionSettings>
|
|
25
|
+
/** Original result seqs whose first-exposure KEEP/REDUCE decision has committed. */
|
|
26
|
+
readonly firstExposure: WeakMap<Session, Set<number>>
|
|
27
|
+
/** Result seqs permanently exempt from further reduction (recovery outputs and registered equivalents). */
|
|
28
|
+
readonly recoveryExemptions: WeakMap<Session, Set<number>>
|
|
29
|
+
/** Per-session canonical-content hash index backing tokenpilot-inspired dedupe. */
|
|
30
|
+
readonly dedupeTables: WeakMap<Session, DedupeTable>
|
|
31
|
+
/** Advisory estimator verdicts consumed by the read-state classification. */
|
|
32
|
+
readonly estimatorVerdicts: WeakMap<Session, Map<number, boolean>>
|
|
33
|
+
/** Per-session estimator failure backoff state. */
|
|
34
|
+
readonly estimatorFailures: WeakMap<Session, EstimatorFailures>
|
|
35
|
+
/** Runtime prerequisite warnings deduplicated per Session and failure key. */
|
|
36
|
+
readonly warnedFailures: WeakMap<Session, Set<string>>
|
|
37
|
+
/** Last Adaptive postflight attempt emitted per Session; keeps diagnostics bounded and independent. */
|
|
38
|
+
readonly postflightDiagnostics: WeakMap<Session, string>
|
|
39
|
+
/** Current pre-step chain identity, shared by this producer and downstream compaction-basic. */
|
|
40
|
+
readonly activeRequestBoundaries: WeakMap<Session, object>
|
|
41
|
+
/** Boundary identity that already attempted one fully preflighted TailTrim publication. */
|
|
42
|
+
readonly tailTrimBoundaryAttempts: WeakMap<Session, object>
|
|
43
|
+
/** Last effective policy audit key emitted for each Session. */
|
|
44
|
+
readonly policyResolutionAudits: WeakMap<Session, string>
|
|
45
|
+
/** Last observed turn index per Session: the monotonic clock for advisory records. */
|
|
46
|
+
readonly turnClocks: WeakMap<Session, number>
|
|
47
|
+
/** Estimator-reported remaining turns Ŝ per Session; advisory only. */
|
|
48
|
+
readonly estimatorRemainingTurns: WeakMap<Session, number>
|
|
49
|
+
/** Per-session advisor side channel, constructed once with the advisor overrides. */
|
|
50
|
+
readonly advisorChannels: WeakMap<Session, SideChannel>
|
|
51
|
+
/** Staged intent fold awaiting the next pressure round (at most one per session). */
|
|
52
|
+
readonly pendingIntentFolds: WeakMap<Session, PendingIntentFold>
|
|
53
|
+
/** Landed intent-fold seqs: fold-once, never reconsidered by any later stage. */
|
|
54
|
+
readonly intentFoldedSeqs: WeakMap<Session, Set<number>>
|
|
55
|
+
/** Live-surface tokens when the last intent fold landed (growth-gate baseline). */
|
|
56
|
+
readonly intentBaselines: WeakMap<Session, number>
|
|
57
|
+
}
|
|
@@ -91,6 +91,12 @@ import {
|
|
|
91
91
|
runSessionAdvisorPass,
|
|
92
92
|
} from './runtime/tokenpilot/advisor.ts'
|
|
93
93
|
import { getAdvisorState } from './runtime/tokenpilot/advisor-state.ts'
|
|
94
|
+
import { evaluateIntentGate } from './runtime/tokenpilot/intent-gate.ts'
|
|
95
|
+
import { extractErrorLines, maskCandidateForSummary, type IntentRole } from './runtime/tokenpilot/intent-input-mask.ts'
|
|
96
|
+
import { computeIntentRange, INTENT_RANGE_MAX_CANDIDATES } from './runtime/tokenpilot/intent-range.ts'
|
|
97
|
+
import { INTENT_FOLD_MARKER, renderIntentFoldBlock } from './runtime/tokenpilot/intent-fold.ts'
|
|
98
|
+
import { buildIntentSummarySystemPrompt, buildIntentSummaryUserPrompt, parseIntentSummaryAnswer } from './runtime/tokenpilot/advisor-prompt.ts'
|
|
99
|
+
import { getSummaryOverride, observeIntentEnabled, recordIntentFold } from './runtime/tokenpilot/advisor-state.ts'
|
|
94
100
|
|
|
95
101
|
import {
|
|
96
102
|
DedupeTable,
|
|
@@ -253,6 +259,9 @@ export class ToolResultPruner extends Service {
|
|
|
253
259
|
turnClocks: new WeakMap(),
|
|
254
260
|
estimatorRemainingTurns: new WeakMap(),
|
|
255
261
|
advisorChannels: new WeakMap(),
|
|
262
|
+
pendingIntentFolds: new WeakMap(),
|
|
263
|
+
intentFoldedSeqs: new WeakMap(),
|
|
264
|
+
intentBaselines: new WeakMap(),
|
|
256
265
|
}
|
|
257
266
|
|
|
258
267
|
// 会话结束汇总(dsh-token-optimizer monitor 模式的同款体验):输出该会话的
|
|
@@ -343,6 +352,9 @@ export class ToolResultPruner extends Service {
|
|
|
343
352
|
// summaries, scores, and decay figure never touch any decision path.
|
|
344
353
|
// Strictly fire-and-forget, with its own backoff state.
|
|
345
354
|
void this.postflightAdvisorPass(agent.session, turn, signal).catch(() => undefined)
|
|
355
|
+
// Turn-tail intent summary: strictly fire-and-forget like the advisor;
|
|
356
|
+
// the growth gate inside decides whether a summary call is even spent.
|
|
357
|
+
void this.postflightIntentFoldPass(agent.session, turn, signal).catch(() => undefined)
|
|
346
358
|
})
|
|
347
359
|
}
|
|
348
360
|
|
|
@@ -771,6 +783,200 @@ export class ToolResultPruner extends Service {
|
|
|
771
783
|
}
|
|
772
784
|
}
|
|
773
785
|
|
|
786
|
+
// ─────────── Turn-tail intent summary (host-driven fold, model writes text only) ───────────
|
|
787
|
+
|
|
788
|
+
/**
|
|
789
|
+
* Fire-and-forget postflight: evaluate the growth gate, and only when it
|
|
790
|
+
* passes, select the consumed increment OUTSIDE the protected working set,
|
|
791
|
+
* mask it to semantic-role records, and spend ONE summary-writer call. The
|
|
792
|
+
* verdict stages as a pending fold that the NEXT pressure round lands via
|
|
793
|
+
* the ordinary plan/apply machinery — the synchronous decision path never
|
|
794
|
+
* waits on an LLM.
|
|
795
|
+
*/
|
|
796
|
+
private async postflightIntentFoldPass(session: Session, turn: number, signal: AbortSignal): Promise<void> {
|
|
797
|
+
const started = Date.now()
|
|
798
|
+
const sessionId = String(session.id)
|
|
799
|
+
const policy = this.activePolicy(session)
|
|
800
|
+
const settings = this.activeSettings(session)
|
|
801
|
+
const intentEnabled = settings.intentSummary.enabled
|
|
802
|
+
const override = getSummaryOverride(sessionId)
|
|
803
|
+
observeIntentEnabled(sessionId, intentEnabled)
|
|
804
|
+
if (policy === undefined) return
|
|
805
|
+
if (this.state.pendingIntentFolds.has(session)) return
|
|
806
|
+
const advisorState = getAdvisorState(session)
|
|
807
|
+
if (advisorState.inFlight) return
|
|
808
|
+
if (isCoolingDown(advisorState.failures, Date.now())) return
|
|
809
|
+
|
|
810
|
+
const view = measureForCompaction(this.ctx, session)
|
|
811
|
+
// The window is the Auto Compact linkage input: policy.autoCompactTokens
|
|
812
|
+
// == floor(window * threshold/100); invert for the gate floor.
|
|
813
|
+
const thresholdPercent = settings.autoCompact.thresholdPercent
|
|
814
|
+
const contextWindow = policy.autoCompactTokens !== undefined && thresholdPercent > 0
|
|
815
|
+
? Math.round(policy.autoCompactTokens / (thresholdPercent / 100))
|
|
816
|
+
: undefined
|
|
817
|
+
const gate = evaluateIntentGate({
|
|
818
|
+
enabled: intentEnabled,
|
|
819
|
+
override,
|
|
820
|
+
liveTokens: view.totalTokens,
|
|
821
|
+
contextWindow,
|
|
822
|
+
baselineTokens: this.state.intentBaselines.get(session) ?? 0,
|
|
823
|
+
})
|
|
824
|
+
if (!gate.decision) return
|
|
825
|
+
|
|
826
|
+
const settingsPreset = settings.presetOptions
|
|
827
|
+
if (settingsPreset === undefined) return
|
|
828
|
+
if (settingsPreset.estimatorBaseUrl === undefined || settingsPreset.estimatorBaseUrl.length === 0
|
|
829
|
+
|| settingsPreset.estimatorModel === undefined || settingsPreset.estimatorModel.length === 0) {
|
|
830
|
+
emitCompressionAudit(this.ctx.logger, {
|
|
831
|
+
schemaVersion: 1,
|
|
832
|
+
kind: 'intent-summary-outcome',
|
|
833
|
+
sessionId,
|
|
834
|
+
ok: false,
|
|
835
|
+
reason: 'no-direct-endpoint',
|
|
836
|
+
turnIndex: turn,
|
|
837
|
+
latencyMs: Date.now() - started,
|
|
838
|
+
})
|
|
839
|
+
return
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
const candidates = this.snapshot(session, view).filter(candidate => !this.isRecoveryExempt(session, candidate))
|
|
843
|
+
const protectedSeqs = this.protectedHistoryCandidateSeqs(candidates, policy)
|
|
844
|
+
const range = computeIntentRange({
|
|
845
|
+
candidates,
|
|
846
|
+
protectedSeqs,
|
|
847
|
+
foldedSeqs: this.state.intentFoldedSeqs.get(session) ?? new Set<number>(),
|
|
848
|
+
maxCandidates: INTENT_RANGE_MAX_CANDIDATES,
|
|
849
|
+
})
|
|
850
|
+
if (range.seqs.length === 0) return
|
|
851
|
+
|
|
852
|
+
const bySeq = new Map(candidates.map(candidate => [candidate.seq, candidate]))
|
|
853
|
+
const records: { seq: number, role: IntentRole, toolName: string, line: string }[] = []
|
|
854
|
+
const errorLines = new Set<string>()
|
|
855
|
+
for (const seq of range.seqs) {
|
|
856
|
+
const candidate = bySeq.get(seq)
|
|
857
|
+
if (candidate === undefined) continue
|
|
858
|
+
const result = candidate.event.data.message as ToolResultMessage
|
|
859
|
+
const text = onlyTextBlock(result.content)?.text ?? ''
|
|
860
|
+
const masked = maskCandidateForSummary(seq, candidate.call.name, candidate.call.arguments, text)
|
|
861
|
+
records.push({ seq, role: masked.role, toolName: candidate.call.name, line: masked.record })
|
|
862
|
+
for (const line of extractErrorLines(text)) errorLines.add(line)
|
|
863
|
+
}
|
|
864
|
+
if (records.length === 0) return
|
|
865
|
+
|
|
866
|
+
const events = sessionEvents(session)
|
|
867
|
+
const task = collectTaskSemantics(events)
|
|
868
|
+
let channel = this.state.advisorChannels.get(session)
|
|
869
|
+
if (channel === undefined) {
|
|
870
|
+
channel = new SideChannel(this.ctx, settingsPreset, {
|
|
871
|
+
mode: 'direct',
|
|
872
|
+
timeoutMs: 30_000,
|
|
873
|
+
maxTokens: 512,
|
|
874
|
+
})
|
|
875
|
+
this.state.advisorChannels.set(session, channel)
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
const answer = await channel.ask({
|
|
879
|
+
system: buildIntentSummarySystemPrompt(),
|
|
880
|
+
user: buildIntentSummaryUserPrompt(task?.taskText ?? '(no task semantics yet)', records.map(record => record.line), collectTailText(events)),
|
|
881
|
+
signal,
|
|
882
|
+
})
|
|
883
|
+
const summaryCallChars = answer?.length ?? 0
|
|
884
|
+
const parsed = answer === undefined ? undefined : parseIntentSummaryAnswer(answer)
|
|
885
|
+
if (parsed === undefined) {
|
|
886
|
+
const failures = (advisorState.failures?.failures ?? 0) + 1
|
|
887
|
+
advisorState.failures = { failures, cooldownUntil: Date.now() + backoffCooldownMs(failures) }
|
|
888
|
+
emitCompressionAudit(this.ctx.logger, {
|
|
889
|
+
schemaVersion: 1,
|
|
890
|
+
kind: 'intent-summary-outcome',
|
|
891
|
+
sessionId,
|
|
892
|
+
ok: false,
|
|
893
|
+
reason: answer === undefined ? 'ask-failed' : 'parse-failed',
|
|
894
|
+
turnIndex: turn,
|
|
895
|
+
foldedCount: records.length,
|
|
896
|
+
summaryCallChars,
|
|
897
|
+
latencyMs: Date.now() - started,
|
|
898
|
+
})
|
|
899
|
+
return
|
|
900
|
+
}
|
|
901
|
+
this.state.pendingIntentFolds.set(session, {
|
|
902
|
+
createdAt: Date.now(),
|
|
903
|
+
turn,
|
|
904
|
+
startSeq: range.seqs[0]!,
|
|
905
|
+
endSeq: range.seqs[range.seqs.length - 1]!,
|
|
906
|
+
summary: parsed.summary,
|
|
907
|
+
errorLines: [...errorLines],
|
|
908
|
+
records,
|
|
909
|
+
summaryCallChars,
|
|
910
|
+
})
|
|
911
|
+
emitCompressionAudit(this.ctx.logger, {
|
|
912
|
+
schemaVersion: 1,
|
|
913
|
+
kind: 'intent-summary-outcome',
|
|
914
|
+
sessionId,
|
|
915
|
+
ok: true,
|
|
916
|
+
reason: 'staged',
|
|
917
|
+
turnIndex: turn,
|
|
918
|
+
foldedCount: records.length,
|
|
919
|
+
summaryCallChars,
|
|
920
|
+
latencyMs: Date.now() - started,
|
|
921
|
+
})
|
|
922
|
+
}
|
|
923
|
+
|
|
924
|
+
/**
|
|
925
|
+
* Convert a staged pending fold into per-candidate planned replacements
|
|
926
|
+
* (reducer `intent-summary`). Fail-open: a candidate that would grow, is
|
|
927
|
+
* rich-content, or no longer exists keeps its original text. Returns
|
|
928
|
+
* `undefined` when there is nothing (or no longer anything) to fold.
|
|
929
|
+
*/
|
|
930
|
+
private applyPendingIntentFold(
|
|
931
|
+
session: Session,
|
|
932
|
+
policy: CompressionPolicy,
|
|
933
|
+
view: CompactionTokenView,
|
|
934
|
+
eligible: readonly SnapshotCandidate[],
|
|
935
|
+
): { plans: PlannedReplacement[], reclaim: number, foldedSeqs: Set<number>, charsBefore: number, charsAfter: number, turn: number, summaryCallChars: number } | undefined {
|
|
936
|
+
const pending = this.state.pendingIntentFolds.get(session)
|
|
937
|
+
if (pending === undefined) return undefined
|
|
938
|
+
const bySeq = new Map(eligible.map(candidate => [candidate.seq, candidate]))
|
|
939
|
+
const foldable = pending.records
|
|
940
|
+
.map(record => record.seq)
|
|
941
|
+
.filter(seq => bySeq.has(seq))
|
|
942
|
+
.sort((a, b) => a - b)
|
|
943
|
+
if (foldable.length === 0) {
|
|
944
|
+
this.state.pendingIntentFolds.delete(session)
|
|
945
|
+
return undefined
|
|
946
|
+
}
|
|
947
|
+
const plans: PlannedReplacement[] = []
|
|
948
|
+
const foldedSeqs = new Set<number>()
|
|
949
|
+
let reclaim = 0
|
|
950
|
+
let charsBefore = 0
|
|
951
|
+
let charsAfter = 0
|
|
952
|
+
for (const seq of foldable) {
|
|
953
|
+
const candidate = bySeq.get(seq)!
|
|
954
|
+
const result = candidate.event.data.message as ToolResultMessage
|
|
955
|
+
const block = onlyTextBlock(result.content)
|
|
956
|
+
if (block === null) continue
|
|
957
|
+
const text = renderIntentFoldBlock(pending, seq)
|
|
958
|
+
const plan = this.plan(
|
|
959
|
+
candidate,
|
|
960
|
+
[{ ...block, text }],
|
|
961
|
+
rootToolResultSeq(session, candidate.seq),
|
|
962
|
+
'intent-summary',
|
|
963
|
+
'pressure',
|
|
964
|
+
'history',
|
|
965
|
+
policy.historyMode,
|
|
966
|
+
view,
|
|
967
|
+
)
|
|
968
|
+
if (plan === null || plan.charsAfter >= plan.charsBefore) continue
|
|
969
|
+
plans.push(plan)
|
|
970
|
+
foldedSeqs.add(seq)
|
|
971
|
+
reclaim += plan.charsBefore - plan.charsAfter
|
|
972
|
+
charsBefore += plan.charsBefore
|
|
973
|
+
charsAfter += plan.charsAfter
|
|
974
|
+
}
|
|
975
|
+
if (plans.length === 0) return undefined
|
|
976
|
+
this.state.intentFoldedSeqs.get(session)?.forEach(seq => foldedSeqs.add(seq))
|
|
977
|
+
return { plans, reclaim, foldedSeqs, charsBefore, charsAfter, turn: pending.turn, summaryCallChars: pending.summaryCallChars }
|
|
978
|
+
}
|
|
979
|
+
|
|
774
980
|
// ─────────── Advisory benefit model (statistics & suggestions only) ───────────
|
|
775
981
|
|
|
776
982
|
/**
|
|
@@ -1683,13 +1889,15 @@ export class ToolResultPruner extends Service {
|
|
|
1683
1889
|
if (this.isRecoveryExempt(session, candidate)) return true
|
|
1684
1890
|
const result = candidate.event.data.message as ToolResultMessage
|
|
1685
1891
|
const block = onlyTextBlock(result.content)
|
|
1892
|
+
// Fold-once: an already-folded intent block is never re-candidated.
|
|
1893
|
+
if (block?.text.includes(INTENT_FOLD_MARKER) === true) return true
|
|
1686
1894
|
return block?.text.includes('[Old tool result content cleared from active context]') === true
|
|
1687
1895
|
}
|
|
1688
1896
|
// Distinguish "nothing safe to touch" (recovery tool output or already
|
|
1689
1897
|
// cleared) from "everything left is inside the protected working set":
|
|
1690
1898
|
// both skip, but they are different operational facts.
|
|
1691
1899
|
const safe = candidates.filter(candidate => !isUnsafe(candidate))
|
|
1692
|
-
const eligible = safe.filter(candidate => !protectedSeqs.has(candidate.seq))
|
|
1900
|
+
const eligible: SnapshotCandidate[] = safe.filter(candidate => !protectedSeqs.has(candidate.seq))
|
|
1693
1901
|
if (eligible.length === 0) {
|
|
1694
1902
|
return safe.length === 0
|
|
1695
1903
|
? { kind: 'no-safe-candidates' }
|
|
@@ -1697,6 +1905,38 @@ export class ToolResultPruner extends Service {
|
|
|
1697
1905
|
}
|
|
1698
1906
|
const planned: PlannedReplacement[] = []
|
|
1699
1907
|
let reclaim = 0
|
|
1908
|
+
// Turn-tail intent summary (task_2.5): a fold staged by a previous turn's
|
|
1909
|
+
// postflight lands FIRST, through the same plan pipeline as every other
|
|
1910
|
+
// reducer; its reclaim counts toward the batch target and its seqs are
|
|
1911
|
+
// removed from the ordinary loop (fold-once).
|
|
1912
|
+
const intentApplied = this.applyPendingIntentFold(session, policy, view, eligible)
|
|
1913
|
+
if (intentApplied !== undefined) {
|
|
1914
|
+
planned.push(...intentApplied.plans)
|
|
1915
|
+
reclaim += intentApplied.reclaim
|
|
1916
|
+
this.state.intentFoldedSeqs.set(session, intentApplied.foldedSeqs)
|
|
1917
|
+
this.state.pendingIntentFolds.delete(session)
|
|
1918
|
+
this.state.intentBaselines.set(session, view.totalTokens)
|
|
1919
|
+
recordIntentFold(String(session.id), {
|
|
1920
|
+
turn: intentApplied.turn,
|
|
1921
|
+
startSeq: intentApplied.foldedSeqs.size > 0 ? Math.min(...intentApplied.foldedSeqs) : 0,
|
|
1922
|
+
endSeq: intentApplied.foldedSeqs.size > 0 ? Math.max(...intentApplied.foldedSeqs) : 0,
|
|
1923
|
+
liveTokensBefore: view.totalTokens,
|
|
1924
|
+
at: Date.now(),
|
|
1925
|
+
})
|
|
1926
|
+
emitCompressionAudit(this.ctx.logger, {
|
|
1927
|
+
schemaVersion: 1,
|
|
1928
|
+
kind: 'intent-summary-outcome',
|
|
1929
|
+
sessionId: String(session.id),
|
|
1930
|
+
ok: true,
|
|
1931
|
+
reason: 'landed',
|
|
1932
|
+
foldedCount: intentApplied.plans.length,
|
|
1933
|
+
...(intentApplied.charsBefore > 0 ? { retentionRatio: intentApplied.charsAfter / intentApplied.charsBefore } : {}),
|
|
1934
|
+
summaryCallChars: intentApplied.summaryCallChars,
|
|
1935
|
+
})
|
|
1936
|
+
for (let index = eligible.length - 1; index >= 0; index -= 1) {
|
|
1937
|
+
if (intentApplied.foldedSeqs.has(eligible[index]!.seq)) eligible.splice(index, 1)
|
|
1938
|
+
}
|
|
1939
|
+
}
|
|
1700
1940
|
// Linked batches must reach the deadline target; unlinked batches keep
|
|
1701
1941
|
// the traditional minimum-reclaim commit threshold. All arithmetic runs on
|
|
1702
1942
|
// the character basis: token-named thresholds enter via charsForTokens.
|