dsh-context-compression-improved 0.10.5 → 0.11.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.md +8 -0
- package/CHANGELOG.zh.md +9 -0
- package/README.de.md +1 -1
- package/assets/dshfind-card.svg +33 -0
- package/docs/shallow-teaching-preset-template.md +46 -0
- package/package.json +6 -6
- package/packages/selector/dsh.plugin.json +2 -2
- package/packages/selector/lib/client.d.ts +8 -0
- package/packages/selector/lib/client.js +212 -3
- package/packages/selector/lib/index.js +1 -1
- package/packages/selector/lib/profiles.d.ts +34 -0
- package/packages/selector/lib/pruner.d.ts +55 -0
- package/packages/selector/lib/pruner.js +1925 -303
- package/packages/selector/lib/savings-integral.js +126 -3
- package/packages/selector/lib/tool-result.js +9 -1
- package/packages/selector/package.json +21 -21
- package/packages/selector/src/client/CompressionProfileControls.tsx +33 -0
- package/packages/selector/src/client/CompressionProfileSelector.tsx +2 -0
- package/packages/selector/src/client/decode.ts +5 -1
- package/packages/selector/src/client/index.ts +4 -0
- package/packages/selector/src/client/locales/de.ts +7 -0
- package/packages/selector/src/client/locales/es.ts +7 -0
- package/packages/selector/src/client/locales/fr.ts +7 -0
- package/packages/selector/src/client/locales/it.ts +7 -0
- package/packages/selector/src/client/locales/ja.ts +7 -0
- package/packages/selector/src/client/locales/ko.ts +7 -0
- package/packages/selector/src/client/locales/ru.ts +7 -0
- package/packages/selector/src/client/locales.ts +14 -0
- package/packages/selector/src/client/monitor-fab.ts +14 -0
- package/packages/selector/src/client/settings-section.tsx +9 -2
- package/packages/selector/src/profiles.ts +103 -0
- package/packages/selector/src/pruner.ts +310 -4
- package/packages/selector/src/runtime/audit.ts +1 -0
- package/packages/selector/src/runtime/config.ts +88 -1
- package/packages/selector/src/runtime/fold-router.ts +143 -0
- package/packages/selector/src/runtime/monitor.ts +31 -0
- package/packages/selector/src/runtime/reducers.ts +1 -1
- package/packages/selector/src/runtime/sediment-card.ts +126 -0
- package/packages/selector/src/runtime/sediment-clock.ts +87 -0
- package/packages/selector/src/runtime/sediment-guard.ts +136 -0
- package/packages/selector/src/runtime/sediment-publish.ts +144 -0
- package/packages/selector/src/runtime/sediment-span.ts +170 -0
- package/packages/selector/src/runtime/sediment.ts +209 -0
- package/packages/selector/src/runtime/shallow-tools.ts +342 -0
- package/packages/selector/src/runtime/tool-names.ts +6 -0
- package/packages/selector/src/runtime/triage/masks.ts +128 -0
- package/packages/selector/src/runtime/triage/shallow.ts +132 -0
- package/packages/selector/src/runtime/triage/signals.ts +167 -0
- package/packages/selector/src/runtime/triage/types.ts +125 -0
- package/packages/selector/src/runtime/types.ts +28 -0
- package/packages/selector/tests/fixtures/sediment-pool/52adc205-cloud-5.orig.txt +231 -0
- package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-25.orig.txt +236 -0
- package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-38.orig.txt +220 -0
- package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-42.orig.txt +140 -0
- package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-53.orig.txt +117 -0
- package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-local-10.orig.txt +67 -0
- package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-45.orig.txt +119 -0
- package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-49.orig.txt +119 -0
- package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-63.orig.txt +131 -0
- package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-75.orig.txt +196 -0
- package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-76.orig.txt +71 -0
- package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-85.orig.txt +126 -0
- package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-86.orig.txt +86 -0
- package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-87.orig.txt +50 -0
- package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-96.orig.txt +102 -0
- package/packages/selector/tests/public/package-contract.client.spec.ts +7 -4
- package/packages/selector/tests/runtime/fold-router.spec.ts +140 -0
- package/packages/selector/tests/runtime/sediment-card.spec.ts +111 -0
- package/packages/selector/tests/runtime/sediment-config.spec.ts +56 -0
- package/packages/selector/tests/runtime/sediment-guard.spec.ts +71 -0
- package/packages/selector/tests/runtime/sediment-masks.spec.ts +95 -0
- package/packages/selector/tests/runtime/sediment-orchestrator.spec.ts +166 -0
- package/packages/selector/tests/runtime/sediment-pool-share.spec.ts +65 -0
- package/packages/selector/tests/runtime/sediment-publish.spec.ts +142 -0
- package/packages/selector/tests/runtime/sediment-real-shapes.spec.ts +158 -0
- package/packages/selector/tests/runtime/sediment-settings.spec.ts +73 -0
- package/packages/selector/tests/runtime/sediment-signals.spec.ts +124 -0
- package/packages/selector/tests/runtime/sediment-span.spec.ts +92 -0
- package/packages/selector/tests/runtime/shallow-primitives.spec.ts +135 -0
- package/packages/selector/tests/settings-seat.client.spec.ts +1 -1
- package/scripts/hosts.d.mts +3 -0
- package/scripts/hosts.mjs +3 -1
- package/scripts/sediment-latency-report.mjs +63 -0
- package/scripts/verify-release.mjs +7 -2
- package/$null +0 -1
|
@@ -40,6 +40,8 @@ export interface MonitorSnapshotPayload {
|
|
|
40
40
|
gate?: { floorFraction?: unknown; growthTokens?: unknown }
|
|
41
41
|
lastFold?: { turn?: unknown; startSeq?: unknown; endSeq?: unknown } | undefined
|
|
42
42
|
}
|
|
43
|
+
/** 沉降门状态(plan cci-sedimentation-triage T5.1);未观测时 absent。 */
|
|
44
|
+
sediment?: { conservative?: unknown; reason?: unknown; cuts?: unknown }
|
|
43
45
|
context?: { liveTokens?: unknown; contextWindow?: unknown; pct?: unknown }
|
|
44
46
|
suggestion?: { suggest?: unknown; thresholdPct?: unknown; occupancyPct?: unknown }
|
|
45
47
|
recentOffsets?: Array<{ component?: unknown; tokens?: unknown }>
|
|
@@ -144,6 +146,7 @@ export function initMonitorFab(deps: MonitorFabDeps): void {
|
|
|
144
146
|
<button data-overon>${t('monitor.panel.resume')}</button>
|
|
145
147
|
<button data-overoff class="ghost">${t('monitor.panel.disable')}</button></div>
|
|
146
148
|
<div class="row muted" data-fold style="display:none"></div>
|
|
149
|
+
<div class="row muted" data-sediment style="display:none"></div>
|
|
147
150
|
<div class="stale" data-stale>${t('monitor.panel.stale')}</div>
|
|
148
151
|
<div data-compwrap style="display:none">
|
|
149
152
|
<div class="row"><span class="label">${t('monitor.panel.composition')}</span></div>
|
|
@@ -358,6 +361,17 @@ export function initMonitorFab(deps: MonitorFabDeps): void {
|
|
|
358
361
|
} else {
|
|
359
362
|
foldEl.style.display = 'none';
|
|
360
363
|
}
|
|
364
|
+
// 沉降门状态行(T5.1):未观测隐藏;conservative 态优先展示告警语义。
|
|
365
|
+
const sediment = snap.sediment;
|
|
366
|
+
const sedimentEl = panel.querySelector('[data-sediment]') as HTMLElement;
|
|
367
|
+
if (sediment !== undefined && sediment !== null && typeof sediment === 'object') {
|
|
368
|
+
sedimentEl.style.display = '';
|
|
369
|
+
sedimentEl.textContent = sediment.conservative === true
|
|
370
|
+
? `${t('monitor.panel.sedimentConservative')} (${String(sediment.reason ?? '–')})`
|
|
371
|
+
: `${t('monitor.panel.sedimentCuts')} ${String(sediment.cuts ?? 0)}`;
|
|
372
|
+
} else {
|
|
373
|
+
sedimentEl.style.display = 'none';
|
|
374
|
+
}
|
|
361
375
|
// 最近抵消(压缩后再读全文的负项) top3:无记录整行隐藏——旧空态文案
|
|
362
376
|
// 「尚无压缩记录」与上方组成块自相矛盾(无抵消≠无压缩,回填投影明明在),
|
|
363
377
|
// savings.empty 的真正空态职责在设置页账本(savings-card)。
|
|
@@ -15,7 +15,7 @@ import {
|
|
|
15
15
|
type CustomCompressionPolicyV3,
|
|
16
16
|
} from '../profiles.ts'
|
|
17
17
|
import type { CompressionProfileSelectorProps } from './CompressionProfileSelector.tsx'
|
|
18
|
-
import { AutoCompactThresholdControls, CodeSkeletonControls, IntentSummaryControls, MonitorPanelControls } from './CompressionProfileControls.tsx'
|
|
18
|
+
import { AutoCompactThresholdControls, CodeSkeletonControls, SedimentControls, IntentSummaryControls, MonitorPanelControls } from './CompressionProfileControls.tsx'
|
|
19
19
|
import { EstimatorControls, EstimatorInactiveNotice } from './EstimatorControls.tsx'
|
|
20
20
|
import { CustomPolicyEditor, editableCustom } from './CustomPolicyEditor.tsx'
|
|
21
21
|
import { SavingsCard } from './savings-card'
|
|
@@ -26,7 +26,7 @@ export function ContextCompressionSettingsSection(props: CompressionProfileSelec
|
|
|
26
26
|
}
|
|
27
27
|
|
|
28
28
|
export function SettingsCompressionProfileControls({
|
|
29
|
-
useCompression, select, saveCustom, resetCustom, savePtcCustom, resetPtcCustom, saveAutoCompact, saveCodeSkeleton, saveIntentSummary, saveMonitorPanel,
|
|
29
|
+
useCompression, select, saveCustom, resetCustom, savePtcCustom, resetPtcCustom, saveAutoCompact, saveCodeSkeleton, saveSediment, saveIntentSummary, saveMonitorPanel,
|
|
30
30
|
savePresetOptions, t,
|
|
31
31
|
}: CompressionProfileSelectorProps) {
|
|
32
32
|
const state = useCompression(snapshot => snapshot)
|
|
@@ -108,6 +108,13 @@ export function SettingsCompressionProfileControls({
|
|
|
108
108
|
settle={settle}
|
|
109
109
|
t={t}
|
|
110
110
|
/>
|
|
111
|
+
<SedimentControls
|
|
112
|
+
value={state.value?.sediment?.enabled ?? false}
|
|
113
|
+
disabled={busy || !state.writable || !selectorAvailable}
|
|
114
|
+
save={saveSediment}
|
|
115
|
+
settle={settle}
|
|
116
|
+
t={t}
|
|
117
|
+
/>
|
|
111
118
|
<IntentSummaryControls
|
|
112
119
|
value={state.value?.intentSummary?.enabled ?? false}
|
|
113
120
|
disabled={busy || !state.writable || !selectorAvailable}
|
|
@@ -139,6 +139,107 @@ export interface MonitorPanelSettings {
|
|
|
139
139
|
enabled: boolean
|
|
140
140
|
}
|
|
141
141
|
|
|
142
|
+
/**
|
|
143
|
+
* Orthogonal turn-tail sedimentation gate (plan cci-sedimentation-triage,
|
|
144
|
+
* R1/R13): whole-turn atomic replacement primary, span as the oversized-turn
|
|
145
|
+
* split and cache-strict fallback granularity. Default OFF; absent inherits
|
|
146
|
+
* the off defaults exactly like `monitorPanel`. Session-frozen like every
|
|
147
|
+
* selector setting: edits affect newly observed sessions only.
|
|
148
|
+
*/
|
|
149
|
+
export interface SedimentSettings {
|
|
150
|
+
enabled: boolean
|
|
151
|
+
/** Replacement granularity; `span` also serves as the cache-strict fallback. */
|
|
152
|
+
granularity: 'turn' | 'span'
|
|
153
|
+
/** Closing-summary qualification floor (tokens); below it the three-tier narrative fallback engages (R13). */
|
|
154
|
+
minClosingTokens: number
|
|
155
|
+
/** Rewrite guard: a cut must save at least tail-rewrite × ratio (community 1:15 evidence, findings F2). */
|
|
156
|
+
rewriteGuardRatio: number
|
|
157
|
+
/** Upper bound for one whole-turn replacement span before it splits (oversized turns). */
|
|
158
|
+
maxTurnSpanTokens: number
|
|
159
|
+
/**
|
|
160
|
+
* Append-only extra failure-signal patterns (R2 extension slot). Merging
|
|
161
|
+
* NEVER replaces the built-in base set; invalid regex entries reject the
|
|
162
|
+
* whole section (never silently dropped).
|
|
163
|
+
*/
|
|
164
|
+
extraSignalPatterns?: string[]
|
|
165
|
+
/** Fold narrative channel (Phase 4); '' keeps narrative tier 2 inert. */
|
|
166
|
+
foldMode?: '' | 'host' | 'direct'
|
|
167
|
+
foldBaseUrl?: string
|
|
168
|
+
foldBaseUrlKey?: string
|
|
169
|
+
foldStrataProvider?: string
|
|
170
|
+
foldStrataModel?: string
|
|
171
|
+
foldLocal35Provider?: string
|
|
172
|
+
foldLocal35Model?: string
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Off-defaults mirrored browser-safe from the runtime sediment section. */
|
|
176
|
+
export const DEFAULT_SEDIMENT_SETTINGS: SedimentSettings = {
|
|
177
|
+
enabled: false,
|
|
178
|
+
granularity: 'turn',
|
|
179
|
+
minClosingTokens: 120,
|
|
180
|
+
rewriteGuardRatio: 3,
|
|
181
|
+
maxTurnSpanTokens: 32_000,
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Browser-safe mirror of the runtime sediment section (absent inherits the off
|
|
186
|
+
* defaults). Strict like the other gates: unknown keys, wrong types, or an
|
|
187
|
+
* unparseable extra pattern invalidate the whole section — never coerced.
|
|
188
|
+
*/
|
|
189
|
+
export function decodeSedimentSettings(value: unknown): SedimentSettings | undefined {
|
|
190
|
+
if (value === undefined) return { ...DEFAULT_SEDIMENT_SETTINGS }
|
|
191
|
+
if (!isPlainRecord(value)) return undefined
|
|
192
|
+
const allowed = new Set(['enabled', 'granularity', 'minClosingTokens', 'rewriteGuardRatio', 'maxTurnSpanTokens', 'extraSignalPatterns', 'foldMode', 'foldBaseUrl', 'foldBaseUrlKey', 'foldStrataProvider', 'foldStrataModel', 'foldLocal35Provider', 'foldLocal35Model'])
|
|
193
|
+
if (Object.keys(value).some(key => !allowed.has(key))) return undefined
|
|
194
|
+
if (value.enabled !== undefined && typeof value.enabled !== 'boolean') return undefined
|
|
195
|
+
if (value.granularity !== undefined && value.granularity !== 'turn' && value.granularity !== 'span') return undefined
|
|
196
|
+
if (value.foldMode !== undefined && value.foldMode !== '' && value.foldMode !== 'host' && value.foldMode !== 'direct') return undefined
|
|
197
|
+
for (const key of ['foldBaseUrl', 'foldBaseUrlKey', 'foldStrataProvider', 'foldStrataModel', 'foldLocal35Provider', 'foldLocal35Model'] as const) {
|
|
198
|
+
if (value[key] !== undefined && typeof value[key] !== 'string') return undefined
|
|
199
|
+
}
|
|
200
|
+
const bounded: Array<[unknown, number, number]> = [
|
|
201
|
+
[value.minClosingTokens, 40, 2_000],
|
|
202
|
+
[value.rewriteGuardRatio, 1, 10],
|
|
203
|
+
[value.maxTurnSpanTokens, 4_000, 64_000],
|
|
204
|
+
]
|
|
205
|
+
for (const [entry, min, max] of bounded) {
|
|
206
|
+
if (entry !== undefined
|
|
207
|
+
&& (typeof entry !== 'number' || !Number.isSafeInteger(entry) || entry < min || entry > max)) return undefined
|
|
208
|
+
}
|
|
209
|
+
if (value.extraSignalPatterns !== undefined) {
|
|
210
|
+
if (!Array.isArray(value.extraSignalPatterns)
|
|
211
|
+
|| value.extraSignalPatterns.some(entry => typeof entry !== 'string' || !isSafeSignalPattern(entry))) return undefined
|
|
212
|
+
}
|
|
213
|
+
return {
|
|
214
|
+
enabled: (value.enabled as boolean | undefined) ?? DEFAULT_SEDIMENT_SETTINGS.enabled,
|
|
215
|
+
granularity: (value.granularity as 'turn' | 'span' | undefined) ?? DEFAULT_SEDIMENT_SETTINGS.granularity,
|
|
216
|
+
minClosingTokens: (value.minClosingTokens as number | undefined) ?? DEFAULT_SEDIMENT_SETTINGS.minClosingTokens,
|
|
217
|
+
rewriteGuardRatio: (value.rewriteGuardRatio as number | undefined) ?? DEFAULT_SEDIMENT_SETTINGS.rewriteGuardRatio,
|
|
218
|
+
maxTurnSpanTokens: (value.maxTurnSpanTokens as number | undefined) ?? DEFAULT_SEDIMENT_SETTINGS.maxTurnSpanTokens,
|
|
219
|
+
...value.extraSignalPatterns === undefined
|
|
220
|
+
? {}
|
|
221
|
+
: { extraSignalPatterns: [...value.extraSignalPatterns as string[]] },
|
|
222
|
+
...(value.foldMode === undefined ? {} : { foldMode: value.foldMode as '' | 'host' | 'direct' }),
|
|
223
|
+
...(value.foldBaseUrl === undefined ? {} : { foldBaseUrl: value.foldBaseUrl as string }),
|
|
224
|
+
...(value.foldBaseUrlKey === undefined ? {} : { foldBaseUrlKey: value.foldBaseUrlKey as string }),
|
|
225
|
+
...(value.foldStrataProvider === undefined ? {} : { foldStrataProvider: value.foldStrataProvider as string }),
|
|
226
|
+
...(value.foldStrataModel === undefined ? {} : { foldStrataModel: value.foldStrataModel as string }),
|
|
227
|
+
...(value.foldLocal35Provider === undefined ? {} : { foldLocal35Provider: value.foldLocal35Provider as string }),
|
|
228
|
+
...(value.foldLocal35Model === undefined ? {} : { foldLocal35Model: value.foldLocal35Model as string }),
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** Accept only parseable, length-bounded patterns; caps keep one scan linear. */
|
|
233
|
+
function isSafeSignalPattern(entry: string): boolean {
|
|
234
|
+
if (entry.length === 0 || entry.length > 200) return false
|
|
235
|
+
try {
|
|
236
|
+
new RegExp(entry)
|
|
237
|
+
return true
|
|
238
|
+
} catch {
|
|
239
|
+
return false
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
142
243
|
/**
|
|
143
244
|
* Decode the persisted codeSkeleton section with exactly the runtime schema's
|
|
144
245
|
* strictness: absent means the lossless off default; present values must be a
|
|
@@ -346,6 +447,8 @@ export interface ContextCompressionSettings {
|
|
|
346
447
|
intentSummary: IntentSummarySettings
|
|
347
448
|
/** Floating compression-monitor panel (FAB); absent inherits hidden. */
|
|
348
449
|
monitorPanel?: MonitorPanelSettings
|
|
450
|
+
/** Turn-tail sedimentation gate (plan cci-sedimentation-triage); absent inherits the off defaults. */
|
|
451
|
+
sediment?: SedimentSettings
|
|
349
452
|
/** Optional tokenpilot-inspired sub-capability overrides (presence-validated only). */
|
|
350
453
|
presetOptions?: PresetOptionsSettings
|
|
351
454
|
}
|
|
@@ -60,6 +60,14 @@ import {
|
|
|
60
60
|
tailTrimStub,
|
|
61
61
|
} from './runtime/tail-trim.ts'
|
|
62
62
|
import { installContextCompressionRetrieve } from './runtime/retrieve.ts'
|
|
63
|
+
import { installShallowTools, liveShallowFor } from './runtime/shallow-tools.ts'
|
|
64
|
+
import { buildShallowFooter } from './runtime/triage/shallow.ts'
|
|
65
|
+
import { SedimentOrchestrator } from './runtime/sediment.ts'
|
|
66
|
+
import { FoldRouter, foldTier } from './runtime/fold-router.ts'
|
|
67
|
+
import { SedimentFeedbackWatcher } from './runtime/sediment-guard.ts'
|
|
68
|
+
import { detectPtcMode, readStateBlind } from './runtime/sediment-guard.ts'
|
|
69
|
+
import { isWriteToolName } from './runtime/triage/masks.ts'
|
|
70
|
+
import { estimateTokens } from './runtime/sediment-card.ts'
|
|
63
71
|
import { RUNTIME_TOOL_NAMES } from './runtime/tool-names.ts'
|
|
64
72
|
import type { PrunerState } from './pruner/state.ts'
|
|
65
73
|
import { countOmittedLines, CAPACITY_PRESSURE_RATIO } from './pruner/tuning.ts'
|
|
@@ -117,7 +125,7 @@ import { computeIntentRange, INTENT_RANGE_MAX_CANDIDATES } from './runtime/token
|
|
|
117
125
|
import { INTENT_FOLD_MARKER, renderIntentFoldBlock } from './runtime/tokenpilot/intent-fold.ts'
|
|
118
126
|
import { buildIntentSummarySystemPrompt, buildIntentSummaryUserPrompt, parseIntentSummaryAnswer } from './runtime/tokenpilot/advisor-prompt.ts'
|
|
119
127
|
import { getSummaryOverride, observeIntentEnabled, recordIntentFold } from './runtime/tokenpilot/advisor-state.ts'
|
|
120
|
-
import { observeContextUsage } from './runtime/monitor.ts'
|
|
128
|
+
import { observeContextUsage, setSedimentObservation } from './runtime/monitor.ts'
|
|
121
129
|
import { compressionMessageSource, viewToolResult } from './compat/tool-result.ts'
|
|
122
130
|
|
|
123
131
|
import {
|
|
@@ -132,6 +140,36 @@ import { kickStatsBackfillOnDispose } from './runtime/stats-backfill.ts'
|
|
|
132
140
|
import { sampleIntegralBoundary } from './runtime/savings-integral.ts'
|
|
133
141
|
import { projectSessionSavings } from './runtime/savings-projection.ts'
|
|
134
142
|
|
|
143
|
+
/** Loose read-only event face for sediment accounting (sessionEvents is opaque across generations). */
|
|
144
|
+
type LooseRecord = Record<string, unknown>
|
|
145
|
+
type LooseEvent = Readonly<Record<string, unknown>>
|
|
146
|
+
|
|
147
|
+
function looseEvents(session: Session): readonly LooseEvent[] {
|
|
148
|
+
return sessionEvents(session) as unknown as readonly LooseEvent[]
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function looseData(event: LooseEvent | undefined): LooseRecord | undefined {
|
|
152
|
+
return event?.data as LooseRecord | undefined
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function looseContent(event: LooseEvent | undefined): readonly unknown[] {
|
|
156
|
+
const data = looseData(event)
|
|
157
|
+
const message = (data?.message ?? data) as LooseRecord | undefined
|
|
158
|
+
const content = message?.content
|
|
159
|
+
return Array.isArray(content) ? content : []
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Flatten the visible text of any surface event for sediment accounting. */
|
|
163
|
+
function sedimentEventText(event: LooseEvent | undefined): string {
|
|
164
|
+
return looseContent(event)
|
|
165
|
+
.filter(block => {
|
|
166
|
+
const record = block as LooseRecord | null
|
|
167
|
+
return record !== null && record.type === 'text' && typeof record.text === 'string'
|
|
168
|
+
})
|
|
169
|
+
.map(block => (block as { text: string }).text)
|
|
170
|
+
.join('\n')
|
|
171
|
+
}
|
|
172
|
+
|
|
135
173
|
/** 节省统计配对键用原文(纯文本块才可配对;富内容返回 undefined)。 */
|
|
136
174
|
function originalTextForSavings(candidate: SnapshotCandidate): string | undefined {
|
|
137
175
|
return flattenPlainText(viewToolResult(candidate.event.data.message).blocks as ContentBlock[])
|
|
@@ -301,6 +339,8 @@ export class ToolResultPruner extends Service {
|
|
|
301
339
|
super(ctx, 'toolResultPruner')
|
|
302
340
|
ctx.inject(['tools', 'systemPrompt'], recoveryCtx => {
|
|
303
341
|
installContextCompressionRetrieve(recoveryCtx)
|
|
342
|
+
// Upgrade-discard pair primitives (plan cci-sedimentation-triage Phase 4.5).
|
|
343
|
+
installShallowTools(recoveryCtx)
|
|
304
344
|
})
|
|
305
345
|
this.state = {
|
|
306
346
|
config: resolveConfig(config),
|
|
@@ -368,6 +408,17 @@ export class ToolResultPruner extends Service {
|
|
|
368
408
|
ctx.logger.warn('context-compression summary locator failed open: %o', error)
|
|
369
409
|
}
|
|
370
410
|
}
|
|
411
|
+
if (event.type === 'turn/end') {
|
|
412
|
+
// Sedimentation (plan cci-sedimentation-triage): the enabled gate is
|
|
413
|
+
// the first check inside — with default-off settings this returns
|
|
414
|
+
// without touching the orchestrator, the event reader, or the ledger.
|
|
415
|
+
try {
|
|
416
|
+
this.sedimentTurnEnd(session)
|
|
417
|
+
} catch (error: unknown) {
|
|
418
|
+
this.auditFailure(session, 'pressure', 'sediment', error)
|
|
419
|
+
ctx.logger.warn('context-compression sediment pass failed open: %o', error)
|
|
420
|
+
}
|
|
421
|
+
}
|
|
371
422
|
})
|
|
372
423
|
|
|
373
424
|
// This is the true first-exposure boundary available in the Harness:
|
|
@@ -428,7 +479,26 @@ export class ToolResultPruner extends Service {
|
|
|
428
479
|
String(agent.session.id),
|
|
429
480
|
new Set([...agent.session.surface.nodes].map(Number)),
|
|
430
481
|
)
|
|
431
|
-
} catch { /*
|
|
482
|
+
} catch { /* 观测失败静默:维持上次口径 */ }
|
|
483
|
+
// T3.11/T5.1:负反馈消费点——把账本增量交给会话级 watcher,
|
|
484
|
+
// conservative 状态与沉降刀数写进监控观测位(面板 sediment 块)。
|
|
485
|
+
try {
|
|
486
|
+
const feedbackSessionId = String(agent.session.id)
|
|
487
|
+
let watcher = this.sedimentWatchers.get(agent.session)
|
|
488
|
+
if (watcher === undefined) {
|
|
489
|
+
watcher = new SedimentFeedbackWatcher()
|
|
490
|
+
this.sedimentWatchers.set(agent.session, watcher)
|
|
491
|
+
}
|
|
492
|
+
const mode = watcher.observe(getSavingsLedger().snapshot(feedbackSessionId))
|
|
493
|
+
setSedimentObservation(feedbackSessionId, {
|
|
494
|
+
conservative: mode.conservative,
|
|
495
|
+
reason: mode.reason,
|
|
496
|
+
cuts: this.sedimentCuts.get(feedbackSessionId) ?? 0,
|
|
497
|
+
})
|
|
498
|
+
if (mode.conservative) {
|
|
499
|
+
this.warnOnce(agent.session, 'sediment:conservative', 'context-compression sediment feedback armed conservative mode: %s', mode.reason)
|
|
500
|
+
}
|
|
501
|
+
} catch { /* 观测失败静默:反馈环维持上次状态 */ }
|
|
432
502
|
// TokenPilot-inspired E1: advisory estimator pass, strictly off the
|
|
433
503
|
// synchronous chain. Verdicts only feed the next pressure pass.
|
|
434
504
|
void this.postflightEstimatorPass(agent.session, signal).catch(() => undefined)
|
|
@@ -652,6 +722,232 @@ export class ToolResultPruner extends Service {
|
|
|
652
722
|
return snapshot
|
|
653
723
|
}
|
|
654
724
|
|
|
725
|
+
private readonly sedimentOrchestrators = new WeakMap<Session, SedimentOrchestrator>()
|
|
726
|
+
private readonly sedimentWatchers = new WeakMap<Session, SedimentFeedbackWatcher>()
|
|
727
|
+
private readonly sedimentCuts = new Map<string, number>()
|
|
728
|
+
private readonly ptcAgingMemo = new WeakMap<Session, { events: number, blocked: boolean }>()
|
|
729
|
+
|
|
730
|
+
/**
|
|
731
|
+
* PTC aging short-circuit (T3.10): when an omnibus runner is registered and
|
|
732
|
+
* no direct write-family tool call is observed in the session, the regex
|
|
733
|
+
* superseded predicate is blind (writes fold into run_code bodies) — the
|
|
734
|
+
* rule-based aging branch is disabled for that session. Active only while
|
|
735
|
+
* the sediment gate is on: with default-off settings the existing readState
|
|
736
|
+
* behavior is byte-identical.
|
|
737
|
+
*/
|
|
738
|
+
private ptcAgingBlocked(session: Session): boolean {
|
|
739
|
+
if (this.activeSettings(session).sediment?.enabled !== true) return false
|
|
740
|
+
const events = looseEvents(session)
|
|
741
|
+
const memo = this.ptcAgingMemo.get(session)
|
|
742
|
+
if (memo !== undefined && memo.events === events.length) return memo.blocked
|
|
743
|
+
let blocked = false
|
|
744
|
+
const hasTool = (name: string): boolean => {
|
|
745
|
+
try {
|
|
746
|
+
return (this.ctx.get('tools') as { get?: (n: string) => unknown } | undefined)?.get?.(name) !== undefined
|
|
747
|
+
} catch {
|
|
748
|
+
return false
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
if (detectPtcMode(hasTool)) {
|
|
752
|
+
let observedCalls = 0
|
|
753
|
+
let writeHits = 0
|
|
754
|
+
for (const event of events) {
|
|
755
|
+
if (event.type !== 'assistant/message') continue
|
|
756
|
+
for (const raw of looseContent(event)) {
|
|
757
|
+
const block = raw as LooseRecord | null
|
|
758
|
+
if (block !== null && block.type === 'tool-call') {
|
|
759
|
+
observedCalls += 1
|
|
760
|
+
if (isWriteToolName(String(block.name ?? ''))) writeHits += 1
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
blocked = readStateBlind(true, writeHits, observedCalls)
|
|
765
|
+
}
|
|
766
|
+
this.ptcAgingMemo.set(session, { events: events.length, blocked })
|
|
767
|
+
return blocked
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
/**
|
|
771
|
+
* Sedimentation entry (plan cci-sedimentation-triage T3.6): whole-turn
|
|
772
|
+
* replacement decided at `turn/end`, inside the quiet seam before the next
|
|
773
|
+
* request derives. Disabled sessions exit at the settings gate with zero
|
|
774
|
+
* downstream work; committed cards flush like any other surface write.
|
|
775
|
+
*/
|
|
776
|
+
private sedimentTurnEnd(session: Session): void {
|
|
777
|
+
const settings = this.activeSettings(session).sediment
|
|
778
|
+
if (settings === undefined || settings.enabled !== true) return
|
|
779
|
+
const events = sessionEvents(session)
|
|
780
|
+
let turn: number | undefined
|
|
781
|
+
for (let index = events.length - 1; index >= 0; index -= 1) {
|
|
782
|
+
const candidate = events[index]
|
|
783
|
+
if (candidate?.type === 'turn/end') {
|
|
784
|
+
const value = (candidate.data as { turn?: unknown }).turn
|
|
785
|
+
if (typeof value === 'number') { turn = value; break }
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
if (turn === undefined) return
|
|
789
|
+
const orchestrator = this.sedimentOrchestratorFor(session, settings)
|
|
790
|
+
let officialCheckpointSeq: number | undefined
|
|
791
|
+
for (const seq of [...session.surface.nodes].reverse()) {
|
|
792
|
+
const event = events[seq]
|
|
793
|
+
if (event?.type !== 'user/message') continue
|
|
794
|
+
const kind = (event.data as { source?: { kind?: unknown } }).source?.kind
|
|
795
|
+
if (kind === 'compact-checkpoint') { officialCheckpointSeq = seq; break }
|
|
796
|
+
}
|
|
797
|
+
let compactionOpen = false
|
|
798
|
+
for (let index = events.length - 1; index >= 0; index -= 1) {
|
|
799
|
+
const type = events[index]?.type
|
|
800
|
+
if (type === 'compaction/end') break
|
|
801
|
+
if (type === 'compaction/start') { compactionOpen = true; break }
|
|
802
|
+
}
|
|
803
|
+
const outcomePromise = orchestrator.handleTurnEnd(session as never, turn, {
|
|
804
|
+
lastEventType: 'turn/end',
|
|
805
|
+
inFlightRequest: this.state.activeRequestBoundaries.get(session) !== undefined,
|
|
806
|
+
compactionOpen,
|
|
807
|
+
officialCheckpointSeq,
|
|
808
|
+
resumeFirstBatch: false,
|
|
809
|
+
})
|
|
810
|
+
void outcomePromise.then(outcome => {
|
|
811
|
+
if (outcome.committed) {
|
|
812
|
+
try {
|
|
813
|
+
void (this.ctx as { sessions?: { flush?: (s: Session) => unknown } }).sessions?.flush?.(session)
|
|
814
|
+
} catch {
|
|
815
|
+
/* flush failure leaves the card durable in the event log; next flush picks it up */
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
}).catch(error => {
|
|
819
|
+
this.auditFailure(session, 'pressure', 'sediment', error)
|
|
820
|
+
this.ctx.logger.warn('context-compression sediment commit failed open: %o', error)
|
|
821
|
+
})
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
private sedimentOrchestratorFor(session: Session, settings: NonNullable<ContextCompressionSettings['sediment']>): SedimentOrchestrator {
|
|
825
|
+
let orchestrator = this.sedimentOrchestrators.get(session)
|
|
826
|
+
if (orchestrator !== undefined) return orchestrator
|
|
827
|
+
orchestrator = new SedimentOrchestrator({
|
|
828
|
+
settingsFor: () => this.activeSettings(session).sediment,
|
|
829
|
+
eventsFor: (_s, turn) => looseEvents(session)
|
|
830
|
+
.filter(event => looseData(event)?.turn === turn)
|
|
831
|
+
.map(event => {
|
|
832
|
+
const data = looseData(event)
|
|
833
|
+
return {
|
|
834
|
+
seq: event.seq as number,
|
|
835
|
+
type: event.type as string,
|
|
836
|
+
...(data === undefined ? {} : { data }),
|
|
837
|
+
}
|
|
838
|
+
}),
|
|
839
|
+
callInfoFor: () => {
|
|
840
|
+
const map = new Map<string, { name: string; argsJson: string }>()
|
|
841
|
+
for (const event of looseEvents(session)) {
|
|
842
|
+
if (event.type !== 'assistant/message') continue
|
|
843
|
+
for (const raw of looseContent(event)) {
|
|
844
|
+
const block = raw as LooseRecord | null
|
|
845
|
+
if (block !== null && block.type === 'tool-call' && typeof block.id === 'string') {
|
|
846
|
+
map.set(block.id, {
|
|
847
|
+
name: String(block.name ?? 'tool'),
|
|
848
|
+
argsJson: typeof block.arguments === 'string' ? block.arguments : JSON.stringify(block.arguments ?? {}),
|
|
849
|
+
})
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
return (callId: string | undefined) => (callId === undefined ? undefined : map.get(callId))
|
|
854
|
+
},
|
|
855
|
+
tailTokensFor: (_s, endSeq) => {
|
|
856
|
+
let tail = 0
|
|
857
|
+
for (const event of looseEvents(session)) {
|
|
858
|
+
if (typeof event.seq !== 'number' || event.seq <= endSeq) continue
|
|
859
|
+
tail += estimateTokens(sedimentEventText(event))
|
|
860
|
+
}
|
|
861
|
+
return tail
|
|
862
|
+
},
|
|
863
|
+
// Narrative tier 2 (T4.5): fold channel exists only when configured.
|
|
864
|
+
...(settings.foldMode === undefined || settings.foldMode === ''
|
|
865
|
+
? {}
|
|
866
|
+
: {
|
|
867
|
+
fold: {
|
|
868
|
+
run: async (sessionId, prompt, signal) => {
|
|
869
|
+
// T5.3 observability: fold P99 sampling rides this one log line;
|
|
870
|
+
// the latency budget measured here is the LAN call itself.
|
|
871
|
+
const started = Date.now()
|
|
872
|
+
const outcome = await new FoldRouter(this.ctx, settings).fold(sessionId, prompt, signal)
|
|
873
|
+
this.ctx.logger.info(
|
|
874
|
+
'context-compression sediment fold (%s): tier=%s ok=%s latencyMs=%d%s',
|
|
875
|
+
sessionId, foldTier(prompt.inputTokens), outcome.text !== undefined,
|
|
876
|
+
Date.now() - started,
|
|
877
|
+
outcome.audit.ok ? '' : ` reason=${outcome.audit.reason ?? 'unknown'}`,
|
|
878
|
+
)
|
|
879
|
+
return outcome.text
|
|
880
|
+
},
|
|
881
|
+
},
|
|
882
|
+
}),
|
|
883
|
+
// T3.11 consumption: conservative state tightens the rewrite guard.
|
|
884
|
+
feedback: () => {
|
|
885
|
+
const watcher = this.sedimentWatchers.get(session)
|
|
886
|
+
return watcher === undefined
|
|
887
|
+
? { conservative: false, reason: 'ok' }
|
|
888
|
+
: { conservative: watcher.conservative, reason: watcher.conservative ? 'net-negative-streak' : 'ok' }
|
|
889
|
+
},
|
|
890
|
+
onLanded: (sessionId, savedTokens, tier, result) => {
|
|
891
|
+
this.sedimentCuts.set(sessionId, (this.sedimentCuts.get(sessionId) ?? 0) + 1)
|
|
892
|
+
this.ctx.logger.info(
|
|
893
|
+
'context-compression sediment landed (%s): turn saved %d tok via %s narrative',
|
|
894
|
+
sessionId, savedTokens, tier,
|
|
895
|
+
)
|
|
896
|
+
// 节省统计与 tail-trim 同口径:从 manifest 事件回取 shadowed 原文配对键。
|
|
897
|
+
const allEvents = looseEvents(session)
|
|
898
|
+
const manifestEvent = allEvents.find(event => event.seq === result.manifestSeq)
|
|
899
|
+
const shadowedSeqs: number[] = (looseData(manifestEvent)?.shadowedSeqs as number[] | undefined) ?? []
|
|
900
|
+
const originalText = shadowedSeqs
|
|
901
|
+
.map(seq => sedimentEventText(allEvents[seq]))
|
|
902
|
+
.join('\n')
|
|
903
|
+
const tokensBefore = (looseData(manifestEvent)?.shadowedTokenCount as number | undefined) ?? savedTokens
|
|
904
|
+
if (originalText.length > 0) {
|
|
905
|
+
getSavingsLedger().recordSaving({
|
|
906
|
+
sessionId,
|
|
907
|
+
component: 'sediment',
|
|
908
|
+
tokensBefore,
|
|
909
|
+
tokensAfter: Math.max(0, tokensBefore - savedTokens),
|
|
910
|
+
basis: 'characters',
|
|
911
|
+
sourceSeq: result.manifestSeq ?? 0,
|
|
912
|
+
replacementSeq: result.replacementSeq ?? 0,
|
|
913
|
+
originalText,
|
|
914
|
+
})
|
|
915
|
+
}
|
|
916
|
+
},
|
|
917
|
+
onSkip: (sessionId, reason) => {
|
|
918
|
+
this.ctx.logger.debug?.(
|
|
919
|
+
'context-compression sediment skipped (%s): %s', sessionId, reason,
|
|
920
|
+
)
|
|
921
|
+
},
|
|
922
|
+
})
|
|
923
|
+
this.sedimentOrchestrators.set(session, orchestrator)
|
|
924
|
+
return orchestrator
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
/**
|
|
928
|
+
* T4.8 pairing footer: when a read-class result supersedes a live shallow
|
|
929
|
+
* map of the same file, the reduced text carries the data-shaped reminder
|
|
930
|
+
* (sibling ref + discard hint). Non-read calls, unparseable arguments, and
|
|
931
|
+
* sessions without a live map all return undefined — zero side effects.
|
|
932
|
+
*/
|
|
933
|
+
private shallowPairFooter(
|
|
934
|
+
session: Session,
|
|
935
|
+
candidate: { call: { name: string; arguments: string } },
|
|
936
|
+
): string | undefined {
|
|
937
|
+
if (/^(read|read_file|view)$/i.test(candidate.call.name) === false) return undefined
|
|
938
|
+
let filePath: string
|
|
939
|
+
try {
|
|
940
|
+
const parsed = JSON.parse(candidate.call.arguments) as Record<string, unknown>
|
|
941
|
+
filePath = typeof parsed.file_path === 'string' ? parsed.file_path
|
|
942
|
+
: typeof parsed.path === 'string' ? parsed.path : ''
|
|
943
|
+
} catch {
|
|
944
|
+
return undefined
|
|
945
|
+
}
|
|
946
|
+
if (filePath === '') return undefined
|
|
947
|
+
const entry = liveShallowFor(session, filePath)
|
|
948
|
+
return entry === undefined ? undefined : buildShallowFooter(entry.checkpoint, entry.bodyTokens)
|
|
949
|
+
}
|
|
950
|
+
|
|
655
951
|
/**
|
|
656
952
|
* TokenPilot-inspired A2: replace the compaction summary checkpoint node
|
|
657
953
|
* with the same summary plus an Exact Sources locator block. Fails open:
|
|
@@ -726,6 +1022,9 @@ export class ToolResultPruner extends Service {
|
|
|
726
1022
|
const policy = this.activePolicy(session)
|
|
727
1023
|
const presetOptions = policy?.presetOptions
|
|
728
1024
|
if (policy === undefined || presetOptions?.readState !== true) return
|
|
1025
|
+
// T3.10: PTC-blind sessions must not feed the estimator either — its
|
|
1026
|
+
// verdicts unlock the same aging branch the short-circuit just closed.
|
|
1027
|
+
if (this.ptcAgingBlocked(session)) return
|
|
729
1028
|
const estimatorMode = presetOptions.estimator?.mode ?? ''
|
|
730
1029
|
if (estimatorMode === '') return
|
|
731
1030
|
const failures = this.state.estimatorFailures.get(session)
|
|
@@ -1883,9 +2182,15 @@ export class ToolResultPruner extends Service {
|
|
|
1883
2182
|
codeSkeleton,
|
|
1884
2183
|
})
|
|
1885
2184
|
if (output !== null) {
|
|
2185
|
+
// T4.8 pairing footer: a read result that supersedes a live shallow
|
|
2186
|
+
// map carries the data-shaped reminder (sibling ref + discard hint).
|
|
2187
|
+
const footer = this.shallowPairFooter(session, candidate)
|
|
2188
|
+
const reducedText = footer === undefined
|
|
2189
|
+
? output.text
|
|
2190
|
+
: `${output.text}\n\n${footer}`
|
|
1886
2191
|
const plan = this.plan(
|
|
1887
2192
|
candidate,
|
|
1888
|
-
[{ ...textBlock, text:
|
|
2193
|
+
[{ ...textBlock, text: reducedText }],
|
|
1889
2194
|
sourceSeq,
|
|
1890
2195
|
output.reducer,
|
|
1891
2196
|
'fresh',
|
|
@@ -2101,7 +2406,7 @@ export class ToolResultPruner extends Service {
|
|
|
2101
2406
|
// TokenPilot-inspired R2: a read output whose file was later mutated is
|
|
2102
2407
|
// superseded — its text can no longer match the file — so it takes the
|
|
2103
2408
|
// small whole-result placeholder before the ordinary reducer runs.
|
|
2104
|
-
if (policy.presetOptions?.readState === true && block !== null) {
|
|
2409
|
+
if (policy.presetOptions?.readState === true && block !== null && !this.ptcAgingBlocked(session)) {
|
|
2105
2410
|
const readPath = toolCallPath(candidate.call.arguments)
|
|
2106
2411
|
const estimatorExpired = this.state.estimatorVerdicts.get(session)?.get(candidate.seq) === true
|
|
2107
2412
|
if (readPath !== undefined
|
|
@@ -2843,6 +3148,7 @@ export class ToolResultPruner extends Service {
|
|
|
2843
3148
|
| 'terminal-pass'
|
|
2844
3149
|
| 'policy-resolution'
|
|
2845
3150
|
| 'summary-locator'
|
|
3151
|
+
| 'sediment'
|
|
2846
3152
|
| 'publication',
|
|
2847
3153
|
error: unknown,
|
|
2848
3154
|
): void {
|
|
@@ -143,6 +143,7 @@ export interface CompressionFailureAuditRecord extends CompressionAuditBase {
|
|
|
143
143
|
| 'terminal-pass'
|
|
144
144
|
| 'policy-resolution'
|
|
145
145
|
| 'summary-locator'
|
|
146
|
+
| 'sediment'
|
|
146
147
|
| 'publication'
|
|
147
148
|
readonly component?: CompressionAuditComponent
|
|
148
149
|
readonly manifestSeq?: number
|