Commit graph

51 commits

Author SHA1 Message Date
Garm
dd509585b0 Merge remote-tracking branch 'origin/main' into feat/persist-savings-history 2026-03-31 10:57:36 +02:00
Garm
9a695249af feat: add historical rollups and exports 2026-03-31 10:25:45 +02:00
chopratejas
acf532bc55 Update Discord invite link across all docs 2026-03-30 22:04:05 -07:00
gglucass
165d3ca726
Merge branch 'main' into feat/persist-savings-history 2026-03-30 12:04:39 +02:00
Tejas Chopra
42ea085751
Merge pull request #60 from gglucass/feat/add-headroom-sdk
feat: allow overriding proxy telemetry sdk via HEADROOM_SDK
2026-03-29 18:21:13 -07:00
kunallohtia
9590dbc214 feat: add LangGraph compress_tool_messages node for ToolMessage compression 2026-03-29 17:11:15 -07:00
chopratejas
95f9e7a3e0 docs: add OpenClaw plugin to README, integration guide, index, and TS SDK docs 2026-03-29 00:02:05 -07:00
Garm
69080be966 feat: persist proxy savings history 2026-03-27 15:27:05 +01:00
Garm
8232e7822e feat: allow overriding proxy telemetry sdk via HEADROOM_SDK 2026-03-27 14:23:32 +01:00
chopratejas
72e65148d2 Add TypeScript SDK (headroom-ai npm package)
- New `compress()` function: HTTP client calling POST /v1/compress on the proxy
- HeadroomClient: reusable client with retry, fallback, auth support
- Vercel AI SDK adapter: headroomMiddleware() for wrapLanguageModel()
- OpenAI SDK adapter: withHeadroom() Proxy wrapper
- Anthropic SDK adapter: withHeadroom() Proxy wrapper
- Format converters: Vercel AI SDK ↔ OpenAI message format round-trip
- POST /v1/compress proxy endpoint: compression without LLM call
- 90 TypeScript tests (84 unit + 6 integration) + 9 Python tests
- Zero runtime dependencies, all framework peers optional
- Updated README, proxy docs, integration guide, and 6 other doc pages
- New docs/typescript-sdk.md with full SDK documentation
- Removed docs/superpowers/ from tracking (.gitignore)
2026-03-26 15:41:56 -07:00
chopratejas
0db650fd72 Revamp docs site: new theme, comprehensive landing page, complete nav
Theme:
- Deep purple + amber accent, Inter font, JetBrains Mono for code
- Sticky nav tabs, instant navigation, search sharing, progress bar
- Custom CSS: hero section, feature grid, stats bar, card hover effects
- Mermaid diagram support for architecture visualization

Landing page (index.md) rewrite:
- Stats bar: 87% reduction, 100% accuracy, 6 algorithms, 100+ providers
- Interactive quick-start tabs (proxy, SDK, coding agents, LiteLLM)
- Framework integration grid with code snippets (LangChain, Agno, Strands, MCP)
- Mermaid pipeline diagram showing ContentRouter routing logic
- Content type → compressor mapping table
- Full benchmark results table
- Feature cards linking to deep-dive docs

Navigation reorganized:
- All 29 doc pages now in nav (was 22, 7 orphaned)
- Logical grouping: Getting Started, User Guide, Integrations, How It Works,
  Benchmarks, Reference, Deployment
- Added: SharedContext, Learn, Limitations, Integration Guide overview

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-25 20:16:22 -07:00
chopratejas
c61ba522a3 Fix docs to match implementation: remove false claims, add Strands guide
- Remove CrewAI and OpenAI Agents SDK claims (not implemented)
- Upgrade LangChain from "Experimental" to "Stable" (fully implemented)
- Fix latency FAQ: "1-5ms" → accurate "15-200ms" with cost-benefit context
- Create docs/strands.md (README linked to it but file didn't exist)
- Align docs/index.md with compress() function API (was showing stale class API)
- Add Strands, MCP, Integration Guide to mkdocs nav
- Note stale v0.3.7 benchmarks in LATENCY_BENCHMARKS.md

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-25 20:04:35 -07:00
chopratejas
a399a9bb37 Add implementation plan for token headroom mode
11 tasks across 4 chunks: CompressionCache core, ProxyConfig/pipeline setup,
handler integration (Anthropic + OpenAI), and integration/E2E tests.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 09:30:26 -07:00
chopratejas
f9476a1c46 Update token headroom mode spec with review fixes
Address spec review findings: fix protect_recent_fraction plumbing (set at
startup, not per-call kwarg), clarify Zone 3 scope (excluded-tool messages
only), fix frozen count to treat user/assistant as stable, increase cache
to 10K entries, add observability section, define update_from_result contract,
handle force_compress_threshold interaction, add mode-switch and latency
edge cases.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 09:15:15 -07:00
chopratejas
42883c555d Add design spec for token headroom mode
Introduces dual-mode optimization (cost_savings vs token_headroom) to address
low compression rates in long Claude Code sessions caused by prefix freeze
consuming all messages.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 09:11:37 -07:00
chopratejas
6ab448800b Add SharedContext for multi-agent, rewrite README, fix proxy cleanup
- SharedContext: compressed inter-agent context sharing via put()/get()
over existing CCR compression pipeline. Zero new dependencies.
- README rewrite: lead with "any agent" positioning, not just coding
agents. Add headroom wrap, SharedContext, MCP tools to Quick Start.
Reorder integration table: universal first, coding shortcuts last.
Update compression pipeline references (LLMLingua → Kompress).
- Fix proxy cleanup in headroom wrap: don't kill shared proxy if other
clients are still using it (was orphaning terminals 2-N).
- New docs: docs/shared-context.md
2026-03-17 16:31:04 -07:00
chopratejas
891d4d0cad Updated README and mcp docs 2026-03-16 23:15:03 -07:00
Long Ngo
693deb4d58 fix(docs): fix Docker example and document hnswlib C++ build requirement
The Docker example in proxy.md used the wrong package name and lacked
build-essential, causing install failures on slim images. hnswlib (a
core dependency) requires a C++ compiler to build from source.

- Fix proxy.md Docker example: headroom[proxy] -> headroom-ai[proxy],
  add build-essential install/cleanup pattern
- Add troubleshooting entry for C++ compilation errors with solutions
  for Linux and macOS environments

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-02 14:46:14 -06:00
Long Ngo
180b4ef05a fix: remove hnswlib from core deps and fix package name in docs
hnswlib requires C++ compilation and is only used by the memory
subsystem - it belongs in the [memory] extra, not core dependencies.
Installing headroom-ai on slim Docker images or any environment
without build tools would fail at the hnswlib build step.

Also fixes docs/quickstart.md and docs/troubleshooting.md which
referenced the wrong PyPI package name `headroom` (an unrelated
package) instead of `headroom-ai`.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-02 10:11:16 -06:00
chopratejas
17442c2dcc Add headroom learn: offline failure learning for coding agents
Analyzes past conversation history to find tool call failure patterns,
correlates each failure with what eventually succeeded, and writes
specific project-level learnings to CLAUDE.md and MEMORY.md.

Key design:
- Success correlation: extracts the diff between failed and successful
  inputs as the learning (not generic advice)
- Generic architecture: tool-agnostic ToolCall model with pluggable
  Scanner/Writer adapters (Claude Code first, extensible to Cursor/Codex)
- 5 analyzers: Environment, Structure, Commands, Retries, Cross-Session
- Dry-run by default, --apply to write, --all for all projects

Also fixes mypy errors in litellm_callback, asgi, langchain chat_model,
and anthropic provider (AsyncClient typing, ToolCall arg-type, int cast).
2026-02-27 21:19:03 -08:00
chopratejas
a2b2ec5463 Add OSS evaluation suite, universal JSON crush, latency benchmarks
Evaluation Suite:
- Tiered eval framework (Tier 1 ~$3/15min, Tier 2/3 for extended coverage)
- 16 benchmarks across 3 tiers: GSM8K, TruthfulQA, MMLU, ARC, HumanEval,
  SQuAD v2, BFCL, Tool Outputs, CCR needle retention, HotpotQA, and more
- Before/After runner with full proxy support (compression + CCR retrieval)
- LLM-as-judge for ground-truth comparison (BFCL function calling)
- Zero-cost compression-only runner (CCR needle retention, info retention)
- Cost tracker with per-model pricing and budget enforcement
- Report card generator (Markdown, JSON, HTML)
- Suite CLI: python -m headroom.evals suite --tier 1
- Fix BFCL dataset loader for current HuggingFace schema
- CI workflow: PR smoke test + weekly full Tier 1

Results: SQuAD 97%, BFCL 97%, Tool Outputs 100%, CCR 100%

SmartCrusher:
- Universal JSON crush for heterogeneous arrays
- Fix mypy redefinition warning in _crush_string_array

Other:
- Latency benchmark suite with docs
- Known limitations doc
- Prompt comparison evaluator
- Config updates for new features
2026-02-23 19:08:54 -08:00
chopratejas
3ebcd89d46 Rewrite README + add Integration Guide
README: 694 → 203 lines. Crisp, scannable, links to docs.
- compress() as the hero quickstart (not proxy)
- Integration table: compress(), LiteLLM, ASGI, proxy, Agno, LangChain
- LangChain marked as experimental
- "Already have a proxy?" callout linking to Integration Guide
- Architecture: ContentRouter (not SmartCrusher) as the primary compressor

New: docs/integration-guide.md
- Detailed setup for every integration path
- compress() with Anthropic, OpenAI, LiteLLM, raw HTTP
- LiteLLM callback + LiteLLM proxy ASGI middleware
- ASGI middleware for any FastAPI/Starlette app
- Compression hooks for advanced customization
- FAQ section

Fix: compress() uses default pipeline (CacheAligner + ContentRouter +
IntelligentContext) instead of manually specifying SmartCrusher.
2026-02-19 10:17:33 -08:00
chopratejas
fe2e30a7ef Add MCP CLI for Claude Code subscription users
- Add `headroom mcp install` to configure ~/.claude/mcp.json
- Add `headroom mcp uninstall` to remove configuration
- Add `headroom mcp status` to check setup
- Add `headroom mcp serve` for MCP server (called by Claude Code)
- Add `mcp` optional dependency in pyproject.toml
- Add docs/mcp.md with full documentation
- Add 22 integration tests for MCP CLI
- Fix mypy errors in trained_router.py (None check, type annotation)
- Update README with subscription user instructions

This enables CCR (Compress-Cache-Retrieve) for subscription users who
don't have API access. MCP is Claude's official extension mechanism
that works with subscriptions.

Usage:
  pip install "headroom-ai[mcp]"
  headroom mcp install
  headroom proxy  # Terminal 1
  claude          # Terminal 2
2026-02-02 11:05:24 -08:00
chopratejas
bbbf0c5a7e Fix mypy errors in html_extraction.py
Rename client/response variables to be unique per provider branch
to avoid type inference conflicts. Use getattr for Anthropic content
block text access to handle union types.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-31 10:16:41 -08:00
chopratejas
d291710176 Add MkDocs GitHub Pages documentation site
- Add mkdocs.yml with Material theme (indigo, professional)
- Add docs/index.md landing page with quick install
- Add GitHub Actions workflow for auto-deployment
- Remove old docs/README.md (replaced by index.md)
2026-01-30 20:33:29 -08:00
chopratejas
83c0334ccd docs: update documentation for IntelligentContext TOIN + CCR integration
Updates across multiple docs to reflect the new message-level compression
with TOIN + CCR integration:

- docs/ccr.md: Add CCR-enabled components table, message-level CCR section
- docs/ARCHITECTURE.md: Expand Transform 6 with TOIN + CCR integration details
- docs/configuration.md: Add CCR integration config and marker format
- docs/proxy.md: Add CCR integration note for context management
- docs/README.md: Update to reference IntelligentContextManager as default

Also adds examples/test_intelligent_context_toin_ccr.py for scale testing
the TOIN + CCR integration with real API calls.
2026-01-27 16:08:36 -08:00
chopratejas
fef02fa053 feat(toin): add TOIN + CCR integration to IntelligentContextManager
IntelligentContext is a message-level compressor that drops low-value
messages. This change adds bidirectional TOIN integration:

- Dropped messages stored in CCR for potential retrieval
- Drops recorded to TOIN for cross-user learning
- Retrieval feedback improves future importance scoring

When messages are dropped and users retrieve them via CCR, TOIN learns
to score those patterns higher next time. This creates a feedback loop
that improves drop decisions across all users.

Changes:
- Add _create_message_signature() for TOIN pattern tracking
- Add _get_compression_store() for CCR integration
- Add _store_dropped_in_ccr() to store dropped messages
- Add _record_drops_to_toin() to record drops for learning
- Update marker to include CCR reference when available
- Update docs with TOIN + CCR integration section
- Update tests to accept both marker formats
2026-01-27 16:08:36 -08:00
chopratejas
4f9a3d1e05 feat(toin): extend TOIN integration to all ContentRouter compression strategies
Previously, only SmartCrusher (JSON arrays) recorded compressions to TOIN.
Now all compression strategies record to TOIN for cross-user learning:

- CODE_AWARE: AST-based code compression
- SEARCH: grep/ripgrep results
- LOG: build/test output
- LLMLINGUA: ML-based text compression
- TEXT: heuristic text compression

Changes:
- Add _create_content_signature() for non-JSON content types
- Add _record_to_toin() method to ContentRouter
- Update _apply_strategy_to_content() to record after compression
- Update docs/transforms.md with TOIN integration section

This enables the feedback loop where TOIN learns from retrieval patterns
across all content types, not just JSON arrays.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-01-27 16:08:36 -08:00
Tejas Chopra
2fd9552102 Add image token compression with trained ML router
Introduces automatic image compression for LLM requests, reducing token
usage by 40-90% while maintaining answer accuracy.

Key features:
- Trained MiniLM classifier (93.7% accuracy) hosted on HuggingFace
- SigLIP-based image analysis for content-aware routing
- Provider-specific compression:
  - OpenAI: detail="low" parameter
  - Anthropic: PIL resize to 512px
  - Google: PIL resize to 768px (tile-optimized)
- Four compression techniques: full_low, preserve, crop, transcode
- Integration in both Headroom proxy and SDK (ContentRouter)

New files:
- headroom/image/ module with ImageCompressor API
- docs/image-compression.md user documentation
- tests/test_image_compressor.py (51 tests)

Model: chopratejas/technique-router on HuggingFace (~128MB)
2026-01-25 22:40:43 -08:00
chopratejas
0b3e4d2586 Remove hardcoded source hint system from ContentRouter
ContentRouter now routes purely based on content analysis instead of
relying on hardcoded tool name mappings. This makes the router work
with any MCP tool regardless of naming convention.

Changes:
- Remove generate_source_hint() function and _strategy_from_hint() method
- Remove source_hint parameter from compress() method
- Remove _get_tool_source_hint() from IntelligentContextManager
- Update tests to remove source hint test cases
- Update docs to document content detection approach
2026-01-23 00:28:22 -08:00
chopratejas
8c88d49172 Update memory documentation for HierarchicalMemory system
- Update Quick Start to use with_memory() API (replaces with_fast_memory)
- Add hierarchical scoping section (USER → SESSION → AGENT → TURN)
- Add temporal versioning section with supersession examples
- Add comparison with state of the art (Letta, Mem0) with feature matrices
- Document Memory API for direct access (.memory.search, .add, .get_all)
- Add advanced HierarchicalMemory API usage examples
- Update configuration options for embedders and storage
- Add protocol-based architecture diagram
- Update memory categories (PREFERENCE, FACT, CONTEXT, ENTITY, DECISION, INSIGHT)
- Add troubleshooting and best practices sections
2026-01-22 23:37:14 -08:00
chopratejas
2292724ff7 Add dynamic anchor selection with content deduplication
Replace static "first 3 + last 2" preservation with intelligent anchor
selection that adapts to data patterns and array size.

Key changes:
- Add AnchorSelector class for dynamic position-based preservation
- Add AnchorConfig for configurable anchor allocation (budget ratio,
  strategy weights, information density scoring)
- Add content-based deduplication to prevent wasting slots on identical
  items using SHA256 hashing
- Add _fill_remaining_slots() to maximize output when dedup reduces items
- Support data pattern detection (TIME_SERIES, SEARCH_RESULTS, LOGS, GENERIC)
- Support query-aware anchor adjustment for back-heavy patterns

Enterprise hardening:
- Thread-safe: No shared state modified
- O(n) performance for dedup and slot filling
- Fault-tolerant serialization with fallbacks
- Configurable via dedup_identical_items flag

52 tests covering adversarial positions, size adaptation, pattern-aware
anchoring, query-aware selection, information density, coverage metrics,
edge cases, and preservation guarantees.
2026-01-21 00:19:05 -08:00
chopratejas
cd5ea2ea1d Add architecture diagrams to README and docs 2026-01-20 00:44:55 -08:00
Tejas Chopra
f5ffba61a7 Merge pull request #8 from nicolabeghin/proxy-custom-openai-api-url
Add OpenAI API URL override option
2026-01-19 17:58:11 -08:00
Tejas Chopra
18e01a0480 Merge pull request #6 from smartwatermelon/claude/docs-macos-deployment-20260119
Add macOS LaunchAgent deployment guide and templates
2026-01-19 17:52:25 -08:00
Nicola Beghin
f59690a7a7 docs update 2026-01-19 23:35:16 +01:00
Claude Code Bot
3ac26207b8 docs(deployment): add macOS LaunchAgent deployment guide and templates
Add comprehensive macOS deployment support for running headroom proxy as a
persistent background service using LaunchAgent. This enables automatic startup,
crash recovery, and proper lifecycle management for local development environments.

Files added:
- examples/deployment/macos-launchagent/com.headroom.proxy.plist.template
- examples/deployment/macos-launchagent/install.sh (shellcheck-clean)
- examples/deployment/macos-launchagent/uninstall.sh (shellcheck-clean)
- examples/deployment/macos-launchagent/shell-integration.sh (bash + zsh)
- examples/deployment/macos-launchagent/README.md
- docs/macos-deployment.md

Key features:
- Configurable port via HEADROOM_PROXY_PORT environment variable (default: 8787)
- Automated installation and uninstallation scripts
- Shell integration supporting both bash and zsh
- Comprehensive documentation with troubleshooting guide
- All shell scripts are shellcheck-clean (zero errors, warnings, or info messages)

Files modified:
- .gitignore: Added CLAUDE.md to prevent committing local config
- docs/README.md: Added Deployment & Operations section with navigation entry

AI review: Pending (will be run by pre-commit hook)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-19 13:34:52 -08:00
chopratejas
14ecab6bfa Add IntelligentContextManager for semantic-aware context management
- Add multi-factor importance scoring (recency, semantic similarity,
  TOIN importance, error indicators, forward references, token density)
- No hardcoded patterns - all signals learned from TOIN or computed
- Add ScoringWeights and IntelligentContextConfig dataclasses
- Add MessageScorer for scoring individual messages
- Add strategy selection: NONE, COMPRESS_FIRST, DROP_BY_SCORE
- Preserve tool call/response atomicity when dropping
- Add comprehensive tests (62 tests total)
- Update documentation (transforms, configuration, api, architecture)
2026-01-18 22:22:48 -08:00
chopratejas
0b945cf862 Add feature coverage and known limitations to Agno docs
Documents what the integration optimizes (messages, tool calls, streaming)
and what operates outside the optimization boundary (agent memory, knowledge
bases, agent teams). Includes best practices and future improvement plans.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-16 16:25:31 -08:00
chopratejas
aaaca9fa6a Add Agno integration documentation
- Update README.md with Agno quickstart and framework integration
- Create comprehensive docs/agno.md guide covering:
  - Model wrapping with HeadroomAgnoModel
  - Observability hooks (HeadroomPreHook, HeadroomPostHook)
  - Multi-provider auto-detection
  - Real-world examples and configuration reference
- Update docs/README.md index with Agno link
2026-01-16 16:17:14 -08:00
chopratejas
31aa72c885 Add universal compression module with ML-based content detection
- Add headroom.compression module with UniversalCompressor
- ML-based content detection using Magika (JSON, code, logs, text)
- Structure-preserving compression via handler protocol
- JSON handler: preserves keys, brackets, high-entropy values (UUIDs)
- Code handler: preserves imports, signatures, types (tree-sitter AST)
- Entropy-based preservation for identifiers and hashes
- CCR integration for reversible compression
- Comprehensive test suite with LLM eval tests
- Add docs/compression.md with full API documentation
2026-01-15 15:26:14 -08:00
chopratejas
9c9bb30ded Add persistent memory system with zero-latency inline extraction
Features:
- with_fast_memory(): Zero-latency inline extraction (Letta-style)
  - Memory extracted as part of LLM response, no extra API calls
  - Semantic retrieval with local embeddings (sub-50ms)
- with_memory(): Background extraction for non-blocking memory
- SQLite + FTS5 storage with vector similarity search
- Multi-user isolation by user_id

Memory enables temporal compression - extract key facts instead of
carrying full conversation history (4000 tokens → 50 tokens).

Includes:
- Comprehensive test suite (71 new tests)
- Documentation (docs/memory.md)
- Benchmark examples comparing approaches
- E2E test with LLM-as-judge evaluation
2026-01-14 21:32:09 -08:00
chopratejas
bb041047c8 Add seamless LangChain integration
- Add HeadroomChatModel wrapper with auto provider detection (OpenAI, Anthropic, Google)
- Add HeadroomChatMessageHistory for automatic conversation compression
- Add HeadroomDocumentCompressor for retriever integration
- Add wrap_tools_with_headroom() for agent tool output compression
- Add async support (ainvoke, astream)
- Add LangSmith integration for observability
- Restructure integrations package into nested langchain/ and mcp/ subpackages
- Fix Pydantic v2 deprecation warning
- Add comprehensive docs/langchain.md guide with real-world examples
- Update README with LangChain quickstart and framework integrations

Bump version to 0.2.3
2026-01-14 16:03:34 -08:00
chopratejas
905c229251 Add AST-based code compression and custom model configuration
CodeAwareCompressor:
- Tree-sitter based AST parsing for Python, JS, TS, Go, Rust, Java, C, C++
- Preserves imports, signatures, type annotations, error handlers
- Guarantees syntactically valid output
- Uses tree-sitter-language-pack for broad language support

ContentRouter:
- Intelligent compression orchestrator
- Auto-routes content to optimal compressor based on type detection
- Source hint support for high-confidence routing

Custom Model Configuration:
- HEADROOM_MODEL_LIMITS env var and ~/.headroom/models.json support
- Pattern-based inference for unknown models (opus/sonnet/haiku tiers)
- Support for Claude 4.5, Claude 4, o3, o3-mini
- Graceful fallback - never crashes on unknown models
2026-01-14 13:46:55 -08:00
chopratejas
d724f14022 v0.2.2: Add CCR Response Handler, Context Tracker, and restructure docs
Features:
- CCR Response Handler: Automatically intercepts and handles headroom_retrieve tool calls
- CCR Context Tracker: Multi-turn awareness with proactive expansion of relevant compressed content
- New CCR demo script showing before/after flow

Documentation:
- Restructured README from 885 lines to 190 lines for better DevEx
- Split detailed docs into focused guides: ccr.md, sdk.md, configuration.md,
  text-compression.md, llmlingua.md, metrics.md, errors.md
- Updated docs/README.md index with all new documentation

Tests:
- Added comprehensive tests for Response Handler (32 tests)
- Added comprehensive tests for Context Tracker (32 tests)
- All 977 tests passing
2026-01-14 13:03:41 -08:00
chopratejas
45633b69ab Add LLMLingua-2 opt-in support to proxy server
Integrate Microsoft's LLMLingua-2 ML-based compression as an opt-in
feature for the proxy server, with excellent developer experience.

Features:
- New CLI flags: --llmlingua, --llmlingua-device, --llmlingua-rate
- ProxyConfig options: llmlingua_enabled, llmlingua_device, llmlingua_target_rate
- Smart startup hints when llmlingua is available but not enabled
- Helpful error messages when enabled but not installed
- LLMLinguaCompressor inserted before RollingWindow in pipeline

Why opt-in:
- Heavy dependencies (~2GB torch, transformers)
- 10-30s cold start for model loading
- ~1GB RAM when loaded
- Default proxy stays lightweight (<5ms overhead)

Tests:
- 26 new tests in test_proxy_llmlingua.py covering config, setup,
  banner status, CLI args, DevEx messages, and edge cases

Documentation:
- Updated README.md with proxy integration section
- Updated docs/proxy.md with LLMLingua CLI options
- Updated docs/transforms.md with LLMLinguaCompressor reference
- Updated docs/ARCHITECTURE.md with pipeline and file structure
- Updated CHANGELOG.md with new feature
2026-01-14 12:21:51 -08:00
chopratejas
bf779b54e6 Fix all mypy type errors and flaky embedding test
- Fix 34 mypy errors across 17 files with type annotations and casts
- Add type: ignore comments for legitimate dynamic patterns
- Handle None operands with (value or 0) pattern
- Cast return values to proper types (int, float, str, bool)
- Add EstimatingTokenCounter imports where needed
- Use getattr() for potentially missing attributes
- Fix flaky test_paraphrase_match with more distinct semantic examples
- Add mlx to mypy ignore list (broken third-party stubs)
2026-01-10 18:27:33 -08:00
chopratejas
e4a41faa33 Fix all ruff lint and format errors for CI
- Fix E402: Move module-level imports to top of file
- Fix F401: Add noqa for availability check imports
- Fix F402: Rename loop variables shadowing imports
- Fix E722: Replace bare except with except Exception
- Fix B904: Add exception chaining (from e)
- Fix F811: Remove duplicate imports
- Fix B027: Add noqa for empty close() method
- Fix E741: Rename ambiguous variable l -> label
- Fix I001: Import sorting issues
- Apply ruff format to all 106 files

All 902 tests pass.
2026-01-10 15:33:44 -08:00
chopratejas
90d3aea44c Publish headroom-ai v0.2.0 to PyPI with DevEx fixes
- Renamed package from 'headroom' to 'headroom-ai' (PyPI name conflict)
- Fixed numpy/jinja2 imports to be lazy (core install no longer crashes)
- Fixed SQLite default path (now uses temp directory)
- Fixed f-string {tool} crash in proxy server
- Updated README with correct package name and examples
- Added quickstart and troubleshooting docs

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-10 14:51:08 -08:00
chopratejas
c1feb60595 feat: Add CCR architecture, TOIN telemetry, and DevEx improvements
## Core Features

### Compress-Cache-Retrieve (CCR) Architecture
- Implement reversible compression with automatic retrieval support
- Add CompressionStore for caching original content with TTL-based eviction
- Add CompressionFeedback for learning from retrieval patterns
- Implement tool injection for LLM retrieval capability
- Add MCP server support for CCR operations
- Track retrieval rates to dynamically adjust compression aggressiveness

### Tool Output Intelligence Network (TOIN)
- Implement cross-session pattern learning for tool compression
- Add ToolSignature for structural hashing of tool outputs
- Track compression success rates per strategy (top_n, sample, truncate, etc.)
- Implement privacy-preserving telemetry with SHA256 hashing
- Add persistent storage with JSON file backend
- Support network-effect learning across tool types

### SmartCrusher Enhancements
- Add crushability analysis with variance/uniqueness detection
- Implement statistical anomaly detection for outlier preservation
- Add relevance-based item prioritization using BM25 scoring
- Support multiple compression strategies with quality retention
- Add change point detection for time-series data
- Implement constant factoring for homogeneous datasets

## Developer Experience Improvements

### Exception Hierarchy
- Add HeadroomError base class for all custom exceptions
- Add specific exceptions: ConfigurationError, ProviderError,
  StorageError, CompressionError, TokenizationError, CacheError,
  ValidationError, TransformError

### Client Enhancements
- Add validate_setup() for configuration verification
- Add get_stats() for in-memory session metrics without DB query
- Track session statistics (requests, tokens saved, cache hits)

### Logging Infrastructure
- Add structured logging to TransformPipeline with token savings
- Add logging to RollingWindow for dropped message tracking
- Add logging to ToolCrusher for compression events
- Add logging to CacheAligner for cache hit/miss detection
- Add logging to SmartCrusher for strategy selection

## Bug Fixes (from deep analysis)

### Critical Fixes
- Fix eviction heap memory leak with stale entry tracking
- Fix hash collision detection in compression store
- Fix strategy truncation desync in TOIN
- Fix non-deterministic set truncation with sorted iteration
- Fix race conditions in lazy initialization with proper locking
- Fix user count double-counting in TOIN metrics

### High Priority Fixes
- Fix unbounded strategy_success_rates growth with LRU eviction
- Fix mutable pattern references with defensive copying
- Fix lock held during file I/O with copy-then-write pattern
- Fix state divergence on eviction with success event recording
- Fix TOIN skip check order for CPU efficiency
- Fix preserve_fields type mismatch (set vs list)
- Fix prioritize_indices exceeding max_items limit
- Fix instance ID collision risk (32-bit to 64-bit hash)

## Testing

- Add comprehensive test suites for CCR, TOIN, and telemetry
- Add crushability detection tests
- Add quality retention tests for compression
- Add integration tests for cross-component data flow
- All 902 tests passing
2026-01-10 10:12:13 -08:00