Skip to content

7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.

TypeScript

Add prompt and context compression pipeline (#628)

Tashfeen878fb89365c0
diff --git a/.env.example b/.env.example
index 2a7626ca..819d0ec7 100644
--- a/.env.example
+++ b/.env.example
@@ -106,6 +106,14 @@ PORT=3001
# Hard cap on stored entries; the least-recently-used are evicted past this.
# RESPONSE_CACHE_MAX_ENTRIES=5000
+# Request-side prompt/context compression. The default is off. `lossless`
+# applies whitespace hygiene, exact repeated-block references, and reversible
+# tabular-JSON encoding; `standard` also filters tool output and superseded file
+# reads; `aggressive` adds age/relevance/budget condensation. The dashboard can
+# change this live under Settings. A request may lower the configured mode with
+# `X-FreeLLM-Compress`, but cannot override a global `off` master switch.
+# FREELLMAPI_COMPRESSION=off
+
# Custom-provider URL policy. Cloud metadata and link-local addresses
# (169.254.169.254, metadata.google.internal, fe80::/10, ...) are ALWAYS
# blocked as custom provider base URLs. By default localhost and private LAN
diff --git a/README.md b/README.md
index 9d4c86ad..eccb99c1 100644
--- a/README.md
+++ b/README.md
@@ -43,7 +43,7 @@ Your router updates its own model catalog from a signed feed: new free models, q
- [Contributing](#contributing)
- [Disclaimer](#disclaimer)
-**Guides:** [Install & deploy](docs/install.md) · [API reference](docs/api.md) · [Clients & coding agents](docs/clients.md) · [Architecture & internals](docs/architecture.md) · [Documentation index](docs/README.md) · [Contributor guide](CONTRIBUTING.md)
+**Guides:** [Install & deploy](docs/install.md) · [API reference](docs/api.md) · [Clients & coding agents](docs/clients.md) · [Prompt compression](docs/compression.md) · [Architecture & internals](docs/architecture.md) · [Documentation index](docs/README.md) · [Contributor guide](CONTRIBUTING.md)
## Why this exists
@@ -106,6 +106,7 @@ Based on public documentation, July 2026 — corrections welcome.
- **Per-key rate tracking** — RPM/RPD/TPM/TPD counters per `(platform, model, key)` that learn providers' reported ceilings, so routing always stays under every cap.
- **Self-updating model catalog** — the router syncs a signed catalog from freellmapi.co twice a day: new models, quota changes, and provider quirk fixes land automatically. [Premium →](#premium-live-catalog)
- **Sticky sessions & context handoff** — conversations stay on one model for 30 minutes; an optional compact handoff note keeps the thread coherent when a mid-chat switch does happen. [Details →](docs/clients.md#context-handoff)
+- **Prompt compression (opt-in)** — a shared, fail-open request pipeline can deduplicate prompts, filter tool output, compact repeated JSON, and trim stale context before cache lookup and routing. [Details →](docs/compression.md)
- **Encrypted keys, one token out** — provider keys are AES-256-GCM encrypted in SQLite and decrypted in-memory per request; your apps only ever see a single unified `freellmapi-…` bearer token.
- **Admin dashboard & analytics** — React UI to manage keys, reorder the chain, run a playground, and read p50/p95/TTFT analytics over 24h–90d windows; login-gated, dark/light themes, [60 languages](#languages).
- **MCP server & interactive docs** — agents can introspect usable models, provider health, and routing strategy over `/mcp`; a dependency-free OpenAPI viewer lives at `/v1/docs`. [Coding agents →](docs/clients.md)
diff --git a/client/src/components/settings-dialog.tsx b/client/src/components/settings-dialog.tsx
index 003fc50d..00f75969 100644
--- a/client/src/components/settings-dialog.tsx
+++ b/client/src/components/settings-dialog.tsx
@@ -1,5 +1,5 @@
-import { useMemo, useState } from 'react'
-import { Check, ChevronsUpDown, Monitor, Moon, Search, Sun, X } from 'lucide-react'
+import { useEffect, useMemo, useState } from 'react'
+import { Check, ChevronsUpDown, Gauge, Loader2, Monitor, Moon, Search, Sun, X } from 'lucide-react'
import {
Dialog,
DialogClose,
@@ -9,6 +9,7 @@ import {
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import { SUPPORTED_LOCALES, type Locale, useI18n } from '@/i18n'
import { type Theme, useTheme } from '@/theme-context'
+import { apiFetch } from '@/lib/api'
function LanguageCombobox() {
const { locale, setLocale, t } = useI18n()
@@ -124,6 +125,258 @@ const themeIcons = {
dark: Moon,
} satisfies Record<Theme, typeof Monitor>
+type CompressionMode = 'off' | 'lossless' | 'standard' | 'aggressive'
+
+interface CompressionEngineConfig {
+ enabled: boolean
+ [key: string]: unknown
+}
+
+interface CompressionConfig {
+ mode: CompressionMode
+ engines: Record<string, CompressionEngineConfig>
+ autoTriggerEstTokens?: number | null
+ targetTokens?: number | null
+ trustProjectFilters: boolean
+ prefixFreeze: boolean
+}
+
+interface CompressionStats {
+ requests: number
+ compressedRequests: number
+ estSavedTokens: number
+ savingsPercent: number
+}
+
+const ENGINE_IDS = [
+ 'dedup',
+ 'lite',
+ 'read-lifecycle',
+ 'toolfilter',
+ 'jsoncompact',
+ 'relevance',
+ 'aging',
+ 'hard-budget',
+] as const
+
+function CompressionSettings({ active }: { active: boolean }) {
+ const { t } = useI18n()
+ const [config, setConfig] = useState<CompressionConfig | null>(null)
+ const [stats, setStats] = useState<CompressionStats | null>(null)
+ const [previewInput, setPreviewInput] = useState('')
+ const [previewOutput, setPreviewOutput] = useState('')
+ const [busy, setBusy] = useState<'load' | 'save' | 'preview' | null>('load')
+ const [error, setError] = useState('')
+
+ useEffect(() => {
+ if (!active) return
+ let cancelled = false
+ Promise.all([
+ apiFetch<CompressionConfig>('/api/settings/compression'),
+ apiFetch<CompressionStats>('/api/compression/stats'),
+ ]).then(([nextConfig, nextStats]) => {
+ if (cancelled) return
+ setConfig(nextConfig)
+ setStats(nextStats)
+ setError('')
+ }).catch(reason => {
+ if (!cancelled) setError(reason instanceof Error ? reason.message : t('common.unknownError'))
+ }).finally(() => {
+ if (!cancelled) setBusy(null)
+ })
+ return () => { cancelled = true }
+ }, [active, t])
+
+ async function save() {
+ if (!config) return
+ setBusy('save')
+ setError('')
+ try {
+ setConfig(await apiFetch<CompressionConfig>('/api/settings/compression', {
+ method: 'PUT',
+ body: JSON.stringify(config),
+ }))
+ } catch (reason) {
+ setError(reason instanceof Error ? reason.message : t('common.unknownError'))
+ } finally {
+ setBusy(null)
+ }
+ }
+
+ async function preview() {
+ if (!config || !previewInput.trim()) return
+ setBusy('preview')
+ setError('')
+ try {
+ let requestBody: unknown = previewInput
+ try { requestBody = JSON.parse(previewInput) } catch { /* plain text preview */ }
+ const result = await apiFetch<{
+ compressed: unknown
+ stats: { estSavedTokens: number }
+ }>('/api/compression/preview', {
+ method: 'POST',
+ body: JSON.stringify({
+ mode: config.mode,
+ ...(requestBody && typeof requestBody === 'object' && 'messages' in requestBody
+ ? requestBody as Record<string, unknown>
+ : { body: previewInput }),
+ }),
+ })
+ setPreviewOutput(`${JSON.stringify(result.compressed, null, 2)}\n\n~${result.stats.estSavedTokens} tokens saved`)
+ } catch (reason) {
+ setError(reason instanceof Error ? reason.message : t('common.unknownError'))
+ } finally {
+ setBusy(null)
+ }
+ }
+
+ if (busy === 'load' && !config) {
+ return <div className="flex items-center gap-2 text-sm text-muted-foreground"><Loader2 className="size-4 animate-spin" />{t('common.loading')}</div>
+ }
+ if (!config) {
+ return error ? <p className="text-sm text-destructive">{error}</p> : null
+ }
+
+ const modes: Array<{ value: CompressionMode; label: string }> = [
+ { value: 'off', label: t('settings.compressionOff') },
+ { value: 'lossless', label: t('settings.compressionLossless') },
+ { value: 'standard', label: t('settings.compressionStandard') },
+ { value: 'aggressive', label: t('settings.compressionAggressive') },
+ ]
+
+ return (
+ <section className="space-y-4 border-t pt-5">
+ <div className="space-y-1">
+ <div className="flex items-center gap-2">
+ <Gauge className="size-4 text-muted-foreground" />
+ <h2 className="text-sm font-medium">{t('settings.compressionTitle')}</h2>
+ </div>
+ <p className="text-xs leading-relaxed text-muted-foreground">{t('settings.compressionDescription')}</p>
+ </div>
+
+ <div className="grid grid-cols-2 gap-1 rounded-xl border p-1 sm:grid-cols-4" role="radiogroup">
+ {modes.map(option => (
+ <button
+ key={option.value}
+ type="button"
+ role="radio"
+ aria-checked={config.mode === option.value}
+ onClick={() => setConfig(current => current ? { ...current, mode: option.value } : current)}
+ className={`rounded-lg px-2 py-2 text-xs transition-colors ${
+ config.mode === option.value
+ ? 'bg-foreground font-medium text-background'
+ : 'text-muted-foreground hover:bg-muted hover:text-foreground'
+ }`}
+ >
+ {option.label}
+ </button>
+ ))}
+ </div>
+
+ <div className="space-y-2">
+ <h3 className="text-xs font-medium uppercase tracking-wide text-muted-foreground">{t('settings.compressionEngines')}</h3>
+ <div className="grid grid-cols-2 gap-2 sm:grid-cols-4">
+ {ENGINE_IDS.map(id => (
+ <label key={id} className="flex items-center gap-2 rounded-lg border px-2.5 py-2 text-xs">
+ <input
+ type="checkbox"
+ checked={config.engines[id]?.enabled ?? true}
+ onChange={event => setConfig(current => current ? {
+ ...current,
+ engines: {
+ ...current.engines,
+ [id]: { ...(current.engines[id] ?? {}), enabled: event.target.checked },
+ },
+ } : current)}
+ className="size-3.5 accent-foreground"
+ />
+ <span className="truncate font-mono">{id}</span>
+ </label>
+ ))}
+ </div>
+ </div>
+
+ <div className="grid gap-3 sm:grid-cols-2">
+ <label className="space-y-1 text-xs">
+ <span className="font-medium">{t('settings.compressionAutoTrigger')}</span>
+ <input
+ type="number"
+ min={1}
+ value={config.autoTriggerEstTokens ?? ''}
+ onChange={event => setConfig(current => current ? {
+ ...current,
+ autoTriggerEstTokens: event.target.value ? Number(event.target.value) : null,
+ } : current)}
+ placeholder="32000"
+ className="h-9 w-full rounded-lg border bg-transparent px-3 font-mono outline-none focus-visible:ring-3 focus-visible:ring-ring/50"
+ />
+ </label>
+ <div className="space-y-2 pt-0.5 text-xs">
+ <label className="flex items-center gap-2">
+ <input
+ type="checkbox"
+ checked={config.prefixFreeze}
+ onChange={event => setConfig(current => current ? { ...current, prefixFreeze: event.target.checked } : current)}
+ className="size-3.5 accent-foreground"
+ />
+ {t('settings.compressionPrefixFreeze')}
+ </label>
+ <label className="flex items-center gap-2">
+ <input
+ type="checkbox"
+ checked={config.trustProjectFilters}
+ onChange={event => setConfig(current => current ? { ...current, trustProjectFilters: event.target.checked } : current)}
+ className="size-3.5 accent-foreground"
+ />
+ {t('settings.compressionTrustProjectFilters')}
+ </label>
+ </div>
+ </div>
+
+ {stats && (
+ <div className="grid grid-cols-3 divide-x rounded-xl border py-3 text-center">
+ <div><div className="text-base font-semibold">{stats.requests}</div><div className="text-[10px] text-muted-foreground">{t('analytics.requests')}</div></div>
+ <div><div className="text-base font-semibold">~{stats.estSavedTokens}</div><div className="text-[10px] text-muted-foreground">{t('settings.compressionEstimatedTokensSaved')}</div></div>
+ <div><div className="text-base font-semibold">{stats.savingsPercent}%</div><div className="text-[10px] text-muted-foreground">{t('settings.compressionStats')}</div></div>
+ </div>
+ )}
+
+ <div className="space-y-2">
+ <h3 className="text-xs font-medium uppercase tracking-wide text-muted-foreground">{t('settings.compressionPreview')}</h3>
+ <div className="grid gap-2 sm:grid-cols-2">
+ <textarea
+ value={previewInput}
+ onChange={event => setPreviewInput(event.target.value)}
+ placeholder={t('settings.compressionPreviewPlaceholder')}
+ className="min-h-28 resize-y rounded-lg border bg-transparent p-2 font-mono text-[11px] outline-none focus-visible:ring-3 focus-visible:ring-ring/50"
+ />
+ <pre className="min-h-28 max-h-52 overflow-auto whitespace-pre-wrap rounded-lg border bg-muted/30 p-2 text-[11px] text-muted-foreground">
+ {previewOutput}
+ </pre>
+ </div>
+ <button
+ type="button"
+ onClick={preview}
+ disabled={!previewInput.trim() || busy !== null}
+ className="rounded-lg border px-3 py-1.5 text-xs transition-colors hover:bg-muted disabled:opacity-50"
+ >
+ {busy === 'preview' ? t('common.applying') : t('settings.compressionRunPreview')}
+ </button>
+ </div>
+
+ {error && <p className="text-xs text-destructive">{error}</p>}
+ <button
+ type="button"
+ onClick={save}
+ disabled={busy !== null}
+ className="w-full rounded-lg bg-foreground px-3 py-2 text-xs font-medium text-background disabled:opacity-50"
+ >
+ {busy === 'save' ? t('common.saving') : t('common.saveChanges')}
+ </button>
+ </section>
+ )
+}
+
export function SettingsDialog({
open,
onOpenChange,
@@ -141,7 +394,7 @@ export function SettingsDialog({
return (
<Dialog open={open} onOpenChange={onOpenChange}>
- <DialogPopup maxWidth="max-w-md">
+ <DialogPopup maxWidth="max-w-2xl">
<div className="mb-6 flex items-center justify-between gap-4">
<DialogTitle>{t('settings.title')}</DialogTitle>
<DialogClose
@@ -188,6 +441,8 @@ export function SettingsDialog({
})}
</div>
</section>
+
+ <CompressionSettings active={open} />
</div>
</DialogPopup>
</Dialog>
diff --git a/client/src/i18n/locales/am.json b/client/src/i18n/locales/am.json
index 61823fdd..098e7dc3 100644
--- a/client/src/i18n/locales/am.json
+++ b/client/src/i18n/locales/am.json
@@ -76,7 +76,22 @@
"themeLight": "ብሩህ",
"themeDark": "ጨለማ",
"searchLanguage": "ቋንቋዎችን ይፈልጉ...",
- "noLanguages": "ምንም ቋንቋዎች አልተገኙም"
+ "noLanguages": "ምንም ቋንቋዎች አልተገኙም",
+ "compressionTitle": "የፕሮምፕት ጭመቃ",
+ "compressionDescription": "ኮድን፣ ስህተቶችን፣ ዱካዎችን፣ ቁጥሮችን እና የመሣሪያ ትርጓሜዎችን በመጠበቅ ከመላክ በፊት የጥያቄውን መጠን ይቀንሱ።",
+ "compressionOff": "ጠፍቷል",
+ "compressionLossless": "ያለ ኪሳራ",
+ "compressionStandard": "መደበኛ",
+ "compressionAggressive": "ኃይለኛ",
+ "compressionEngines": "ሞተሮች",
+ "compressionAutoTrigger": "ከተገመቱ ማስመሰያዎች በላይ ሲሆን በራስ-ሰር አስጀምር",
+ "compressionPrefixFreeze": "ተደጋጋሚ የፕሮምፕት ቅድመ-ቅጥያዎችን አቀዝቅዝ",
+ "compressionTrustProjectFilters": "የፕሮጀክት ማጣሪያ ፋይሎችን እመን",
+ "compressionStats": "የተቆጠበ መጠን",
+ "compressionEstimatedTokensSaved": "የተቆጠቡ ግምታዊ ማስመሰያዎች",
+ "compressionPreview": "ቀጥታ ቅድመ-እይታ",
+ "compressionPreviewPlaceholder": "የጥያቄ JSON ወይም ተራ ጽሑፍ ይለጥፉ",
+ "compressionRunPreview": "ቅድመ-እይታ አሂድ"
},
"models": {
"title": "ሞዴሎች",
diff --git a/client/src/i18n/locales/ar.json b/client/src/i18n/locales/ar.json
index 54fe4ba0..d6a08f2d 100644
--- a/client/src/i18n/locales/ar.json
+++ b/client/src/i18n/locales/ar.json
@@ -76,7 +76,22 @@
"themeLight": "فاتح",
"themeDark": "داكن",
"searchLanguage": "البحث عن اللغات…",
- "noLanguages": "لم يتم العثور على لغات"
+ "noLanguages": "لم يتم العثور على لغات",
+ "compressionTitle": "ضغط الموجه",
+ "compressionDescription": "تقليل حجم الطلب قبل التوجيه مع الحفاظ على الكود والأخطاء والمسارات والأرقام وتعريفات الأدوات.",
+ "compressionOff": "إيقاف",
+ "compressionLossless": "بدون فقد",
+ "compressionStandard": "قياسي",
+ "compressionAggressive": "مكثف",
+ "compressionEngines": "المحركات",
+ "compressionAutoTrigger": "تشغيل تلقائي عند تجاوز الرموز المقدرة",
+ "compressionPrefixFreeze": "تثبيت بادئات الموجه المتكررة",
+ "compressionTrustProjectFilters": "الوثوق بملفات تصفية المشروع",
+ "compressionStats": "الحجم الموفر",
+ "compressionEstimatedTokensSaved": "رموز مقدرة تم توفيرها",
+ "compressionPreview": "معاينة مباشرة",
+ "compressionPreviewPlaceholder": "الصق JSON الطلب أو نصًا عاديًا",
+ "compressionRunPreview": "تشغيل المعاينة"
},
"models": {
"title": "نماذج",
diff --git a/client/src/i18n/locales/az.json b/client/src/i18n/locales/az.json
index f6978595..45e9f4db 100644
--- a/client/src/i18n/locales/az.json
+++ b/client/src/i18n/locales/az.json
@@ -76,7 +76,22 @@
"themeLight": "İşıqlı",
"themeDark": "Tünd",
"searchLanguage": "Dilləri axtar...",
- "noLanguages": "Heç bir dil tapılmadı"
+ "noLanguages": "Heç bir dil tapılmadı",
+ "compressionTitle": "Prompt sıxılması",
+ "compressionDescription": "Kodu, səhvləri, yolları, rəqəmləri və alət təriflərini qoruyaraq marşrutlaşdırmadan əvvəl sorğu ölçüsünü azaldın.",
+ "compressionOff": "Söndürülüb",
+ "compressionLossless": "İtkisiz",
+ "compressionStandard": "Standart",
+ "compressionAggressive": "Aqressiv",
+ "compressionEngines": "Mühərriklər",
+ "compressionAutoTrigger": "Təxmini token həddi aşıldıqda avtomatik başlat",
+ "compressionPrefixFreeze": "Təkrarlanan prompt prefikslərini dondur",
+ "compressionTrustProjectFilters": "Layihə filtr fayllarına etibar et",
+ "compressionStats": "qənaət edilən ölçü",
+ "compressionEstimatedTokensSaved": "qənaət edilən təxmini tokenlər",
+ "compressionPreview": "Canlı önbaxış",
+ "compressionPreviewPlaceholder": "Sorğu JSON və ya sadə mətn yapışdırın",
+ "compressionRunPreview": "Önbaxışı işə sal"
},
"models": {
"title": "Modellər",
diff --git a/client/src/i18n/locales/bg.json b/client/src/i18n/locales/bg.json
index 9f3d7dd0..5b93952a 100644
--- a/client/src/i18n/locales/bg.json
+++ b/client/src/i18n/locales/bg.json
@@ -76,7 +76,22 @@
"themeLight": "Светла",
"themeDark": "Тъмна",
"searchLanguage": "Търсене на езици…",
- "noLanguages": "Няма намерени езици"
+ "noLanguages": "Няма намерени езици",
+ "compressionTitle": "Компресия на промпта",
+ "compressionDescription": "Намалете размера на заявката преди маршрутизиране, като запазите код, грешки, пътища, числа и дефиниции на инструменти.",
+ "compressionOff": "Изкл.",
+ "compressionLossless": "Без загуби",
+ "compressionStandard": "Стандартно",
+ "compressionAggressive": "Агресивно",
+ "compressionEngines": "Механизми",
+ "compressionAutoTrigger": "Автоматично задействане над прогнозния брой жетони",
+ "compressionPrefixFreeze": "Замразяване на повтарящи се префикси на промпта",
+ "compressionTrustProjectFilters": "Доверяване на файловете с филтри на проекта",
+ "compressionStats": "спестен размер",
+ "compressionEstimatedTokensSaved": "прогнозно спестени жетони",
+ "compressionPreview": "Преглед на живо",
+ "compressionPreviewPlaceholder": "Поставете JSON на заявка или обикновен текст",
+ "compressionRunPreview": "Изпълни преглед"
},
"models": {
"title": "Модели",
diff --git a/client/src/i18n/locales/bn.json b/client/src/i18n/locales/bn.json
index 77427090..9cc69d0a 100644
--- a/client/src/i18n/locales/bn.json
+++ b/client/src/i18n/locales/bn.json
@@ -76,7 +76,22 @@
"themeLight": "হালকা",
"themeDark": "গাঢ়",
"searchLanguage": "ভাষা অনুসন্ধান করুন...",
- "noLanguages": "কোনো ভাষা পাওয়া যায়নি"
+ "noLanguages": "কোনো ভাষা পাওয়া যায়নি",
+ "compressionTitle": "প্রম্পট কম্প্রেশন",
+ "compressionDescription": "কোড, ত্রুটি, পাথ, সংখ্যা এবং টুল সংজ্ঞা সংরক্ষণ করে রাউটিংয়ের আগে অনুরোধের আকার কমান।",
+ "compressionOff": "বন্ধ",
+ "compressionLossless": "লসলেস",
+ "compressionStandard": "স্ট্যান্ডার্ড",
+ "compressionAggressive": "আক্রমণাত্মক",
+ "compressionEngines": "ইঞ্জিন",
+ "compressionAutoTrigger": "আনুমানিক টোকেন ছাড়িয়ে গেলে স্বয়ংক্রিয়ভাবে চালু হবে",
+ "compressionPrefixFreeze": "পুনরাবৃত্ত প্রম্পট প্রিফিক্স ফ্রিজ করুন",
+ "compressionTrustProjectFilters": "প্রজেক্টের ফিল্টার ফাইল বিশ্বাস করুন",
+ "compressionStats": "আকার সাশ্রয়",
+ "compressionEstimatedTokensSaved": "আনুমানিক টোকেন সাশ্রয়",
+ "compressionPreview": "লাইভ প্রিভিউ",
+ "compressionPreviewPlaceholder": "অনুরোধের JSON বা সাধারণ টেক্সট পেস্ট করুন",
+ "compressionRunPreview": "প্রিভিউ চালান"
},
"models": {
"title": "মডেল",
diff --git a/client/src/i18n/locales/cs.json b/client/src/i18n/locales/cs.json
index 62142234..808e6817 100644
--- a/client/src/i18n/locales/cs.json
+++ b/client/src/i18n/locales/cs.json
@@ -76,7 +76,22 @@
"themeLight": "Světlý",
"themeDark": "Tmavý",
"searchLanguage": "Hledat jazyky…",
- "noLanguages": "Nenalezeny žádné jazyky"
+ "noLanguages": "Nenalezeny žádné jazyky",
+ "compressionTitle": "Komprese promptů",
+ "compressionDescription": "Zmenšete velikost požadavku před směrováním se zachováním kódu, chyb, cest, čísel a definic nástrojů.",
+ "compressionOff": "Vypnuto",
+ "compressionLossless": "Bezeztrátová",
+ "compressionStandard": "Standardní",
+ "compressionAggressive": "Agresivní",
+ "compressionEngines": "Moduly",
+ "compressionAutoTrigger": "Automaticky spustit nad odhadovaným počtem žetonů",
+ "compressionPrefixFreeze": "Zmrazit opakující se prefixy promptů",
+ "compressionTrustProjectFilters": "Důvěřovat filtrovacím souborům projektu",
+ "compressionStats": "ušetřená velikost",
+ "compressionEstimatedTokensSaved": "odhadem ušetřené žetony",
+ "compressionPreview": "Živý náhled",
+ "compressionPreviewPlaceholder": "Vložte JSON požadavku nebo prostý text",
+ "compressionRunPreview": "Spustit náhled"
},
"models": {
"title": "Modely",
diff --git a/client/src/i18n/locales/da.json b/client/src/i18n/locales/da.json
index 16d0ed04..39b5894d 100644
--- a/client/src/i18n/locales/da.json
+++ b/client/src/i18n/locales/da.json
@@ -76,7 +76,22 @@
"themeLight": "Lys",
"themeDark": "Mørk",
"searchLanguage": "Søg efter sprog…",
- "noLanguages": "Ingen sprog fundet"
+ "noLanguages": "Ingen sprog fundet",
+ "compressionTitle": "Promptkomprimering",
+ "compressionDescription": "Reducer forespørgslens størrelse før routing, mens kode, fejl, stier, tal og værktøjsdefinitioner bevares.",
+ "compressionOff": "Fra",
+ "compressionLossless": "Tabsfri",
+ "compressionStandard": "Standard",
+ "compressionAggressive": "Aggressiv",
+ "compressionEngines": "Motorer",
+ "compressionAutoTrigger": "Aktivér automatisk over estimerede tokens",
+ "compressionPrefixFreeze": "Frys tilbagevendende promptpræfikser",
+ "compressionTrustProjectFilters": "Stol på projektets filterfiler",
+ "compressionStats": "størrelse sparet",
+ "compressionEstimatedTokensSaved": "estimerede tokens sparet",
+ "compressionPreview": "Live-forhåndsvisning",
+ "compressionPreviewPlaceholder": "Indsæt forespørgsels-JSON eller almindelig tekst",
+ "compressionRunPreview": "Kør forhåndsvisning"
},
"models": {
"title": "Modeller",
diff --git a/client/src/i18n/locales/de.json b/client/src/i18n/locales/de.json
index 6399b8d7..068b66ed 100644
--- a/client/src/i18n/locales/de.json
+++ b/client/src/i18n/locales/de.json
@@ -76,7 +76,22 @@
"themeLight": "Hell",
"themeDark": "Dunkel",
"searchLanguage": "Sprachen suchen…",
- "noLanguages": "Keine Sprachen gefunden"
+ "noLanguages": "Keine Sprachen gefunden",
+ "compressionTitle": "Prompt-Komprimierung",
+ "compressionDescription": "Reduziert die Anfragegröße vor dem Routing und bewahrt dabei Code, Fehler, Pfade, Zahlen und Tool-Definitionen.",
+ "compressionOff": "Aus",
+ "compressionLossless": "Verlustfrei",
+ "compressionStandard": "Standard",
+ "compressionAggressive": "Aggressiv",
+ "compressionEngines": "Engines",
+ "compressionAutoTrigger": "Automatisch auslösen ab geschätzter Token-Anzahl",
+ "compressionPrefixFreeze": "Wiederkehrende Prompt-Präfixe einfrieren",
+ "compressionTrustProjectFilters": "Projekt-Filterdateien vertrauen",
+ "compressionStats": "Größe eingespart",
+ "compressionEstimatedTokensSaved": "geschätzte eingesparte Tokens",
+ "compressionPreview": "Live-Vorschau",
+ "compressionPreviewPlaceholder": "Anfrage-JSON oder einfachen Text einfügen",
+ "compressionRunPreview": "Vorschau ausführen"
},
"models": {
"title": "Modelle",
diff --git a/client/src/i18n/locales/el.json b/client/src/i18n/locales/el.json
index 6dca1e16..287e9a42 100644
--- a/client/src/i18n/locales/el.json
+++ b/client/src/i18n/locales/el.json
@@ -76,7 +76,22 @@
"themeLight": "Ανοιχτό",
"themeDark": "Σκούρο",
"searchLanguage": "Αναζήτηση γλωσσών...",
- "noLanguages": "Δεν βρέθηκαν γλώσσες"
+ "noLanguages": "Δεν βρέθηκαν γλώσσες",
+ "compressionTitle": "Συμπίεση prompt",
+ "compressionDescription": "Μειώστε το μέγεθος του αιτήματος πριν από τη δρομολόγηση, διατηρώντας κώδικα, σφάλματα, διαδρομές, αριθμούς και ορισμούς εργαλείων.",
+ "compressionOff": "Ανενεργό",
+ "compressionLossless": "Χωρίς απώλειες",
+ "compressionStandard": "Τυπική",
+ "compressionAggressive": "Επιθετική",
+ "compressionEngines": "Μηχανές",
+ "compressionAutoTrigger": "Αυτόματη ενεργοποίηση πάνω από τα εκτιμώμενα tokens",
+ "compressionPrefixFreeze": "Πάγωμα επαναλαμβανόμενων προθεμάτων prompt",
+ "compressionTrustProjectFilters": "Εμπιστοσύνη στα αρχεία φίλτρων του έργου",
+ "compressionStats": "εξοικονόμηση μεγέθους",
+ "compressionEstimatedTokensSaved": "εκτιμώμενα tokens που εξοικονομήθηκαν",
+ "compressionPreview": "Ζωντανή προεπισκόπηση",
+ "compressionPreviewPlaceholder": "Επικολλήστε JSON αιτήματος ή απλό κείμενο",
+ "compressionRunPreview": "Εκτέλεση προεπισκόπησης"
},
"models": {
"title": "Μοντέλα",
diff --git a/client/src/i18n/locales/en.json b/client/src/i18n/locales/en.json
index defd9620..d35007ff 100644
--- a/client/src/i18n/locales/en.json
+++ b/client/src/i18n/locales/en.json
@@ -76,7 +76,22 @@
"themeLight": "Light",
"themeDark": "Dark",
"searchLanguage": "Search languages…",
- "noLanguages": "No languages found"
+ "noLanguages": "No languages found",
+ "compressionTitle": "Prompt compression",
+ "compressionDescription": "Reduce request size before routing while preserving code, errors, paths, numbers, and tool definitions.",
+ "compressionOff": "Off",
+ "compressionLossless": "Lossless",
+ "compressionStandard": "Standard",
+ "compressionAggressive": "Aggressive",
+ "compressionEngines": "Engines",
+ "compressionAutoTrigger": "Auto-trigger above estimated tokens",
+ "compressionPrefixFreeze": "Freeze recurring prompt prefixes",
+ "compressionTrustProjectFilters": "Trust project filter files",
+ "compressionStats": "size saved",
+ "compressionEstimatedTokensSaved": "estimated tokens saved",
+ "compressionPreview": "Live preview",
+ "compressionPreviewPlaceholder": "Paste request JSON or plain text",
+ "compressionRunPreview": "Run preview"
},
"models": {
"title": "Models",
diff --git a/client/src/i18n/locales/es.json b/client/src/i18n/locales/es.json
index 989abe4d..f63c2d6b 100644
--- a/client/src/i18n/locales/es.json
+++ b/client/src/i18n/locales/es.json
@@ -76,7 +76,22 @@
"themeLight": "Claro",
"themeDark": "Oscuro",
"searchLanguage": "Buscar idiomas…",
- "noLanguages": "No se encontraron idiomas"
+ "noLanguages": "No se encontraron idiomas",
+ "compressionTitle": "Compresión de prompts",
+ "compressionDescription": "Reduce el tamaño de la solicitud antes del enrutamiento, preservando código, errores, rutas, números y definiciones de herramientas.",
+ "compressionOff": "Desactivada",
+ "compressionLossless": "Sin pérdidas",
+ "compressionStandard": "Estándar",
+ "compressionAggressive": "Agresiva",
+ "compressionEngines": "Motores",
+ "compressionAutoTrigger": "Activar automáticamente por encima de los tokens estimados",
+ "compressionPrefixFreeze": "Congelar prefijos de prompt recurrentes",
+ "compressionTrustProjectFilters": "Confiar en los archivos de filtro del proyecto",
+ "compressionStats": "tamaño ahorrado",
+ "compressionEstimatedTokensSaved": "tokens estimados ahorrados",
+ "compressionPreview": "Vista previa en vivo",
+ "compressionPreviewPlaceholder": "Pega JSON de la solicitud o texto sin formato",
+ "compressionRunPreview": "Ejecutar vista previa"
},
"models": {
"title": "Modelos",
diff --git a/client/src/i18n/locales/fa.json b/client/src/i18n/locales/fa.json
index 1b6c5b39..dd3bd4e1 100644
--- a/client/src/i18n/locales/fa.json
+++ b/client/src/i18n/locales/fa.json
@@ -76,7 +76,22 @@
"themeLight": "روشن",
"themeDark": "تیره",
"searchLanguage": "جستجوی زبان‌ها…",
- "noLanguages": "هیچ زبانی یافت نشد"
+ "noLanguages": "هیچ زبانی یافت نشد",
+ "compressionTitle": "فشرده‌سازی پرامپت",
+ "compressionDescription": "حجم درخواست را قبل از مسیریابی کاهش دهید و در عین حال کد، خطاها، مسیرها، اعداد و تعاریف ابزار حفظ شوند.",
+ "compressionOff": "خاموش",
+ "compressionLossless": "بدون اتلاف",
+ "compressionStandard": "استاندارد",
+ "compressionAggressive": "تهاجمی",
+ "compressionEngines": "موتورها",
+ "compressionAutoTrigger": "فعال‌سازی خودکار بالاتر از توکن‌های تخمینی",
+ "compressionPrefixFreeze": "ثابت نگه داشتن پیشوندهای تکراری پرامپت",
+ "compressionTrustProjectFilters": "اعتماد به فایل‌های فیلتر پروژه",
+ "compressionStats": "حجم صرفه‌جویی‌شده",
+ "compressionEstimatedTokensSaved": "توکن‌های تخمینی صرفه‌جویی‌شده",
+ "compressionPreview": "پیش‌نمایش زنده",
+ "compressionPreviewPlaceholder": "JSON درخواست یا متن ساده را جای‌گذاری کنید",
+ "compressionRunPreview": "اجرای پیش‌نمایش"
},
"models": {
"title": "مدل ها",
diff --git a/client/src/i18n/locales/fi.json b/client/src/i18n/locales/fi.json
index 922a9e06..b7bcb87b 100644
--- a/client/src/i18n/locales/fi.json
+++ b/client/src/i18n/locales/fi.json
@@ -76,7 +76,22 @@
"themeLight": "Vaalea",
"themeDark": "Tumma",
"searchLanguage": "Hae kieliä…",
- "noLanguages": "Kieliä ei löytynyt"
+ "noLanguages": "Kieliä ei löytynyt",
+ "compressionTitle": "Promptien pakkaus",
+ "compressionDescription": "Pienennä pyynnön kokoa ennen reititystä säilyttäen koodin, virheet, polut, numerot ja työkalumääritykset.",
+ "compressionOff": "Pois",
+ "compressionLossless": "Häviötön",
+ "compressionStandard": "Vakio",
+ "compressionAggressive": "Aggressiivinen",
+ "compressionEngines": "Moottorit",
+ "compressionAutoTrigger": "Käynnistä automaattisesti arvioitujen tokenien ylittyessä",
+ "compressionPrefixFreeze": "Jäädytä toistuvat prompt-etuliitteet",
+ "compressionTrustProjectFilters": "Luota projektin suodatintiedostoihin",
+ "compressionStats": "säästetty koko",
+ "compressionEstimatedTokensSaved": "arviolta säästetyt tokenit",
+ "compressionPreview": "Live-esikatselu",
+ "compressionPreviewPlaceholder": "Liitä pyynnön JSON tai pelkkä teksti",
+ "compressionRunPreview": "Suorita esikatselu"
},
"models": {
"title": "Mallit",
diff --git a/client/src/i18n/locales/fr.json b/client/src/i18n/locales/fr.json
index 51990aa4..15b97477 100644
--- a/client/src/i18n/locales/fr.json
+++ b/client/src/i18n/locales/fr.json
@@ -76,7 +76,22 @@
"themeLight": "Clair",
"themeDark": "Sombre",
"searchLanguage": "Rechercher des langues…",
- "noLanguages": "Aucune langue trouvée"
+ "noLanguages": "Aucune langue trouvée",
+ "compressionTitle": "Compression des prompts",
+ "compressionDescription": "Réduisez la taille des requêtes avant le routage tout en préservant le code, les erreurs, les chemins, les nombres et les définitions d'outils.",
+ "compressionOff": "Désactivée",
+ "compressionLossless": "Sans perte",
+ "compressionStandard": "Standard",
+ "compressionAggressive": "Agressive",
+ "compressionEngines": "Moteurs",
+ "compressionAutoTrigger": "Déclenchement automatique au-delà des tokens estimés",
+ "compressionPrefixFreeze": "Figer les préfixes de prompt récurrents",
+ "compressionTrustProjectFilters": "Faire confiance aux fichiers de filtres du projet",
+ "compressionStats": "taille économisée",
+ "compressionEstimatedTokensSaved": "tokens estimés économisés",
+ "compressionPreview": "Aperçu en direct",
+ "compressionPreviewPlaceholder": "Collez le JSON de la requête ou du texte brut",
+ "compressionRunPreview": "Lancer l'aperçu"
},
"models": {
"title": "Modèles",
diff --git a/client/src/i18n/locales/gu.json b/client/src/i18n/locales/gu.json
index 0a5b64bd..a706362f 100644
--- a/client/src/i18n/locales/gu.json
+++ b/client/src/i18n/locales/gu.json
@@ -76,7 +76,22 @@
"themeLight": "આછું",
"themeDark": "ઘાટું",
"searchLanguage": "ભાષાઓ શોધો...",
- "noLanguages": "કોઈ ભાષા મળી નથી"
+ "noLanguages": "કોઈ ભાષા મળી નથી",
+ "compressionTitle": "પ્રોમ્પ્ટ કમ્પ્રેશન",
+ "compressionDescription": "કોડ, ભૂલો, પાથ, સંખ્યાઓ અને ટૂલ વ્યાખ્યાઓ સાચવીને રાઉટિંગ પહેલાં વિનંતીનું કદ ઘટાડો.",
+ "compressionOff": "બંધ",
+ "compressionLossless": "લોસલેસ",
+ "compressionStandard": "સ્ટાન્ડર્ડ",
+ "compressionAggressive": "આક્રમક",
+ "compressionEngines": "એન્જિન",
+ "compressionAutoTrigger": "અંદાજિત ટોકન કરતાં વધુ થાય ત્યારે આપમેળે શરૂ કરો",
+ "compressionPrefixFreeze": "પુનરાવર્તિત પ્રોમ્પ્ટ પ્રીફિક્સ ફ્રીઝ કરો",
+ "compressionTrustProjectFilters": "પ્રોજેક્ટ ફિલ્ટર ફાઇલો પર વિશ્વાસ કરો",
+ "compressionStats": "કદ બચત",
+ "compressionEstimatedTokensSaved": "અંદાજિત ટોકન બચત",
+ "compressionPreview": "લાઇવ પ્રીવ્યૂ",
+ "compressionPreviewPlaceholder": "વિનંતીનું JSON અથવા સાદો ટેક્સ્ટ પેસ્ટ કરો",
+ "compressionRunPreview": "પ્રીવ્યૂ ચલાવો"
},
"models": {
"title": "મોડલ્સ",
diff --git a/client/src/i18n/locales/ha.json b/client/src/i18n/locales/ha.json
index d8423dfa..fc34c225 100644
--- a/client/src/i18n/locales/ha.json
+++ b/client/src/i18n/locales/ha.json
@@ -76,7 +76,22 @@
"themeLight": "Haske",
"themeDark": "Duhu",
"searchLanguage": "Bincika harsuna…",
- "noLanguages": "Ba a sami yaruka ba"
+ "noLanguages": "Ba a sami yaruka ba",
+ "compressionTitle": "Matsawar prompt",
+ "compressionDescription": "Rage girman buƙata kafin turawa yayin da ake kiyaye kod, kurakurai, hanyoyi, lambobi da ma'anonin kayan aiki.",
+ "compressionOff": "Kashe",
+ "compressionLossless": "Ba tare da asara ba",
+ "compressionStandard": "Daidaitacce",
+ "compressionAggressive": "Mai ƙarfi",
+ "compressionEngines": "Injina",
+ "compressionAutoTrigger": "Kunna kai tsaye idan an wuce ƙiyasin alamomi",
+ "compressionPrefixFreeze": "Daskare prefix na prompt masu maimaituwa",
+ "compressionTrustProjectFilters": "Amince da fayilolin tacewa na aikin",
+ "compressionStats": "girman da aka rage",
+ "compressionEstimatedTokensSaved": "ƙiyasin alamomin da aka rage",
+ "compressionPreview": "Samfoti kai tsaye",
+ "compressionPreviewPlaceholder": "Manna JSON na buƙata ko rubutu kawai",
+ "compressionRunPreview": "Gudanar da samfoti"
},
"models": {
"title": "Samfura",
diff --git a/client/src/i18n/locales/he.json b/client/src/i18n/locales/he.json
index 5d1d9939..e1001656 100644
--- a/client/src/i18n/locales/he.json
+++ b/client/src/i18n/locales/he.json
@@ -76,7 +76,22 @@
"themeLight": "בהיר",
"themeDark": "כהה",
"searchLanguage": "חיפוש שפות...",
- "noLanguages": "לא נמצאו שפות"
+ "noLanguages": "לא נמצאו שפות",
+ "compressionTitle": "דחיסת פרומפטים",
+ "compressionDescription": "הקטנת גודל הבקשה לפני הניתוב תוך שמירה על קוד, שגיאות, נתיבים, מספרים והגדרות כלים.",
+ "compressionOff": "כבוי",
+ "compressionLossless": "ללא אובדן",
+ "compressionStandard": "רגיל",
+ "compressionAggressive": "אגרסיבי",
+ "compressionEngines": "מנועים",
+ "compressionAutoTrigger": "הפעלה אוטומטית מעל אומדן טוקנים",
+ "compressionPrefixFreeze": "הקפאת קידומות פרומפט חוזרות",
+ "compressionTrustProjectFilters": "בטח בקובצי הסינון של הפרויקט",
+ "compressionStats": "חיסכון בגודל",
+ "compressionEstimatedTokensSaved": "אומדן טוקנים שנחסכו",
+ "compressionPreview": "תצוגה מקדימה חיה",
+ "compressionPreviewPlaceholder": "הדבק JSON של בקשה או טקסט רגיל",
+ "compressionRunPreview": "הרץ תצוגה מקדימה"
},
"models": {
"title": "דגמים",
diff --git a/client/src/i18n/locales/hi.json b/client/src/i18n/locales/hi.json
index c38b0de2..91ad2d82 100644
--- a/client/src/i18n/locales/hi.json
+++ b/client/src/i18n/locales/hi.json
@@ -76,7 +76,22 @@
"themeLight": "हल्का",
"themeDark": "गहरा",
"searchLanguage": "भाषाएँ खोजें…",
- "noLanguages": "कोई भाषा नहीं मिली"
+ "noLanguages": "कोई भाषा नहीं मिली",
+ "compressionTitle": "प्रॉम्प्ट संपीड़न",
+ "compressionDescription": "कोड, त्रुटियाँ, पाथ, संख्याएँ और टूल परिभाषाएँ सुरक्षित रखते हुए रूटिंग से पहले अनुरोध का आकार घटाएँ।",
+ "compressionOff": "बंद",
+ "compressionLossless": "हानिरहित",
+ "compressionStandard": "मानक",
+ "compressionAggressive": "आक्रामक",
+ "compressionEngines": "इंजन",
+ "compressionAutoTrigger": "अनुमानित टोकन से ऊपर स्वतः सक्रिय करें",
+ "compressionPrefixFreeze": "दोहराए जाने वाले प्रॉम्प्ट प्रीफ़िक्स फ़्रीज़ करें",
+ "compressionTrustProjectFilters": "प्रोजेक्ट फ़िल्टर फ़ाइलों पर भरोसा करें",
+ "compressionStats": "आकार में बचत",
+ "compressionEstimatedTokensSaved": "अनुमानित टोकन बचत",
+ "compressionPreview": "लाइव पूर्वावलोकन",
+ "compressionPreviewPlaceholder": "अनुरोध JSON या सादा टेक्स्ट पेस्ट करें",
+ "compressionRunPreview": "पूर्वावलोकन चलाएँ"
},
"models": {
"title": "मॉडल",
diff --git a/client/src/i18n/locales/hr.json b/client/src/i18n/locales/hr.json
index 8c60e32d..20c5c1b8 100644
--- a/client/src/i18n/locales/hr.json
+++ b/client/src/i18n/locales/hr.json
@@ -76,7 +76,22 @@
"themeLight": "Svijetla",
"themeDark": "Tamna",
"searchLanguage": "Pretraži jezike...",
- "noLanguages": "Nema pronađenih jezika"
+ "noLanguages": "Nema pronađenih jezika",
+ "compressionTitle": "Kompresija promptova",
+ "compressionDescription": "Smanjite veličinu zahtjeva prije usmjeravanja uz očuvanje koda, grešaka, putanja, brojeva i definicija alata.",
+ "compressionOff": "Isključeno",
+ "compressionLossless": "Bez gubitaka",
+ "compressionStandard": "Standardno",
+ "compressionAggressive": "Agresivno",
+ "compressionEngines": "Mehanizmi",
+ "compressionAutoTrigger": "Automatski pokreni iznad procijenjenih tokena",
+ "compressionPrefixFreeze": "Zamrzni ponavljajuće prefikse promptova",
+ "compressionTrustProjectFilters": "Vjeruj datotekama filtara projekta",
+ "compressionStats": "ušteda veličine",
+ "compressionEstimatedTokensSaved": "procijenjena ušteda tokena",
+ "compressionPreview": "Pregled uživo",
+ "compressionPreviewPlaceholder": "Zalijepite JSON zahtjeva ili običan tekst",
+ "compressionRunPreview": "Pokreni pregled"
},
"models": {
"title": "Modeli",
diff --git a/client/src/i18n/locales/hu.json b/client/src/i18n/locales/hu.json
index 733d5bad..309597e2 100644
--- a/client/src/i18n/locales/hu.json
+++ b/client/src/i18n/locales/hu.json
@@ -76,7 +76,22 @@
"themeLight": "Világos",
"themeDark": "Sötét",
"searchLanguage": "Nyelvek keresése…",
- "noLanguages": "Nem található nyelv"
+ "noLanguages": "Nem található nyelv",
+ "compressionTitle": "Prompt-tömörítés",
+ "compressionDescription": "Csökkenti a kérés méretét az útválasztás előtt, megőrizve a kódot, a hibákat, az elérési utakat, a számokat és az eszközdefiníciókat.",
+ "compressionOff": "Ki",
+ "compressionLossless": "Veszteségmentes",
+ "compressionStandard": "Normál",
+ "compressionAggressive": "Agresszív",
+ "compressionEngines": "Motorok",
+ "compressionAutoTrigger": "Automatikus indítás a becsült tokenszám felett",
+ "compressionPrefixFreeze": "Ismétlődő prompt-előtagok rögzítése",
+ "compressionTrustProjectFilters": "Bízzon a projekt szűrőfájljaiban",
+ "compressionStats": "megtakarított méret",
+ "compressionEstimatedTokensSaved": "becsült megtakarított tokenek",
+ "compressionPreview": "Élő előnézet",
+ "compressionPreviewPlaceholder": "Illessze be a kérés JSON-jét vagy egyszerű szöveget",
+ "compressionRunPreview": "Előnézet futtatása"
},
"models": {
"title": "Modellek",
diff --git a/client/src/i18n/locales/id.json b/client/src/i18n/locales/id.json
index dc788012..bfb7f71a 100644
--- a/client/src/i18n/locales/id.json
+++ b/client/src/i18n/locales/id.json
@@ -76,7 +76,22 @@
"themeLight": "Terang",
"themeDark": "Gelap",
"searchLanguage": "Cari bahasa…",
- "noLanguages": "Tidak ada bahasa yang ditemukan"
+ "noLanguages": "Tidak ada bahasa yang ditemukan",
+ "compressionTitle": "Kompresi prompt",
+ "compressionDescription": "Kurangi ukuran permintaan sebelum perutean sambil mempertahankan kode, error, path, angka, dan definisi alat.",
+ "compressionOff": "Nonaktif",
+ "compressionLossless": "Tanpa kehilangan",
+ "compressionStandard": "Standar",
+ "compressionAggressive": "Agresif",
+ "compressionEngines": "Mesin",
+ "compressionAutoTrigger": "Picu otomatis di atas estimasi token",
+ "compressionPrefixFreeze": "Bekukan prefiks prompt yang berulang",
+ "compressionTrustProjectFilters": "Percayai file filter proyek",
+ "compressionStats": "ukuran dihemat",
+ "compressionEstimatedTokensSaved": "estimasi token dihemat",
+ "compressionPreview": "Pratinjau langsung",
+ "compressionPreviewPlaceholder": "Tempel JSON permintaan atau teks biasa",
+ "compressionRunPreview": "Jalankan pratinjau"
},
"models": {
"title": "Model",
diff --git a/client/src/i18n/locales/ig.json b/client/src/i18n/locales/ig.json
index 2c77d85b..33847d7b 100644
--- a/client/src/i18n/locales/ig.json
+++ b/client/src/i18n/locales/ig.json
@@ -76,7 +76,22 @@
"themeLight": "Ìhè",
"themeDark": "Ọchịchịrị",
"searchLanguage": "Chọọ asụsụ…",
- "noLanguages": "Ọnweghị asụsụ ahụrụ"
+ "noLanguages": "Ọnweghị asụsụ ahụrụ",
+ "compressionTitle": "Mpịkọta prompt",
+ "compressionDescription": "Belata nha arịrịọ tupu ntụzịaka ma na-echekwa koodu, njehie, ụzọ, ọnụọgụgụ, na nkọwa ngwaọrụ.",
+ "compressionOff": "Gbanyụọ",
+ "compressionLossless": "Enweghị mfu",
+ "compressionStandard": "Ọkọlọtọ",
+ "compressionAggressive": "Nke siri ike",
+ "compressionEngines": "Injin",
+ "compressionAutoTrigger": "Malite onwe ya mgbe token atụmatụ gafere",
+ "compressionPrefixFreeze": "Jigide mmalite prompt na-eme ugboro ugboro",
+ "compressionTrustProjectFilters": "Tụkwasị obi na faịlụ nzacha nke ọrụ ngo",
+ "compressionStats": "nha echekwara",
+ "compressionEstimatedTokensSaved": "token atụmatụ echekwara",
+ "compressionPreview": "Nlele ozugbo",
+ "compressionPreviewPlaceholder": "Tinye JSON arịrịọ ma ọ bụ ederede nkịtị",
+ "compressionRunPreview": "Mee nlele"
},
"models": {
"title": "Ụdị",
diff --git a/client/src/i18n/locales/it.json b/client/src/i18n/locales/it.json
index 43a9f0c6..3830e2d6 100644
--- a/client/src/i18n/locales/it.json
+++ b/client/src/i18n/locales/it.json
@@ -76,7 +76,22 @@
"themeLight": "Chiaro",
"themeDark": "Scuro",
"searchLanguage": "Cerca lingue…",
- "noLanguages": "Nessuna lingua trovata"
+ "noLanguages": "Nessuna lingua trovata",
+ "compressionTitle": "Compressione dei prompt",
+ "compressionDescription": "Riduci la dimensione delle richieste prima del routing preservando codice, errori, percorsi, numeri e definizioni degli strumenti.",
+ "compressionOff": "Disattivata",
+ "compressionLossless": "Senza perdita",
+ "compressionStandard": "Standard",
+ "compressionAggressive": "Aggressiva",
+ "compressionEngines": "Motori",
+ "compressionAutoTrigger": "Attivazione automatica oltre i token stimati",
+ "compressionPrefixFreeze": "Congela i prefissi ricorrenti dei prompt",
+ "compressionTrustProjectFilters": "Considera attendibili i file filtro del progetto",
+ "compressionStats": "dimensione risparmiata",
+ "compressionEstimatedTokensSaved": "token stimati risparmiati",
+ "compressionPreview": "Anteprima live",
+ "compressionPreviewPlaceholder": "Incolla il JSON della richiesta o testo semplice",
+ "compressionRunPreview": "Esegui anteprima"
},
"models": {
"title": "Modelli",
diff --git a/client/src/i18n/locales/ja.json b/client/src/i18n/locales/ja.json
index 18e507d6..efac9c84 100644
--- a/client/src/i18n/locales/ja.json
+++ b/client/src/i18n/locales/ja.json
@@ -76,7 +76,22 @@
"themeLight": "ライト",
"themeDark": "ダーク",
"searchLanguage": "言語を検索…",
- "noLanguages": "言語が見つかりません"
+ "noLanguages": "言語が見つかりません",
+ "compressionTitle": "プロンプト圧縮",
+ "compressionDescription": "コード、エラー、パス、数値、ツール定義を保持したまま、ルーティング前にリクエストサイズを削減します。",
+ "compressionOff": "オフ",
+ "compressionLossless": "ロスレス",
+ "compressionStandard": "標準",
+ "compressionAggressive": "アグレッシブ",
+ "compressionEngines": "エンジン",
+ "compressionAutoTrigger": "推定トークン数を超えたら自動実行",
+ "compressionPrefixFreeze": "繰り返されるプロンプトの接頭辞を固定",
+ "compressionTrustProjectFilters": "プロジェクトのフィルターファイルを信頼",
+ "compressionStats": "サイズ削減",
+ "compressionEstimatedTokensSaved": "推定削減トークン数",
+ "compressionPreview": "ライブプレビュー",
+ "compressionPreviewPlaceholder": "リクエストのJSONまたはプレーンテキストを貼り付け",
+ "compressionRunPreview": "プレビューを実行"
},
"models": {
"title": "モデル",
diff --git a/client/src/i18n/locales/ka.json b/client/src/i18n/locales/ka.json
index fb228d05..2014b7f3 100644
--- a/client/src/i18n/locales/ka.json
+++ b/client/src/i18n/locales/ka.json
@@ -76,7 +76,22 @@
"themeLight": "ღია",
"themeDark": "მუქი",
"searchLanguage": "ენების ძიება…",
- "noLanguages": "ენები ვერ მოიძებნა"
+ "noLanguages": "ენები ვერ მოიძებნა",
+ "compressionTitle": "პრომპტის შეკუმშვა",
+ "compressionDescription": "შეამცირეთ მოთხოვნის ზომა მარშრუტიზაციამდე კოდის, შეცდომების, გზების, რიცხვებისა და ხელსაწყოთა განმარტებების შენარჩუნებით.",
+ "compressionOff": "გამორთული",
+ "compressionLossless": "დანაკარგის გარეშე",
+ "compressionStandard": "სტანდარტული",
+ "compressionAggressive": "აგრესიული",
+ "compressionEngines": "ძრავები",
+ "compressionAutoTrigger": "ავტომატური ჩართვა სავარაუდო ტოკენების ზემოთ",
+ "compressionPrefixFreeze": "განმეორებადი პრომპტის პრეფიქსების გაყინვა",
+ "compressionTrustProjectFilters": "ენდეთ პროექტის ფილტრის ფაილებს",
+ "compressionStats": "დაზოგილი ზომა",
+ "compressionEstimatedTokensSaved": "სავარაუდო დაზოგილი ტოკენები",
+ "compressionPreview": "ცოცხალი გადახედვა",
+ "compressionPreviewPlaceholder": "ჩასვით მოთხოვნის JSON ან უბრალო ტექსტი",
+ "compressionRunPreview": "გადახედვის გაშვება"
},
"models": {
"title": "მოდელები",
diff --git a/client/src/i18n/locales/km.json b/client/src/i18n/locales/km.json
index 53c6b8c8..a51bb1c4 100644
--- a/client/src/i18n/locales/km.json
+++ b/client/src/i18n/locales/km.json
@@ -76,7 +76,22 @@
"themeLight": "ភ្លឺ",
"themeDark": "ងងឹត",
"searchLanguage": "ស្វែងរកភាសា...",
- "noLanguages": "រកមិនឃើញភាសា"
+ "noLanguages": "រកមិនឃើញភាសា",
+ "compressionTitle": "ការបង្ហាប់ prompt",
+ "compressionDescription": "កាត់បន្ថយទំហំសំណើមុនពេលបញ្ជូន ដោយរក្សាកូដ កំហុស ផ្លូវ លេខ និងនិយមន័យឧបករណ៍។",
+ "compressionOff": "បិទ",
+ "compressionLossless": "គ្មានការបាត់បង់",
+ "compressionStandard": "ស្តង់ដារ",
+ "compressionAggressive": "ខ្លាំង",
+ "compressionEngines": "ម៉ាស៊ីន",
+ "compressionAutoTrigger": "ចាប់ផ្តើមស្វ័យប្រវត្តិលើសពីតូខិនប៉ាន់ស្មាន",
+ "compressionPrefixFreeze": "បង្កកបុព្វបទ prompt ដែលកើតឡើងដដែលៗ",
+ "compressionTrustProjectFilters": "ទុកចិត្តឯកសារតម្រងគម្រោង",
+ "compressionStats": "ទំហំបានសន្សំ",
+ "compressionEstimatedTokensSaved": "តូខិនប៉ាន់ស្មានបានសន្សំ",
+ "compressionPreview": "មើលជាមុនផ្ទាល់",
+ "compressionPreviewPlaceholder": "បិទភ្ជាប់ JSON សំណើ ឬអត្ថបទធម្មតា",
+ "compressionRunPreview": "ដំណើរការមើលជាមុន"
},
"models": {
"title": "ម៉ូដែល",
diff --git a/client/src/i18n/locales/kn.json b/client/src/i18n/locales/kn.json
index bfc588f4..dd78f6cd 100644
--- a/client/src/i18n/locales/kn.json
+++ b/client/src/i18n/locales/kn.json
@@ -76,7 +76,22 @@
"themeLight": "ತಿಳಿ",
"themeDark": "ಗಾಢ",
"searchLanguage": "ಭಾಷೆಗಳನ್ನು ಹುಡುಕಿ...",
- "noLanguages": "ಯಾವುದೇ ಭಾಷೆಗಳು ಕಂಡುಬಂದಿಲ್ಲ"
+ "noLanguages": "ಯಾವುದೇ ಭಾಷೆಗಳು ಕಂಡುಬಂದಿಲ್ಲ",
+ "compressionTitle": "ಪ್ರಾಂಪ್ಟ್ ಸಂಕೋಚನ",
+ "compressionDescription": "ಕೋಡ್, ದೋಷಗಳು, ಪಾತ್‌ಗಳು, ಸಂಖ್ಯೆಗಳು ಮತ್ತು ಟೂಲ್ ವ್ಯಾಖ್ಯಾನಗಳನ್ನು ಉಳಿಸಿಕೊಂಡು ರೂಟಿಂಗ್‌ಗೆ ಮೊದಲು ವಿನಂತಿಯ ಗಾತ್ರವನ್ನು ಕಡಿಮೆ ಮಾಡಿ.",
+ "compressionOff": "ಆಫ್",
+ "compressionLossless": "ನಷ್ಟರಹಿತ",
+ "compressionStandard": "ಪ್ರಮಾಣಿತ",
+ "compressionAggressive": "ಆಕ್ರಮಣಶೀಲ",
+ "compressionEngines": "ಇಂಜಿನ್‌ಗಳು",
+ "compressionAutoTrigger": "ಅಂದಾಜು ಟೋಕನ್‌ಗಳನ್ನು ಮೀರಿದಾಗ ಸ್ವಯಂ ಪ್ರಚೋದನೆ",
+ "compressionPrefixFreeze": "ಮರುಕಳಿಸುವ ಪ್ರಾಂಪ್ಟ್ ಪೂರ್ವಪ್ರತ್ಯಯಗಳನ್ನು ಫ್ರೀಜ್ ಮಾಡಿ",
+ "compressionTrustProjectFilters": "ಪ್ರಾಜೆಕ್ಟ್ ಫಿಲ್ಟರ್ ಫೈಲ್‌ಗಳನ್ನು ನಂಬಿರಿ",
+ "compressionStats": "ಗಾತ್ರ ಉಳಿತಾಯ",
+ "compressionEstimatedTokensSaved": "ಅಂದಾಜು ಟೋಕನ್ ಉಳಿತಾಯ",
+ "compressionPreview": "ಲೈವ್ ಪೂರ್ವವೀಕ್ಷಣೆ",
+ "compressionPreviewPlaceholder": "ವಿನಂತಿಯ JSON ಅಥವಾ ಸರಳ ಪಠ್ಯವನ್ನು ಅಂಟಿಸಿ",
+ "compressionRunPreview": "ಪೂರ್ವವೀಕ್ಷಣೆ ರನ್ ಮಾಡಿ"
},
"models": {
"title": "ಮಾದರಿಗಳು",
diff --git a/client/src/i18n/locales/ko.json b/client/src/i18n/locales/ko.json
index 5b30bc1d..f89373de 100644
--- a/client/src/i18n/locales/ko.json
+++ b/client/src/i18n/locales/ko.json
@@ -76,7 +76,22 @@
"themeLight": "라이트",
"themeDark": "다크",
"searchLanguage": "언어 검색…",
- "noLanguages": "언어를 찾을 수 없습니다."
+ "noLanguages": "언어를 찾을 수 없습니다.",
+ "compressionTitle": "프롬프트 압축",
+ "compressionDescription": "코드, 오류, 경로, 숫자, 도구 정의를 유지하면서 라우팅 전에 요청 크기를 줄입니다.",
+ "compressionOff": "꺼짐",
+ "compressionLossless": "무손실",
+ "compressionStandard": "표준",
+ "compressionAggressive": "적극적",
+ "compressionEngines": "엔진",
+ "compressionAutoTrigger": "예상 토큰 초과 시 자동 실행",
+ "compressionPrefixFreeze": "반복되는 프롬프트 접두사 고정",
+ "compressionTrustProjectFilters": "프로젝트 필터 파일 신뢰",
+ "compressionStats": "크기 절감",
+ "compressionEstimatedTokensSaved": "예상 절감 토큰",
+ "compressionPreview": "실시간 미리보기",
+ "compressionPreviewPlaceholder": "요청 JSON 또는 일반 텍스트를 붙여넣으세요",
+ "compressionRunPreview": "미리보기 실행"
},
"models": {
"title": "모델",
diff --git a/client/src/i18n/locales/lt.json b/client/src/i18n/locales/lt.json
index 722bf60e..3db5e09d 100644
--- a/client/src/i18n/locales/lt.json
+++ b/client/src/i18n/locales/lt.json
@@ -76,7 +76,22 @@
"themeLight": "Šviesi",
"themeDark": "Tamsi",
"searchLanguage": "Ieškoti kalbų…",
- "noLanguages": "Kalbų nerasta"
+ "noLanguages": "Kalbų nerasta",
+ "compressionTitle": "Raginimų (prompt) suspaudimas",
+ "compressionDescription": "Sumažinkite užklausos dydį prieš maršrutizavimą, išsaugant kodą, klaidas, kelius, skaičius ir įrankių apibrėžimus.",
+ "compressionOff": "Išjungta",
+ "compressionLossless": "Be nuostolių",
+ "compressionStandard": "Standartinis",
+ "compressionAggressive": "Agresyvus",
+ "compressionEngines": "Varikliai",
+ "compressionAutoTrigger": "Automatiškai įjungti viršijus numatomus žetonus",
+ "compressionPrefixFreeze": "Užšaldyti pasikartojančius raginimų prefiksus",
+ "compressionTrustProjectFilters": "Pasitikėti projekto filtrų failais",
+ "compressionStats": "sutaupyta dydžio",
+ "compressionEstimatedTokensSaved": "numatoma sutaupytų žetonų",
+ "compressionPreview": "Tiesioginė peržiūra",
+ "compressionPreviewPlaceholder": "Įklijuokite užklausos JSON arba paprastą tekstą",
+ "compressionRunPreview": "Vykdyti peržiūrą"
},
"models": {
"title": "Modeliai",
diff --git a/client/src/i18n/locales/ml.json b/client/src/i18n/locales/ml.json
index a7dff750..45e2dd2c 100644
--- a/client/src/i18n/locales/ml.json
+++ b/client/src/i18n/locales/ml.json
@@ -76,7 +76,22 @@
"themeLight": "ലൈറ്റ്",
"themeDark": "ഡാർക്ക്",
"searchLanguage": "ഭാഷകൾ തിരയുക...",
- "noLanguages": "ഭാഷകളൊന്നും കണ്ടെത്തിയില്ല"
+ "noLanguages": "ഭാഷകളൊന്നും കണ്ടെത്തിയില്ല",
+ "compressionTitle": "പ്രോംപ്റ്റ് കംപ്രഷൻ",
+ "compressionDescription": "കോഡ്, പിശകുകൾ, പാതകൾ, സംഖ്യകൾ, ടൂൾ നിർവചനങ്ങൾ എന്നിവ നിലനിർത്തിക്കൊണ്ട് റൂട്ടിംഗിന് മുമ്പ് അഭ്യർത്ഥനയുടെ വലുപ്പം കുറയ്ക്കുക.",
+ "compressionOff": "ഓഫ്",
+ "compressionLossless": "നഷ്ടരഹിതം",
+ "compressionStandard": "സ്റ്റാൻഡേർഡ്",
+ "compressionAggressive": "ആക്രമണാത്മകം",
+ "compressionEngines": "എൻജിനുകൾ",
+ "compressionAutoTrigger": "കണക്കാക്കിയ ടോക്കണുകൾ കവിഞ്ഞാൽ സ്വയം പ്രവർത്തനക്ഷമമാക്കുക",
+ "compressionPrefixFreeze": "ആവർത്തിക്കുന്ന പ്രോംപ്റ്റ് പ്രിഫിക്സുകൾ ഫ്രീസ് ചെയ്യുക",
+ "compressionTrustProjectFilters": "പ്രോജക്റ്റ് ഫിൽട്ടർ ഫയലുകളെ വിശ്വസിക്കുക",
+ "compressionStats": "വലുപ്പം ലാഭിച്ചു",
+ "compressionEstimatedTokensSaved": "കണക്കാക്കിയ ടോക്കൺ ലാഭം",
+ "compressionPreview": "ലൈവ് പ്രിവ്യൂ",
+ "compressionPreviewPlaceholder": "അഭ്യർത്ഥന JSON അല്ലെങ്കിൽ സാധാരണ ടെക്സ്റ്റ് പേസ്റ്റ് ചെയ്യുക",
+ "compressionRunPreview": "പ്രിവ്യൂ പ്രവർത്തിപ്പിക്കുക"
},
"models": {
"title": "മോഡലുകൾ",
diff --git a/client/src/i18n/locales/mr.json b/client/src/i18n/locales/mr.json
index 1a8ab58c..46878434 100644
--- a/client/src/i18n/locales/mr.json
+++ b/client/src/i18n/locales/mr.json
@@ -76,7 +76,22 @@
"themeLight": "हलकी",
"themeDark": "गडद",
"searchLanguage": "भाषा शोधा…",
- "noLanguages": "कोणतीही भाषा आढळली नाही"
+ "noLanguages": "कोणतीही भाषा आढळली नाही",
+ "compressionTitle": "प्रॉम्प्ट कॉम्प्रेशन",
+ "compressionDescription": "कोड, त्रुटी, पाथ, संख्या आणि टूल व्याख्या जपून ठेवत राउटिंगपूर्वी विनंतीचा आकार कमी करा.",
+ "compressionOff": "बंद",
+ "compressionLossless": "हानीरहित",
+ "compressionStandard": "मानक",
+ "compressionAggressive": "आक्रमक",
+ "compressionEngines": "इंजिने",
+ "compressionAutoTrigger": "अंदाजे टोकनपेक्षा जास्त झाल्यास स्वयंचलित सुरू करा",
+ "compressionPrefixFreeze": "पुनरावृत्ती होणारे प्रॉम्प्ट प्रीफिक्स गोठवा",
+ "compressionTrustProjectFilters": "प्रोजेक्ट फिल्टर फाइल्सवर विश्वास ठेवा",
+ "compressionStats": "आकारात बचत",
+ "compressionEstimatedTokensSaved": "अंदाजे टोकन बचत",
+ "compressionPreview": "लाइव्ह पूर्वावलोकन",
+ "compressionPreviewPlaceholder": "विनंतीचे JSON किंवा साधा मजकूर पेस्ट करा",
+ "compressionRunPreview": "पूर्वावलोकन चालवा"
},
"models": {
"title": "मॉडेल्स",
diff --git a/client/src/i18n/locales/ms.json b/client/src/i18n/locales/ms.json
index 7ec76490..2d5fe9c8 100644
--- a/client/src/i18n/locales/ms.json
+++ b/client/src/i18n/locales/ms.json
@@ -76,7 +76,22 @@
"themeLight": "Cerah",
"themeDark": "Gelap",
"searchLanguage": "Bahasa carian...",
- "noLanguages": "Tiada bahasa ditemui"
+ "noLanguages": "Tiada bahasa ditemui",
+ "compressionTitle": "Pemampatan prompt",
+ "compressionDescription": "Kurangkan saiz permintaan sebelum penghalaan sambil mengekalkan kod, ralat, laluan, nombor, dan definisi alat.",
+ "compressionOff": "Mati",
+ "compressionLossless": "Tanpa kehilangan",
+ "compressionStandard": "Standard",
+ "compressionAggressive": "Agresif",
+ "compressionEngines": "Enjin",
+ "compressionAutoTrigger": "Cetus automatik melebihi anggaran token",
+ "compressionPrefixFreeze": "Bekukan awalan prompt yang berulang",
+ "compressionTrustProjectFilters": "Percayai fail penapis projek",
+ "compressionStats": "saiz dijimatkan",
+ "compressionEstimatedTokensSaved": "anggaran token dijimatkan",
+ "compressionPreview": "Pratonton langsung",
+ "compressionPreviewPlaceholder": "Tampal JSON permintaan atau teks biasa",
+ "compressionRunPreview": "Jalankan pratonton"
},
"models": {
"title": "Model",
diff --git a/client/src/i18n/locales/my.json b/client/src/i18n/locales/my.json
index 1db995aa..b113a842 100644
--- a/client/src/i18n/locales/my.json
+++ b/client/src/i18n/locales/my.json
@@ -76,7 +76,22 @@
"themeLight": "အလင်း",
"themeDark": "အမှောင်",
"searchLanguage": "ဘာသာစကားများကို ရှာဖွေရန်...",
- "noLanguages": "ဘာသာစကား မတွေ့ရှိပါ"
+ "noLanguages": "ဘာသာစကား မတွေ့ရှိပါ",
+ "compressionTitle": "Prompt ချုံ့ခြင်း",
+ "compressionDescription": "ကုဒ်၊ အမှားများ၊ လမ်းကြောင်းများ၊ နံပါတ်များနှင့် tool သတ်မှတ်ချက်များကို ထိန်းသိမ်းလျက် မပို့ဆောင်မီ တောင်းဆိုမှု အရွယ်အစားကို လျှော့ချသည်။",
+ "compressionOff": "ပိတ်",
+ "compressionLossless": "ဆုံးရှုံးမှုမရှိ",
+ "compressionStandard": "ပုံမှန်",
+ "compressionAggressive": "ပြင်းထန်",
+ "compressionEngines": "အင်ဂျင်များ",
+ "compressionAutoTrigger": "ခန့်မှန်း token အရေအတွက် ကျော်လွန်ပါက အလိုအလျောက် စတင်ရန်",
+ "compressionPrefixFreeze": "ထပ်ခါထပ်ခါ ပါဝင်သော prompt ရှေ့ဆက်များကို ပုံသေထားရန်",
+ "compressionTrustProjectFilters": "ပရောဂျက် filter ဖိုင်များကို ယုံကြည်ရန်",
+ "compressionStats": "ချွေတာနိုင်သော အရွယ်အစား",
+ "compressionEstimatedTokensSaved": "ခန့်မှန်း ချွေတာနိုင်သော token များ",
+ "compressionPreview": "တိုက်ရိုက် အစမ်းကြည့်ရှုမှု",
+ "compressionPreviewPlaceholder": "တောင်းဆိုမှု JSON သို့မဟုတ် စာသားရိုးရိုးကို ကူးထည့်ပါ",
+ "compressionRunPreview": "အစမ်းကြည့်ရန်"
},
"models": {
"title": "မော်ဒယ်များ",
diff --git a/client/src/i18n/locales/ne.json b/client/src/i18n/locales/ne.json
index 272fdef3..9454e073 100644
--- a/client/src/i18n/locales/ne.json
+++ b/client/src/i18n/locales/ne.json
@@ -76,7 +76,22 @@
"themeLight": "उज्यालो",
"themeDark": "अँध्यारो",
"searchLanguage": "भाषा खोजी गर्नुहोस्...",
- "noLanguages": "कुनै भाषा फेला परेन"
+ "noLanguages": "कुनै भाषा फेला परेन",
+ "compressionTitle": "प्रम्प्ट कम्प्रेसन",
+ "compressionDescription": "कोड, त्रुटिहरू, पथहरू, नम्बरहरू, र उपकरण परिभाषाहरू सुरक्षित राख्दै राउटिङ अघि अनुरोधको आकार घटाउनुहोस्।",
+ "compressionOff": "बन्द",
+ "compressionLossless": "क्षतिरहित",
+ "compressionStandard": "मानक",
+ "compressionAggressive": "आक्रामक",
+ "compressionEngines": "इन्जिनहरू",
+ "compressionAutoTrigger": "अनुमानित टोकनभन्दा माथि स्वतः सक्रिय",
+ "compressionPrefixFreeze": "दोहोरिने प्रम्प्ट उपसर्गहरू स्थिर राख्नुहोस्",
+ "compressionTrustProjectFilters": "परियोजना फिल्टर फाइलहरूमा विश्वास गर्नुहोस्",
+ "compressionStats": "आकार बचत",
+ "compressionEstimatedTokensSaved": "अनुमानित टोकन बचत",
+ "compressionPreview": "प्रत्यक्ष पूर्वावलोकन",
+ "compressionPreviewPlaceholder": "अनुरोध JSON वा सादा पाठ टाँस्नुहोस्",
+ "compressionRunPreview": "पूर्वावलोकन चलाउनुहोस्"
},
"models": {
"title": "नमूनाहरू",
diff --git a/client/src/i18n/locales/nl.json b/client/src/i18n/locales/nl.json
index 04a128b7..0c0f377e 100644
--- a/client/src/i18n/locales/nl.json
+++ b/client/src/i18n/locales/nl.json
@@ -76,7 +76,22 @@
"themeLight": "Licht",
"themeDark": "Donker",
"searchLanguage": "Talen zoeken…",
- "noLanguages": "Geen talen gevonden"
+ "noLanguages": "Geen talen gevonden",
+ "compressionTitle": "Promptcompressie",
+ "compressionDescription": "Verklein de omvang van verzoeken vóór routering, met behoud van code, fouten, paden, getallen en tooldefinities.",
+ "compressionOff": "Uit",
+ "compressionLossless": "Verliesvrij",
+ "compressionStandard": "Standaard",
+ "compressionAggressive": "Agressief",
+ "compressionEngines": "Engines",
+ "compressionAutoTrigger": "Automatisch activeren boven geschat aantal tokens",
+ "compressionPrefixFreeze": "Terugkerende promptprefixen bevriezen",
+ "compressionTrustProjectFilters": "Projectfilterbestanden vertrouwen",
+ "compressionStats": "omvang bespaard",
+ "compressionEstimatedTokensSaved": "geschat aantal bespaarde tokens",
+ "compressionPreview": "Live voorbeeld",
+ "compressionPreviewPlaceholder": "Plak verzoek-JSON of platte tekst",
+ "compressionRunPreview": "Voorbeeld uitvoeren"
},
"models": {
"title": "Modellen",
diff --git a/client/src/i18n/locales/no.json b/client/src/i18n/locales/no.json
index 404548aa..408b8234 100644
--- a/client/src/i18n/locales/no.json
+++ b/client/src/i18n/locales/no.json
@@ -76,7 +76,22 @@
"themeLight": "Lys",
"themeDark": "Mørk",
"searchLanguage": "Søk etter språk…",
- "noLanguages": "Ingen språk funnet"
+ "noLanguages": "Ingen språk funnet",
+ "compressionTitle": "Promptkomprimering",
+ "compressionDescription": "Reduser forespørselsstørrelsen før ruting, samtidig som kode, feil, stier, tall og verktøydefinisjoner bevares.",
+ "compressionOff": "Av",
+ "compressionLossless": "Tapsfri",
+ "compressionStandard": "Standard",
+ "compressionAggressive": "Aggressiv",
+ "compressionEngines": "Motorer",
+ "compressionAutoTrigger": "Utløs automatisk over estimerte tokens",
+ "compressionPrefixFreeze": "Frys gjentakende promptprefikser",
+ "compressionTrustProjectFilters": "Stol på prosjektfilterfiler",
+ "compressionStats": "størrelse spart",
+ "compressionEstimatedTokensSaved": "estimerte tokens spart",
+ "compressionPreview": "Direkte forhåndsvisning",
+ "compressionPreviewPlaceholder": "Lim inn forespørsels-JSON eller ren tekst",
+ "compressionRunPreview": "Kjør forhåndsvisning"
},
"models": {
"title": "Modeller",
diff --git a/client/src/i18n/locales/or.json b/client/src/i18n/locales/or.json
index 1273f625..4a5b264c 100644
--- a/client/src/i18n/locales/or.json
+++ b/client/src/i18n/locales/or.json
@@ -76,7 +76,22 @@
"themeLight": "ହାଲୁକା",
"themeDark": "ଗାଢ଼",
"searchLanguage": "ଭାଷାଗୁଡିକ ସନ୍ଧାନ କରନ୍ତୁ...",
- "noLanguages": "କୌଣସି ଭାଷା ମିଳିଲା ନାହିଁ"
+ "noLanguages": "କୌଣସି ଭାଷା ମିଳିଲା ନାହିଁ",
+ "compressionTitle": "ପ୍ରମ୍ପ୍ଟ ସଙ୍କୋଚନ",
+ "compressionDescription": "କୋଡ୍, ତ୍ରୁଟି, ପଥ, ସଂଖ୍ୟା, ଏବଂ ଟୁଲ୍ ପରିଭାଷାଗୁଡ଼ିକୁ ସୁରକ୍ଷିତ ରଖି ରାଉଟିଂ ପୂର୍ବରୁ ଅନୁରୋଧର ଆକାର କମାନ୍ତୁ।",
+ "compressionOff": "ବନ୍ଦ",
+ "compressionLossless": "କ୍ଷତିହୀନ",
+ "compressionStandard": "ମାନକ",
+ "compressionAggressive": "ଆକ୍ରମଣାତ୍ମକ",
+ "compressionEngines": "ଇଞ୍ଜିନ୍",
+ "compressionAutoTrigger": "ଆକଳିତ ଟୋକେନ୍ ଠାରୁ ଅଧିକ ହେଲେ ସ୍ୱୟଂଚାଳିତ ଭାବେ ସକ୍ରିୟ",
+ "compressionPrefixFreeze": "ପୁନରାବୃତ୍ତ ପ୍ରମ୍ପ୍ଟ ଉପସର୍ଗଗୁଡ଼ିକୁ ସ୍ଥିର ରଖନ୍ତୁ",
+ "compressionTrustProjectFilters": "ପ୍ରୋଜେକ୍ଟ ଫିଲ୍ଟର୍ ଫାଇଲଗୁଡ଼ିକୁ ବିଶ୍ୱାସ କରନ୍ତୁ",
+ "compressionStats": "ଆକାର ସଞ୍ଚୟ",
+ "compressionEstimatedTokensSaved": "ଆକଳିତ ଟୋକେନ୍ ସଞ୍ଚୟ",
+ "compressionPreview": "ଲାଇଭ୍ ପୂର୍ବାବଲୋକନ",
+ "compressionPreviewPlaceholder": "ଅନୁରୋଧ JSON କିମ୍ବା ସାଧା ଟେକ୍ସଟ୍ ପେଷ୍ଟ କରନ୍ତୁ",
+ "compressionRunPreview": "ପୂର୍ବାବଲୋକନ ଚଲାନ୍ତୁ"
},
"models": {
"title": "ମଡେଲଗୁଡିକ",
diff --git a/client/src/i18n/locales/pa.json b/client/src/i18n/locales/pa.json
index c126db46..af63de0e 100644
--- a/client/src/i18n/locales/pa.json
+++ b/client/src/i18n/locales/pa.json
@@ -76,7 +76,22 @@
"themeLight": "ਹਲਕਾ",
"themeDark": "ਗੂੜ੍ਹਾ",
"searchLanguage": "ਭਾਸ਼ਾਵਾਂ ਖੋਜੋ…",
- "noLanguages": "ਕੋਈ ਭਾਸ਼ਾਵਾਂ ਨਹੀਂ ਲੱਭੀਆਂ"
+ "noLanguages": "ਕੋਈ ਭਾਸ਼ਾਵਾਂ ਨਹੀਂ ਲੱਭੀਆਂ",
+ "compressionTitle": "ਪ੍ਰੋਂਪਟ ਕੰਪਰੈਸ਼ਨ",
+ "compressionDescription": "ਕੋਡ, ਗਲਤੀਆਂ, ਪਾਥ, ਨੰਬਰ ਅਤੇ ਟੂਲ ਪਰਿਭਾਸ਼ਾਵਾਂ ਨੂੰ ਸੁਰੱਖਿਅਤ ਰੱਖਦੇ ਹੋਏ ਰੂਟਿੰਗ ਤੋਂ ਪਹਿਲਾਂ ਬੇਨਤੀ ਦਾ ਆਕਾਰ ਘਟਾਓ।",
+ "compressionOff": "ਬੰਦ",
+ "compressionLossless": "ਨੁਕਸਾਨ-ਰਹਿਤ",
+ "compressionStandard": "ਮਿਆਰੀ",
+ "compressionAggressive": "ਹਮਲਾਵਰ",
+ "compressionEngines": "ਇੰਜਣ",
+ "compressionAutoTrigger": "ਅਨੁਮਾਨਿਤ ਟੋਕਨਾਂ ਤੋਂ ਵੱਧ ਹੋਣ 'ਤੇ ਆਪਣੇ-ਆਪ ਚਾਲੂ",
+ "compressionPrefixFreeze": "ਦੁਹਰਾਉਣ ਵਾਲੇ ਪ੍ਰੋਂਪਟ ਅਗੇਤਰ ਸਥਿਰ ਰੱਖੋ",
+ "compressionTrustProjectFilters": "ਪ੍ਰੋਜੈਕਟ ਫਿਲਟਰ ਫਾਈਲਾਂ 'ਤੇ ਭਰੋਸਾ ਕਰੋ",
+ "compressionStats": "ਆਕਾਰ ਦੀ ਬੱਚਤ",
+ "compressionEstimatedTokensSaved": "ਅਨੁਮਾਨਿਤ ਟੋਕਨਾਂ ਦੀ ਬੱਚਤ",
+ "compressionPreview": "ਲਾਈਵ ਝਲਕ",
+ "compressionPreviewPlaceholder": "ਬੇਨਤੀ JSON ਜਾਂ ਸਾਦਾ ਟੈਕਸਟ ਪੇਸਟ ਕਰੋ",
+ "compressionRunPreview": "ਝਲਕ ਚਲਾਓ"
},
"models": {
"title": "ਮਾਡਲ",
diff --git a/client/src/i18n/locales/pl.json b/client/src/i18n/locales/pl.json
index 007a2fd8..3b1924e7 100644
--- a/client/src/i18n/locales/pl.json
+++ b/client/src/i18n/locales/pl.json
@@ -76,7 +76,22 @@
"themeLight": "Jasny",
"themeDark": "Ciemny",
"searchLanguage": "Szukaj języków…",
- "noLanguages": "Nie znaleziono języków"
+ "noLanguages": "Nie znaleziono języków",
+ "compressionTitle": "Kompresja promptów",
+ "compressionDescription": "Zmniejszaj rozmiar żądań przed routingiem, zachowując kod, błędy, ścieżki, liczby i definicje narzędzi.",
+ "compressionOff": "Wyłączona",
+ "compressionLossless": "Bezstratna",
+ "compressionStandard": "Standardowa",
+ "compressionAggressive": "Agresywna",
+ "compressionEngines": "Silniki",
+ "compressionAutoTrigger": "Uruchamiaj automatycznie powyżej szacowanej liczby tokenów",
+ "compressionPrefixFreeze": "Zamrażaj powtarzające się prefiksy promptów",
+ "compressionTrustProjectFilters": "Ufaj plikom filtrów projektu",
+ "compressionStats": "zaoszczędzony rozmiar",
+ "compressionEstimatedTokensSaved": "szacowane zaoszczędzone tokeny",
+ "compressionPreview": "Podgląd na żywo",
+ "compressionPreviewPlaceholder": "Wklej JSON żądania lub zwykły tekst",
+ "compressionRunPreview": "Uruchom podgląd"
},
"models": {
"title": "Modele",
diff --git a/client/src/i18n/locales/pt-BR.json b/client/src/i18n/locales/pt-BR.json
index f8d78535..06be7889 100644
--- a/client/src/i18n/locales/pt-BR.json
+++ b/client/src/i18n/locales/pt-BR.json
@@ -76,7 +76,22 @@
"themeLight": "Claro",
"themeDark": "Escuro",
"searchLanguage": "Pesquisar idiomas…",
- "noLanguages": "Nenhum idioma encontrado"
+ "noLanguages": "Nenhum idioma encontrado",
+ "compressionTitle": "Compressão de prompts",
+ "compressionDescription": "Reduza o tamanho das solicitações antes do roteamento, preservando código, erros, caminhos, números e definições de ferramentas.",
+ "compressionOff": "Desativada",
+ "compressionLossless": "Sem perdas",
+ "compressionStandard": "Padrão",
+ "compressionAggressive": "Agressiva",
+ "compressionEngines": "Mecanismos",
+ "compressionAutoTrigger": "Acionar automaticamente acima dos tokens estimados",
+ "compressionPrefixFreeze": "Congelar prefixos de prompt recorrentes",
+ "compressionTrustProjectFilters": "Confiar nos arquivos de filtro do projeto",
+ "compressionStats": "tamanho economizado",
+ "compressionEstimatedTokensSaved": "tokens estimados economizados",
+ "compressionPreview": "Prévia ao vivo",
+ "compressionPreviewPlaceholder": "Cole o JSON da solicitação ou texto simples",
+ "compressionRunPreview": "Executar prévia"
},
"models": {
"title": "Modelos",
diff --git a/client/src/i18n/locales/pt-PT.json b/client/src/i18n/locales/pt-PT.json
index 48ed0c1e..6f30af49 100644
--- a/client/src/i18n/locales/pt-PT.json
+++ b/client/src/i18n/locales/pt-PT.json
@@ -76,7 +76,22 @@
"themeLight": "Claro",
"themeDark": "Escuro",
"searchLanguage": "Procurar idiomas…",
- "noLanguages": "Nenhuma língua encontrada"
+ "noLanguages": "Nenhuma língua encontrada",
+ "compressionTitle": "Compressão de prompts",
+ "compressionDescription": "Reduza o tamanho dos pedidos antes do encaminhamento, preservando código, erros, caminhos, números e definições de ferramentas.",
+ "compressionOff": "Desativada",
+ "compressionLossless": "Sem perdas",
+ "compressionStandard": "Padrão",
+ "compressionAggressive": "Agressiva",
+ "compressionEngines": "Motores",
+ "compressionAutoTrigger": "Ativar automaticamente acima dos tokens estimados",
+ "compressionPrefixFreeze": "Congelar prefixos de prompt recorrentes",
+ "compressionTrustProjectFilters": "Confiar nos ficheiros de filtro do projeto",
+ "compressionStats": "tamanho poupado",
+ "compressionEstimatedTokensSaved": "tokens estimados poupados",
+ "compressionPreview": "Pré-visualização em direto",
+ "compressionPreviewPlaceholder": "Cole o JSON do pedido ou texto simples",
+ "compressionRunPreview": "Executar pré-visualização"
},
"models": {
"title": "Modelos",
diff --git a/client/src/i18n/locales/ro.json b/client/src/i18n/locales/ro.json
index 6661bf6c..3f89afaa 100644
--- a/client/src/i18n/locales/ro.json
+++ b/client/src/i18n/locales/ro.json
@@ -76,7 +76,22 @@
"themeLight": "Luminos",
"themeDark": "Întunecat",
"searchLanguage": "Căutați limbi…",
- "noLanguages": "Nicio limbă găsită"
+ "noLanguages": "Nicio limbă găsită",
+ "compressionTitle": "Comprimarea prompturilor",
+ "compressionDescription": "Reduce dimensiunea cererilor înainte de rutare, păstrând codul, erorile, căile, numerele și definițiile instrumentelor.",
+ "compressionOff": "Dezactivată",
+ "compressionLossless": "Fără pierderi",
+ "compressionStandard": "Standard",
+ "compressionAggressive": "Agresivă",
+ "compressionEngines": "Motoare",
+ "compressionAutoTrigger": "Declanșare automată peste tokenurile estimate",
+ "compressionPrefixFreeze": "Îngheață prefixele de prompt recurente",
+ "compressionTrustProjectFilters": "Ai încredere în fișierele de filtru ale proiectului",
+ "compressionStats": "dimensiune economisită",
+ "compressionEstimatedTokensSaved": "tokenuri estimate economisite",
+ "compressionPreview": "Previzualizare live",
+ "compressionPreviewPlaceholder": "Lipește JSON-ul cererii sau text simplu",
+ "compressionRunPreview": "Rulează previzualizarea"
},
"models": {
"title": "Modele",
diff --git a/client/src/i18n/locales/ru.json b/client/src/i18n/locales/ru.json
index 7e51d010..447cd369 100644
--- a/client/src/i18n/locales/ru.json
+++ b/client/src/i18n/locales/ru.json
@@ -76,7 +76,22 @@
"themeLight": "Светлая",
"themeDark": "Тёмная",
"searchLanguage": "Поиск языков…",
- "noLanguages": "Языки не найдены"
+ "noLanguages": "Языки не найдены",
+ "compressionTitle": "Сжатие промптов",
+ "compressionDescription": "Уменьшает размер запросов перед маршрутизацией, сохраняя код, ошибки, пути, числа и определения инструментов.",
+ "compressionOff": "Выключено",
+ "compressionLossless": "Без потерь",
+ "compressionStandard": "Стандартное",
+ "compressionAggressive": "Агрессивное",
+ "compressionEngines": "Движки",
+ "compressionAutoTrigger": "Автозапуск при превышении оценочного числа токенов",
+ "compressionPrefixFreeze": "Замораживать повторяющиеся префиксы промптов",
+ "compressionTrustProjectFilters": "Доверять файлам фильтров проекта",
+ "compressionStats": "экономия размера",
+ "compressionEstimatedTokensSaved": "оценочная экономия токенов",
+ "compressionPreview": "Живой предпросмотр",
+ "compressionPreviewPlaceholder": "Вставьте JSON запроса или обычный текст",
+ "compressionRunPreview": "Запустить предпросмотр"
},
"models": {
"title": "Модели",
diff --git a/client/src/i18n/locales/si.json b/client/src/i18n/locales/si.json
index b8eab75f..229cb05c 100644
--- a/client/src/i18n/locales/si.json
+++ b/client/src/i18n/locales/si.json
@@ -76,7 +76,22 @@
"themeLight": "ලා",
"themeDark": "අඳුරු",
"searchLanguage": "භාෂා සොයන්න...",
- "noLanguages": "භාෂා හමු නොවීය"
+ "noLanguages": "භාෂා හමු නොවීය",
+ "compressionTitle": "ප්‍රොම්ප්ට් සම්පීඩනය",
+ "compressionDescription": "කේතය, දෝෂ, මාර්ග, අංක සහ මෙවලම් නිර්වචන ආරක්ෂා කරමින් රවුටින් වලට පෙර ඉල්ලීමේ ප්‍රමාණය අඩු කරන්න.",
+ "compressionOff": "අක්‍රියයි",
+ "compressionLossless": "හානි රහිත",
+ "compressionStandard": "සම්මත",
+ "compressionAggressive": "ප්‍රබල",
+ "compressionEngines": "එන්ජින්",
+ "compressionAutoTrigger": "ඇස්තමේන්තුගත ටෝකන ඉක්මවූ විට ස්වයංක්‍රීයව ක්‍රියාත්මක වේ",
+ "compressionPrefixFreeze": "නැවත නැවත එන ප්‍රොම්ප්ට් උපසර්ග ස්ථිර කරන්න",
+ "compressionTrustProjectFilters": "ව්‍යාපෘති පෙරහන් ගොනු විශ්වාස කරන්න",
+ "compressionStats": "ඉතිරි වූ ප්‍රමාණය",
+ "compressionEstimatedTokensSaved": "ඇස්තමේන්තුගත ඉතිරි වූ ටෝකන",
+ "compressionPreview": "සජීවී පෙරදසුන",
+ "compressionPreviewPlaceholder": "ඉල්ලීමේ JSON හෝ සරල පෙළ අලවන්න",
+ "compressionRunPreview": "පෙරදසුන ධාවනය කරන්න"
},
"models": {
"title": "ආකෘති",
diff --git a/client/src/i18n/locales/sk.json b/client/src/i18n/locales/sk.json
index 0498d587..93d6cc22 100644
--- a/client/src/i18n/locales/sk.json
+++ b/client/src/i18n/locales/sk.json
@@ -76,7 +76,22 @@
"themeLight": "Svetlý",
"themeDark": "Tmavý",
"searchLanguage": "Hľadať jazyky…",
- "noLanguages": "Nenašli sa žiadne jazyky"
+ "noLanguages": "Nenašli sa žiadne jazyky",
+ "compressionTitle": "Kompresia promptov",
+ "compressionDescription": "Zmenšuje veľkosť požiadaviek pred smerovaním, pričom zachováva kód, chyby, cesty, čísla a definície nástrojov.",
+ "compressionOff": "Vypnutá",
+ "compressionLossless": "Bezstratová",
+ "compressionStandard": "Štandardná",
+ "compressionAggressive": "Agresívna",
+ "compressionEngines": "Enginy",
+ "compressionAutoTrigger": "Automatické spustenie nad odhadovaným počtom tokenov",
+ "compressionPrefixFreeze": "Zmraziť opakujúce sa prefixy promptov",
+ "compressionTrustProjectFilters": "Dôverovať súborom filtrov projektu",
+ "compressionStats": "ušetrená veľkosť",
+ "compressionEstimatedTokensSaved": "odhadované ušetrené tokeny",
+ "compressionPreview": "Živý náhľad",
+ "compressionPreviewPlaceholder": "Vložte JSON požiadavky alebo obyčajný text",
+ "compressionRunPreview": "Spustiť náhľad"
},
"models": {
"title": "Modely",
diff --git a/client/src/i18n/locales/sr.json b/client/src/i18n/locales/sr.json
index 06ede923..e6ef96e4 100644
--- a/client/src/i18n/locales/sr.json
+++ b/client/src/i18n/locales/sr.json
@@ -76,7 +76,22 @@
"themeLight": "Светла",
"themeDark": "Тамна",
"searchLanguage": "Претражи језике…",
- "noLanguages": "Ниједан језик није пронађен"
+ "noLanguages": "Ниједан језик није пронађен",
+ "compressionTitle": "Компресија промптова",
+ "compressionDescription": "Смањује величину захтева пре рутирања, уз очување кода, грешака, путања, бројева и дефиниција алата.",
+ "compressionOff": "Искључено",
+ "compressionLossless": "Без губитака",
+ "compressionStandard": "Стандардно",
+ "compressionAggressive": "Агресивно",
+ "compressionEngines": "Механизми",
+ "compressionAutoTrigger": "Аутоматско покретање изнад процењених токена",
+ "compressionPrefixFreeze": "Замрзни понављајуће префиксе промптова",
+ "compressionTrustProjectFilters": "Веруј датотекама филтера пројекта",
+ "compressionStats": "уштеђена величина",
+ "compressionEstimatedTokensSaved": "процењени уштеђени токени",
+ "compressionPreview": "Преглед уживо",
+ "compressionPreviewPlaceholder": "Налепи JSON захтева или обичан текст",
+ "compressionRunPreview": "Покрени преглед"
},
"models": {
"title": "Модели",
diff --git a/client/src/i18n/locales/sv.json b/client/src/i18n/locales/sv.json
index 090386ca..24886127 100644
--- a/client/src/i18n/locales/sv.json
+++ b/client/src/i18n/locales/sv.json
@@ -76,7 +76,22 @@
"themeLight": "Ljust",
"themeDark": "Mörkt",
"searchLanguage": "Sök språk…",
- "noLanguages": "Inga språk hittade"
+ "noLanguages": "Inga språk hittade",
+ "compressionTitle": "Promptkomprimering",
+ "compressionDescription": "Minska förfrågningsstorleken före routing samtidigt som kod, fel, sökvägar, siffror och verktygsdefinitioner bevaras.",
+ "compressionOff": "Av",
+ "compressionLossless": "Förlustfri",
+ "compressionStandard": "Standard",
+ "compressionAggressive": "Aggressiv",
+ "compressionEngines": "Motorer",
+ "compressionAutoTrigger": "Aktivera automatiskt över uppskattade tokens",
+ "compressionPrefixFreeze": "Frys återkommande promptprefix",
+ "compressionTrustProjectFilters": "Lita på projektets filterfiler",
+ "compressionStats": "storlek sparad",
+ "compressionEstimatedTokensSaved": "uppskattade tokens sparade",
+ "compressionPreview": "Live-förhandsvisning",
+ "compressionPreviewPlaceholder": "Klistra in förfrågnings-JSON eller vanlig text",
+ "compressionRunPreview": "Kör förhandsvisning"
},
"models": {
"title": "Modeller",
diff --git a/client/src/i18n/locales/sw.json b/client/src/i18n/locales/sw.json
index 029b459b..909d8041 100644
--- a/client/src/i18n/locales/sw.json
+++ b/client/src/i18n/locales/sw.json
@@ -76,7 +76,22 @@
"themeLight": "Angavu",
"themeDark": "Giza",
"searchLanguage": "Tafuta lugha...",
- "noLanguages": "Hakuna lugha zilizopatikana"
+ "noLanguages": "Hakuna lugha zilizopatikana",
+ "compressionTitle": "Ubanaji wa agizo",
+ "compressionDescription": "Punguza ukubwa wa ombi kabla ya uelekezaji huku ukihifadhi msimbo, hitilafu, njia, nambari, na ufafanuzi wa zana.",
+ "compressionOff": "Imezimwa",
+ "compressionLossless": "Bila hasara",
+ "compressionStandard": "Kawaida",
+ "compressionAggressive": "Kali",
+ "compressionEngines": "Injini",
+ "compressionAutoTrigger": "Anzisha kiotomatiki juu ya tokeni zilizokadiriwa",
+ "compressionPrefixFreeze": "Gandisha viambishi vya maagizo vinavyojirudia",
+ "compressionTrustProjectFilters": "Amini faili za kichujio za mradi",
+ "compressionStats": "ukubwa uliookolewa",
+ "compressionEstimatedTokensSaved": "tokeni zilizokadiriwa kuokolewa",
+ "compressionPreview": "Hakikisho la moja kwa moja",
+ "compressionPreviewPlaceholder": "Bandika JSON ya ombi au maandishi wazi",
+ "compressionRunPreview": "Endesha hakikisho"
},
"models": {
"title": "Mifano",
diff --git a/client/src/i18n/locales/ta.json b/client/src/i18n/locales/ta.json
index fce22c1d..8c68b46f 100644
--- a/client/src/i18n/locales/ta.json
+++ b/client/src/i18n/locales/ta.json
@@ -76,7 +76,22 @@
"themeLight": "வெளிர்",
"themeDark": "அடர்",
"searchLanguage": "மொழிகளைத் தேடு…",
- "noLanguages": "மொழிகள் எதுவும் இல்லை"
+ "noLanguages": "மொழிகள் எதுவும் இல்லை",
+ "compressionTitle": "ப்ராம்ட் சுருக்கம்",
+ "compressionDescription": "குறியீடு, பிழைகள், பாதைகள், எண்கள் மற்றும் கருவி வரையறைகளைப் பாதுகாத்தபடி ரூட்டிங்கிற்கு முன் கோரிக்கை அளவைக் குறைக்கவும்.",
+ "compressionOff": "ஆஃப்",
+ "compressionLossless": "இழப்பில்லா",
+ "compressionStandard": "நிலையான",
+ "compressionAggressive": "தீவிரம்",
+ "compressionEngines": "என்ஜின்கள்",
+ "compressionAutoTrigger": "மதிப்பிடப்பட்ட டோக்கன்களுக்கு மேல் தானாகத் தூண்டு",
+ "compressionPrefixFreeze": "மீண்டும் வரும் ப்ராம்ட் முன்னொட்டுகளை உறைய வைக்கவும்",
+ "compressionTrustProjectFilters": "திட்ட வடிப்பான் கோப்புகளை நம்பு",
+ "compressionStats": "அளவு சேமிப்பு",
+ "compressionEstimatedTokensSaved": "மதிப்பிடப்பட்ட டோக்கன்கள் சேமிப்பு",
+ "compressionPreview": "நேரடி முன்னோட்டம்",
+ "compressionPreviewPlaceholder": "கோரிக்கை JSON அல்லது சாதாரண உரையை ஒட்டவும்",
+ "compressionRunPreview": "முன்னோட்டத்தை இயக்கு"
},
"models": {
"title": "மாதிரிகள்",
diff --git a/client/src/i18n/locales/te.json b/client/src/i18n/locales/te.json
index ce76050a..cc991888 100644
--- a/client/src/i18n/locales/te.json
+++ b/client/src/i18n/locales/te.json
@@ -76,7 +76,22 @@
"themeLight": "లేత",
"themeDark": "ముదురు",
"searchLanguage": "భాషలను వెతకండి...",
- "noLanguages": "భాషలు ఏవీ కనుగొనబడలేదు"
+ "noLanguages": "భాషలు ఏవీ కనుగొనబడలేదు",
+ "compressionTitle": "ప్రాంప్ట్ కంప్రెషన్",
+ "compressionDescription": "కోడ్, ఎర్రర్లు, పాత్‌లు, సంఖ్యలు మరియు టూల్ నిర్వచనాలను భద్రపరుస్తూ రూటింగ్‌కు ముందు అభ్యర్థన పరిమాణాన్ని తగ్గించండి.",
+ "compressionOff": "ఆఫ్",
+ "compressionLossless": "నష్టరహితం",
+ "compressionStandard": "ప్రామాణికం",
+ "compressionAggressive": "దూకుడు",
+ "compressionEngines": "ఇంజిన్లు",
+ "compressionAutoTrigger": "అంచనా టోకెన్లకు మించితే ఆటో-ట్రిగ్గర్",
+ "compressionPrefixFreeze": "పునరావృత ప్రాంప్ట్ ప్రిఫిక్స్‌లను ఫ్రీజ్ చేయండి",
+ "compressionTrustProjectFilters": "ప్రాజెక్ట్ ఫిల్టర్ ఫైళ్లను విశ్వసించండి",
+ "compressionStats": "పరిమాణం ఆదా",
+ "compressionEstimatedTokensSaved": "అంచనా టోకెన్లు ఆదా",
+ "compressionPreview": "లైవ్ ప్రివ్యూ",
+ "compressionPreviewPlaceholder": "అభ్యర్థన JSON లేదా సాదా టెక్స్ట్ అతికించండి",
+ "compressionRunPreview": "ప్రివ్యూ అమలు చేయండి"
},
"models": {
"title": "మోడల్స్",
diff --git a/client/src/i18n/locales/th.json b/client/src/i18n/locales/th.json
index 4d42dffe..b98a0da2 100644
--- a/client/src/i18n/locales/th.json
+++ b/client/src/i18n/locales/th.json
@@ -76,7 +76,22 @@
"themeLight": "สว่าง",
"themeDark": "มืด",
"searchLanguage": "ค้นหาภาษา...",
- "noLanguages": "ไม่พบภาษา"
+ "noLanguages": "ไม่พบภาษา",
+ "compressionTitle": "การบีบอัดพร้อมท์",
+ "compressionDescription": "ลดขนาดคำขอก่อนการกำหนดเส้นทาง โดยยังคงรักษาโค้ด ข้อผิดพลาด พาธ ตัวเลข และคำจำกัดความของเครื่องมือ",
+ "compressionOff": "ปิด",
+ "compressionLossless": "ไม่สูญเสียข้อมูล",
+ "compressionStandard": "มาตรฐาน",
+ "compressionAggressive": "เชิงรุก",
+ "compressionEngines": "เอนจิน",
+ "compressionAutoTrigger": "ทริกเกอร์อัตโนมัติเมื่อเกินโทเค็นโดยประมาณ",
+ "compressionPrefixFreeze": "ตรึงคำนำหน้าพร้อมท์ที่เกิดซ้ำ",
+ "compressionTrustProjectFilters": "เชื่อถือไฟล์ตัวกรองของโปรเจกต์",
+ "compressionStats": "ขนาดที่ประหยัดได้",
+ "compressionEstimatedTokensSaved": "โทเค็นที่ประหยัดได้โดยประมาณ",
+ "compressionPreview": "ตัวอย่างสด",
+ "compressionPreviewPlaceholder": "วาง JSON ของคำขอหรือข้อความธรรมดา",
+ "compressionRunPreview": "รันตัวอย่าง"
},
"models": {
"title": "โมเดล",
diff --git a/client/src/i18n/locales/tl.json b/client/src/i18n/locales/tl.json
index 96ecc69c..286ad075 100644
--- a/client/src/i18n/locales/tl.json
+++ b/client/src/i18n/locales/tl.json
@@ -76,7 +76,22 @@
"themeLight": "Maliwanag",
"themeDark": "Madilim",
"searchLanguage": "Maghanap ng mga wika...",
- "noLanguages": "Walang natagpuang wika"
+ "noLanguages": "Walang natagpuang wika",
+ "compressionTitle": "Compression ng prompt",
+ "compressionDescription": "Bawasan ang laki ng request bago ang routing habang pinapanatili ang code, mga error, path, numero, at tool definition.",
+ "compressionOff": "Naka-off",
+ "compressionLossless": "Lossless",
+ "compressionStandard": "Standard",
+ "compressionAggressive": "Agresibo",
+ "compressionEngines": "Mga engine",
+ "compressionAutoTrigger": "Awtomatikong i-trigger kapag lumagpas sa tinatayang token",
+ "compressionPrefixFreeze": "I-freeze ang paulit-ulit na prompt prefix",
+ "compressionTrustProjectFilters": "Pagkatiwalaan ang mga filter file ng proyekto",
+ "compressionStats": "laki na natipid",
+ "compressionEstimatedTokensSaved": "tinatayang token na natipid",
+ "compressionPreview": "Live preview",
+ "compressionPreviewPlaceholder": "I-paste ang request JSON o plain text",
+ "compressionRunPreview": "Patakbuhin ang preview"
},
"models": {
"title": "Mga Modelo",
diff --git a/client/src/i18n/locales/tr.json b/client/src/i18n/locales/tr.json
index 69a1446d..a265c2fa 100644
--- a/client/src/i18n/locales/tr.json
+++ b/client/src/i18n/locales/tr.json
@@ -76,7 +76,22 @@
"themeLight": "Açık",
"themeDark": "Koyu",
"searchLanguage": "Dilleri ara…",
- "noLanguages": "Dil bulunamadı"
+ "noLanguages": "Dil bulunamadı",
+ "compressionTitle": "İstem sıkıştırma",
+ "compressionDescription": "Kod, hatalar, yollar, sayılar ve araç tanımlarını koruyarak yönlendirmeden önce istek boyutunu azaltın.",
+ "compressionOff": "Kapalı",
+ "compressionLossless": "Kayıpsız",
+ "compressionStandard": "Standart",
+ "compressionAggressive": "Agresif",
+ "compressionEngines": "Motorlar",
+ "compressionAutoTrigger": "Tahmini jeton sayısının üzerinde otomatik tetikle",
+ "compressionPrefixFreeze": "Yinelenen istem öneklerini dondur",
+ "compressionTrustProjectFilters": "Proje filtre dosyalarına güven",
+ "compressionStats": "boyut tasarrufu",
+ "compressionEstimatedTokensSaved": "tahmini jeton tasarrufu",
+ "compressionPreview": "Canlı önizleme",
+ "compressionPreviewPlaceholder": "İstek JSON'u veya düz metin yapıştırın",
+ "compressionRunPreview": "Önizlemeyi çalıştır"
},
"models": {
"title": "Modeller",
diff --git a/client/src/i18n/locales/uk.json b/client/src/i18n/locales/uk.json
index 1247b8da..b818a269 100644
--- a/client/src/i18n/locales/uk.json
+++ b/client/src/i18n/locales/uk.json
@@ -76,7 +76,22 @@
"themeLight": "Світла",
"themeDark": "Темна",
"searchLanguage": "Пошук мов…",
- "noLanguages": "Мови не знайдено"
+ "noLanguages": "Мови не знайдено",
+ "compressionTitle": "Стиснення підказок",
+ "compressionDescription": "Зменшуйте розмір запиту перед маршрутизацією, зберігаючи код, помилки, шляхи, числа та визначення інструментів.",
+ "compressionOff": "Вимкнено",
+ "compressionLossless": "Без втрат",
+ "compressionStandard": "Стандартний",
+ "compressionAggressive": "Агресивний",
+ "compressionEngines": "Рушії",
+ "compressionAutoTrigger": "Автозапуск понад оцінену кількість токенів",
+ "compressionPrefixFreeze": "Заморожувати повторювані префікси підказок",
+ "compressionTrustProjectFilters": "Довіряти файлам фільтрів проєкту",
+ "compressionStats": "збережено розміру",
+ "compressionEstimatedTokensSaved": "орієнтовно збережено токенів",
+ "compressionPreview": "Попередній перегляд наживо",
+ "compressionPreviewPlaceholder": "Вставте JSON запиту або звичайний текст",
+ "compressionRunPreview": "Запустити перегляд"
},
"models": {
"title": "Моделі",
diff --git a/client/src/i18n/locales/ur.json b/client/src/i18n/locales/ur.json
index 2aa40831..77eaab0d 100644
--- a/client/src/i18n/locales/ur.json
+++ b/client/src/i18n/locales/ur.json
@@ -76,7 +76,22 @@
"themeLight": "روشن",
"themeDark": "گہرا",
"searchLanguage": "زبانیں تلاش کریں…",
- "noLanguages": "کوئی زبانیں نہیں ملی"
+ "noLanguages": "کوئی زبانیں نہیں ملی",
+ "compressionTitle": "پرامپٹ کمپریشن",
+ "compressionDescription": "کوڈ، ایررز، پاتھز، نمبرز اور ٹول ڈیفینیشنز کو محفوظ رکھتے ہوئے روٹنگ سے پہلے درخواست کا سائز کم کریں۔",
+ "compressionOff": "بند",
+ "compressionLossless": "بغیر نقصان",
+ "compressionStandard": "معیاری",
+ "compressionAggressive": "جارحانہ",
+ "compressionEngines": "انجن",
+ "compressionAutoTrigger": "تخمینی ٹوکنز سے زیادہ پر خودکار ٹرگر",
+ "compressionPrefixFreeze": "بار بار آنے والے پرامپٹ پری فکسز کو منجمد کریں",
+ "compressionTrustProjectFilters": "پروجیکٹ فلٹر فائلوں پر اعتماد کریں",
+ "compressionStats": "سائز کی بچت",
+ "compressionEstimatedTokensSaved": "تخمینی ٹوکنز کی بچت",
+ "compressionPreview": "لائیو پیش منظر",
+ "compressionPreviewPlaceholder": "درخواست کا JSON یا سادہ متن پیسٹ کریں",
+ "compressionRunPreview": "پیش منظر چلائیں"
},
"models": {
"title": "ماڈلز",
diff --git a/client/src/i18n/locales/uz.json b/client/src/i18n/locales/uz.json
index 29aa99e8..1ef745b9 100644
--- a/client/src/i18n/locales/uz.json
+++ b/client/src/i18n/locales/uz.json
@@ -76,7 +76,22 @@
"themeLight": "Yorugʻ",
"themeDark": "Qorong'i",
"searchLanguage": "Tillarni qidirish…",
- "noLanguages": "Hech qanday til topilmadi"
+ "noLanguages": "Hech qanday til topilmadi",
+ "compressionTitle": "Promptni siqish",
+ "compressionDescription": "Kod, xatolar, yo'llar, raqamlar va vosita ta'riflarini saqlagan holda marshrutlashdan oldin so'rov hajmini kamaytiring.",
+ "compressionOff": "O'chirilgan",
+ "compressionLossless": "Yo'qotishsiz",
+ "compressionStandard": "Standart",
+ "compressionAggressive": "Agressiv",
+ "compressionEngines": "Mexanizmlar",
+ "compressionAutoTrigger": "Taxminiy tokenlardan oshganda avtomatik ishga tushirish",
+ "compressionPrefixFreeze": "Takrorlanuvchi prompt prefikslarini muzlatish",
+ "compressionTrustProjectFilters": "Loyiha filtri fayllariga ishonish",
+ "compressionStats": "tejalgan hajm",
+ "compressionEstimatedTokensSaved": "taxminiy tejalgan tokenlar",
+ "compressionPreview": "Jonli oldindan ko'rish",
+ "compressionPreviewPlaceholder": "So'rov JSON yoki oddiy matnni joylashtiring",
+ "compressionRunPreview": "Oldindan ko'rishni ishga tushirish"
},
"models": {
"title": "Modellar",
diff --git a/client/src/i18n/locales/vi.json b/client/src/i18n/locales/vi.json
index 4f5ef9a8..b9dd82c6 100644
--- a/client/src/i18n/locales/vi.json
+++ b/client/src/i18n/locales/vi.json
@@ -76,7 +76,22 @@
"themeLight": "Sáng",
"themeDark": "Tối",
"searchLanguage": "Tìm kiếm ngôn ngữ…",
- "noLanguages": "Không tìm thấy ngôn ngữ nào"
+ "noLanguages": "Không tìm thấy ngôn ngữ nào",
+ "compressionTitle": "Nén lời nhắc",
+ "compressionDescription": "Giảm kích thước yêu cầu trước khi định tuyến trong khi vẫn giữ nguyên mã, lỗi, đường dẫn, số và định nghĩa công cụ.",
+ "compressionOff": "Tắt",
+ "compressionLossless": "Không mất dữ liệu",
+ "compressionStandard": "Tiêu chuẩn",
+ "compressionAggressive": "Mạnh",
+ "compressionEngines": "Bộ máy nén",
+ "compressionAutoTrigger": "Tự động kích hoạt khi vượt số mã thông báo ước tính",
+ "compressionPrefixFreeze": "Cố định tiền tố lời nhắc lặp lại",
+ "compressionTrustProjectFilters": "Tin cậy tệp bộ lọc của dự án",
+ "compressionStats": "kích thước tiết kiệm",
+ "compressionEstimatedTokensSaved": "mã thông báo ước tính đã tiết kiệm",
+ "compressionPreview": "Xem trước trực tiếp",
+ "compressionPreviewPlaceholder": "Dán JSON yêu cầu hoặc văn bản thuần",
+ "compressionRunPreview": "Chạy xem trước"
},
"models": {
"title": "Người mẫu",
diff --git a/client/src/i18n/locales/yo.json b/client/src/i18n/locales/yo.json
index 2ab10f9c..8756c4f7 100644
--- a/client/src/i18n/locales/yo.json
+++ b/client/src/i18n/locales/yo.json
@@ -76,7 +76,22 @@
"themeLight": "Imọlẹ",
"themeDark": "Dudu",
"searchLanguage": "Wa awọn ede…",
- "noLanguages": "Ko si awọn ede ti a rii"
+ "noLanguages": "Ko si awọn ede ti a rii",
+ "compressionTitle": "Ifunpọ ilana",
+ "compressionDescription": "Din iwọn ibeere ku ṣaaju ipa ọna lakoko ti o n tọju koodu, awọn aṣiṣe, awọn ipa ọna, awọn nọmba, ati awọn itumọ irinṣẹ.",
+ "compressionOff": "Paa",
+ "compressionLossless": "Laisi pipadanu",
+ "compressionStandard": "Boṣewa",
+ "compressionAggressive": "Líle",
+ "compressionEngines": "Awọn ẹrọ",
+ "compressionAutoTrigger": "Bẹrẹ laifọwọyi loke awọn àmi ti a fojú díwọ̀n",
+ "compressionPrefixFreeze": "Di awọn ìbẹ̀rẹ̀ ilana ti o tun nwaye",
+ "compressionTrustProjectFilters": "Gbẹkẹle awọn faili àlẹmọ iṣẹ akanṣe",
+ "compressionStats": "iwọn ti a fipamọ",
+ "compressionEstimatedTokensSaved": "awọn àmi ti a fojú díwọ̀n ti a fipamọ",
+ "compressionPreview": "Awotẹlẹ laaye",
+ "compressionPreviewPlaceholder": "Lẹ JSON ibeere tabi ọrọ lasan",
+ "compressionRunPreview": "Ṣiṣe awotẹlẹ"
},
"models": {
"title": "Awọn awoṣe",
diff --git a/client/src/i18n/locales/zh-CN.json b/client/src/i18n/locales/zh-CN.json
index 8d30d579..8a9b252d 100644
--- a/client/src/i18n/locales/zh-CN.json
+++ b/client/src/i18n/locales/zh-CN.json
@@ -76,7 +76,22 @@
"themeLight": "浅色",
"themeDark": "深色",
"searchLanguage": "搜索语言...",
- "noLanguages": "未找到语言"
+ "noLanguages": "未找到语言",
+ "compressionTitle": "提示词压缩",
+ "compressionDescription": "在路由前减小请求体积,同时保留代码、错误信息、路径、数字和工具定义。",
+ "compressionOff": "关闭",
+ "compressionLossless": "无损",
+ "compressionStandard": "标准",
+ "compressionAggressive": "激进",
+ "compressionEngines": "引擎",
+ "compressionAutoTrigger": "超过预估令牌数时自动触发",
+ "compressionPrefixFreeze": "冻结重复出现的提示词前缀",
+ "compressionTrustProjectFilters": "信任项目过滤文件",
+ "compressionStats": "节省的体积",
+ "compressionEstimatedTokensSaved": "预估节省的令牌数",
+ "compressionPreview": "实时预览",
+ "compressionPreviewPlaceholder": "粘贴请求 JSON 或纯文本",
+ "compressionRunPreview": "运行预览"
},
"models": {
"title": "模型",
diff --git a/client/src/i18n/locales/zh-TW.json b/client/src/i18n/locales/zh-TW.json
index c46c9383..b14013b5 100644
--- a/client/src/i18n/locales/zh-TW.json
+++ b/client/src/i18n/locales/zh-TW.json
@@ -76,7 +76,22 @@
"themeLight": "淺色",
"themeDark": "深色",
"searchLanguage": "搜尋語言…",
- "noLanguages": "找不到語言"
+ "noLanguages": "找不到語言",
+ "compressionTitle": "提示壓縮",
+ "compressionDescription": "在路由前縮減請求大小,同時保留程式碼、錯誤、路徑、數字與工具定義。",
+ "compressionOff": "關閉",
+ "compressionLossless": "無損",
+ "compressionStandard": "標準",
+ "compressionAggressive": "積極",
+ "compressionEngines": "引擎",
+ "compressionAutoTrigger": "超過預估代幣數時自動觸發",
+ "compressionPrefixFreeze": "凍結重複出現的提示前綴",
+ "compressionTrustProjectFilters": "信任專案篩選檔案",
+ "compressionStats": "節省的大小",
+ "compressionEstimatedTokensSaved": "預估節省的代幣數",
+ "compressionPreview": "即時預覽",
+ "compressionPreviewPlaceholder": "貼上請求 JSON 或純文字",
+ "compressionRunPreview": "執行預覽"
},
"models": {
"title": "型號",
diff --git a/docs/README.md b/docs/README.md
index 9a970923..5a714f8e 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -7,6 +7,7 @@ The root [README](../README.md) is the product overview; the detailed guides liv
- **[Install & deploy](install.md)** — quick start, Docker Compose, local development, declarative startup config, the Docker image, backups, the desktop app, and where your data lives.
- **[API reference](api.md)** — chat completions, `auto:*` routing strategies, streaming, tool calling, vision, Gemini Google Search grounding, embeddings, response headers, and the Anthropic Messages surface.
- **[Clients & coding agents](clients.md)** — OpenAI-compatible clients, recipes for Claude Code / Codex CLI / Cline / Continue / Aider / opencode / Cursor, the MCP server, editor autocomplete, and Context Handoff.
+- **[Prompt compression](compression.md)** — request-side modes, safeguards, per-request controls, custom tool-output filters, statistics, and preview APIs.
- **[Architecture & internals](architecture.md)** — how the router works, routing and operational details, what's not supported, honest limitations, and the provider Terms-of-Service review.
## More
diff --git a/docs/api.md b/docs/api.md
index 9ad3df93..ebab5921 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -185,6 +185,8 @@ Every response carries an `X-Routed-Via: <platform>/<model>` header so you can s
The opt-in response cache can be toggled per request with `X-FreeLLM-Cache: on|off` — an exact-match in-memory LRU for identical non-streaming requests (canonical SHA-256 keys over the full request, TTL and temperature gates, saved-token stats on the dashboard). Off by default; cache hits consume zero provider quota.
+When [prompt compression](compression.md) is enabled, `X-FreeLLM-Compress: off|on|lossless|standard|aggressive` can disable or lower the configured mode for one request. It cannot raise the operator's configured mode. The response reports the effective mode and estimated savings, for example `X-FreeLLM-Compress: standard; saved~=1840`.
+
## Embeddings
`/v1/embeddings` is OpenAI-compatible, with one deliberate difference from chat routing: **failover never crosses models.** Vectors from different models live in incompatible spaces — silently switching models would corrupt any vector store built on top of the proxy. So embeddings route by **family** (one model identity + dimension), and failover only walks the providers serving that same family.
diff --git a/docs/compression.md b/docs/compression.md
new file mode 100644
index 00000000..ff942a8e
--- /dev/null
+++ b/docs/compression.md
@@ -0,0 +1,86 @@
+# Prompt compression
+
+[← Back to README](../README.md) · [Documentation index](README.md) · [API reference](api.md)
+
+Long coding-agent sessions repeatedly send system prompts, file reads, command output, and tool schemas. FreeLLMAPI can shrink that request context before cache lookup, token budgeting, and routing, so the router sees the reduced estimate and more small-context models remain eligible. Provider responses are never rewritten.
+
+The same pipeline runs on Chat Completions, Responses, Anthropic Messages, and Anthropic token counting. Compression is **off by default**.
+
+## Enable it
+
+Choose a mode under dashboard **Settings → Prompt compression**, or bootstrap the mode with:
+
+```env
+FREELLMAPI_COMPRESSION=lossless
+```
+
+Once settings have been saved in the dashboard, the stored setting takes precedence over the environment value.
+
+| Mode | What runs |
+| --- | --- |
+| `off` | No request rewriting. This is a master switch; a request header cannot enable it. |
+| `lossless` | Repeated-block deduplication, whitespace hygiene, and reversible homogeneous-JSON table encoding. |
+| `standard` | Lossless engines plus command-aware tool-output filtering and stale file-read supersession. |
+| `aggressive` | Standard engines plus older-turn condensation, lexical relevance filtering, and an optional hard token target. |
+
+The dashboard also controls each engine independently, the estimated-token auto-trigger, target size, stable-prefix freezing, and whether repository-local filters are trusted.
+
+## Per-request control
+
+Send one of these values with `X-FreeLLM-Compress`:
+
+```text
+off | on | lossless | standard | aggressive
+```
+
+The header may turn compression off or lower the operator's configured mode, but it cannot raise it. `on` uses the configured mode. Responses report the effective mode and estimated savings:
+
+```text
+X-FreeLLM-Compress: standard; saved~=1840
+```
+
+Savings use the same estimated `chars / 4` accounting as routing, so the header deliberately uses `~=`.
+
+## Adaptive compression
+
+When `autoTriggerEstTokens` is configured and an uncompressed request crosses that estimate, the pipeline may use aggressive engines even if the normal configured mode is lower. It stops once `targetTokens` is reached. An explicit request header still wins when it lowers the permitted mode.
+
+## Fidelity and cache safety
+
+The pipeline is fail-open. Every engine runs independently, and its output is discarded if it grows the request, throws an exception, or fails a fidelity gate. The gate requires:
+
+- all distinct numeric literals and diff hunks to survive;
+- every explicit constraint, security instruction, and error line to survive;
+- at least 90% of JSON keys to survive;
+- at least 95% of other protected spans to survive;
+- tool-call and tool-result envelopes to remain valid.
+
+Protected spans include code fences, URLs, file paths, stack traces, explicit constraints, error lines, key/value pairs, and structured tool metadata.
+
+Repeated stable system prefixes are frozen after their third appearance. Anthropic `cache_control` prefixes are capped at lossless rewriting. Compression configuration is included in the response-cache fingerprint, so differently compressed requests cannot share a stale cache entry.
+
+## Tool-output filters
+
+Built-in filters understand common output from Git, package managers, test runners, builds, Docker, search tools, JSON, and stack traces. They can remove ANSI escape sequences, collapse repetitive sections, keep matched lines, and preserve useful head/tail context under character and line limits. Error output receives conservative treatment.
+
+Additional JSON filter definitions can be loaded from:
+
+- `~/.freellmapi/filters/*.json` for user-owned filters;
+- `.freellmapi/filters.json` in the project, only when **Trust project filter files** is enabled.
+
+Project filters are disabled by default because repositories may be untrusted.
+
+## Design boundaries
+
+The built-in path is deterministic, synchronous, dependency-light, and provider-neutral. It does not call another model, use a learned token-pruning model, rewrite images, or emit opaque provider-specific compaction blocks. Those approaches can be useful when a compatible upstream provider or agent runtime owns the context state, but silently translating them across providers would weaken the fail-open and fidelity guarantees of this router.
+
+## Settings, preview, and statistics APIs
+
+Authenticated admin clients can use:
+
+- `GET /api/settings/compression` — read the effective configuration.
+- `PUT /api/settings/compression` — update modes, engines, limits, and trust controls.
+- `POST /api/compression/preview` — inspect compressed output and per-engine results without affecting live statistics.
+- `GET /api/compression/stats` — read rolling aggregate and per-engine savings and fidelity-gate discards.
+
+MCP clients can read the same live aggregates with the `compression_stats` tool. Statistics contain counts, timings, and estimated savings only; request bodies are never retained.
diff --git a/server/src/__tests__/fixtures/compression-golden.json b/server/src/__tests__/fixtures/compression-golden.json
new file mode 100644
index 00000000..ab0ced1d
--- /dev/null
+++ b/server/src/__tests__/fixtures/compression-golden.json
@@ -0,0 +1,83 @@
+[
+ {
+ "name": "claude-code-build",
+ "messages": [
+ {
+ "role": "system",
+ "content": "You are Claude Code. Work carefully. \n\n\n\nPreserve the user's repository state."
+ },
+ {
+ "role": "user",
+ "content": "Fix the build and do not stop until the tests pass."
+ },
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {
+ "id": "toolu_build",
+ "type": "function",
+ "function": {
+ "name": "run_command",
+ "arguments": "{\"command\":\"npm run build\"}"
+ }
+ }
+ ]
+ },
+ {
+ "role": "tool",
+ "tool_call_id": "toolu_build",
+ "content": "building package alpha\nbuilding package alpha\nbuilding package alpha\nbuilding package alpha\nbuilding package alpha\nbuilding package alpha\nbuilding package alpha\nbuilding package alpha\nbuilding package alpha\nbuilding package alpha\nbuilding package alpha\nbuilding package alpha\nbuilding package alpha\nbuilding package alpha\nbuilding package alpha\nbuilding package alpha\nbuilding package alpha\nbuilding package alpha\nbuilding package alpha\nbuilding package alpha\nError: compilation failed in /repo/src/index.ts at 42\n at compile (/repo/src/build.ts:42:7)\n@@ -10,2 +10,3 @@\nexit_code=1"
+ }
+ ]
+ },
+ {
+ "name": "codex-json-tool-result",
+ "messages": [
+ {
+ "role": "system",
+ "content": "You are a coding agent."
+ },
+ {
+ "role": "assistant",
+ "content": null,
+ "tool_calls": [
+ {
+ "id": "call_rows",
+ "type": "function",
+ "function": {
+ "name": "query_database",
+ "arguments": "{\"table\":\"models\"}"
+ }
+ }
+ ]
+ },
+ {
+ "role": "tool",
+ "tool_call_id": "call_rows",
+ "content": "[\n { \"id\": 1, \"name\": \"alpha\", \"enabled\": true },\n { \"id\": 2, \"name\": \"beta\", \"enabled\": true },\n { \"id\": 3, \"name\": \"gamma\", \"enabled\": false },\n { \"id\": 4, \"name\": \"delta\", \"enabled\": true },\n { \"id\": 5, \"name\": \"epsilon\", \"enabled\": true },\n { \"id\": 6, \"name\": \"zeta\", \"enabled\": false },\n { \"id\": 7, \"name\": \"eta\", \"enabled\": true },\n { \"id\": 8, \"name\": \"theta\", \"enabled\": true },\n { \"id\": 9, \"name\": \"iota\", \"enabled\": true },\n { \"id\": 10, \"name\": \"kappa\", \"enabled\": false }\n]"
+ }
+ ]
+ },
+ {
+ "name": "aider-repeated-context",
+ "messages": [
+ {
+ "role": "system",
+ "content": "Act as an expert pair programmer."
+ },
+ {
+ "role": "user",
+ "content": "The application must remain responsive during catalog refreshes.\nThe catalog refresh runs in the background and publishes an immutable snapshot.\nReaders should continue using the previous snapshot until the new one is ready.\nThis paragraph is deliberately repeated by the client as repository context."
+ },
+ {
+ "role": "assistant",
+ "content": "I will inspect the refresh path."
+ },
+ {
+ "role": "user",
+ "content": "The application must remain responsive during catalog refreshes.\nThe catalog refresh runs in the background and publishes an immutable snapshot.\nReaders should continue using the previous snapshot until the new one is ready.\nThis paragraph is deliberately repeated by the client as repository context.\n\nNow implement the fix."
+ }
+ ]
+ }
+]
diff --git a/server/src/__tests__/routes/compression.test.ts b/server/src/__tests__/routes/compression.test.ts
new file mode 100644
index 00000000..a08928f2
--- /dev/null
+++ b/server/src/__tests__/routes/compression.test.ts
@@ -0,0 +1,166 @@
+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { Express } from 'express';
+import { createApp } from '../../app.js';
+import { getDb, getUnifiedApiKey, initDb, setSetting } from '../../db/index.js';
+import { mintDashboardToken } from '../helpers/auth.js';
+import { clearCompressionStats } from '../../services/compression/stats.js';
+
+let app: Express;
+let dashboardToken = '';
+
+async function request(
+ method: string,
+ path: string,
+ body?: unknown,
+ headers: Record<string, string> = {},
+) {
+ const server = await new Promise<ReturnType<Express['listen']>>((resolve, reject) => {
+ const listener = app.listen(0, '127.0.0.1', () => resolve(listener));
+ listener.once('error', reject);
+ });
+ const address = server.address() as { port: number };
+ const response = await fetch(`http://127.0.0.1:${address.port}${path}`, {
+ method,
+ headers: {
+ ...(body === undefined ? {} : { 'Content-Type': 'application/json' }),
+ ...(path.startsWith('/api/') ? { Authorization: `Bearer ${dashboardToken}` } : {}),
+ ...headers,
+ },
+ body: body === undefined ? undefined : JSON.stringify(body),
+ });
+ const raw = await response.text();
+ server.close();
+ return {
+ status: response.status,
+ body: raw ? JSON.parse(raw) : null,
+ headers: response.headers,
+ };
+}
+
+describe('compression routes and chat integration', () => {
+ beforeAll(() => {
+ process.env.ENCRYPTION_KEY = '0'.repeat(64);
+ initDb(':memory:');
+ dashboardToken = mintDashboardToken();
+ app = createApp();
+ });
+
+ beforeEach(() => {
+ clearCompressionStats();
+ getDb().prepare('DELETE FROM api_keys').run();
+ setSetting('compression', JSON.stringify({
+ mode: 'lossless',
+ engines: {
+ dedup: { enabled: true, minBlockChars: 80, minBlockLines: 3 },
+ lite: { enabled: true },
+ jsoncompact: { enabled: true, minRows: 8 },
+ },
+ trustProjectFilters: false,
+ prefixFreeze: false,
+ }));
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('reads and updates compression settings', async () => {
+ const current = await request('GET', '/api/settings/compression');
+ expect(current.status).toBe(200);
+ expect(current.body.mode).toBe('lossless');
+ const updated = await request('PUT', '/api/settings/compression', {
+ mode: 'standard',
+ autoTriggerEstTokens: 32_000,
+ engines: { toolfilter: { enabled: true, intensity: 'aggressive' } },
+ });
+ expect(updated.status).toBe(200);
+ expect(updated.body.mode).toBe('standard');
+ expect(updated.body.autoTriggerEstTokens).toBe(32_000);
+ expect(updated.body.engines.toolfilter.intensity).toBe('aggressive');
+ });
+
+ it('previews a request without adding it to live aggregate stats', async () => {
+ const preview = await request('POST', '/api/compression/preview', {
+ mode: 'lossless',
+ messages: [{ role: 'user', content: 'hello \n\n\n\nworld' }],
+ });
+ expect(preview.status).toBe(200);
+ expect(preview.body.compressed[0].content).toBe('hello\n\nworld');
+ expect(preview.body.stats.estSavedTokens).toBeGreaterThan(0);
+ const stats = await request('GET', '/api/compression/stats');
+ expect(stats.body.requests).toBe(0);
+ });
+
+ it('compresses all three chat surfaces before provider dispatch and reports the response header', async () => {
+ const added = await request('POST', '/api/keys', {
+ platform: 'groq',
+ key: 'gsk_compression_test',
+ label: 'compression',
+ });
+ expect(added.status).toBe(201);
+ const originalFetch = global.fetch;
+ const forwarded: any[] = [];
+ vi.spyOn(global, 'fetch').mockImplementation(async (url, init) => {
+ if (String(url).includes('api.groq.com/openai/v1/chat/completions')) {
+ forwarded.push(JSON.parse(String((init as RequestInit).body)));
+ return {
+ ok: true,
+ json: async () => ({
+ id: 'compression-test',
+ object: 'chat.completion',
+ created: 1,
+ model: 'openai/gpt-oss-120b',
+ choices: [{ index: 0, message: { role: 'assistant', content: 'ok' }, finish_reason: 'stop' }],
+ usage: { prompt_tokens: 3, completion_tokens: 1, total_tokens: 4 },
+ }),
+ } as Response;
+ }
+ return originalFetch(url, init);
+ });
+ const response = await request('POST', '/v1/chat/completions', {
+ model: 'auto',
+ messages: [{ role: 'user', content: 'hello \n\n\n\nworld' }],
+ }, { Authorization: `Bearer ${getUnifiedApiKey()}` });
+ expect(response.status).toBe(200);
+ expect(forwarded[0].messages[0].content).toBe('hello\n\nworld');
+ expect(response.headers.get('x-freellm-compress')).toMatch(/^lossless; saved~=\d+$/);
+
+ const anthropic = await request('POST', '/v1/messages', {
+ model: 'auto',
+ max_tokens: 32,
+ messages: [{ role: 'user', content: 'anthropic \n\n\n\nmessage' }],
+ }, {
+ 'x-api-key': getUnifiedApiKey(),
+ 'anthropic-version': '2023-06-01',
+ });
+ expect(anthropic.status).toBe(200);
+ expect(forwarded[1].messages[0].content).toBe('anthropic\n\nmessage');
+ expect(anthropic.headers.get('x-freellm-compress')).toMatch(/^lossless; saved~=\d+$/);
+
+ const responses = await request('POST', '/v1/responses', {
+ model: 'auto',
+ input: 'responses \n\n\n\nmessage',
+ max_output_tokens: 32,
+ }, { Authorization: `Bearer ${getUnifiedApiKey()}` });
+ expect(responses.status).toBe(200);
+ expect(forwarded[2].messages[0].content).toBe('responses\n\nmessage');
+ expect(responses.headers.get('x-freellm-compress')).toMatch(/^lossless; saved~=\d+$/);
+
+ const stats = await request('GET', '/api/compression/stats');
+ expect(stats.body.requests).toBe(3);
+ });
+
+ it('honors per-request lowering and the operator off master switch', async () => {
+ setSetting('compression', JSON.stringify({
+ mode: 'off',
+ engines: {},
+ trustProjectFilters: false,
+ prefixFreeze: false,
+ }));
+ // Authentication/model setup is intentionally omitted: compression runs
+ // after validation but the master-switch resolution is directly visible
+ // through preview only when explicitly forced, so inspect settings here.
+ const current = await request('GET', '/api/settings/compression');
+ expect(current.body.mode).toBe('off');
+ });
+});
diff --git a/server/src/__tests__/routes/mcp.test.ts b/server/src/__tests__/routes/mcp.test.ts
index a110d5ef..068a60ae 100644
--- a/server/src/__tests__/routes/mcp.test.ts
+++ b/server/src/__tests__/routes/mcp.test.ts
@@ -124,10 +124,10 @@ describe('MCP server (/mcp, stateless Streamable HTTP)', () => {
expect(data.top_models.some((m: any) => m.model_id === 'test-model')).toBe(true);
});
- it('lists the six gateway tools with schemas', async () => {
+ it('lists the seven gateway tools with schemas', async () => {
const { body } = await rpc({ jsonrpc: '2.0', id: 2, method: 'tools/list' });
const names = body.result.tools.map((t: any) => t.name).sort();
- expect(names).toEqual(['cache_stats', 'list_models', 'provider_health', 'routing_info', 'set_routing_strategy', 'usage_summary']);
+ expect(names).toEqual(['cache_stats', 'compression_stats', 'list_models', 'provider_health', 'routing_info', 'set_routing_strategy', 'usage_summary']);
for (const tool of body.result.tools) {
expect(tool.description.length).toBeGreaterThan(20);
expect(tool.inputSchema.type).toBe('object');
@@ -168,8 +168,8 @@ describe('MCP server (/mcp, stateless Streamable HTTP)', () => {
expect(body.result.content[0].text).toContain('strategy must be one of');
});
- it('usage_summary and provider_health and cache_stats answer on an empty install', async () => {
- for (const name of ['usage_summary', 'provider_health', 'cache_stats']) {
+ it('usage, health, cache, and compression stats answer on an empty install', async () => {
+ for (const name of ['usage_summary', 'provider_health', 'cache_stats', 'compression_stats']) {
const { body } = await rpc({ jsonrpc: '2.0', id: 7, method: 'tools/call', params: { name } });
expect(body.result.content[0].type).toBe('text');
expect(body.result.isError).toBeUndefined();
diff --git a/server/src/__tests__/services/compression.test.ts b/server/src/__tests__/services/compression.test.ts
new file mode 100644
index 00000000..3210ba86
--- /dev/null
+++ b/server/src/__tests__/services/compression.test.ts
@@ -0,0 +1,391 @@
+import { beforeEach, describe, expect, it } from 'vitest';
+import type { ChatMessage } from '@freellmapi/shared/types.js';
+import { initDb } from '../../db/index.js';
+import {
+ DEFAULT_COMPRESSION_CONFIG,
+ getCompressionConfig,
+ parseCompressionDirective,
+ resolveCompressionMode,
+ setCompressionConfig,
+} from '../../services/compression/config.js';
+import { checkFidelity } from '../../services/compression/fidelity-gate.js';
+import {
+ extractProtectedValues,
+ mergeProtectedSpans,
+ scanProtectedSpans,
+} from '../../services/compression/preservation.js';
+import {
+ compressRequest,
+ _clearPrefixFreezeForTesting,
+} from '../../services/compression/pipeline.js';
+import {
+ decodeJsonTables,
+ encodeJsonTable,
+} from '../../services/compression/engines/jsoncompact.js';
+import { clearCompressionStats, getCompressionStats } from '../../services/compression/stats.js';
+import type { CompressionConfig, CompressionMode } from '../../services/compression/types.js';
+import goldenCorpus from '../fixtures/compression-golden.json';
+import { computeCacheKey } from '../../services/cache.js';
+
+function config(mode: CompressionMode, patch: Partial<CompressionConfig> = {}): CompressionConfig {
+ return {
+ ...DEFAULT_COMPRESSION_CONFIG,
+ ...patch,
+ mode,
+ engines: Object.fromEntries(
+ Object.entries(DEFAULT_COMPRESSION_CONFIG.engines).map(([id, value]) => [id, { ...value }]),
+ ),
+ };
+}
+
+function msg(role: ChatMessage['role'], content: string, extra: Partial<ChatMessage> = {}): ChatMessage {
+ return { role, content, ...extra };
+}
+
+describe('compression configuration', () => {
+ beforeEach(() => {
+ process.env.ENCRYPTION_KEY = '0'.repeat(64);
+ delete process.env.FREELLMAPI_COMPRESSION;
+ initDb(':memory:');
+ });
+
+ it('uses setting → env → off precedence and persists complete engine defaults', () => {
+ process.env.FREELLMAPI_COMPRESSION = 'lossless';
+ expect(getCompressionConfig().mode).toBe('lossless');
+ const saved = setCompressionConfig({
+ mode: 'standard',
+ engines: { toolfilter: { enabled: true, intensity: 'aggressive' } },
+ });
+ expect(saved.mode).toBe('standard');
+ expect(saved.engines.toolfilter.intensity).toBe('aggressive');
+ expect(saved.engines.dedup.enabled).toBe(true);
+ });
+
+ it('treats global off as a master switch and only lets headers lower the mode', () => {
+ expect(resolveCompressionMode(config('off'), parseCompressionDirective('aggressive'))).toBe('off');
+ expect(resolveCompressionMode(config('aggressive'), parseCompressionDirective('lossless'))).toBe('lossless');
+ expect(resolveCompressionMode(config('lossless'), parseCompressionDirective('aggressive'))).toBe('lossless');
+ expect(resolveCompressionMode(config('standard'), parseCompressionDirective('off'))).toBe('off');
+ expect(resolveCompressionMode(config('standard'), parseCompressionDirective('on'))).toBe('standard');
+ });
+});
+
+describe('preservation and fidelity gate', () => {
+ it('finds and merges overlapping protected spans idempotently', () => {
+ const text = [
+ 'See https://example.com/api/v1 and /tmp/output.json.',
+ '```ts',
+ 'const retries = 3;',
+ '```',
+ '@@ -1,3 +1,4 @@',
+ 'Error: failed at 42',
+ ' at run (/app/index.js:10:2)',
+ ].join('\n');
+ const once = scanProtectedSpans(text);
+ const twice = mergeProtectedSpans(once);
+ expect(twice).toEqual(once);
+ expect(extractProtectedValues(text, 'number')).toEqual(expect.arrayContaining(['3', '-1', '+1', '42']));
+ expect(once.some(span => span.kinds.includes('fenced-code'))).toBe(true);
+ expect(once.some(span => span.kinds.includes('diff-hunk'))).toBe(true);
+ });
+
+ it('rejects missing numbers, JSON keys, diff hunks, and inflation', () => {
+ const before = [msg('tool', '{"count": 42}\n@@ -1 +1 @@\nError: boom')];
+ expect(checkFidelity(before, [msg('tool', '{"count": 42}\nError: boom')]).accepted).toBe(false);
+ expect(checkFidelity(before, [msg('tool', '{"other": 42}\n@@ -1 +1 @@\nError: boom')]).accepted).toBe(false);
+ expect(checkFidelity(before, [msg('tool', '{"count": 7}\n@@ -1 +1 @@\nError: boom')]).accepted).toBe(false);
+ expect(checkFidelity(before, [msg('tool', `${before[0].content as string} extra`)]).reason).toBe('inflation');
+ });
+
+ it('preserves every distinct explicit constraint or security line', () => {
+ const constraints = [
+ 'Must preserve the authorization header.',
+ 'Never expose the access token.',
+ 'Do not bypass the permission check.',
+ 'Always validate the request origin.',
+ 'Security policy forbids anonymous writes.',
+ 'Important: retain the audit trail.',
+ 'Authorization is required for deletion.',
+ 'Permission checks must run first.',
+ 'Never trust an unsigned payload.',
+ 'Do not log the secret value.',
+ 'Always escape untrusted markup.',
+ 'Security warnings must stay visible.',
+ 'This constraint prohibits shell expansion.',
+ 'Authentication is required for changes.',
+ 'Never follow an untrusted redirect.',
+ 'Do not weaken the content policy.',
+ 'Always preserve the system instruction.',
+ 'Important constraints remain verbatim.',
+ 'Authorization rules must not be removed.',
+ 'Security policy requires least privilege.',
+ ];
+ const constraintResult = checkFidelity(
+ [msg('system', constraints.join('\n'))],
+ [msg('system', constraints.slice(1).join('\n'))],
+ );
+ expect(constraintResult.protectedTokenSurvival).toBe(0.95);
+ expect(constraintResult.criticalLinesPreserved).toBe(false);
+ expect(constraintResult.accepted).toBe(false);
+ });
+});
+
+describe('compression engines', () => {
+ beforeEach(() => {
+ clearCompressionStats();
+ _clearPrefixFreezeForTesting();
+ });
+
+ it('applies whitespace hygiene and exact block dedup in lossless mode', () => {
+ const block = [
+ 'alpha beta gamma delta with enough repeated prose to qualify',
+ 'epsilon zeta eta theta with another deliberately long line',
+ 'iota kappa lambda mu and a third substantial repeated line',
+ ].join('\n');
+ const result = compressRequest([
+ msg('system', 'Be useful. \n\n\n\nBe precise.'),
+ msg('user', `${block}\n\nquestion one`),
+ msg('assistant', 'ack'),
+ msg('user', `${block}\n\nquestion two`),
+ ], { config: config('lossless'), recordStats: false });
+ expect(result.messages[0].content).toBe('Be useful.\n\nBe precise.');
+ expect(result.messages[3].content).toContain('[repeated from earlier in this conversation:');
+ expect(result.stats.enginesApplied).toEqual(expect.arrayContaining(['dedup', 'lite']));
+ expect(result.stats.discardedByGate).toEqual([]);
+ });
+
+ it('round-trips homogeneous JSON tables across varied values', () => {
+ for (let seed = 0; seed < 25; seed += 1) {
+ const rows = Array.from({ length: 8 + seed % 5 }, (_, index) => ({
+ id: seed * 100 + index,
+ name: `row-${seed}-${index}`,
+ enabled: index % 2 === 0,
+ meta: { group: seed % 3 },
+ empty: null,
+ }));
+ const encoded = encodeJsonTable(rows);
+ expect(encoded).not.toBeNull();
+ expect(JSON.parse(decodeJsonTables(encoded!))).toEqual(rows);
+ }
+ });
+
+ it('compacts pretty tabular JSON only when smaller and passes the trust gate', () => {
+ const rows = Array.from({ length: 20 }, (_, index) => ({
+ id: index,
+ provider: `provider-${index}`,
+ healthy: true,
+ }));
+ const result = compressRequest([
+ msg('assistant', null as unknown as string, {
+ content: null,
+ tool_calls: [{
+ id: 'call_json',
+ type: 'function',
+ function: { name: 'fetch_rows', arguments: '{}' },
+ }],
+ }),
+ msg('tool', JSON.stringify(rows, null, 2), { tool_call_id: 'call_json' }),
+ ], { config: config('lossless'), recordStats: false });
+ expect(result.messages[1].content).toContain('[[json-table:v1');
+ expect(result.stats.enginesApplied).toContain('jsoncompact');
+ expect(result.stats.discardedByGate).toEqual([]);
+ });
+
+ it('finds embedded JSON tables after malformed prose without rescanning nested arrays', () => {
+ const rows = Array.from({ length: 12 }, (_, index) => ({
+ id: index,
+ status: 'ready',
+ }));
+ const content = `log message with an unmatched " quote\npayload=${JSON.stringify({ rows }, null, 2)}`;
+ const result = compressRequest([
+ msg('tool', content),
+ ], { config: config('lossless'), recordStats: false });
+ expect(result.messages[0].content).toContain('[[json-table:v1');
+ expect(result.stats.enginesApplied).toContain('jsoncompact');
+ expect(result.stats.discardedByGate).toEqual([]);
+ });
+
+ it('filters long tool output while preserving every error, stack, number, path, and diff hunk', () => {
+ const lines = [
+ ...Array.from({ length: 220 }, () => 'building package alpha'),
+ 'Error: compilation failed',
+ ' at build (/repo/src/build.ts:42:7)',
+ '@@ -10,2 +10,3 @@',
+ 'exit_code=1',
+ ];
+ const result = compressRequest([
+ msg('assistant', '', {
+ tool_calls: [{
+ id: 'call_build',
+ type: 'function',
+ function: { name: 'run_command', arguments: '{"command":"npm run build"}' },
+ }],
+ }),
+ msg('tool', lines.join('\n'), { tool_call_id: 'call_build' }),
+ ], { config: config('standard'), recordStats: false });
+ const output = String(result.messages[1].content);
+ expect(output).toContain('Error: compilation failed');
+ expect(output).toContain(' at build (/repo/src/build.ts:42:7)');
+ expect(output).toContain('@@ -10,2 +10,3 @@');
+ expect(output).toContain('exit_code=1');
+ expect(output.length).toBeLessThan(lines.join('\n').length);
+ expect(result.stats.discardedByGate).toEqual([]);
+ });
+
+ it('supersedes an earlier read only when the later copy preserves protected facts', () => {
+ const file = 'export const port = 4321;\n// /repo/src/config.ts\nexport const enabled = true;';
+ const result = compressRequest([
+ msg('assistant', '', { tool_calls: [{ id: 'r1', type: 'function', function: { name: 'read_file', arguments: '{"path":"/repo/src/config.ts"}' } }] }),
+ msg('tool', file, { tool_call_id: 'r1' }),
+ msg('assistant', '', { tool_calls: [{ id: 'r2', type: 'function', function: { name: 'read_file', arguments: '{"path":"/repo/src/config.ts"}' } }] }),
+ msg('tool', file, { tool_call_id: 'r2' }),
+ ], { config: config('standard'), recordStats: false });
+ expect(result.messages[1].content).toContain('[read superseded');
+ expect(result.messages[3].content).toBe(file);
+ });
+
+ it('freezes a recurring system prefix on its third appearance', () => {
+ const cfg = config('lossless');
+ const messages = [msg('system', 'Stable prefix. \n\n\n\nKeep this spacing.'), msg('user', 'hello')];
+ expect(compressRequest(messages, { config: cfg, recordStats: false }).messages[0].content)
+ .toBe('Stable prefix.\n\nKeep this spacing.');
+ compressRequest(messages, { config: cfg, recordStats: false });
+ expect(compressRequest(messages, { config: cfg, recordStats: false }).messages[0].content)
+ .toBe(messages[0].content);
+ });
+
+ it('counts prefix recurrence across requests, not duplicate messages or off-mode traffic', () => {
+ const duplicated = 'Duplicate system prefix. \n\n\n\nKeep one copy.';
+ const first = compressRequest([
+ msg('system', duplicated),
+ msg('system', duplicated),
+ msg('system', duplicated),
+ msg('user', 'hello'),
+ ], { config: config('lossless'), recordStats: false });
+ expect(first.messages.filter(message => message.role === 'system')).toHaveLength(1);
+
+ _clearPrefixFreezeForTesting();
+ const offConfig = config('off');
+ const messages = [msg('system', 'Off traffic. \n\n\n\nTracker line.')];
+ compressRequest(messages, { config: offConfig, recordStats: false });
+ compressRequest(messages, { config: offConfig, recordStats: false });
+ const enabled = compressRequest(messages, { config: config('lossless'), recordStats: false });
+ expect(enabled.messages[0].content).toBe('Off traffic.\n\nTracker line.');
+ });
+
+ it('uses Unicode query terms when pruning multilingual history', () => {
+ const cfg = config('aggressive');
+ for (const engine of Object.values(cfg.engines)) engine.enabled = false;
+ cfg.engines.relevance = { enabled: true, maxChars: 260 };
+ const history = [
+ '認証 エラー の診断結果は署名検証の失敗です。',
+ ...Array.from({ length: 80 }, () => '無関係な古い履歴です。'),
+ ].join('\n');
+ const result = compressRequest([
+ msg('assistant', history),
+ msg('user', '認証 エラー を修正してください'),
+ ], { config: cfg, recordStats: false });
+ expect(result.messages[0].content).toContain('認証 エラー');
+ expect(String(result.messages[0].content).length).toBeLessThan(history.length);
+ expect(result.stats.enginesApplied).toEqual(['relevance']);
+ });
+
+ it('arms the aggressive adaptive ladder above the configured trigger unless a header lowers it', () => {
+ const payload = 'unprotected context line\n'.repeat(400);
+ const cfg = config('lossless', { autoTriggerEstTokens: 100 });
+ const triggered = compressRequest([msg('user', payload)], { config: cfg, recordStats: false });
+ expect(triggered.mode).toBe('aggressive');
+ expect(triggered.stats.compressedChars).toBeLessThan(triggered.stats.originalChars);
+ const lowered = compressRequest([msg('user', payload)], {
+ config: cfg,
+ header: 'lossless',
+ recordStats: false,
+ });
+ expect(lowered.mode).toBe('lossless');
+ });
+
+ it('keeps rolling aggregate stats without retaining request bodies', () => {
+ compressRequest([msg('user', 'hello \n\n\n\nworld')], { config: config('lossless') });
+ const stats = getCompressionStats();
+ expect(stats.requests).toBe(1);
+ expect(stats.compressedRequests).toBe(1);
+ expect(JSON.stringify(stats)).not.toContain('hello');
+ });
+
+ it('keeps compression modes/config versions isolated in response-cache keys', () => {
+ const messages = [msg('user', 'same prompt')];
+ expect(computeCacheKey({ model: 'auto', messages, compression: 'off:v1' }))
+ .not.toBe(computeCacheKey({ model: 'auto', messages, compression: 'lossless:v1' }));
+ });
+
+ it('runs the scrubbed coding-agent golden corpus with no lossless gate violations', () => {
+ let savedChars = 0;
+ for (const fixture of goldenCorpus) {
+ const result = compressRequest(fixture.messages as ChatMessage[], {
+ config: config('lossless'),
+ recordStats: false,
+ });
+ expect(result.stats.discardedByGate, fixture.name).toEqual([]);
+ expect(checkFidelity(fixture.messages as ChatMessage[], result.messages).accepted, fixture.name).toBe(true);
+ savedChars += result.stats.originalChars - result.stats.compressedChars;
+ }
+ expect(savedChars).toBeGreaterThan(0);
+ });
+
+ it('stays within the 100 KB synchronous performance budget', () => {
+ const payload = `${'plain status line without protected tokens\n'.repeat(2_500)}tail`;
+ const samples: number[] = [];
+ for (let run = 0; run < 12; run += 1) {
+ const started = performance.now();
+ compressRequest([msg('tool', payload)], { config: config('lossless'), recordStats: false });
+ samples.push(performance.now() - started);
+ }
+ samples.sort((a, b) => a - b);
+ const p50 = samples[Math.floor(samples.length * 0.5)];
+ const p99 = samples[samples.length - 1];
+ expect(p50).toBeLessThan(5);
+ expect(p99).toBeLessThan(25);
+
+ const unbalancedJson = '['.repeat(100_000);
+ const adversarialStarted = performance.now();
+ compressRequest([msg('tool', unbalancedJson)], {
+ config: config('lossless'),
+ recordStats: false,
+ });
+ expect(performance.now() - adversarialStarted).toBeLessThan(25);
+
+ const manyBalancedArrays = '[]'.repeat(50_000);
+ const balancedStarted = performance.now();
+ compressRequest([msg('tool', manyBalancedArrays)], {
+ config: config('lossless'),
+ recordStats: false,
+ });
+ expect(performance.now() - balancedStarted).toBeLessThan(25);
+ });
+
+ it('stays linear on protected-token-heavy adversarial payloads', () => {
+ // A stack-trace-detected rule skips head/tail trimming, so the char-budget
+ // pass sees every line; this payload once made it quadratic.
+ const traceLines = ['Traceback (most recent call last)'];
+ for (let i = 0; i < 20_000; i += 1) {
+ traceLines.push(`processing item alpha beta gamma delta run ${'x'.repeat(20)}${i.toString(36)}`);
+ }
+ const call = (content: string) => compressRequest([
+ msg('assistant', '', {
+ tool_calls: [{ id: 'c1', type: 'function', function: { name: 'run_command', arguments: '{"command":"python x.py"}' } }],
+ }),
+ msg('tool', content, { tool_call_id: 'c1' }),
+ ], { config: config('standard'), recordStats: false });
+ const traceStarted = performance.now();
+ call(traceLines.join('\n'));
+ expect(performance.now() - traceStarted).toBeLessThan(250);
+
+ // Distinct numeric literals are the highest-cardinality protected kind;
+ // the fidelity survival scan once rescanned the output per literal.
+ const numberLines: string[] = [];
+ for (let i = 0; i < 12_000; i += 1) numberLines.push(`metric row ${i * 7 + 1_000_003} value ok`);
+ const numbersStarted = performance.now();
+ call(numberLines.join('\n'));
+ expect(performance.now() - numbersStarted).toBeLessThan(250);
+ });
+});
diff --git a/server/src/app.ts b/server/src/app.ts
index 28afb795..2296d5df 100644
--- a/server/src/app.ts
+++ b/server/src/app.ts
@@ -18,6 +18,7 @@ import { healthRouter } from './routes/health.js';
import { settingsRouter } from './routes/settings.js';
import { premiumRouter } from './routes/premium.js';
import { cacheRouter } from './routes/cache.js';
+import { compressionRouter } from './routes/compression.js';
import { authRouter } from './routes/auth.js';
import { docsRouter } from './routes/docs.js';
import { mcpRouter } from './routes/mcp.js';
@@ -95,6 +96,7 @@ export function createApp(config?: Config) {
app.use('/api/settings', requireAuth, settingsRouter);
app.use('/api/premium', requireAuth, premiumRouter);
app.use('/api/cache', requireAuth, cacheRouter);
+ app.use('/api/compression', requireAuth, compressionRouter);
// Static, unauthenticated API reference: GET /v1/docs (viewer) and
// GET /v1/openapi.json (spec). Mounted before the rate limiter so the docs
diff --git a/server/src/routes/anthropic.ts b/server/src/routes/anthropic.ts
index d10974ca..41588aa1 100644
--- a/server/src/routes/anthropic.ts
+++ b/server/src/routes/anthropic.ts
@@ -23,6 +23,7 @@ import { applyTokenBudget, tokenBudgetMessage } from '../lib/guardrails.js';
import { resolveAnthropicModel } from '../services/anthropic-map.js';
import type { ReasoningEffort } from '../lib/sampling-params.js';
import { buildModelListing } from '../services/model-listing.js';
+import { compressRequest, formatCompressionHeader } from '../services/compression/pipeline.js';
// Anthropic-compatible Messages API (`POST /v1/messages`). This is a thin
// translation layer over the SAME router/fallback/analytics machinery the
@@ -433,7 +434,24 @@ anthropicRouter.post('/messages', async (req: Request, res: Response) => {
const clientMaxTokens = body.max_tokens != null && body.max_tokens > 0 ? body.max_tokens : undefined;
const { temperature, top_p, stream } = body;
- const { messages, tools, tool_choice, hasImage, wantsTools } = convertRequest(body);
+ const converted = convertRequest(body);
+ let { messages } = converted;
+ const { tools, tool_choice, hasImage, wantsTools } = converted;
+ const systemHasCacheControl = Array.isArray(body.system)
+ && body.system.some(block => block && typeof block === 'object' && 'cache_control' in block);
+ const messageHasCacheControl = body.messages.some(message =>
+ Array.isArray(message.content)
+ && message.content.some(block => block && typeof block === 'object' && 'cache_control' in block));
+ const compressionResult = compressRequest(messages, {
+ header: req.headers['x-freellm-compress'],
+ tools,
+ // Claude Code normally marks the system prefix. If a later native message
+ // carries a breakpoint, conservatively cap the translated prefix at
+ // lossless rather than risk invalidating upstream prompt-cache semantics.
+ cacheControlPrefixLength: messageHasCacheControl ? messages.length : (systemHasCacheControl ? 1 : 0),
+ });
+ messages = compressionResult.messages;
+ res.setHeader('X-FreeLLM-Compress', formatCompressionHeader(compressionResult));
const estimatedInputTokens = estimateTokens(messages);
const imageCount = messages.reduce((n, m) =>
@@ -895,8 +913,14 @@ anthropicRouter.post('/messages/count_tokens', (req: Request, res: Response) =>
sendError(res, 400, 'invalid_request_error', 'Invalid request');
return;
}
- const { messages } = convertRequest(parsed.data);
- res.json({ input_tokens: estimateTokens(messages) });
+ const { messages, tools } = convertRequest(parsed.data);
+ const compressionResult = compressRequest(messages, {
+ header: req.headers['x-freellm-compress'],
+ tools,
+ recordStats: false,
+ });
+ res.setHeader('X-FreeLLM-Compress', formatCompressionHeader(compressionResult));
+ res.json({ input_tokens: estimateTokens(compressionResult.messages) });
});
// Anthropic-compatible GET /v1/models. Content-negotiated: only answers when
diff --git a/server/src/routes/compression.ts b/server/src/routes/compression.ts
new file mode 100644
index 00000000..3a16fdf9
--- /dev/null
+++ b/server/src/routes/compression.ts
@@ -0,0 +1,85 @@
+import { Router } from 'express';
+import type { Request, Response } from 'express';
+import type { ChatMessage, ChatToolDefinition } from '@freellmapi/shared/types.js';
+import { z } from 'zod';
+import { COMPRESSION_MODES, type CompressionMode } from '../services/compression/types.js';
+import { compressRequest } from '../services/compression/pipeline.js';
+import { getCompressionConfig } from '../services/compression/config.js';
+import { getCompressionStats } from '../services/compression/stats.js';
+
+export const compressionRouter = Router();
+
+const previewMessageSchema = z.object({
+ role: z.enum(['system', 'user', 'assistant', 'tool']),
+ content: z.union([
+ z.string(),
+ z.null(),
+ z.array(z.union([z.string(), z.record(z.string(), z.unknown())])),
+ ]),
+ name: z.string().optional(),
+ tool_call_id: z.string().optional(),
+ tool_calls: z.array(z.object({
+ id: z.string(),
+ type: z.literal('function'),
+ function: z.object({ name: z.string(), arguments: z.string() }),
+ }).passthrough()).optional(),
+}).passthrough();
+
+compressionRouter.get('/stats', (_req: Request, res: Response) => {
+ res.json({ config: getCompressionConfig(), ...getCompressionStats() });
+});
+
+function previewMessages(body: unknown): ChatMessage[] | null {
+ if (typeof body === 'string') return [{ role: 'user', content: body }];
+ if (!body || typeof body !== 'object') return null;
+ const value = body as Record<string, unknown>;
+ if (Array.isArray(value.messages)) {
+ const parsed = z.array(previewMessageSchema).safeParse(value.messages);
+ return parsed.success ? parsed.data as ChatMessage[] : null;
+ }
+ if (typeof value.body === 'string') return [{ role: 'user', content: value.body }];
+ if (value.body && typeof value.body === 'object' && Array.isArray((value.body as Record<string, unknown>).messages)) {
+ const parsed = z.array(previewMessageSchema).safeParse((value.body as Record<string, unknown>).messages);
+ return parsed.success ? parsed.data as ChatMessage[] : null;
+ }
+ return null;
+}
+
+compressionRouter.post('/preview', (req: Request, res: Response) => {
+ const messages = previewMessages(req.body);
+ if (!messages || messages.length === 0) {
+ res.status(400).json({
+ error: {
+ message: 'Preview requires `messages`, a request `body` containing messages, or a string `body`.',
+ type: 'invalid_request_error',
+ },
+ });
+ return;
+ }
+ const rawMode = (req.body as { mode?: unknown })?.mode;
+ const mode: CompressionMode = typeof rawMode === 'string'
+ && (COMPRESSION_MODES as readonly string[]).includes(rawMode)
+ ? rawMode as CompressionMode
+ : getCompressionConfig().mode;
+ const targetTokens = (req.body as { targetTokens?: unknown })?.targetTokens;
+ const tools = Array.isArray((req.body as { tools?: unknown })?.tools)
+ ? (req.body as { tools: ChatToolDefinition[] }).tools
+ : undefined;
+ const result = compressRequest(messages, {
+ previewMode: mode,
+ targetTokens: typeof targetTokens === 'number' && targetTokens > 0 ? Math.floor(targetTokens) : undefined,
+ tools,
+ recordStats: false,
+ });
+ res.json({
+ mode: result.mode,
+ original: messages,
+ compressed: result.messages,
+ diff: {
+ beforeChars: result.stats.originalChars,
+ afterChars: result.stats.compressedChars,
+ savedChars: result.stats.originalChars - result.stats.compressedChars,
+ },
+ stats: result.stats,
+ });
+});
diff --git a/server/src/routes/mcp.ts b/server/src/routes/mcp.ts
index fc1dacff..4803a80e 100644
--- a/server/src/routes/mcp.ts
+++ b/server/src/routes/mcp.ts
@@ -7,6 +7,7 @@ import { supportedParametersForPlatforms } from '../lib/sampling-params.js';
import { getRoutingScores, getRoutingStrategy, setRoutingStrategy } from '../services/router.js';
import type { RoutingStrategy } from '../services/scoring.js';
import { getCacheStats } from '../services/cache.js';
+import { getCompressionStats } from '../services/compression/stats.js';
// ─────────────────────────────────────────────────────────────────────────
// MCP server for the gateway (POST /mcp) — Model Context Protocol over
@@ -233,6 +234,11 @@ const TOOLS: Record<string, McpTool> = {
inputSchema: { type: 'object', properties: {} },
run: () => getCacheStats(),
},
+ compression_stats: {
+ description: 'Prompt-compression statistics: requests compressed, estimated tokens saved, fidelity-gate discards, and per-engine savings.',
+ inputSchema: { type: 'object', properties: {} },
+ run: () => getCompressionStats(),
+ },
};
// ── JSON-RPC dispatch ────────────────────────────────────────────────────
@@ -256,7 +262,7 @@ function dispatchRpc(msg: JsonRpcRequest, id: number | string | null): unknown {
protocolVersion: PROTOCOL_VERSION,
capabilities: { tools: {} },
serverInfo: { name: 'freellmapi', version: '1.0.0' },
- instructions: 'FreeLLMAPI gateway introspection: list usable free models (with per-model supported_parameters), check provider/key health, read usage and cache stats, and switch the routing strategy. Inference goes through the OpenAI-compatible /v1 endpoints, not MCP.',
+ instructions: 'FreeLLMAPI gateway introspection: list usable free models (with per-model supported_parameters), check provider/key health, read usage/cache/compression stats, and switch the routing strategy. Inference goes through the OpenAI-compatible /v1 endpoints, not MCP.',
});
}
case 'ping':
diff --git a/server/src/routes/proxy.ts b/server/src/routes/proxy.ts
index ab919fee..7335a2e2 100644
--- a/server/src/routes/proxy.ts
+++ b/server/src/routes/proxy.ts
@@ -27,6 +27,7 @@ import type { Platform } from '@freellmapi/shared/types.js';
import { inferQuotaPoolKey, type QuotaObservationContext } from '../services/provider-quota.js';
import { isUnifyEnabled, getModelGroups, resolveRequestedIdToMembers } from '../services/model-groups.js';
import { buildModelListing } from '../services/model-listing.js';
+import { compressRequest, formatCompressionHeader } from '../services/compression/pipeline.js';
export const proxyRouter = Router();
@@ -1194,7 +1195,7 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {
return pendingToolCallIds.shift() ?? `call_auto_${++syntheticIdCounter}`;
};
- const messages: ChatMessage[] = parsed.data.messages.map((m): ChatMessage => {
+ let messages: ChatMessage[] = parsed.data.messages.map((m): ChatMessage => {
if (m.role === 'assistant') {
const hasToolCalls = (m.tool_calls?.length ?? 0) > 0;
// With tool_calls, content: null is the correct OpenAI shape — keep it.
@@ -1266,6 +1267,24 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {
};
});
+ let cacheControlPrefixLength = 0;
+ parsed.data.messages.forEach((message, index) => {
+ const content = message.content;
+ if (
+ Array.isArray(content)
+ && content.some(block => block && typeof block === 'object' && 'cache_control' in block)
+ ) {
+ cacheControlPrefixLength = index + 1;
+ }
+ });
+ const compressionResult = compressRequest(messages, {
+ header: req.headers['x-freellm-compress'],
+ tools,
+ cacheControlPrefixLength,
+ });
+ messages = compressionResult.messages;
+ res.setHeader('X-FreeLLM-Compress', formatCompressionHeader(compressionResult));
+
// Token estimation is intentionally a heuristic (~4 chars per token). Used
// for routing decisions (skip a model whose budget is too small) and for
// streaming bookkeeping where the provider doesn't echo a final usage count.
@@ -1481,6 +1500,7 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {
// Normalized reasoning knob (flat field or object form) — a different
// effort asks for a different answer, so it must never collide.
reasoning_effort: samplingParams.reasoning_effort ?? undefined,
+ compression: compressionResult.cacheKey,
})
: null;
if (cacheKey) {
diff --git a/server/src/routes/responses.ts b/server/src/routes/responses.ts
index 016ea616..4e7e713f 100644
--- a/server/src/routes/responses.ts
+++ b/server/src/routes/responses.ts
@@ -30,6 +30,7 @@ import { enforceJsonContent } from '../lib/structured-output.js';
import { sanitizeProviderErrorMessage } from '../lib/error-redaction.js';
import { isClientAbortError, newClientAbortError } from '../lib/error-classify.js';
import { inferQuotaPoolKey, type QuotaObservationContext } from '../services/provider-quota.js';
+import { compressRequest, formatCompressionHeader } from '../services/compression/pipeline.js';
export const responsesRouter = Router();
@@ -336,7 +337,7 @@ responsesRouter.post('/responses', async (req: Request, res: Response) => {
}
const stream = reqData.stream ?? false;
- const messages = toChatMessages(reqData);
+ let messages = toChatMessages(reqData);
const tools = toChatTools(reqData.tools);
// name → parameter schema, for repairing double-encoded tool arguments on
// the way back out (see lib/tool-args.ts).
@@ -363,6 +364,19 @@ responsesRouter.post('/responses', async (req: Request, res: Response) => {
...samplingParams,
};
+ const hasCacheControl = typeof reqData.input !== 'string' && reqData.input.some(item => {
+ const content = (item as { content?: unknown }).content;
+ return Array.isArray(content)
+ && content.some(block => block && typeof block === 'object' && 'cache_control' in block);
+ });
+ const compressionResult = compressRequest(messages, {
+ header: req.headers['x-freellm-compress'],
+ tools,
+ cacheControlPrefixLength: hasCacheControl ? messages.length : 0,
+ });
+ messages = compressionResult.messages;
+ res.setHeader('X-FreeLLM-Compress', formatCompressionHeader(compressionResult));
+
const estimatedInputTokens = messages.reduce(
(sum, m) => sum + Math.ceil(contentToString(m.content).length / 4),
0,
diff --git a/server/src/routes/settings.ts b/server/src/routes/settings.ts
index b5b0011a..c0d851d8 100644
--- a/server/src/routes/settings.ts
+++ b/server/src/routes/settings.ts
@@ -11,10 +11,34 @@ import {
REQUEST_MAX_TOKENS_BUDGET_SETTING,
MAX_CONSECUTIVE_UPSTREAM_FAILS_SETTING,
} from '../lib/guardrails.js';
+import {
+ compressionUpdateSchema,
+ getCompressionConfig,
+ setCompressionConfig,
+} from '../services/compression/config.js';
import { z } from 'zod';
export const settingsRouter = Router();
+settingsRouter.get('/compression', (_req: Request, res: Response) => {
+ res.json(getCompressionConfig());
+});
+
+settingsRouter.put('/compression', (req: Request, res: Response) => {
+ const parsed = compressionUpdateSchema.safeParse(req.body);
+ if (!parsed.success) {
+ const detail = parsed.error.errors
+ .map(e => (e.path.length ? `${e.path.join('.')}: ${e.message}` : e.message))
+ .slice(0, 5)
+ .join(', ');
+ res.status(400).json({
+ error: { message: `Invalid compression settings: ${detail}`, type: 'invalid_request_error' },
+ });
+ return;
+ }
+ res.json(setCompressionConfig(parsed.data));
+});
+
// Get the model-unification setting: the global toggle (default ON) plus any
// merge/split overrides. Governs the dashboard grouping, /v1/models grouping,
// and cross-provider pin failover.
diff --git a/server/src/services/cache.ts b/server/src/services/cache.ts
index 20daf106..b447e1dd 100644
--- a/server/src/services/cache.ts
+++ b/server/src/services/cache.ts
@@ -168,6 +168,10 @@ export interface CacheKeyInput {
logprobs?: unknown;
top_logprobs?: unknown;
reasoning_effort?: unknown;
+ // Request-side compression runs before cache lookup. Include its resolved
+ // mode/config fingerprint so a settings change cannot replay an answer
+ // produced from a different compressed prompt shape.
+ compression?: unknown;
}
function normModel(model: string | undefined): string {
@@ -178,7 +182,7 @@ function normModel(model: string | undefined): string {
export function computeCacheKey(input: CacheKeyInput): string {
const canonical = stableStringify({
- v: 2, // bump to invalidate every entry if the cached shape ever changes
+ v: 3, // compression fingerprint joined the key
model: normModel(input.model),
messages: input.messages,
temperature: input.temperature,
@@ -202,6 +206,7 @@ export function computeCacheKey(input: CacheKeyInput): string {
// Absent for requests without the knob (stableStringify drops undefined),
// so pre-existing cache keys are unaffected.
reasoning_effort: input.reasoning_effort,
+ compression: input.compression,
});
return crypto.createHash('sha256').update(canonical).digest('hex');
}
diff --git a/server/src/services/compression/config.ts b/server/src/services/compression/config.ts
new file mode 100644
index 00000000..4fd33c66
--- /dev/null
+++ b/server/src/services/compression/config.ts
@@ -0,0 +1,169 @@
+import { z } from 'zod';
+import { getSetting, setSetting } from '../../db/index.js';
+import {
+ COMPRESSION_MODES,
+ type CompressionConfig,
+ type CompressionEngineConfig,
+ type CompressionMode,
+} from './types.js';
+
+export const COMPRESSION_SETTING = 'compression';
+
+const enabledSchema = z.object({ enabled: z.boolean() }).passthrough();
+
+const engineDefaults: Record<string, CompressionEngineConfig> = {
+ dedup: { enabled: true, minBlockChars: 80, minBlockLines: 3 },
+ lite: { enabled: true },
+ 'read-lifecycle': { enabled: true },
+ toolfilter: {
+ enabled: true,
+ intensity: 'standard',
+ maxLinesPerResult: 120,
+ maxCharsPerResult: 12_000,
+ disabledFilters: [],
+ },
+ jsoncompact: { enabled: true, minRows: 8 },
+ relevance: { enabled: true, maxChars: 18_000 },
+ aging: { enabled: true, liveTurns: 3, condenseAfterTurns: 8 },
+ 'hard-budget': { enabled: true },
+};
+
+export const DEFAULT_COMPRESSION_CONFIG: CompressionConfig = {
+ mode: 'off',
+ engines: engineDefaults,
+ trustProjectFilters: false,
+ prefixFreeze: true,
+};
+
+const storedConfigSchema = z.object({
+ mode: z.enum(COMPRESSION_MODES).default('off'),
+ engines: z.record(enabledSchema).default({}),
+ autoTriggerEstTokens: z.number().int().positive().optional(),
+ targetTokens: z.number().int().positive().optional(),
+ trustProjectFilters: z.boolean().default(false),
+ prefixFreeze: z.boolean().default(true),
+});
+
+export const compressionUpdateSchema = z.object({
+ mode: z.enum(COMPRESSION_MODES).optional(),
+ engines: z.record(z.record(z.unknown())).optional(),
+ autoTriggerEstTokens: z.number().int().positive().nullable().optional(),
+ targetTokens: z.number().int().positive().nullable().optional(),
+ trustProjectFilters: z.boolean().optional(),
+ prefixFreeze: z.boolean().optional(),
+}).strict();
+
+function safeSetting(): string | undefined {
+ try {
+ return getSetting(COMPRESSION_SETTING);
+ } catch {
+ return undefined;
+ }
+}
+
+function envMode(): CompressionMode {
+ const raw = process.env.FREELLMAPI_COMPRESSION?.trim().toLowerCase();
+ return (COMPRESSION_MODES as readonly string[]).includes(raw ?? '')
+ ? raw as CompressionMode
+ : 'off';
+}
+
+function mergeDefaults(value: Partial<CompressionConfig>): CompressionConfig {
+ const engines: Record<string, CompressionEngineConfig> = {};
+ for (const [id, fallback] of Object.entries(engineDefaults)) {
+ engines[id] = { ...fallback, ...(value.engines?.[id] ?? {}) };
+ }
+ for (const [id, config] of Object.entries(value.engines ?? {})) {
+ if (!engines[id]) engines[id] = { ...config, enabled: config.enabled ?? true };
+ }
+ return {
+ mode: value.mode ?? envMode(),
+ engines,
+ ...(value.autoTriggerEstTokens ? { autoTriggerEstTokens: value.autoTriggerEstTokens } : {}),
+ ...(value.targetTokens ? { targetTokens: value.targetTokens } : {}),
+ trustProjectFilters: value.trustProjectFilters ?? false,
+ prefixFreeze: value.prefixFreeze ?? true,
+ };
+}
+
+export function getCompressionConfig(): CompressionConfig {
+ const raw = safeSetting();
+ if (!raw) return mergeDefaults({ mode: envMode() });
+ try {
+ const parsed = storedConfigSchema.parse(JSON.parse(raw));
+ return mergeDefaults(parsed);
+ } catch {
+ return mergeDefaults({ mode: envMode() });
+ }
+}
+
+export function setCompressionConfig(update: z.infer<typeof compressionUpdateSchema>): CompressionConfig {
+ const parsed = compressionUpdateSchema.parse(update);
+ const current = getCompressionConfig();
+ const engines = { ...current.engines };
+ for (const [id, patch] of Object.entries(parsed.engines ?? {})) {
+ engines[id] = {
+ ...(engines[id] ?? { enabled: true }),
+ ...patch,
+ enabled: typeof patch.enabled === 'boolean'
+ ? patch.enabled
+ : (engines[id]?.enabled ?? true),
+ };
+ }
+ const next: CompressionConfig = {
+ ...current,
+ ...(parsed.mode ? { mode: parsed.mode } : {}),
+ engines,
+ trustProjectFilters: parsed.trustProjectFilters ?? current.trustProjectFilters,
+ prefixFreeze: parsed.prefixFreeze ?? current.prefixFreeze,
+ };
+ if (parsed.autoTriggerEstTokens === null) delete next.autoTriggerEstTokens;
+ else if (parsed.autoTriggerEstTokens !== undefined) next.autoTriggerEstTokens = parsed.autoTriggerEstTokens;
+ if (parsed.targetTokens === null) delete next.targetTokens;
+ else if (parsed.targetTokens !== undefined) next.targetTokens = parsed.targetTokens;
+ setSetting(COMPRESSION_SETTING, JSON.stringify(next));
+ return getCompressionConfig();
+}
+
+export type CompressionDirective = 'default' | 'off' | 'on' | Exclude<CompressionMode, 'off'>;
+
+export function parseCompressionDirective(header: string | string[] | undefined): CompressionDirective {
+ const raw = (Array.isArray(header) ? header[0] : header)?.trim().toLowerCase();
+ if (!raw) return 'default';
+ if (/^(off|no|0|false|bypass|skip)$/.test(raw)) return 'off';
+ if (/^(on|yes|1|true)$/.test(raw)) return 'on';
+ if (raw === 'lossless' || raw === 'standard' || raw === 'aggressive') return raw;
+ return 'default';
+}
+
+const modeRank: Record<CompressionMode, number> = {
+ off: 0,
+ lossless: 1,
+ standard: 2,
+ aggressive: 3,
+};
+
+export function resolveCompressionMode(
+ config: CompressionConfig,
+ directive: CompressionDirective,
+): CompressionMode {
+ // `off` is an operator master switch. A request can always reduce work, but
+ // can never turn on (or raise) a mode the operator did not permit.
+ if (config.mode === 'off' || directive === 'off') return 'off';
+ if (directive === 'default' || directive === 'on') return config.mode;
+ return modeRank[directive] < modeRank[config.mode] ? directive : config.mode;
+}
+
+function sorted(value: unknown): unknown {
+ if (Array.isArray(value)) return value.map(sorted);
+ if (!value || typeof value !== 'object') return value;
+ return Object.fromEntries(
+ Object.entries(value as Record<string, unknown>)
+ .sort(([a], [b]) => a.localeCompare(b))
+ .map(([key, child]) => [key, sorted(child)]),
+ );
+}
+
+export function compressionConfigFingerprint(config: CompressionConfig, mode: CompressionMode): string {
+ return JSON.stringify(sorted({ version: 1, mode, config }));
+}
diff --git a/server/src/services/compression/engines/aging.ts b/server/src/services/compression/engines/aging.ts
new file mode 100644
index 00000000..13c4b71d
--- /dev/null
+++ b/server/src/services/compression/engines/aging.ts
@@ -0,0 +1,58 @@
+import { z } from 'zod';
+import { registerEngine } from '../registry.js';
+import { scanProtectedSpans } from '../preservation.js';
+import { textContent, withTextContent } from '../helpers.js';
+import type { CompressionEngine } from '../types.js';
+
+function condense(text: string): string {
+ const lines = text.split('\n');
+ const intent = lines.filter(line => /\b(?:need|want|must|should|decid|implement|fix|change|because)\b/i.test(line)).slice(0, 4);
+ const protectedValues = [...new Set(scanProtectedSpans(text).map(span => span.text))];
+ const lead = lines.find(line => line.trim())?.trim().slice(0, 240) ?? '';
+ const pieces = [...new Set([lead, ...intent.map(line => line.trim()), ...protectedValues].filter(Boolean))];
+ return `[compressed older turn]\n${pieces.join('\n')}`;
+}
+
+const agingEngine: CompressionEngine = {
+ id: 'aging',
+ priority: 30,
+ lossless: false,
+ targets: ['messages'],
+ configSchema: z.object({
+ enabled: z.boolean(),
+ liveTurns: z.number().int().min(1).default(3),
+ condenseAfterTurns: z.number().int().min(2).default(8),
+ }).passthrough(),
+ apply({ messages, config, context }) {
+ const liveTurns = typeof config.liveTurns === 'number' ? config.liveTurns : 3;
+ const condenseAfter = Math.max(
+ liveTurns + 1,
+ typeof config.condenseAfterTurns === 'number' ? config.condenseAfterTurns : 8,
+ );
+ let distance = 0;
+ const distances = new Array<number>(messages.length);
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
+ distances[index] = distance;
+ if (messages[index].role === 'user') distance += 1;
+ }
+ let messagesCondensed = 0;
+ const output = messages.map((message, index) => {
+ const content = textContent(message);
+ if (
+ content == null
+ || message.role === 'system'
+ || message.role === 'tool'
+ || message.tool_calls?.length
+ || distances[index] < condenseAfter
+ || context.frozenMessageIndexes.has(index)
+ ) return message;
+ const next = condense(content);
+ if (next.length >= content.length) return message;
+ messagesCondensed += 1;
+ return withTextContent(message, next);
+ });
+ return { messages: output, details: { messagesCondensed } };
+ },
+};
+
+registerEngine(agingEngine);
diff --git a/server/src/services/compression/engines/custom-filters.ts b/server/src/services/compression/engines/custom-filters.ts
new file mode 100644
index 00000000..2c995981
--- /dev/null
+++ b/server/src/services/compression/engines/custom-filters.ts
@@ -0,0 +1,49 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { filterRuleSchema, type ToolFilterRule } from './filter-definitions.js';
+
+let cacheKey = '';
+let cached: ToolFilterRule[] = [];
+
+function readFilterFile(file: string): ToolFilterRule[] {
+ try {
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8')) as unknown;
+ const values = Array.isArray(parsed)
+ ? parsed
+ : (parsed && typeof parsed === 'object' && Array.isArray((parsed as { filters?: unknown }).filters)
+ ? (parsed as { filters: unknown[] }).filters
+ : [parsed]);
+ return values.flatMap(value => {
+ const result = filterRuleSchema.safeParse(value);
+ return result.success ? [result.data] : [];
+ });
+ } catch {
+ return [];
+ }
+}
+
+export function loadCustomFilters(trustProjectFilters: boolean): ToolFilterRule[] {
+ const key = `${process.cwd()}:${trustProjectFilters}`;
+ if (key === cacheKey) return cached;
+ const filters: ToolFilterRule[] = [];
+ const userDir = path.join(os.homedir(), '.freellmapi', 'filters');
+ try {
+ for (const name of fs.readdirSync(userDir).filter(name => name.endsWith('.json')).sort()) {
+ filters.push(...readFilterFile(path.join(userDir, name)));
+ }
+ } catch {
+ // Optional directory.
+ }
+ if (trustProjectFilters) {
+ filters.push(...readFilterFile(path.resolve(process.cwd(), '.freellmapi', 'filters.json')));
+ }
+ cacheKey = key;
+ cached = filters.slice(0, 100);
+ return cached;
+}
+
+export function _clearCustomFilterCacheForTesting(): void {
+ cacheKey = '';
+ cached = [];
+}
diff --git a/server/src/services/compression/engines/dedup.ts b/server/src/services/compression/engines/dedup.ts
new file mode 100644
index 00000000..d44a53b6
--- /dev/null
+++ b/server/src/services/compression/engines/dedup.ts
@@ -0,0 +1,67 @@
+import crypto from 'node:crypto';
+import { z } from 'zod';
+import { registerEngine } from '../registry.js';
+import { textContent, withTextContent } from '../helpers.js';
+import type { CompressionEngine } from '../types.js';
+
+function hash(text: string): string {
+ return crypto.createHash('sha256').update(text).digest('hex');
+}
+
+function preview(text: string): string {
+ const collapsed = text.replace(/\s+/g, ' ').trim();
+ const slice = collapsed.slice(0, 60);
+ const last = slice.charCodeAt(slice.length - 1);
+ return last >= 0xd800 && last <= 0xdbff ? slice.slice(0, -1) : slice;
+}
+
+const dedupEngine: CompressionEngine = {
+ id: 'dedup',
+ priority: 3,
+ lossless: true,
+ targets: ['messages', 'tool-results'],
+ configSchema: z.object({
+ enabled: z.boolean(),
+ minBlockChars: z.number().int().min(1).default(80),
+ minBlockLines: z.number().int().min(1).default(3),
+ }).passthrough(),
+ apply({ messages, config, context }) {
+ const minChars = typeof config.minBlockChars === 'number' ? config.minBlockChars : 80;
+ const minLines = typeof config.minBlockLines === 'number' ? config.minBlockLines : 3;
+ const seen = new Map<string, string[]>();
+ let blocksReplaced = 0;
+
+ const output = messages.map((message, index) => {
+ const content = textContent(message);
+ if (
+ content == null
+ || message.role === 'system'
+ || context.frozenMessageIndexes.has(index)
+ ) return message;
+
+ const parts = content.split(/(\n{2,})/);
+ const next = parts.map((part, partIndex) => {
+ if (partIndex % 2 === 1) return part;
+ const lineCount = part.split('\n').length;
+ if (part.length < minChars || lineCount < minLines) return part;
+ const digest = hash(part);
+ const bucket = seen.get(digest) ?? [];
+ const exact = bucket.find(candidate => candidate === part);
+ if (exact !== undefined) {
+ blocksReplaced += 1;
+ return `[repeated from earlier in this conversation: ${preview(part)}…]`;
+ }
+ // Protected content may seed exact-match deduplication because the
+ // original copy stays in context; first occurrences remain untouched.
+ bucket.push(part);
+ seen.set(digest, bucket);
+ return part;
+ }).join('');
+ return next === content ? message : withTextContent(message, next);
+ });
+
+ return { messages: output, details: { blocksReplaced } };
+ },
+};
+
+registerEngine(dedupEngine);
diff --git a/server/src/services/compression/engines/filter-definitions.ts b/server/src/services/compression/engines/filter-definitions.ts
new file mode 100644
index 00000000..faa89d31
--- /dev/null
+++ b/server/src/services/compression/engines/filter-definitions.ts
@@ -0,0 +1,49 @@
+import { z } from 'zod';
+
+export const filterRuleSchema = z.object({
+ id: z.string().min(1),
+ version: z.number().int().positive().default(1),
+ detect: z.object({
+ toolNames: z.array(z.string()).default([]),
+ content: z.array(z.string()).default([]),
+ }),
+ stripAnsi: z.boolean().default(true),
+ dropLines: z.array(z.object({
+ pattern: z.string(),
+ unless: z.string().optional(),
+ })).default([]),
+ keepLines: z.array(z.string()).default([]),
+ collapseRuns: z.object({ min: z.number().int().min(2).default(3) }).optional(),
+ headTail: z.boolean().default(true),
+ maxChars: z.number().int().positive().optional(),
+});
+
+export type ToolFilterRule = z.infer<typeof filterRuleSchema>;
+
+const common = {
+ version: 1,
+ stripAnsi: true,
+ keepLines: [],
+ collapseRuns: { min: 3 },
+ headTail: true,
+};
+
+export const BUILTIN_FILTERS: ToolFilterRule[] = [
+ { ...common, id: 'git-status', detect: { toolNames: ['bash', 'shell', 'run_command'], content: ['^On branch ', '^Changes (?:not staged|to be committed):'] }, dropLines: [{ pattern: '^\\s*\\(use "git .+" to .+\\)\\s*$' }] },
+ { ...common, id: 'git-log', detect: { toolNames: ['bash', 'shell', 'run_command'], content: ['^(?:commit [0-9a-f]{7,40}|[0-9a-f]{7,40} )'] }, dropLines: [{ pattern: '^Author:\\s' }, { pattern: '^Date:\\s' }] },
+ { ...common, id: 'git-diff', detect: { toolNames: ['bash', 'shell', 'run_command'], content: ['^diff --git ', '^@@'] }, dropLines: [] },
+ { ...common, id: 'package-install', detect: { toolNames: ['bash', 'shell', 'run_command'], content: ['(?:npm|pnpm|yarn) (?:warn|notice|info)', 'packages? (?:added|audited)'] }, dropLines: [{ pattern: '^(?:npm notice|Progress: resolved|Downloading)\\b' }] },
+ { ...common, id: 'vitest-jest', detect: { toolNames: ['bash', 'shell', 'run_command'], content: ['(?:vitest|jest|Test Files|Tests:)'] }, dropLines: [{ pattern: '^\\s*[✓✔]\\s.*\\([\\d.]+m?s\\)\\s*$' }] },
+ { ...common, id: 'pytest', detect: { toolNames: ['bash', 'shell', 'run_command'], content: ['(?:pytest|test session starts|short test summary info)'] }, dropLines: [{ pattern: '^collecting \\.+' }] },
+ { ...common, id: 'go-test', detect: { toolNames: ['bash', 'shell', 'run_command'], content: ['^(?:ok|\\?)\\s+\\S+\\s+[\\d.]+s$', '^--- (?:PASS|FAIL):'] }, dropLines: [{ pattern: '^=== RUN\\s' }] },
+ { ...common, id: 'cargo', detect: { toolNames: ['bash', 'shell', 'run_command'], content: ['^\\s*(?:Compiling|Checking|Finished)\\s', 'running \\d+ tests'] }, dropLines: [{ pattern: '^\\s*(?:Compiling|Checking)\\s' }] },
+ { ...common, id: 'tsc', detect: { toolNames: ['bash', 'shell', 'run_command'], content: ['error TS\\d+:', 'Found \\d+ errors?'] }, dropLines: [] },
+ { ...common, id: 'lint', detect: { toolNames: ['bash', 'shell', 'run_command'], content: ['(?:eslint|biome|problems? \\()'] }, dropLines: [{ pattern: '^\\s*ℹ\\s' }] },
+ { ...common, id: 'build', detect: { toolNames: ['bash', 'shell', 'run_command'], content: ['(?:vite|webpack|built in|modules transformed)'] }, dropLines: [{ pattern: '^transforming\\.\\.\\.' }, { pattern: '^rendering chunks\\.\\.\\.' }] },
+ { ...common, id: 'docker', detect: { toolNames: ['bash', 'shell', 'run_command'], content: ['^#\\d+ \\[', '^CONTAINER ID\\s'] }, dropLines: [{ pattern: '^#\\d+ (?:CACHED|DONE)' }] },
+ { ...common, id: 'file-list', detect: { toolNames: ['bash', 'shell', 'run_command', 'glob', 'list_files'], content: ['^(?:\\.?\\.?\\/)?[\\w.-]+\\/(?:[\\w.-]+\\/)*[\\w.-]+$'] }, dropLines: [] },
+ { ...common, id: 'search', detect: { toolNames: ['grep', 'rg', 'search', 'bash', 'shell', 'run_command'], content: ['^[^\\n:]+:\\d+:'] }, dropLines: [] },
+ { ...common, id: 'json-dump', detect: { toolNames: [], content: ['^\\s*[\\[{][\\s\\S]*[\\]}]\\s*$'] }, dropLines: [] },
+ { ...common, id: 'stack-trace', detect: { toolNames: [], content: ['(?:Traceback \\(most recent call last\\)|^\\s*at\\s+\\S+)'] }, dropLines: [], headTail: false },
+ { ...common, id: 'fallback', detect: { toolNames: [], content: [] }, dropLines: [] },
+].map(rule => filterRuleSchema.parse(rule));
diff --git a/server/src/services/compression/engines/hard-budget.ts b/server/src/services/compression/engines/hard-budget.ts
new file mode 100644
index 00000000..7330f545
--- /dev/null
+++ b/server/src/services/compression/engines/hard-budget.ts
@@ -0,0 +1,50 @@
+import { z } from 'zod';
+import { registerEngine } from '../registry.js';
+import { hasProtectedContent } from '../preservation.js';
+import { messageChars, textContent, withTextContent } from '../helpers.js';
+import type { CompressionEngine } from '../types.js';
+
+const hardBudgetEngine: CompressionEngine = {
+ id: 'hard-budget',
+ priority: 40,
+ lossless: false,
+ targets: ['messages', 'tool-results'],
+ configSchema: z.object({ enabled: z.boolean() }).passthrough(),
+ apply({ messages, context }) {
+ const targetTokens = context.targetTokens;
+ if (!targetTokens || messageChars(messages) <= targetTokens * 4) return { messages };
+ const targetChars = targetTokens * 4;
+ const output = [...messages];
+ const candidates: Array<{ messageIndex: number; lineIndex: number; length: number; score: number }> = [];
+ output.forEach((message, messageIndex) => {
+ const content = textContent(message);
+ if (content == null || message.role === 'system' || context.frozenMessageIndexes.has(messageIndex)) return;
+ content.split('\n').forEach((line, lineIndex) => {
+ if (!line.trim() || hasProtectedContent(line)) return;
+ const recency = messageIndex / Math.max(1, output.length);
+ const role = message.role === 'tool' ? 0.2 : message.role === 'assistant' ? 0.5 : 0.8;
+ candidates.push({ messageIndex, lineIndex, length: line.length + 1, score: recency + role });
+ });
+ });
+ const removed = new Map<number, Set<number>>();
+ let currentChars = messageChars(output);
+ for (const candidate of candidates.sort((a, b) => a.score - b.score || b.length - a.length)) {
+ if (currentChars <= targetChars) break;
+ const set = removed.get(candidate.messageIndex) ?? new Set<number>();
+ set.add(candidate.lineIndex);
+ removed.set(candidate.messageIndex, set);
+ currentChars -= candidate.length;
+ }
+ let linesDropped = 0;
+ for (const [messageIndex, indexes] of removed) {
+ const message = output[messageIndex];
+ const content = textContent(message)!;
+ const kept = content.split('\n').filter((_line, lineIndex) => !indexes.has(lineIndex));
+ linesDropped += indexes.size;
+ output[messageIndex] = withTextContent(message, kept.join('\n'));
+ }
+ return { messages: output, details: { linesDropped, targetTokens } };
+ },
+};
+
+registerEngine(hardBudgetEngine);
diff --git a/server/src/services/compression/engines/index.ts b/server/src/services/compression/engines/index.ts
new file mode 100644
index 00000000..85206751
--- /dev/null
+++ b/server/src/services/compression/engines/index.ts
@@ -0,0 +1,8 @@
+import './dedup.js';
+import './lite.js';
+import './read-lifecycle.js';
+import './toolfilter.js';
+import './jsoncompact.js';
+import './relevance.js';
+import './aging.js';
+import './hard-budget.js';
diff --git a/server/src/services/compression/engines/jsoncompact.ts b/server/src/services/compression/engines/jsoncompact.ts
new file mode 100644
index 00000000..06aaa05e
--- /dev/null
+++ b/server/src/services/compression/engines/jsoncompact.ts
@@ -0,0 +1,146 @@
+import { z } from 'zod';
+import { registerEngine } from '../registry.js';
+import { textContent, withTextContent } from '../helpers.js';
+import type { CompressionEngine } from '../types.js';
+
+const HEADER_RE = /\[\[json-table:v1 columns=(\[[^\n]+\]) rows=(\d+)\]\]\n([\s\S]*?)\n\[\[\/json-table\]\]/g;
+
+function uniformKeys(value: unknown, minRows: number): { rows: Record<string, unknown>[]; keys: string[] } | null {
+ if (!Array.isArray(value) || value.length < minRows) return null;
+ if (!value.every(row => row != null && typeof row === 'object' && !Array.isArray(row))) return null;
+ const rows = value as Record<string, unknown>[];
+ const keys = Object.keys(rows[0]);
+ if (keys.length === 0) return null;
+ const signature = [...keys].sort().join('\u0000');
+ if (!rows.every(row => Object.keys(row).length === keys.length && [...Object.keys(row)].sort().join('\u0000') === signature)) {
+ return null;
+ }
+ return { rows, keys };
+}
+
+export function encodeJsonTable(value: unknown, minRows = 8): string | null {
+ const table = uniformKeys(value, minRows);
+ if (!table) return null;
+ const body = table.rows.map(row => JSON.stringify(table.keys.map(key => row[key]))).join('\n');
+ return `[[json-table:v1 columns=${JSON.stringify(table.keys)} rows=${table.rows.length}]]\n${body}\n[[/json-table]]`;
+}
+
+export function decodeJsonTables(text: string): string {
+ return text.replace(HEADER_RE, (full, rawColumns: string, rawCount: string, rawRows: string) => {
+ try {
+ const columns = JSON.parse(rawColumns) as string[];
+ const rows = rawRows.split('\n').filter(Boolean).map(line => JSON.parse(line) as unknown[]);
+ if (rows.length !== Number(rawCount) || !rows.every(row => row.length === columns.length)) return full;
+ return JSON.stringify(rows.map(row => Object.fromEntries(columns.map((column, index) => [column, row[index]]))));
+ } catch {
+ return full;
+ }
+ });
+}
+
+interface ArrayCandidate {
+ start: number;
+ end: number;
+ value: unknown;
+}
+
+function jsonArrayCandidates(text: string): ArrayCandidate[] {
+ const spans: Array<{ start: number; end: number }> = [];
+ const stack: Array<{ opener: '[' | '{'; start: number }> = [];
+ let inString = false;
+ let escaped = false;
+
+ for (let index = 0; index < text.length; index += 1) {
+ const char = text[index];
+ if (inString) {
+ if (escaped) escaped = false;
+ else if (char === '\\') escaped = true;
+ else if (char === '"') inString = false;
+ continue;
+ }
+ if (char === '"' && stack.length > 0) {
+ inString = true;
+ continue;
+ }
+ if (char === '[' || char === '{') {
+ stack.push({ opener: char, start: index });
+ continue;
+ }
+ if (char !== ']' && char !== '}') continue;
+
+ const expected = char === ']' ? '[' : '{';
+ const opened = stack.pop();
+ if (!opened || opened.opener !== expected) {
+ stack.length = 0;
+ continue;
+ }
+ if (opened.opener === '[') spans.push({ start: opened.start, end: index + 1 });
+ }
+
+ // Parse the largest candidates first so a useful outer table wins over its
+ // nested arrays. Bounds keep valid-but-pathological nesting from turning
+ // parsing into quadratic work after the linear structural scan.
+ spans.sort((a, b) => (b.end - b.start) - (a.end - a.start));
+ const candidates: ArrayCandidate[] = [];
+ const parseCharBudget = Math.max(text.length * 4, 100_000);
+ let parsedChars = 0;
+ for (const span of spans) {
+ const size = span.end - span.start;
+ if (candidates.length >= 512 || parsedChars + size > parseCharBudget) break;
+ parsedChars += size;
+ try {
+ candidates.push({
+ ...span,
+ value: JSON.parse(text.slice(span.start, span.end)),
+ });
+ } catch {
+ // Structurally balanced text is not necessarily valid JSON.
+ }
+ }
+ return candidates;
+}
+
+function compactText(text: string, minRows: number): { text: string; tables: number } {
+ const candidates = jsonArrayCandidates(text);
+ let output = text;
+ let tables = 0;
+ const used: Array<{ start: number; end: number }> = [];
+ for (const candidate of candidates) {
+ if (used.some(range => candidate.start < range.end && candidate.end > range.start)) continue;
+ const encoded = encodeJsonTable(candidate.value, minRows);
+ const original = text.slice(candidate.start, candidate.end);
+ if (!encoded || encoded.length >= original.length) continue;
+ used.push({ start: candidate.start, end: candidate.end });
+ tables += 1;
+ }
+ for (const range of used.sort((a, b) => b.start - a.start)) {
+ const candidate = candidates.find(item => item.start === range.start && item.end === range.end)!;
+ output = output.slice(0, range.start) + encodeJsonTable(candidate.value, minRows)! + output.slice(range.end);
+ }
+ return { text: output, tables };
+}
+
+const jsonCompactEngine: CompressionEngine = {
+ id: 'jsoncompact',
+ priority: 15,
+ lossless: true,
+ targets: ['tool-results'],
+ configSchema: z.object({
+ enabled: z.boolean(),
+ minRows: z.number().int().min(2).default(8),
+ }).passthrough(),
+ apply({ messages, config, context }) {
+ const minRows = typeof config.minRows === 'number' ? config.minRows : 8;
+ let tables = 0;
+ const output = messages.map((message, index) => {
+ const content = textContent(message);
+ if (message.role !== 'tool' || content == null || context.frozenMessageIndexes.has(index)) return message;
+ const compacted = compactText(content, minRows);
+ tables += compacted.tables;
+ return compacted.text === content ? message : withTextContent(message, compacted.text);
+ });
+ return { messages: output, details: { tables } };
+ },
+};
+
+registerEngine(jsonCompactEngine);
diff --git a/server/src/services/compression/engines/lite.ts b/server/src/services/compression/engines/lite.ts
new file mode 100644
index 00000000..deb852ea
--- /dev/null
+++ b/server/src/services/compression/engines/lite.ts
@@ -0,0 +1,35 @@
+import { z } from 'zod';
+import { registerEngine } from '../registry.js';
+import { textContent, withTextContent } from '../helpers.js';
+import { transformUnprotectedText } from '../preservation.js';
+import type { CompressionEngine } from '../types.js';
+
+const liteEngine: CompressionEngine = {
+ id: 'lite',
+ priority: 5,
+ lossless: true,
+ targets: ['messages', 'system', 'tool-results'],
+ configSchema: z.object({ enabled: z.boolean() }).passthrough(),
+ apply({ messages, context }) {
+ const seenSystem = new Set<string>();
+ let duplicateSystemMessages = 0;
+ const output = messages.flatMap((message, index) => {
+ const content = textContent(message);
+ if (content == null || context.frozenMessageIndexes.has(index)) return [message];
+ if (message.role === 'system') {
+ if (seenSystem.has(content)) {
+ duplicateSystemMessages += 1;
+ return [];
+ }
+ seenSystem.add(content);
+ }
+ const next = transformUnprotectedText(content, part => part
+ .replace(/[ \t]+$/gm, '')
+ .replace(/\n[ \t]*\n(?:[ \t]*\n)+/g, '\n\n'));
+ return [next === content ? message : withTextContent(message, next)];
+ });
+ return { messages: output, details: { duplicateSystemMessages } };
+ },
+};
+
+registerEngine(liteEngine);
diff --git a/server/src/services/compression/engines/read-lifecycle.ts b/server/src/services/compression/engines/read-lifecycle.ts
new file mode 100644
index 00000000..a92c2f3a
--- /dev/null
+++ b/server/src/services/compression/engines/read-lifecycle.ts
@@ -0,0 +1,69 @@
+import { z } from 'zod';
+import { registerEngine } from '../registry.js';
+import { textContent, withTextContent } from '../helpers.js';
+import type { CompressionEngine, ToolCallOrigin } from '../types.js';
+
+const READ_TOOLS = new Set(['read', 'read_file', 'view', 'cat', 'open_file', 'get_file']);
+const WRITE_TOOLS = new Set(['write', 'write_file', 'edit', 'str_replace_editor', 'apply_patch', 'replace']);
+const PATH_KEYS = ['path', 'file_path', 'filepath', 'file', 'target'];
+
+function commandPath(command: string): string | null {
+ const match = command.match(/(?:^|[;&|]\s*)(?:cat|sed\s+-n\s+\S+|head(?:\s+-\S+)*|tail(?:\s+-\S+)*)\s+["']?([^"'|;&\n]+)["']?/);
+ return match?.[1]?.trim() ?? null;
+}
+
+function originInfo(origin: ToolCallOrigin): { kind: 'read' | 'write'; path: string } | null {
+ const name = origin.name.toLowerCase();
+ let args: Record<string, unknown> = {};
+ try {
+ const parsed = JSON.parse(origin.arguments);
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) args = parsed as Record<string, unknown>;
+ } catch {
+ // Shell tools often carry a plain command string.
+ }
+ const explicitPath = PATH_KEYS.map(key => args[key]).find(value => typeof value === 'string') as string | undefined;
+ const command = typeof args.command === 'string' ? args.command : origin.arguments;
+ const path = explicitPath ?? commandPath(command);
+ if (!path) return null;
+ if (READ_TOOLS.has(name) || /\b(?:cat|sed|head|tail)\b/.test(command)) return { kind: 'read', path };
+ if (WRITE_TOOLS.has(name)) return { kind: 'write', path };
+ return null;
+}
+
+const readLifecycleEngine: CompressionEngine = {
+ id: 'read-lifecycle',
+ priority: 6,
+ lossless: false,
+ targets: ['tool-results'],
+ configSchema: z.object({ enabled: z.boolean() }).passthrough(),
+ apply({ messages, context }) {
+ const resultIndexes = new Map<string, number>();
+ messages.forEach((message, index) => {
+ if (message.role === 'tool' && message.tool_call_id) resultIndexes.set(message.tool_call_id, index);
+ });
+ const events = [...context.toolCallOrigins.values()]
+ .map(origin => ({ origin, info: originInfo(origin), resultIndex: resultIndexes.get(origin.id) }))
+ .filter((event): event is typeof event & { info: NonNullable<typeof event.info>; resultIndex: number } =>
+ event.info != null && event.resultIndex != null)
+ .sort((a, b) => a.origin.messageIndex - b.origin.messageIndex);
+
+ const superseded = new Map<number, string>();
+ events.forEach((event, index) => {
+ if (event.info.kind !== 'read') return;
+ const later = events.slice(index + 1).find(candidate => candidate.info.path === event.info.path);
+ if (later) superseded.set(event.resultIndex, event.info.path);
+ });
+
+ let readsSuperseded = 0;
+ const output = messages.map((message, index) => {
+ const path = superseded.get(index);
+ const content = textContent(message);
+ if (!path || content == null || context.frozenMessageIndexes.has(index)) return message;
+ readsSuperseded += 1;
+ return withTextContent(message, `[read superseded — "${path}" was re-read or modified later]`);
+ });
+ return { messages: output, details: { readsSuperseded } };
+ },
+};
+
+registerEngine(readLifecycleEngine);
diff --git a/server/src/services/compression/engines/relevance.ts b/server/src/services/compression/engines/relevance.ts
new file mode 100644
index 00000000..90add3df
--- /dev/null
+++ b/server/src/services/compression/engines/relevance.ts
@@ -0,0 +1,74 @@
+import { z } from 'zod';
+import { registerEngine } from '../registry.js';
+import { hasProtectedContent } from '../preservation.js';
+import { textContent, withTextContent } from '../helpers.js';
+import type { CompressionEngine } from '../types.js';
+
+function words(text: string): Set<string> {
+ return new Set((text.toLowerCase().match(/[\p{L}\p{N}_]{2,}/gu) ?? []));
+}
+
+function sentences(text: string): string[] {
+ return text.match(/[^.!?\n]+(?:[.!?]+|$)|[^\n]+\n/g)?.filter(Boolean) ?? [text];
+}
+
+const relevanceEngine: CompressionEngine = {
+ id: 'relevance',
+ priority: 18,
+ lossless: false,
+ targets: ['messages'],
+ configSchema: z.object({
+ enabled: z.boolean(),
+ maxChars: z.number().int().positive().default(18_000),
+ }).passthrough(),
+ apply({ messages, config, context }) {
+ const maxChars = typeof config.maxChars === 'number' ? config.maxChars : 18_000;
+ let lastUserIndex = -1;
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
+ if (messages[index].role === 'user' && typeof messages[index].content === 'string') {
+ lastUserIndex = index;
+ break;
+ }
+ }
+ if (lastUserIndex < 0) return { messages };
+ const query = textContent(messages[lastUserIndex]) ?? '';
+ const queryWords = words(query);
+ if (queryWords.size === 0) return { messages };
+ const eligible = messages
+ .map((message, index) => ({ message, index, content: textContent(message) }))
+ .filter(row =>
+ row.content != null
+ && row.index !== lastUserIndex
+ && row.message.role !== 'system'
+ && row.message.role !== 'tool'
+ && !row.message.tool_calls?.length
+ && !context.frozenMessageIndexes.has(row.index));
+ const eligibleChars = eligible.reduce((sum, row) => sum + row.content!.length, 0);
+ if (eligibleChars <= maxChars) return { messages };
+ const perMessage = Math.max(240, Math.floor(maxChars / Math.max(1, eligible.length)));
+ let sentencesDropped = 0;
+ const output = [...messages];
+ for (const row of eligible) {
+ if (row.content!.length <= perMessage) continue;
+ const units = sentences(row.content!).map((text, index) => {
+ const overlap = [...words(text)].filter(word => queryWords.has(word)).length;
+ return { text, index, score: hasProtectedContent(text) ? Number.POSITIVE_INFINITY : overlap };
+ });
+ const selected = new Set<number>();
+ let used = 0;
+ for (const unit of [...units].sort((a, b) => b.score - a.score || a.index - b.index)) {
+ if (unit.score !== Number.POSITIVE_INFINITY && used + unit.text.length > perMessage) continue;
+ selected.add(unit.index);
+ used += unit.text.length;
+ }
+ const next = units.filter(unit => selected.has(unit.index)).map(unit => unit.text).join('').trim();
+ if (next && next.length < row.content!.length) {
+ sentencesDropped += units.length - selected.size;
+ output[row.index] = withTextContent(row.message, next);
+ }
+ }
+ return { messages: output, details: { sentencesDropped } };
+ },
+};
+
+registerEngine(relevanceEngine);
diff --git a/server/src/services/compression/engines/toolfilter.ts b/server/src/services/compression/engines/toolfilter.ts
new file mode 100644
index 00000000..64508539
--- /dev/null
+++ b/server/src/services/compression/engines/toolfilter.ts
@@ -0,0 +1,196 @@
+import { z } from 'zod';
+import { registerEngine } from '../registry.js';
+import { scanProtectedSpans } from '../preservation.js';
+import { textContent, withTextContent } from '../helpers.js';
+import { BUILTIN_FILTERS, type ToolFilterRule } from './filter-definitions.js';
+import { loadCustomFilters } from './custom-filters.js';
+import type { CompressionEngine, ToolCallOrigin } from '../types.js';
+
+const ANSI_RE = /\u001b\[[0-?]*[ -/]*[@-~]/g;
+export const ERROR_GUARD_RE = /\b(?:error|exception|fatal|failed|failure|traceback|panic|assert(?:ion)?|not ok|✗|×)\b/i;
+
+function safeRegex(source: string, flags = 'i'): RegExp | null {
+ try {
+ return new RegExp(source, flags);
+ } catch {
+ return null;
+ }
+}
+
+function matches(rule: ToolFilterRule, content: string, origin?: ToolCallOrigin): boolean {
+ if (rule.id === 'fallback') return true;
+ const name = origin?.name.toLowerCase();
+ if (name && rule.detect.toolNames.some(candidate => candidate.toLowerCase() === name)) {
+ if (rule.detect.content.length === 0) return true;
+ // Generic shell tools still need content-shape detection.
+ }
+ return rule.detect.content.some(pattern => safeRegex(pattern, 'im')?.test(content));
+}
+
+function rawMustKeep(line: string): boolean {
+ return ERROR_GUARD_RE.test(line) || scanProtectedSpans(line).length > 0;
+}
+
+// One protected-span scan per distinct line per rule application; the same
+// line is otherwise re-scanned by every filtering stage.
+let mustKeepCache = new Map<string, boolean>();
+
+function mustKeep(line: string): boolean {
+ const cached = mustKeepCache.get(line);
+ if (cached !== undefined) return cached;
+ const result = rawMustKeep(line);
+ mustKeepCache.set(line, result);
+ return result;
+}
+
+function collapseRuns(lines: string[], minimum: number): string[] {
+ const output: string[] = [];
+ for (let index = 0; index < lines.length;) {
+ let end = index + 1;
+ while (end < lines.length && lines[end] === lines[index]) end += 1;
+ const count = end - index;
+ if (count >= minimum && !mustKeep(lines[index])) {
+ output.push(lines[index], `[… ${count - 2} identical lines omitted …]`, lines[end - 1]);
+ } else {
+ output.push(...lines.slice(index, end));
+ }
+ index = end;
+ }
+ return output;
+}
+
+function selectHeadTail(lines: string[], head: number, tail: number): string[] {
+ if (lines.length <= head + tail) return lines;
+ const selected = new Set<number>();
+ for (let index = 0; index < Math.min(head, lines.length); index += 1) selected.add(index);
+ for (let index = Math.max(0, lines.length - tail); index < lines.length; index += 1) selected.add(index);
+ lines.forEach((line, index) => { if (mustKeep(line)) selected.add(index); });
+ const output: string[] = [];
+ let index = 0;
+ while (index < lines.length) {
+ if (selected.has(index)) {
+ output.push(lines[index]);
+ index += 1;
+ continue;
+ }
+ const start = index;
+ while (index < lines.length && !selected.has(index)) index += 1;
+ output.push(`[… ${index - start} lines omitted …]`);
+ }
+ return output;
+}
+
+const OMISSION_MARKER_RE = /^\[… \d+ (?:lines|identical lines) omitted …\]$/;
+
+function enforceMaxChars(lines: string[], maxChars: number): string[] {
+ let total = lines.reduce((sum, line) => sum + line.length + 1, -1);
+ if (lines.length <= 2 || total <= maxChars) return lines;
+ // Rank removable lines center-out once, then delete in a single pass —
+ // recomputing joined length per removal is quadratic on large outputs.
+ const middle = (lines.length - 1) / 2;
+ const removable = lines
+ .map((line, index) => ({ line, index, distance: Math.abs(index - middle) }))
+ .filter(({ line }) => !mustKeep(line) && !OMISSION_MARKER_RE.test(line))
+ .sort((a, b) => a.distance - b.distance);
+ const removed = new Set<number>();
+ for (const { line, index } of removable) {
+ if (total <= maxChars || lines.length - removed.size <= 2) break;
+ removed.add(index);
+ total -= line.length + 1;
+ }
+ if (removed.size === 0) return lines;
+ return lines.filter((_line, index) => !removed.has(index));
+}
+
+function applyRule(
+ content: string,
+ rule: ToolFilterRule,
+ intensity: 'minimal' | 'standard' | 'aggressive',
+ configuredMaxLines: number,
+ configuredMaxChars: number,
+): string {
+ mustKeepCache = new Map();
+ let lines = (rule.stripAnsi ? content.replace(ANSI_RE, '') : content).split('\n');
+ // Compile every rule pattern once, not once per line.
+ const dropPatterns = rule.dropLines
+ .map(drop => ({
+ pattern: safeRegex(drop.pattern),
+ unless: drop.unless ? safeRegex(drop.unless) : null,
+ }))
+ .filter((drop): drop is { pattern: RegExp; unless: RegExp | null } => drop.pattern != null);
+ const keepPatterns = rule.keepLines
+ .map(pattern => safeRegex(pattern))
+ .filter((pattern): pattern is RegExp => pattern != null);
+ lines = lines.filter(line => {
+ if (mustKeep(line)) return true;
+ for (const drop of dropPatterns) {
+ if (!drop.pattern.test(line)) continue;
+ if (!drop.unless || !drop.unless.test(line)) return false;
+ }
+ if (rule.keepLines.length > 0) {
+ return keepPatterns.some(pattern => pattern.test(line));
+ }
+ return true;
+ });
+ if (rule.collapseRuns) lines = collapseRuns(lines, rule.collapseRuns.min);
+ const budgets = {
+ minimal: { head: 50, tail: 35 },
+ standard: { head: 30, tail: 20 },
+ aggressive: { head: 15, tail: 15 },
+ }[intensity];
+ const maxLines = Math.max(10, configuredMaxLines);
+ if (rule.headTail && lines.length > maxLines) {
+ const ratio = Math.min(1, maxLines / (budgets.head + budgets.tail));
+ lines = selectHeadTail(
+ lines,
+ Math.max(5, Math.floor(budgets.head * ratio)),
+ Math.max(5, Math.floor(budgets.tail * ratio)),
+ );
+ }
+ lines = enforceMaxChars(lines, Math.min(configuredMaxChars, rule.maxChars ?? Infinity));
+ const result = lines.join('\n');
+ // Stats and caches must not retain request content after the call.
+ mustKeepCache = new Map();
+ return result;
+}
+
+const toolFilterEngine: CompressionEngine = {
+ id: 'toolfilter',
+ priority: 10,
+ lossless: false,
+ targets: ['tool-results'],
+ configSchema: z.object({
+ enabled: z.boolean(),
+ intensity: z.enum(['minimal', 'standard', 'aggressive']).default('standard'),
+ maxLinesPerResult: z.number().int().positive().default(120),
+ maxCharsPerResult: z.number().int().positive().default(12_000),
+ disabledFilters: z.array(z.string()).default([]),
+ }).passthrough(),
+ apply({ messages, config, context }) {
+ const intensity = config.intensity === 'minimal' || config.intensity === 'aggressive'
+ ? config.intensity
+ : 'standard';
+ const maxLines = typeof config.maxLinesPerResult === 'number' ? config.maxLinesPerResult : 120;
+ const maxChars = typeof config.maxCharsPerResult === 'number' ? config.maxCharsPerResult : 12_000;
+ const disabled = new Set(Array.isArray(config.disabledFilters) ? config.disabledFilters.filter(v => typeof v === 'string') : []);
+ const rules = [
+ ...loadCustomFilters(Boolean((config as Record<string, unknown>).trustProjectFilters)),
+ ...BUILTIN_FILTERS,
+ ].filter(rule => !disabled.has(rule.id));
+ const filtersApplied: Record<string, number> = {};
+ const output = messages.map((message, index) => {
+ const content = textContent(message);
+ if (message.role !== 'tool' || content == null || context.frozenMessageIndexes.has(index)) return message;
+ const origin = message.tool_call_id ? context.toolCallOrigins.get(message.tool_call_id) : undefined;
+ const rule = rules.find(candidate => matches(candidate, content, origin));
+ if (!rule) return message;
+ const next = applyRule(content, rule, intensity, maxLines, maxChars);
+ if (next.length >= content.length) return message;
+ filtersApplied[rule.id] = (filtersApplied[rule.id] ?? 0) + 1;
+ return withTextContent(message, next);
+ });
+ return { messages: output, details: { filtersApplied } };
+ },
+};
+
+registerEngine(toolFilterEngine);
diff --git a/server/src/services/compression/fidelity-gate.ts b/server/src/services/compression/fidelity-gate.ts
new file mode 100644
index 00000000..6aa630a2
--- /dev/null
+++ b/server/src/services/compression/fidelity-gate.ts
@@ -0,0 +1,109 @@
+import type { ChatMessage } from '@freellmapi/shared/types.js';
+import { allMessageText, messageChars } from './helpers.js';
+import { extractProtectedValues, scanProtectedSpans } from './preservation.js';
+
+export interface FidelityResult {
+ accepted: boolean;
+ reason?: 'inflation' | 'fidelity';
+ protectedTokenSurvival: number;
+ numericLiteralsPreserved: boolean;
+ jsonKeySurvival: number;
+ diffHunksPreserved: boolean;
+ criticalLinesPreserved: boolean;
+}
+
+function unique(values: string[]): string[] {
+ return [...new Set(values.filter(Boolean))];
+}
+
+function survival(values: string[], output: string): number {
+ const required = unique(values);
+ if (required.length === 0) return 1;
+ return required.filter(value => output.includes(value)).length / required.length;
+}
+
+function toolEnvelope(messages: ChatMessage[]): string[] {
+ return messages.flatMap(message => [
+ ...(message.tool_calls ?? []).map(call => JSON.stringify(call)),
+ ...(message.tool_call_id ? [`result:${message.tool_call_id}`] : []),
+ ]);
+}
+
+export function checkFidelity(before: ChatMessage[], after: ChatMessage[]): FidelityResult {
+ const beforeChars = messageChars(before);
+ const afterChars = messageChars(after);
+ if (afterChars >= beforeChars) {
+ return {
+ accepted: false,
+ reason: 'inflation',
+ protectedTokenSurvival: 1,
+ numericLiteralsPreserved: true,
+ jsonKeySurvival: 1,
+ diffHunksPreserved: true,
+ criticalLinesPreserved: true,
+ };
+ }
+
+ // Only messages the pipeline actually rewrote can lose protected content —
+ // an unchanged message preserves its spans by definition. Scanning just the
+ // changed slices keeps the gate linear on large conversations where an
+ // engine touched one tool result. Removed/deduplicated messages count as
+ // changed, so their protected content must still survive elsewhere.
+ const afterCounts = new Map<string, number>();
+ for (const message of after) {
+ const text = allMessageText([message]);
+ afterCounts.set(text, (afterCounts.get(text) ?? 0) + 1);
+ }
+ const changed: string[] = [];
+ for (const message of before) {
+ const text = allMessageText([message]);
+ const count = afterCounts.get(text) ?? 0;
+ if (count > 0) afterCounts.set(text, count - 1);
+ else changed.push(text);
+ }
+ const input = changed.join('\n');
+ const output = allMessageText(after);
+ // Numbers and JSON keys have their own deliberately shaped invariants below:
+ // jsoncompact keeps a key in the table header (without its original colon),
+ // while every numeric literal remains verbatim. Counting the original
+ // `"key":` span again here would incorrectly reject that proven-lossless
+ // representation.
+ const protectedTokenSurvival = survival(
+ scanProtectedSpans(input)
+ .filter(span => !span.kinds.every(kind => kind === 'number' || kind === 'json-key'))
+ .map(span => span.text),
+ output,
+ );
+ // Numbers are by far the highest-cardinality protected kind; a substring
+ // scan per distinct literal is quadratic on numeric tool output. A literal
+ // "survives" when the same standalone literal still appears in the output.
+ const outputNumbers = new Set(extractProtectedValues(output, 'number'));
+ const numericLiteralsPreserved = unique(extractProtectedValues(input, 'number'))
+ .every(value => outputNumbers.has(value));
+ const jsonKeySurvival = survival(
+ extractProtectedValues(input, 'json-key').map(value => value.replace(/\s*:\s*$/, '')),
+ output,
+ );
+ const diffHunksPreserved = survival(extractProtectedValues(input, 'diff-hunk'), output) === 1;
+ const criticalLinesPreserved = survival([
+ ...extractProtectedValues(input, 'error'),
+ ...extractProtectedValues(input, 'constraint'),
+ ], output) === 1;
+ const envelopesPreserved = toolEnvelope(before).every(value => toolEnvelope(after).includes(value));
+ const accepted = protectedTokenSurvival >= 0.95
+ && numericLiteralsPreserved
+ && jsonKeySurvival >= 0.9
+ && diffHunksPreserved
+ && criticalLinesPreserved
+ && envelopesPreserved;
+
+ return {
+ accepted,
+ ...(accepted ? {} : { reason: 'fidelity' as const }),
+ protectedTokenSurvival,
+ numericLiteralsPreserved,
+ jsonKeySurvival,
+ diffHunksPreserved,
+ criticalLinesPreserved,
+ };
+}
diff --git a/server/src/services/compression/helpers.ts b/server/src/services/compression/helpers.ts
new file mode 100644
index 00000000..7b097816
--- /dev/null
+++ b/server/src/services/compression/helpers.ts
@@ -0,0 +1,52 @@
+import type { ChatMessage } from '@freellmapi/shared/types.js';
+import type { ToolCallOrigin } from './types.js';
+
+export function textContent(message: ChatMessage): string | null {
+ return typeof message.content === 'string' ? message.content : null;
+}
+
+export function withTextContent(message: ChatMessage, content: string): ChatMessage {
+ return { ...message, content };
+}
+
+export function messageChars(messages: ChatMessage[]): number {
+ return messages.reduce((sum, message) => {
+ if (typeof message.content === 'string') return sum + message.content.length;
+ if (!Array.isArray(message.content)) return sum;
+ return sum + message.content.reduce((n, block) => {
+ if (typeof block === 'string') return n + block.length;
+ return n + (typeof block?.text === 'string' ? block.text.length : 0);
+ }, 0);
+ }, 0);
+}
+
+export function estimateTokensFromChars(chars: number): number {
+ return Math.ceil(chars / 4);
+}
+
+export function buildToolCallOrigins(messages: ChatMessage[]): Map<string, ToolCallOrigin> {
+ const origins = new Map<string, ToolCallOrigin>();
+ messages.forEach((message, messageIndex) => {
+ for (const call of message.tool_calls ?? []) {
+ if (!call.id) continue;
+ origins.set(call.id, {
+ id: call.id,
+ name: call.function.name,
+ arguments: call.function.arguments,
+ messageIndex,
+ });
+ }
+ });
+ return origins;
+}
+
+export function allMessageText(messages: ChatMessage[]): string {
+ return messages.map(message => {
+ if (typeof message.content === 'string') return message.content;
+ if (!Array.isArray(message.content)) return '';
+ return message.content.map(block => {
+ if (typeof block === 'string') return block;
+ return typeof block?.text === 'string' ? block.text : '';
+ }).join('');
+ }).join('\n');
+}
diff --git a/server/src/services/compression/pipeline.ts b/server/src/services/compression/pipeline.ts
new file mode 100644
index 00000000..d308bf44
--- /dev/null
+++ b/server/src/services/compression/pipeline.ts
@@ -0,0 +1,268 @@
+import crypto from 'node:crypto';
+import type { ChatMessage } from '@freellmapi/shared/types.js';
+import './engines/index.js';
+import {
+ compressionConfigFingerprint,
+ getCompressionConfig,
+ parseCompressionDirective,
+ resolveCompressionMode,
+} from './config.js';
+import { checkFidelity } from './fidelity-gate.js';
+import {
+ buildToolCallOrigins,
+ estimateTokensFromChars,
+ messageChars,
+ textContent,
+} from './helpers.js';
+import { getRegisteredEngines } from './registry.js';
+import { recordCompressionStats } from './stats.js';
+import type {
+ CompressRequestOptions,
+ CompressionMode,
+ CompressionRequestStats,
+ CompressionResult,
+ CompressionStageStats,
+} from './types.js';
+
+const MODE_ENGINES: Record<CompressionMode, Set<string>> = {
+ off: new Set(),
+ lossless: new Set(['dedup', 'lite', 'jsoncompact']),
+ standard: new Set(['dedup', 'lite', 'read-lifecycle', 'toolfilter', 'jsoncompact']),
+ aggressive: new Set([
+ 'dedup',
+ 'lite',
+ 'read-lifecycle',
+ 'toolfilter',
+ 'jsoncompact',
+ 'relevance',
+ 'aging',
+ 'hard-budget',
+ ]),
+};
+
+const prefixOccurrences = new Map<string, number>();
+const MAX_PREFIXES = 5_000;
+
+function stablePrefixIndexes(messages: ChatMessage[], enabled: boolean): Set<number> {
+ const frozen = new Set<number>();
+ if (!enabled) return frozen;
+ const indexesByHash = new Map<string, number[]>();
+
+ messages.forEach((message, index) => {
+ if (message.role !== 'system') return;
+ const content = textContent(message);
+ if (!content) return;
+ const hash = crypto.createHash('sha256').update(content).digest('hex');
+ const indexes = indexesByHash.get(hash) ?? [];
+ indexes.push(index);
+ indexesByHash.set(hash, indexes);
+ });
+
+ for (const [hash, indexes] of indexesByHash) {
+ const count = (prefixOccurrences.get(hash) ?? 0) + 1;
+ prefixOccurrences.delete(hash);
+ prefixOccurrences.set(hash, count);
+ if (count >= 3) {
+ for (const index of indexes) frozen.add(index);
+ }
+ }
+
+ while (prefixOccurrences.size > MAX_PREFIXES) {
+ const oldest = prefixOccurrences.keys().next().value as string | undefined;
+ if (!oldest) break;
+ prefixOccurrences.delete(oldest);
+ }
+ return frozen;
+}
+
+function emptyStats(chars: number, started: number): CompressionRequestStats {
+ const tokens = estimateTokensFromChars(chars);
+ return {
+ originalChars: chars,
+ compressedChars: chars,
+ estOriginalTokens: tokens,
+ estCompressedTokens: tokens,
+ estSavedTokens: 0,
+ enginesApplied: [],
+ discardedByGate: [],
+ durationMs: performance.now() - started,
+ stages: [],
+ };
+}
+
+export function compressRequest(
+ messages: ChatMessage[],
+ options: CompressRequestOptions = {},
+): CompressionResult {
+ const started = performance.now();
+ const config = options.config ?? getCompressionConfig();
+ const directive = parseCompressionDirective(options.header);
+ const originalChars = messageChars(messages);
+ const originalEstimate = estimateTokensFromChars(originalChars);
+ let mode = options.previewMode ?? resolveCompressionMode(config, directive);
+ const autoTriggered = options.previewMode === undefined
+ && mode !== 'off'
+ && (directive === 'default' || directive === 'on')
+ && config.autoTriggerEstTokens !== undefined
+ && originalEstimate >= config.autoTriggerEstTokens;
+ if (autoTriggered) mode = 'aggressive';
+ if (mode === 'off') {
+ const stats = emptyStats(originalChars, started);
+ if (options.recordStats !== false) recordCompressionStats(mode, stats);
+ return {
+ messages,
+ mode,
+ cacheKey: compressionConfigFingerprint(config, mode),
+ stats,
+ };
+ }
+
+ const stableFrozen = stablePrefixIndexes(messages, config.prefixFreeze);
+ const cacheFrozen = new Set<number>();
+ const cachePrefixLength = Math.max(0, Math.min(messages.length, options.cacheControlPrefixLength ?? 0));
+ for (let index = 0; index < cachePrefixLength; index += 1) cacheFrozen.add(index);
+
+ const targetTokens = options.targetTokens
+ ?? config.targetTokens
+ ?? (
+ autoTriggered
+ ? Math.max(1, Math.floor(config.autoTriggerEstTokens! * 0.9))
+ : undefined
+ );
+ let current = messages;
+ const stages: CompressionStageStats[] = [];
+ const enginesApplied: string[] = [];
+ const discardedByGate: string[] = [];
+
+ for (const engine of getRegisteredEngines()) {
+ if (!MODE_ENGINES[mode].has(engine.id)) continue;
+ // Adaptive requests stop as soon as the requested ceiling is met. Manual
+ // modes without a target still run their complete engine set.
+ if (targetTokens && messageChars(current) <= targetTokens * 4) break;
+ const engineConfig = config.engines[engine.id] ?? { enabled: true };
+ if (!engineConfig.enabled) {
+ stages.push({
+ engine: engine.id,
+ inputChars: messageChars(current),
+ outputChars: messageChars(current),
+ savedChars: 0,
+ applied: false,
+ discarded: 'disabled',
+ });
+ continue;
+ }
+
+ const inputChars = messageChars(current);
+ try {
+ const validated = engine.configSchema.safeParse({
+ ...engineConfig,
+ trustProjectFilters: config.trustProjectFilters,
+ });
+ if (!validated.success) throw new Error(`Invalid ${engine.id} configuration`);
+ const frozenMessageIndexes = engine.lossless
+ ? stableFrozen
+ : new Set([...stableFrozen, ...cacheFrozen]);
+ const result = engine.apply({
+ messages: current,
+ config: validated.data,
+ context: {
+ mode,
+ tools: options.tools,
+ targetTokens,
+ frozenMessageIndexes,
+ toolCallOrigins: buildToolCallOrigins(current),
+ },
+ });
+ const outputChars = messageChars(result.messages);
+ if (outputChars === inputChars) {
+ stages.push({
+ engine: engine.id,
+ inputChars,
+ outputChars,
+ savedChars: 0,
+ applied: false,
+ discarded: 'unchanged',
+ details: result.details,
+ });
+ continue;
+ }
+ const fidelity = checkFidelity(current, result.messages);
+ if (!fidelity.accepted) {
+ const discarded = fidelity.reason === 'inflation' ? 'inflation' : 'fidelity';
+ if (discarded === 'fidelity') discardedByGate.push(engine.id);
+ stages.push({
+ engine: engine.id,
+ inputChars,
+ outputChars,
+ savedChars: 0,
+ applied: false,
+ discarded,
+ fidelity: {
+ protectedTokenSurvival: fidelity.protectedTokenSurvival,
+ numericLiteralsPreserved: fidelity.numericLiteralsPreserved,
+ jsonKeySurvival: fidelity.jsonKeySurvival,
+ diffHunksPreserved: fidelity.diffHunksPreserved,
+ criticalLinesPreserved: fidelity.criticalLinesPreserved,
+ },
+ details: result.details,
+ });
+ continue;
+ }
+ current = result.messages;
+ enginesApplied.push(engine.id);
+ stages.push({
+ engine: engine.id,
+ inputChars,
+ outputChars,
+ savedChars: inputChars - outputChars,
+ applied: true,
+ fidelity: {
+ protectedTokenSurvival: fidelity.protectedTokenSurvival,
+ numericLiteralsPreserved: fidelity.numericLiteralsPreserved,
+ jsonKeySurvival: fidelity.jsonKeySurvival,
+ diffHunksPreserved: fidelity.diffHunksPreserved,
+ criticalLinesPreserved: fidelity.criticalLinesPreserved,
+ },
+ details: result.details,
+ });
+ } catch {
+ discardedByGate.push(engine.id);
+ stages.push({
+ engine: engine.id,
+ inputChars,
+ outputChars: inputChars,
+ savedChars: 0,
+ applied: false,
+ discarded: 'exception',
+ });
+ }
+ }
+
+ const compressedChars = messageChars(current);
+ const stats: CompressionRequestStats = {
+ originalChars,
+ compressedChars,
+ estOriginalTokens: estimateTokensFromChars(originalChars),
+ estCompressedTokens: estimateTokensFromChars(compressedChars),
+ estSavedTokens: Math.max(0, Math.floor((originalChars - compressedChars) / 4)),
+ enginesApplied,
+ discardedByGate,
+ durationMs: performance.now() - started,
+ stages,
+ };
+ if (options.recordStats !== false) recordCompressionStats(mode, stats);
+ return {
+ messages: current,
+ mode,
+ cacheKey: compressionConfigFingerprint(config, mode),
+ stats,
+ };
+}
+
+export function formatCompressionHeader(result: CompressionResult): string {
+ return `${result.mode}; saved~=${result.stats.estSavedTokens}`;
+}
+
+export function _clearPrefixFreezeForTesting(): void {
+ prefixOccurrences.clear();
+}
diff --git a/server/src/services/compression/preservation.ts b/server/src/services/compression/preservation.ts
new file mode 100644
index 00000000..24b37827
--- /dev/null
+++ b/server/src/services/compression/preservation.ts
@@ -0,0 +1,113 @@
+export type ProtectedKind =
+ | 'fenced-code'
+ | 'inline-code'
+ | 'url'
+ | 'path'
+ | 'json-key'
+ | 'number'
+ | 'stack-trace'
+ | 'diff-hunk'
+ | 'key-value'
+ | 'error'
+ | 'constraint';
+
+export interface ProtectedSpan {
+ start: number;
+ end: number;
+ text: string;
+ kinds: ProtectedKind[];
+}
+
+const RULES: Array<{ kind: ProtectedKind; regex: RegExp }> = [
+ { kind: 'fenced-code', regex: /```[\s\S]*?```/g },
+ { kind: 'inline-code', regex: /`[^`\n]+`/g },
+ { kind: 'url', regex: /\bhttps?:\/\/[^\s<>()]+/gi },
+ { kind: 'path', regex: /(?:\b[A-Za-z]:\\(?:[^\\\s:"<>|?*]+\\)*[^\\\s:"<>|?*]*|\B~?\/(?:[\w.@%+~=-]+\/)*[\w.@%+~=-]+|\B\.{1,2}\/(?:[\w.@%+~=-]+\/)*[\w.@%+~=-]+)/g },
+ { kind: 'json-key', regex: /"(?:\\.|[^"\\])+"\s*:/g },
+ { kind: 'number', regex: /(?<![\w])[-+]?(?:0[xX][0-9a-fA-F]+|\d+(?:\.\d+)?(?:[eE][-+]?\d+)?)(?![\w])/g },
+ { kind: 'stack-trace', regex: /^\s*at\s+.+$/gm },
+ { kind: 'diff-hunk', regex: /^@@[^\n]*@@[^\n]*$/gm },
+ { kind: 'key-value', regex: /\b[A-Za-z_][A-Za-z0-9_.-]*=(?:"[^"]*"|'[^']*'|[^\s]+)/g },
+ { kind: 'error', regex: /^.*\b(?:error|exception|fatal|failed|failure|traceback|panic)\b.*$/gim },
+ {
+ kind: 'constraint',
+ regex:
+ /^.*\b(?:must(?:\s+not)?|do\s+not|don't|never|always|require(?:d|ment|ments)?|constraint|important|warning|security|permission|authorization|forbidden|prohibited)\b.*$/gim,
+ },
+];
+
+export function mergeProtectedSpans(spans: ProtectedSpan[]): ProtectedSpan[] {
+ const ordered = spans
+ .filter(span => span.end > span.start)
+ .sort((a, b) => a.start - b.start || b.end - a.end);
+ const merged: ProtectedSpan[] = [];
+ for (const span of ordered) {
+ const previous = merged[merged.length - 1];
+ if (!previous || span.start > previous.end) {
+ merged.push({ ...span, kinds: [...new Set(span.kinds)] });
+ continue;
+ }
+ previous.end = Math.max(previous.end, span.end);
+ previous.kinds = [...new Set([...previous.kinds, ...span.kinds])];
+ }
+ return merged;
+}
+
+export function scanProtectedSpans(text: string): ProtectedSpan[] {
+ const spans: ProtectedSpan[] = [];
+ for (const rule of RULES) {
+ rule.regex.lastIndex = 0;
+ for (const match of text.matchAll(rule.regex)) {
+ if (match.index == null || !match[0]) continue;
+ spans.push({
+ start: match.index,
+ end: match.index + match[0].length,
+ text: match[0],
+ kinds: [rule.kind],
+ });
+ }
+ }
+ return mergeProtectedSpans(spans).map(span => ({ ...span, text: text.slice(span.start, span.end) }));
+}
+
+export function transformUnprotectedText(text: string, transform: (part: string) => string): string {
+ const spans = scanProtectedSpans(text);
+ if (spans.length === 0) return transform(text);
+ const placeholders: string[] = [];
+ let masked = '';
+ let cursor = 0;
+ spans.forEach((span, index) => {
+ const placeholder = `\uE000${index.toString(36)}\uE001`;
+ placeholders.push(text.slice(span.start, span.end));
+ masked += text.slice(cursor, span.start);
+ masked += placeholder;
+ cursor = span.end;
+ });
+ masked += text.slice(cursor);
+ // Restore in one pass \u2014 a per-placeholder `.replace()` rescans the whole
+ // string each time and turns span-heavy text quadratic.
+ return transform(masked).replace(
+ /\uE000([0-9a-z]+)\uE001/g,
+ (match, index: string) => placeholders[Number.parseInt(index, 36)] ?? match,
+ );
+}
+
+export function hasProtectedContent(text: string): boolean {
+ return scanProtectedSpans(text).length > 0;
+}
+
+export function protectedLines(text: string): string[] {
+ return text.split('\n').filter(line => scanProtectedSpans(line).length > 0);
+}
+
+export function extractProtectedValues(text: string, kind?: ProtectedKind): string[] {
+ const values: string[] = [];
+ if (!kind) return scanProtectedSpans(text).map(span => span.text);
+ const rule = RULES.find(entry => entry.kind === kind);
+ if (!rule) return values;
+ rule.regex.lastIndex = 0;
+ for (const match of text.matchAll(rule.regex)) {
+ if (match[0]) values.push(match[0]);
+ }
+ return values;
+}
diff --git a/server/src/services/compression/registry.ts b/server/src/services/compression/registry.ts
new file mode 100644
index 00000000..d6a8a96c
--- /dev/null
+++ b/server/src/services/compression/registry.ts
@@ -0,0 +1,20 @@
+import type { CompressionEngine } from './types.js';
+
+const engines = new Map<string, CompressionEngine>();
+
+export function registerEngine(engine: CompressionEngine): void {
+ if (engines.has(engine.id)) throw new Error(`Compression engine already registered: ${engine.id}`);
+ engines.set(engine.id, engine);
+}
+
+export function getEngine(id: string): CompressionEngine | undefined {
+ return engines.get(id);
+}
+
+export function getRegisteredEngines(): CompressionEngine[] {
+ return [...engines.values()].sort((a, b) => a.priority - b.priority || a.id.localeCompare(b.id));
+}
+
+export function _clearRegistryForTesting(): void {
+ engines.clear();
+}
diff --git a/server/src/services/compression/stats.ts b/server/src/services/compression/stats.ts
new file mode 100644
index 00000000..01d59076
--- /dev/null
+++ b/server/src/services/compression/stats.ts
@@ -0,0 +1,67 @@
+import type { CompressionMode, CompressionRequestStats } from './types.js';
+
+interface EngineAggregate {
+ applied: number;
+ discarded: number;
+ savedChars: number;
+}
+
+interface ModeAggregate {
+ requests: number;
+ savedChars: number;
+}
+
+let requests = 0;
+let compressedRequests = 0;
+let originalChars = 0;
+let compressedChars = 0;
+let totalDurationMs = 0;
+const engines = new Map<string, EngineAggregate>();
+const modes = new Map<CompressionMode, ModeAggregate>();
+
+export function recordCompressionStats(mode: CompressionMode, stats: CompressionRequestStats): void {
+ requests += 1;
+ if (stats.compressedChars < stats.originalChars) compressedRequests += 1;
+ originalChars += stats.originalChars;
+ compressedChars += stats.compressedChars;
+ totalDurationMs += stats.durationMs;
+ const modeRow = modes.get(mode) ?? { requests: 0, savedChars: 0 };
+ modeRow.requests += 1;
+ modeRow.savedChars += stats.originalChars - stats.compressedChars;
+ modes.set(mode, modeRow);
+ for (const stage of stats.stages) {
+ const row = engines.get(stage.engine) ?? { applied: 0, discarded: 0, savedChars: 0 };
+ if (stage.applied) row.applied += 1;
+ else if (stage.discarded && stage.discarded !== 'disabled' && stage.discarded !== 'unchanged') row.discarded += 1;
+ row.savedChars += stage.savedChars;
+ engines.set(stage.engine, row);
+ }
+}
+
+export function getCompressionStats() {
+ const savedChars = Math.max(0, originalChars - compressedChars);
+ return {
+ requests,
+ compressedRequests,
+ originalChars,
+ compressedChars,
+ estSavedTokens: Math.floor(savedChars / 4),
+ savingsPercent: originalChars > 0 ? Math.round((savedChars / originalChars) * 10_000) / 100 : 0,
+ avgDurationMs: requests > 0 ? Math.round((totalDurationMs / requests) * 100) / 100 : 0,
+ byMode: Object.fromEntries([...modes.entries()].map(([mode, row]) => [
+ mode,
+ { ...row, estSavedTokens: Math.floor(row.savedChars / 4) },
+ ])),
+ engines: Object.fromEntries([...engines.entries()].sort(([a], [b]) => a.localeCompare(b))),
+ };
+}
+
+export function clearCompressionStats(): void {
+ requests = 0;
+ compressedRequests = 0;
+ originalChars = 0;
+ compressedChars = 0;
+ totalDurationMs = 0;
+ engines.clear();
+ modes.clear();
+}
diff --git a/server/src/services/compression/types.ts b/server/src/services/compression/types.ts
new file mode 100644
index 00000000..a0bde24e
--- /dev/null
+++ b/server/src/services/compression/types.ts
@@ -0,0 +1,101 @@
+import type { ChatMessage, ChatToolDefinition } from '@freellmapi/shared/types.js';
+import type { ZodTypeAny } from 'zod';
+
+export const COMPRESSION_MODES = ['off', 'lossless', 'standard', 'aggressive'] as const;
+export type CompressionMode = (typeof COMPRESSION_MODES)[number];
+export type CompressionTarget = 'tool-results' | 'messages' | 'system';
+
+export interface CompressionEngineConfig {
+ enabled: boolean;
+ [key: string]: unknown;
+}
+
+export interface CompressionConfig {
+ mode: CompressionMode;
+ engines: Record<string, CompressionEngineConfig>;
+ autoTriggerEstTokens?: number;
+ targetTokens?: number;
+ trustProjectFilters: boolean;
+ prefixFreeze: boolean;
+}
+
+export interface ToolCallOrigin {
+ id: string;
+ name: string;
+ arguments: string;
+ messageIndex: number;
+}
+
+export interface EngineContext {
+ mode: CompressionMode;
+ tools?: ChatToolDefinition[];
+ targetTokens?: number;
+ frozenMessageIndexes: ReadonlySet<number>;
+ toolCallOrigins: ReadonlyMap<string, ToolCallOrigin>;
+}
+
+export interface EngineInput {
+ messages: ChatMessage[];
+ config: CompressionEngineConfig;
+ context: EngineContext;
+}
+
+export interface EngineOutput {
+ messages: ChatMessage[];
+ details?: Record<string, unknown>;
+}
+
+export interface CompressionEngine {
+ id: string;
+ priority: number;
+ lossless: boolean;
+ targets: CompressionTarget[];
+ configSchema: ZodTypeAny;
+ apply(input: EngineInput): EngineOutput;
+}
+
+export interface CompressionStageStats {
+ engine: string;
+ inputChars: number;
+ outputChars: number;
+ savedChars: number;
+ applied: boolean;
+ discarded?: 'exception' | 'fidelity' | 'inflation' | 'disabled' | 'unchanged';
+ fidelity?: {
+ protectedTokenSurvival: number;
+ numericLiteralsPreserved: boolean;
+ jsonKeySurvival: number;
+ diffHunksPreserved: boolean;
+ criticalLinesPreserved: boolean;
+ };
+ details?: Record<string, unknown>;
+}
+
+export interface CompressionRequestStats {
+ originalChars: number;
+ compressedChars: number;
+ estOriginalTokens: number;
+ estCompressedTokens: number;
+ estSavedTokens: number;
+ enginesApplied: string[];
+ discardedByGate: string[];
+ durationMs: number;
+ stages: CompressionStageStats[];
+}
+
+export interface CompressionResult {
+ messages: ChatMessage[];
+ mode: CompressionMode;
+ cacheKey: string;
+ stats: CompressionRequestStats;
+}
+
+export interface CompressRequestOptions {
+ header?: string | string[];
+ tools?: ChatToolDefinition[];
+ config?: CompressionConfig;
+ previewMode?: CompressionMode;
+ targetTokens?: number;
+ cacheControlPrefixLength?: number;
+ recordStats?: boolean;
+}