Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

Add TypeScript SDK (headroom-ai npm package)

chopratejas72e65148d2b6
diff --git a/.gitignore b/.gitignore
index 55998c130..43baf592e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -176,5 +176,8 @@ CLAUDE.md
# Vitals provenance data
.vitals/
+# Superpowers working files (plans, specs, brainstorming)
+docs/superpowers/
+
# Managed platform (separate private repo)
headroom-managed/
diff --git a/README.md b/README.md
index 3d0724925..004dd32e7 100644
--- a/README.md
+++ b/README.md
@@ -7,7 +7,7 @@
Every tool call, DB query, file read, and RAG retrieval your agent makes is 70-95% boilerplate.<br>
Headroom compresses it away before it hits the model.<br><br>
Works with <b>any agent</b> — coding agents (Claude Code, Codex, Cursor, Aider), custom agents<br>
- (LangChain, LangGraph, Agno, Strands), or your own Python code.
+ (LangChain, LangGraph, Agno, Strands), or your own Python and TypeScript code.
</p>
</p>
@@ -24,6 +24,9 @@
<a href="https://pypistats.org/packages/headroom-ai">
<img src="https://img.shields.io/pypi/dm/headroom-ai.svg" alt="Downloads">
</a>
+ <a href="https://www.npmjs.com/package/headroom-ai">
+ <img src="https://img.shields.io/npm/v/headroom-ai.svg" alt="npm">
+ </a>
<a href="https://github.com/chopratejas/headroom/blob/main/LICENSE">
<img src="https://img.shields.io/badge/license-Apache%202.0-blue.svg" alt="License">
</a>
@@ -46,7 +49,7 @@ Your Agent / App
│
│ tool calls, logs, DB reads, RAG results, file reads, API responses
▼
- Headroom ← proxy, Python library, or framework integration
+ Headroom ← proxy, Python/TypeScript SDK, or framework integration
│
▼
LLM Provider (OpenAI, Anthropic, Google, Bedrock, 100+ via LiteLLM)
@@ -69,12 +72,19 @@ Headroom optimizes any data your agent injects into a prompt:
## Quick Start
+**Python:**
```bash
pip install "headroom-ai[all]"
```
+**TypeScript / Node.js:**
+```bash
+npm install headroom-ai
+```
+
### Any agent — one function
+**Python:**
```python
from headroom import compress
@@ -83,7 +93,16 @@ response = client.messages.create(model="claude-sonnet-4-5-20250929", messages=r
print(f"Saved {result.tokens_saved} tokens ({result.compression_ratio:.0%})")
```
-Works with any Python LLM client — Anthropic, OpenAI, LiteLLM, Bedrock, httpx, anything. Works with any agent framework — LangChain, LangGraph, Agno, Strands, or your own code.
+**TypeScript:**
+```typescript
+import { compress } from 'headroom-ai';
+
+const result = await compress(messages, { model: 'gpt-4o' });
+const response = await openai.chat.completions.create({ model: 'gpt-4o', messages: result.messages });
+console.log(`Saved ${result.tokensSaved} tokens`);
+```
+
+Works with any LLM client — Anthropic, OpenAI, LiteLLM, Bedrock, Vercel AI SDK, or your own code.
### Any agent — proxy (zero code changes)
@@ -136,6 +155,10 @@ Gives your AI tool three MCP tools: `headroom_compress`, `headroom_retrieve`, `h
| Your setup | Add Headroom | One-liner |
|------------|-------------|-----------|
| **Any Python app** | `compress()` | `result = compress(messages, model="gpt-4o")` |
+| **Any TypeScript app** | `compress()` | `const result = await compress(messages, { model: 'gpt-4o' })` |
+| **Vercel AI SDK** | Middleware | `wrapLanguageModel({ model, middleware: headroomMiddleware() })` |
+| **OpenAI Node SDK** | Wrap client | `const client = withHeadroom(new OpenAI())` |
+| **Anthropic TS SDK** | Wrap client | `const client = withHeadroom(new Anthropic())` |
| **Multi-agent** | SharedContext | `ctx = SharedContext(); ctx.put("key", data)` |
| **LiteLLM** | Callback | `litellm.callbacks = [HeadroomCallback()]` |
| **Any Python proxy** | ASGI Middleware | `app.add_middleware(CompressionMiddleware)` |
@@ -144,7 +167,7 @@ Gives your AI tool three MCP tools: `headroom_compress`, `headroom_retrieve`, `h
| **Claude Code** | Wrap | `headroom wrap claude` |
| **Codex / Aider** | Wrap | `headroom wrap codex` or `headroom wrap aider` |
-**[Full Integration Guide](docs/integration-guide.md)** — detailed setup for every framework.
+**[Full Integration Guide](docs/integration-guide.md)** | **[TypeScript SDK](docs/typescript-sdk.md)**
---
diff --git a/docs/api.md b/docs/api.md
index 6401c6779..69e60c08f 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -439,3 +439,11 @@ report = generate_report(
period="day",
)
```
+
+---
+
+## TypeScript SDK
+
+For the TypeScript SDK API reference, see [TypeScript SDK](typescript-sdk.md).
+
+The TypeScript SDK provides `compress()`, `HeadroomClient`, and framework adapters for Vercel AI SDK, OpenAI, and Anthropic.
diff --git a/docs/configuration.md b/docs/configuration.md
index ae64888e7..fcd7c7281 100644
--- a/docs/configuration.md
+++ b/docs/configuration.md
@@ -419,3 +419,38 @@ if not result["valid"]:
for issue in result["issues"]:
print(f" - {issue}")
```
+
+---
+
+## TypeScript SDK Configuration
+
+The TypeScript SDK is configured via environment variables or constructor options.
+
+### Environment Variables
+
+| Variable | Description | Default |
+|----------|-------------|---------|
+| `HEADROOM_BASE_URL` | Base URL of the Headroom proxy or cloud API | `http://localhost:8787` |
+| `HEADROOM_API_KEY` | API key for Headroom Cloud authentication | - |
+
+### Usage
+
+```bash
+export HEADROOM_BASE_URL=http://localhost:8787
+export HEADROOM_API_KEY=your-api-key
+```
+
+```typescript
+import { HeadroomClient } from 'headroom-ai';
+
+// Reads from HEADROOM_BASE_URL and HEADROOM_API_KEY automatically
+const client = new HeadroomClient();
+
+// Or configure explicitly
+const client = new HeadroomClient({
+ baseUrl: 'http://localhost:8787',
+ apiKey: 'your-api-key',
+});
+```
+
+See the [TypeScript SDK Guide](typescript-sdk.md) for full configuration options.
diff --git a/docs/getting-started.md b/docs/getting-started.md
index 66c1e0ebe..464ee8504 100644
--- a/docs/getting-started.md
+++ b/docs/getting-started.md
@@ -4,6 +4,8 @@ This guide will help you get up and running with Headroom in under 5 minutes.
## Installation
+**Python:**
+
```bash
# Core package (minimal dependencies)
pip install headroom
@@ -18,6 +20,12 @@ pip install headroom[relevance]
pip install headroom[all]
```
+**TypeScript / Node.js:**
+
+```bash
+npm install headroom-ai
+```
+
## Quick Start: Proxy Mode (Recommended)
The easiest way to use Headroom is as a proxy server:
diff --git a/docs/index.md b/docs/index.md
index 08f9307d9..5096f2017 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -102,6 +102,18 @@ Headroom works as a **transparent proxy** (zero code changes), a **Python functi
Starts the proxy, points your tool at it, compresses everything automatically.
+=== "TypeScript SDK"
+
+ ```typescript
+ import { compress } from 'headroom-ai';
+
+ const result = await compress(messages, { model: 'claude-sonnet-4-5-20250929' });
+ // Use result.messages with any LLM client
+ console.log(`Saved ${result.tokensSaved} tokens`);
+ ```
+
+ Works with Vercel AI SDK, OpenAI Node SDK, and Anthropic TS SDK. [Full TS guide &rarr;](typescript-sdk.md)
+
=== "LiteLLM Callback"
```python
@@ -182,6 +194,20 @@ headroom mcp install && claude
</div>
+<div class="grid-item" markdown>
+
+### TypeScript SDK
+
+`compress()`, Vercel AI SDK middleware, OpenAI and Anthropic client wrappers.
+
+```bash
+npm install headroom-ai
+```
+
+[TypeScript SDK Guide &rarr;](typescript-sdk.md)
+
+</div>
+
</div>
[All integration patterns &rarr;](integration-guide.md){ .md-button }
@@ -346,8 +372,9 @@ Or via LiteLLM for 100+ providers (Together, Groq, Fireworks, Ollama, vLLM, etc.
## Installation
```bash
-pip install headroom-ai # Core library
+pip install headroom-ai # Core library (Python)
pip install "headroom-ai[all]" # Everything (recommended)
+npm install headroom-ai # TypeScript / Node.js
pip install "headroom-ai[proxy]" # Proxy server + MCP tools
pip install "headroom-ai[ml]" # ML compression (Kompress, requires torch)
pip install "headroom-ai[langchain]" # LangChain integration
diff --git a/docs/integration-guide.md b/docs/integration-guide.md
index fe3c8838d..011383795 100644
--- a/docs/integration-guide.md
+++ b/docs/integration-guide.md
@@ -13,6 +13,10 @@ You don't need to run the Headroom proxy. Headroom is a compression library that
| Agno agents | [Agno integration](#agno) | Wrap model |
| LangChain | [LangChain integration](#langchain) | Wrap model |
| Non-Python app | [Headroom proxy](#proxy) | HTTP |
+| TypeScript SDK | [`compress()`](#typescript-sdk) | `npm install headroom-ai` |
+| Vercel AI SDK | [`headroomMiddleware()`](#typescript-sdk) | Middleware adapter |
+| OpenAI Node SDK | [`withHeadroom()`](#typescript-sdk) | Client wrapper |
+| Anthropic TS SDK | [`withHeadroom()`](#typescript-sdk) | Client wrapper |
---
@@ -249,6 +253,18 @@ See [LangChain Guide](langchain.md) for details and known limitations.
---
+## TypeScript SDK
+
+For Node.js, Next.js, and any TypeScript/JavaScript application.
+
+```bash
+npm install headroom-ai
+```
+
+See the [TypeScript SDK Guide](typescript-sdk.md) for full documentation including Vercel AI SDK middleware, OpenAI SDK wrapper, and Anthropic SDK wrapper.
+
+---
+
## Compression Hooks (Advanced)
Customize compression behavior without modifying Headroom's code:
diff --git a/docs/proxy.md b/docs/proxy.md
index 2dc58091b..ef805df17 100644
--- a/docs/proxy.md
+++ b/docs/proxy.md
@@ -2,6 +2,8 @@
The Headroom proxy server is a production-ready HTTP server that applies context optimization to all requests passing through it.
+> **New:** The proxy now supports the [TypeScript SDK](typescript-sdk.md) via the `POST /v1/compress` endpoint, enabling compression-as-a-service for any HTTP client without calling an LLM.
+
## Starting the Proxy
```bash
@@ -120,6 +122,36 @@ POST /v1/messages
POST /v1/chat/completions
```
+### `POST /v1/compress`
+
+Compression-only endpoint. Compresses messages without calling any LLM. Used by the [TypeScript SDK](typescript-sdk.md) and any HTTP client that wants compression as a service.
+
+**Request:**
+```json
+{
+ "messages": [...], // OpenAI chat format
+ "model": "gpt-4o" // model name (for token counting)
+}
+```
+
+**Response:**
+```json
+{
+ "messages": [...], // compressed messages
+ "tokens_before": 15000,
+ "tokens_after": 3500,
+ "tokens_saved": 11500,
+ "compression_ratio": 0.23,
+ "transforms_applied": ["router:smart_crusher:0.35"],
+ "ccr_hashes": ["a1b2c3"]
+}
+```
+
+**Headers:**
+- `x-headroom-bypass: true` — skip compression, return messages as-is
+
+**Error responses:** 400 (missing fields), 401 (bad API key), 503 (compression failed)
+
## Using with Claude Code
```bash
diff --git a/docs/quickstart.md b/docs/quickstart.md
index 0da33cebe..86aec20dc 100644
--- a/docs/quickstart.md
+++ b/docs/quickstart.md
@@ -6,6 +6,8 @@ Get Headroom running in 5 minutes with these copy-paste examples.
## Installation
+**Python:**
+
```bash
# Core only (minimal dependencies)
pip install headroom-ai
@@ -17,6 +19,12 @@ pip install "headroom-ai[proxy]"
pip install "headroom-ai[all]"
```
+**TypeScript / Node.js:**
+
+```bash
+npm install headroom-ai
+```
+
---
## Option 1: Proxy Server (Zero Code Changes)
diff --git a/docs/superpowers/plans/2026-03-19-token-headroom-mode.md b/docs/superpowers/plans/2026-03-19-token-headroom-mode.md
deleted file mode 100644
index ca3e2bcd4..000000000
--- a/docs/superpowers/plans/2026-03-19-token-headroom-mode.md
+++ /dev/null
@@ -1,1230 +0,0 @@
-# Token Headroom Mode Implementation Plan
-
-> **For agentic workers:** REQUIRED: Use superpowers:subagent-driven-development (if subagents available) or superpowers:executing-plans to implement this plan. Steps use checkbox (`- [ ]`) syntax for tracking.
-
-**Goal:** Add a `HEADROOM_MODE=token_headroom` config that compresses older messages to extend session length, trading prefix cache cost savings for token reduction.
-
-**Architecture:** Content-addressed CompressionCache maps original message content hashes to compressed versions. On each turn, already-compressed messages are swapped from cache and re-frozen; newly aged-out messages are compressed by the existing ContentRouter pipeline; recent messages pass through unchanged. Works for all providers (Anthropic + OpenAI).
-
-**Tech Stack:** Python 3.11+, pytest, existing Headroom transforms (ContentRouter, CodeAwareCompressor, SmartCrusher, Kompress)
-
-**Spec:** `docs/superpowers/specs/2026-03-19-token-headroom-mode-design.md`
-
----
-
-## Chunk 1: CompressionCache Core + Unit Tests
-
-### Task 1: CompressionCache — Data Structure + Core Methods
-
-**Files:**
-- Create: `headroom/cache/compression_cache.py`
-- Test: `tests/test_compression_cache.py`
-
-- [ ] **Step 1: Write failing tests for CompressionCache core**
-
-Create `tests/test_compression_cache.py`:
-
-```python
-"""Tests for CompressionCache — content-addressed compression result cache."""
-
-import pytest
-
-from headroom.cache.compression_cache import CompressionCache
-
-
-class TestCompressionCacheStoreAndRetrieve:
- """Basic cache hit/miss behavior."""
-
- def test_cache_miss_returns_none(self):
- cache = CompressionCache()
- assert cache.get_compressed("nonexistent_hash") is None
-
- def test_store_and_retrieve(self):
- cache = CompressionCache()
- cache.store_compressed("abc123", "compressed content", tokens_saved=500)
- assert cache.get_compressed("abc123") == "compressed content"
-
- def test_different_content_different_hash(self):
- cache = CompressionCache()
- cache.store_compressed("hash_v1", "compressed v1", tokens_saved=100)
- cache.store_compressed("hash_v2", "compressed v2", tokens_saved=200)
- assert cache.get_compressed("hash_v1") == "compressed v1"
- assert cache.get_compressed("hash_v2") == "compressed v2"
-
- def test_overwrite_same_hash(self):
- cache = CompressionCache()
- cache.store_compressed("abc", "old", tokens_saved=100)
- cache.store_compressed("abc", "new", tokens_saved=200)
- assert cache.get_compressed("abc") == "new"
-
- def test_stats_tracking(self):
- cache = CompressionCache()
- cache.store_compressed("h1", "c1", tokens_saved=100)
- cache.store_compressed("h2", "c2", tokens_saved=200)
- stats = cache.get_stats()
- assert stats["entries"] == 2
- assert stats["total_tokens_saved"] == 300
-
-
-class TestCompressionCacheLRU:
- """LRU eviction when cache exceeds max_entries."""
-
- def test_eviction_at_max_entries(self):
- cache = CompressionCache(max_entries=3)
- cache.store_compressed("h1", "c1", tokens_saved=10)
- cache.store_compressed("h2", "c2", tokens_saved=10)
- cache.store_compressed("h3", "c3", tokens_saved=10)
- # h1 is oldest
- cache.store_compressed("h4", "c4", tokens_saved=10)
- assert cache.get_compressed("h1") is None # evicted
- assert cache.get_compressed("h4") == "c4" # newest
-
- def test_access_refreshes_lru(self):
- cache = CompressionCache(max_entries=3)
- cache.store_compressed("h1", "c1", tokens_saved=10)
- cache.store_compressed("h2", "c2", tokens_saved=10)
- cache.store_compressed("h3", "c3", tokens_saved=10)
- # Access h1 to make it recent
- cache.get_compressed("h1")
- # Now add h4 — h2 should be evicted (oldest untouched)
- cache.store_compressed("h4", "c4", tokens_saved=10)
- assert cache.get_compressed("h1") == "c1" # refreshed, still present
- assert cache.get_compressed("h2") is None # evicted
-```
-
-- [ ] **Step 2: Run tests to verify they fail**
-
-Run: `python -m pytest tests/test_compression_cache.py -v`
-Expected: FAIL — `ModuleNotFoundError: No module named 'headroom.cache.compression_cache'`
-
-- [ ] **Step 3: Write CompressionCache implementation**
-
-Create `headroom/cache/compression_cache.py`:
-
-```python
-"""Content-addressed compression cache for token headroom mode.
-
-Maps original content hashes to compressed versions. Used to avoid
-re-compressing the same content on every turn. Session-scoped.
-
-The cache is keyed by SHA-256 of original content. This means:
-- Same file content across turns = same hash = cache hit
-- Edited file = different hash = cache miss = fresh compression
-- Claude Code dropping a message = unused cache entry (LRU eviction)
-"""
-
-from __future__ import annotations
-
-import hashlib
-import logging
-import time
-from collections import OrderedDict
-from dataclasses import dataclass, field
-from typing import Any
-
-logger = logging.getLogger(__name__)
-
-
-@dataclass
-class CompressionCacheEntry:
- """A single cached compression result."""
-
- compressed: str
- tokens_saved: int
- created_at: float = field(default_factory=time.time)
-
-
-class CompressionCache:
- """Content-addressed cache of compressed message content.
-
- Maps content_hash → compressed_content. No position tracking —
- works purely on content identity. Handles Claude Code dropping
- messages gracefully (unused entries stay in cache until LRU eviction).
- """
-
- def __init__(self, max_entries: int = 10000):
- self.max_entries = max_entries
- self._cache: OrderedDict[str, CompressionCacheEntry] = OrderedDict()
- # Stats
- self._hits: int = 0
- self._misses: int = 0
-
- def get_compressed(self, content_hash: str) -> str | None:
- """Look up cached compression result. O(1).
-
- Returns compressed content or None if not cached.
- Refreshes LRU position on hit.
- """
- entry = self._cache.get(content_hash)
- if entry is None:
- self._misses += 1
- return None
- # Move to end (most recently used)
- self._cache.move_to_end(content_hash)
- self._hits += 1
- return entry.compressed
-
- def store_compressed(
- self, content_hash: str, compressed: str, tokens_saved: int
- ) -> None:
- """Cache a compression result.
-
- Args:
- content_hash: SHA-256 of the original content.
- compressed: The compressed content string.
- tokens_saved: Tokens saved by this compression.
- """
- if content_hash in self._cache:
- # Update existing entry, move to end
- self._cache[content_hash] = CompressionCacheEntry(
- compressed=compressed, tokens_saved=tokens_saved
- )
- self._cache.move_to_end(content_hash)
- else:
- self._cache[content_hash] = CompressionCacheEntry(
- compressed=compressed, tokens_saved=tokens_saved
- )
- # Evict oldest if over limit
- while len(self._cache) > self.max_entries:
- self._cache.popitem(last=False)
-
- def get_stats(self) -> dict[str, Any]:
- """Return cache statistics."""
- total_tokens_saved = sum(e.tokens_saved for e in self._cache.values())
- return {
- "entries": len(self._cache),
- "max_entries": self.max_entries,
- "hits": self._hits,
- "misses": self._misses,
- "hit_rate": round(
- self._hits / max(1, self._hits + self._misses) * 100, 1
- ),
- "total_tokens_saved": total_tokens_saved,
- }
-
- @staticmethod
- def content_hash(content: str | list) -> str:
- """Compute SHA-256 hash of message content.
-
- Handles both string content and Anthropic-format list content.
- """
- if isinstance(content, list):
- # Anthropic format: list of content blocks
- # Hash the text content of each block
- parts = []
- for block in content:
- if isinstance(block, dict):
- if block.get("type") == "text":
- parts.append(block.get("text", ""))
- elif block.get("type") == "tool_result":
- parts.append(str(block.get("content", "")))
- elif isinstance(block, str):
- parts.append(block)
- text = "\n".join(parts)
- elif isinstance(content, str):
- text = content
- else:
- text = str(content)
- return hashlib.sha256(text.encode("utf-8", errors="replace")).hexdigest()[:16]
-```
-
-- [ ] **Step 4: Run tests to verify they pass**
-
-Run: `python -m pytest tests/test_compression_cache.py -v`
-Expected: All 7 tests PASS
-
-- [ ] **Step 5: Commit**
-
-```bash
-git add headroom/cache/compression_cache.py tests/test_compression_cache.py
-git commit -m "feat: add CompressionCache with LRU eviction for token headroom mode"
-```
-
----
-
-### Task 2: CompressionCache — Frozen Count + Apply/Update Methods
-
-**Files:**
-- Modify: `headroom/cache/compression_cache.py`
-- Modify: `tests/test_compression_cache.py`
-
-- [ ] **Step 1: Write failing tests for frozen count and apply/update**
-
-Append to `tests/test_compression_cache.py`:
-
-```python
-class TestCompressionCacheFrozenCount:
- """Frozen count: consecutive stable messages from start."""
-
- def _make_msg(self, role: str, content: str) -> dict:
- return {"role": role, "content": content}
-
- def test_empty_cache_returns_zero(self):
- cache = CompressionCache()
- messages = [
- self._make_msg("user", "hello"),
- self._make_msg("assistant", "hi"),
- ]
- assert cache.compute_frozen_count(messages) == 0
-
- def test_user_assistant_always_stable(self):
- """User/assistant messages are always stable (never compressed)."""
- cache = CompressionCache()
- messages = [
- self._make_msg("user", "hello"),
- self._make_msg("assistant", "hi"),
- self._make_msg("user", "do something"),
- ]
- # No tool results, all user/assistant → all stable
- assert cache.compute_frozen_count(messages) == 3
-
- def test_tool_result_with_cache_hit_is_stable(self):
- cache = CompressionCache()
- tool_content = "file contents here..."
- h = CompressionCache.content_hash(tool_content)
- cache.store_compressed(h, "compressed file", tokens_saved=100)
-
- messages = [
- self._make_msg("user", "read file"),
- {"role": "assistant", "content": [{"type": "tool_use", "id": "t1", "name": "Read"}]},
- {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t1", "content": tool_content}]},
- ]
- # All 3 stable: user (always), assistant (always), tool_result (cache hit)
- assert cache.compute_frozen_count(messages) == 3
-
- def test_tool_result_cache_miss_stops_frozen(self):
- cache = CompressionCache()
- messages = [
- self._make_msg("user", "hello"),
- {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t1", "content": "uncached data"}]},
- self._make_msg("user", "continue"),
- ]
- # Message 0: user (stable), Message 1: tool_result (cache miss) → stop
- assert cache.compute_frozen_count(messages) == 1
-
- def test_frozen_count_with_dropped_messages(self):
- """If Claude Code drops a message, consecutive run may break."""
- cache = CompressionCache()
- content_a = "content A"
- content_b = "content B"
- cache.store_compressed(CompressionCache.content_hash(content_a), "ca", tokens_saved=10)
- # content_b NOT in cache (simulates a dropped/new message)
-
- messages = [
- self._make_msg("user", "hi"),
- {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t1", "content": content_a}]},
- {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t2", "content": content_b}]},
- ]
- # user (stable), tool_result_a (cache hit, stable), tool_result_b (cache miss, stop)
- assert cache.compute_frozen_count(messages) == 2
-
-
-class TestCompressionCacheApplyAndUpdate:
- """apply_cached swaps compressed content; update_from_result caches new compressions."""
-
- def _make_msg(self, role: str, content: str) -> dict:
- return {"role": role, "content": content}
-
- def test_apply_cached_swaps_tool_results(self):
- cache = CompressionCache()
- original_content = "long file content " * 100
- compressed = "short version"
- h = CompressionCache.content_hash(original_content)
- cache.store_compressed(h, compressed, tokens_saved=500)
-
- messages = [
- self._make_msg("user", "read file"),
- {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t1", "content": original_content}]},
- ]
- result = cache.apply_cached(messages)
- # First message unchanged (user)
- assert result[0] == messages[0]
- # Second message: tool_result content swapped
- tool_block = result[1]["content"][0]
- assert tool_block["content"] == compressed
-
- def test_apply_cached_preserves_uncached_messages(self):
- cache = CompressionCache()
- messages = [
- self._make_msg("user", "hello"),
- self._make_msg("assistant", "world"),
- ]
- result = cache.apply_cached(messages)
- assert result[0]["content"] == "hello"
- assert result[1]["content"] == "world"
-
- def test_apply_cached_never_adds_messages(self):
- """Critical invariant: output length == input length."""
- cache = CompressionCache()
- cache.store_compressed("orphan_hash", "orphan content", tokens_saved=10)
- messages = [self._make_msg("user", "hello")]
- result = cache.apply_cached(messages)
- assert len(result) == len(messages)
-
- def test_update_from_result_caches_changes(self):
- cache = CompressionCache()
- originals = [
- self._make_msg("user", "hello"),
- {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t1", "content": "original data"}]},
- ]
- compressed = [
- self._make_msg("user", "hello"), # unchanged
- {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t1", "content": "compressed data"}]},
- ]
- cache.update_from_result(originals, compressed)
-
- # Now the original content should be cached
- h = CompressionCache.content_hash("original data")
- assert cache.get_compressed(h) == "compressed data"
-
- def test_update_from_result_ignores_unchanged(self):
- cache = CompressionCache()
- originals = [self._make_msg("user", "hello")]
- compressed = [self._make_msg("user", "hello")] # same
- cache.update_from_result(originals, compressed)
- assert cache.get_stats()["entries"] == 0
-
- def test_apply_does_not_modify_original_messages(self):
- """apply_cached must not mutate the input message list."""
- cache = CompressionCache()
- content = "original file"
- h = CompressionCache.content_hash(content)
- cache.store_compressed(h, "compressed", tokens_saved=50)
-
- messages = [
- {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t1", "content": content}]},
- ]
- import copy
- original_copy = copy.deepcopy(messages)
- cache.apply_cached(messages)
- assert messages == original_copy # original not mutated
-```
-
-- [ ] **Step 2: Run tests to verify they fail**
-
-Run: `python -m pytest tests/test_compression_cache.py -v`
-Expected: FAIL — `AttributeError: 'CompressionCache' object has no attribute 'compute_frozen_count'`
-
-- [ ] **Step 3: Add compute_frozen_count, apply_cached, update_from_result to CompressionCache**
-
-Add these methods to `headroom/cache/compression_cache.py` in the `CompressionCache` class:
-
-```python
- def _is_tool_result_message(self, message: dict) -> bool:
- """Check if a message contains tool result content."""
- content = message.get("content")
- if isinstance(content, list):
- return any(
- isinstance(b, dict) and b.get("type") == "tool_result"
- for b in content
- )
- # OpenAI format: role == "tool"
- return message.get("role") == "tool"
-
- def _extract_tool_result_content(self, message: dict) -> str | None:
- """Extract the text content from a tool result message.
-
- Returns the content string, or None if not a tool result.
- """
- content = message.get("content")
- if isinstance(content, list):
- for block in content:
- if isinstance(block, dict) and block.get("type") == "tool_result":
- inner = block.get("content", "")
- if isinstance(inner, str):
- return inner
- if isinstance(inner, list):
- # Anthropic nested content blocks
- parts = []
- for sub in inner:
- if isinstance(sub, dict) and sub.get("type") == "text":
- parts.append(sub.get("text", ""))
- return "\n".join(parts) if parts else None
- return None
- # OpenAI format
- if message.get("role") == "tool" and isinstance(content, str):
- return content
- return None
-
- def compute_frozen_count(self, messages: list[dict]) -> int:
- """Count consecutive stable messages from the start.
-
- A message is stable if:
- - It's a user/assistant/system message (always stable, never compressed)
- - It's a tool_result with content that's in the cache (already compressed)
-
- First unstable message (tool_result with cache miss) stops the count.
- """
- count = 0
- for msg in messages:
- if self._is_tool_result_message(msg):
- content_str = self._extract_tool_result_content(msg)
- if content_str is not None:
- h = self.content_hash(content_str)
- if h not in self._cache:
- break # Cache miss — stop frozen prefix
- # User/assistant/system/tool_use OR tool_result with cache hit → stable
- count += 1
- return count
-
- def apply_cached(self, messages: list[dict]) -> list[dict]:
- """Swap cached compressed content into tool result messages.
-
- Returns a NEW list of messages. Does NOT mutate the input.
- Non-tool-result messages are passed through unchanged.
- """
- result = []
- for msg in messages:
- content_str = self._extract_tool_result_content(msg)
- if content_str is not None:
- h = self.content_hash(content_str)
- cached = self.get_compressed(h)
- if cached is not None:
- # Deep copy the message and swap content
- new_msg = _swap_tool_result_content(msg, cached)
- result.append(new_msg)
- continue
- result.append(msg)
- return result
-
- def update_from_result(
- self, originals: list[dict], compressed: list[dict]
- ) -> None:
- """Cache newly compressed content by comparing originals to compressed.
-
- Index-aligned comparison: for each position, if the tool result content
- differs, store the mapping original_hash → compressed_content.
-
- Assumes the pipeline does NOT reorder or merge messages.
- """
- if len(originals) != len(compressed):
- logger.warning(
- "update_from_result: message count mismatch (%d vs %d), skipping",
- len(originals),
- len(compressed),
- )
- return
-
- for orig_msg, comp_msg in zip(originals, compressed):
- orig_content = self._extract_tool_result_content(orig_msg)
- comp_content = self._extract_tool_result_content(comp_msg)
- if (
- orig_content is not None
- and comp_content is not None
- and orig_content != comp_content
- ):
- h = self.content_hash(orig_content)
- tokens_saved = max(0, len(orig_content) // 4 - len(comp_content) // 4)
- self.store_compressed(h, comp_content, tokens_saved=tokens_saved)
-
-
-def _swap_tool_result_content(message: dict, new_content: str) -> dict:
- """Create a copy of message with tool result content replaced.
-
- Handles both Anthropic format (content blocks) and OpenAI format (role=tool).
- Does NOT mutate the original message.
- """
- import copy
-
- new_msg = copy.deepcopy(message)
- content = new_msg.get("content")
-
- if isinstance(content, list):
- for block in content:
- if isinstance(block, dict) and block.get("type") == "tool_result":
- block["content"] = new_content
- break
- elif new_msg.get("role") == "tool" and isinstance(content, str):
- new_msg["content"] = new_content
-
- return new_msg
-```
-
-- [ ] **Step 4: Run tests to verify they pass**
-
-Run: `python -m pytest tests/test_compression_cache.py -v`
-Expected: All 18 tests PASS
-
-- [ ] **Step 5: Commit**
-
-```bash
-git add headroom/cache/compression_cache.py tests/test_compression_cache.py
-git commit -m "feat: add frozen count, apply_cached, update_from_result to CompressionCache"
-```
-
----
-
-### Task 3: Export CompressionCache from cache package
-
-**Files:**
-- Modify: `headroom/cache/__init__.py`
-
-- [ ] **Step 1: Add import and export**
-
-In `headroom/cache/__init__.py`, add to imports:
-```python
-from .compression_cache import CompressionCache
-```
-
-Add `"CompressionCache"` to the `__all__` list.
-
-- [ ] **Step 2: Verify import works**
-
-Run: `python -c "from headroom.cache import CompressionCache; print('OK')"`
-Expected: `OK`
-
-- [ ] **Step 3: Commit**
-
-```bash
-git add headroom/cache/__init__.py
-git commit -m "feat: export CompressionCache from cache package"
-```
-
----
-
-## Chunk 2: ProxyConfig + Mode-Based Pipeline Construction
-
-### Task 4: Add `mode` field to ProxyConfig
-
-**Files:**
-- Modify: `headroom/proxy/server.py`
-
-- [ ] **Step 1: Add `mode` field to ProxyConfig dataclass**
-
-In `headroom/proxy/server.py`, find the `ProxyConfig` class (around line 496, after the `optimize` field). Add:
-
-```python
- # Optimization mode: "cost_savings" (default) or "token_headroom"
- # cost_savings: preserve prefix cache for cost reduction
- # token_headroom: compress older messages for session extension
- mode: str = "cost_savings"
-```
-
-- [ ] **Step 2: Add HEADROOM_MODE env var in config construction**
-
-Find the `ProxyConfig(...)` constructor call (around line 7576). Add the `mode` parameter:
-
-```python
- mode=_get_env_str("HEADROOM_MODE", "cost_savings"),
-```
-
-- [ ] **Step 3: Add mode validation at startup**
-
-Find the startup logging section (around line 1700 where `logger.info(f"Optimization: ...")` is). Add after it:
-
-```python
- if self.config.mode not in ("cost_savings", "token_headroom"):
- logger.warning(
- f"Unknown HEADROOM_MODE '{self.config.mode}', falling back to 'cost_savings'"
- )
- self.config.mode = "cost_savings"
- logger.info(f"Mode: {self.config.mode}")
-```
-
-- [ ] **Step 4: Verify proxy starts with default mode**
-
-Run: `python -c "from headroom.proxy.server import ProxyConfig; c = ProxyConfig(); print(c.mode)"`
-Expected: `cost_savings`
-
-- [ ] **Step 5: Commit**
-
-```bash
-git add headroom/proxy/server.py
-git commit -m "feat: add HEADROOM_MODE config to ProxyConfig"
-```
-
----
-
-### Task 5: Mode-Based Pipeline Configuration at Startup
-
-**Files:**
-- Modify: `headroom/proxy/server.py`
-
-- [ ] **Step 1: Set ContentRouterConfig based on mode**
-
-Find where `ContentRouterConfig` is instantiated (around line 1419, inside the `if config.smart_routing:` block). After the `router_config = ContentRouterConfig(...)` line, add:
-
-```python
- # Token headroom mode: allow compression of older excluded-tool results
- if config.mode == "token_headroom":
- router_config.protect_recent_reads_fraction = 0.3
- logger.info("Token headroom mode: protect_recent_reads_fraction=0.3")
-```
-
-- [ ] **Step 2: Set CCR TTL based on mode**
-
-In the same pipeline construction area, find where `CodeCompressorConfig` or `ReadLifecycleConfig` is used. After the router_config modification, add:
-
-```python
- # Extend CCR TTL for long sessions
- if hasattr(router_config, 'read_lifecycle'):
- router_config.read_lifecycle.ccr_ttl = 14400 # 4 hours
-```
-
-Also check: if `CodeAwareCompressor` is configured separately, its `ccr_ttl` should also be set. Look for `CodeCompressorConfig` instantiation in the same block and set `ccr_ttl=14400`.
-
-- [ ] **Step 3: Initialize CompressionCache store**
-
-Find where `self.session_tracker_store` is initialized (in `__init__` or `_build_pipelines`). Add nearby:
-
-```python
- # Compression cache for token_headroom mode (session-scoped)
- from headroom.cache.compression_cache import CompressionCache
- self._compression_caches: dict[str, CompressionCache] = {}
-```
-
-Add a helper method to the proxy class:
-
-```python
- def _get_compression_cache(self, session_id: str) -> CompressionCache:
- """Get or create a CompressionCache for a session."""
- if session_id not in self._compression_caches:
- self._compression_caches[session_id] = CompressionCache()
- return self._compression_caches[session_id]
-```
-
-- [ ] **Step 4: Add startup logging for token_headroom mode**
-
-In the startup logging section (around line 1700), add:
-
-```python
- if self.config.mode == "token_headroom":
- logger.info("Token headroom mode active:")
- logger.info(" Prefix freeze: re-freeze after compression")
- logger.info(" Read protection window: 30%% of excluded-tool messages")
- logger.info(" CCR TTL: 4 hours")
- logger.info(" Compression cache: active")
-```
-
-- [ ] **Step 5: Verify startup with HEADROOM_MODE=token_headroom**
-
-Run: `HEADROOM_MODE=token_headroom python -c "from headroom.proxy.server import ProxyConfig; c = ProxyConfig(mode='token_headroom'); print(c.mode)"`
-Expected: `token_headroom`
-
-- [ ] **Step 6: Commit**
-
-```bash
-git add headroom/proxy/server.py
-git commit -m "feat: configure pipeline based on HEADROOM_MODE at startup"
-```
-
----
-
-## Chunk 3: Token Headroom Pipeline Integration (Both Providers)
-
-### Task 6: Token Headroom Branch in Anthropic Handler
-
-**Files:**
-- Modify: `headroom/proxy/server.py`
-
-- [ ] **Step 1: Add token_headroom branch in handle_anthropic_messages**
-
-Find the optimization block in `handle_anthropic_messages` (around line 2071). The current code is:
-
-```python
- if self.config.optimize and messages:
- try:
- context_limit = self.anthropic_provider.get_context_limit(model)
- result = self.anthropic_pipeline.apply(
- messages=messages,
- model=model,
- model_limit=context_limit,
- frozen_message_count=frozen_message_count,
- biases=self.config.hooks.compute_biases(messages, _hook_ctx)
- if self.config.hooks
- else None,
- )
- ...
-```
-
-Replace with:
-
-```python
- if self.config.optimize and messages:
- try:
- context_limit = self.anthropic_provider.get_context_limit(model)
- biases = (
- self.config.hooks.compute_biases(messages, _hook_ctx)
- if self.config.hooks
- else None
- )
-
- if self.config.mode == "token_headroom":
- comp_cache = self._get_compression_cache(session_id)
-
- # Zone 1: Swap cached compressed versions into working copy
- working_messages = comp_cache.apply_cached(messages)
-
- # Re-freeze boundary: consecutive stable messages from start
- frozen_message_count = comp_cache.compute_frozen_count(messages)
-
- result = self.anthropic_pipeline.apply(
- messages=working_messages,
- model=model,
- model_limit=context_limit,
- frozen_message_count=frozen_message_count,
- biases=biases,
- )
-
- # Cache newly compressed messages (index-aligned diff)
- if result.messages != working_messages:
- comp_cache.update_from_result(messages, result.messages)
- else:
- result = self.anthropic_pipeline.apply(
- messages=messages,
- model=model,
- model_limit=context_limit,
- frozen_message_count=frozen_message_count,
- biases=biases,
- )
-
- if result.messages != messages:
- optimized_messages = result.messages
- transforms_applied = result.transforms_applied
- pipeline_timing = result.timing
- original_tokens = result.tokens_before
- optimized_tokens = result.tokens_after
- if result.waste_signals:
- waste_signals_dict = result.waste_signals.to_dict()
-```
-
-**IMPORTANT**: The `if result.messages != messages:` check at the end needs to compare against the right baseline. In token_headroom mode, `result.messages` should be compared against `working_messages` (the pre-swapped version), not `messages` (the originals). Fix:
-
-```python
- baseline = working_messages if self.config.mode == "token_headroom" else messages
- if result.messages != baseline:
- optimized_messages = result.messages
- ...
-```
-
-Wait — actually in token_headroom mode, we ALWAYS want to use result.messages because apply_cached already swapped Zone 1. The comparison should detect Zone 2 changes. But even if Zone 2 has no changes, Zone 1 swaps still need to be used. So in token_headroom mode, always use result.messages:
-
-```python
- if self.config.mode == "token_headroom":
- # Always use pipeline result — Zone 1 swaps are already applied
- optimized_messages = result.messages
- transforms_applied = result.transforms_applied
- pipeline_timing = result.timing
- original_tokens = result.tokens_before
- optimized_tokens = result.tokens_after
- elif result.messages != messages:
- optimized_messages = result.messages
- transforms_applied = result.transforms_applied
- pipeline_timing = result.timing
- original_tokens = result.tokens_before
- optimized_tokens = result.tokens_after
-```
-
-- [ ] **Step 2: Verify no side effects — cost_savings mode unchanged**
-
-Run: `python -m pytest tests/ -k "anthropic" --timeout=30 -x -q`
-Expected: Existing tests pass (cost_savings is default, no behavior change)
-
-- [ ] **Step 3: Commit**
-
-```bash
-git add headroom/proxy/server.py
-git commit -m "feat: add token_headroom branch to Anthropic handler"
-```
-
----
-
-### Task 7: Token Headroom Branch in OpenAI Handler
-
-**Files:**
-- Modify: `headroom/proxy/server.py`
-
-- [ ] **Step 1: Apply same pattern to handle_openai_chat**
-
-Find the optimization block in `handle_openai_chat` (around line 4604). Apply the exact same pattern as the Anthropic handler:
-
-```python
- if self.config.optimize and messages:
- try:
- context_limit = self.openai_provider.get_context_limit(model)
- biases = _hook_biases
-
- if self.config.mode == "token_headroom":
- comp_cache = self._get_compression_cache(openai_session_id)
- working_messages = comp_cache.apply_cached(messages)
- openai_frozen_count = comp_cache.compute_frozen_count(messages)
-
- result = self.openai_pipeline.apply(
- messages=working_messages,
- model=model,
- model_limit=context_limit,
- frozen_message_count=openai_frozen_count,
- biases=biases,
- )
-
- if result.messages != working_messages:
- comp_cache.update_from_result(messages, result.messages)
- else:
- result = self.openai_pipeline.apply(
- messages=messages,
- model=model,
- model_limit=context_limit,
- frozen_message_count=openai_frozen_count,
- biases=biases,
- )
-
- if self.config.mode == "token_headroom":
- optimized_messages = result.messages
- transforms_applied = result.transforms_applied
- pipeline_timing = result.timing
- original_tokens = result.tokens_before
- optimized_tokens = result.tokens_after
- elif result.messages != messages:
- optimized_messages = result.messages
- transforms_applied = result.transforms_applied
- pipeline_timing = result.timing
- original_tokens = result.tokens_before
- optimized_tokens = result.tokens_after
- if result.waste_signals:
- waste_signals_dict = result.waste_signals.to_dict()
- except Exception as e:
- logger.warning(f"Optimization failed: {e}")
-```
-
-- [ ] **Step 2: Verify no side effects**
-
-Run: `python -m pytest tests/ -k "openai" --timeout=30 -x -q`
-Expected: Existing tests pass
-
-- [ ] **Step 3: Commit**
-
-```bash
-git add headroom/proxy/server.py
-git commit -m "feat: add token_headroom branch to OpenAI handler"
-```
-
----
-
-### Task 8: Add CompressionCache Stats to /stats Endpoint
-
-**Files:**
-- Modify: `headroom/proxy/server.py`
-
-- [ ] **Step 1: Add compression_cache stats to the stats response**
-
-Find the `/stats` endpoint handler (around line 6243). Find where the response dict is built. Add a new key:
-
-```python
- # Compression cache stats (token_headroom mode)
- compression_cache_stats = {}
- if self.config.mode == "token_headroom":
- all_cache_stats = {}
- for sid, cache in self._compression_caches.items():
- all_cache_stats[sid] = cache.get_stats()
- # Aggregate across sessions
- total_entries = sum(s.get("entries", 0) for s in all_cache_stats.values())
- total_hits = sum(s.get("hits", 0) for s in all_cache_stats.values())
- total_misses = sum(s.get("misses", 0) for s in all_cache_stats.values())
- compression_cache_stats = {
- "active_sessions": len(all_cache_stats),
- "total_entries": total_entries,
- "total_hits": total_hits,
- "total_misses": total_misses,
- "hit_rate": round(total_hits / max(1, total_hits + total_misses) * 100, 1),
- }
-```
-
-Add it to the response dict:
-
-```python
- "compression_cache": compression_cache_stats,
-```
-
-- [ ] **Step 2: Commit**
-
-```bash
-git add headroom/proxy/server.py
-git commit -m "feat: add compression_cache stats to /stats endpoint"
-```
-
----
-
-### Task 9: Fix Missing Model Entry (claude-opus-4-6)
-
-**Files:**
-- Modify: `headroom/providers/anthropic.py`
-
-- [ ] **Step 1: Add claude-opus-4-6 to ANTHROPIC_CONTEXT_LIMITS**
-
-In `headroom/providers/anthropic.py`, find `ANTHROPIC_CONTEXT_LIMITS` (line 47). Add after the claude-opus-4-5 entry:
-
-```python
- "claude-opus-4-6": 1000000,
-```
-
-Also add to `ANTHROPIC_PRICING` (line 72):
-
-```python
- "claude-opus-4-6": {"input": 15.00, "output": 75.00, "cached_input": 1.50},
-```
-
-- [ ] **Step 2: Verify**
-
-Run: `python -c "from headroom.providers.anthropic import AnthropicProvider; p = AnthropicProvider.__new__(AnthropicProvider); p._context_limits = {}; from headroom.providers.anthropic import ANTHROPIC_CONTEXT_LIMITS; print(ANTHROPIC_CONTEXT_LIMITS.get('claude-opus-4-6'))"`
-Expected: `1000000`
-
-- [ ] **Step 3: Commit**
-
-```bash
-git add headroom/providers/anthropic.py
-git commit -m "fix: add claude-opus-4-6 (1M context) to ANTHROPIC_CONTEXT_LIMITS"
-```
-
----
-
-## Chunk 4: Integration + E2E Tests
-
-### Task 10: Integration Tests — Token Headroom Pipeline
-
-**Files:**
-- Create: `tests/test_token_headroom_mode.py`
-
-- [ ] **Step 1: Write integration tests**
-
-Create `tests/test_token_headroom_mode.py`:
-
-```python
-"""Integration tests for token_headroom mode.
-
-Tests the full pipeline flow: CompressionCache + ContentRouter + pipeline
-working together across simulated multi-turn conversations.
-"""
-
-import copy
-import pytest
-
-from headroom.cache.compression_cache import CompressionCache
-from headroom.config import HeadroomConfig
-from headroom.transforms.content_router import ContentRouter, ContentRouterConfig
-from headroom.transforms.pipeline import TransformPipeline, PipelineConfig
-from headroom.tokenizers import EstimatingTokenCounter
-
-
-def _make_user_msg(text: str) -> dict:
- return {"role": "user", "content": text}
-
-
-def _make_assistant_msg(text: str) -> dict:
- return {"role": "assistant", "content": text}
-
-
-def _make_tool_use_msg(tool_id: str, name: str) -> dict:
- return {
- "role": "assistant",
- "content": [{"type": "tool_use", "id": tool_id, "name": name, "input": {}}],
- }
-
-
-def _make_tool_result_msg(tool_id: str, content: str) -> dict:
- """Anthropic-format tool result."""
- return {
- "role": "user",
- "content": [{"type": "tool_result", "tool_use_id": tool_id, "content": content}],
- }
-
-
-def _make_openai_tool_msg(tool_call_id: str, content: str) -> dict:
- """OpenAI-format tool result."""
- return {"role": "tool", "tool_call_id": tool_call_id, "content": content}
-
-
-def _large_code_content(lines: int = 200) -> str:
- """Generate realistic Python code content."""
- parts = ["import os\nimport sys\nfrom typing import List, Dict\n\n"]
- for i in range(lines // 10):
- parts.append(
- f"def function_{i}(arg: str) -> str:\n"
- f' """Docstring for function {i}."""\n'
- f" result = arg.strip()\n"
- f" for j in range({i}):\n"
- f" result += str(j)\n"
- f" return result\n\n"
- )
- return "".join(parts)
-
-
-class TestTokenHeadroomMultiTurn:
- """Simulate multi-turn conversations to verify compression cascade."""
-
- def test_messages_compress_as_they_age_out(self):
- """Turn by turn: messages age out of protection window and get compressed."""
- cache = CompressionCache()
- router_config = ContentRouterConfig(
- protect_recent_reads_fraction=0.3,
- enable_kompress=False, # Disable ML compressors for test speed
- enable_llmlingua=False,
- )
- router = ContentRouter(router_config)
-
- # Build a 20-message conversation
- messages = []
- for i in range(10):
- messages.append(_make_user_msg(f"Read file_{i}.py"))
- messages.append(_make_tool_use_msg(f"t{i}", "Read"))
- # Large tool result that should be compressible
- messages.append(_make_tool_result_msg(f"t{i}", _large_code_content(100)))
-
- assert len(messages) == 30
-
- # Simulate turn with token_headroom pipeline
- working = cache.apply_cached(messages)
- frozen = cache.compute_frozen_count(messages)
-
- # First turn: nothing cached yet, frozen=0 for first tool_result
- # (user messages are stable, but first tool_result at index 2 is a miss)
- # Actually: msg 0 = user (stable), msg 1 = assistant/tool_use (stable),
- # msg 2 = tool_result (cache miss) → frozen = 2
- assert frozen <= 2 # First tool result is uncached
-
- def test_no_message_injection(self):
- """Critical: output message count == input message count."""
- cache = CompressionCache()
-
- messages = [
- _make_user_msg("hello"),
- _make_tool_use_msg("t1", "Read"),
- _make_tool_result_msg("t1", _large_code_content(50)),
- _make_user_msg("edit it"),
- ]
-
- # Pre-populate cache with some content
- cache.store_compressed(
- CompressionCache.content_hash(_large_code_content(50)),
- "compressed code",
- tokens_saved=500,
- )
-
- result = cache.apply_cached(messages)
- assert len(result) == len(messages)
-
- def test_claude_code_drops_messages(self):
- """When CC drops messages, proxy does not re-add them."""
- cache = CompressionCache()
-
- # Simulate: first 5 messages were sent on turn 1
- content_a = "content A " * 100
- content_b = "content B " * 100
- cache.store_compressed(
- CompressionCache.content_hash(content_a), "ca", tokens_saved=100
- )
- cache.store_compressed(
- CompressionCache.content_hash(content_b), "cb", tokens_saved=100
- )
-
- # Turn 2: CC dropped the message with content_b
- messages = [
- _make_user_msg("hello"),
- _make_tool_result_msg("t1", content_a), # still present
- # content_b message was DROPPED by CC
- _make_user_msg("continue"),
- ]
-
- result = cache.apply_cached(messages)
- assert len(result) == 3 # NOT 4 — no re-insertion
-
- def test_user_assistant_never_compressed(self):
- """User and assistant messages are never modified regardless of age."""
- cache = CompressionCache()
-
- messages = [
- _make_user_msg("important instruction " * 50),
- _make_assistant_msg("detailed response " * 50),
- ]
-
- result = cache.apply_cached(messages)
- assert result[0]["content"] == messages[0]["content"]
- assert result[1]["content"] == messages[1]["content"]
-
- def test_openai_format_tool_results(self):
- """OpenAI-format tool messages are handled correctly."""
- cache = CompressionCache()
- content = "large tool output " * 100
- h = CompressionCache.content_hash(content)
- cache.store_compressed(h, "compressed output", tokens_saved=300)
-
- messages = [
- _make_user_msg("run command"),
- {"role": "assistant", "content": None, "tool_calls": [
- {"id": "tc1", "type": "function", "function": {"name": "bash", "arguments": "{}"}}
- ]},
- _make_openai_tool_msg("tc1", content),
- ]
-
- result = cache.apply_cached(messages)
- assert len(result) == 3
- assert result[2]["content"] == "compressed output"
-
- def test_re_freeze_consecutive_cached(self):
- """After first compression, Zone 1 forms a stable re-frozen prefix."""
- cache = CompressionCache()
-
- content_1 = "file one " * 100
- content_2 = "file two " * 100
- h1 = CompressionCache.content_hash(content_1)
- h2 = CompressionCache.content_hash(content_2)
- cache.store_compressed(h1, "c1", tokens_saved=100)
- cache.store_compressed(h2, "c2", tokens_saved=100)
-
- messages = [
- _make_user_msg("read files"),
- _make_tool_result_msg("t1", content_1),
- _make_tool_result_msg("t2", content_2),
- _make_user_msg("now edit"),
- _make_tool_result_msg("t3", "brand new content not cached"),
- ]
-
- frozen = cache.compute_frozen_count(messages)
- # msg 0: user (stable), msg 1: tool_result (cached → stable),
- # msg 2: tool_result (cached → stable), msg 3: user (stable),
- # msg 4: tool_result (NOT cached → stop)
- assert frozen == 4
-```
-
-- [ ] **Step 2: Run tests**
-
-Run: `python -m pytest tests/test_token_headroom_mode.py -v`
-Expected: All tests PASS
-
-- [ ] **Step 3: Commit**
-
-```bash
-git add tests/test_token_headroom_mode.py
-git commit -m "test: add integration tests for token_headroom mode"
-```
-
----
-
-### Task 11: Run Full Test Suite — No Side Effects
-
-**Files:** None (verification only)
-
-- [ ] **Step 1: Run full test suite**
-
-Run: `python -m pytest tests/ --timeout=60 -x -q --ignore=tests/test_token_headroom_mode.py`
-Expected: All existing tests PASS — no side effects from the new code. The default mode is `cost_savings` so all existing behavior is unchanged.
-
-- [ ] **Step 2: Run new tests**
-
-Run: `python -m pytest tests/test_compression_cache.py tests/test_token_headroom_mode.py -v`
-Expected: All new tests PASS
-
-- [ ] **Step 3: Run linting**
-
-Run: `ruff check headroom/cache/compression_cache.py headroom/proxy/server.py headroom/providers/anthropic.py`
-Expected: No errors
-
-Run: `ruff format --check headroom/cache/compression_cache.py`
-Expected: No formatting issues
-
-- [ ] **Step 4: Final commit if any fixes needed**
-
-```bash
-git add -A && git commit -m "fix: address linting issues from token headroom implementation"
-```
-
-(Only if linting found issues)
diff --git a/docs/superpowers/specs/2026-03-19-token-headroom-mode-design.md b/docs/superpowers/specs/2026-03-19-token-headroom-mode-design.md
deleted file mode 100644
index 940c1bf52..000000000
--- a/docs/superpowers/specs/2026-03-19-token-headroom-mode-design.md
+++ /dev/null
@@ -1,275 +0,0 @@
-# Token Headroom Mode — Design Spec
-
-**Date**: 2026-03-19
-**Status**: Approved
-**Problem**: In long Claude Code sessions, the prefix freeze mechanism prevents compression of cached messages. Users see ~1% compression instead of 20-30%, burning through usage limits faster.
-
-## Background
-
-Headroom's proxy has two competing optimizations:
-
-1. **Prefix freeze**: Preserves Anthropic's prefix cache (90% read discount) by never modifying cached messages. Saves money.
-2. **Compression**: Reduces token count by compressing older tool results. Extends sessions.
-
-Currently, prefix freeze always wins. Once Anthropic caches a message prefix (which happens after the first turn), the proxy freezes those messages and never compresses them. As the session grows, the frozen prefix grows to cover nearly all messages. Compression only runs on the last few new messages per turn.
-
-For users who are bottlenecked on **token consumption limits** (not cost), this is the wrong tradeoff. They need fewer tokens, not cheaper tokens.
-
-## Solution: Dual-Mode Optimization
-
-Add a `HEADROOM_MODE` config toggle:
-
-- `cost_savings` (default): Current behavior. Prefix freeze enabled. Optimizes for API cost.
-- `token_headroom`: Compresses older messages to reduce token count. Accepts prefix cache busts to gain session length.
-
-## Architecture
-
-### CompressionCache
-
-Content-addressed cache mapping original content hashes to compressed versions. Session-scoped (lives as long as the proxy process).
-
-```python
-class CompressionCache:
- """Content-addressed cache of compressed messages.
-
- Maps original_content_hash → compressed_content.
- No position tracking — works purely on content identity.
- Handles Claude Code dropping messages gracefully (unused entries stay in cache).
- """
- cache: dict[str, str] # content_hash → compressed_content
- token_savings: dict[str, int] # content_hash → tokens saved
- max_entries: int = 10000 # LRU eviction beyond this
-
- def get_compressed(self, content_hash: str) -> str | None
- def store_compressed(self, content_hash: str, compressed: str, tokens_saved: int)
- def compute_frozen_count(self, messages: list[dict]) -> int
- def update_from_result(self, originals: list[dict], compressed: list[dict]) -> None
-```
-
-**Cache key**: SHA-256 of original content. Same file content across turns = same hash = cache hit. Edited file = different hash = cache miss = fresh compression.
-
-**Max entries**: 10,000 (not 2,000). Long coding sessions can generate thousands of tool results. Evicting cache entries forces re-compression, defeating the re-freeze optimization. 10K entries at ~1KB average compressed text = ~10MB — acceptable.
-
-**Frozen count calculation**: Count consecutive messages from the start that are "stable" (either have cache hits OR are non-compressible messages like user/assistant/tool-use). The key rule:
-
-- **Tool-result messages**: Stable if content hash is in cache (compressed version available).
-- **User, assistant, system, tool-use messages**: Always considered stable (they pass through unchanged, so they won't bust the prefix cache).
-
-First *unstable* message (tool-result with cache miss) = end of frozen prefix. This prevents the frozen count from being 0 just because message 0 is a user message.
-
-This handles Claude Code dropping messages: if a cached tool-result is dropped, the next message may not be in cache, breaking the consecutive run and stopping the frozen prefix there.
-
-**`update_from_result` contract**: Performs index-aligned comparison between `originals` and `compressed`. For each index where content differs, stores the mapping original_hash → compressed_content. Assumes the pipeline does NOT reorder or merge messages (this is a pipeline contract that holds today and must be preserved).
-
-### Pipeline Flow in Token Headroom Mode
-
-Each turn, the proxy receives all messages from Claude Code (originals, uncompressed):
-
-```
-Messages: [m1, m2, m3, ..., mP, mP+1, ..., mN]
- |← cache hits →|← cache misses →|← protection window (30%) →|
-
-Zone 1: Cache hits → Swap in compressed versions, re-freeze as stable prefix
-Zone 2: Cache misses → Run full ContentRouter compression, cache results
-Zone 3: Protection window → Pass through unchanged (last 30% of messages)
-```
-
-**Zone 1** (already compressed): The proxy swaps in cached compressed content. These form a new stable prefix. Anthropic caches them. Next turn gets 90% read discount on Zone 1.
-
-**Zone 2** (newly eligible): First time outside protection window. ContentRouter runs full compression: CodeAwareCompressor for code, SmartCrusher for JSON, Kompress for text. Results cached. On next turn, these move into Zone 1.
-
-**Zone 3** (protected): Recent messages, untouched. The LLM needs these fresh for current work.
-
-**Critical invariant**: The proxy ONLY operates on messages Claude Code actually sends. It never adds, re-inserts, or reorders messages. If Claude Code drops a message via its own context management, the proxy does not re-add it.
-
-### Zone 3 (Protection Window) Definition
-
-Zone 3 protects the **last 30% of excluded-tool messages** (Read, Glob, Grep, Write, Edit results), not 30% of all messages. This matches the existing `protect_recent_reads_fraction` semantics in ContentRouter. User messages, assistant messages, and tool-use blocks are always protected regardless of position — they don't factor into the 30% calculation.
-
-Example: 100 messages, 40 of which are Read/Glob/Grep results → last 12 excluded-tool results protected (30% of 40). All user/assistant messages protected independently.
-
-### Config Plumbing
-
-`protect_recent_reads_fraction` is a `ContentRouterConfig` instance attribute, not a per-call kwarg. It is set **at proxy startup** based on mode:
-
-```python
-# In HeadroomProxy.__init__ or _build_pipelines:
-if self.config.mode == "token_headroom":
- router_config.protect_recent_reads_fraction = 0.3
- router_config.ccr_ttl = 14400
-else:
- router_config.protect_recent_reads_fraction = 0.0 # protect all (current default)
-```
-
-Similarly, `force_compress_threshold` on `PrefixFreezeConfig` is set to `0.0` in token_headroom mode (always allow compression through the cache). This avoids two competing mechanisms for cache-bust decisions.
-
-### Integration Point
-
-In `server.py`, `_handle_anthropic_request` (line ~2071):
-
-```python
-if self.config.mode == "token_headroom":
- comp_cache = self.compression_cache_store.get_or_create(session_id)
-
- # Zone 1: Swap cached compressed versions
- working_messages = comp_cache.apply_cached(messages)
-
- # Calculate re-freeze boundary (consecutive stable messages from start)
- frozen_count = comp_cache.compute_frozen_count(messages)
-
- # Zone 2+3: Pipeline compresses Zone 2, skips Zone 3 (protected)
- result = self.anthropic_pipeline.apply(
- working_messages, model,
- frozen_message_count=frozen_count,
- )
-
- # Cache newly compressed messages (index-aligned diff)
- comp_cache.update_from_result(messages, result.messages)
-else:
- # Current cost_savings behavior — unchanged
- frozen_count = prefix_tracker.get_frozen_message_count()
- result = self.anthropic_pipeline.apply(
- messages, model, frozen_message_count=frozen_count
- )
-```
-
-## Tool-Specific Compression Strategies
-
-| Tool Result | Compressor | CCR Retrieval | Expected Reduction |
-|---|---|---|---|
-| Read (code) | CodeAwareCompressor (tree-sitter AST) | Yes — hash marker, original stored | 60-80% |
-| Read (non-code) | Kompress / SmartCrusher | Yes | 40-60% |
-| Glob | SmartCrusher (JSON array crush) | No (too small) | 50-70% |
-| Grep | SmartCrusher (keep matches, drop context) | Yes | 40-60% |
-| Bash | ContentRouter auto-routes (log/text/JSON) | Yes for large outputs | 50-80% |
-| Stale Read | ReadLifecycle marker (already built) | Yes — original stored | ~95% |
-| Superseded Read | ReadLifecycle marker | No (later read has content) | ~95% |
-
-### CodeAwareCompressor (existing, key for Read results)
-
-- Uses tree-sitter for proper AST parsing (multi-language)
-- Keeps: imports, function/class signatures, type hints, docstrings, decorators
-- Removes: function bodies (replaced with `...` + line count)
-- CCR integration: stores original in CCR store, appends `# [N tokens compressed. Retrieve more: hash=abc123.]`
-- Syntax validity guaranteed
-- If tree-sitter unavailable: falls back to text-level compression via ContentRouter chain
-
-### ReadLifecycle (existing, runs before ContentRouter)
-
-- **Stale reads** (file edited after read): Replaced with `[file.py was modified after this read. Re-read if needed.]`
-- **Superseded reads** (same file re-read later): Replaced with marker pointing to later read
-- In token_headroom mode: runs without prefix freeze blocking it
-
-## Configuration
-
-### New config on ProxyConfig
-
-```python
-mode: str = "cost_savings" # "cost_savings" | "token_headroom"
-```
-
-Activation: `HEADROOM_MODE=token_headroom` environment variable or config file.
-
-### Settings that change per mode
-
-| Setting | cost_savings (default) | token_headroom |
-|---|---|---|
-| prefix_freeze_enabled | True | True (re-freezes compressed content) |
-| protect_recent_reads_fraction | 0.0 (protect all) | 0.3 (protect last 30%) |
-| ccr_ttl | 300 (5 min) | 14400 (4 hours) |
-| read_lifecycle | True (frozen blocks it) | True (runs freely on aged-out) |
-| CompressionCache | Not used | Active per session |
-| Excluded tools (Read/Glob/Grep) | Protected forever | Protected in last 30% only |
-
-### What stays the same in both modes
-
-- User messages: always protected
-- Assistant messages: always protected
-- Tool-use blocks: always protected
-- ContentRouter routing logic
-- All compressors (CodeAware, SmartCrusher, Kompress)
-- MCP server tools
-
-### Startup log
-
-```
-Headroom proxy v0.4.6 | Mode: token_headroom
- Prefix freeze: enabled (re-freeze after compression)
- Read protection window: 30% of messages
- CCR TTL: 4 hours
- Compression cache: active
-```
-
-## Observability
-
-In token_headroom mode, the `/stats` endpoint and startup logs must expose:
-
-- **Per-turn zone breakdown**: Zone 1/2/3 message counts and token counts
-- **Compression cache stats**: entries, hits, misses, hit rate
-- **Net token savings**: tokens saved by compression minus tokens lost to cache bust write premium
-- **CCR store stats**: entries, memory usage, eviction count
-
-The CCR store uses TTL-based eviction (entries expire after 4 hours). The `CompressionCache` uses LRU eviction at 10K entries. Both report eviction counts in stats so operators can detect if bounds are too tight.
-
-## Also Fix: Missing Model Entry (Separate Task)
-
-`claude-opus-4-6` is not in `ANTHROPIC_CONTEXT_LIMITS`. Falls back to pattern match → 200K. Real context is 1M. Add it with correct limit. (Separate from token_headroom mode but discovered during investigation.)
-
-## Edge Cases
-
-1. **Very short conversations (< 10 messages)**: Protection window covers almost everything. Minimum protection of 4 messages means nothing compressed until message ~6+. Correct — no overhead for short sessions.
-
-2. **All user/assistant messages (no tool results)**: These are always protected. CompressionCache stays empty. No-op. Correct.
-
-3. **CodeAwareCompressor not installed**: Falls back to Kompress/SmartCrusher via ContentRouter's existing chain. Log warning.
-
-4. **CCR store unavailable**: Compression still happens, just no retrieval markers. LLM must re-read if it needs exact content. Acceptable degradation.
-
-5. **Session resume (--resume) with empty cache**: First turn: full compression pass. Turn 2: cache populated, re-freeze, prefix cache rebuilds. Recovery within 1-2 turns.
-
-6. **Compression makes content larger**: ContentRouter already checks compression_ratio >= min_ratio and passes through unchanged. Cache only stores actual reductions.
-
-7. **Claude Code drops messages**: Cache entries go unused (LRU eviction eventually). Proxy never re-inserts dropped messages. Frozen count stops at first unstable message, preventing stale frozen prefix.
-
-8. **Mode switch mid-session**: If proxy restarts with a different mode, the CompressionCache is empty (new process) and the prefix tracker is reset. In token_headroom mode, the first turn does a full compression pass (edge case 5). In cost_savings mode, the prefix tracker rebuilds from the first API response. No stale state carries over.
-
-9. **Large Zone 2 on first turn after --resume**: Many tool results age out simultaneously. ContentRouter processes them sequentially. If compression latency exceeds 10 seconds, log a warning but do not skip — the user explicitly chose token_headroom mode and the one-time cost is justified. Subsequent turns are fast (cache hits).
-
-## Testing Strategy
-
-### Unit Tests — CompressionCache
-
-- `test_store_and_retrieve`: Cache hit/miss behavior
-- `test_different_content_different_hash`: Edited file → new hash → fresh compression
-- `test_lru_eviction`: Max entries respected
-- `test_frozen_count_consecutive_hits`: Stops at first miss
-- `test_frozen_count_with_dropped_messages`: Claude Code drops messages → correct frozen boundary
-- `test_protection_window_calculation`: 30% of N messages, minimum 4
-
-### Integration Tests — Pipeline in Token Headroom Mode
-
-- `test_mode_toggle`: Same conversation, both modes → token_headroom produces fewer tokens
-- `test_multi_turn_waterfall`: 10-turn simulation. Verify messages age out → compress → cache → re-freeze. Cumulative savings > 30%.
-- `test_claude_code_drops_messages`: Proxy does NOT re-insert dropped messages
-- `test_stale_read_lifecycle`: Read → Edit → verify stale marker with CCR hash
-- `test_read_edit_reread`: First read stale (marker), second read fresh (full content)
-- `test_code_compressor_with_ccr`: AST compression, CCR marker, TTL = 14400s, valid syntax
-- `test_glob_grep_bash_compression`: Each compressor type activates for its content type
-- `test_re_freeze_after_compression`: Zone 1 re-frozen, pipeline sees correct frozen_count
-- `test_user_assistant_always_protected`: Never compressed regardless of age
-
-### End-to-End Simulation
-
-- `test_e2e_long_session`: 70+ requests simulating bug report. cost_savings ~1%, token_headroom >25%.
-- `test_e2e_resumed_session`: Empty cache → full compression → cache recovery in 2 turns.
-- `test_e2e_cost_comparison`: Log tokens + cost for both modes. Verify token_headroom extends session >30%.
-- `test_e2e_no_message_injection`: Verify output message count <= input message count (never adds messages).
-
-## Files to Modify
-
-1. **New file**: `headroom/cache/compression_cache.py` — CompressionCache class
-2. **Modify**: `headroom/proxy/server.py` — ProxyConfig.mode, mode-based config at startup, pipeline flow branch, CompressionCache session store, stats endpoint additions
-3. **Modify**: `headroom/proxy/server.py` — Set `ContentRouterConfig.protect_recent_reads_fraction` and `PrefixFreezeConfig.force_compress_threshold` at startup based on mode
-4. **Modify**: `headroom/providers/anthropic.py` — Add claude-opus-4-6 to ANTHROPIC_CONTEXT_LIMITS (separate commit)
-5. **New file**: `tests/test_compression_cache.py` — Unit tests for CompressionCache
-6. **New file**: `tests/test_token_headroom_mode.py` — Integration + E2E tests
diff --git a/docs/typescript-sdk.md b/docs/typescript-sdk.md
new file mode 100644
index 000000000..c72bb65e3
--- /dev/null
+++ b/docs/typescript-sdk.md
@@ -0,0 +1,213 @@
+# TypeScript SDK
+
+The Headroom TypeScript SDK lets any JavaScript or TypeScript application compress LLM messages before sending them to a model. It saves tokens, reduces costs, and fits more context into every request.
+
+## Install
+
+```bash
+npm install headroom-ai
+```
+
+Requires a running [Headroom proxy](proxy.md) or Headroom Cloud API key.
+
+## Quick Start
+
+```typescript
+import { compress } from 'headroom-ai';
+
+const result = await compress(messages, { model: 'gpt-4o' });
+console.log(`Saved ${result.tokensSaved} tokens`);
+
+const response = await openai.chat.completions.create({
+ model: 'gpt-4o',
+ messages: result.messages,
+});
+```
+
+## How It Works
+
+The TypeScript SDK is an HTTP client. When you call `compress()`, it sends your messages to the Headroom proxy's `POST /v1/compress` endpoint. The proxy runs the full compression pipeline (SmartCrusher, ContentRouter, CacheAligner, etc.) and returns compressed messages. No compression logic runs in Node.js — all the heavy lifting happens in the proxy.
+
+```
+Your TypeScript App
+ │
+ │ compress(messages)
+ ▼
+headroom-ai (npm) ← HTTP client
+ │
+ │ POST /v1/compress
+ ▼
+Headroom Proxy / Cloud ← compression pipeline (Python)
+ │
+ │ compressed messages
+ ▼
+Your TypeScript App
+ │
+ │ openai.chat.completions.create(compressed)
+ ▼
+LLM Provider
+```
+
+## Core API: `compress()`
+
+```typescript
+import { compress } from 'headroom-ai';
+
+const result = await compress(messages, {
+ model: 'gpt-4o', // model name (for token counting)
+ baseUrl: 'http://localhost:8787', // proxy URL (default)
+ apiKey: 'hr_...', // Headroom Cloud key
+ timeout: 30000, // ms (default)
+ fallback: true, // return uncompressed if proxy down (default)
+ retries: 1, // retry on transient errors (default)
+});
+
+result.messages // compressed messages (same format as input)
+result.tokensBefore // original token count
+result.tokensAfter // compressed token count
+result.tokensSaved // tokens removed
+result.compressionRatio // tokensAfter / tokensBefore
+result.transformsApplied // e.g. ['router:smart_crusher:0.35']
+result.compressed // false if fallback kicked in
+```
+
+Messages use standard OpenAI chat format: `{ role, content, tool_calls?, tool_call_id? }`.
+
+### Environment Variables
+
+Instead of passing options, set environment variables:
+
+- `HEADROOM_BASE_URL` — proxy or cloud URL (default: `http://localhost:8787`)
+- `HEADROOM_API_KEY` — Headroom Cloud API key
+
+## Reusable Client
+
+For apps making many calls, create a client once and reuse it:
+
+```typescript
+import { HeadroomClient } from 'headroom-ai';
+
+const client = new HeadroomClient({
+ baseUrl: 'http://localhost:8787',
+ apiKey: 'hr_...',
+});
+
+const r1 = await client.compress(messages1, { model: 'gpt-4o' });
+const r2 = await client.compress(messages2, { model: 'gpt-4o' });
+```
+
+## Framework Adapters
+
+### Vercel AI SDK
+
+The Headroom middleware plugs directly into Vercel AI SDK's `wrapLanguageModel()`:
+
+```typescript
+import { headroomMiddleware } from 'headroom-ai/vercel-ai';
+import { wrapLanguageModel, generateText } from 'ai';
+import { openai } from '@ai-sdk/openai';
+
+const model = wrapLanguageModel({
+ model: openai('gpt-4o'),
+ middleware: headroomMiddleware(),
+});
+
+// All calls through this model are automatically compressed
+const { text } = await generateText({ model, messages });
+```
+
+The middleware intercepts messages in the `transformParams` hook, converts Vercel's internal format to OpenAI format, compresses via the proxy, and converts back. Your app code doesn't change.
+
+You can also compress Vercel messages directly:
+
+```typescript
+import { compressVercelMessages } from 'headroom-ai/vercel-ai';
+
+const result = await compressVercelMessages(modelMessages, { model: 'gpt-4o' });
+// result.messages is in Vercel ModelMessage[] format
+```
+
+### OpenAI SDK
+
+Wrap your OpenAI client to auto-compress messages on every `chat.completions.create()` call:
+
+```typescript
+import { withHeadroom } from 'headroom-ai/openai';
+import OpenAI from 'openai';
+
+const client = withHeadroom(new OpenAI());
+
+// Messages are compressed before sending — transparent to your code
+const response = await client.chat.completions.create({
+ model: 'gpt-4o',
+ messages: longConversation,
+});
+```
+
+Only `chat.completions.create()` is intercepted. All other methods (embeddings, images, audio) pass through unchanged.
+
+### Anthropic SDK
+
+Same pattern for the Anthropic client:
+
+```typescript
+import { withHeadroom } from 'headroom-ai/anthropic';
+import Anthropic from '@anthropic-ai/sdk';
+
+const client = withHeadroom(new Anthropic());
+
+const response = await client.messages.create({
+ model: 'claude-sonnet-4-5-20250929',
+ messages: longConversation,
+ max_tokens: 1024,
+});
+```
+
+Only `messages.create()` is intercepted. The adapter converts between Anthropic's content block format and OpenAI format automatically.
+
+## Error Handling
+
+```typescript
+import { compress, HeadroomConnectionError, HeadroomAuthError } from 'headroom-ai';
+
+try {
+ const result = await compress(messages, { model: 'gpt-4o', fallback: false });
+} catch (error) {
+ if (error instanceof HeadroomAuthError) {
+ // Invalid API key (401)
+ } else if (error instanceof HeadroomConnectionError) {
+ // Proxy unreachable
+ }
+}
+```
+
+With `fallback: true` (the default), connection errors and 5xx responses return the original messages uncompressed instead of throwing. Auth errors (401) and client errors (400) always throw.
+
+## Fallback Behavior
+
+By default, `compress()` never blocks your app. If the proxy is unreachable:
+
+| Scenario | `fallback: true` (default) | `fallback: false` |
+|----------|---------------------------|-------------------|
+| Proxy unreachable | Returns uncompressed, `compressed: false` | Throws `HeadroomConnectionError` |
+| Proxy 503 error | Returns uncompressed after retries | Throws `HeadroomCompressError` |
+| Invalid API key (401) | Throws `HeadroomAuthError` | Throws `HeadroomAuthError` |
+| Bad request (400) | Throws `HeadroomCompressError` | Throws `HeadroomCompressError` |
+
+## Zero Dependencies
+
+The `headroom-ai` package has no runtime dependencies. Framework SDKs (Vercel AI, OpenAI, Anthropic) are optional peer dependencies — only install what you use.
+
+## Comparison with Python SDK
+
+| Feature | Python SDK | TypeScript SDK |
+|---------|-----------|---------------|
+| `compress()` | Native (runs locally) | HTTP client (calls proxy) |
+| Proxy | Built-in server | Connects to proxy |
+| Vercel AI SDK | N/A | Middleware adapter |
+| OpenAI SDK | `HeadroomClient` wrapper | `withHeadroom()` wrapper |
+| Anthropic SDK | `HeadroomClient` wrapper | `withHeadroom()` wrapper |
+| LangChain | `HeadroomChatModel` | Use `compress()` directly |
+| Memory system | Full (SQLite + HNSW) | Not yet (use proxy) |
+| MCP server | Built-in | Not yet |
+| CLI tools | `headroom proxy`, `headroom wrap`, etc. | N/A (use Python CLI) |
diff --git a/headroom/proxy/server.py b/headroom/proxy/server.py
index e7d678d09..a5a62c3a2 100644
--- a/headroom/proxy/server.py
+++ b/headroom/proxy/server.py
@@ -2153,6 +2153,116 @@ class HeadroomProxy:
raise last_error # type: ignore[misc]
+ async def handle_compress(self, request: Request) -> JSONResponse:
+ """Compress messages without calling an LLM.
+
+ POST /v1/compress
+ Body: {"messages": [...], "model": "...", "config": {}}
+ Returns compressed messages + metrics.
+ """
+ # Check bypass header
+ if request.headers.get("x-headroom-bypass", "").lower() == "true":
+ body = await request.json()
+ messages = body.get("messages", [])
+ return JSONResponse(
+ {
+ "messages": messages,
+ "tokens_before": 0,
+ "tokens_after": 0,
+ "tokens_saved": 0,
+ "compression_ratio": 1.0,
+ "transforms_applied": [],
+ "ccr_hashes": [],
+ }
+ )
+
+ try:
+ body = await request.json()
+ except Exception:
+ return JSONResponse(
+ status_code=400,
+ content={
+ "error": {
+ "type": "invalid_request",
+ "message": "Invalid JSON in request body.",
+ }
+ },
+ )
+
+ messages = body.get("messages")
+ model = body.get("model")
+
+ if messages is None:
+ return JSONResponse(
+ status_code=400,
+ content={
+ "error": {
+ "type": "invalid_request",
+ "message": "Missing required field: messages",
+ }
+ },
+ )
+
+ if model is None:
+ return JSONResponse(
+ status_code=400,
+ content={
+ "error": {
+ "type": "invalid_request",
+ "message": "Missing required field: model",
+ }
+ },
+ )
+
+ if not messages:
+ return JSONResponse(
+ {
+ "messages": [],
+ "tokens_before": 0,
+ "tokens_after": 0,
+ "tokens_saved": 0,
+ "compression_ratio": 1.0,
+ "transforms_applied": [],
+ "ccr_hashes": [],
+ }
+ )
+
+ try:
+ # Use OpenAI pipeline (messages are in OpenAI format from TS SDK)
+ context_limit = self.openai_provider.get_context_limit(model)
+ result = self.openai_pipeline.apply(
+ messages=messages,
+ model=model,
+ model_limit=context_limit,
+ )
+
+ return JSONResponse(
+ {
+ "messages": result.messages,
+ "tokens_before": result.tokens_before,
+ "tokens_after": result.tokens_after,
+ "tokens_saved": result.tokens_before - result.tokens_after,
+ "compression_ratio": (
+ result.tokens_after / result.tokens_before
+ if result.tokens_before > 0
+ else 1.0
+ ),
+ "transforms_applied": result.transforms_applied,
+ "ccr_hashes": result.markers_inserted,
+ }
+ )
+ except Exception as e:
+ logger.exception("Compression failed: %s", e)
+ return JSONResponse(
+ status_code=503,
+ content={
+ "error": {
+ "type": "compression_error",
+ "message": str(e),
+ }
+ },
+ )
+
async def handle_anthropic_messages(
self,
request: Request,
@@ -7632,6 +7742,11 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:
"data": retrieval_data,
}
+ # Compression-only endpoint (for TypeScript SDK and other HTTP clients)
+ @app.post("/v1/compress")
+ async def compress_messages(request: Request):
+ return await proxy.handle_compress(request)
+
# Anthropic endpoints
@app.post("/v1/messages")
async def anthropic_messages(request: Request):
diff --git a/sdk/typescript/.gitignore b/sdk/typescript/.gitignore
new file mode 100644
index 000000000..f4e2c6d6b
--- /dev/null
+++ b/sdk/typescript/.gitignore
@@ -0,0 +1,3 @@
+node_modules/
+dist/
+*.tsbuildinfo
diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md
new file mode 100644
index 000000000..8923a1a89
--- /dev/null
+++ b/sdk/typescript/README.md
@@ -0,0 +1,108 @@
+# headroom-ai
+
+Compress LLM context. Save tokens. Fit more into every request.
+
+## Install
+
+```bash
+npm install headroom-ai
+```
+
+## Quick Start
+
+```typescript
+import { compress } from 'headroom-ai';
+
+const result = await compress(messages, { model: 'gpt-4o' });
+console.log(`Saved ${result.tokensSaved} tokens (${((1 - result.compressionRatio) * 100).toFixed(0)}%)`);
+
+// Use compressed messages with any LLM client
+const response = await openai.chat.completions.create({
+ model: 'gpt-4o',
+ messages: result.messages,
+});
+```
+
+Requires a running Headroom proxy (`headroom proxy`) or Headroom Cloud API key.
+
+## Framework Adapters
+
+### Vercel AI SDK
+
+```typescript
+import { headroomMiddleware } from 'headroom-ai/vercel-ai';
+import { wrapLanguageModel, generateText } from 'ai';
+import { openai } from '@ai-sdk/openai';
+
+const model = wrapLanguageModel({
+ model: openai('gpt-4o'),
+ middleware: headroomMiddleware(),
+});
+
+const { text } = await generateText({ model, messages });
+```
+
+### OpenAI SDK
+
+```typescript
+import { withHeadroom } from 'headroom-ai/openai';
+import OpenAI from 'openai';
+
+const client = withHeadroom(new OpenAI());
+const response = await client.chat.completions.create({
+ model: 'gpt-4o',
+ messages: longConversation,
+});
+```
+
+### Anthropic SDK
+
+```typescript
+import { withHeadroom } from 'headroom-ai/anthropic';
+import Anthropic from '@anthropic-ai/sdk';
+
+const client = withHeadroom(new Anthropic());
+const response = await client.messages.create({
+ model: 'claude-sonnet-4-5-20250929',
+ messages: longConversation,
+ max_tokens: 1024,
+});
+```
+
+## Configuration
+
+```typescript
+import { compress } from 'headroom-ai';
+
+const result = await compress(messages, {
+ model: 'gpt-4o',
+ baseUrl: 'http://localhost:8787', // or https://api.headroom.ai
+ apiKey: 'hr_...', // for Headroom Cloud
+ timeout: 30000, // ms
+ fallback: true, // return uncompressed if proxy is down (default)
+ retries: 1, // retry on transient failures (default)
+});
+```
+
+Or use environment variables:
+- `HEADROOM_BASE_URL` — proxy/cloud URL
+- `HEADROOM_API_KEY` — Cloud API key
+
+## Reusable Client
+
+```typescript
+import { HeadroomClient } from 'headroom-ai';
+
+const client = new HeadroomClient({
+ baseUrl: 'http://localhost:8787',
+ apiKey: 'hr_...',
+});
+
+// Reuse across many calls
+const r1 = await client.compress(messages1, { model: 'gpt-4o' });
+const r2 = await client.compress(messages2, { model: 'gpt-4o' });
+```
+
+## License
+
+Apache-2.0
diff --git a/sdk/typescript/package-lock.json b/sdk/typescript/package-lock.json
new file mode 100644
index 000000000..a3dfcf126
--- /dev/null
+++ b/sdk/typescript/package-lock.json
@@ -0,0 +1,3088 @@
+{
+ "name": "headroom-ai",
+ "version": "0.1.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "headroom-ai",
+ "version": "0.1.0",
+ "license": "Apache-2.0",
+ "devDependencies": {
+ "@ai-sdk/provider": "^1.0.0",
+ "@anthropic-ai/sdk": "^0.39.0",
+ "ai": "^6.0.0",
+ "openai": "^4.80.0",
+ "tsup": "^8.0.0",
+ "typescript": "^5.5.0",
+ "vitest": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ },
+ "peerDependencies": {
+ "@ai-sdk/provider": ">=1.0.0",
+ "@anthropic-ai/sdk": ">=0.30.0",
+ "ai": ">=6.0.0",
+ "openai": ">=4.0.0"
+ },
+ "peerDependenciesMeta": {
+ "@ai-sdk/provider": {
+ "optional": true
+ },
+ "@anthropic-ai/sdk": {
+ "optional": true
+ },
+ "ai": {
+ "optional": true
+ },
+ "openai": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@ai-sdk/gateway": {
+ "version": "3.0.80",
+ "resolved": "https://registry.npmjs.org/@ai-sdk/gateway/-/gateway-3.0.80.tgz",
+ "integrity": "sha512-uM7kpZB5l977lW7+2X1+klBUxIZQ78+1a9jHlaHFEzcOcmmslTl3sdP0QqfuuBcO0YBM2gwOiqVdp8i4TRQYcw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@ai-sdk/provider": "3.0.8",
+ "@ai-sdk/provider-utils": "4.0.21",
+ "@vercel/oidc": "3.1.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "peerDependencies": {
+ "zod": "^3.25.76 || ^4.1.8"
+ }
+ },
+ "node_modules/@ai-sdk/gateway/node_modules/@ai-sdk/provider": {
+ "version": "3.0.8",
+ "resolved": "https://registry.npmjs.org/@ai-sdk/provider/-/provider-3.0.8.tgz",
+ "integrity": "sha512-oGMAgGoQdBXbZqNG0Ze56CHjDZ1IDYOwGYxYjO5KLSlz5HiNQ9udIXsPZ61VWaHGZ5XW/jyjmr6t2xz2jGVwbQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "json-schema": "^0.4.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@ai-sdk/provider": {
+ "version": "1.1.3",
+ "resolved": "https://registry.npmjs.org/@ai-sdk/provider/-/provider-1.1.3.tgz",
+ "integrity": "sha512-qZMxYJ0qqX/RfnuIaab+zp8UAeJn/ygXXAffR5I4N0n1IrvA6qBsjc8hXLmBiMV2zoXlifkacF7sEFnYnjBcqg==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "json-schema": "^0.4.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@ai-sdk/provider-utils": {
+ "version": "4.0.21",
+ "resolved": "https://registry.npmjs.org/@ai-sdk/provider-utils/-/provider-utils-4.0.21.tgz",
+ "integrity": "sha512-MtFUYI1/8mgDvRmaBDjbLJPFFrMG777AvSgyIFQtZHIMzm88R/12vYBBpnk7pfiWLFE1DSZzY4WDYzGbKAcmiw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@ai-sdk/provider": "3.0.8",
+ "@standard-schema/spec": "^1.1.0",
+ "eventsource-parser": "^3.0.6"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "peerDependencies": {
+ "zod": "^3.25.76 || ^4.1.8"
+ }
+ },
+ "node_modules/@ai-sdk/provider-utils/node_modules/@ai-sdk/provider": {
+ "version": "3.0.8",
+ "resolved": "https://registry.npmjs.org/@ai-sdk/provider/-/provider-3.0.8.tgz",
+ "integrity": "sha512-oGMAgGoQdBXbZqNG0Ze56CHjDZ1IDYOwGYxYjO5KLSlz5HiNQ9udIXsPZ61VWaHGZ5XW/jyjmr6t2xz2jGVwbQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "json-schema": "^0.4.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@anthropic-ai/sdk": {
+ "version": "0.39.0",
+ "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.39.0.tgz",
+ "integrity": "sha512-eMyDIPRZbt1CCLErRCi3exlAvNkBtRe+kW5vvJyef93PmNr/clstYgHhtvmkxN82nlKgzyGPCyGxrm0JQ1ZIdg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "^18.11.18",
+ "@types/node-fetch": "^2.6.4",
+ "abort-controller": "^3.0.0",
+ "agentkeepalive": "^4.2.1",
+ "form-data-encoder": "1.7.2",
+ "formdata-node": "^4.3.2",
+ "node-fetch": "^2.6.7"
+ }
+ },
+ "node_modules/@esbuild/aix-ppc64": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.4.tgz",
+ "integrity": "sha512-cQPwL2mp2nSmHHJlCyoXgHGhbEPMrEEU5xhkcy3Hs/O7nGZqEpZ2sUtLaL9MORLtDfRvVl2/3PAuEkYZH0Ty8Q==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "aix"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.4.tgz",
+ "integrity": "sha512-X9bUgvxiC8CHAGKYufLIHGXPJWnr0OCdR0anD2e21vdvgCI8lIfqFbnoeOz7lBjdrAGUhqLZLcQo6MLhTO2DKQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm64": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.4.tgz",
+ "integrity": "sha512-gdLscB7v75wRfu7QSm/zg6Rx29VLdy9eTr2t44sfTW7CxwAtQghZ4ZnqHk3/ogz7xao0QAgrkradbBzcqFPasw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-x64": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.4.tgz",
+ "integrity": "sha512-PzPFnBNVF292sfpfhiyiXCGSn9HZg5BcAz+ivBuSsl6Rk4ga1oEXAamhOXRFyMcjwr2DVtm40G65N3GLeH1Lvw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-arm64": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.4.tgz",
+ "integrity": "sha512-b7xaGIwdJlht8ZFCvMkpDN6uiSmnxxK56N2GDTMYPr2/gzvfdQN8rTfBsvVKmIVY/X7EM+/hJKEIbbHs9oA4tQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-x64": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.4.tgz",
+ "integrity": "sha512-sR+OiKLwd15nmCdqpXMnuJ9W2kpy0KigzqScqHI3Hqwr7IXxBp3Yva+yJwoqh7rE8V77tdoheRYataNKL4QrPw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-arm64": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.4.tgz",
+ "integrity": "sha512-jnfpKe+p79tCnm4GVav68A7tUFeKQwQyLgESwEAUzyxk/TJr4QdGog9sqWNcUbr/bZt/O/HXouspuQDd9JxFSw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-x64": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.4.tgz",
+ "integrity": "sha512-2kb4ceA/CpfUrIcTUl1wrP/9ad9Atrp5J94Lq69w7UwOMolPIGrfLSvAKJp0RTvkPPyn6CIWrNy13kyLikZRZQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.4.tgz",
+ "integrity": "sha512-aBYgcIxX/wd5n2ys0yESGeYMGF+pv6g0DhZr3G1ZG4jMfruU9Tl1i2Z+Wnj9/KjGz1lTLCcorqE2viePZqj4Eg==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm64": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.4.tgz",
+ "integrity": "sha512-7nQOttdzVGth1iz57kxg9uCz57dxQLHWxopL6mYuYthohPKEK0vU0C3O21CcBK6KDlkYVcnDXY099HcCDXd9dA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ia32": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.4.tgz",
+ "integrity": "sha512-oPtixtAIzgvzYcKBQM/qZ3R+9TEUd1aNJQu0HhGyqtx6oS7qTpvjheIWBbes4+qu1bNlo2V4cbkISr8q6gRBFA==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-loong64": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.4.tgz",
+ "integrity": "sha512-8mL/vh8qeCoRcFH2nM8wm5uJP+ZcVYGGayMavi8GmRJjuI3g1v6Z7Ni0JJKAJW+m0EtUuARb6Lmp4hMjzCBWzA==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-mips64el": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.4.tgz",
+ "integrity": "sha512-1RdrWFFiiLIW7LQq9Q2NES+HiD4NyT8Itj9AUeCl0IVCA459WnPhREKgwrpaIfTOe+/2rdntisegiPWn/r/aAw==",
+ "cpu": [
+ "mips64el"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ppc64": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.4.tgz",
+ "integrity": "sha512-tLCwNG47l3sd9lpfyx9LAGEGItCUeRCWeAx6x2Jmbav65nAwoPXfewtAdtbtit/pJFLUWOhpv0FpS6GQAmPrHA==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-riscv64": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.4.tgz",
+ "integrity": "sha512-BnASypppbUWyqjd1KIpU4AUBiIhVr6YlHx/cnPgqEkNoVOhHg+YiSVxM1RLfiy4t9cAulbRGTNCKOcqHrEQLIw==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-s390x": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.4.tgz",
+ "integrity": "sha512-+eUqgb/Z7vxVLezG8bVB9SfBie89gMueS+I0xYh2tJdw3vqA/0ImZJ2ROeWwVJN59ihBeZ7Tu92dF/5dy5FttA==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-x64": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.4.tgz",
+ "integrity": "sha512-S5qOXrKV8BQEzJPVxAwnryi2+Iq5pB40gTEIT69BQONqR7JH1EPIcQ/Uiv9mCnn05jff9umq/5nqzxlqTOg9NA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-arm64": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.4.tgz",
+ "integrity": "sha512-xHT8X4sb0GS8qTqiwzHqpY00C95DPAq7nAwX35Ie/s+LO9830hrMd3oX0ZMKLvy7vsonee73x0lmcdOVXFzd6Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-x64": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.4.tgz",
+ "integrity": "sha512-RugOvOdXfdyi5Tyv40kgQnI0byv66BFgAqjdgtAKqHoZTbTF2QqfQrFwa7cHEORJf6X2ht+l9ABLMP0dnKYsgg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-arm64": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.4.tgz",
+ "integrity": "sha512-2MyL3IAaTX+1/qP0O1SwskwcwCoOI4kV2IBX1xYnDDqthmq5ArrW94qSIKCAuRraMgPOmG0RDTA74mzYNQA9ow==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-x64": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.4.tgz",
+ "integrity": "sha512-u8fg/jQ5aQDfsnIV6+KwLOf1CmJnfu1ShpwqdwC0uA7ZPwFws55Ngc12vBdeUdnuWoQYx/SOQLGDcdlfXhYmXQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openharmony-arm64": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.4.tgz",
+ "integrity": "sha512-JkTZrl6VbyO8lDQO3yv26nNr2RM2yZzNrNHEsj9bm6dOwwu9OYN28CjzZkH57bh4w0I2F7IodpQvUAEd1mbWXg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/sunos-x64": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.4.tgz",
+ "integrity": "sha512-/gOzgaewZJfeJTlsWhvUEmUG4tWEY2Spp5M20INYRg2ZKl9QPO3QEEgPeRtLjEWSW8FilRNacPOg8R1uaYkA6g==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "sunos"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-arm64": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.4.tgz",
+ "integrity": "sha512-Z9SExBg2y32smoDQdf1HRwHRt6vAHLXcxD2uGgO/v2jK7Y718Ix4ndsbNMU/+1Qiem9OiOdaqitioZwxivhXYg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-ia32": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.4.tgz",
+ "integrity": "sha512-DAyGLS0Jz5G5iixEbMHi5KdiApqHBWMGzTtMiJ72ZOLhbu/bzxgAe8Ue8CTS3n3HbIUHQz/L51yMdGMeoxXNJw==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-x64": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.4.tgz",
+ "integrity": "sha512-+knoa0BDoeXgkNvvV1vvbZX4+hizelrkwmGJBdT17t8FNPwG2lKemmuMZlmaNQ3ws3DKKCxpb4zRZEIp3UxFCg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@jridgewell/gen-mapping": {
+ "version": "0.3.13",
+ "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
+ "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/sourcemap-codec": "^1.5.0",
+ "@jridgewell/trace-mapping": "^0.3.24"
+ }
+ },
+ "node_modules/@jridgewell/resolve-uri": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
+ "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
+ "node_modules/@jridgewell/sourcemap-codec": {
+ "version": "1.5.5",
+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",
+ "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@jridgewell/trace-mapping": {
+ "version": "0.3.31",
+ "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",
+ "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/resolve-uri": "^3.1.0",
+ "@jridgewell/sourcemap-codec": "^1.4.14"
+ }
+ },
+ "node_modules/@opentelemetry/api": {
+ "version": "1.9.0",
+ "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.0.tgz",
+ "integrity": "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=8.0.0"
+ }
+ },
+ "node_modules/@rollup/rollup-android-arm-eabi": {
+ "version": "4.60.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.60.0.tgz",
+ "integrity": "sha512-WOhNW9K8bR3kf4zLxbfg6Pxu2ybOUbB2AjMDHSQx86LIF4rH4Ft7vmMwNt0loO0eonglSNy4cpD3MKXXKQu0/A==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ]
+ },
+ "node_modules/@rollup/rollup-android-arm64": {
+ "version": "4.60.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.60.0.tgz",
+ "integrity": "sha512-u6JHLll5QKRvjciE78bQXDmqRqNs5M/3GVqZeMwvmjaNODJih/WIrJlFVEihvV0MiYFmd+ZyPr9wxOVbPAG2Iw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ]
+ },
+ "node_modules/@rollup/rollup-darwin-arm64": {
+ "version": "4.60.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.60.0.tgz",
+ "integrity": "sha512-qEF7CsKKzSRc20Ciu2Zw1wRrBz4g56F7r/vRwY430UPp/nt1x21Q/fpJ9N5l47WWvJlkNCPJz3QRVw008fi7yA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ]
+ },
+ "node_modules/@rollup/rollup-darwin-x64": {
+ "version": "4.60.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.60.0.tgz",
+ "integrity": "sha512-WADYozJ4QCnXCH4wPB+3FuGmDPoFseVCUrANmA5LWwGmC6FL14BWC7pcq+FstOZv3baGX65tZ378uT6WG8ynTw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ]
+ },
+ "node_modules/@rollup/rollup-freebsd-arm64": {
+ "version": "4.60.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.60.0.tgz",
+ "integrity": "sha512-6b8wGHJlDrGeSE3aH5mGNHBjA0TTkxdoNHik5EkvPHCt351XnigA4pS7Wsj/Eo9Y8RBU6f35cjN9SYmCFBtzxw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ]
+ },
+ "node_modules/@rollup/rollup-freebsd-x64": {
+ "version": "4.60.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.60.0.tgz",
+ "integrity": "sha512-h25Ga0t4jaylMB8M/JKAyrvvfxGRjnPQIR8lnCayyzEjEOx2EJIlIiMbhpWxDRKGKF8jbNH01NnN663dH638mA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm-gnueabihf": {
+ "version": "4.60.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.60.0.tgz",
+ "integrity": "sha512-RzeBwv0B3qtVBWtcuABtSuCzToo2IEAIQrcyB/b2zMvBWVbjo8bZDjACUpnaafaxhTw2W+imQbP2BD1usasK4g==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm-musleabihf": {
+ "version": "4.60.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.60.0.tgz",
+ "integrity": "sha512-Sf7zusNI2CIU1HLzuu9Tc5YGAHEZs5Lu7N1ssJG4Tkw6e0MEsN7NdjUDDfGNHy2IU+ENyWT+L2obgWiguWibWQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm64-gnu": {
+ "version": "4.60.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.60.0.tgz",
+ "integrity": "sha512-DX2x7CMcrJzsE91q7/O02IJQ5/aLkVtYFryqCjduJhUfGKG6yJV8hxaw8pZa93lLEpPTP/ohdN4wFz7yp/ry9A==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm64-musl": {
+ "version": "4.60.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.60.0.tgz",
+ "integrity": "sha512-09EL+yFVbJZlhcQfShpswwRZ0Rg+z/CsSELFCnPt3iK+iqwGsI4zht3secj5vLEs957QvFFXnzAT0FFPIxSrkQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-loong64-gnu": {
+ "version": "4.60.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.60.0.tgz",
+ "integrity": "sha512-i9IcCMPr3EXm8EQg5jnja0Zyc1iFxJjZWlb4wr7U2Wx/GrddOuEafxRdMPRYVaXjgbhvqalp6np07hN1w9kAKw==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-loong64-musl": {
+ "version": "4.60.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.60.0.tgz",
+ "integrity": "sha512-DGzdJK9kyJ+B78MCkWeGnpXJ91tK/iKA6HwHxF4TAlPIY7GXEvMe8hBFRgdrR9Ly4qebR/7gfUs9y2IoaVEyog==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-ppc64-gnu": {
+ "version": "4.60.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.60.0.tgz",
+ "integrity": "sha512-RwpnLsqC8qbS8z1H1AxBA1H6qknR4YpPR9w2XX0vo2Sz10miu57PkNcnHVaZkbqyw/kUWfKMI73jhmfi9BRMUQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-ppc64-musl": {
+ "version": "4.60.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.60.0.tgz",
+ "integrity": "sha512-Z8pPf54Ly3aqtdWC3G4rFigZgNvd+qJlOE52fmko3KST9SoGfAdSRCwyoyG05q1HrrAblLbk1/PSIV+80/pxLg==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-riscv64-gnu": {
+ "version": "4.60.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.60.0.tgz",
+ "integrity": "sha512-3a3qQustp3COCGvnP4SvrMHnPQ9d1vzCakQVRTliaz8cIp/wULGjiGpbcqrkv0WrHTEp8bQD/B3HBjzujVWLOA==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-riscv64-musl": {
+ "version": "4.60.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.60.0.tgz",
+ "integrity": "sha512-pjZDsVH/1VsghMJ2/kAaxt6dL0psT6ZexQVrijczOf+PeP2BUqTHYejk3l6TlPRydggINOeNRhvpLa0AYpCWSQ==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-s390x-gnu": {
+ "version": "4.60.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.60.0.tgz",
+ "integrity": "sha512-3ObQs0BhvPgiUVZrN7gqCSvmFuMWvWvsjG5ayJ3Lraqv+2KhOsp+pUbigqbeWqueGIsnn+09HBw27rJ+gYK4VQ==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-x64-gnu": {
+ "version": "4.60.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.60.0.tgz",
+ "integrity": "sha512-EtylprDtQPdS5rXvAayrNDYoJhIz1/vzN2fEubo3yLE7tfAw+948dO0g4M0vkTVFhKojnF+n6C8bDNe+gDRdTg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-x64-musl": {
+ "version": "4.60.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.60.0.tgz",
+ "integrity": "sha512-k09oiRCi/bHU9UVFqD17r3eJR9bn03TyKraCrlz5ULFJGdJGi7VOmm9jl44vOJvRJ6P7WuBi/s2A97LxxHGIdw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-openbsd-x64": {
+ "version": "4.60.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.60.0.tgz",
+ "integrity": "sha512-1o/0/pIhozoSaDJoDcec+IVLbnRtQmHwPV730+AOD29lHEEo4F5BEUB24H0OBdhbBBDwIOSuf7vgg0Ywxdfiiw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ]
+ },
+ "node_modules/@rollup/rollup-openharmony-arm64": {
+ "version": "4.60.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.60.0.tgz",
+ "integrity": "sha512-pESDkos/PDzYwtyzB5p/UoNU/8fJo68vcXM9ZW2V0kjYayj1KaaUfi1NmTUTUpMn4UhU4gTuK8gIaFO4UGuMbA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-arm64-msvc": {
+ "version": "4.60.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.60.0.tgz",
+ "integrity": "sha512-hj1wFStD7B1YBeYmvY+lWXZ7ey73YGPcViMShYikqKT1GtstIKQAtfUI6yrzPjAy/O7pO0VLXGmUVWXQMaYgTQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-ia32-msvc": {
+ "version": "4.60.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.60.0.tgz",
+ "integrity": "sha512-SyaIPFoxmUPlNDq5EHkTbiKzmSEmq/gOYFI/3HHJ8iS/v1mbugVa7dXUzcJGQfoytp9DJFLhHH4U3/eTy2Bq4w==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-x64-gnu": {
+ "version": "4.60.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.60.0.tgz",
+ "integrity": "sha512-RdcryEfzZr+lAr5kRm2ucN9aVlCCa2QNq4hXelZxb8GG0NJSazq44Z3PCCc8wISRuCVnGs0lQJVX5Vp6fKA+IA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-x64-msvc": {
+ "version": "4.60.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.60.0.tgz",
+ "integrity": "sha512-PrsWNQ8BuE00O3Xsx3ALh2Df8fAj9+cvvX9AIA6o4KpATR98c9mud4XtDWVvsEuyia5U4tVSTKygawyJkjm60w==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@standard-schema/spec": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",
+ "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/estree": {
+ "version": "1.0.8",
+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",
+ "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/node": {
+ "version": "18.19.130",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.130.tgz",
+ "integrity": "sha512-GRaXQx6jGfL8sKfaIDD6OupbIHBr9jv7Jnaml9tB7l4v068PAOXqfcujMMo5PhbIs6ggR1XODELqahT2R8v0fg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "undici-types": "~5.26.4"
+ }
+ },
+ "node_modules/@types/node-fetch": {
+ "version": "2.6.13",
+ "resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.6.13.tgz",
+ "integrity": "sha512-QGpRVpzSaUs30JBSGPjOg4Uveu384erbHBoT1zeONvyCfwQxIkUshLAOqN/k9EjGviPRmWTTe6aH2qySWKTVSw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "*",
+ "form-data": "^4.0.4"
+ }
+ },
+ "node_modules/@vercel/oidc": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/@vercel/oidc/-/oidc-3.1.0.tgz",
+ "integrity": "sha512-Fw28YZpRnA3cAHHDlkt7xQHiJ0fcL+NRcIqsocZQUSmbzeIKRpwttJjik5ZGanXP+vlA4SbTg+AbA3bP363l+w==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">= 20"
+ }
+ },
+ "node_modules/@vitest/expect": {
+ "version": "2.1.9",
+ "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-2.1.9.tgz",
+ "integrity": "sha512-UJCIkTBenHeKT1TTlKMJWy1laZewsRIzYighyYiJKZreqtdxSos/S1t+ktRMQWu2CKqaarrkeszJx1cgC5tGZw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/spy": "2.1.9",
+ "@vitest/utils": "2.1.9",
+ "chai": "^5.1.2",
+ "tinyrainbow": "^1.2.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/mocker": {
+ "version": "2.1.9",
+ "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-2.1.9.tgz",
+ "integrity": "sha512-tVL6uJgoUdi6icpxmdrn5YNo3g3Dxv+IHJBr0GXHaEdTcw3F+cPKnsXFhli6nO+f/6SDKPHEK1UN+k+TQv0Ehg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/spy": "2.1.9",
+ "estree-walker": "^3.0.3",
+ "magic-string": "^0.30.12"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ },
+ "peerDependencies": {
+ "msw": "^2.4.9",
+ "vite": "^5.0.0"
+ },
+ "peerDependenciesMeta": {
+ "msw": {
+ "optional": true
+ },
+ "vite": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@vitest/pretty-format": {
+ "version": "2.1.9",
+ "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-2.1.9.tgz",
+ "integrity": "sha512-KhRIdGV2U9HOUzxfiHmY8IFHTdqtOhIzCpd8WRdJiE7D/HUcZVD0EgQCVjm+Q9gkUXWgBvMmTtZgIG48wq7sOQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "tinyrainbow": "^1.2.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/runner": {
+ "version": "2.1.9",
+ "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-2.1.9.tgz",
+ "integrity": "sha512-ZXSSqTFIrzduD63btIfEyOmNcBmQvgOVsPNPe0jYtESiXkhd8u2erDLnMxmGrDCwHCCHE7hxwRDCT3pt0esT4g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/utils": "2.1.9",
+ "pathe": "^1.1.2"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/runner/node_modules/pathe": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/pathe/-/pathe-1.1.2.tgz",
+ "integrity": "sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@vitest/snapshot": {
+ "version": "2.1.9",
+ "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-2.1.9.tgz",
+ "integrity": "sha512-oBO82rEjsxLNJincVhLhaxxZdEtV0EFHMK5Kmx5sJ6H9L183dHECjiefOAdnqpIgT5eZwT04PoggUnW88vOBNQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/pretty-format": "2.1.9",
+ "magic-string": "^0.30.12",
+ "pathe": "^1.1.2"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/snapshot/node_modules/pathe": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/pathe/-/pathe-1.1.2.tgz",
+ "integrity": "sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@vitest/spy": {
+ "version": "2.1.9",
+ "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-2.1.9.tgz",
+ "integrity": "sha512-E1B35FwzXXTs9FHNK6bDszs7mtydNi5MIfUWpceJ8Xbfb1gBMscAnwLbEu+B44ed6W3XjL9/ehLPHR1fkf1KLQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "tinyspy": "^3.0.2"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/utils": {
+ "version": "2.1.9",
+ "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-2.1.9.tgz",
+ "integrity": "sha512-v0psaMSkNJ3A2NMrUEHFRzJtDPFn+/VWZ5WxImB21T9fjucJRmS7xCS3ppEnARb9y11OAzaD+P2Ps+b+BGX5iQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/pretty-format": "2.1.9",
+ "loupe": "^3.1.2",
+ "tinyrainbow": "^1.2.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/abort-controller": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz",
+ "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "event-target-shim": "^5.0.0"
+ },
+ "engines": {
+ "node": ">=6.5"
+ }
+ },
+ "node_modules/acorn": {
+ "version": "8.16.0",
+ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz",
+ "integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "acorn": "bin/acorn"
+ },
+ "engines": {
+ "node": ">=0.4.0"
+ }
+ },
+ "node_modules/agentkeepalive": {
+ "version": "4.6.0",
+ "resolved": "https://registry.npmjs.org/agentkeepalive/-/agentkeepalive-4.6.0.tgz",
+ "integrity": "sha512-kja8j7PjmncONqaTsB8fQ+wE2mSU2DJ9D4XKoJ5PFWIdRMa6SLSN1ff4mOr4jCbfRSsxR4keIiySJU0N9T5hIQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "humanize-ms": "^1.2.1"
+ },
+ "engines": {
+ "node": ">= 8.0.0"
+ }
+ },
+ "node_modules/ai": {
+ "version": "6.0.138",
+ "resolved": "https://registry.npmjs.org/ai/-/ai-6.0.138.tgz",
+ "integrity": "sha512-49OfPe0f5uxJ6jUdA5BBXjIinP6+ZdYfAtpF2aEH64GA5wPcxH2rf/TBUQQ0bbamBz/D+TLMV18xilZqOC+zaA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@ai-sdk/gateway": "3.0.80",
+ "@ai-sdk/provider": "3.0.8",
+ "@ai-sdk/provider-utils": "4.0.21",
+ "@opentelemetry/api": "1.9.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "peerDependencies": {
+ "zod": "^3.25.76 || ^4.1.8"
+ }
+ },
+ "node_modules/ai/node_modules/@ai-sdk/provider": {
+ "version": "3.0.8",
+ "resolved": "https://registry.npmjs.org/@ai-sdk/provider/-/provider-3.0.8.tgz",
+ "integrity": "sha512-oGMAgGoQdBXbZqNG0Ze56CHjDZ1IDYOwGYxYjO5KLSlz5HiNQ9udIXsPZ61VWaHGZ5XW/jyjmr6t2xz2jGVwbQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "json-schema": "^0.4.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/any-promise": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz",
+ "integrity": "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/assertion-error": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
+ "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/asynckit": {
+ "version": "0.4.0",
+ "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
+ "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/bundle-require": {
+ "version": "5.1.0",
+ "resolved": "https://registry.npmjs.org/bundle-require/-/bundle-require-5.1.0.tgz",
+ "integrity": "sha512-3WrrOuZiyaaZPWiEt4G3+IffISVC9HYlWueJEBWED4ZH4aIAC2PnkdnuRrR94M+w6yGWn4AglWtJtBI8YqvgoA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "load-tsconfig": "^0.2.3"
+ },
+ "engines": {
+ "node": "^12.20.0 || ^14.13.1 || >=16.0.0"
+ },
+ "peerDependencies": {
+ "esbuild": ">=0.18"
+ }
+ },
+ "node_modules/cac": {
+ "version": "6.7.14",
+ "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz",
+ "integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/call-bind-apply-helpers": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
+ "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "function-bind": "^1.1.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/chai": {
+ "version": "5.3.3",
+ "resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz",
+ "integrity": "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "assertion-error": "^2.0.1",
+ "check-error": "^2.1.1",
+ "deep-eql": "^5.0.1",
+ "loupe": "^3.1.0",
+ "pathval": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/check-error": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.3.tgz",
+ "integrity": "sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 16"
+ }
+ },
+ "node_modules/chokidar": {
+ "version": "4.0.3",
+ "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz",
+ "integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "readdirp": "^4.0.1"
+ },
+ "engines": {
+ "node": ">= 14.16.0"
+ },
+ "funding": {
+ "url": "https://paulmillr.com/funding/"
+ }
+ },
+ "node_modules/combined-stream": {
+ "version": "1.0.8",
+ "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
+ "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "delayed-stream": "~1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/commander": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz",
+ "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 6"
+ }
+ },
+ "node_modules/confbox": {
+ "version": "0.1.8",
+ "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.1.8.tgz",
+ "integrity": "sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/consola": {
+ "version": "3.4.2",
+ "resolved": "https://registry.npmjs.org/consola/-/consola-3.4.2.tgz",
+ "integrity": "sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "^14.18.0 || >=16.10.0"
+ }
+ },
+ "node_modules/debug": {
+ "version": "4.4.3",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "ms": "^2.1.3"
+ },
+ "engines": {
+ "node": ">=6.0"
+ },
+ "peerDependenciesMeta": {
+ "supports-color": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/deep-eql": {
+ "version": "5.0.2",
+ "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz",
+ "integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/delayed-stream": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
+ "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.4.0"
+ }
+ },
+ "node_modules/dunder-proto": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
+ "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind-apply-helpers": "^1.0.1",
+ "es-errors": "^1.3.0",
+ "gopd": "^1.2.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/es-define-property": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
+ "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/es-errors": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
+ "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/es-module-lexer": {
+ "version": "1.7.0",
+ "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz",
+ "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/es-object-atoms": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz",
+ "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/es-set-tostringtag": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",
+ "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "get-intrinsic": "^1.2.6",
+ "has-tostringtag": "^1.0.2",
+ "hasown": "^2.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/esbuild": {
+ "version": "0.27.4",
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.4.tgz",
+ "integrity": "sha512-Rq4vbHnYkK5fws5NF7MYTU68FPRE1ajX7heQ/8QXXWqNgqqJ/GkmmyxIzUnf2Sr/bakf8l54716CcMGHYhMrrQ==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "bin": {
+ "esbuild": "bin/esbuild"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "optionalDependencies": {
+ "@esbuild/aix-ppc64": "0.27.4",
+ "@esbuild/android-arm": "0.27.4",
+ "@esbuild/android-arm64": "0.27.4",
+ "@esbuild/android-x64": "0.27.4",
+ "@esbuild/darwin-arm64": "0.27.4",
+ "@esbuild/darwin-x64": "0.27.4",
+ "@esbuild/freebsd-arm64": "0.27.4",
+ "@esbuild/freebsd-x64": "0.27.4",
+ "@esbuild/linux-arm": "0.27.4",
+ "@esbuild/linux-arm64": "0.27.4",
+ "@esbuild/linux-ia32": "0.27.4",
+ "@esbuild/linux-loong64": "0.27.4",
+ "@esbuild/linux-mips64el": "0.27.4",
+ "@esbuild/linux-ppc64": "0.27.4",
+ "@esbuild/linux-riscv64": "0.27.4",
+ "@esbuild/linux-s390x": "0.27.4",
+ "@esbuild/linux-x64": "0.27.4",
+ "@esbuild/netbsd-arm64": "0.27.4",
+ "@esbuild/netbsd-x64": "0.27.4",
+ "@esbuild/openbsd-arm64": "0.27.4",
+ "@esbuild/openbsd-x64": "0.27.4",
+ "@esbuild/openharmony-arm64": "0.27.4",
+ "@esbuild/sunos-x64": "0.27.4",
+ "@esbuild/win32-arm64": "0.27.4",
+ "@esbuild/win32-ia32": "0.27.4",
+ "@esbuild/win32-x64": "0.27.4"
+ }
+ },
+ "node_modules/estree-walker": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
+ "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "^1.0.0"
+ }
+ },
+ "node_modules/event-target-shim": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz",
+ "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/eventsource-parser": {
+ "version": "3.0.6",
+ "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.0.6.tgz",
+ "integrity": "sha512-Vo1ab+QXPzZ4tCa8SwIHJFaSzy4R6SHf7BY79rFBDf0idraZWAkYrDjDj8uWaSm3S2TK+hJ7/t1CEmZ7jXw+pg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/expect-type": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.3.0.tgz",
+ "integrity": "sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=12.0.0"
+ }
+ },
+ "node_modules/fdir": {
+ "version": "6.5.0",
+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "peerDependencies": {
+ "picomatch": "^3 || ^4"
+ },
+ "peerDependenciesMeta": {
+ "picomatch": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/fix-dts-default-cjs-exports": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/fix-dts-default-cjs-exports/-/fix-dts-default-cjs-exports-1.0.1.tgz",
+ "integrity": "sha512-pVIECanWFC61Hzl2+oOCtoJ3F17kglZC/6N94eRWycFgBH35hHx0Li604ZIzhseh97mf2p0cv7vVrOZGoqhlEg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "magic-string": "^0.30.17",
+ "mlly": "^1.7.4",
+ "rollup": "^4.34.8"
+ }
+ },
+ "node_modules/form-data": {
+ "version": "4.0.5",
+ "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.5.tgz",
+ "integrity": "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "asynckit": "^0.4.0",
+ "combined-stream": "^1.0.8",
+ "es-set-tostringtag": "^2.1.0",
+ "hasown": "^2.0.2",
+ "mime-types": "^2.1.12"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
+ "node_modules/form-data-encoder": {
+ "version": "1.7.2",
+ "resolved": "https://registry.npmjs.org/form-data-encoder/-/form-data-encoder-1.7.2.tgz",
+ "integrity": "sha512-qfqtYan3rxrnCk1VYaA4H+Ms9xdpPqvLZa6xmMgFvhO32x7/3J/ExcTd6qpxM0vH2GdMI+poehyBZvqfMTto8A==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/formdata-node": {
+ "version": "4.4.1",
+ "resolved": "https://registry.npmjs.org/formdata-node/-/formdata-node-4.4.1.tgz",
+ "integrity": "sha512-0iirZp3uVDjVGt9p49aTaqjk84TrglENEDuqfdlZQ1roC9CWlPk6Avf8EEnZNcAqPonwkG35x4n3ww/1THYAeQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "node-domexception": "1.0.0",
+ "web-streams-polyfill": "4.0.0-beta.3"
+ },
+ "engines": {
+ "node": ">= 12.20"
+ }
+ },
+ "node_modules/fsevents": {
+ "version": "2.3.3",
+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
+ }
+ },
+ "node_modules/function-bind": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
+ "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/get-intrinsic": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
+ "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind-apply-helpers": "^1.0.2",
+ "es-define-property": "^1.0.1",
+ "es-errors": "^1.3.0",
+ "es-object-atoms": "^1.1.1",
+ "function-bind": "^1.1.2",
+ "get-proto": "^1.0.1",
+ "gopd": "^1.2.0",
+ "has-symbols": "^1.1.0",
+ "hasown": "^2.0.2",
+ "math-intrinsics": "^1.1.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/get-proto": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
+ "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "dunder-proto": "^1.0.1",
+ "es-object-atoms": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/gopd": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
+ "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/has-symbols": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
+ "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/has-tostringtag": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",
+ "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "has-symbols": "^1.0.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/hasown": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",
+ "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "function-bind": "^1.1.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/humanize-ms": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/humanize-ms/-/humanize-ms-1.2.1.tgz",
+ "integrity": "sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "ms": "^2.0.0"
+ }
+ },
+ "node_modules/joycon": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/joycon/-/joycon-3.1.1.tgz",
+ "integrity": "sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/json-schema": {
+ "version": "0.4.0",
+ "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.4.0.tgz",
+ "integrity": "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA==",
+ "dev": true,
+ "license": "(AFL-2.1 OR BSD-3-Clause)"
+ },
+ "node_modules/lilconfig": {
+ "version": "3.1.3",
+ "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.3.tgz",
+ "integrity": "sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=14"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/antonk52"
+ }
+ },
+ "node_modules/lines-and-columns": {
+ "version": "1.2.4",
+ "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz",
+ "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/load-tsconfig": {
+ "version": "0.2.5",
+ "resolved": "https://registry.npmjs.org/load-tsconfig/-/load-tsconfig-0.2.5.tgz",
+ "integrity": "sha512-IXO6OCs9yg8tMKzfPZ1YmheJbZCiEsnBdcB03l0OcfK9prKnJb96siuHCr5Fl37/yo9DnKU+TLpxzTUspw9shg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "^12.20.0 || ^14.13.1 || >=16.0.0"
+ }
+ },
+ "node_modules/loupe": {
+ "version": "3.2.1",
+ "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz",
+ "integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/magic-string": {
+ "version": "0.30.21",
+ "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
+ "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/sourcemap-codec": "^1.5.5"
+ }
+ },
+ "node_modules/math-intrinsics": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
+ "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/mime-db": {
+ "version": "1.52.0",
+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
+ "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/mime-types": {
+ "version": "2.1.35",
+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
+ "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "mime-db": "1.52.0"
+ },
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/mlly": {
+ "version": "1.8.2",
+ "resolved": "https://registry.npmjs.org/mlly/-/mlly-1.8.2.tgz",
+ "integrity": "sha512-d+ObxMQFmbt10sretNDytwt85VrbkhhUA/JBGm1MPaWJ65Cl4wOgLaB1NYvJSZ0Ef03MMEU/0xpPMXUIQ29UfA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "acorn": "^8.16.0",
+ "pathe": "^2.0.3",
+ "pkg-types": "^1.3.1",
+ "ufo": "^1.6.3"
+ }
+ },
+ "node_modules/ms": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/mz": {
+ "version": "2.7.0",
+ "resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz",
+ "integrity": "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "any-promise": "^1.0.0",
+ "object-assign": "^4.0.1",
+ "thenify-all": "^1.0.0"
+ }
+ },
+ "node_modules/nanoid": {
+ "version": "3.3.11",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz",
+ "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "bin": {
+ "nanoid": "bin/nanoid.cjs"
+ },
+ "engines": {
+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
+ }
+ },
+ "node_modules/node-domexception": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz",
+ "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==",
+ "deprecated": "Use your platform's native DOMException instead",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/jimmywarting"
+ },
+ {
+ "type": "github",
+ "url": "https://paypal.me/jimmywarting"
+ }
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=10.5.0"
+ }
+ },
+ "node_modules/node-fetch": {
+ "version": "2.7.0",
+ "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz",
+ "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "whatwg-url": "^5.0.0"
+ },
+ "engines": {
+ "node": "4.x || >=6.0.0"
+ },
+ "peerDependencies": {
+ "encoding": "^0.1.0"
+ },
+ "peerDependenciesMeta": {
+ "encoding": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/object-assign": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
+ "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/openai": {
+ "version": "4.104.0",
+ "resolved": "https://registry.npmjs.org/openai/-/openai-4.104.0.tgz",
+ "integrity": "sha512-p99EFNsA/yX6UhVO93f5kJsDRLAg+CTA2RBqdHK4RtK8u5IJw32Hyb2dTGKbnnFmnuoBv5r7Z2CURI9sGZpSuA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@types/node": "^18.11.18",
+ "@types/node-fetch": "^2.6.4",
+ "abort-controller": "^3.0.0",
+ "agentkeepalive": "^4.2.1",
+ "form-data-encoder": "1.7.2",
+ "formdata-node": "^4.3.2",
+ "node-fetch": "^2.6.7"
+ },
+ "bin": {
+ "openai": "bin/cli"
+ },
+ "peerDependencies": {
+ "ws": "^8.18.0",
+ "zod": "^3.23.8"
+ },
+ "peerDependenciesMeta": {
+ "ws": {
+ "optional": true
+ },
+ "zod": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/pathe": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",
+ "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/pathval": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/pathval/-/pathval-2.0.1.tgz",
+ "integrity": "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 14.16"
+ }
+ },
+ "node_modules/picocolors": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/picomatch": {
+ "version": "4.0.4",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz",
+ "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/jonschlinkert"
+ }
+ },
+ "node_modules/pirates": {
+ "version": "4.0.7",
+ "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.7.tgz",
+ "integrity": "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 6"
+ }
+ },
+ "node_modules/pkg-types": {
+ "version": "1.3.1",
+ "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-1.3.1.tgz",
+ "integrity": "sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "confbox": "^0.1.8",
+ "mlly": "^1.7.4",
+ "pathe": "^2.0.1"
+ }
+ },
+ "node_modules/postcss": {
+ "version": "8.5.8",
+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.8.tgz",
+ "integrity": "sha512-OW/rX8O/jXnm82Ey1k44pObPtdblfiuWnrd8X7GJ7emImCOstunGbXUpp7HdBrFQX6rJzn3sPT397Wp5aCwCHg==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/postcss/"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/postcss"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "nanoid": "^3.3.11",
+ "picocolors": "^1.1.1",
+ "source-map-js": "^1.2.1"
+ },
+ "engines": {
+ "node": "^10 || ^12 || >=14"
+ }
+ },
+ "node_modules/postcss-load-config": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/postcss-load-config/-/postcss-load-config-6.0.1.tgz",
+ "integrity": "sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/postcss/"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "lilconfig": "^3.1.1"
+ },
+ "engines": {
+ "node": ">= 18"
+ },
+ "peerDependencies": {
+ "jiti": ">=1.21.0",
+ "postcss": ">=8.0.9",
+ "tsx": "^4.8.1",
+ "yaml": "^2.4.2"
+ },
+ "peerDependenciesMeta": {
+ "jiti": {
+ "optional": true
+ },
+ "postcss": {
+ "optional": true
+ },
+ "tsx": {
+ "optional": true
+ },
+ "yaml": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/readdirp": {
+ "version": "4.1.2",
+ "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz",
+ "integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 14.18.0"
+ },
+ "funding": {
+ "type": "individual",
+ "url": "https://paulmillr.com/funding/"
+ }
+ },
+ "node_modules/resolve-from": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz",
+ "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/rollup": {
+ "version": "4.60.0",
+ "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.60.0.tgz",
+ "integrity": "sha512-yqjxruMGBQJ2gG4HtjZtAfXArHomazDHoFwFFmZZl0r7Pdo7qCIXKqKHZc8yeoMgzJJ+pO6pEEHa+V7uzWlrAQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "1.0.8"
+ },
+ "bin": {
+ "rollup": "dist/bin/rollup"
+ },
+ "engines": {
+ "node": ">=18.0.0",
+ "npm": ">=8.0.0"
+ },
+ "optionalDependencies": {
+ "@rollup/rollup-android-arm-eabi": "4.60.0",
+ "@rollup/rollup-android-arm64": "4.60.0",
+ "@rollup/rollup-darwin-arm64": "4.60.0",
+ "@rollup/rollup-darwin-x64": "4.60.0",
+ "@rollup/rollup-freebsd-arm64": "4.60.0",
+ "@rollup/rollup-freebsd-x64": "4.60.0",
+ "@rollup/rollup-linux-arm-gnueabihf": "4.60.0",
+ "@rollup/rollup-linux-arm-musleabihf": "4.60.0",
+ "@rollup/rollup-linux-arm64-gnu": "4.60.0",
+ "@rollup/rollup-linux-arm64-musl": "4.60.0",
+ "@rollup/rollup-linux-loong64-gnu": "4.60.0",
+ "@rollup/rollup-linux-loong64-musl": "4.60.0",
+ "@rollup/rollup-linux-ppc64-gnu": "4.60.0",
+ "@rollup/rollup-linux-ppc64-musl": "4.60.0",
+ "@rollup/rollup-linux-riscv64-gnu": "4.60.0",
+ "@rollup/rollup-linux-riscv64-musl": "4.60.0",
+ "@rollup/rollup-linux-s390x-gnu": "4.60.0",
+ "@rollup/rollup-linux-x64-gnu": "4.60.0",
+ "@rollup/rollup-linux-x64-musl": "4.60.0",
+ "@rollup/rollup-openbsd-x64": "4.60.0",
+ "@rollup/rollup-openharmony-arm64": "4.60.0",
+ "@rollup/rollup-win32-arm64-msvc": "4.60.0",
+ "@rollup/rollup-win32-ia32-msvc": "4.60.0",
+ "@rollup/rollup-win32-x64-gnu": "4.60.0",
+ "@rollup/rollup-win32-x64-msvc": "4.60.0",
+ "fsevents": "~2.3.2"
+ }
+ },
+ "node_modules/siginfo": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz",
+ "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/source-map": {
+ "version": "0.7.6",
+ "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.6.tgz",
+ "integrity": "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">= 12"
+ }
+ },
+ "node_modules/source-map-js": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
+ "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/stackback": {
+ "version": "0.0.2",
+ "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz",
+ "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/std-env": {
+ "version": "3.10.0",
+ "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz",
+ "integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/sucrase": {
+ "version": "3.35.1",
+ "resolved": "https://registry.npmjs.org/sucrase/-/sucrase-3.35.1.tgz",
+ "integrity": "sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/gen-mapping": "^0.3.2",
+ "commander": "^4.0.0",
+ "lines-and-columns": "^1.1.6",
+ "mz": "^2.7.0",
+ "pirates": "^4.0.1",
+ "tinyglobby": "^0.2.11",
+ "ts-interface-checker": "^0.1.9"
+ },
+ "bin": {
+ "sucrase": "bin/sucrase",
+ "sucrase-node": "bin/sucrase-node"
+ },
+ "engines": {
+ "node": ">=16 || 14 >=14.17"
+ }
+ },
+ "node_modules/thenify": {
+ "version": "3.3.1",
+ "resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz",
+ "integrity": "sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "any-promise": "^1.0.0"
+ }
+ },
+ "node_modules/thenify-all": {
+ "version": "1.6.0",
+ "resolved": "https://registry.npmjs.org/thenify-all/-/thenify-all-1.6.0.tgz",
+ "integrity": "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "thenify": ">= 3.1.0 < 4"
+ },
+ "engines": {
+ "node": ">=0.8"
+ }
+ },
+ "node_modules/tinybench": {
+ "version": "2.9.0",
+ "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",
+ "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/tinyexec": {
+ "version": "0.3.2",
+ "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-0.3.2.tgz",
+ "integrity": "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/tinyglobby": {
+ "version": "0.2.15",
+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz",
+ "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "fdir": "^6.5.0",
+ "picomatch": "^4.0.3"
+ },
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/SuperchupuDev"
+ }
+ },
+ "node_modules/tinypool": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-1.1.1.tgz",
+ "integrity": "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "^18.0.0 || >=20.0.0"
+ }
+ },
+ "node_modules/tinyrainbow": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-1.2.0.tgz",
+ "integrity": "sha512-weEDEq7Z5eTHPDh4xjX789+fHfF+P8boiFB+0vbWzpbnbsEr/GRaohi/uMKxg8RZMXnl1ItAi/IUHWMsjDV7kQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=14.0.0"
+ }
+ },
+ "node_modules/tinyspy": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-3.0.2.tgz",
+ "integrity": "sha512-n1cw8k1k0x4pgA2+9XrOkFydTerNcJ1zWCO5Nn9scWHTD+5tp8dghT2x1uduQePZTZgd3Tupf+x9BxJjeJi77Q==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=14.0.0"
+ }
+ },
+ "node_modules/tr46": {
+ "version": "0.0.3",
+ "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
+ "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/tree-kill": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz",
+ "integrity": "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "tree-kill": "cli.js"
+ }
+ },
+ "node_modules/ts-interface-checker": {
+ "version": "0.1.13",
+ "resolved": "https://registry.npmjs.org/ts-interface-checker/-/ts-interface-checker-0.1.13.tgz",
+ "integrity": "sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==",
+ "dev": true,
+ "license": "Apache-2.0"
+ },
+ "node_modules/tsup": {
+ "version": "8.5.1",
+ "resolved": "https://registry.npmjs.org/tsup/-/tsup-8.5.1.tgz",
+ "integrity": "sha512-xtgkqwdhpKWr3tKPmCkvYmS9xnQK3m3XgxZHwSUjvfTjp7YfXe5tT3GgWi0F2N+ZSMsOeWeZFh7ZZFg5iPhing==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "bundle-require": "^5.1.0",
+ "cac": "^6.7.14",
+ "chokidar": "^4.0.3",
+ "consola": "^3.4.0",
+ "debug": "^4.4.0",
+ "esbuild": "^0.27.0",
+ "fix-dts-default-cjs-exports": "^1.0.0",
+ "joycon": "^3.1.1",
+ "picocolors": "^1.1.1",
+ "postcss-load-config": "^6.0.1",
+ "resolve-from": "^5.0.0",
+ "rollup": "^4.34.8",
+ "source-map": "^0.7.6",
+ "sucrase": "^3.35.0",
+ "tinyexec": "^0.3.2",
+ "tinyglobby": "^0.2.11",
+ "tree-kill": "^1.2.2"
+ },
+ "bin": {
+ "tsup": "dist/cli-default.js",
+ "tsup-node": "dist/cli-node.js"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "peerDependencies": {
+ "@microsoft/api-extractor": "^7.36.0",
+ "@swc/core": "^1",
+ "postcss": "^8.4.12",
+ "typescript": ">=4.5.0"
+ },
+ "peerDependenciesMeta": {
+ "@microsoft/api-extractor": {
+ "optional": true
+ },
+ "@swc/core": {
+ "optional": true
+ },
+ "postcss": {
+ "optional": true
+ },
+ "typescript": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/typescript": {
+ "version": "5.9.3",
+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "tsc": "bin/tsc",
+ "tsserver": "bin/tsserver"
+ },
+ "engines": {
+ "node": ">=14.17"
+ }
+ },
+ "node_modules/ufo": {
+ "version": "1.6.3",
+ "resolved": "https://registry.npmjs.org/ufo/-/ufo-1.6.3.tgz",
+ "integrity": "sha512-yDJTmhydvl5lJzBmy/hyOAA0d+aqCBuwl818haVdYCRrWV84o7YyeVm4QlVHStqNrrJSTb6jKuFAVqAFsr+K3Q==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/undici-types": {
+ "version": "5.26.5",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz",
+ "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/vite": {
+ "version": "5.4.21",
+ "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.21.tgz",
+ "integrity": "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "esbuild": "^0.21.3",
+ "postcss": "^8.4.43",
+ "rollup": "^4.20.0"
+ },
+ "bin": {
+ "vite": "bin/vite.js"
+ },
+ "engines": {
+ "node": "^18.0.0 || >=20.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/vitejs/vite?sponsor=1"
+ },
+ "optionalDependencies": {
+ "fsevents": "~2.3.3"
+ },
+ "peerDependencies": {
+ "@types/node": "^18.0.0 || >=20.0.0",
+ "less": "*",
+ "lightningcss": "^1.21.0",
+ "sass": "*",
+ "sass-embedded": "*",
+ "stylus": "*",
+ "sugarss": "*",
+ "terser": "^5.4.0"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ },
+ "less": {
+ "optional": true
+ },
+ "lightningcss": {
+ "optional": true
+ },
+ "sass": {
+ "optional": true
+ },
+ "sass-embedded": {
+ "optional": true
+ },
+ "stylus": {
+ "optional": true
+ },
+ "sugarss": {
+ "optional": true
+ },
+ "terser": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/vite-node": {
+ "version": "2.1.9",
+ "resolved": "https://registry.npmjs.org/vite-node/-/vite-node-2.1.9.tgz",
+ "integrity": "sha512-AM9aQ/IPrW/6ENLQg3AGY4K1N2TGZdR5e4gu/MmmR2xR3Ll1+dib+nook92g4TV3PXVyeyxdWwtaCAiUL0hMxA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "cac": "^6.7.14",
+ "debug": "^4.3.7",
+ "es-module-lexer": "^1.5.4",
+ "pathe": "^1.1.2",
+ "vite": "^5.0.0"
+ },
+ "bin": {
+ "vite-node": "vite-node.mjs"
+ },
+ "engines": {
+ "node": "^18.0.0 || >=20.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/vite-node/node_modules/pathe": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/pathe/-/pathe-1.1.2.tgz",
+ "integrity": "sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/vite/node_modules/@esbuild/aix-ppc64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz",
+ "integrity": "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "aix"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/android-arm": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.21.5.tgz",
+ "integrity": "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/android-arm64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.21.5.tgz",
+ "integrity": "sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/android-x64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.21.5.tgz",
+ "integrity": "sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/darwin-arm64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.21.5.tgz",
+ "integrity": "sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/darwin-x64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.21.5.tgz",
+ "integrity": "sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/freebsd-arm64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.21.5.tgz",
+ "integrity": "sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/freebsd-x64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.21.5.tgz",
+ "integrity": "sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/linux-arm": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.21.5.tgz",
+ "integrity": "sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/linux-arm64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.21.5.tgz",
+ "integrity": "sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/linux-ia32": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.21.5.tgz",
+ "integrity": "sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/linux-loong64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.21.5.tgz",
+ "integrity": "sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/linux-mips64el": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.21.5.tgz",
+ "integrity": "sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==",
+ "cpu": [
+ "mips64el"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/linux-ppc64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.21.5.tgz",
+ "integrity": "sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/linux-riscv64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.21.5.tgz",
+ "integrity": "sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/linux-s390x": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.21.5.tgz",
+ "integrity": "sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/linux-x64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz",
+ "integrity": "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/netbsd-x64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.21.5.tgz",
+ "integrity": "sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/openbsd-x64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.21.5.tgz",
+ "integrity": "sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/sunos-x64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.21.5.tgz",
+ "integrity": "sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "sunos"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/win32-arm64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.21.5.tgz",
+ "integrity": "sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/win32-ia32": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.21.5.tgz",
+ "integrity": "sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/win32-x64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.21.5.tgz",
+ "integrity": "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/vite/node_modules/esbuild": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz",
+ "integrity": "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "bin": {
+ "esbuild": "bin/esbuild"
+ },
+ "engines": {
+ "node": ">=12"
+ },
+ "optionalDependencies": {
+ "@esbuild/aix-ppc64": "0.21.5",
+ "@esbuild/android-arm": "0.21.5",
+ "@esbuild/android-arm64": "0.21.5",
+ "@esbuild/android-x64": "0.21.5",
+ "@esbuild/darwin-arm64": "0.21.5",
+ "@esbuild/darwin-x64": "0.21.5",
+ "@esbuild/freebsd-arm64": "0.21.5",
+ "@esbuild/freebsd-x64": "0.21.5",
+ "@esbuild/linux-arm": "0.21.5",
+ "@esbuild/linux-arm64": "0.21.5",
+ "@esbuild/linux-ia32": "0.21.5",
+ "@esbuild/linux-loong64": "0.21.5",
+ "@esbuild/linux-mips64el": "0.21.5",
+ "@esbuild/linux-ppc64": "0.21.5",
+ "@esbuild/linux-riscv64": "0.21.5",
+ "@esbuild/linux-s390x": "0.21.5",
+ "@esbuild/linux-x64": "0.21.5",
+ "@esbuild/netbsd-x64": "0.21.5",
+ "@esbuild/openbsd-x64": "0.21.5",
+ "@esbuild/sunos-x64": "0.21.5",
+ "@esbuild/win32-arm64": "0.21.5",
+ "@esbuild/win32-ia32": "0.21.5",
+ "@esbuild/win32-x64": "0.21.5"
+ }
+ },
+ "node_modules/vitest": {
+ "version": "2.1.9",
+ "resolved": "https://registry.npmjs.org/vitest/-/vitest-2.1.9.tgz",
+ "integrity": "sha512-MSmPM9REYqDGBI8439mA4mWhV5sKmDlBKWIYbA3lRb2PTHACE0mgKwA8yQ2xq9vxDTuk4iPrECBAEW2aoFXY0Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/expect": "2.1.9",
+ "@vitest/mocker": "2.1.9",
+ "@vitest/pretty-format": "^2.1.9",
+ "@vitest/runner": "2.1.9",
+ "@vitest/snapshot": "2.1.9",
+ "@vitest/spy": "2.1.9",
+ "@vitest/utils": "2.1.9",
+ "chai": "^5.1.2",
+ "debug": "^4.3.7",
+ "expect-type": "^1.1.0",
+ "magic-string": "^0.30.12",
+ "pathe": "^1.1.2",
+ "std-env": "^3.8.0",
+ "tinybench": "^2.9.0",
+ "tinyexec": "^0.3.1",
+ "tinypool": "^1.0.1",
+ "tinyrainbow": "^1.2.0",
+ "vite": "^5.0.0",
+ "vite-node": "2.1.9",
+ "why-is-node-running": "^2.3.0"
+ },
+ "bin": {
+ "vitest": "vitest.mjs"
+ },
+ "engines": {
+ "node": "^18.0.0 || >=20.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ },
+ "peerDependencies": {
+ "@edge-runtime/vm": "*",
+ "@types/node": "^18.0.0 || >=20.0.0",
+ "@vitest/browser": "2.1.9",
+ "@vitest/ui": "2.1.9",
+ "happy-dom": "*",
+ "jsdom": "*"
+ },
+ "peerDependenciesMeta": {
+ "@edge-runtime/vm": {
+ "optional": true
+ },
+ "@types/node": {
+ "optional": true
+ },
+ "@vitest/browser": {
+ "optional": true
+ },
+ "@vitest/ui": {
+ "optional": true
+ },
+ "happy-dom": {
+ "optional": true
+ },
+ "jsdom": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/vitest/node_modules/pathe": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/pathe/-/pathe-1.1.2.tgz",
+ "integrity": "sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/web-streams-polyfill": {
+ "version": "4.0.0-beta.3",
+ "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-4.0.0-beta.3.tgz",
+ "integrity": "sha512-QW95TCTaHmsYfHDybGMwO5IJIM93I/6vTRk+daHTWFPhwh+C8Cg7j7XyKrwrj8Ib6vYXe0ocYNrmzY4xAAN6ug==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/webidl-conversions": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
+ "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==",
+ "dev": true,
+ "license": "BSD-2-Clause"
+ },
+ "node_modules/whatwg-url": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
+ "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "tr46": "~0.0.3",
+ "webidl-conversions": "^3.0.0"
+ }
+ },
+ "node_modules/why-is-node-running": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",
+ "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "siginfo": "^2.0.0",
+ "stackback": "0.0.2"
+ },
+ "bin": {
+ "why-is-node-running": "cli.js"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/zod": {
+ "version": "3.25.76",
+ "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
+ "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
+ "dev": true,
+ "license": "MIT",
+ "peer": true,
+ "funding": {
+ "url": "https://github.com/sponsors/colinhacks"
+ }
+ }
+ }
+}
diff --git a/sdk/typescript/package.json b/sdk/typescript/package.json
new file mode 100644
index 000000000..5940846b4
--- /dev/null
+++ b/sdk/typescript/package.json
@@ -0,0 +1,57 @@
+{
+ "name": "headroom-ai",
+ "version": "0.1.0",
+ "description": "Compress LLM context. Save tokens. Fit more into every request.",
+ "type": "module",
+ "main": "./dist/index.cjs",
+ "module": "./dist/index.js",
+ "types": "./dist/index.d.ts",
+ "files": ["dist", "README.md", "LICENSE"],
+ "exports": {
+ ".": {
+ "import": { "types": "./dist/index.d.ts", "default": "./dist/index.js" },
+ "require": { "types": "./dist/index.d.cts", "default": "./dist/index.cjs" }
+ },
+ "./vercel-ai": {
+ "import": { "types": "./dist/adapters/vercel-ai.d.ts", "default": "./dist/adapters/vercel-ai.js" },
+ "require": { "types": "./dist/adapters/vercel-ai.d.cts", "default": "./dist/adapters/vercel-ai.cjs" }
+ },
+ "./openai": {
+ "import": { "types": "./dist/adapters/openai.d.ts", "default": "./dist/adapters/openai.js" },
+ "require": { "types": "./dist/adapters/openai.d.cts", "default": "./dist/adapters/openai.cjs" }
+ },
+ "./anthropic": {
+ "import": { "types": "./dist/adapters/anthropic.d.ts", "default": "./dist/adapters/anthropic.js" },
+ "require": { "types": "./dist/adapters/anthropic.d.cts", "default": "./dist/adapters/anthropic.cjs" }
+ }
+ },
+ "engines": { "node": ">=18.0.0" },
+ "scripts": {
+ "build": "tsup",
+ "test": "vitest run",
+ "test:watch": "vitest",
+ "typecheck": "tsc --noEmit"
+ },
+ "peerDependencies": {
+ "ai": ">=6.0.0",
+ "@ai-sdk/provider": ">=1.0.0",
+ "openai": ">=4.0.0",
+ "@anthropic-ai/sdk": ">=0.30.0"
+ },
+ "peerDependenciesMeta": {
+ "ai": { "optional": true },
+ "@ai-sdk/provider": { "optional": true },
+ "openai": { "optional": true },
+ "@anthropic-ai/sdk": { "optional": true }
+ },
+ "devDependencies": {
+ "typescript": "^5.5.0",
+ "vitest": "^2.0.0",
+ "tsup": "^8.0.0",
+ "@ai-sdk/provider": "^1.0.0",
+ "ai": "^6.0.0",
+ "openai": "^4.80.0",
+ "@anthropic-ai/sdk": "^0.39.0"
+ },
+ "license": "Apache-2.0"
+}
diff --git a/sdk/typescript/src/adapters/anthropic.ts b/sdk/typescript/src/adapters/anthropic.ts
new file mode 100644
index 000000000..0b1772f57
--- /dev/null
+++ b/sdk/typescript/src/adapters/anthropic.ts
@@ -0,0 +1,214 @@
+import { compress } from "../compress.js";
+import type { CompressOptions, OpenAIMessage } from "../types.js";
+import type { AssistantMessage, ToolCall } from "../types.js";
+
+/* eslint-disable @typescript-eslint/no-explicit-any */
+
+interface AnthropicLike {
+ messages: {
+ create: (params: any) => any;
+ };
+ [key: string]: any;
+}
+
+/**
+ * Convert Anthropic messages to OpenAI format for compression.
+ *
+ * Anthropic format:
+ * { role: 'user' | 'assistant', content: string | ContentBlock[] }
+ * ContentBlock = { type: 'text', text } | { type: 'tool_use', ... } | { type: 'tool_result', ... }
+ */
+function anthropicToOpenAI(messages: any[]): OpenAIMessage[] {
+ const result: OpenAIMessage[] = [];
+
+ for (const msg of messages) {
+ if (msg.role === "user") {
+ if (typeof msg.content === "string") {
+ result.push({ role: "user", content: msg.content });
+ } else if (Array.isArray(msg.content)) {
+ const toolResults = msg.content.filter(
+ (b: any) => b.type === "tool_result",
+ );
+ const textBlocks = msg.content.filter((b: any) => b.type === "text");
+
+ if (textBlocks.length > 0) {
+ result.push({
+ role: "user",
+ content: textBlocks.map((b: any) => b.text).join("\n"),
+ });
+ }
+ for (const tr of toolResults) {
+ result.push({
+ role: "tool",
+ content:
+ typeof tr.content === "string"
+ ? tr.content
+ : JSON.stringify(tr.content),
+ tool_call_id: tr.tool_use_id,
+ });
+ }
+ }
+ continue;
+ }
+
+ if (msg.role === "assistant") {
+ if (typeof msg.content === "string") {
+ result.push({ role: "assistant", content: msg.content });
+ } else if (Array.isArray(msg.content)) {
+ const textBlocks = msg.content.filter((b: any) => b.type === "text");
+ const toolUseBlocks = msg.content.filter(
+ (b: any) => b.type === "tool_use",
+ );
+
+ const content =
+ textBlocks.length > 0
+ ? textBlocks.map((b: any) => b.text).join("\n")
+ : null;
+
+ const openaiMsg: AssistantMessage = { role: "assistant", content };
+ if (toolUseBlocks.length > 0) {
+ openaiMsg.tool_calls = toolUseBlocks.map(
+ (b: any): ToolCall => ({
+ id: b.id,
+ type: "function",
+ function: {
+ name: b.name,
+ arguments: JSON.stringify(b.input),
+ },
+ }),
+ );
+ }
+ result.push(openaiMsg);
+ }
+ continue;
+ }
+ }
+
+ return result;
+}
+
+/**
+ * Convert compressed OpenAI messages back to Anthropic format.
+ */
+function openAIToAnthropic(messages: OpenAIMessage[]): any[] {
+ const result: any[] = [];
+
+ for (const msg of messages) {
+ if (msg.role === "user") {
+ if (typeof msg.content === "string") {
+ result.push({ role: "user", content: msg.content });
+ } else if (Array.isArray(msg.content)) {
+ result.push({
+ role: "user",
+ content: msg.content.map((p) => {
+ if (p.type === "text") return { type: "text", text: p.text };
+ return { type: "text", text: "" };
+ }),
+ });
+ }
+ continue;
+ }
+
+ if (msg.role === "assistant") {
+ const blocks: any[] = [];
+ if (msg.content) blocks.push({ type: "text", text: msg.content });
+ if (msg.tool_calls) {
+ for (const tc of msg.tool_calls) {
+ blocks.push({
+ type: "tool_use",
+ id: tc.id,
+ name: tc.function.name,
+ input: JSON.parse(tc.function.arguments),
+ });
+ }
+ }
+ result.push({
+ role: "assistant",
+ content:
+ blocks.length === 1 && blocks[0].type === "text"
+ ? blocks[0].text
+ : blocks,
+ });
+ continue;
+ }
+
+ if (msg.role === "tool") {
+ result.push({
+ role: "user",
+ content: [
+ {
+ type: "tool_result",
+ tool_use_id: msg.tool_call_id,
+ content: msg.content,
+ },
+ ],
+ });
+ continue;
+ }
+
+ if (msg.role === "system") {
+ // System messages are handled separately in Anthropic (as `system` param)
+ // Pass through as user message if it appears in the messages array
+ result.push({ role: "user", content: msg.content });
+ }
+ }
+
+ return result;
+}
+
+/**
+ * Wrap an Anthropic client to auto-compress messages before each request.
+ *
+ * Intercepts `client.messages.create()` only. All other methods pass through.
+ *
+ * @example
+ * ```typescript
+ * import { withHeadroom } from 'headroom-ai/anthropic';
+ * import Anthropic from '@anthropic-ai/sdk';
+ *
+ * const client = withHeadroom(new Anthropic());
+ * const response = await client.messages.create({
+ * model: 'claude-sonnet-4-5-20250929',
+ * messages: longConversation,
+ * max_tokens: 1024,
+ * });
+ * ```
+ */
+export function withHeadroom<T extends AnthropicLike>(
+ client: T,
+ options: CompressOptions = {},
+): T {
+ const originalCreate = client.messages.create.bind(client.messages);
+
+ const compressedCreate = async (params: any) => {
+ const messages = params.messages;
+ const model =
+ options.model ?? params.model ?? "claude-sonnet-4-5-20250929";
+
+ const openaiMessages = anthropicToOpenAI(messages);
+ const result = await compress(openaiMessages, { ...options, model });
+
+ const anthropicMessages = result.compressed
+ ? openAIToAnthropic(result.messages)
+ : messages;
+
+ return originalCreate({
+ ...params,
+ messages: anthropicMessages,
+ });
+ };
+
+ const messagesProxy = new Proxy(client.messages, {
+ get(target, prop) {
+ if (prop === "create") return compressedCreate;
+ return (target as any)[prop];
+ },
+ });
+
+ return new Proxy(client, {
+ get(target, prop) {
+ if (prop === "messages") return messagesProxy;
+ return (target as any)[prop];
+ },
+ }) as T;
+}
diff --git a/sdk/typescript/src/adapters/openai.ts b/sdk/typescript/src/adapters/openai.ts
new file mode 100644
index 000000000..f3bc2b289
--- /dev/null
+++ b/sdk/typescript/src/adapters/openai.ts
@@ -0,0 +1,73 @@
+import { compress } from "../compress.js";
+import type { CompressOptions, OpenAIMessage } from "../types.js";
+
+/* eslint-disable @typescript-eslint/no-explicit-any */
+
+interface OpenAILike {
+ chat: {
+ completions: {
+ create: (params: any) => any;
+ };
+ };
+ [key: string]: any;
+}
+
+/**
+ * Wrap an OpenAI client to auto-compress messages before each request.
+ *
+ * Intercepts `client.chat.completions.create()` only. All other methods
+ * (embeddings, images, audio, etc.) pass through unchanged.
+ *
+ * @example
+ * ```typescript
+ * import { withHeadroom } from 'headroom-ai/openai';
+ * import OpenAI from 'openai';
+ *
+ * const client = withHeadroom(new OpenAI());
+ * const response = await client.chat.completions.create({
+ * model: 'gpt-4o',
+ * messages: longConversation,
+ * });
+ * ```
+ */
+export function withHeadroom<T extends OpenAILike>(
+ client: T,
+ options: CompressOptions = {},
+): T {
+ const originalCreate = client.chat.completions.create.bind(
+ client.chat.completions,
+ );
+
+ const compressedCreate = async (params: any) => {
+ const messages: OpenAIMessage[] = params.messages;
+ const model = options.model ?? params.model ?? "gpt-4o";
+
+ const result = await compress(messages, { ...options, model });
+
+ return originalCreate({
+ ...params,
+ messages: result.messages,
+ });
+ };
+
+ const completionsProxy = new Proxy(client.chat.completions, {
+ get(target, prop) {
+ if (prop === "create") return compressedCreate;
+ return (target as any)[prop];
+ },
+ });
+
+ const chatProxy = new Proxy(client.chat, {
+ get(target, prop) {
+ if (prop === "completions") return completionsProxy;
+ return (target as any)[prop];
+ },
+ });
+
+ return new Proxy(client, {
+ get(target, prop) {
+ if (prop === "chat") return chatProxy;
+ return (target as any)[prop];
+ },
+ }) as T;
+}
diff --git a/sdk/typescript/src/adapters/vercel-ai.ts b/sdk/typescript/src/adapters/vercel-ai.ts
new file mode 100644
index 000000000..965fee548
--- /dev/null
+++ b/sdk/typescript/src/adapters/vercel-ai.ts
@@ -0,0 +1,70 @@
+import { compress } from "../compress.js";
+import type { CompressOptions, CompressResult } from "../types.js";
+import { vercelToOpenAI, openAIToVercel } from "../utils/format.js";
+
+/* eslint-disable @typescript-eslint/no-explicit-any */
+type VercelMessage = any;
+
+/**
+ * Vercel AI SDK LanguageModelV3Middleware that compresses messages
+ * before they reach the LLM.
+ *
+ * @example
+ * ```typescript
+ * import { headroomMiddleware } from 'headroom-ai/vercel-ai';
+ * import { wrapLanguageModel } from 'ai';
+ * import { openai } from '@ai-sdk/openai';
+ *
+ * const model = wrapLanguageModel({
+ * model: openai('gpt-4o'),
+ * middleware: headroomMiddleware(),
+ * });
+ * ```
+ */
+export function headroomMiddleware(options: CompressOptions = {}) {
+ return {
+ transformParams: async ({
+ params,
+ }: {
+ params: any;
+ model: any;
+ type: string;
+ }) => {
+ const prompt: VercelMessage[] = params.prompt;
+ if (!prompt || prompt.length === 0) return params;
+
+ const model = options.model ?? params.modelId ?? "gpt-4o";
+
+ // Convert Vercel format → OpenAI format
+ const openaiMessages = vercelToOpenAI(prompt);
+
+ // Compress via Headroom
+ const result = await compress(openaiMessages, { ...options, model });
+
+ if (!result.compressed) return params;
+
+ // Convert back to Vercel format
+ const compressedPrompt = openAIToVercel(result.messages);
+
+ return { ...params, prompt: compressedPrompt };
+ },
+ };
+}
+
+/**
+ * Standalone: compress Vercel AI SDK ModelMessage[] directly.
+ * Returns compressed messages in Vercel format + compression stats.
+ */
+export async function compressVercelMessages(
+ messages: VercelMessage[],
+ options: CompressOptions = {},
+): Promise<CompressResult & { messages: VercelMessage[] }> {
+ const openaiMessages = vercelToOpenAI(messages);
+ const result = await compress(openaiMessages, options);
+ const vercelMessages = openAIToVercel(result.messages);
+
+ return {
+ ...result,
+ messages: vercelMessages,
+ };
+}
diff --git a/sdk/typescript/src/client.ts b/sdk/typescript/src/client.ts
new file mode 100644
index 000000000..399c1d919
--- /dev/null
+++ b/sdk/typescript/src/client.ts
@@ -0,0 +1,151 @@
+import type {
+ OpenAIMessage,
+ CompressResult,
+ HeadroomClientOptions,
+ HeadroomClientInterface,
+ ProxyCompressResponse,
+ ProxyErrorResponse,
+} from "./types.js";
+import {
+ HeadroomConnectionError,
+ HeadroomAuthError,
+ HeadroomCompressError,
+} from "./types.js";
+
+const DEFAULT_BASE_URL = "http://localhost:8787";
+const DEFAULT_TIMEOUT = 30_000;
+const DEFAULT_RETRIES = 1;
+
+function getEnv(key: string): string | undefined {
+ if (typeof process !== "undefined" && process.env) {
+ return process.env[key];
+ }
+ return undefined;
+}
+
+function makeFallbackResult(messages: OpenAIMessage[]): CompressResult {
+ return {
+ messages,
+ tokensBefore: 0,
+ tokensAfter: 0,
+ tokensSaved: 0,
+ compressionRatio: 1.0,
+ transformsApplied: [],
+ ccrHashes: [],
+ compressed: false,
+ };
+}
+
+export class HeadroomClient implements HeadroomClientInterface {
+ private baseUrl: string;
+ private apiKey: string | undefined;
+ private timeout: number;
+ private fallback: boolean;
+ private retries: number;
+
+ constructor(options: HeadroomClientOptions = {}) {
+ this.baseUrl = (
+ options.baseUrl ??
+ getEnv("HEADROOM_BASE_URL") ??
+ DEFAULT_BASE_URL
+ ).replace(/\/+$/, "");
+ this.apiKey = options.apiKey ?? getEnv("HEADROOM_API_KEY");
+ this.timeout = options.timeout ?? DEFAULT_TIMEOUT;
+ this.fallback = options.fallback ?? true;
+ this.retries = options.retries ?? DEFAULT_RETRIES;
+ }
+
+ async compress(
+ messages: OpenAIMessage[],
+ options: { model?: string } = {},
+ ): Promise<CompressResult> {
+ const model = options.model ?? "gpt-4o";
+
+ let lastError: unknown;
+ const maxAttempts = 1 + this.retries;
+
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
+ try {
+ return await this._doCompress(messages, model);
+ } catch (error) {
+ lastError = error;
+ // Don't retry auth errors or client errors
+ if (error instanceof HeadroomAuthError) throw error;
+ if (
+ error instanceof HeadroomCompressError &&
+ error.statusCode < 500
+ ) {
+ throw error;
+ }
+ // Retry on transient errors (network, 5xx)
+ }
+ }
+
+ // All attempts exhausted
+ if (this.fallback) {
+ return makeFallbackResult(messages);
+ }
+ if (lastError instanceof HeadroomConnectionError) throw lastError;
+ if (lastError instanceof HeadroomCompressError) throw lastError;
+ throw new HeadroomConnectionError(
+ `Failed after ${maxAttempts} attempts: ${lastError}`,
+ );
+ }
+
+ private async _doCompress(
+ messages: OpenAIMessage[],
+ model: string,
+ ): Promise<CompressResult> {
+ const url = `${this.baseUrl}/v1/compress`;
+ const headers: Record<string, string> = {
+ "Content-Type": "application/json",
+ };
+ if (this.apiKey) {
+ headers["Authorization"] = `Bearer ${this.apiKey}`;
+ }
+
+ let response: Response;
+ try {
+ response = await fetch(url, {
+ method: "POST",
+ headers,
+ body: JSON.stringify({ messages, model }),
+ signal: AbortSignal.timeout(this.timeout),
+ });
+ } catch (error) {
+ throw new HeadroomConnectionError(
+ `Failed to connect to Headroom at ${this.baseUrl}: ${error}`,
+ );
+ }
+
+ if (!response.ok) {
+ let errorBody: ProxyErrorResponse | undefined;
+ try {
+ errorBody = (await response.json()) as ProxyErrorResponse;
+ } catch {
+ // ignore parse errors on error responses
+ }
+ const errorType = errorBody?.error?.type ?? "unknown";
+ const errorMessage =
+ errorBody?.error?.message ?? `HTTP ${response.status}`;
+
+ if (response.status === 401) {
+ throw new HeadroomAuthError(errorMessage);
+ }
+ throw new HeadroomCompressError(response.status, errorType, errorMessage);
+ }
+
+ const data = (await response.json()) as ProxyCompressResponse;
+
+ return {
+ messages: data.messages,
+ tokensBefore: data.tokens_before,
+ tokensAfter: data.tokens_after,
+ tokensSaved: data.tokens_saved,
+ compressionRatio: data.compression_ratio,
+ transformsApplied: data.transforms_applied,
+ ccrHashes: data.ccr_hashes,
+ compressed: true,
+ };
+ }
+}
diff --git a/sdk/typescript/src/compress.ts b/sdk/typescript/src/compress.ts
new file mode 100644
index 000000000..3b30a09ce
--- /dev/null
+++ b/sdk/typescript/src/compress.ts
@@ -0,0 +1,32 @@
+import { HeadroomClient } from "./client.js";
+import type {
+ OpenAIMessage,
+ CompressResult,
+ CompressOptions,
+} from "./types.js";
+
+/**
+ * Compress an array of messages using the Headroom proxy or cloud.
+ *
+ * This is the main entry point for the SDK. It accepts OpenAI-format messages,
+ * sends them to the Headroom compression pipeline, and returns compressed
+ * messages with stats.
+ *
+ * @example
+ * ```typescript
+ * import { compress } from 'headroom-ai';
+ *
+ * const result = await compress(messages, { model: 'gpt-4o' });
+ * console.log(`Saved ${result.tokensSaved} tokens`);
+ * ```
+ */
+export async function compress(
+ messages: OpenAIMessage[],
+ options: CompressOptions = {},
+): Promise<CompressResult> {
+ const { client: providedClient, model, ...clientOptions } = options;
+
+ const client = providedClient ?? new HeadroomClient(clientOptions);
+
+ return client.compress(messages, { model });
+}
diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.ts
new file mode 100644
index 000000000..9e71ffd2a
--- /dev/null
+++ b/sdk/typescript/src/index.ts
@@ -0,0 +1,25 @@
+export { compress } from "./compress.js";
+export { HeadroomClient } from "./client.js";
+
+export type {
+ TextContentPart,
+ ImageContentPart,
+ ContentPart,
+ ToolCall,
+ SystemMessage,
+ UserMessage,
+ AssistantMessage,
+ ToolMessage,
+ OpenAIMessage,
+ CompressOptions,
+ CompressResult,
+ HeadroomClientOptions,
+ HeadroomClientInterface,
+} from "./types.js";
+
+export {
+ HeadroomError,
+ HeadroomConnectionError,
+ HeadroomAuthError,
+ HeadroomCompressError,
+} from "./types.js";
diff --git a/sdk/typescript/src/types.ts b/sdk/typescript/src/types.ts
new file mode 100644
index 000000000..f6abdefdf
--- /dev/null
+++ b/sdk/typescript/src/types.ts
@@ -0,0 +1,141 @@
+// --- Message types (OpenAI chat format) ---
+
+export interface TextContentPart {
+ type: "text";
+ text: string;
+}
+
+export interface ImageContentPart {
+ type: "image_url";
+ image_url: { url: string; detail?: "auto" | "low" | "high" };
+}
+
+export type ContentPart = TextContentPart | ImageContentPart;
+
+export interface ToolCall {
+ id: string;
+ type: "function";
+ function: { name: string; arguments: string };
+}
+
+export interface SystemMessage {
+ role: "system";
+ content: string;
+}
+
+export interface UserMessage {
+ role: "user";
+ content: string | ContentPart[];
+}
+
+export interface AssistantMessage {
+ role: "assistant";
+ content: string | null;
+ tool_calls?: ToolCall[];
+}
+
+export interface ToolMessage {
+ role: "tool";
+ content: string;
+ tool_call_id: string;
+}
+
+export type OpenAIMessage =
+ | SystemMessage
+ | UserMessage
+ | AssistantMessage
+ | ToolMessage;
+
+// --- Compress API ---
+
+export interface CompressOptions {
+ model?: string;
+ baseUrl?: string;
+ apiKey?: string;
+ timeout?: number;
+ fallback?: boolean;
+ retries?: number;
+ client?: HeadroomClientInterface;
+}
+
+export interface CompressResult {
+ messages: OpenAIMessage[];
+ tokensBefore: number;
+ tokensAfter: number;
+ tokensSaved: number;
+ compressionRatio: number;
+ transformsApplied: string[];
+ ccrHashes: string[];
+ compressed: boolean;
+}
+
+// --- Client ---
+
+export interface HeadroomClientOptions {
+ baseUrl?: string;
+ apiKey?: string;
+ timeout?: number;
+ fallback?: boolean;
+ retries?: number;
+}
+
+export interface HeadroomClientInterface {
+ compress(
+ messages: OpenAIMessage[],
+ options?: { model?: string },
+ ): Promise<CompressResult>;
+}
+
+// --- Errors ---
+
+export class HeadroomError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "HeadroomError";
+ }
+}
+
+export class HeadroomConnectionError extends HeadroomError {
+ constructor(message: string) {
+ super(message);
+ this.name = "HeadroomConnectionError";
+ }
+}
+
+export class HeadroomAuthError extends HeadroomError {
+ constructor(message: string) {
+ super(message);
+ this.name = "HeadroomAuthError";
+ }
+}
+
+export class HeadroomCompressError extends HeadroomError {
+ statusCode: number;
+ errorType: string;
+
+ constructor(statusCode: number, errorType: string, message: string) {
+ super(message);
+ this.name = "HeadroomCompressError";
+ this.statusCode = statusCode;
+ this.errorType = errorType;
+ }
+}
+
+// --- Proxy response (internal) ---
+
+export interface ProxyCompressResponse {
+ messages: OpenAIMessage[];
+ tokens_before: number;
+ tokens_after: number;
+ tokens_saved: number;
+ compression_ratio: number;
+ transforms_applied: string[];
+ ccr_hashes: string[];
+}
+
+export interface ProxyErrorResponse {
+ error: {
+ type: string;
+ message: string;
+ };
+}
diff --git a/sdk/typescript/src/utils/format.ts b/sdk/typescript/src/utils/format.ts
new file mode 100644
index 000000000..65501312a
--- /dev/null
+++ b/sdk/typescript/src/utils/format.ts
@@ -0,0 +1,189 @@
+/**
+ * Convert between Vercel AI SDK ModelMessage format and OpenAI message format.
+ *
+ * Vercel uses typed content parts (TextPart, ToolCallPart, ToolResultPart, etc.)
+ * OpenAI uses { role, content, tool_calls, tool_call_id }.
+ *
+ * We use loose types (any) for Vercel messages to avoid forcing users to install
+ * @ai-sdk/provider. The adapter (vercel-ai.ts) provides the typed wrapper.
+ */
+
+import type {
+ OpenAIMessage,
+ AssistantMessage,
+ ToolCall,
+} from "../types.js";
+
+/* eslint-disable @typescript-eslint/no-explicit-any */
+type VercelMessage = any;
+
+/**
+ * Convert Vercel AI SDK ModelMessage[] to OpenAI message format.
+ *
+ * Handles: system, user (text + image), assistant (text + tool-call),
+ * tool (tool-result). Skips reasoning and file parts (non-compressible).
+ */
+export function vercelToOpenAI(messages: VercelMessage[]): OpenAIMessage[] {
+ const result: OpenAIMessage[] = [];
+
+ for (const msg of messages) {
+ if (msg.role === "system") {
+ result.push({ role: "system", content: msg.content });
+ continue;
+ }
+
+ if (msg.role === "user") {
+ const parts = Array.isArray(msg.content) ? msg.content : [msg.content];
+ const textParts = parts.filter((p: any) => p.type === "text");
+ const imageParts = parts.filter((p: any) => p.type === "image");
+
+ if (imageParts.length === 0 && textParts.length > 0) {
+ // Text-only: flatten to string
+ result.push({
+ role: "user",
+ content: textParts.map((p: any) => p.text).join(""),
+ });
+ } else {
+ // Mixed content: use content parts array
+ const openaiParts = parts
+ .filter((p: any) => p.type === "text" || p.type === "image")
+ .map((p: any) => {
+ if (p.type === "text") {
+ return { type: "text" as const, text: p.text };
+ }
+ if (p.type === "image") {
+ const url =
+ p.image instanceof URL ? p.image.toString() : String(p.image);
+ return { type: "image_url" as const, image_url: { url } };
+ }
+ return { type: "text" as const, text: "" };
+ });
+ result.push({ role: "user", content: openaiParts });
+ }
+ continue;
+ }
+
+ if (msg.role === "assistant") {
+ const parts = Array.isArray(msg.content) ? msg.content : [];
+ const textParts = parts.filter((p: any) => p.type === "text");
+ const toolCallParts = parts.filter((p: any) => p.type === "tool-call");
+
+ const content =
+ textParts.length > 0
+ ? textParts.map((p: any) => p.text).join("")
+ : null;
+
+ const openaiMsg: AssistantMessage = { role: "assistant", content };
+
+ if (toolCallParts.length > 0) {
+ openaiMsg.tool_calls = toolCallParts.map(
+ (p: any): ToolCall => ({
+ id: p.toolCallId,
+ type: "function",
+ function: {
+ name: p.toolName,
+ arguments: JSON.stringify(p.args),
+ },
+ }),
+ );
+ }
+
+ result.push(openaiMsg);
+ continue;
+ }
+
+ if (msg.role === "tool") {
+ const parts = Array.isArray(msg.content) ? msg.content : [];
+ for (const part of parts) {
+ if (part.type === "tool-result") {
+ result.push({
+ role: "tool",
+ content:
+ typeof part.result === "string"
+ ? part.result
+ : JSON.stringify(part.result),
+ tool_call_id: part.toolCallId,
+ });
+ }
+ }
+ continue;
+ }
+ }
+
+ return result;
+}
+
+/**
+ * Convert OpenAI message format back to Vercel AI SDK ModelMessage[].
+ */
+export function openAIToVercel(messages: OpenAIMessage[]): VercelMessage[] {
+ const result: VercelMessage[] = [];
+
+ for (const msg of messages) {
+ if (msg.role === "system") {
+ result.push({ role: "system", content: msg.content });
+ continue;
+ }
+
+ if (msg.role === "user") {
+ if (typeof msg.content === "string") {
+ result.push({
+ role: "user",
+ content: [{ type: "text", text: msg.content }],
+ });
+ } else if (Array.isArray(msg.content)) {
+ const parts = msg.content.map((p) => {
+ if (p.type === "text") return { type: "text", text: p.text };
+ if (p.type === "image_url") {
+ return { type: "image", image: new URL(p.image_url.url) };
+ }
+ return { type: "text", text: "" };
+ });
+ result.push({ role: "user", content: parts });
+ }
+ continue;
+ }
+
+ if (msg.role === "assistant") {
+ const parts: any[] = [];
+ if (msg.content) {
+ parts.push({ type: "text", text: msg.content });
+ }
+ if (msg.tool_calls) {
+ for (const tc of msg.tool_calls) {
+ parts.push({
+ type: "tool-call",
+ toolCallId: tc.id,
+ toolName: tc.function.name,
+ args: JSON.parse(tc.function.arguments),
+ });
+ }
+ }
+ result.push({ role: "assistant", content: parts });
+ continue;
+ }
+
+ if (msg.role === "tool") {
+ let parsedResult: any;
+ try {
+ parsedResult = JSON.parse(msg.content);
+ } catch {
+ parsedResult = msg.content;
+ }
+ result.push({
+ role: "tool",
+ content: [
+ {
+ type: "tool-result",
+ toolCallId: msg.tool_call_id,
+ toolName: "unknown",
+ result: parsedResult,
+ },
+ ],
+ });
+ continue;
+ }
+ }
+
+ return result;
+}
diff --git a/sdk/typescript/test/adapters/anthropic.test.ts b/sdk/typescript/test/adapters/anthropic.test.ts
new file mode 100644
index 000000000..c5d4e21f8
--- /dev/null
+++ b/sdk/typescript/test/adapters/anthropic.test.ts
@@ -0,0 +1,217 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { withHeadroom } from "../../src/adapters/anthropic.js";
+
+const mockFetch = vi.fn();
+vi.stubGlobal("fetch", mockFetch);
+
+function mockCompressSuccess(
+ messages = [{ role: "user", content: "compressed" }],
+) {
+ return new Response(
+ JSON.stringify({
+ messages,
+ tokens_before: 100,
+ tokens_after: 30,
+ tokens_saved: 70,
+ compression_ratio: 0.3,
+ transforms_applied: ["smart_crusher"],
+ ccr_hashes: [],
+ }),
+ { status: 200, headers: { "Content-Type": "application/json" } },
+ );
+}
+
+describe("withHeadroom (Anthropic)", () => {
+ beforeEach(() => {
+ mockFetch.mockReset();
+ });
+
+ it("intercepts messages.create and compresses", async () => {
+ mockFetch.mockResolvedValueOnce(mockCompressSuccess());
+
+ const mockCreate = vi.fn().mockResolvedValue({
+ id: "msg_123",
+ content: [{ type: "text", text: "response" }],
+ });
+ const fakeClient = {
+ messages: { create: mockCreate },
+ completions: { create: vi.fn() },
+ };
+
+ const wrapped = withHeadroom(fakeClient as any, {
+ baseUrl: "http://localhost:8787",
+ });
+
+ await wrapped.messages.create({
+ model: "claude-sonnet-4-5-20250929",
+ messages: [{ role: "user", content: "long message" }],
+ max_tokens: 1024,
+ });
+
+ // Should have called compress
+ expect(mockFetch).toHaveBeenCalledOnce();
+
+ // Should have called original create
+ expect(mockCreate).toHaveBeenCalledOnce();
+ const createArgs = mockCreate.mock.calls[0][0];
+ expect(createArgs.max_tokens).toBe(1024);
+ expect(createArgs.model).toBe("claude-sonnet-4-5-20250929");
+ });
+
+ it("passes through non-messages methods", () => {
+ const completionsCreate = vi.fn();
+ const fakeClient = {
+ messages: { create: vi.fn() },
+ completions: { create: completionsCreate },
+ beta: { something: vi.fn() },
+ };
+
+ const wrapped = withHeadroom(fakeClient as any, {
+ baseUrl: "http://localhost:8787",
+ });
+
+ expect(wrapped.completions.create).toBe(completionsCreate);
+ expect(wrapped.beta).toBe(fakeClient.beta);
+ });
+
+ it("preserves return value from original create", async () => {
+ mockFetch.mockResolvedValueOnce(mockCompressSuccess());
+
+ const expectedResponse = {
+ id: "msg_123",
+ type: "message",
+ role: "assistant",
+ content: [{ type: "text", text: "Hello!" }],
+ model: "claude-sonnet-4-5-20250929",
+ stop_reason: "end_turn",
+ usage: { input_tokens: 30, output_tokens: 10 },
+ };
+ const mockCreate = vi.fn().mockResolvedValue(expectedResponse);
+ const fakeClient = { messages: { create: mockCreate } };
+
+ const wrapped = withHeadroom(fakeClient as any, {
+ baseUrl: "http://localhost:8787",
+ });
+
+ const result = await wrapped.messages.create({
+ model: "claude-sonnet-4-5-20250929",
+ messages: [{ role: "user", content: "hello" }],
+ max_tokens: 1024,
+ });
+
+ expect(result).toEqual(expectedResponse);
+ });
+
+ it("converts Anthropic content blocks to OpenAI format for compression", async () => {
+ mockFetch.mockResolvedValueOnce(mockCompressSuccess());
+
+ const mockCreate = vi.fn().mockResolvedValue({});
+ const fakeClient = { messages: { create: mockCreate } };
+
+ const wrapped = withHeadroom(fakeClient as any, {
+ baseUrl: "http://localhost:8787",
+ });
+
+ await wrapped.messages.create({
+ model: "claude-sonnet-4-5-20250929",
+ messages: [
+ {
+ role: "user",
+ content: [{ type: "text", text: "analyze this data" }],
+ },
+ ],
+ max_tokens: 1024,
+ });
+
+ // Verify the compress call used OpenAI format
+ const body = JSON.parse(mockFetch.mock.calls[0][1].body);
+ expect(body.messages[0].role).toBe("user");
+ expect(body.messages[0].content).toBe("analyze this data");
+ });
+
+ it("handles Anthropic tool_use and tool_result blocks", async () => {
+ // Proxy returns compressed messages
+ mockFetch.mockResolvedValueOnce(
+ mockCompressSuccess([
+ { role: "user", content: "search for X" },
+ {
+ role: "assistant",
+ content: null,
+ tool_calls: [
+ {
+ id: "tu_1",
+ type: "function",
+ function: { name: "search", arguments: '{"q":"X"}' },
+ },
+ ],
+ },
+ {
+ role: "tool",
+ content: '{"results":["a","b"]}',
+ tool_call_id: "tu_1",
+ },
+ ]),
+ );
+
+ const mockCreate = vi.fn().mockResolvedValue({});
+ const fakeClient = { messages: { create: mockCreate } };
+
+ const wrapped = withHeadroom(fakeClient as any, {
+ baseUrl: "http://localhost:8787",
+ });
+
+ await wrapped.messages.create({
+ model: "claude-sonnet-4-5-20250929",
+ messages: [
+ { role: "user", content: "search for X" },
+ {
+ role: "assistant",
+ content: [
+ { type: "tool_use", id: "tu_1", name: "search", input: { q: "X" } },
+ ],
+ },
+ {
+ role: "user",
+ content: [
+ {
+ type: "tool_result",
+ tool_use_id: "tu_1",
+ content: '{"results":["a","b"]}',
+ },
+ ],
+ },
+ ],
+ max_tokens: 1024,
+ });
+
+ expect(mockCreate).toHaveBeenCalledOnce();
+ // Messages should be converted back to Anthropic format
+ const createArgs = mockCreate.mock.calls[0][0];
+ expect(createArgs.messages.length).toBeGreaterThan(0);
+ });
+
+ it("returns original messages on compression fallback", async () => {
+ // Simulate proxy unreachable
+ mockFetch.mockRejectedValueOnce(new TypeError("fetch failed"));
+
+ const originalMessages = [{ role: "user", content: "hello" }];
+ const mockCreate = vi.fn().mockResolvedValue({});
+ const fakeClient = { messages: { create: mockCreate } };
+
+ const wrapped = withHeadroom(fakeClient as any, {
+ baseUrl: "http://localhost:8787",
+ fallback: true,
+ });
+
+ await wrapped.messages.create({
+ model: "claude-sonnet-4-5-20250929",
+ messages: originalMessages,
+ max_tokens: 1024,
+ });
+
+ // Should still call original with uncompressed messages
+ expect(mockCreate).toHaveBeenCalledOnce();
+ const createArgs = mockCreate.mock.calls[0][0];
+ expect(createArgs.messages).toEqual(originalMessages);
+ });
+});
diff --git a/sdk/typescript/test/adapters/openai.test.ts b/sdk/typescript/test/adapters/openai.test.ts
new file mode 100644
index 000000000..a9d35aaaf
--- /dev/null
+++ b/sdk/typescript/test/adapters/openai.test.ts
@@ -0,0 +1,174 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { withHeadroom } from "../../src/adapters/openai.js";
+
+const mockFetch = vi.fn();
+vi.stubGlobal("fetch", mockFetch);
+
+function mockCompressSuccess(
+ messages = [{ role: "user", content: "compressed" }],
+) {
+ return new Response(
+ JSON.stringify({
+ messages,
+ tokens_before: 100,
+ tokens_after: 30,
+ tokens_saved: 70,
+ compression_ratio: 0.3,
+ transforms_applied: ["smart_crusher"],
+ ccr_hashes: [],
+ }),
+ { status: 200, headers: { "Content-Type": "application/json" } },
+ );
+}
+
+describe("withHeadroom (OpenAI)", () => {
+ beforeEach(() => {
+ mockFetch.mockReset();
+ });
+
+ it("intercepts chat.completions.create and compresses messages", async () => {
+ mockFetch.mockResolvedValueOnce(mockCompressSuccess());
+
+ const mockCreate = vi.fn().mockResolvedValue({
+ id: "chatcmpl-123",
+ choices: [{ message: { role: "assistant", content: "hi" } }],
+ });
+ const fakeClient = {
+ chat: { completions: { create: mockCreate } },
+ embeddings: { create: vi.fn() },
+ };
+
+ const wrapped = withHeadroom(fakeClient as any, {
+ baseUrl: "http://localhost:8787",
+ });
+
+ await wrapped.chat.completions.create({
+ model: "gpt-4o",
+ messages: [{ role: "user", content: "long message here" }],
+ });
+
+ // Should have called compress endpoint
+ expect(mockFetch).toHaveBeenCalledOnce();
+ const [url] = mockFetch.mock.calls[0];
+ expect(url).toBe("http://localhost:8787/v1/compress");
+
+ // Should have called original create with compressed messages
+ expect(mockCreate).toHaveBeenCalledOnce();
+ const createArgs = mockCreate.mock.calls[0][0];
+ expect(createArgs.messages).toEqual([
+ { role: "user", content: "compressed" },
+ ]);
+ expect(createArgs.model).toBe("gpt-4o");
+ });
+
+ it("preserves non-chat methods unchanged", () => {
+ const embeddingsCreate = vi.fn();
+ const fakeClient = {
+ chat: { completions: { create: vi.fn() } },
+ embeddings: { create: embeddingsCreate },
+ images: { generate: vi.fn() },
+ };
+
+ const wrapped = withHeadroom(fakeClient as any, {
+ baseUrl: "http://localhost:8787",
+ });
+
+ expect(wrapped.embeddings.create).toBe(embeddingsCreate);
+ expect(wrapped.images).toBe(fakeClient.images);
+ });
+
+ it("preserves return value from original create", async () => {
+ mockFetch.mockResolvedValueOnce(mockCompressSuccess());
+
+ const expectedResponse = {
+ id: "chatcmpl-123",
+ choices: [
+ {
+ index: 0,
+ message: { role: "assistant", content: "Hello!" },
+ finish_reason: "stop",
+ },
+ ],
+ usage: { prompt_tokens: 30, completion_tokens: 10, total_tokens: 40 },
+ };
+ const mockCreate = vi.fn().mockResolvedValue(expectedResponse);
+ const fakeClient = {
+ chat: { completions: { create: mockCreate } },
+ };
+
+ const wrapped = withHeadroom(fakeClient as any, {
+ baseUrl: "http://localhost:8787",
+ });
+
+ const result = await wrapped.chat.completions.create({
+ model: "gpt-4o",
+ messages: [{ role: "user", content: "hello" }],
+ });
+
+ expect(result).toEqual(expectedResponse);
+ });
+
+ it("passes model from params to compress", async () => {
+ mockFetch.mockResolvedValueOnce(mockCompressSuccess());
+
+ const fakeClient = {
+ chat: { completions: { create: vi.fn().mockResolvedValue({}) } },
+ };
+
+ const wrapped = withHeadroom(fakeClient as any, {
+ baseUrl: "http://localhost:8787",
+ });
+
+ await wrapped.chat.completions.create({
+ model: "gpt-4o-mini",
+ messages: [{ role: "user", content: "hello" }],
+ });
+
+ const body = JSON.parse(mockFetch.mock.calls[0][1].body);
+ expect(body.model).toBe("gpt-4o-mini");
+ });
+
+ it("uses model from options when provided", async () => {
+ mockFetch.mockResolvedValueOnce(mockCompressSuccess());
+
+ const fakeClient = {
+ chat: { completions: { create: vi.fn().mockResolvedValue({}) } },
+ };
+
+ const wrapped = withHeadroom(fakeClient as any, {
+ baseUrl: "http://localhost:8787",
+ model: "gpt-4o",
+ });
+
+ await wrapped.chat.completions.create({
+ model: "gpt-4o-mini", // this should be overridden for compression
+ messages: [{ role: "user", content: "hello" }],
+ });
+
+ const body = JSON.parse(mockFetch.mock.calls[0][1].body);
+ expect(body.model).toBe("gpt-4o"); // from options
+ });
+
+ it("still passes original model to LLM even when compress model differs", async () => {
+ mockFetch.mockResolvedValueOnce(mockCompressSuccess());
+
+ const mockCreate = vi.fn().mockResolvedValue({});
+ const fakeClient = {
+ chat: { completions: { create: mockCreate } },
+ };
+
+ const wrapped = withHeadroom(fakeClient as any, {
+ baseUrl: "http://localhost:8787",
+ model: "gpt-4o", // compression model
+ });
+
+ await wrapped.chat.completions.create({
+ model: "gpt-4o-mini", // LLM model
+ messages: [{ role: "user", content: "hello" }],
+ });
+
+ // Original create should still get gpt-4o-mini
+ const createArgs = mockCreate.mock.calls[0][0];
+ expect(createArgs.model).toBe("gpt-4o-mini");
+ });
+});
diff --git a/sdk/typescript/test/adapters/vercel-ai.test.ts b/sdk/typescript/test/adapters/vercel-ai.test.ts
new file mode 100644
index 000000000..36ec6b02d
--- /dev/null
+++ b/sdk/typescript/test/adapters/vercel-ai.test.ts
@@ -0,0 +1,173 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import {
+ headroomMiddleware,
+ compressVercelMessages,
+} from "../../src/adapters/vercel-ai.js";
+
+const mockFetch = vi.fn();
+vi.stubGlobal("fetch", mockFetch);
+
+function mockCompressResponse(
+ messages: any[],
+ tokensBefore = 100,
+ tokensAfter = 30,
+) {
+ return new Response(
+ JSON.stringify({
+ messages,
+ tokens_before: tokensBefore,
+ tokens_after: tokensAfter,
+ tokens_saved: tokensBefore - tokensAfter,
+ compression_ratio: tokensAfter / tokensBefore,
+ transforms_applied: ["smart_crusher"],
+ ccr_hashes: [],
+ }),
+ { status: 200, headers: { "Content-Type": "application/json" } },
+ );
+}
+
+describe("headroomMiddleware", () => {
+ beforeEach(() => {
+ mockFetch.mockReset();
+ });
+
+ it("returns object with transformParams function", () => {
+ const mw = headroomMiddleware({ baseUrl: "http://localhost:8787" });
+ expect(mw.transformParams).toBeDefined();
+ expect(typeof mw.transformParams).toBe("function");
+ });
+
+ it("compresses prompt via transformParams", async () => {
+ // Proxy returns compressed OpenAI messages
+ mockFetch.mockResolvedValueOnce(
+ mockCompressResponse([{ role: "user", content: "compressed" }]),
+ );
+
+ const mw = headroomMiddleware({ baseUrl: "http://localhost:8787" });
+
+ const params = {
+ prompt: [
+ { role: "system", content: "Be helpful" },
+ {
+ role: "user",
+ content: [{ type: "text", text: "long message here" }],
+ },
+ ],
+ modelId: "gpt-4o",
+ };
+
+ const result = await mw.transformParams!({
+ params: params as any,
+ model: {} as any,
+ type: "generate",
+ });
+
+ expect(mockFetch).toHaveBeenCalledOnce();
+ expect(result.prompt).toBeDefined();
+ expect(result.prompt).not.toEqual(params.prompt); // should be modified
+ });
+
+ it("passes through empty prompt unchanged", async () => {
+ const mw = headroomMiddleware({ baseUrl: "http://localhost:8787" });
+
+ const params = { prompt: [], modelId: "gpt-4o" };
+ const result = await mw.transformParams!({
+ params: params as any,
+ model: {} as any,
+ type: "generate",
+ });
+
+ expect(mockFetch).not.toHaveBeenCalled();
+ expect(result).toEqual(params);
+ });
+
+ it("passes through when compression returns compressed=false", async () => {
+ // Simulate fallback (proxy unreachable)
+ mockFetch.mockRejectedValueOnce(new TypeError("fetch failed"));
+
+ const mw = headroomMiddleware({
+ baseUrl: "http://localhost:8787",
+ fallback: true,
+ });
+
+ const originalPrompt = [
+ {
+ role: "user",
+ content: [{ type: "text", text: "hello" }],
+ },
+ ];
+
+ const params = { prompt: originalPrompt, modelId: "gpt-4o" };
+ const result = await mw.transformParams!({
+ params: params as any,
+ model: {} as any,
+ type: "generate",
+ });
+
+ // Should return original params since compression failed
+ expect(result).toEqual(params);
+ });
+
+ it("uses model from options over params.modelId", async () => {
+ mockFetch.mockResolvedValueOnce(
+ mockCompressResponse([{ role: "user", content: "x" }]),
+ );
+
+ const mw = headroomMiddleware({
+ baseUrl: "http://localhost:8787",
+ model: "claude-sonnet-4-5-20250929",
+ });
+
+ await mw.transformParams!({
+ params: {
+ prompt: [
+ { role: "user", content: [{ type: "text", text: "hi" }] },
+ ],
+ modelId: "gpt-4o",
+ } as any,
+ model: {} as any,
+ type: "generate",
+ });
+
+ const body = JSON.parse(mockFetch.mock.calls[0][1].body);
+ expect(body.model).toBe("claude-sonnet-4-5-20250929");
+ });
+});
+
+describe("compressVercelMessages", () => {
+ beforeEach(() => {
+ mockFetch.mockReset();
+ });
+
+ it("converts, compresses, and converts back to Vercel format", async () => {
+ mockFetch.mockResolvedValueOnce(
+ mockCompressResponse([
+ { role: "system", content: "Be helpful" },
+ { role: "user", content: "hello" },
+ ]),
+ );
+
+ const vercelMessages = [
+ { role: "system", content: "Be helpful" },
+ {
+ role: "user",
+ content: [{ type: "text", text: "hello" }],
+ },
+ ];
+
+ const result = await compressVercelMessages(vercelMessages, {
+ model: "gpt-4o",
+ baseUrl: "http://localhost:8787",
+ });
+
+ expect(result.compressed).toBe(true);
+ expect(result.tokensBefore).toBe(100);
+ // Messages should be in Vercel format (user has content parts array)
+ expect(result.messages[0]).toEqual({
+ role: "system",
+ content: "Be helpful",
+ });
+ expect(result.messages[1].role).toBe("user");
+ expect(result.messages[1].content[0].type).toBe("text");
+ });
+});
diff --git a/sdk/typescript/test/client.test.ts b/sdk/typescript/test/client.test.ts
new file mode 100644
index 000000000..0f5cc48cf
--- /dev/null
+++ b/sdk/typescript/test/client.test.ts
@@ -0,0 +1,266 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { HeadroomClient } from "../src/client.js";
+import type { OpenAIMessage } from "../src/types.js";
+import {
+ HeadroomConnectionError,
+ HeadroomAuthError,
+ HeadroomCompressError,
+} from "../src/types.js";
+
+const mockFetch = vi.fn();
+vi.stubGlobal("fetch", mockFetch);
+
+function okResponse(body: object) {
+ return new Response(JSON.stringify(body), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ });
+}
+
+function errorResponse(status: number, body: object) {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { "Content-Type": "application/json" },
+ });
+}
+
+const sampleMessages: OpenAIMessage[] = [
+ { role: "user", content: "hello" },
+ { role: "assistant", content: "hi there" },
+];
+
+const sampleProxyResponse = {
+ messages: sampleMessages,
+ tokens_before: 10,
+ tokens_after: 8,
+ tokens_saved: 2,
+ compression_ratio: 0.8,
+ transforms_applied: ["smart_crusher"],
+ ccr_hashes: [],
+};
+
+describe("HeadroomClient", () => {
+ beforeEach(() => {
+ mockFetch.mockReset();
+ });
+
+ it("sends POST to /v1/compress with messages and model", async () => {
+ mockFetch.mockResolvedValueOnce(okResponse(sampleProxyResponse));
+
+ const client = new HeadroomClient({ baseUrl: "http://localhost:8787" });
+ await client.compress(sampleMessages, { model: "gpt-4o" });
+
+ expect(mockFetch).toHaveBeenCalledOnce();
+ const [url, opts] = mockFetch.mock.calls[0];
+ expect(url).toBe("http://localhost:8787/v1/compress");
+ expect(opts.method).toBe("POST");
+ const body = JSON.parse(opts.body);
+ expect(body.messages).toEqual(sampleMessages);
+ expect(body.model).toBe("gpt-4o");
+ });
+
+ it("maps snake_case proxy response to camelCase result", async () => {
+ mockFetch.mockResolvedValueOnce(
+ okResponse({
+ messages: [{ role: "user", content: "hello" }],
+ tokens_before: 100,
+ tokens_after: 30,
+ tokens_saved: 70,
+ compression_ratio: 0.3,
+ transforms_applied: ["router:smart_crusher:0.35"],
+ ccr_hashes: ["abc123"],
+ }),
+ );
+
+ const client = new HeadroomClient({ baseUrl: "http://localhost:8787" });
+ const result = await client.compress(sampleMessages, { model: "gpt-4o" });
+
+ expect(result.tokensBefore).toBe(100);
+ expect(result.tokensAfter).toBe(30);
+ expect(result.tokensSaved).toBe(70);
+ expect(result.compressionRatio).toBe(0.3);
+ expect(result.transformsApplied).toEqual(["router:smart_crusher:0.35"]);
+ expect(result.ccrHashes).toEqual(["abc123"]);
+ expect(result.compressed).toBe(true);
+ });
+
+ it("sends apiKey as Authorization bearer header", async () => {
+ mockFetch.mockResolvedValueOnce(okResponse(sampleProxyResponse));
+
+ const client = new HeadroomClient({
+ baseUrl: "http://localhost:8787",
+ apiKey: "hr_test123",
+ });
+ await client.compress(sampleMessages, { model: "gpt-4o" });
+
+ const [, opts] = mockFetch.mock.calls[0];
+ expect(opts.headers["Authorization"]).toBe("Bearer hr_test123");
+ });
+
+ it("does not send Authorization header when no apiKey", async () => {
+ mockFetch.mockResolvedValueOnce(okResponse(sampleProxyResponse));
+
+ const client = new HeadroomClient({ baseUrl: "http://localhost:8787" });
+ await client.compress(sampleMessages, { model: "gpt-4o" });
+
+ const [, opts] = mockFetch.mock.calls[0];
+ expect(opts.headers["Authorization"]).toBeUndefined();
+ });
+
+ it("strips trailing slashes from baseUrl", async () => {
+ mockFetch.mockResolvedValueOnce(okResponse(sampleProxyResponse));
+
+ const client = new HeadroomClient({
+ baseUrl: "http://localhost:8787///",
+ });
+ await client.compress(sampleMessages, { model: "gpt-4o" });
+
+ const [url] = mockFetch.mock.calls[0];
+ expect(url).toBe("http://localhost:8787/v1/compress");
+ });
+
+ it("throws HeadroomAuthError on 401 (always, even with fallback)", async () => {
+ mockFetch.mockResolvedValueOnce(
+ errorResponse(401, {
+ error: { type: "authentication_error", message: "Invalid API key" },
+ }),
+ );
+
+ const client = new HeadroomClient({
+ baseUrl: "http://localhost:8787",
+ fallback: true, // fallback doesn't apply to auth errors
+ });
+
+ await expect(
+ client.compress(sampleMessages, { model: "gpt-4o" }),
+ ).rejects.toThrow(HeadroomAuthError);
+ });
+
+ it("throws HeadroomCompressError on 400 (always, even with fallback)", async () => {
+ mockFetch.mockResolvedValueOnce(
+ errorResponse(400, {
+ error: { type: "invalid_request", message: "Missing model" },
+ }),
+ );
+
+ const client = new HeadroomClient({
+ baseUrl: "http://localhost:8787",
+ fallback: true, // fallback doesn't apply to client errors
+ });
+
+ await expect(
+ client.compress(sampleMessages, { model: "gpt-4o" }),
+ ).rejects.toThrow(HeadroomCompressError);
+ });
+
+ it("falls back to uncompressed on network error when fallback=true", async () => {
+ mockFetch.mockRejectedValueOnce(new TypeError("fetch failed"));
+
+ const client = new HeadroomClient({
+ baseUrl: "http://localhost:8787",
+ fallback: true,
+ });
+ const result = await client.compress(sampleMessages, { model: "gpt-4o" });
+
+ expect(result.compressed).toBe(false);
+ expect(result.messages).toEqual(sampleMessages);
+ expect(result.tokensSaved).toBe(0);
+ });
+
+ it("throws HeadroomConnectionError on network error when fallback=false", async () => {
+ mockFetch.mockRejectedValueOnce(new TypeError("fetch failed"));
+
+ const client = new HeadroomClient({
+ baseUrl: "http://localhost:8787",
+ fallback: false,
+ retries: 0,
+ });
+
+ await expect(
+ client.compress(sampleMessages, { model: "gpt-4o" }),
+ ).rejects.toThrow(HeadroomConnectionError);
+ });
+
+ it("falls back on 503 when fallback=true", async () => {
+ mockFetch.mockResolvedValueOnce(
+ errorResponse(503, {
+ error: { type: "compression_error", message: "Pipeline failed" },
+ }),
+ );
+
+ const client = new HeadroomClient({
+ baseUrl: "http://localhost:8787",
+ fallback: true,
+ retries: 0,
+ });
+ const result = await client.compress(sampleMessages, { model: "gpt-4o" });
+
+ expect(result.compressed).toBe(false);
+ expect(result.messages).toEqual(sampleMessages);
+ });
+
+ it("retries on transient network errors then succeeds", async () => {
+ mockFetch
+ .mockRejectedValueOnce(new TypeError("fetch failed"))
+ .mockResolvedValueOnce(okResponse(sampleProxyResponse));
+
+ const client = new HeadroomClient({
+ baseUrl: "http://localhost:8787",
+ retries: 1,
+ });
+ const result = await client.compress(sampleMessages, { model: "gpt-4o" });
+
+ expect(mockFetch).toHaveBeenCalledTimes(2);
+ expect(result.compressed).toBe(true);
+ });
+
+ it("retries on 503 then succeeds", async () => {
+ mockFetch
+ .mockResolvedValueOnce(
+ errorResponse(503, {
+ error: { type: "compression_error", message: "Busy" },
+ }),
+ )
+ .mockResolvedValueOnce(okResponse(sampleProxyResponse));
+
+ const client = new HeadroomClient({
+ baseUrl: "http://localhost:8787",
+ retries: 1,
+ fallback: false,
+ });
+ const result = await client.compress(sampleMessages, { model: "gpt-4o" });
+
+ expect(mockFetch).toHaveBeenCalledTimes(2);
+ expect(result.compressed).toBe(true);
+ });
+
+ it("does not retry on 400 client errors", async () => {
+ mockFetch.mockResolvedValueOnce(
+ errorResponse(400, {
+ error: { type: "invalid_request", message: "Bad request" },
+ }),
+ );
+
+ const client = new HeadroomClient({
+ baseUrl: "http://localhost:8787",
+ retries: 3,
+ fallback: false,
+ });
+
+ await expect(
+ client.compress(sampleMessages, { model: "gpt-4o" }),
+ ).rejects.toThrow(HeadroomCompressError);
+
+ expect(mockFetch).toHaveBeenCalledTimes(1); // no retries
+ });
+
+ it("defaults model to gpt-4o when not provided", async () => {
+ mockFetch.mockResolvedValueOnce(okResponse(sampleProxyResponse));
+
+ const client = new HeadroomClient({ baseUrl: "http://localhost:8787" });
+ await client.compress(sampleMessages); // no model option
+
+ const body = JSON.parse(mockFetch.mock.calls[0][1].body);
+ expect(body.model).toBe("gpt-4o");
+ });
+});
diff --git a/sdk/typescript/test/compress.test.ts b/sdk/typescript/test/compress.test.ts
new file mode 100644
index 000000000..69a741bd2
--- /dev/null
+++ b/sdk/typescript/test/compress.test.ts
@@ -0,0 +1,118 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { compress } from "../src/compress.js";
+import type { OpenAIMessage } from "../src/types.js";
+
+const mockFetch = vi.fn();
+vi.stubGlobal("fetch", mockFetch);
+
+function okResponse(overrides = {}) {
+ return new Response(
+ JSON.stringify({
+ messages: [{ role: "user", content: "hello" }],
+ tokens_before: 100,
+ tokens_after: 30,
+ tokens_saved: 70,
+ compression_ratio: 0.3,
+ transforms_applied: ["smart_crusher"],
+ ccr_hashes: [],
+ ...overrides,
+ }),
+ { status: 200, headers: { "Content-Type": "application/json" } },
+ );
+}
+
+describe("compress()", () => {
+ beforeEach(() => {
+ mockFetch.mockReset();
+ });
+
+ it("compresses messages and returns CompressResult", async () => {
+ mockFetch.mockResolvedValueOnce(okResponse());
+
+ const messages: OpenAIMessage[] = [{ role: "user", content: "hello" }];
+ const result = await compress(messages, {
+ model: "gpt-4o",
+ baseUrl: "http://localhost:8787",
+ });
+
+ expect(result.compressed).toBe(true);
+ expect(result.tokensBefore).toBe(100);
+ expect(result.tokensAfter).toBe(30);
+ expect(result.tokensSaved).toBe(70);
+ });
+
+ it("passes all options through to the HTTP call", async () => {
+ mockFetch.mockResolvedValueOnce(okResponse());
+
+ await compress([{ role: "user", content: "hello" }], {
+ model: "claude-sonnet-4-5-20250929",
+ baseUrl: "http://custom:9999",
+ apiKey: "hr_mykey",
+ });
+
+ const [url, opts] = mockFetch.mock.calls[0];
+ expect(url).toBe("http://custom:9999/v1/compress");
+ expect(opts.headers["Authorization"]).toBe("Bearer hr_mykey");
+ const body = JSON.parse(opts.body);
+ expect(body.model).toBe("claude-sonnet-4-5-20250929");
+ });
+
+ it("uses provided client instance instead of creating new one", async () => {
+ const mockClient = {
+ compress: vi.fn().mockResolvedValue({
+ messages: [],
+ tokensBefore: 0,
+ tokensAfter: 0,
+ tokensSaved: 0,
+ compressionRatio: 1.0,
+ transformsApplied: [],
+ ccrHashes: [],
+ compressed: false,
+ }),
+ };
+
+ await compress([{ role: "user", content: "hello" }], {
+ client: mockClient,
+ model: "gpt-4o",
+ });
+
+ expect(mockClient.compress).toHaveBeenCalledOnce();
+ expect(mockFetch).not.toHaveBeenCalled(); // no HTTP call
+ });
+
+ it("handles multi-turn conversation with tool calls", async () => {
+ mockFetch.mockResolvedValueOnce(okResponse());
+
+ const messages: OpenAIMessage[] = [
+ { role: "system", content: "You are a helpful assistant" },
+ { role: "user", content: "Search for data" },
+ {
+ role: "assistant",
+ content: null,
+ tool_calls: [
+ {
+ id: "tc_1",
+ type: "function",
+ function: { name: "search", arguments: '{"q":"data"}' },
+ },
+ ],
+ },
+ {
+ role: "tool",
+ content: '{"results": [1, 2, 3]}',
+ tool_call_id: "tc_1",
+ },
+ { role: "user", content: "Summarize" },
+ ];
+
+ const result = await compress(messages, {
+ model: "gpt-4o",
+ baseUrl: "http://localhost:8787",
+ });
+
+ expect(result.compressed).toBe(true);
+ // Verify all messages were sent to proxy
+ const body = JSON.parse(mockFetch.mock.calls[0][1].body);
+ expect(body.messages).toHaveLength(5);
+ });
+});
diff --git a/sdk/typescript/test/integration.test.ts b/sdk/typescript/test/integration.test.ts
new file mode 100644
index 000000000..d6716f07a
--- /dev/null
+++ b/sdk/typescript/test/integration.test.ts
@@ -0,0 +1,249 @@
+/**
+ * Integration tests for the Headroom TypeScript SDK.
+ *
+ * These tests run against a real Headroom proxy server.
+ * They require:
+ * - The proxy running on http://localhost:8787
+ * - OPENAI_API_KEY and ANTHROPIC_API_KEY in .env
+ *
+ * Run with: HEADROOM_INTEGRATION=1 npx vitest run test/integration.test.ts
+ */
+import { describe, it, expect, beforeAll } from "vitest";
+import { config } from "dotenv";
+import { resolve } from "path";
+
+// Load .env from the project root
+config({ path: resolve(__dirname, "../../../.env") });
+
+const PROXY_URL = "http://localhost:8787";
+const RUN_INTEGRATION = process.env.HEADROOM_INTEGRATION === "1";
+
+// Large tool output that should get meaningfully compressed
+function makeLargeToolOutput(itemCount: number): string {
+ const items = Array.from({ length: itemCount }, (_, i) => ({
+ id: i + 1,
+ name: `item_${i + 1}`,
+ status: i % 10 === 0 ? "error" : "ok",
+ value: Math.random() * 1000,
+ timestamp: new Date(Date.now() - i * 60000).toISOString(),
+ metadata: {
+ category: ["A", "B", "C"][i % 3],
+ tags: [`tag_${i % 5}`, `tag_${(i + 1) % 5}`],
+ description: `This is item number ${i + 1} with some descriptive text that takes up tokens`,
+ },
+ }));
+ return JSON.stringify({ results: items, total: itemCount, page: 1 });
+}
+
+describe.skipIf(!RUN_INTEGRATION)("Integration: compress() with real proxy", () => {
+ beforeAll(async () => {
+ // Verify proxy is running
+ try {
+ const res = await fetch(`${PROXY_URL}/health`);
+ if (!res.ok) throw new Error(`Proxy health check failed: ${res.status}`);
+ } catch (e) {
+ throw new Error(
+ `Proxy not running at ${PROXY_URL}. Start with: headroom proxy --port 8787\n${e}`,
+ );
+ }
+ });
+
+ it("compress() returns compressed messages with real proxy", async () => {
+ const { compress } = await import("../src/compress.js");
+
+ const messages = [
+ { role: "user" as const, content: "Search for recent data" },
+ {
+ role: "assistant" as const,
+ content: null,
+ tool_calls: [
+ {
+ id: "tc_1",
+ type: "function" as const,
+ function: {
+ name: "search_database",
+ arguments: '{"query": "recent data", "limit": 100}',
+ },
+ },
+ ],
+ },
+ {
+ role: "tool" as const,
+ content: makeLargeToolOutput(100),
+ tool_call_id: "tc_1",
+ },
+ { role: "user" as const, content: "Summarize the key findings" },
+ ];
+
+ const result = await compress(messages, {
+ model: "gpt-4o",
+ baseUrl: PROXY_URL,
+ });
+
+ // Verify structure
+ expect(result.messages).toBeDefined();
+ expect(Array.isArray(result.messages)).toBe(true);
+ expect(result.messages.length).toBeGreaterThan(0);
+ expect(result.tokensBefore).toBeGreaterThan(0);
+ expect(result.tokensAfter).toBeGreaterThan(0);
+ expect(result.tokensSaved).toBeGreaterThanOrEqual(0);
+ expect(result.compressionRatio).toBeGreaterThan(0);
+ expect(result.compressionRatio).toBeLessThanOrEqual(1);
+ expect(result.compressed).toBe(true);
+
+ // With 100 items of tool output, we expect meaningful compression
+ console.log(
+ ` compress(): ${result.tokensBefore} → ${result.tokensAfter} tokens ` +
+ `(saved ${result.tokensSaved}, ratio ${result.compressionRatio.toFixed(2)})`,
+ );
+ console.log(` transforms: ${result.transformsApplied.join(", ")}`);
+
+ // Should save at least some tokens with 100 items
+ expect(result.tokensSaved).toBeGreaterThan(0);
+ });
+
+ it("compress() preserves message structure for small inputs", async () => {
+ const { compress } = await import("../src/compress.js");
+
+ const messages = [
+ { role: "system" as const, content: "You are helpful" },
+ { role: "user" as const, content: "Hello" },
+ ];
+
+ const result = await compress(messages, {
+ model: "gpt-4o",
+ baseUrl: PROXY_URL,
+ });
+
+ // Small messages should pass through with structure intact
+ expect(result.messages.length).toBe(2);
+ expect(result.messages[0].role).toBe("system");
+ expect(result.messages[1].role).toBe("user");
+ });
+
+ it("compress() works with claude model name", async () => {
+ const { compress } = await import("../src/compress.js");
+
+ const messages = [
+ { role: "user" as const, content: "Search results" },
+ {
+ role: "tool" as const,
+ content: makeLargeToolOutput(50),
+ tool_call_id: "tc_1",
+ },
+ ];
+
+ const result = await compress(messages, {
+ model: "claude-sonnet-4-5-20250929",
+ baseUrl: PROXY_URL,
+ });
+
+ expect(result.compressed).toBe(true);
+ expect(result.tokensBefore).toBeGreaterThan(0);
+ console.log(
+ ` claude model: ${result.tokensBefore} → ${result.tokensAfter} tokens`,
+ );
+ });
+
+ it("HeadroomClient can be reused across calls", async () => {
+ const { HeadroomClient } = await import("../src/client.js");
+
+ const client = new HeadroomClient({ baseUrl: PROXY_URL });
+
+ const result1 = await client.compress(
+ [
+ { role: "user", content: "First call" },
+ {
+ role: "tool",
+ content: makeLargeToolOutput(50),
+ tool_call_id: "tc_1",
+ },
+ ],
+ { model: "gpt-4o" },
+ );
+
+ const result2 = await client.compress(
+ [
+ { role: "user", content: "Second call" },
+ {
+ role: "tool",
+ content: makeLargeToolOutput(50),
+ tool_call_id: "tc_2",
+ },
+ ],
+ { model: "gpt-4o" },
+ );
+
+ expect(result1.compressed).toBe(true);
+ expect(result2.compressed).toBe(true);
+ });
+
+ it("compress() with empty messages returns empty", async () => {
+ const { compress } = await import("../src/compress.js");
+
+ const result = await compress([], {
+ model: "gpt-4o",
+ baseUrl: PROXY_URL,
+ });
+
+ expect(result.messages).toEqual([]);
+ expect(result.tokensSaved).toBe(0);
+ });
+
+ it("Vercel AI SDK adapter converts and compresses", async () => {
+ const { compressVercelMessages } = await import(
+ "../src/adapters/vercel-ai.js"
+ );
+
+ const vercelMessages = [
+ { role: "system", content: "Be helpful" },
+ {
+ role: "user",
+ content: [{ type: "text", text: "Analyze this data" }],
+ },
+ {
+ role: "assistant",
+ content: [
+ { type: "text", text: "Let me search" },
+ {
+ type: "tool-call",
+ toolCallId: "tc_1",
+ toolName: "search",
+ args: { query: "data" },
+ },
+ ],
+ },
+ {
+ role: "tool",
+ content: [
+ {
+ type: "tool-result",
+ toolCallId: "tc_1",
+ toolName: "search",
+ result: JSON.parse(makeLargeToolOutput(80)),
+ },
+ ],
+ },
+ {
+ role: "user",
+ content: [{ type: "text", text: "Summarize" }],
+ },
+ ];
+
+ const result = await compressVercelMessages(vercelMessages, {
+ model: "gpt-4o",
+ baseUrl: PROXY_URL,
+ });
+
+ expect(result.compressed).toBe(true);
+ expect(result.tokensBefore).toBeGreaterThan(0);
+
+ // Messages should be back in Vercel format
+ expect(result.messages[0].role).toBe("system");
+
+ console.log(
+ ` Vercel adapter: ${result.tokensBefore} → ${result.tokensAfter} tokens ` +
+ `(saved ${result.tokensSaved})`,
+ );
+ });
+});
diff --git a/sdk/typescript/test/types.test.ts b/sdk/typescript/test/types.test.ts
new file mode 100644
index 000000000..a0e3dee94
--- /dev/null
+++ b/sdk/typescript/test/types.test.ts
@@ -0,0 +1,244 @@
+import { describe, it, expectTypeOf } from "vitest";
+import type {
+ TextContentPart,
+ ImageContentPart,
+ ContentPart,
+ ToolCall,
+ SystemMessage,
+ UserMessage,
+ AssistantMessage,
+ ToolMessage,
+ OpenAIMessage,
+ CompressOptions,
+ CompressResult,
+ HeadroomClientOptions,
+ HeadroomClientInterface,
+ ProxyCompressResponse,
+ ProxyErrorResponse,
+} from "../src/types.js";
+import {
+ HeadroomError,
+ HeadroomConnectionError,
+ HeadroomAuthError,
+ HeadroomCompressError,
+} from "../src/types.js";
+
+describe("Message types", () => {
+ it("TextContentPart has correct shape", () => {
+ expectTypeOf<TextContentPart>().toMatchTypeOf<{ type: "text"; text: string }>();
+ });
+
+ it("ImageContentPart has correct shape", () => {
+ expectTypeOf<ImageContentPart>().toHaveProperty("type");
+ expectTypeOf<ImageContentPart>().toHaveProperty("image_url");
+ expectTypeOf<ImageContentPart["image_url"]>().toHaveProperty("url");
+ expectTypeOf<ImageContentPart["image_url"]["detail"]>().toEqualTypeOf<
+ "auto" | "low" | "high" | undefined
+ >();
+ });
+
+ it("ContentPart is union of Text and Image", () => {
+ expectTypeOf<TextContentPart>().toMatchTypeOf<ContentPart>();
+ expectTypeOf<ImageContentPart>().toMatchTypeOf<ContentPart>();
+ });
+
+ it("ToolCall has correct shape", () => {
+ expectTypeOf<ToolCall>().toHaveProperty("id");
+ expectTypeOf<ToolCall>().toHaveProperty("type");
+ expectTypeOf<ToolCall>().toHaveProperty("function");
+ expectTypeOf<ToolCall["type"]>().toEqualTypeOf<"function">();
+ expectTypeOf<ToolCall["function"]>().toEqualTypeOf<{
+ name: string;
+ arguments: string;
+ }>();
+ });
+
+ it("SystemMessage has role system and string content", () => {
+ expectTypeOf<SystemMessage["role"]>().toEqualTypeOf<"system">();
+ expectTypeOf<SystemMessage["content"]>().toBeString();
+ });
+
+ it("UserMessage content can be string or ContentPart[]", () => {
+ expectTypeOf<UserMessage["role"]>().toEqualTypeOf<"user">();
+ expectTypeOf<UserMessage["content"]>().toEqualTypeOf<
+ string | ContentPart[]
+ >();
+ });
+
+ it("AssistantMessage content can be string or null", () => {
+ expectTypeOf<AssistantMessage["role"]>().toEqualTypeOf<"assistant">();
+ expectTypeOf<AssistantMessage["content"]>().toEqualTypeOf<string | null>();
+ });
+
+ it("AssistantMessage tool_calls is optional", () => {
+ expectTypeOf<AssistantMessage["tool_calls"]>().toEqualTypeOf<
+ ToolCall[] | undefined
+ >();
+ });
+
+ it("ToolMessage has tool_call_id", () => {
+ expectTypeOf<ToolMessage["role"]>().toEqualTypeOf<"tool">();
+ expectTypeOf<ToolMessage>().toHaveProperty("tool_call_id");
+ expectTypeOf<ToolMessage["tool_call_id"]>().toBeString();
+ });
+
+ it("OpenAIMessage is union of all message types", () => {
+ expectTypeOf<SystemMessage>().toMatchTypeOf<OpenAIMessage>();
+ expectTypeOf<UserMessage>().toMatchTypeOf<OpenAIMessage>();
+ expectTypeOf<AssistantMessage>().toMatchTypeOf<OpenAIMessage>();
+ expectTypeOf<ToolMessage>().toMatchTypeOf<OpenAIMessage>();
+ });
+});
+
+describe("CompressOptions", () => {
+ it("all fields are optional", () => {
+ expectTypeOf<CompressOptions>().toMatchTypeOf<{}>();
+ });
+
+ it("has expected optional fields", () => {
+ expectTypeOf<CompressOptions["model"]>().toEqualTypeOf<
+ string | undefined
+ >();
+ expectTypeOf<CompressOptions["baseUrl"]>().toEqualTypeOf<
+ string | undefined
+ >();
+ expectTypeOf<CompressOptions["apiKey"]>().toEqualTypeOf<
+ string | undefined
+ >();
+ expectTypeOf<CompressOptions["timeout"]>().toEqualTypeOf<
+ number | undefined
+ >();
+ expectTypeOf<CompressOptions["fallback"]>().toEqualTypeOf<
+ boolean | undefined
+ >();
+ expectTypeOf<CompressOptions["retries"]>().toEqualTypeOf<
+ number | undefined
+ >();
+ expectTypeOf<CompressOptions["client"]>().toEqualTypeOf<
+ HeadroomClientInterface | undefined
+ >();
+ });
+});
+
+describe("CompressResult", () => {
+ it("has all required fields with correct types", () => {
+ expectTypeOf<CompressResult>().toHaveProperty("messages");
+ expectTypeOf<CompressResult["messages"]>().toEqualTypeOf<OpenAIMessage[]>();
+ expectTypeOf<CompressResult["tokensBefore"]>().toBeNumber();
+ expectTypeOf<CompressResult["tokensAfter"]>().toBeNumber();
+ expectTypeOf<CompressResult["tokensSaved"]>().toBeNumber();
+ expectTypeOf<CompressResult["compressionRatio"]>().toBeNumber();
+ expectTypeOf<CompressResult["transformsApplied"]>().toEqualTypeOf<
+ string[]
+ >();
+ expectTypeOf<CompressResult["ccrHashes"]>().toEqualTypeOf<string[]>();
+ expectTypeOf<CompressResult["compressed"]>().toBeBoolean();
+ });
+});
+
+describe("HeadroomClientOptions", () => {
+ it("all fields are optional", () => {
+ expectTypeOf<HeadroomClientOptions>().toMatchTypeOf<{}>();
+ });
+
+ it("has expected optional fields", () => {
+ expectTypeOf<HeadroomClientOptions["baseUrl"]>().toEqualTypeOf<
+ string | undefined
+ >();
+ expectTypeOf<HeadroomClientOptions["apiKey"]>().toEqualTypeOf<
+ string | undefined
+ >();
+ expectTypeOf<HeadroomClientOptions["timeout"]>().toEqualTypeOf<
+ number | undefined
+ >();
+ expectTypeOf<HeadroomClientOptions["fallback"]>().toEqualTypeOf<
+ boolean | undefined
+ >();
+ expectTypeOf<HeadroomClientOptions["retries"]>().toEqualTypeOf<
+ number | undefined
+ >();
+ });
+});
+
+describe("HeadroomClientInterface", () => {
+ it("has compress method", () => {
+ expectTypeOf<HeadroomClientInterface>().toHaveProperty("compress");
+ });
+
+ it("compress returns Promise<CompressResult>", () => {
+ expectTypeOf<HeadroomClientInterface["compress"]>().returns.toEqualTypeOf<
+ Promise<CompressResult>
+ >();
+ });
+
+ it("compress accepts messages and optional options", () => {
+ expectTypeOf<HeadroomClientInterface["compress"]>().parameters.toEqualTypeOf<
+ [OpenAIMessage[], ({ model?: string } | undefined)?]
+ >();
+ });
+});
+
+describe("Error classes", () => {
+ it("HeadroomError extends Error", () => {
+ expectTypeOf<HeadroomError>().toMatchTypeOf<Error>();
+ });
+
+ it("HeadroomConnectionError extends HeadroomError", () => {
+ expectTypeOf<HeadroomConnectionError>().toMatchTypeOf<HeadroomError>();
+ });
+
+ it("HeadroomAuthError extends HeadroomError", () => {
+ expectTypeOf<HeadroomAuthError>().toMatchTypeOf<HeadroomError>();
+ });
+
+ it("HeadroomCompressError extends HeadroomError", () => {
+ expectTypeOf<HeadroomCompressError>().toMatchTypeOf<HeadroomError>();
+ });
+
+ it("HeadroomCompressError has statusCode and errorType", () => {
+ expectTypeOf<HeadroomCompressError>().toHaveProperty("statusCode");
+ expectTypeOf<HeadroomCompressError["statusCode"]>().toBeNumber();
+ expectTypeOf<HeadroomCompressError>().toHaveProperty("errorType");
+ expectTypeOf<HeadroomCompressError["errorType"]>().toBeString();
+ });
+
+ it("error classes are constructable", () => {
+ const err = new HeadroomError("test");
+ expectTypeOf(err).toMatchTypeOf<Error>();
+
+ const connErr = new HeadroomConnectionError("test");
+ expectTypeOf(connErr).toMatchTypeOf<HeadroomError>();
+
+ const authErr = new HeadroomAuthError("test");
+ expectTypeOf(authErr).toMatchTypeOf<HeadroomError>();
+
+ const compressErr = new HeadroomCompressError(500, "server_error", "test");
+ expectTypeOf(compressErr).toMatchTypeOf<HeadroomError>();
+ expectTypeOf(compressErr.statusCode).toBeNumber();
+ expectTypeOf(compressErr.errorType).toBeString();
+ });
+});
+
+describe("Proxy response types (internal)", () => {
+ it("ProxyCompressResponse uses snake_case", () => {
+ expectTypeOf<ProxyCompressResponse>().toHaveProperty("tokens_before");
+ expectTypeOf<ProxyCompressResponse>().toHaveProperty("tokens_after");
+ expectTypeOf<ProxyCompressResponse>().toHaveProperty("tokens_saved");
+ expectTypeOf<ProxyCompressResponse>().toHaveProperty("compression_ratio");
+ expectTypeOf<ProxyCompressResponse>().toHaveProperty("transforms_applied");
+ expectTypeOf<ProxyCompressResponse>().toHaveProperty("ccr_hashes");
+ expectTypeOf<ProxyCompressResponse>().toHaveProperty("messages");
+ expectTypeOf<ProxyCompressResponse["tokens_before"]>().toBeNumber();
+ expectTypeOf<ProxyCompressResponse["messages"]>().toEqualTypeOf<
+ OpenAIMessage[]
+ >();
+ });
+
+ it("ProxyErrorResponse has error with type and message", () => {
+ expectTypeOf<ProxyErrorResponse>().toHaveProperty("error");
+ expectTypeOf<ProxyErrorResponse["error"]>().toEqualTypeOf<{
+ type: string;
+ message: string;
+ }>();
+ });
+});
diff --git a/sdk/typescript/test/utils/format.test.ts b/sdk/typescript/test/utils/format.test.ts
new file mode 100644
index 000000000..6ef01ca9c
--- /dev/null
+++ b/sdk/typescript/test/utils/format.test.ts
@@ -0,0 +1,434 @@
+import { describe, it, expect } from "vitest";
+import { vercelToOpenAI, openAIToVercel } from "../../src/utils/format.js";
+import type { OpenAIMessage } from "../../src/types.js";
+
+describe("vercelToOpenAI", () => {
+ it("converts system message (passthrough)", () => {
+ const result = vercelToOpenAI([
+ { role: "system", content: "You are helpful" },
+ ]);
+ expect(result).toEqual([{ role: "system", content: "You are helpful" }]);
+ });
+
+ it("converts user text-only message to flat string", () => {
+ const result = vercelToOpenAI([
+ {
+ role: "user",
+ content: [{ type: "text", text: "hello" }],
+ },
+ ]);
+ expect(result).toEqual([{ role: "user", content: "hello" }]);
+ });
+
+ it("converts user message with multiple text parts", () => {
+ const result = vercelToOpenAI([
+ {
+ role: "user",
+ content: [
+ { type: "text", text: "hello " },
+ { type: "text", text: "world" },
+ ],
+ },
+ ]);
+ expect(result).toEqual([{ role: "user", content: "hello world" }]);
+ });
+
+ it("converts user message with image to content parts", () => {
+ const result = vercelToOpenAI([
+ {
+ role: "user",
+ content: [
+ { type: "text", text: "describe this" },
+ {
+ type: "image",
+ image: new URL("https://example.com/img.png"),
+ },
+ ],
+ },
+ ]);
+ expect(result).toEqual([
+ {
+ role: "user",
+ content: [
+ { type: "text", text: "describe this" },
+ {
+ type: "image_url",
+ image_url: { url: "https://example.com/img.png" },
+ },
+ ],
+ },
+ ]);
+ });
+
+ it("converts assistant text-only message", () => {
+ const result = vercelToOpenAI([
+ {
+ role: "assistant",
+ content: [{ type: "text", text: "Here is the answer" }],
+ },
+ ]);
+ expect(result).toEqual([
+ { role: "assistant", content: "Here is the answer" },
+ ]);
+ });
+
+ it("converts assistant message with tool calls", () => {
+ const result = vercelToOpenAI([
+ {
+ role: "assistant",
+ content: [
+ { type: "text", text: "Let me search" },
+ {
+ type: "tool-call",
+ toolCallId: "tc_1",
+ toolName: "search",
+ args: { query: "test" },
+ },
+ ],
+ },
+ ]);
+ expect(result).toEqual([
+ {
+ role: "assistant",
+ content: "Let me search",
+ tool_calls: [
+ {
+ id: "tc_1",
+ type: "function",
+ function: {
+ name: "search",
+ arguments: '{"query":"test"}',
+ },
+ },
+ ],
+ },
+ ]);
+ });
+
+ it("converts assistant with only tool calls (no text)", () => {
+ const result = vercelToOpenAI([
+ {
+ role: "assistant",
+ content: [
+ {
+ type: "tool-call",
+ toolCallId: "tc_1",
+ toolName: "search",
+ args: {},
+ },
+ ],
+ },
+ ]);
+ expect(result).toEqual([
+ {
+ role: "assistant",
+ content: null,
+ tool_calls: [
+ {
+ id: "tc_1",
+ type: "function",
+ function: { name: "search", arguments: "{}" },
+ },
+ ],
+ },
+ ]);
+ });
+
+ it("converts tool result message", () => {
+ const result = vercelToOpenAI([
+ {
+ role: "tool",
+ content: [
+ {
+ type: "tool-result",
+ toolCallId: "tc_1",
+ toolName: "search",
+ result: { data: [1, 2, 3] },
+ },
+ ],
+ },
+ ]);
+ expect(result).toEqual([
+ {
+ role: "tool",
+ content: '{"data":[1,2,3]}',
+ tool_call_id: "tc_1",
+ },
+ ]);
+ });
+
+ it("converts tool result with string result", () => {
+ const result = vercelToOpenAI([
+ {
+ role: "tool",
+ content: [
+ {
+ type: "tool-result",
+ toolCallId: "tc_1",
+ toolName: "echo",
+ result: "hello world",
+ },
+ ],
+ },
+ ]);
+ expect(result).toEqual([
+ {
+ role: "tool",
+ content: "hello world",
+ tool_call_id: "tc_1",
+ },
+ ]);
+ });
+
+ it("handles multiple tool results in one tool message", () => {
+ const result = vercelToOpenAI([
+ {
+ role: "tool",
+ content: [
+ {
+ type: "tool-result",
+ toolCallId: "tc_1",
+ toolName: "a",
+ result: "result_a",
+ },
+ {
+ type: "tool-result",
+ toolCallId: "tc_2",
+ toolName: "b",
+ result: "result_b",
+ },
+ ],
+ },
+ ]);
+ expect(result).toHaveLength(2);
+ expect(result[0]).toEqual({
+ role: "tool",
+ content: "result_a",
+ tool_call_id: "tc_1",
+ });
+ expect(result[1]).toEqual({
+ role: "tool",
+ content: "result_b",
+ tool_call_id: "tc_2",
+ });
+ });
+
+ it("skips reasoning parts in assistant messages", () => {
+ const result = vercelToOpenAI([
+ {
+ role: "assistant",
+ content: [
+ { type: "reasoning", text: "thinking..." },
+ { type: "text", text: "answer" },
+ ],
+ },
+ ]);
+ expect(result).toEqual([{ role: "assistant", content: "answer" }]);
+ });
+
+ it("handles full multi-turn conversation", () => {
+ const result = vercelToOpenAI([
+ { role: "system", content: "Be helpful" },
+ { role: "user", content: [{ type: "text", text: "Hi" }] },
+ {
+ role: "assistant",
+ content: [
+ { type: "text", text: "Searching..." },
+ {
+ type: "tool-call",
+ toolCallId: "tc_1",
+ toolName: "web_search",
+ args: { q: "test" },
+ },
+ ],
+ },
+ {
+ role: "tool",
+ content: [
+ {
+ type: "tool-result",
+ toolCallId: "tc_1",
+ toolName: "web_search",
+ result: { results: ["a", "b"] },
+ },
+ ],
+ },
+ {
+ role: "assistant",
+ content: [{ type: "text", text: "Found results" }],
+ },
+ ]);
+
+ expect(result).toHaveLength(5);
+ expect(result[0].role).toBe("system");
+ expect(result[1].role).toBe("user");
+ expect(result[2].role).toBe("assistant");
+ expect(result[2].tool_calls).toHaveLength(1);
+ expect(result[3].role).toBe("tool");
+ expect(result[4].role).toBe("assistant");
+ });
+});
+
+describe("openAIToVercel", () => {
+ it("converts system message (passthrough)", () => {
+ const result = openAIToVercel([
+ { role: "system", content: "You are helpful" },
+ ]);
+ expect(result).toEqual([{ role: "system", content: "You are helpful" }]);
+ });
+
+ it("converts user string to text part array", () => {
+ const result = openAIToVercel([{ role: "user", content: "hello" }]);
+ expect(result).toEqual([
+ { role: "user", content: [{ type: "text", text: "hello" }] },
+ ]);
+ });
+
+ it("converts user content parts", () => {
+ const msgs: OpenAIMessage[] = [
+ {
+ role: "user",
+ content: [
+ { type: "text", text: "look" },
+ {
+ type: "image_url",
+ image_url: { url: "https://example.com/img.png" },
+ },
+ ],
+ },
+ ];
+ const result = openAIToVercel(msgs);
+ expect(result[0].content[0]).toEqual({ type: "text", text: "look" });
+ expect(result[0].content[1].type).toBe("image");
+ expect(result[0].content[1].image.toString()).toBe(
+ "https://example.com/img.png",
+ );
+ });
+
+ it("converts assistant with text and tool calls", () => {
+ const msgs: OpenAIMessage[] = [
+ {
+ role: "assistant",
+ content: "searching",
+ tool_calls: [
+ {
+ id: "tc_1",
+ type: "function",
+ function: { name: "search", arguments: '{"q":"test"}' },
+ },
+ ],
+ },
+ ];
+ const result = openAIToVercel(msgs);
+ expect(result[0].role).toBe("assistant");
+ const content = result[0].content;
+ expect(content).toContainEqual({ type: "text", text: "searching" });
+ expect(content).toContainEqual({
+ type: "tool-call",
+ toolCallId: "tc_1",
+ toolName: "search",
+ args: { q: "test" },
+ });
+ });
+
+ it("converts assistant with null content (tool calls only)", () => {
+ const msgs: OpenAIMessage[] = [
+ {
+ role: "assistant",
+ content: null,
+ tool_calls: [
+ {
+ id: "tc_1",
+ type: "function",
+ function: { name: "fn", arguments: "{}" },
+ },
+ ],
+ },
+ ];
+ const result = openAIToVercel(msgs);
+ expect(result[0].content).toEqual([
+ { type: "tool-call", toolCallId: "tc_1", toolName: "fn", args: {} },
+ ]);
+ });
+
+ it("converts tool message to tool-result", () => {
+ const msgs: OpenAIMessage[] = [
+ { role: "tool", content: '{"data":true}', tool_call_id: "tc_1" },
+ ];
+ const result = openAIToVercel(msgs);
+ expect(result).toEqual([
+ {
+ role: "tool",
+ content: [
+ {
+ type: "tool-result",
+ toolCallId: "tc_1",
+ toolName: "unknown",
+ result: { data: true },
+ },
+ ],
+ },
+ ]);
+ });
+
+ it("handles non-JSON tool content gracefully", () => {
+ const msgs: OpenAIMessage[] = [
+ {
+ role: "tool",
+ content: "plain text result",
+ tool_call_id: "tc_1",
+ },
+ ];
+ const result = openAIToVercel(msgs);
+ expect(result[0].content[0].result).toBe("plain text result");
+ });
+});
+
+describe("round-trip conversion", () => {
+ it("preserves system message through round-trip", () => {
+ const original = [{ role: "system", content: "Be helpful" }];
+ const roundTripped = openAIToVercel(vercelToOpenAI(original));
+ expect(roundTripped).toEqual(original);
+ });
+
+ it("preserves user text through round-trip", () => {
+ const vercel = [
+ { role: "user", content: [{ type: "text", text: "hello" }] },
+ ];
+ const openai = vercelToOpenAI(vercel);
+ expect(openai).toEqual([{ role: "user", content: "hello" }]);
+ const back = openAIToVercel(openai);
+ expect(back).toEqual(vercel);
+ });
+
+ it("preserves tool call flow through round-trip", () => {
+ const vercel = [
+ {
+ role: "assistant",
+ content: [
+ { type: "text", text: "Let me search" },
+ {
+ type: "tool-call",
+ toolCallId: "tc_1",
+ toolName: "search",
+ args: { q: "test" },
+ },
+ ],
+ },
+ ];
+ const openai = vercelToOpenAI(vercel);
+ const back = openAIToVercel(openai);
+
+ expect(back[0].role).toBe("assistant");
+ expect(back[0].content).toContainEqual({
+ type: "text",
+ text: "Let me search",
+ });
+ expect(back[0].content).toContainEqual({
+ type: "tool-call",
+ toolCallId: "tc_1",
+ toolName: "search",
+ args: { q: "test" },
+ });
+ });
+});
diff --git a/sdk/typescript/tsconfig.json b/sdk/typescript/tsconfig.json
new file mode 100644
index 000000000..f4791bc50
--- /dev/null
+++ b/sdk/typescript/tsconfig.json
@@ -0,0 +1,19 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "lib": ["ES2022"],
+ "strict": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "declaration": true,
+ "outDir": "dist",
+ "rootDir": "src",
+ "sourceMap": true,
+ "resolveJsonModule": true,
+ "isolatedModules": true
+ },
+ "include": ["src"],
+ "exclude": ["node_modules", "dist", "test"]
+}
diff --git a/sdk/typescript/tsup.config.ts b/sdk/typescript/tsup.config.ts
new file mode 100644
index 000000000..4050c8156
--- /dev/null
+++ b/sdk/typescript/tsup.config.ts
@@ -0,0 +1,16 @@
+import { defineConfig } from "tsup";
+
+export default defineConfig({
+ entry: {
+ index: "src/index.ts",
+ "adapters/vercel-ai": "src/adapters/vercel-ai.ts",
+ "adapters/openai": "src/adapters/openai.ts",
+ "adapters/anthropic": "src/adapters/anthropic.ts",
+ },
+ format: ["esm", "cjs"],
+ dts: true,
+ sourcemap: true,
+ clean: true,
+ splitting: true,
+ treeshake: true,
+});
diff --git a/sdk/typescript/vitest.config.ts b/sdk/typescript/vitest.config.ts
new file mode 100644
index 000000000..3f824fb95
--- /dev/null
+++ b/sdk/typescript/vitest.config.ts
@@ -0,0 +1,8 @@
+import { defineConfig } from "vitest/config";
+
+export default defineConfig({
+ test: {
+ globals: true,
+ environment: "node",
+ },
+});
diff --git a/tests/test_proxy_compress_endpoint.py b/tests/test_proxy_compress_endpoint.py
new file mode 100644
index 000000000..780025d54
--- /dev/null
+++ b/tests/test_proxy_compress_endpoint.py
@@ -0,0 +1,250 @@
+"""Tests for the /v1/compress endpoint in the proxy server.
+
+These tests verify that the compression-only endpoint works correctly
+for the TypeScript SDK and other HTTP clients.
+"""
+
+import json
+
+import pytest
+
+# Skip if fastapi not available
+pytest.importorskip("fastapi")
+
+from fastapi.testclient import TestClient
+
+from headroom.proxy.server import ProxyConfig, create_app
+
+
+def client():
+ """Create test client with optimization enabled."""
+ config = ProxyConfig(
+ optimize=True,
+ cache_enabled=False,
+ rate_limit_enabled=False,
+ cost_tracking_enabled=False,
+ )
+ app = create_app(config)
+ with TestClient(app) as c:
+ yield c
+
+
+def client_no_optimize():
+ """Create test client with optimization disabled."""
+ config = ProxyConfig(
+ optimize=False,
+ cache_enabled=False,
+ rate_limit_enabled=False,
+ cost_tracking_enabled=False,
+ )
+ app = create_app(config)
+ with TestClient(app) as c:
+ yield c
+
+
+class TestCompressEndpointValidation:
+ """Test request validation for /v1/compress."""
+
+ def test_missing_messages_returns_400(self, client):
+ """Request without messages field should return 400."""
+ response = client.post("/v1/compress", json={"model": "gpt-4"})
+ assert response.status_code == 400
+ data = response.json()
+ assert "error" in data
+ assert data["error"]["type"] == "invalid_request"
+ assert "messages" in data["error"]["message"]
+
+ def test_missing_model_returns_400(self, client):
+ """Request without model field should return 400."""
+ response = client.post(
+ "/v1/compress",
+ json={"messages": [{"role": "user", "content": "hello"}]},
+ )
+ assert response.status_code == 400
+ data = response.json()
+ assert "error" in data
+ assert data["error"]["type"] == "invalid_request"
+ assert "model" in data["error"]["message"]
+
+ def test_invalid_json_returns_400(self, client):
+ """Request with invalid JSON should return 400."""
+ response = client.post(
+ "/v1/compress",
+ content=b"not valid json",
+ headers={"content-type": "application/json"},
+ )
+ assert response.status_code == 400
+ data = response.json()
+ assert data["error"]["type"] == "invalid_request"
+
+
+class TestCompressEndpointBasic:
+ """Test basic compress endpoint behavior."""
+
+ def test_empty_messages_returns_empty(self, client):
+ """Empty messages list should return as-is with zero metrics."""
+ response = client.post(
+ "/v1/compress",
+ json={"messages": [], "model": "gpt-4"},
+ )
+ assert response.status_code == 200
+ data = response.json()
+ assert data["messages"] == []
+ assert data["tokens_before"] == 0
+ assert data["tokens_after"] == 0
+ assert data["tokens_saved"] == 0
+ assert data["compression_ratio"] == 1.0
+ assert data["transforms_applied"] == []
+ assert data["ccr_hashes"] == []
+
+ def test_basic_compression_response_shape(self, client):
+ """Verify the response contains all expected fields."""
+ response = client.post(
+ "/v1/compress",
+ json={
+ "messages": [{"role": "user", "content": "Hello, world!"}],
+ "model": "gpt-4",
+ },
+ )
+ assert response.status_code == 200
+ data = response.json()
+
+ # Check all expected fields are present
+ assert "messages" in data
+ assert "tokens_before" in data
+ assert "tokens_after" in data
+ assert "tokens_saved" in data
+ assert "compression_ratio" in data
+ assert "transforms_applied" in data
+ assert "ccr_hashes" in data
+
+ # Messages should be a list
+ assert isinstance(data["messages"], list)
+ assert len(data["messages"]) >= 1
+
+ # Numeric fields should be non-negative
+ assert data["tokens_before"] >= 0
+ assert data["tokens_after"] >= 0
+ assert data["tokens_saved"] >= 0
+ assert data["compression_ratio"] > 0
+
+ def test_bypass_header_returns_uncompressed(self, client):
+ """X-Headroom-Bypass header should skip compression."""
+ messages = [
+ {"role": "user", "content": "Hello"},
+ {"role": "assistant", "content": "Hi there!"},
+ {"role": "user", "content": "How are you?"},
+ ]
+ response = client.post(
+ "/v1/compress",
+ json={"messages": messages, "model": "gpt-4"},
+ headers={"x-headroom-bypass": "true"},
+ )
+ assert response.status_code == 200
+ data = response.json()
+ assert data["messages"] == messages
+ assert data["tokens_before"] == 0
+ assert data["tokens_after"] == 0
+ assert data["tokens_saved"] == 0
+ assert data["compression_ratio"] == 1.0
+ assert data["transforms_applied"] == []
+ assert data["ccr_hashes"] == []
+
+ def test_bypass_header_case_insensitive(self, client):
+ """Bypass header should be case-insensitive."""
+ messages = [{"role": "user", "content": "Hello"}]
+ response = client.post(
+ "/v1/compress",
+ json={"messages": messages, "model": "gpt-4"},
+ headers={"x-headroom-bypass": "TRUE"},
+ )
+ assert response.status_code == 200
+ data = response.json()
+ assert data["messages"] == messages
+
+
+class TestCompressEndpointCompression:
+ """Test that actual compression happens for large content."""
+
+ def test_large_tool_output_gets_compressed(self, client):
+ """Large tool output content should result in tokens_saved > 0."""
+ # Create a large repetitive tool output that should be compressible
+ large_data = json.dumps(
+ [
+ {
+ "id": i,
+ "name": f"Item {i}",
+ "description": f"This is a detailed description for item number {i}. "
+ f"It contains various attributes and metadata that are typical "
+ f"of API responses. The item has a status of active and was "
+ f"created on 2024-01-{(i % 28) + 1:02d}. Additional fields "
+ f"include category=electronics, price={i * 10.99:.2f}, "
+ f"rating={4.0 + (i % 10) / 10:.1f}, stock={i * 5}.",
+ "tags": ["electronics", "sale", "featured", "new-arrival"],
+ "metadata": {
+ "created_by": "system",
+ "updated_at": "2024-01-15T00:00:00Z",
+ "version": i,
+ "source": "api",
+ },
+ }
+ for i in range(200)
+ ]
+ )
+
+ messages = [
+ {"role": "user", "content": "What items are available?"},
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {
+ "id": "call_123",
+ "type": "function",
+ "function": {
+ "name": "list_items",
+ "arguments": "{}",
+ },
+ }
+ ],
+ },
+ {
+ "role": "tool",
+ "tool_call_id": "call_123",
+ "content": large_data,
+ },
+ {"role": "user", "content": "Summarize the first 5 items."},
+ ]
+
+ response = client.post(
+ "/v1/compress",
+ json={"messages": messages, "model": "gpt-4"},
+ )
+ assert response.status_code == 200
+ data = response.json()
+
+ # With a large tool output, the pipeline should process successfully
+ assert data["tokens_before"] > 0
+ assert data["tokens_after"] > 0
+ assert data["tokens_after"] <= data["tokens_before"]
+ assert data["tokens_saved"] == data["tokens_before"] - data["tokens_after"]
+ assert 0 < data["compression_ratio"] <= 1.0
+ assert isinstance(data["transforms_applied"], list)
+
+ def test_small_content_may_not_compress(self, client):
+ """Small messages may not get compressed but should still work."""
+ response = client.post(
+ "/v1/compress",
+ json={
+ "messages": [{"role": "user", "content": "Hi"}],
+ "model": "gpt-4",
+ },
+ )
+ assert response.status_code == 200
+ data = response.json()
+ # Should still return valid response regardless of compression
+ assert data["tokens_before"] >= 0
+ assert data["tokens_after"] >= 0
+ assert isinstance(data["transforms_applied"], list)