dsh-context-compression-improved 0.10.3 → 0.10.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/$null +1 -0
  2. package/.github/workflows/ci.yml +10 -2
  3. package/README.de.md +1 -1
  4. package/README.es.md +1 -1
  5. package/README.fr.md +1 -1
  6. package/README.it.md +1 -1
  7. package/README.ja.md +1 -1
  8. package/README.ko.md +1 -1
  9. package/README.md +1 -1
  10. package/README.ru.md +1 -1
  11. package/README.zh.md +1 -1
  12. package/package.json +6 -6
  13. package/packages/selector/dsh.plugin.json +2 -2
  14. package/packages/selector/lib/client.d.ts +4 -0
  15. package/packages/selector/lib/client.js +70 -5
  16. package/packages/selector/lib/invariant.js +1 -1
  17. package/packages/selector/lib/profiles.d.ts +3 -1
  18. package/packages/selector/lib/pruner.d.ts +4 -2
  19. package/packages/selector/lib/pruner.js +40 -37
  20. package/packages/selector/lib/savings-integral.js +83 -24
  21. package/packages/selector/lib/tail-trim.js +2 -2
  22. package/packages/selector/lib/tool-result.js +22 -1
  23. package/packages/selector/package.json +21 -21
  24. package/packages/selector/src/client/CompressionProfileControls.tsx +30 -4
  25. package/packages/selector/src/client/CompressionProfileSelector.tsx +2 -0
  26. package/packages/selector/src/client/decode.ts +8 -1
  27. package/packages/selector/src/client/index.ts +11 -1
  28. package/packages/selector/src/client/locales/de.ts +2 -0
  29. package/packages/selector/src/client/locales/es.ts +2 -0
  30. package/packages/selector/src/client/locales/fr.ts +2 -0
  31. package/packages/selector/src/client/locales/it.ts +2 -0
  32. package/packages/selector/src/client/locales/ja.ts +2 -0
  33. package/packages/selector/src/client/locales/ko.ts +2 -0
  34. package/packages/selector/src/client/locales/ru.ts +2 -0
  35. package/packages/selector/src/client/locales.ts +4 -0
  36. package/packages/selector/src/client/settings-section.tsx +12 -3
  37. package/packages/selector/src/profiles.ts +20 -0
  38. package/packages/selector/src/pruner/content.ts +3 -2
  39. package/packages/selector/src/pruner.ts +8 -6
  40. package/packages/selector/src/runtime/config.ts +58 -14
  41. package/packages/selector/src/runtime/custom-policy.ts +22 -0
  42. package/packages/selector/src/runtime/reducers.ts +15 -14
  43. package/packages/selector/src/runtime/retrieve.ts +18 -16
  44. package/packages/selector/src/runtime/tail-trim.ts +2 -1
  45. package/packages/selector/src/runtime/tokenpilot/dedup.ts +2 -1
  46. package/packages/selector/src/runtime/tokenpilot/locator.ts +2 -1
  47. package/packages/selector/src/runtime/tool-names.ts +36 -0
  48. package/packages/selector/src/runtime/types.ts +3 -0
  49. package/packages/selector/tests/profiles.client.spec.tsx +4 -4
  50. package/packages/selector/tests/ptc-custom-write.client.spec.ts +86 -0
  51. package/packages/selector/tests/runtime/ptc-profile.spec.ts +133 -0
  52. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +15 -1
  53. package/packages/selector/tests/runtime/stats-backfill.spec.ts +3 -1
  54. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +14 -12
  55. package/packages/selector/tests/settings-seat.client.spec.ts +1 -1
  56. package/scripts/hosts.mjs +1 -0
@@ -22,7 +22,7 @@ import type { CompressionProfileSelectorProps } from './CompressionProfileSelect
22
22
  import { CustomPolicyEditor, editableCustom } from './CustomPolicyEditor.tsx'
23
23
 
24
24
  export function CompressionProfileControls({
25
- useCompression, select, saveCustom, resetCustom, t, showCustomEditor,
25
+ useCompression, select, saveCustom, resetCustom, savePtcCustom, resetPtcCustom, t, showCustomEditor,
26
26
  }: CompressionProfileSelectorProps & { showCustomEditor: boolean }) {
27
27
  const state = useCompression(snapshot => snapshot)
28
28
  // Harness 0.1.5 dropped browser-side agentPreset from session summaries; see
@@ -33,6 +33,7 @@ export function CompressionProfileControls({
33
33
  const [saving, setSaving] = useState(false)
34
34
  const [saveError, setSaveError] = useState<string | null>(null)
35
35
  const [draft, setDraft] = useState<CustomCompressionPolicyV3 | null>(null)
36
+ const [ptcDraft, setPtcDraft] = useState<CustomCompressionPolicyV3 | null>(null)
36
37
  const unavailableId = useId()
37
38
  const current = state.value?.profile ?? 'balanced'
38
39
  useEffect(() => {
@@ -41,8 +42,12 @@ export function CompressionProfileControls({
41
42
  }, [contextCompressionAvailable, state.status, state.writable])
42
43
  useEffect(() => {
43
44
  const custom = state.value?.custom
44
- setDraft(current === 'custom' && custom !== undefined ? editableCustom(custom) : null)
45
+ setDraft((current === 'custom' || current === 'tokenpilot-inspired') && custom !== undefined ? editableCustom(custom) : null)
45
46
  }, [current, state.value?.custom])
47
+ useEffect(() => {
48
+ const ptcCustom = state.value?.ptcCustom
49
+ setPtcDraft(current === 'ptc' && ptcCustom !== undefined ? editableCustom(ptcCustom) : null)
50
+ }, [current, state.value?.ptcCustom])
46
51
  if (state.status === 'unavailable') return null
47
52
  const busy = state.status === 'loading' || saving
48
53
  const label = busy ? t('status.loading') : t(`profile.${current}`)
@@ -103,10 +108,10 @@ export function CompressionProfileControls({
103
108
  <div className={css.settingsHint}>
104
109
  {t('autoCompact.summaryHint').replace('{percent}', String(state.value?.autoCompact?.thresholdPercent ?? AUTO_COMPACT_THRESHOLD_LIMITS.default))}
105
110
  </div>
106
- {current !== 'custom' || showCustomEditor ? null : (
111
+ {current !== 'custom' && current !== 'tokenpilot-inspired' || showCustomEditor ? null : (
107
112
  <div className={css.settingsHint}>{t('custom.settingsHint')}</div>
108
113
  )}
109
- {current !== 'custom' || draft === null || !showCustomEditor ? null : (
114
+ {current !== 'custom' && current !== 'tokenpilot-inspired' || draft === null || !showCustomEditor ? null : (
110
115
  <CustomPolicyEditor
111
116
  value={draft}
112
117
  disabled={busy || !state.writable || !contextCompressionAvailable}
@@ -127,6 +132,27 @@ export function CompressionProfileControls({
127
132
  t={t}
128
133
  />
129
134
  )}
135
+ {current !== 'ptc' || ptcDraft === null || !showCustomEditor ? null : (
136
+ <CustomPolicyEditor
137
+ value={ptcDraft}
138
+ disabled={busy || !state.writable || !contextCompressionAvailable}
139
+ setValue={setPtcDraft}
140
+ save={() => savePtcCustom(structuredClone(ptcDraft))}
141
+ reset={resetPtcCustom}
142
+ settle={(operation) => {
143
+ setSaveError(null)
144
+ setSaving(true)
145
+ void operation().then(
146
+ () => { setSaving(false) },
147
+ (error: unknown) => {
148
+ setSaving(false)
149
+ setSaveError(error instanceof Error && error.message !== '' ? error.message : t('status.saveFailed'))
150
+ },
151
+ )
152
+ }}
153
+ t={t}
154
+ />
155
+ )}
130
156
  {saveError === null ? null : <div className={css.error} role="alert">{saveError}</div>}
131
157
  </div>
132
158
  )
@@ -27,6 +27,8 @@ export interface CompressionSelectorInjected {
27
27
  select: (profile: CompressionProfile) => Promise<void>
28
28
  saveCustom: (custom: CustomCompressionPolicy) => Promise<void>
29
29
  resetCustom: () => Promise<void>
30
+ savePtcCustom: (custom: CustomCompressionPolicy) => Promise<void>
31
+ resetPtcCustom: () => Promise<void>
30
32
  saveAutoCompact: (thresholdPercent: number) => Promise<void>
31
33
  saveCodeSkeleton: (enabled: boolean) => Promise<void>
32
34
  saveIntentSummary: (enabled: boolean) => Promise<void>
@@ -3,6 +3,7 @@
3
3
  import {
4
4
  canonicalizeCustomPolicy,
5
5
  COMPRESSION_PROFILES,
6
+ DEFAULT_PTC_COMPRESSION_POLICY,
6
7
  decodeAutoCompactSettings,
7
8
  decodeCodeSkeletonSettings,
8
9
  decodeIntentSummarySettings,
@@ -27,11 +28,15 @@ import {
27
28
  export function decodeSettings(value: unknown): ContextCompressionSettings | undefined {
28
29
  if (!isPlainRecord(value)) return undefined
29
30
  const keys = Object.keys(value)
30
- if (keys.some(key => key !== 'profile' && key !== 'custom' && key !== 'autoCompact' && key !== 'codeSkeleton' && key !== 'intentSummary' && key !== 'monitorPanel' && key !== 'presetOptions')) {
31
+ if (keys.some(key => key !== 'profile' && key !== 'custom' && key !== 'ptcCustom' && key !== 'autoCompact' && key !== 'codeSkeleton' && key !== 'intentSummary' && key !== 'monitorPanel' && key !== 'presetOptions')) {
31
32
  return undefined
32
33
  }
33
34
  const profile = (value as { profile?: unknown }).profile
34
35
  const custom = (value as { custom?: unknown }).custom
36
+ const ptcCustomRaw = (value as { ptcCustom?: unknown }).ptcCustom
37
+ const ptcCustom = ptcCustomRaw === undefined
38
+ ? DEFAULT_PTC_COMPRESSION_POLICY
39
+ : isCustomCompressionPolicy(ptcCustomRaw) ? canonicalizeCustomPolicy(ptcCustomRaw) : undefined
35
40
  const autoCompact = decodeAutoCompactSettings((value as { autoCompact?: unknown }).autoCompact)
36
41
  const codeSkeleton = decodeCodeSkeletonSettings((value as { codeSkeleton?: unknown }).codeSkeleton)
37
42
  const intentSummary = decodeIntentSummarySettings((value as { intentSummary?: unknown }).intentSummary)
@@ -40,6 +45,7 @@ export function decodeSettings(value: unknown): ContextCompressionSettings | und
40
45
  return typeof profile === 'string'
41
46
  && (COMPRESSION_PROFILES as readonly string[]).includes(profile)
42
47
  && isCustomCompressionPolicy(custom)
48
+ && ptcCustom !== undefined
43
49
  && autoCompact !== undefined
44
50
  && codeSkeleton !== undefined
45
51
  && intentSummary !== undefined
@@ -47,6 +53,7 @@ export function decodeSettings(value: unknown): ContextCompressionSettings | und
47
53
  ? {
48
54
  profile: profile as CompressionProfile,
49
55
  custom: canonicalizeCustomPolicy(custom),
56
+ ptcCustom,
50
57
  autoCompact,
51
58
  codeSkeleton,
52
59
  intentSummary,
@@ -9,7 +9,7 @@ import {
9
9
  ContextCompressionSettingsSection,
10
10
  type CompressionSelectorInjected, type ContextCompressionSettings,
11
11
  } from './CompressionProfileSelector.tsx'
12
- import { DEFAULT_CUSTOM_COMPRESSION_POLICY } from '../profiles.ts'
12
+ import { DEFAULT_CUSTOM_COMPRESSION_POLICY, DEFAULT_PTC_COMPRESSION_POLICY } from '../profiles.ts'
13
13
  import { decodeSettings } from './decode.ts'
14
14
  import { initMonitorFab } from './monitor-fab.ts'
15
15
  import { en, zh } from './locales.ts'
@@ -315,6 +315,16 @@ let readMonitorPanelEnabled = (): boolean => monitorPanelEnabledCache
315
315
  settings => isCustomCompressionPolicy(settings.custom)
316
316
  && sameCustomPolicy(settings.custom, DEFAULT_CUSTOM_COMPRESSION_POLICY),
317
317
  ),
318
+ savePtcCustom: custom => writeAndConfirm(
319
+ () => scope.set('ptcCustom', custom),
320
+ settings => isCustomCompressionPolicy(settings.ptcCustom)
321
+ && sameCustomPolicy(settings.ptcCustom, custom),
322
+ ),
323
+ resetPtcCustom: () => writeAndConfirm(
324
+ () => scope.set('ptcCustom', structuredClone(DEFAULT_PTC_COMPRESSION_POLICY)),
325
+ settings => isCustomCompressionPolicy(settings.ptcCustom)
326
+ && sameCustomPolicy(settings.ptcCustom, DEFAULT_PTC_COMPRESSION_POLICY),
327
+ ),
318
328
  saveAutoCompact: thresholdPercent => writeAndConfirm(
319
329
  () => scope.set('autoCompact', { thresholdPercent }),
320
330
  settings => settings.autoCompact.thresholdPercent === thresholdPercent,
@@ -17,6 +17,8 @@ export const de = {
17
17
  'profile.savings': 'Sparen',
18
18
  'profile.adaptive': 'Adaptiv (kostenbewusst)',
19
19
  'profile.tokenpilot-inspired': 'TokenPilot-inspiriert',
20
+ 'profile.ptc': 'PTC / Codemodus (absolut)',
21
+ 'detail.ptc': 'Fensterunabhängige absolute Wasserstände für den Codemodus und Sitzungen mit vielen kleinen Ergebnissen; die Historienalterung startet, sobald der Umfang die Schwelle überschreitet, Schwellen separat editierbar',
20
22
  'estimator.title': 'Schätzer (optional)',
21
23
  'estimator.description': 'Ein kleines Hilfsmodell schätzt ohne Beispiele, ob alte Datei-Lesevorgänge wahrscheinlich noch referenziert werden; nur beratend für das Altern des Verlaufs. Ohne Konfiguration oder bei Fehlern greift reines Regelverhalten.',
22
24
  'estimator.mode': 'Kanal',
@@ -17,6 +17,8 @@ export const es = {
17
17
  'profile.savings': 'Ahorro',
18
18
  'profile.adaptive': 'Adaptativo (costo conservador)',
19
19
  'profile.tokenpilot-inspired': 'Inspirado en TokenPilot',
20
+ 'profile.ptc': 'PTC / modo código (absoluto)',
21
+ 'detail.ptc': 'Marcas de agua absolutas independientes de la ventana para el modo código y sesiones con muchos resultados pequeños; el envejecimiento del historial se activa al superar el umbral, umbrales editables por separado',
20
22
  'estimator.title': 'Estimador (opcional)',
21
23
  'estimator.description': 'Un pequeño modelo auxiliar estima sin ejemplos si las lecturas antiguas de archivos probablemente aún se referencian; solo consultivo para el envejecimiento del historial. Sin configuración o ante fallos, se vuelve al comportamiento basado solo en reglas.',
22
24
  'estimator.mode': 'Canal',
@@ -17,6 +17,8 @@ export const fr = {
17
17
  'profile.savings': 'Économies',
18
18
  'profile.adaptive': 'Adaptatif (coût prudent)',
19
19
  'profile.tokenpilot-inspired': 'Inspiré de TokenPilot',
20
+ 'profile.ptc': 'PTC / mode code (absolu)',
21
+ 'detail.ptc': 'Repères absolus indépendants de la fenêtre pour le mode code et les sessions à nombreux petits résultats ; l’ancienneté de l’historique démarre dès que le volume dépasse le seuil, seuils modifiables séparément',
20
22
  'estimator.title': 'Estimateur (optionnel)',
21
23
  'estimator.description': 'Un petit modèle auxiliaire estime sans exemples si les anciennes lectures de fichiers ont encore des chances d’être référencées ; indicatif seulement, pour le vieillissement de l’historique. Sans configuration ou en cas d’échec, retour aux règles seules.',
22
24
  'estimator.mode': 'Canal',
@@ -17,6 +17,8 @@ export const it = {
17
17
  'profile.savings': 'Risparmio',
18
18
  'profile.adaptive': 'Adattivo (costo prudente)',
19
19
  'profile.tokenpilot-inspired': 'Ispirato a TokenPilot',
20
+ 'profile.ptc': 'PTC / modalità codice (assoluto)',
21
+ 'detail.ptc': 'Soglie assolute indipendenti dalla finestra per la modalità codice e sessioni con molti risultati piccoli; l’invecchiamento della cronologia parte al superamento della soglia, soglie modificabili separatamente',
20
22
  'estimator.title': 'Stimatore (opzionale)',
21
23
  'estimator.description': 'Un piccolo modello ausiliario stima senza esempi se le vecchie letture di file sono probabilmente ancora referenziate; solo consultivo per l’invecchiamento della cronologia. Senza configurazione o in caso di errore si ripiega sul solo comportamento a regole.',
22
24
  'estimator.mode': 'Canale',
@@ -17,6 +17,8 @@ export const ja = {
17
17
  'profile.savings': '節約',
18
18
  'profile.adaptive': 'Adaptive(コスト重視)',
19
19
  'profile.tokenpilot-inspired': 'TokenPilot モード',
20
+ 'profile.ptc': 'PTC / コードモード(絶対)',
21
+ 'detail.ptc': 'コードモードや小さな結果が多いセッション向けの、ウィンドウ非依存の絶対水位。履歴の圧縮は存量がしきい値を超えると開始し、しきい値は個別に編集可能',
20
22
  'estimator.title': 'エスティメーター(任意)',
21
23
  'estimator.description': '小規模な補助モデルが、古いファイル読み取りにまだ参照価値があるかをゼロショットで判定します。履歴エージングの補助 only で、未設定や障害時は自動的にルールのみの経路へ戻り、本流には影響しません。',
22
24
  'estimator.mode': 'チャネル',
@@ -17,6 +17,8 @@ export const ko = {
17
17
  'profile.savings': '절약',
18
18
  'profile.adaptive': 'Adaptive(보수적 비용)',
19
19
  'profile.tokenpilot-inspired': 'TokenPilot 모드',
20
+ 'profile.ptc': 'PTC / 코드 모드(절대)',
21
+ 'detail.ptc': '코드 모드와 작은 결과가 많은 세션을 위한 창 독립적 절대 워터마크. 실시간 결과가 임계값을 넘으면 기록 정리가 시작되며, 임계값은 개별 편집 가능',
20
22
  'estimator.title': '추정기(선택 사항)',
21
23
  'estimator.description': '소형 보조 모델이 오래된 파일 읽기에 아직 참조 가치가 있는지 제로샷으로 판단합니다. 이력 에이징을 돕는 자문 전용 채널이며, 미설정 또는 실패 시 자동으로 규칙 전용 경로로 되돌아가므로 본 흐름에 영향을 주지 않습니다.',
22
24
  'estimator.mode': '채널',
@@ -17,6 +17,8 @@ export const ru = {
17
17
  'profile.savings': 'Экономия',
18
18
  'profile.adaptive': 'Адаптивный (консервативная цена)',
19
19
  'profile.tokenpilot-inspired': 'По мотивам TokenPilot',
20
+ 'profile.ptc': 'PTC / режим кода (абсолютный)',
21
+ 'detail.ptc': 'Абсолютные независящие от окна пороги для режима кода и сессий с множеством мелких результатов; старение истории начинается при превышении порога, пороги можно менять отдельно',
20
22
  'estimator.title': 'Оценщик (опционально)',
21
23
  'estimator.description': 'Небольшая вспомогательная модель без примеров оценивает, вероятно ли старое чтение файла всё ещё востребовано; только рекомендация для старения истории. Без настройки или при сбое — режим только правил.',
22
24
  'estimator.mode': 'Канал',
@@ -15,6 +15,8 @@ export const zh = {
15
15
  'profile.savings': '节省模式',
16
16
  'profile.adaptive': 'Adaptive(保守成本)',
17
17
  'profile.tokenpilot-inspired': 'TokenPilot 启发模式',
18
+ 'profile.ptc': 'PTC 模式(绝对水位)',
19
+ 'detail.ptc': '为代码模式与大量小结果会话提供与窗口无关的绝对水位;存量越过阈值即触发历史老化,阈值可在设置中独立编辑',
18
20
  'estimator.title': '估计器(可选)',
19
21
  'estimator.description': '辅助小模型零样本判断旧文件读取是否仍有引用价值,仅建议性加速历史清理;未配置或失败时自动退回纯规则通道,不影响主流程。',
20
22
  'estimator.mode': '通道',
@@ -176,6 +178,8 @@ export const en = {
176
178
  'profile.savings': 'Savings',
177
179
  'profile.adaptive': 'Adaptive (conservative cost)',
178
180
  'profile.tokenpilot-inspired': 'TokenPilot-inspired',
181
+ 'profile.ptc': 'PTC / Code-mode (absolute)',
182
+ 'detail.ptc': 'Window-independent absolute watermarks for code-mode and many-small-result sessions; history aging starts once live results cross the threshold, and the thresholds stay independently editable',
179
183
  'estimator.title': 'Estimator (optional)',
180
184
  'estimator.description': 'A small auxiliary model zero-shots whether old file reads are still likely referenced, advisory-only for history aging; unconfigured or failing endpoints fall back to rule-only behavior.',
181
185
  'estimator.mode': 'Channel',
@@ -26,7 +26,7 @@ export function ContextCompressionSettingsSection(props: CompressionProfileSelec
26
26
  }
27
27
 
28
28
  export function SettingsCompressionProfileControls({
29
- useCompression, select, saveCustom, resetCustom, saveAutoCompact, saveCodeSkeleton, saveIntentSummary, saveMonitorPanel,
29
+ useCompression, select, saveCustom, resetCustom, savePtcCustom, resetPtcCustom, saveAutoCompact, saveCodeSkeleton, saveIntentSummary, saveMonitorPanel,
30
30
  savePresetOptions, t,
31
31
  }: CompressionProfileSelectorProps) {
32
32
  const state = useCompression(snapshot => snapshot)
@@ -36,11 +36,16 @@ export function SettingsCompressionProfileControls({
36
36
  const [saving, setSaving] = useState(false)
37
37
  const [saveError, setSaveError] = useState<string | null>(null)
38
38
  const [draft, setDraft] = useState<CustomCompressionPolicyV3 | null>(null)
39
+ const [ptcDraft, setPtcDraft] = useState<CustomCompressionPolicyV3 | null>(null)
39
40
  const current = state.value?.profile ?? 'balanced'
40
41
  useEffect(() => {
41
42
  const custom = state.value?.custom
42
- setDraft(current === 'custom' && custom !== undefined ? editableCustom(custom) : null)
43
+ setDraft((current === 'custom' || current === 'tokenpilot-inspired') && custom !== undefined ? editableCustom(custom) : null)
43
44
  }, [current, state.value?.custom])
45
+ useEffect(() => {
46
+ const ptcCustom = state.value?.ptcCustom
47
+ setPtcDraft(current === 'ptc' && ptcCustom !== undefined ? editableCustom(ptcCustom) : null)
48
+ }, [current, state.value?.ptcCustom])
44
49
  if (state.status === 'unavailable') return null
45
50
 
46
51
  const busy = state.status === 'loading' || saving
@@ -130,10 +135,14 @@ export function SettingsCompressionProfileControls({
130
135
  )}
131
136
  <SavingsCard t={t} />
132
137
  <div className={css.pricing}>{t('pricing.disclosure')}</div>
133
- {current !== 'custom' || draft === null || !selectorAvailable ? null : (
138
+ {current !== 'custom' && current !== 'tokenpilot-inspired' || draft === null || !selectorAvailable ? null : (
134
139
  <CustomPolicyEditor value={draft} disabled={busy || !state.writable} setValue={setDraft}
135
140
  save={() => saveCustom(structuredClone(draft))} reset={resetCustom} settle={settle} t={t} />
136
141
  )}
142
+ {current !== 'ptc' || ptcDraft === null || !selectorAvailable ? null : (
143
+ <CustomPolicyEditor value={ptcDraft} disabled={busy || !state.writable} setValue={setPtcDraft}
144
+ save={() => savePtcCustom(structuredClone(ptcDraft))} reset={resetPtcCustom} settle={settle} t={t} />
145
+ )}
137
146
  {saveError === null ? null : <div className={css.error} role="alert">{saveError}</div>}
138
147
  </section>
139
148
  )
@@ -7,6 +7,7 @@ export const COMPRESSION_PROFILES = [
7
7
  'savings',
8
8
  'adaptive',
9
9
  'tokenpilot-inspired',
10
+ 'ptc',
10
11
  'custom',
11
12
  ] as const
12
13
 
@@ -95,6 +96,23 @@ export const DEFAULT_CUSTOM_COMPRESSION_POLICY: CustomCompressionPolicyV3 = {
95
96
  tailTrim: { enabled: false, trigger: 700_000 },
96
97
  }
97
98
 
99
+ /** Browser-safe mirror of the runtime PTC default policy (absolute, window-independent). */
100
+ export const DEFAULT_PTC_COMPRESSION_POLICY: CustomCompressionPolicyV3 = {
101
+ version: 3,
102
+ unit: 'tokens',
103
+ fresh: { enabled: true, trigger: 4_096, target: 1_536 },
104
+ aggregate: { enabled: true, trigger: 16_384, target: 4_096 },
105
+ history: {
106
+ enabled: true,
107
+ trigger: 20_000,
108
+ keepRecentToolCalls: 8,
109
+ keepRecentTokens: 8_000,
110
+ minReclaim: 6_000,
111
+ },
112
+ prefixPolicy: 'pressure-break',
113
+ tailTrim: { enabled: false, trigger: 700_000 },
114
+ }
115
+
98
116
  /** User-tunable Auto Compact coordination preferences. */
99
117
  export interface AutoCompactSettings {
100
118
  thresholdPercent: number
@@ -318,6 +336,8 @@ export interface ContextCompressionSettings {
318
336
  profile: CompressionProfile
319
337
  /** Complete canonical policy captured with `profile` when the runtime first observes a Session. */
320
338
  custom: CustomCompressionPolicy
339
+ /** PTC profile's own editable policy, seeded from the ptc defaults; independent of `custom`. Optional like `monitorPanel`/`presetOptions`: schema-defaulted, always present after parse. */
340
+ ptcCustom?: CustomCompressionPolicy
321
341
  /** Auto Compact trigger captured with `profile` when the runtime first observes a Session. */
322
342
  autoCompact: AutoCompactSettings
323
343
  /** Code-skeleton reducer gate captured independently of `profile`. */
@@ -9,6 +9,7 @@
9
9
  */
10
10
 
11
11
  import type { ContentBlock } from '@deepseek-ai/dsh-llm'
12
+ import { RUNTIME_TOOL_NAMES } from '../runtime/tool-names.ts'
12
13
  import type {
13
14
  CompactionTokenView,
14
15
  ProviderMeasurementKey,
@@ -72,8 +73,8 @@ function unavailableCount(reason: string): TokenCount {
72
73
 
73
74
  function recoveryMarker(sourceRef: string, label: string, startLine?: number): string {
74
75
  const hint = startLine === undefined
75
- ? 'use context_compression_retrieve with a query or narrow start_line/max_lines if needed (avoid re-reading the whole result)'
76
- : `retrieve with context_compression_retrieve({"ref":"${sourceRef}","start_line":${String(startLine)},"max_lines":80})`
76
+ ? `use ${RUNTIME_TOOL_NAMES.RETRIEVE} with a query or narrow start_line/max_lines if needed (avoid re-reading the whole result)`
77
+ : `retrieve with ${RUNTIME_TOOL_NAMES.RETRIEVE}({"ref":"${sourceRef}","start_line":${String(startLine)},"max_lines":80})`
77
78
  return `\n\n[... ${label}; source=${sourceRef}; ${hint} ...]\n\n`
78
79
  }
79
80
 
@@ -60,6 +60,7 @@ import {
60
60
  tailTrimStub,
61
61
  } from './runtime/tail-trim.ts'
62
62
  import { installContextCompressionRetrieve } from './runtime/retrieve.ts'
63
+ import { RUNTIME_TOOL_NAMES } from './runtime/tool-names.ts'
63
64
  import type { PrunerState } from './pruner/state.ts'
64
65
  import { countOmittedLines, CAPACITY_PRESSURE_RATIO } from './pruner/tuning.ts'
65
66
  import type { ToolCallInfo, SnapshotCandidate, PlannedReplacement, HistoryPlanOutcome } from './pruner/types.ts'
@@ -1217,6 +1218,7 @@ export class ToolResultPruner extends Service {
1217
1218
  ...contextWindowTokens === undefined ? {} : { contextWindowTokens },
1218
1219
  autoCompactThresholdPercent: settings.autoCompact.thresholdPercent,
1219
1220
  },
1221
+ settings.ptcCustom,
1220
1222
  )
1221
1223
  // Route changes must produce a fresh audit record even when the policy
1222
1224
  // object is unchanged, or the dedupe would hide a mid-session reroute.
@@ -1551,7 +1553,7 @@ export class ToolResultPruner extends Service {
1551
1553
  * recovery tool; the per-session set admits future recovery paths.
1552
1554
  */
1553
1555
  private isRecoveryExempt(session: Session, candidate: SnapshotCandidate): boolean {
1554
- if (candidate.call.name === 'context_compression_retrieve') return true
1556
+ if (candidate.call.name === RUNTIME_TOOL_NAMES.RETRIEVE) return true
1555
1557
  return this.state.recoveryExemptions.get(session)?.has(candidate.seq) ?? false
1556
1558
  }
1557
1559
 
@@ -1627,7 +1629,7 @@ export class ToolResultPruner extends Service {
1627
1629
  ? candidate.count.tokens
1628
1630
  : charsToTokens(candidate.characterPressure)))
1629
1631
  if (policy.freshEnabled) {
1630
- if (candidates.some(candidate => candidate.call.name !== 'context_compression_retrieve'
1632
+ if (candidates.some(candidate => candidate.call.name !== RUNTIME_TOOL_NAMES.RETRIEVE
1631
1633
  && candidate.count.kind !== 'exact-tokenizer')) {
1632
1634
  this.warnExactUnavailable(session, view, 'fresh')
1633
1635
  }
@@ -1946,7 +1948,7 @@ export class ToolResultPruner extends Service {
1946
1948
  '[Tool result reduced to satisfy the completed-step aggregate budget]',
1947
1949
  `tool: ${candidate.call.name}`,
1948
1950
  `source: ${sourceRef}`,
1949
- 'Retrieve a narrow slice via context_compression_retrieve if needed.',
1951
+ `Retrieve a narrow slice via ${RUNTIME_TOOL_NAMES.RETRIEVE} if needed.`,
1950
1952
  ].join('\n')
1951
1953
  const plan = this.plan(
1952
1954
  candidate,
@@ -2293,7 +2295,7 @@ export class ToolResultPruner extends Service {
2293
2295
  || !completedTurns.has(assistant.data.turn)
2294
2296
  || !completedSteps.has(`${String(assistant.data.turn)}:${String(assistant.data.step)}`)) continue
2295
2297
  const calls = assistant.data.message.content as Extract<ContentBlock, { type: 'tool-call' }>[]
2296
- if (calls.some(call => call.name === 'context_compression_retrieve')) continue
2298
+ if (calls.some(call => call.name === RUNTIME_TOOL_NAMES.RETRIEVE)) continue
2297
2299
  const callIds = calls.map(call => String(call.id))
2298
2300
  if (new Set(callIds).size !== callIds.length) continue
2299
2301
  const resultSeqs = nodes.slice(index + 1, index + 1 + calls.length)
@@ -2652,7 +2654,7 @@ export class ToolResultPruner extends Service {
2652
2654
  this.warnOnce(
2653
2655
  session,
2654
2656
  'missing-context-retrieve',
2655
- 'context-compression kept original tool results because context_compression_retrieve is unavailable',
2657
+ `context-compression kept original tool results because ${RUNTIME_TOOL_NAMES.RETRIEVE} is unavailable`,
2656
2658
  )
2657
2659
  return []
2658
2660
  }
@@ -2672,7 +2674,7 @@ export class ToolResultPruner extends Service {
2672
2674
  const tools = this.ctx.get('tools')
2673
2675
  if (tools === undefined) return false
2674
2676
  const agent = this.ctx.get('agents')?.get(session.id)
2675
- return tools.get('context_compression_retrieve', agent) !== undefined
2677
+ return tools.get(RUNTIME_TOOL_NAMES.RETRIEVE, agent) !== undefined
2676
2678
  }
2677
2679
 
2678
2680
  private auditHistoryEvaluation(
@@ -19,6 +19,7 @@ import { COMPRESSION_PROFILES } from './types.ts'
19
19
  import {
20
20
  CustomCompressionPolicySchema,
21
21
  DEFAULT_CUSTOM_COMPRESSION_POLICY,
22
+ DEFAULT_PTC_COMPRESSION_POLICY,
22
23
  resolveCustomPolicy,
23
24
  type CustomPolicyResolutionOptions,
24
25
  } from './custom-policy.ts'
@@ -266,6 +267,7 @@ export function parsePresetOptionsSettings(value: unknown): PresetOptionsSetting
266
267
  const contextCompressionSettingsInputSchema = z.object({
267
268
  profile: z.union([...COMPRESSION_PROFILES]).default('balanced'),
268
269
  custom: CustomCompressionPolicySchema.default(DEFAULT_CUSTOM_COMPRESSION_POLICY),
270
+ ptcCustom: CustomCompressionPolicySchema.default(DEFAULT_PTC_COMPRESSION_POLICY),
269
271
  })
270
272
 
271
273
  /**
@@ -277,7 +279,7 @@ const contextCompressionSettingsInputSchema = z.object({
277
279
  */
278
280
  function assertPresentSection(
279
281
  candidate: Record<string, unknown>,
280
- key: 'profile' | 'custom',
282
+ key: 'profile' | 'custom' | 'ptcCustom',
281
283
  valid: (value: unknown) => boolean,
282
284
  ): void {
283
285
  if (!Object.hasOwn(candidate, key)) return
@@ -295,6 +297,7 @@ const isUsableCustomDocument = (value: unknown): boolean =>
295
297
  export const DEFAULT_CONTEXT_COMPRESSION_SETTINGS: ContextCompressionSettings = {
296
298
  profile: 'balanced',
297
299
  custom: structuredClone(DEFAULT_CUSTOM_COMPRESSION_POLICY),
300
+ ptcCustom: structuredClone(DEFAULT_PTC_COMPRESSION_POLICY),
298
301
  autoCompact: { thresholdPercent: AUTO_COMPACT_THRESHOLD_LIMITS.default },
299
302
  codeSkeleton: { enabled: false },
300
303
  intentSummary: { enabled: false },
@@ -336,7 +339,7 @@ export const ContextCompressionSettingsSchema: z<ContextCompressionSettings> = z
336
339
  // remain valid and inherit their defaults; the sections themselves stay
337
340
  // strictly shaped.
338
341
  const unknown = Object.keys(candidate).find(key =>
339
- key !== 'profile' && key !== 'custom' && key !== 'autoCompact' && key !== 'codeSkeleton' && key !== 'intentSummary' && key !== 'monitorPanel' && key !== 'presetOptions')
342
+ key !== 'profile' && key !== 'custom' && key !== 'ptcCustom' && key !== 'autoCompact' && key !== 'codeSkeleton' && key !== 'intentSummary' && key !== 'monitorPanel' && key !== 'presetOptions')
340
343
  if (unknown !== undefined) {
341
344
  throw new TypeError(`Context-compression settings: unknown key "${unknown}"`)
342
345
  }
@@ -346,6 +349,7 @@ export const ContextCompressionSettingsSchema: z<ContextCompressionSettings> = z
346
349
  // Only genuinely absent sections (internal partial fallbacks) may inherit.
347
350
  assertPresentSection(candidate, 'profile', isSupportedProfile)
348
351
  assertPresentSection(candidate, 'custom', isUsableCustomDocument)
352
+ assertPresentSection(candidate, 'ptcCustom', isUsableCustomDocument)
349
353
  const autoCompact = parseAutoCompactSettings(candidate.autoCompact)
350
354
  const codeSkeleton = parseCodeSkeletonSettings(candidate.codeSkeleton)
351
355
  const intentSummary = parseIntentSummarySettings(candidate.intentSummary)
@@ -623,9 +627,60 @@ export function resolvePolicy(
623
627
  profile: CompressionProfile,
624
628
  custom: CustomCompressionPolicy = DEFAULT_CUSTOM_COMPRESSION_POLICY,
625
629
  options: CustomPolicyResolutionOptions = {},
630
+ ptcCustom: CustomCompressionPolicy = DEFAULT_PTC_COMPRESSION_POLICY,
626
631
  ): CompressionPolicy {
627
632
  if (profile === 'custom') return resolveCustomPolicy(custom, options)
628
- const presets: Record<Exclude<CompressionProfile, 'custom'>, Omit<CompressionPolicy, 'profile'>> = {
633
+ if (profile === 'ptc') {
634
+ const resolved = resolveCustomPolicy(ptcCustom, options)
635
+ const policy: CompressionPolicy = {
636
+ ...resolved,
637
+ profile: 'ptc',
638
+ freshTriggerTokens: config.freshTriggerTokens ?? resolved.freshTriggerTokens,
639
+ freshTargetTokens: config.freshTargetTokens ?? resolved.freshTargetTokens,
640
+ aggregateTriggerTokens: config.aggregateTriggerTokens ?? resolved.aggregateTriggerTokens,
641
+ aggregateTargetTokens: config.aggregateTargetTokens ?? resolved.aggregateTargetTokens,
642
+ historyTriggerTokens: config.historyTriggerTokens ?? resolved.historyTriggerTokens,
643
+ historyKeepRecentToolCalls: config.historyKeepRecentToolCalls ?? resolved.historyKeepRecentToolCalls,
644
+ historyKeepRecentTokens: config.historyKeepRecentTokens ?? resolved.historyKeepRecentTokens,
645
+ historyMinReclaimTokens: config.historyMinReclaimTokens ?? resolved.historyMinReclaimTokens,
646
+ ...config.readInputCapChars === undefined ? {} : { readInputCapChars: config.readInputCapChars },
647
+ }
648
+ if (policy.freshTargetTokens >= policy.freshTriggerTokens && policy.freshEnabled) {
649
+ throw new Error('context compression policy: fresh target must be below trigger')
650
+ }
651
+ if (policy.aggregateTargetTokens >= policy.aggregateTriggerTokens && policy.aggregateEnabled) {
652
+ throw new Error('context compression policy: aggregate target must be below trigger')
653
+ }
654
+ if (policy.readInputCapChars !== undefined && policy.readInputCapChars <= policy.freshTriggerTokens * 4.0) {
655
+ throw new Error('context compression policy: read input cap would silence the fresh path')
656
+ }
657
+ return deepFreeze(policy)
658
+ }
659
+ if (profile === 'tokenpilot-inspired') {
660
+ const resolved = resolveCustomPolicy(custom, options)
661
+ const policy: CompressionPolicy = {
662
+ ...resolved,
663
+ profile: 'tokenpilot-inspired',
664
+ freshTriggerTokens: config.freshTriggerTokens ?? resolved.freshTriggerTokens,
665
+ freshTargetTokens: config.freshTargetTokens ?? resolved.freshTargetTokens,
666
+ aggregateTriggerTokens: config.aggregateTriggerTokens ?? resolved.aggregateTriggerTokens,
667
+ aggregateTargetTokens: config.aggregateTargetTokens ?? resolved.aggregateTargetTokens,
668
+ historyTriggerTokens: config.historyTriggerTokens ?? resolved.historyTriggerTokens,
669
+ historyKeepRecentToolCalls: config.historyKeepRecentToolCalls ?? resolved.historyKeepRecentToolCalls,
670
+ historyKeepRecentTokens: config.historyKeepRecentTokens ?? resolved.historyKeepRecentTokens,
671
+ historyMinReclaimTokens: config.historyMinReclaimTokens ?? resolved.historyMinReclaimTokens,
672
+ ...config.readInputCapChars === undefined ? {} : { readInputCapChars: config.readInputCapChars },
673
+ presetOptions: mergePresetOptions(config.presetOptions),
674
+ }
675
+ if (policy.freshTargetTokens >= policy.freshTriggerTokens && policy.freshEnabled) {
676
+ throw new Error('context compression policy: fresh target must be below trigger')
677
+ }
678
+ if (policy.aggregateTargetTokens >= policy.aggregateTriggerTokens && policy.aggregateEnabled) {
679
+ throw new Error('context compression policy: aggregate target must be below trigger')
680
+ }
681
+ return deepFreeze(policy)
682
+ }
683
+ const presets: Record<Exclude<CompressionProfile, 'custom' | 'tokenpilot-inspired' | 'ptc'>, Omit<CompressionPolicy, 'profile'>> = {
629
684
  off: {
630
685
  nativeToolResultEnabled: false, freshEnabled: false, aggregateEnabled: false, historyMode: 'disabled',
631
686
  nativeTriggerTokens: Number.MAX_SAFE_INTEGER, nativeTargetTokens: Number.MAX_SAFE_INTEGER,
@@ -674,14 +729,6 @@ export function resolvePolicy(
674
729
  historyTriggerTokens: 500_000, historyKeepRecentToolCalls: 10,
675
730
  historyKeepRecentTokens: 64_000, historyMinReclaimTokens: 96_000,
676
731
  },
677
- 'tokenpilot-inspired': {
678
- nativeToolResultEnabled: false, freshEnabled: true, aggregateEnabled: true, historyMode: 'routine',
679
- nativeTriggerTokens: Number.MAX_SAFE_INTEGER, nativeTargetTokens: Number.MAX_SAFE_INTEGER,
680
- freshTriggerTokens: 4_096, freshTargetTokens: 1_536,
681
- aggregateTriggerTokens: 32_768, aggregateTargetTokens: 12_288,
682
- historyTriggerTokens: 500_000, historyKeepRecentToolCalls: 10,
683
- historyKeepRecentTokens: 64_000, historyMinReclaimTokens: 96_000,
684
- },
685
732
  }
686
733
  const preset = presets[profile]
687
734
  const linkage = resolveAutoCompactLinkage(profile, options)
@@ -706,9 +753,6 @@ export function resolvePolicy(
706
753
  autoCompactTokens: linkage.autoCompactTokens,
707
754
  microDeadlineTokens: linkage.microDeadlineTokens,
708
755
  },
709
- ...profile === 'tokenpilot-inspired' ? {
710
- presetOptions: mergePresetOptions(config.presetOptions),
711
- } : {},
712
756
  }
713
757
  if (policy.nativeTargetTokens >= policy.nativeTriggerTokens && profile === 'native') {
714
758
  throw new Error('context compression policy: native target must be below trigger')
@@ -97,6 +97,28 @@ export const DEFAULT_CUSTOM_COMPRESSION_POLICY: CustomCompressionPolicyV3 = deep
97
97
  tailTrim: { enabled: false, trigger: 700_000 },
98
98
  })
99
99
 
100
+ /**
101
+ * PTC/code-mode default policy: window-independent absolute watermarks tuned
102
+ * for many-small-result sessions. `ptc` seeds its own editable `ptcCustom`
103
+ * document from this value, so editing `ptcCustom` never touches `custom` /
104
+ * `tokenpilot-inspired`.
105
+ */
106
+ export const DEFAULT_PTC_COMPRESSION_POLICY: CustomCompressionPolicyV3 = deepFreeze({
107
+ version: 3,
108
+ unit: 'tokens',
109
+ fresh: { enabled: true, trigger: 4_096, target: 1_536 },
110
+ aggregate: { enabled: true, trigger: 16_384, target: 4_096 },
111
+ history: {
112
+ enabled: true,
113
+ trigger: 20_000,
114
+ keepRecentToolCalls: 8,
115
+ keepRecentTokens: 8_000,
116
+ minReclaim: 6_000,
117
+ },
118
+ prefixPolicy: 'pressure-break',
119
+ tailTrim: { enabled: false, trigger: 700_000 },
120
+ })
121
+
100
122
  /** Routed model facts needed only by context-percent Custom documents. */
101
123
  export interface CustomPolicyResolutionOptions {
102
124
  /** Positive resolved shared model context capacity. */