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.

typescript coverage

Adib Mohsincdb721a713a1
diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md
index 8923a1a89..9b99116d0 100644
--- a/sdk/typescript/README.md
+++ b/sdk/typescript/README.md
@@ -30,18 +30,29 @@ Requires a running Headroom proxy (`headroom proxy`) or Headroom Cloud API key.
### Vercel AI SDK
```typescript
-import { headroomMiddleware } from 'headroom-ai/vercel-ai';
-import { wrapLanguageModel, generateText } from 'ai';
+import { withHeadroom } from 'headroom-ai/vercel-ai';
import { openai } from '@ai-sdk/openai';
+import { generateText } from 'ai';
+
+const model = withHeadroom(openai('gpt-4o'));
+const { text } = await generateText({ model, messages });
+```
+
+<details>
+<summary>Advanced: using middleware directly</summary>
+
+```typescript
+import { headroomMiddleware } from 'headroom-ai/vercel-ai';
+import { wrapLanguageModel } from 'ai';
const model = wrapLanguageModel({
model: openai('gpt-4o'),
- middleware: headroomMiddleware(),
+ middleware: headroomMiddleware({ baseUrl: 'http://localhost:8787' }),
});
-
-const { text } = await generateText({ model, messages });
```
+</details>
+
### OpenAI SDK
```typescript
@@ -69,6 +80,278 @@ const response = await client.messages.create({
});
```
+### Google Gemini
+
+```typescript
+import { withHeadroom } from 'headroom-ai/gemini';
+import { GoogleGenerativeAI } from '@google/generative-ai';
+
+const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY!);
+const model = withHeadroom(genAI.getGenerativeModel({ model: 'gemini-2.0-flash' }));
+
+const result = await model.generateContent({
+ contents: longConversation,
+});
+```
+
+## HeadroomClient
+
+The full client provides direct access to the proxy's OpenAI and Anthropic passthrough endpoints, plus metrics, CCR, and observability.
+
+```typescript
+import { HeadroomClient } from 'headroom-ai';
+
+const client = new HeadroomClient({
+ baseUrl: 'http://localhost:8787',
+ providerApiKey: process.env.OPENAI_API_KEY,
+ config: {
+ smartCrusher: { enabled: true, maxItemsAfterCrush: 10 },
+ ccr: { enabled: true },
+ },
+});
+```
+
+### Chat Completions (OpenAI-style)
+
+```typescript
+const response = await client.chat.completions.create({
+ model: 'gpt-4o',
+ messages: longConversation,
+ headroomMode: 'optimize',
+});
+```
+
+### Messages (Anthropic-style)
+
+```typescript
+const response = await client.messages.create({
+ model: 'claude-sonnet-4-5-20250929',
+ messages: longConversation,
+ max_tokens: 1024,
+ headroomMode: 'optimize',
+});
+```
+
+### Direct Compression
+
+```typescript
+const result = await client.compress(messages, { model: 'gpt-4o', tokenBudget: 4000 });
+```
+
+## Simulation (Dry Run)
+
+See what compression would do without calling the LLM.
+
+```typescript
+import { simulate } from 'headroom-ai';
+
+const sim = await simulate(messages, { model: 'gpt-4o' });
+console.log(`Would save ${sim.tokensSaved} tokens (${sim.estimatedSavings})`);
+console.log('Transforms:', sim.transforms);
+console.log('Waste signals:', sim.wasteSignals);
+console.log('Cache alignment:', sim.cacheAlignmentScore);
+```
+
+Also available on the client:
+
+```typescript
+const sim = await client.chat.completions.simulate({
+ model: 'gpt-4o',
+ messages,
+});
+```
+
+## Compression Hooks
+
+Customize compression with pre/post hooks — matching the Python `CompressionHooks` API.
+
+```typescript
+import { compress, CompressionHooks } from 'headroom-ai';
+import type { CompressContext, CompressEvent } from 'headroom-ai';
+
+class MyHooks extends CompressionHooks {
+ // Modify messages before compression
+ preCompress(messages: any[], ctx: CompressContext) {
+ return [{ role: 'system', content: 'Always preserve error details.' }, ...messages];
+ }
+
+ // Set per-message importance biases
+ computeBiases(messages: any[], ctx: CompressContext) {
+ return { 0: 2.0 }; // preserve first message
+ }
+
+ // Observe compression results
+ postCompress(event: CompressEvent) {
+ console.log(`Saved ${event.tokensSaved} tokens via ${event.transformsApplied.join(', ')}`);
+ }
+}
+
+const result = await compress(messages, { model: 'gpt-4o', hooks: new MyHooks() });
+```
+
+## SharedContext (Multi-Agent)
+
+Compressed inter-agent context sharing — matching the Python `SharedContext` API.
+
+```typescript
+import { SharedContext } from 'headroom-ai';
+
+const ctx = new SharedContext({ model: 'gpt-4o', ttl: 3600, maxEntries: 100 });
+
+// Agent A stores data (automatically compressed)
+const entry = await ctx.put('research', bigAgentOutput, { agent: 'researcher' });
+console.log(`Compressed: ${entry.savingsPercent.toFixed(0)}% savings`);
+
+// Agent B reads it (~80% smaller)
+const summary = ctx.get('research');
+
+// Agent B gets original if needed
+const full = ctx.get('research', { full: true });
+
+// Stats
+const stats = ctx.stats();
+console.log(`${stats.entries} entries, ${stats.totalTokensSaved} tokens saved`);
+```
+
+## CCR Retrieve (Compress-Cache-Retrieve)
+
+Retrieve original content when the LLM needs full details.
+
+```typescript
+const result = await client.compress(messages, { model: 'gpt-4o' });
+
+// Later, when the LLM calls headroom_retrieve:
+for (const hash of result.ccrHashes) {
+ const original = await client.retrieve(hash);
+ console.log(`${original.originalTokens} original tokens for ${original.toolName}`);
+}
+
+// Search within compressed content
+const search = await client.retrieve('abc123', { query: 'error logs' });
+
+// Handle LLM tool calls in an agent loop
+const toolResult = await client.handleToolCall({
+ toolCall: assistantMessage.tool_calls[0],
+ provider: 'openai',
+});
+```
+
+## Metrics & Observability
+
+```typescript
+// Proxy health
+const health = await client.health();
+// → { status: 'healthy', version: '0.5.18', config: { optimize: true, ... } }
+
+// Proxy stats
+const stats = await client.proxyStats();
+// → { requests: { total, cached, failed }, tokens: { saved, savingsPercent }, ... }
+
+// Request metrics
+const metrics = await client.getMetrics({ model: 'gpt-4o', limit: 10 });
+
+// Summary
+const summary = await client.getSummary();
+
+// Validate setup
+const validation = await client.validateSetup();
+
+// Clear cache
+await client.clearCache();
+
+// Prometheus metrics
+const prom = await client.prometheusMetrics();
+```
+
+## Telemetry, Feedback & TOIN
+
+Access the proxy's learning systems.
+
+```typescript
+// Telemetry
+const telemetry = await client.telemetry.getStats();
+const tools = await client.telemetry.getTools();
+
+// Feedback — per-tool compression hints
+const hints = await client.feedback.getHints('list_servers');
+// → { hints: { maxItems: 8, skipCompression: false, preserveFields: ['id', 'status'] } }
+
+// TOIN (Tool Output Intelligence Network)
+const toinStats = await client.toin.getStats();
+const patterns = await client.toin.getPatterns(20);
+```
+
+## Configuration Types
+
+Full TypeScript interfaces for every Python config dataclass.
+
+```typescript
+import type { HeadroomConfig, SmartCrusherConfig, CCRConfig } from 'headroom-ai';
+
+const config: HeadroomConfig = {
+ defaultMode: 'optimize',
+ smartCrusher: {
+ enabled: true,
+ minItemsToAnalyze: 5,
+ maxItemsAfterCrush: 10,
+ varianceThreshold: 2.0,
+ relevance: { tier: 'hybrid', relevanceThreshold: 0.25 },
+ anchor: { anchorBudgetPct: 0.25 },
+ },
+ ccr: { enabled: true, injectTool: true },
+ cacheOptimizer: { enabled: true, autoDetectProvider: true },
+ intelligentContext: { enabled: true, useImportanceScoring: true },
+};
+
+const client = new HeadroomClient({ config });
+```
+
+## Error Handling
+
+Full error hierarchy matching the Python SDK.
+
+```typescript
+import {
+ HeadroomError,
+ HeadroomConnectionError,
+ HeadroomAuthError,
+ HeadroomCompressError,
+ ConfigurationError,
+ ProviderError,
+ StorageError,
+ TokenizationError,
+ CacheError,
+ ValidationError,
+ TransformError,
+} from 'headroom-ai';
+
+try {
+ await client.compress(messages);
+} catch (err) {
+ if (err instanceof HeadroomAuthError) {
+ console.error('Auth failed — check HEADROOM_API_KEY');
+ } else if (err instanceof HeadroomCompressError) {
+ console.error(`Compression error ${err.statusCode}: ${err.errorType}`);
+ } else if (err instanceof ConfigurationError) {
+ console.error('Bad config:', err.details);
+ }
+}
+```
+
+## Format Detection & Conversion
+
+Auto-detects and converts between OpenAI, Anthropic, Vercel AI SDK, and Gemini formats.
+
+```typescript
+import { detectFormat, toOpenAI, fromOpenAI } from 'headroom-ai';
+
+const format = detectFormat(messages); // 'openai' | 'anthropic' | 'vercel' | 'gemini'
+const openaiMessages = toOpenAI(messages);
+const back = fromOpenAI(openaiMessages, format);
+```
+
+The `compress()` function handles this automatically — pass any format and get the same format back.
+
## Configuration
```typescript
@@ -81,6 +364,8 @@ const result = await compress(messages, {
timeout: 30000, // ms
fallback: true, // return uncompressed if proxy is down (default)
retries: 1, // retry on transient failures (default)
+ tokenBudget: 4000, // compress to fit this limit
+ hooks: new MyHooks(), // pre/post compression hooks
});
```
@@ -88,19 +373,20 @@ Or use environment variables:
- `HEADROOM_BASE_URL` — proxy/cloud URL
- `HEADROOM_API_KEY` — Cloud API key
-## Reusable Client
+## Utilities
```typescript
-import { HeadroomClient } from 'headroom-ai';
+// Case conversion for proxy communication
+import { deepCamelCase, deepSnakeCase } from 'headroom-ai';
-const client = new HeadroomClient({
- baseUrl: 'http://localhost:8787',
- apiKey: 'hr_...',
-});
+const tsObj = deepCamelCase({ tokens_before: 100 }); // { tokensBefore: 100 }
+const pyObj = deepSnakeCase({ tokensBefore: 100 }); // { tokens_before: 100 }
+
+// SSE stream parsing
+import { parseSSE, collectStream } from 'headroom-ai';
-// Reuse across many calls
-const r1 = await client.compress(messages1, { model: 'gpt-4o' });
-const r2 = await client.compress(messages2, { model: 'gpt-4o' });
+// Hook helpers
+import { extractUserQuery, countTurns, extractToolCalls } from 'headroom-ai';
```
## License
diff --git a/sdk/typescript/examples/README.md b/sdk/typescript/examples/README.md
new file mode 100644
index 000000000..5a6c94585
--- /dev/null
+++ b/sdk/typescript/examples/README.md
@@ -0,0 +1,47 @@
+# headroom-ai examples
+
+Runnable examples showing how to use the Headroom TypeScript SDK for context compression.
+
+## Prerequisites
+
+- Node.js 18+
+- A running Headroom proxy (`pip install "headroom-ai[proxy]" && headroom proxy`)
+- `OPENAI_API_KEY` set in your environment (most examples use OpenAI)
+- Optional: `ANTHROPIC_API_KEY` for Anthropic examples
+
+## Running
+
+```bash
+cd sdk/typescript
+npm install
+npx tsx examples/<filename>.ts
+```
+
+## Examples
+
+### Vercel AI SDK
+
+| Example | Description |
+|---------|-------------|
+| [with-headroom-vercel.ts](with-headroom-vercel.ts) | One-liner `withHeadroom(openai('gpt-4o'))` — simplest integration |
+| [streaming-chat.ts](streaming-chat.ts) | `withHeadroom` + `streamText` for real-time streaming |
+| [tool-calling-agent.ts](tool-calling-agent.ts) | Multi-step agent with tools, context auto-compressed each step |
+| [structured-output.ts](structured-output.ts) | Extract structured data with `Output.object()` from compressed context |
+| [middleware-composition.ts](middleware-composition.ts) | Stack `headroomMiddleware` with other middlewares (`extractReasoningMiddleware`) |
+| [multi-provider.ts](multi-provider.ts) | Same compression across GPT-4o and GPT-4o-mini |
+
+### Core SDK
+
+| Example | Description |
+|---------|-------------|
+| [basic-compress.ts](basic-compress.ts) | `compress()` function — compress then send to any LLM |
+| [simulation-dry-run.ts](simulation-dry-run.ts) | `simulate()` — see what compression would do without calling the LLM |
+| [hooks-custom-compression.ts](hooks-custom-compression.ts) | `CompressionHooks` — customize with pre/post hooks and per-message biases |
+| [shared-context-multi-agent.ts](shared-context-multi-agent.ts) | `SharedContext` — compressed handoff between agents (70-90% savings) |
+| [ccr-retrieve.ts](ccr-retrieve.ts) | CCR — retrieve original content after compression (lossless) |
+
+### Native SDK Adapters
+
+| Example | Description |
+|---------|-------------|
+| [openai-anthropic-adapters.ts](openai-anthropic-adapters.ts) | `withHeadroom` for native OpenAI and Anthropic SDKs (no Vercel AI SDK) |
diff --git a/sdk/typescript/examples/basic-compress.ts b/sdk/typescript/examples/basic-compress.ts
new file mode 100644
index 000000000..ba705c98e
--- /dev/null
+++ b/sdk/typescript/examples/basic-compress.ts
@@ -0,0 +1,64 @@
+/**
+ * Example 01: Basic Compression
+ *
+ * Compress messages before sending to any LLM.
+ * Works with any message format — OpenAI, Anthropic, Vercel AI SDK, Gemini.
+ *
+ * Run: npx tsx examples/01-basic-compress.ts
+ */
+import { compress } from "headroom-ai";
+import { openai } from "@ai-sdk/openai";
+import { generateText } from "ai";
+
+// Simulate a large tool output — 80 server status records
+const serverFleet = Array.from({ length: 80 }, (_, i) => ({
+ id: i + 1,
+ hostname: `web-${String(i + 1).padStart(3, "0")}.prod.internal`,
+ status: i === 42 ? "critical" : i % 15 === 0 ? "warning" : "healthy",
+ cpu_percent: Math.round(Math.random() * 100),
+ memory_mb: Math.round(Math.random() * 16384),
+ region: ["us-east-1", "eu-west-1", "ap-southeast-1"][i % 3],
+ last_heartbeat: "2025-06-15T10:30:00Z",
+ uptime_hours: Math.floor(Math.random() * 8760),
+ active_connections: Math.floor(Math.random() * 1000),
+}));
+
+const messages = [
+ {
+ role: "system" as const,
+ content: "You are a DevOps assistant. Analyze infrastructure data and report issues concisely.",
+ },
+ { role: "user" as const, content: "Show me all servers" },
+ {
+ role: "assistant" as const,
+ content: null,
+ tool_calls: [
+ { id: "call_1", type: "function" as const, function: { name: "list_servers", arguments: "{}" } },
+ ],
+ },
+ {
+ role: "tool" as const,
+ content: JSON.stringify(serverFleet),
+ tool_call_id: "call_1",
+ },
+ { role: "user" as const, content: "Which servers need attention? Be specific." },
+];
+
+async function main() {
+ // Compress the conversation
+ const result = await compress(messages, { model: "gpt-4o" });
+
+ console.log(`Tokens: ${result.tokensBefore} → ${result.tokensAfter}`);
+ console.log(`Saved: ${result.tokensSaved} tokens (${((1 - result.compressionRatio) * 100).toFixed(0)}%)`);
+ console.log(`Transforms: ${result.transformsApplied.join(", ")}`);
+
+ // Use compressed messages with Vercel AI SDK
+ const { text } = await generateText({
+ model: openai("gpt-4o"),
+ messages: result.messages,
+ });
+
+ console.log("\nAssistant:", text);
+}
+
+main().catch(console.error);
diff --git a/sdk/typescript/examples/ccr-retrieve.ts b/sdk/typescript/examples/ccr-retrieve.ts
new file mode 100644
index 000000000..e9d11919d
--- /dev/null
+++ b/sdk/typescript/examples/ccr-retrieve.ts
@@ -0,0 +1,80 @@
+/**
+ * Example 12: CCR Retrieve — Lossless Compression
+ *
+ * Headroom compresses aggressively but stores originals.
+ * When the LLM needs full details, it calls headroom_retrieve.
+ * Nothing is ever thrown away.
+ *
+ * Run: npx tsx examples/12-ccr-retrieve.ts
+ */
+import { HeadroomClient } from "headroom-ai";
+
+// Large dataset that will trigger CCR (Compress-Cache-Retrieve)
+const auditLog = Array.from({ length: 200 }, (_, i) => ({
+ id: i + 1,
+ timestamp: new Date(Date.now() - i * 60000).toISOString(),
+ actor: `user_${Math.floor(Math.random() * 20)}`,
+ action: ["login", "update_profile", "delete_record", "export_data", "change_role", "api_call"][i % 6],
+ resource: `resource_${Math.floor(Math.random() * 50)}`,
+ ip_address: `192.168.${Math.floor(Math.random() * 255)}.${Math.floor(Math.random() * 255)}`,
+ user_agent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",
+ success: i % 23 !== 0,
+ details: i % 23 === 0
+ ? `FAILED: Unauthorized access attempt to admin resource. IP flagged.`
+ : `Routine ${["login", "update_profile", "delete_record", "export_data", "change_role", "api_call"][i % 6]} operation completed.`,
+}));
+
+async function main() {
+ const client = new HeadroomClient();
+
+ // Compress the large audit log
+ const result = await client.compress(
+ [
+ { role: "system", content: "You are a security analyst." },
+ { role: "user", content: "Review the audit log" },
+ {
+ role: "assistant",
+ content: null,
+ tool_calls: [
+ { id: "call_1", type: "function", function: { name: "get_audit_log", arguments: '{"limit":200}' } },
+ ],
+ },
+ { role: "tool", content: JSON.stringify(auditLog), tool_call_id: "call_1" },
+ { role: "user", content: "Find any suspicious activity" },
+ ] as any[],
+ { model: "gpt-4o" },
+ );
+
+ console.log(`Compressed: ${result.tokensBefore} → ${result.tokensAfter} tokens`);
+ console.log(`Saved: ${result.tokensSaved} tokens (${((1 - result.compressionRatio) * 100).toFixed(0)}%)`);
+ console.log(`CCR hashes: ${result.ccrHashes.length}`);
+
+ // The LLM can retrieve full originals via CCR
+ if (result.ccrHashes.length > 0) {
+ console.log("\n=== Retrieving originals via CCR ===");
+ for (const hash of result.ccrHashes) {
+ try {
+ const original = await client.retrieve(hash);
+ console.log(`Hash ${hash}:`);
+ console.log(` Original tokens: ${(original as any).originalTokens}`);
+ console.log(` Tool: ${(original as any).toolName}`);
+ console.log(` Retrievals: ${(original as any).retrievalCount}`);
+ } catch (e: any) {
+ console.log(` Could not retrieve ${hash}: ${e.message}`);
+ }
+ }
+
+ // Search within compressed content
+ console.log("\n=== Searching within compressed content ===");
+ try {
+ const search = await client.retrieve(result.ccrHashes[0], {
+ query: "unauthorized access",
+ });
+ console.log("Search results:", JSON.stringify(search, null, 2).slice(0, 300));
+ } catch (e: any) {
+ console.log(`Search error: ${e.message}`);
+ }
+ }
+}
+
+main().catch(console.error);
diff --git a/sdk/typescript/examples/hooks-custom-compression.ts b/sdk/typescript/examples/hooks-custom-compression.ts
new file mode 100644
index 000000000..c9f353f20
--- /dev/null
+++ b/sdk/typescript/examples/hooks-custom-compression.ts
@@ -0,0 +1,117 @@
+/**
+ * Example 07: Custom Compression Hooks
+ *
+ * Use CompressionHooks to customize what gets compressed and observe results.
+ * Hooks run client-side before/after the proxy compression.
+ *
+ * Run: npx tsx examples/07-hooks-custom-compression.ts
+ */
+import { compress, CompressionHooks } from "headroom-ai";
+import type { CompressContext, CompressEvent } from "headroom-ai";
+import { openai } from "@ai-sdk/openai";
+import { generateText } from "ai";
+
+// Track compression stats across multiple calls
+const stats = {
+ calls: 0,
+ totalSaved: 0,
+ transforms: new Map<string, number>(),
+};
+
+class ObservabilityHooks extends CompressionHooks {
+ /**
+ * Add context before compression — inject hints for the compressor.
+ */
+ preCompress(messages: any[], ctx: CompressContext) {
+ console.log(`[hook] Pre-compress: ${messages.length} messages, model=${ctx.model}`);
+ console.log(`[hook] User query: "${ctx.userQuery.slice(0, 60)}..."`);
+ console.log(`[hook] Tool calls in context: ${ctx.toolCalls.join(", ") || "none"}`);
+ return messages;
+ }
+
+ /**
+ * Set per-message compression biases.
+ * Higher bias = preserve more. Lower bias = compress more aggressively.
+ */
+ computeBiases(messages: any[], _ctx: CompressContext) {
+ const biases: Record<number, number> = {};
+ for (let i = 0; i < messages.length; i++) {
+ // Always preserve system messages fully
+ if (messages[i].role === "system") {
+ biases[i] = 2.0;
+ }
+ // Preserve the last user message (the actual question)
+ if (i === messages.length - 1 && messages[i].role === "user") {
+ biases[i] = 1.5;
+ }
+ }
+ return biases;
+ }
+
+ /**
+ * Observe compression results — log and track stats.
+ */
+ postCompress(event: CompressEvent) {
+ stats.calls++;
+ stats.totalSaved += event.tokensSaved;
+ for (const t of event.transformsApplied) {
+ stats.transforms.set(t, (stats.transforms.get(t) ?? 0) + 1);
+ }
+
+ console.log(`[hook] Post-compress: ${event.tokensBefore} → ${event.tokensAfter} (saved ${event.tokensSaved})`);
+ console.log(`[hook] Ratio: ${(event.compressionRatio * 100).toFixed(1)}%`);
+ console.log(`[hook] Transforms: ${event.transformsApplied.join(", ")}`);
+ if (event.ccrHashes.length > 0) {
+ console.log(`[hook] CCR hashes (retrievable): ${event.ccrHashes.join(", ")}`);
+ }
+ }
+}
+
+// Large structured data
+const inventory = Array.from({ length: 75 }, (_, i) => ({
+ sku: `SKU-${String(i + 1).padStart(4, "0")}`,
+ name: `Product ${i + 1}`,
+ category: ["Electronics", "Clothing", "Home", "Sports", "Books"][i % 5],
+ price: +(Math.random() * 200 + 10).toFixed(2),
+ stock: Math.floor(Math.random() * 500),
+ warehouse: ["NYC", "LAX", "ORD", "DFW"][i % 4],
+ reorder_point: Math.floor(Math.random() * 50 + 10),
+ last_sold: new Date(Date.now() - Math.random() * 7 * 86400000).toISOString(),
+}));
+
+async function main() {
+ const hooks = new ObservabilityHooks();
+
+ console.log("=== Call 1: Inventory analysis ===\n");
+ const result1 = await compress(
+ [
+ { role: "system", content: "You are an inventory management assistant." },
+ { role: "user", content: "Show me inventory" },
+ {
+ role: "assistant",
+ content: null,
+ tool_calls: [{ id: "c1", type: "function", function: { name: "get_inventory", arguments: "{}" } }],
+ },
+ { role: "tool", content: JSON.stringify(inventory), tool_call_id: "c1" },
+ { role: "user", content: "Which items are below reorder point and need restocking?" },
+ ],
+ { model: "gpt-4o", hooks },
+ );
+
+ // Use compressed messages
+ const { text } = await generateText({
+ model: openai("gpt-4o"),
+ messages: result1.messages,
+ });
+ console.log("\nAnswer:", text.slice(0, 200), "...\n");
+
+ console.log("=== Cumulative Stats ===");
+ console.log(`Total calls: ${stats.calls}`);
+ console.log(`Total tokens saved: ${stats.totalSaved}`);
+ console.log("Transform frequency:");
+ for (const [name, count] of stats.transforms) {
+ console.log(` ${name}: ${count}x`);
+ }
+}
+
+main().catch(console.error);
diff --git a/sdk/typescript/examples/middleware-composition.ts b/sdk/typescript/examples/middleware-composition.ts
new file mode 100644
index 000000000..f79dc1fc0
--- /dev/null
+++ b/sdk/typescript/examples/middleware-composition.ts
@@ -0,0 +1,59 @@
+/**
+ * Example 10: Middleware Composition
+ *
+ * Combine headroomMiddleware with other Vercel AI SDK middlewares.
+ * Headroom compresses first, then other middlewares process the result.
+ *
+ * Run: npx tsx examples/10-middleware-composition.ts
+ */
+import { headroomMiddleware } from "headroom-ai/vercel-ai";
+import { openai } from "@ai-sdk/openai";
+import { generateText, wrapLanguageModel, extractReasoningMiddleware } from "ai";
+
+// Large context that benefits from compression
+const codebaseAnalysis = Array.from({ length: 40 }, (_, i) => ({
+ file: `src/modules/${["auth", "billing", "users", "api", "workers"][i % 5]}/handler${Math.floor(i / 5)}.ts`,
+ lines: Math.floor(Math.random() * 500 + 100),
+ complexity: Math.floor(Math.random() * 30 + 1),
+ dependencies: Array.from({ length: Math.floor(Math.random() * 8) }, (_, j) => `dep-${j}`),
+ last_modified: new Date(Date.now() - Math.random() * 180 * 86400000).toISOString(),
+ test_coverage: +(Math.random() * 100).toFixed(1),
+ issues: Array.from({ length: Math.floor(Math.random() * 3) }, () =>
+ ["unused import", "any type", "missing null check", "no error handling", "hardcoded value"][Math.floor(Math.random() * 5)]
+ ),
+}));
+
+async function main() {
+ // Stack multiple middlewares: compression + reasoning extraction
+ const model = wrapLanguageModel({
+ model: openai("gpt-4o"),
+ middleware: [
+ headroomMiddleware(), // compress large context
+ extractReasoningMiddleware({ tagName: "think" }), // extract chain-of-thought
+ ],
+ });
+
+ const { text, reasoning } = await generateText({
+ model,
+ messages: [
+ {
+ role: "system",
+ content: `You are a code quality analyst. When analyzing, wrap your reasoning in <think> tags before giving your final answer.`,
+ },
+ {
+ role: "user",
+ content: `Analyze this codebase for quality issues:\n\n${JSON.stringify(codebaseAnalysis)}\n\nWhat are the top 3 areas that need immediate attention?`,
+ },
+ ],
+ });
+
+ if (reasoning) {
+ console.log("=== Internal Reasoning ===");
+ console.log(reasoning.slice(0, 300), "...\n");
+ }
+
+ console.log("=== Analysis ===");
+ console.log(text);
+}
+
+main().catch(console.error);
diff --git a/sdk/typescript/examples/multi-provider.ts b/sdk/typescript/examples/multi-provider.ts
new file mode 100644
index 000000000..b751af5b2
--- /dev/null
+++ b/sdk/typescript/examples/multi-provider.ts
@@ -0,0 +1,53 @@
+/**
+ * Example 05: Multi-Provider Compression
+ *
+ * Use the same withHeadroom wrapper across different providers.
+ * Headroom compresses identically regardless of which LLM you use.
+ *
+ * Run: npx tsx examples/05-multi-provider.ts
+ */
+import { withHeadroom } from "headroom-ai/vercel-ai";
+import { openai } from "@ai-sdk/openai";
+import { generateText } from "ai";
+
+// Large JSON dataset — same data, different models
+const salesData = Array.from({ length: 60 }, (_, i) => ({
+ quarter: `Q${(i % 4) + 1} ${2023 + Math.floor(i / 4)}`,
+ region: ["North America", "Europe", "Asia Pacific", "Latin America"][i % 4],
+ product: ["Enterprise", "Pro", "Starter"][i % 3],
+ revenue: Math.round(Math.random() * 1000000),
+ customers: Math.floor(Math.random() * 500),
+ churn_rate: +(Math.random() * 0.15).toFixed(3),
+ nps_score: Math.floor(Math.random() * 40 + 60),
+ support_tickets: Math.floor(Math.random() * 200),
+ avg_response_time_hrs: +(Math.random() * 24).toFixed(1),
+}));
+
+const messages = [
+ {
+ role: "system" as const,
+ content: "You are a business analyst. Analyze the data and provide key insights. Be concise — bullet points preferred.",
+ },
+ {
+ role: "user" as const,
+ content: `Here is our sales data:\n${JSON.stringify(salesData)}\n\nWhat are the 3 most important trends?`,
+ },
+];
+
+async function main() {
+ // GPT-4o with compression
+ console.log("=== OpenAI GPT-4o ===");
+ const gpt = withHeadroom(openai("gpt-4o"));
+ const gptResult = await generateText({ model: gpt, messages });
+ console.log(gptResult.text);
+ console.log(`Tokens: ${gptResult.usage.promptTokens} prompt, ${gptResult.usage.completionTokens} completion\n`);
+
+ // GPT-4o-mini with compression (cheaper, faster)
+ console.log("=== OpenAI GPT-4o-mini ===");
+ const mini = withHeadroom(openai("gpt-4o-mini"));
+ const miniResult = await generateText({ model: mini, messages });
+ console.log(miniResult.text);
+ console.log(`Tokens: ${miniResult.usage.promptTokens} prompt, ${miniResult.usage.completionTokens} completion\n`);
+}
+
+main().catch(console.error);
diff --git a/sdk/typescript/examples/openai-anthropic-adapters.ts b/sdk/typescript/examples/openai-anthropic-adapters.ts
new file mode 100644
index 000000000..5798efbcb
--- /dev/null
+++ b/sdk/typescript/examples/openai-anthropic-adapters.ts
@@ -0,0 +1,73 @@
+/**
+ * Example 11: OpenAI & Anthropic SDK Adapters
+ *
+ * Wrap native SDK clients directly — no Vercel AI SDK needed.
+ * Messages are compressed transparently before each API call.
+ *
+ * Run: npx tsx examples/11-openai-anthropic-adapters.ts
+ */
+import { withHeadroom as withHeadroomOpenAI } from "headroom-ai/openai";
+import { withHeadroom as withHeadroomAnthropic } from "headroom-ai/anthropic";
+import OpenAI from "openai";
+import Anthropic from "@anthropic-ai/sdk";
+
+// Same large context for both providers
+const githubIssues = Array.from({ length: 40 }, (_, i) => ({
+ number: 1000 + i,
+ title: `Issue #${1000 + i}: ${["Fix memory leak in worker pool", "Add retry logic for API calls", "Refactor auth middleware", "Update deprecated dependencies", "Add rate limiting"][i % 5]}`,
+ state: i % 8 === 0 ? "closed" : "open",
+ labels: [["bug", "P1"], ["enhancement"], ["tech-debt", "P2"], ["security"], ["performance"]][i % 5],
+ author: `dev${i % 7}`,
+ comments: Math.floor(Math.random() * 15),
+ body: `Detailed description of issue ${1000 + i}. This includes reproduction steps, expected behavior, actual behavior, environment details, and relevant log snippets. The issue was first reported on ${new Date(Date.now() - Math.random() * 90 * 86400000).toISOString().split("T")[0]}.`,
+ created_at: new Date(Date.now() - Math.random() * 90 * 86400000).toISOString(),
+}));
+
+const messages = [
+ {
+ role: "user" as const,
+ content: `Here are our open GitHub issues:\n\n${JSON.stringify(githubIssues)}\n\nPrioritize the top 5 issues we should tackle this sprint and explain why.`,
+ },
+];
+
+async function main() {
+ // === OpenAI with compression ===
+ if (process.env.OPENAI_API_KEY) {
+ console.log("=== OpenAI (compressed) ===");
+ const openai = withHeadroomOpenAI(new OpenAI());
+
+ const response = await openai.chat.completions.create({
+ model: "gpt-4o",
+ messages: [
+ { role: "system", content: "You are a technical project manager. Prioritize issues for the sprint." },
+ ...messages,
+ ],
+ });
+
+ console.log(response.choices[0].message.content?.slice(0, 400), "...\n");
+ }
+
+ // === Anthropic with compression ===
+ if (process.env.ANTHROPIC_API_KEY) {
+ console.log("=== Anthropic (compressed) ===");
+ const anthropic = withHeadroomAnthropic(new Anthropic());
+
+ const response = await anthropic.messages.create({
+ model: "claude-sonnet-4-5-20250929",
+ max_tokens: 1024,
+ messages,
+ });
+
+ const text = response.content
+ .filter((b: any) => b.type === "text")
+ .map((b: any) => b.text)
+ .join("");
+ console.log(text.slice(0, 400), "...\n");
+ }
+
+ if (!process.env.OPENAI_API_KEY && !process.env.ANTHROPIC_API_KEY) {
+ console.log("Set OPENAI_API_KEY or ANTHROPIC_API_KEY to run this example.");
+ }
+}
+
+main().catch(console.error);
diff --git a/sdk/typescript/examples/shared-context-multi-agent.ts b/sdk/typescript/examples/shared-context-multi-agent.ts
new file mode 100644
index 000000000..ae25bad3a
--- /dev/null
+++ b/sdk/typescript/examples/shared-context-multi-agent.ts
@@ -0,0 +1,74 @@
+/**
+ * Example 08: SharedContext — Multi-Agent Compressed Handoff
+ *
+ * Agent A researches a topic and stores compressed results.
+ * Agent B reads the compressed context and acts on it.
+ * Saves 70-90% of tokens on inter-agent communication.
+ *
+ * Run: npx tsx examples/08-shared-context-multi-agent.ts
+ */
+import { SharedContext } from "headroom-ai";
+import { withHeadroom } from "headroom-ai/vercel-ai";
+import { openai } from "@ai-sdk/openai";
+import { generateText } from "ai";
+
+// Simulate a research agent's output — large structured data
+const researchOutput = {
+ topic: "Kubernetes autoscaling strategies",
+ sources: Array.from({ length: 30 }, (_, i) => ({
+ title: `Source ${i + 1}: ${["HPA deep dive", "VPA configuration", "Cluster autoscaler", "KEDA event-driven", "Custom metrics"][i % 5]}`,
+ content: `Detailed technical content about ${["horizontal pod autoscaling", "vertical pod autoscaling", "node autoscaling", "event-driven scaling", "custom metrics scaling"][i % 5]}. This section covers implementation details, best practices, common pitfalls, and real-world examples from production deployments at scale.`,
+ relevance: +(Math.random() * 0.5 + 0.5).toFixed(2),
+ citations: Math.floor(Math.random() * 100),
+ })),
+ summary: "Kubernetes offers multiple autoscaling strategies at different levels: HPA for pod replicas, VPA for resource requests, Cluster Autoscaler for nodes, and KEDA for event-driven workloads.",
+};
+
+async function main() {
+ const ctx = new SharedContext({ model: "gpt-4o", maxEntries: 50 });
+ const model = withHeadroom(openai("gpt-4o"));
+
+ // === Agent A: Research Agent ===
+ console.log("=== Agent A: Research ===");
+
+ const entry = await ctx.put("k8s-scaling-research", JSON.stringify(researchOutput), {
+ agent: "researcher",
+ });
+
+ console.log(`Stored: ${entry.originalTokens} tokens → ${entry.compressedTokens} tokens`);
+ console.log(`Savings: ${entry.savingsPercent.toFixed(0)}%`);
+ console.log(`Transforms: ${entry.transforms.join(", ")}`);
+
+ // === Agent B: Writer Agent ===
+ console.log("\n=== Agent B: Writer ===");
+
+ // Read compressed context (80% smaller)
+ const compressed = ctx.get("k8s-scaling-research");
+ console.log(`Reading compressed context (${compressed?.length ?? 0} chars)`);
+
+ const { text } = await generateText({
+ model,
+ messages: [
+ {
+ role: "system",
+ content: "You are a technical writer. Create a concise blog post outline from research data.",
+ },
+ {
+ role: "user",
+ content: `Based on this research, create a blog post outline:\n\n${compressed}`,
+ },
+ ],
+ });
+
+ console.log("\nBlog outline:", text);
+
+ // === Stats ===
+ console.log("\n=== SharedContext Stats ===");
+ const stats = ctx.stats();
+ console.log(`Entries: ${stats.entries}`);
+ console.log(`Original tokens: ${stats.totalOriginalTokens}`);
+ console.log(`Compressed tokens: ${stats.totalCompressedTokens}`);
+ console.log(`Total saved: ${stats.totalTokensSaved} (${stats.savingsPercent.toFixed(0)}%)`);
+}
+
+main().catch(console.error);
diff --git a/sdk/typescript/examples/simulation-dry-run.ts b/sdk/typescript/examples/simulation-dry-run.ts
new file mode 100644
index 000000000..beab779ac
--- /dev/null
+++ b/sdk/typescript/examples/simulation-dry-run.ts
@@ -0,0 +1,80 @@
+/**
+ * Example 06: Simulation (Dry Run)
+ *
+ * See exactly what compression would do without calling the LLM.
+ * Useful for debugging, cost estimation, and understanding compression behavior.
+ *
+ * Run: npx tsx examples/06-simulation-dry-run.ts
+ */
+import { simulate } from "headroom-ai";
+
+// Different types of content to analyze
+const logEntries = Array.from({ length: 100 }, (_, i) => ({
+ timestamp: new Date(Date.now() - i * 30000).toISOString(),
+ level: i === 67 ? "FATAL" : i % 15 === 0 ? "ERROR" : "INFO",
+ service: "payment-gateway",
+ message: i === 67
+ ? "Connection pool exhausted: max_connections=100, active=100, waiting=47"
+ : `Processing transaction txn_${Math.random().toString(36).slice(2, 10)}`,
+ trace_id: `trace-${i}`,
+ duration_ms: Math.floor(Math.random() * 500),
+}));
+
+const messages = [
+ {
+ role: "system" as const,
+ content: "You are an SRE assistant analyzing production logs.",
+ },
+ {
+ role: "user" as const,
+ content: "Check the payment gateway logs for issues",
+ },
+ {
+ role: "assistant" as const,
+ content: null,
+ tool_calls: [
+ { id: "call_1", type: "function" as const, function: { name: "get_logs", arguments: '{"service":"payment-gateway","limit":100}' } },
+ ],
+ },
+ {
+ role: "tool" as const,
+ content: JSON.stringify(logEntries),
+ tool_call_id: "call_1",
+ },
+ {
+ role: "user" as const,
+ content: "What's wrong? Is there a critical issue?",
+ },
+];
+
+async function main() {
+ console.log("Running compression simulation (no LLM call)...\n");
+
+ const sim = await simulate(messages, { model: "gpt-4o" });
+
+ console.log("=== Simulation Results ===");
+ console.log(`Tokens before: ${sim.tokensBefore}`);
+ console.log(`Tokens after: ${sim.tokensAfter}`);
+ console.log(`Tokens saved: ${sim.tokensSaved}`);
+ console.log(`Estimated savings: ${sim.estimatedSavings}`);
+ console.log(`\nTransforms applied: ${sim.transforms?.join(", ") || "none"}`);
+
+ if (sim.wasteSignals && Object.keys(sim.wasteSignals).length > 0) {
+ console.log("\nWaste signals detected:");
+ for (const [signal, tokens] of Object.entries(sim.wasteSignals)) {
+ if (tokens > 0) console.log(` ${signal}: ${tokens} tokens`);
+ }
+ }
+
+ if (sim.blockBreakdown && Object.keys(sim.blockBreakdown).length > 0) {
+ console.log("\nBlock breakdown:");
+ for (const [kind, count] of Object.entries(sim.blockBreakdown)) {
+ console.log(` ${kind}: ${count}`);
+ }
+ }
+
+ console.log(`\nCache alignment score: ${sim.cacheAlignmentScore}`);
+ console.log(`Stable prefix hash: ${sim.stablePrefixHash || "none"}`);
+}
+
+main().catch(console.error);
diff --git a/sdk/typescript/examples/streaming-chat.ts b/sdk/typescript/examples/streaming-chat.ts
new file mode 100644
index 000000000..19f0c94d8
--- /dev/null
+++ b/sdk/typescript/examples/streaming-chat.ts
@@ -0,0 +1,71 @@
+/**
+ * Example 03: Streaming Chat with Compression
+ *
+ * Use withHeadroom with streamText for real-time streaming responses.
+ * Compression happens before the stream starts — the LLM sees fewer tokens.
+ *
+ * Run: npx tsx examples/03-streaming-chat.ts
+ */
+import { withHeadroom } from "headroom-ai/vercel-ai";
+import { openai } from "@ai-sdk/openai";
+import { streamText } from "ai";
+
+// Simulate a long conversation with code review context
+const codeReviewMessages = [
+ {
+ role: "system" as const,
+ content: "You are a senior code reviewer. Be thorough but concise.",
+ },
+ {
+ role: "user" as const,
+ content: "Review this pull request diff",
+ },
+ {
+ role: "assistant" as const,
+ content: null,
+ toolInvocations: [] as any[],
+ },
+ {
+ role: "tool" as const,
+ content: [
+ {
+ type: "tool-result" as const,
+ toolCallId: "call_diff",
+ toolName: "get_pr_diff",
+ result: generateLargeDiff(),
+ },
+ ],
+ },
+ {
+ role: "user" as const,
+ content: "What are the most critical issues in this diff?",
+ },
+];
+
+function generateLargeDiff(): string {
+ const files = Array.from({ length: 15 }, (_, i) => {
+ const lines = Array.from({ length: 20 }, (_, j) => {
+ const prefix = j % 5 === 0 ? "+" : j % 7 === 0 ? "-" : " ";
+ return `${prefix} ${j % 5 === 0 ? "// TODO: refactor this" : `const value${j} = process(input${j});`}`;
+ });
+ return `--- a/src/module${i}/handler.ts\n+++ b/src/module${i}/handler.ts\n@@ -1,20 +1,20 @@\n${lines.join("\n")}`;
+ });
+ return files.join("\n\n");
+}
+
+async function main() {
+ const model = withHeadroom(openai("gpt-4o"));
+
+ const result = streamText({
+ model,
+ messages: codeReviewMessages,
+ });
+
+ process.stdout.write("Review: ");
+ for await (const chunk of result.textStream) {
+ process.stdout.write(chunk);
+ }
+ console.log("\n\nDone.");
+}
+
+main().catch(console.error);
diff --git a/sdk/typescript/examples/structured-output.ts b/sdk/typescript/examples/structured-output.ts
new file mode 100644
index 000000000..9180661df
--- /dev/null
+++ b/sdk/typescript/examples/structured-output.ts
@@ -0,0 +1,99 @@
+/**
+ * Example 09: Structured Output with Compression
+ *
+ * Compress large context, then extract structured data with generateObject.
+ * Compression preserves the signal needed for accurate extraction.
+ *
+ * Run: npx tsx examples/09-structured-output.ts
+ */
+import { withHeadroom } from "headroom-ai/vercel-ai";
+import { openai } from "@ai-sdk/openai";
+import { generateText, Output } from "ai";
+import { z } from "zod";
+
+// Simulate a large incident report with lots of noise
+const incidentLogs = Array.from({ length: 150 }, (_, i) => {
+ if (i === 73) {
+ return {
+ timestamp: "2025-06-15T14:32:17Z",
+ level: "FATAL",
+ service: "payment-service",
+ message: "Circuit breaker OPEN: downstream timeout after 30s. Affected: POST /api/v2/charges. Error: ETIMEDOUT 10.0.3.42:5432",
+ trace_id: "trace-incident-001",
+ };
+ }
+ if (i === 89) {
+ return {
+ timestamp: "2025-06-15T14:33:01Z",
+ level: "ERROR",
+ service: "payment-service",
+ message: "Retry exhausted for transaction txn_abc123. Customer: cust_xyz. Amount: $249.99. Gateway: stripe. Error: upstream_timeout",
+ trace_id: "trace-incident-001",
+ };
+ }
+ return {
+ timestamp: new Date(Date.now() - (150 - i) * 10000).toISOString(),
+ level: "INFO",
+ service: ["payment-service", "auth-service", "api-gateway", "notification-service"][i % 4],
+ message: `Routine: processed request ${i}, latency=${Math.floor(Math.random() * 100)}ms`,
+ trace_id: `trace-${Math.random().toString(36).slice(2, 8)}`,
+ };
+});
+
+// Schema for structured incident extraction
+const IncidentReport = z.object({
+ severity: z.enum(["critical", "high", "medium", "low"]),
+ title: z.string().describe("Short incident title"),
+ rootCause: z.string().describe("Root cause analysis"),
+ affectedServices: z.array(z.string()),
+ affectedEndpoints: z.array(z.string()),
+ timeline: z.array(
+ z.object({
+ time: z.string(),
+ event: z.string(),
+ }),
+ ),
+ impact: z.string().describe("Customer/business impact"),
+ suggestedFix: z.string(),
+});
+
+async function main() {
+ const model = withHeadroom(openai("gpt-4o"));
+
+ console.log(`Input: ${incidentLogs.length} log entries (${JSON.stringify(incidentLogs).length} chars)`);
+
+ const { output: report } = await generateText({
+ model,
+ output: Output.object({ schema: IncidentReport }),
+ messages: [
+ {
+ role: "system",
+ content: "You are an SRE incident commander. Analyze logs and produce structured incident reports.",
+ },
+ {
+ role: "user",
+ content: `Analyze these production logs and create an incident report:\n\n${JSON.stringify(incidentLogs)}`,
+ },
+ ],
+ });
+
+ if (!report) {
+ console.error("No structured output generated.");
+ return;
+ }
+
+ console.log("\n=== Incident Report ===");
+ console.log(`Severity: ${report.severity}`);
+ console.log(`Title: ${report.title}`);
+ console.log(`Root cause: ${report.rootCause}`);
+ console.log(`Affected services: ${report.affectedServices.join(", ")}`);
+ console.log(`Affected endpoints: ${report.affectedEndpoints.join(", ")}`);
+ console.log(`Impact: ${report.impact}`);
+ console.log(`\nTimeline:`);
+ for (const event of report.timeline) {
+ console.log(` ${event.time} — ${event.event}`);
+ }
+ console.log(`\nSuggested fix: ${report.suggestedFix}`);
+}
+
+main().catch(console.error);
diff --git a/sdk/typescript/examples/tool-calling-agent.ts b/sdk/typescript/examples/tool-calling-agent.ts
new file mode 100644
index 000000000..eae45f71b
--- /dev/null
+++ b/sdk/typescript/examples/tool-calling-agent.ts
@@ -0,0 +1,86 @@
+/**
+ * Example 04: Tool-Calling Agent with Compression
+ *
+ * Build an agent that calls tools and compresses the growing context
+ * automatically. Each tool result gets compressed before the next LLM call.
+ *
+ * Run: npx tsx examples/04-tool-calling-agent.ts
+ */
+import { withHeadroom } from "headroom-ai/vercel-ai";
+import { openai } from "@ai-sdk/openai";
+import { generateText, tool, stepCountIs } from "ai";
+import { z } from "zod";
+
+// Mock database
+const mockDB: Record<string, any[]> = {
+ users: Array.from({ length: 100 }, (_, i) => ({
+ id: i + 1,
+ name: `User ${i + 1}`,
+ email: `user${i + 1}@example.com`,
+ role: ["admin", "editor", "viewer"][i % 3],
+ last_login: new Date(Date.now() - Math.random() * 30 * 86400000).toISOString(),
+ active: i % 7 !== 0,
+ })),
+ logs: Array.from({ length: 200 }, (_, i) => ({
+ id: i + 1,
+ timestamp: new Date(Date.now() - i * 60000).toISOString(),
+ level: i === 47 ? "FATAL" : i % 20 === 0 ? "ERROR" : i % 5 === 0 ? "WARN" : "INFO",
+ service: ["auth", "api", "worker", "scheduler"][i % 4],
+ message: `${i === 47 ? "Database connection pool exhausted" : `Processing request ${i}`}`,
+ trace_id: `trace-${Math.random().toString(36).slice(2, 10)}`,
+ })),
+};
+
+async function main() {
+ const model = withHeadroom(openai("gpt-4o"));
+
+ const { text, steps } = await generateText({
+ model,
+ stopWhen: stepCountIs(5),
+ messages: [
+ {
+ role: "system",
+ content: "You are a database admin assistant. Use the available tools to investigate issues. Report findings concisely.",
+ },
+ {
+ role: "user",
+ content: "Check the logs for any critical errors, then find which users are affected.",
+ },
+ ],
+ tools: {
+ query_logs: tool({
+ description: "Query application logs. Returns matching log entries.",
+ parameters: z.object({
+ level: z.string().optional().describe("Filter by log level: INFO, WARN, ERROR, FATAL"),
+ service: z.string().optional().describe("Filter by service name"),
+ limit: z.number().optional().describe("Max results to return"),
+ }),
+ execute: async ({ level, service, limit }) => {
+ let results = mockDB.logs;
+ if (level) results = results.filter((l) => l.level === level);
+ if (service) results = results.filter((l) => l.service === service);
+ return results.slice(0, limit ?? 50);
+ },
+ }),
+ query_users: tool({
+ description: "Query user database. Returns matching users.",
+ parameters: z.object({
+ role: z.string().optional().describe("Filter by role: admin, editor, viewer"),
+ active: z.boolean().optional().describe("Filter by active status"),
+ limit: z.number().optional().describe("Max results"),
+ }),
+ execute: async ({ role, active, limit }) => {
+ let results = mockDB.users;
+ if (role) results = results.filter((u) => u.role === role);
+ if (active !== undefined) results = results.filter((u) => u.active === active);
+ return results.slice(0, limit ?? 25);
+ },
+ }),
+ },
+ });
+
+ console.log(`Agent completed in ${steps.length} steps`);
+ console.log("\nFinal answer:", text);
+}
+
+main().catch(console.error);
diff --git a/sdk/typescript/examples/with-headroom-vercel.ts b/sdk/typescript/examples/with-headroom-vercel.ts
new file mode 100644
index 000000000..a381773e4
--- /dev/null
+++ b/sdk/typescript/examples/with-headroom-vercel.ts
@@ -0,0 +1,57 @@
+/**
+ * Example 02: withHeadroom — Vercel AI SDK One-Liner
+ *
+ * Wrap any Vercel AI SDK model with automatic compression.
+ * Zero config — just wrap and use.
+ *
+ * Run: npx tsx examples/02-with-headroom-vercel.ts
+ */
+import { withHeadroom } from "headroom-ai/vercel-ai";
+import { openai } from "@ai-sdk/openai";
+import { generateText } from "ai";
+
+// Large API response from a search tool
+const searchResults = Array.from({ length: 50 }, (_, i) => ({
+ rank: i + 1,
+ title: `Result ${i + 1}: ${["Understanding microservices", "Docker best practices", "Kubernetes scaling", "CI/CD pipelines", "Cloud architecture"][i % 5]}`,
+ snippet: `This is a detailed snippet for search result ${i + 1}. It contains relevant information about the topic including technical details, code examples, and best practices that would normally consume many tokens.`,
+ url: `https://example.com/article-${i + 1}`,
+ score: +(Math.random() * 0.5 + 0.5).toFixed(3),
+ published: "2025-03-15",
+ author: `Author ${i % 10}`,
+}));
+
+async function main() {
+ // One-liner: wrap the model, compression happens automatically
+ const model = withHeadroom(openai("gpt-4o"));
+
+ const { text, usage } = await generateText({
+ model,
+ messages: [
+ { role: "system", content: "You are a research assistant. Summarize search results concisely." },
+ { role: "user", content: "Search for microservices best practices" },
+ {
+ role: "assistant",
+ content: null,
+ toolInvocations: [],
+ },
+ {
+ role: "tool",
+ content: [
+ {
+ type: "tool-result",
+ toolCallId: "call_search",
+ toolName: "web_search",
+ result: searchResults,
+ },
+ ],
+ },
+ { role: "user", content: "What are the top 3 most relevant results and why?" },
+ ],
+ });
+
+ console.log("Response:", text);
+ console.log("Tokens used:", usage);
+}
+
+main().catch(console.error);
diff --git a/sdk/typescript/package-lock.json b/sdk/typescript/package-lock.json
index 2fdfe2b87..a2fc7254b 100644
--- a/sdk/typescript/package-lock.json
+++ b/sdk/typescript/package-lock.json
@@ -1555,6 +1555,7 @@
"dev": true,
"hasInstallScript": true,
"license": "MIT",
+ "peer": true,
"bin": {
"esbuild": "bin/esbuild"
},
@@ -2088,6 +2089,7 @@
"integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
"dev": true,
"license": "MIT",
+ "peer": true,
"engines": {
"node": ">=12"
},
@@ -2137,6 +2139,7 @@
}
],
"license": "MIT",
+ "peer": true,
"dependencies": {
"nanoid": "^3.3.11",
"picocolors": "^1.1.1",
@@ -2489,6 +2492,7 @@
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"dev": true,
"license": "Apache-2.0",
+ "peer": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
@@ -2517,6 +2521,7 @@
"integrity": "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"esbuild": "^0.21.3",
"postcss": "^8.4.43",
diff --git a/sdk/typescript/package.json b/sdk/typescript/package.json
index 7f798a2ad..0103fa3c1 100644
--- a/sdk/typescript/package.json
+++ b/sdk/typescript/package.json
@@ -51,6 +51,16 @@
"types": "./dist/adapters/anthropic.d.cts",
"default": "./dist/adapters/anthropic.cjs"
}
+ },
+ "./gemini": {
+ "import": {
+ "types": "./dist/adapters/gemini.d.ts",
+ "default": "./dist/adapters/gemini.js"
+ },
+ "require": {
+ "types": "./dist/adapters/gemini.d.cts",
+ "default": "./dist/adapters/gemini.cjs"
+ }
}
},
"engines": {
diff --git a/sdk/typescript/src/adapters/gemini.ts b/sdk/typescript/src/adapters/gemini.ts
new file mode 100644
index 000000000..7522e70db
--- /dev/null
+++ b/sdk/typescript/src/adapters/gemini.ts
@@ -0,0 +1,83 @@
+/**
+ * Gemini adapter — wraps Google Generative AI model with auto-compression.
+ * Matches the pattern of openai.ts and anthropic.ts adapters.
+ */
+
+import { compress } from "../compress.js";
+import type { CompressOptions } from "../types.js";
+
+/* eslint-disable @typescript-eslint/no-explicit-any */
+
+interface GeminiModelLike {
+ generateContent: (params: any) => any;
+ generateContentStream?: (params: any) => any;
+ [key: string]: any;
+}
+
+/**
+ * Wrap a Google Generative AI model to auto-compress before each request.
+ *
+ * Intercepts `model.generateContent()` and `model.generateContentStream()`.
+ *
+ * @example
+ * ```typescript
+ * import { withHeadroom } from 'headroom-ai/gemini';
+ * import { GoogleGenerativeAI } from '@google/generative-ai';
+ *
+ * const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY!);
+ * const model = withHeadroom(genAI.getGenerativeModel({ model: 'gemini-2.0-flash' }));
+ *
+ * const result = await model.generateContent({ contents: longConversation });
+ * ```
+ */
+export function withHeadroom<T extends GeminiModelLike>(
+ model: T,
+ options: CompressOptions = {},
+): T {
+ const originalGenerate = model.generateContent.bind(model);
+ const originalStream = model.generateContentStream?.bind(model);
+
+ const compressedGenerate = async (params: any) => {
+ const contents = params.contents ?? params;
+ const modelName = options.model ?? "gemini-2.0-flash";
+
+ // compress() auto-detects Gemini format
+ const result = await compress(
+ Array.isArray(contents) ? contents : [contents],
+ { ...options, model: modelName },
+ );
+
+ const newParams = Array.isArray(params)
+ ? result.messages
+ : { ...params, contents: result.messages };
+
+ return originalGenerate(newParams);
+ };
+
+ const compressedStream = originalStream
+ ? async (params: any) => {
+ const contents = params.contents ?? params;
+ const modelName = options.model ?? "gemini-2.0-flash";
+
+ const result = await compress(
+ Array.isArray(contents) ? contents : [contents],
+ { ...options, model: modelName },
+ );
+
+ const newParams = Array.isArray(params)
+ ? result.messages
+ : { ...params, contents: result.messages };
+
+ return originalStream(newParams);
+ }
+ : undefined;
+
+ return new Proxy(model, {
+ get(target, prop) {
+ if (prop === "generateContent") return compressedGenerate;
+ if (prop === "generateContentStream" && compressedStream)
+ return compressedStream;
+ 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
index 965fee548..4a8806157 100644
--- a/sdk/typescript/src/adapters/vercel-ai.ts
+++ b/sdk/typescript/src/adapters/vercel-ai.ts
@@ -1,7 +1,22 @@
+import { createRequire } from "node:module";
import { compress } from "../compress.js";
import type { CompressOptions, CompressResult } from "../types.js";
import { vercelToOpenAI, openAIToVercel } from "../utils/format.js";
+/**
+ * Minimal structural type for Vercel AI SDK language models.
+ * Compatible with both LanguageModelV1 (@ai-sdk/provider <=1.x)
+ * and LanguageModelV3 (@ai-sdk/provider >=2.x).
+ */
+interface LanguageModel {
+ readonly specificationVersion: string;
+ readonly provider: string;
+ readonly modelId: string;
+ doGenerate: (...args: any[]) => any;
+ doStream: (...args: any[]) => any;
+ [key: string]: any;
+}
+
/* eslint-disable @typescript-eslint/no-explicit-any */
type VercelMessage = any;
@@ -68,3 +83,42 @@ export async function compressVercelMessages(
messages: vercelMessages,
};
}
+
+/**
+ * Wrap a Vercel AI SDK language model with Headroom compression.
+ * Convenience wrapper around `wrapLanguageModel` + `headroomMiddleware`.
+ *
+ * @example
+ * ```typescript
+ * import { withHeadroom } from 'headroom-ai/vercel-ai';
+ * import { openai } from '@ai-sdk/openai';
+ * import { generateText } from 'ai';
+ *
+ * const model = withHeadroom(openai('gpt-4o'));
+ * const { text } = await generateText({ model, messages });
+ * ```
+ */
+export function withHeadroom<T extends LanguageModel>(
+ model: T,
+ options: CompressOptions = {},
+): T {
+ let wrapLanguageModel: (opts: {
+ model: T;
+ middleware: any;
+ }) => T;
+
+ try {
+ const require = createRequire(import.meta.url);
+ const ai = require("ai");
+ wrapLanguageModel = ai.wrapLanguageModel;
+ } catch {
+ throw new Error(
+ 'withHeadroom() requires the "ai" package. Install it with: npm install ai',
+ );
+ }
+
+ return wrapLanguageModel({
+ model,
+ middleware: headroomMiddleware(options),
+ });
+}
diff --git a/sdk/typescript/src/client.ts b/sdk/typescript/src/client.ts
index 9d9bd3da5..3402386fd 100644
--- a/sdk/typescript/src/client.ts
+++ b/sdk/typescript/src/client.ts
@@ -1,3 +1,13 @@
+/**
+ * HeadroomClient — HTTP client for the Headroom compression proxy.
+ *
+ * Supports:
+ * - compress() — direct compression via /v1/compress
+ * - chat.completions.create() — OpenAI-style passthrough via /v1/chat/completions
+ * - messages.create() — Anthropic-style passthrough via /v1/messages
+ * - Metrics, health, CCR retrieve, telemetry, feedback, TOIN
+ */
+
import type {
OpenAIMessage,
CompressResult,
@@ -6,11 +16,30 @@ import type {
ProxyCompressResponse,
ProxyErrorResponse,
} from "./types.js";
-import {
- HeadroomConnectionError,
- HeadroomAuthError,
- HeadroomCompressError,
-} from "./types.js";
+import { mapProxyError, HeadroomConnectionError, HeadroomAuthError, HeadroomCompressError } from "./errors.js";
+import { deepCamelCase, deepSnakeCase } from "./utils/case.js";
+import { parseSSE } from "./utils/stream.js";
+import type { HeadroomConfig, HeadroomMode } from "./types/config.js";
+import type {
+ SimulationResult,
+ RequestMetrics,
+ MetricsSummary,
+ SessionStats,
+ ValidationResult,
+ HealthStatus,
+ ProxyStats,
+ MemoryUsage,
+ RetrieveResult,
+ RetrieveSearchResult,
+ CCRStats,
+ TelemetryStats,
+ ToolHints,
+ TOINStats,
+ TOINPattern,
+ MetricsQuery,
+ SummaryQuery,
+ StatsHistoryQuery,
+} from "./types/models.js";
const DEFAULT_BASE_URL = "http://localhost:8787";
const DEFAULT_TIMEOUT = 30_000;
@@ -36,14 +65,151 @@ function makeFallbackResult(messages: OpenAIMessage[]): CompressResult {
};
}
+// --- Headroom request params ---
+
+export interface HeadroomParams {
+ headroomMode?: HeadroomMode;
+ headroomCachePrefixTokens?: number;
+ headroomOutputBufferTokens?: number;
+ headroomKeepTurns?: number;
+ headroomToolProfiles?: Record<string, Record<string, any>>;
+}
+
+// --- Sub-clients ---
+
+class ChatCompletions {
+ constructor(private client: HeadroomClient) {}
+
+ /**
+ * Create a chat completion with automatic compression.
+ * Routes through proxy's POST /v1/chat/completions.
+ */
+ async create(
+ params: { model: string; messages: OpenAIMessage[]; stream?: boolean; [key: string]: any } & HeadroomParams,
+ ): Promise<any> {
+ const { headroomMode, headroomCachePrefixTokens, headroomOutputBufferTokens, headroomKeepTurns, headroomToolProfiles, ...apiParams } = params;
+
+ const headers: Record<string, string> = {};
+ if (headroomMode) headers["x-headroom-mode"] = headroomMode;
+
+ const providerKey = this.client.providerApiKey ?? getEnv("OPENAI_API_KEY");
+ if (providerKey) headers["Authorization"] = `Bearer ${providerKey}`;
+
+ const response = await this.client.rawFetch("/v1/chat/completions", {
+ method: "POST",
+ headers,
+ body: apiParams,
+ stream: params.stream,
+ });
+
+ if (params.stream) {
+ return parseSSE(response);
+ }
+
+ return response.json();
+ }
+
+ /**
+ * Simulate compression without calling the LLM.
+ */
+ async simulate(
+ params: { model: string; messages: OpenAIMessage[] } & HeadroomParams,
+ ): Promise<SimulationResult> {
+ const body = {
+ messages: params.messages,
+ model: params.model,
+ config: { default_mode: "simulate", generate_diff_artifact: true },
+ };
+ const result = await this.client.compressRaw(body);
+ return deepCamelCase<SimulationResult>(result);
+ }
+}
+
+class Messages {
+ constructor(private client: HeadroomClient) {}
+
+ /**
+ * Create a message with automatic compression.
+ * Routes through proxy's POST /v1/messages (Anthropic).
+ */
+ async create(
+ params: { model: string; messages: any[]; max_tokens?: number; system?: string | any[]; stream?: boolean; [key: string]: any } & HeadroomParams,
+ ): Promise<any> {
+ const { headroomMode, headroomCachePrefixTokens, headroomOutputBufferTokens, headroomKeepTurns, headroomToolProfiles, ...apiParams } = params;
+
+ const headers: Record<string, string> = {
+ "anthropic-version": "2023-06-01",
+ };
+ if (headroomMode) headers["x-headroom-mode"] = headroomMode;
+
+ const providerKey = this.client.providerApiKey ?? getEnv("ANTHROPIC_API_KEY");
+ if (providerKey) headers["x-api-key"] = providerKey;
+
+ if (!apiParams.max_tokens) apiParams.max_tokens = 1024;
+
+ const response = await this.client.rawFetch("/v1/messages", {
+ method: "POST",
+ headers,
+ body: apiParams,
+ stream: params.stream,
+ });
+
+ if (params.stream) {
+ return parseSSE(response);
+ }
+
+ return response.json();
+ }
+
+ /**
+ * Stream a message with automatic compression.
+ */
+ stream(
+ params: { model: string; messages: any[]; max_tokens?: number; system?: string | any[]; [key: string]: any } & HeadroomParams,
+ ): Promise<AsyncGenerator<any>> {
+ return this.create({ ...params, stream: true }) as Promise<AsyncGenerator<any>>;
+ }
+
+ /**
+ * Simulate compression without calling the LLM.
+ */
+ async simulate(
+ params: { model: string; messages: any[] } & HeadroomParams,
+ ): Promise<SimulationResult> {
+ const body = {
+ messages: params.messages,
+ model: params.model,
+ config: { default_mode: "simulate", generate_diff_artifact: true },
+ };
+ const result = await this.client.compressRaw(body);
+ return deepCamelCase<SimulationResult>(result);
+ }
+}
+
+// --- Main client ---
+
+export interface ExtendedClientOptions extends HeadroomClientOptions {
+ providerApiKey?: string;
+ defaultMode?: HeadroomMode;
+ config?: HeadroomConfig;
+}
+
export class HeadroomClient implements HeadroomClientInterface {
private baseUrl: string;
private apiKey: string | undefined;
private timeout: number;
private fallback: boolean;
private retries: number;
+ private config: HeadroomConfig | undefined;
+
+ /** @internal */ providerApiKey: string | undefined;
+
+ /** OpenAI-style chat completions API. */
+ readonly chat: { completions: ChatCompletions };
+ /** Anthropic-style messages API. */
+ readonly messages: Messages;
- constructor(options: HeadroomClientOptions = {}) {
+ constructor(options: ExtendedClientOptions = {}) {
this.baseUrl = (
options.baseUrl ??
getEnv("HEADROOM_BASE_URL") ??
@@ -53,8 +219,17 @@ export class HeadroomClient implements HeadroomClientInterface {
this.timeout = options.timeout ?? DEFAULT_TIMEOUT;
this.fallback = options.fallback ?? true;
this.retries = options.retries ?? DEFAULT_RETRIES;
+ this.providerApiKey = options.providerApiKey;
+ this.config = options.config;
+
+ this.chat = { completions: new ChatCompletions(this) };
+ this.messages = new Messages(this);
}
+ // ============================================================
+ // Core: compress
+ // ============================================================
+
async compress(
messages: OpenAIMessage[],
options: { model?: string; tokenBudget?: number } = {},
@@ -69,7 +244,6 @@ export class HeadroomClient implements HeadroomClientInterface {
return await this._doCompress(messages, model, options.tokenBudget);
} catch (error) {
lastError = error;
- // Don't retry auth errors or client errors
if (error instanceof HeadroomAuthError) throw error;
if (
error instanceof HeadroomCompressError &&
@@ -77,11 +251,9 @@ export class HeadroomClient implements HeadroomClientInterface {
) {
throw error;
}
- // Retry on transient errors (network, 5xx)
}
}
- // All attempts exhausted
if (this.fallback) {
return makeFallbackResult(messages);
}
@@ -92,30 +264,307 @@ export class HeadroomClient implements HeadroomClientInterface {
);
}
- private async _doCompress(
- messages: OpenAIMessage[],
- model: string,
- tokenBudget?: number,
- ): Promise<CompressResult> {
- const url = `${this.baseUrl}/v1/compress`;
+ /**
+ * Raw compress call — sends body directly to /v1/compress.
+ * Used by simulate() and other advanced features.
+ * @internal
+ */
+ async compressRaw(body: Record<string, any>): Promise<any> {
+ const response = await this._fetch("/v1/compress", {
+ method: "POST",
+ body: JSON.stringify(body),
+ });
+ return response.json();
+ }
+
+ // ============================================================
+ // Health & Stats
+ // ============================================================
+
+ /** Check if the proxy is running and healthy. */
+ async health(): Promise<HealthStatus> {
+ const resp = await this._fetch("/health", { method: "GET" });
+ return deepCamelCase<HealthStatus>(await resp.json());
+ }
+
+ /** Get comprehensive proxy statistics. */
+ async proxyStats(): Promise<ProxyStats> {
+ const resp = await this._fetch("/stats", { method: "GET" });
+ return deepCamelCase<ProxyStats>(await resp.json());
+ }
+
+ /** Get Prometheus-format metrics. */
+ async prometheusMetrics(): Promise<string> {
+ const resp = await this._fetch("/metrics", { method: "GET" });
+ return resp.text();
+ }
+
+ /** Get historical stats. */
+ async statsHistory(query?: StatsHistoryQuery): Promise<any> {
+ const params = new URLSearchParams();
+ if (query?.format) params.set("format", query.format);
+ if (query?.series) params.set("series", query.series);
+ const qs = params.toString();
+ const resp = await this._fetch(`/stats-history${qs ? `?${qs}` : ""}`, { method: "GET" });
+ return resp.json();
+ }
+
+ /** Get proxy memory usage. */
+ async memoryUsage(): Promise<MemoryUsage> {
+ const resp = await this._fetch("/debug/memory", { method: "GET" });
+ return deepCamelCase<MemoryUsage>(await resp.json());
+ }
+
+ /** Clear the response cache. */
+ async clearCache(): Promise<{ status: string }> {
+ const resp = await this._fetch("/cache/clear", { method: "POST" });
+ return resp.json() as Promise<{ status: string }>;
+ }
+
+ // ============================================================
+ // Metrics & Observability
+ // ============================================================
+
+ /** Get request metrics from the proxy. */
+ async getMetrics(query?: MetricsQuery): Promise<RequestMetrics[]> {
+ const resp = await this._fetch("/stats", { method: "GET" });
+ const stats = (await resp.json()) as any;
+ let metrics: any[] = stats.recent_requests ?? [];
+
+ if (query?.model) {
+ metrics = metrics.filter((m: any) => m.model === query.model);
+ }
+ if (query?.mode) {
+ metrics = metrics.filter((m: any) => m.mode === query.mode);
+ }
+ if (query?.limit) {
+ metrics = metrics.slice(0, query.limit);
+ }
+
+ return metrics.map((m: any) => deepCamelCase<RequestMetrics>(m));
+ }
+
+ /** Get aggregated metrics summary. */
+ async getSummary(query?: SummaryQuery): Promise<MetricsSummary> {
+ const resp = await this._fetch("/stats", { method: "GET" });
+ const stats = (await resp.json()) as any;
+ return deepCamelCase<MetricsSummary>({
+ total_requests: stats.requests?.total ?? 0,
+ total_tokens_before: stats.tokens?.total_before_compression ?? 0,
+ total_tokens_after: (stats.tokens?.total_before_compression ?? 0) - (stats.tokens?.saved ?? 0),
+ total_tokens_saved: stats.tokens?.saved ?? 0,
+ average_compression_ratio: stats.tokens?.savings_percent ? stats.tokens.savings_percent / 100 : 0,
+ models: stats.requests?.by_model ?? {},
+ modes: {},
+ error_count: stats.requests?.failed ?? 0,
+ });
+ }
+
+ /** Get in-memory session stats. */
+ async getStats(): Promise<SessionStats> {
+ const resp = await this._fetch("/stats", { method: "GET" });
+ const stats = (await resp.json()) as any;
+ return deepCamelCase<SessionStats>({
+ total_requests: stats.requests?.total ?? 0,
+ total_tokens_before: stats.tokens?.total_before_compression ?? 0,
+ total_tokens_after: (stats.tokens?.total_before_compression ?? 0) - (stats.tokens?.saved ?? 0),
+ total_tokens_saved: stats.tokens?.saved ?? 0,
+ average_compression_ratio: stats.tokens?.savings_percent ? stats.tokens.savings_percent / 100 : 0,
+ cache_hits: stats.requests?.cached ?? 0,
+ by_mode: {},
+ });
+ }
+
+ /** Validate proxy configuration. */
+ async validateSetup(): Promise<ValidationResult> {
+ const resp = await this._fetch("/health", { method: "GET" });
+ const health = (await resp.json()) as any;
+ return {
+ valid: health.status === "healthy",
+ provider: "",
+ errors: health.status !== "healthy" ? ["Proxy unhealthy"] : [],
+ warnings: [],
+ config: health.config ?? {},
+ };
+ }
+
+ // ============================================================
+ // CCR Retrieve
+ // ============================================================
+
+ /** Retrieve original content from the CCR compression store. */
+ async retrieve(
+ hash: string,
+ options?: { query?: string },
+ ): Promise<RetrieveResult | RetrieveSearchResult> {
+ const body: Record<string, any> = { hash };
+ if (options?.query) body.query = options.query;
+ const resp = await this._fetch("/v1/retrieve", {
+ method: "POST",
+ body: JSON.stringify(body),
+ });
+ return deepCamelCase(await resp.json());
+ }
+
+ /** Get CCR store statistics. */
+ async getCCRStats(): Promise<CCRStats> {
+ const resp = await this._fetch("/v1/retrieve/stats", { method: "GET" });
+ return deepCamelCase<CCRStats>(await resp.json());
+ }
+
+ /** Handle an LLM tool call for headroom_retrieve. */
+ async handleToolCall(request: {
+ toolCall: any;
+ provider?: "anthropic" | "openai";
+ }): Promise<any> {
+ const resp = await this._fetch("/v1/retrieve/tool_call", {
+ method: "POST",
+ body: JSON.stringify(deepSnakeCase(request)),
+ });
+ return deepCamelCase(await resp.json());
+ }
+
+ // ============================================================
+ // Telemetry & Feedback
+ // ============================================================
+
+ readonly telemetry = {
+ getStats: async (): Promise<TelemetryStats> => {
+ const resp = await this._fetch("/v1/telemetry", { method: "GET" });
+ return deepCamelCase<TelemetryStats>(await resp.json());
+ },
+ export: async (): Promise<any> => {
+ const resp = await this._fetch("/v1/telemetry/export", { method: "GET" });
+ return resp.json();
+ },
+ import: async (data: any): Promise<{ status: string }> => {
+ const resp = await this._fetch("/v1/telemetry/import", {
+ method: "POST",
+ body: JSON.stringify(data),
+ });
+ return resp.json() as Promise<{ status: string }>;
+ },
+ getTools: async (): Promise<any> => {
+ const resp = await this._fetch("/v1/telemetry/tools", { method: "GET" });
+ return deepCamelCase(await resp.json());
+ },
+ getTool: async (signatureHash: string): Promise<any> => {
+ const resp = await this._fetch(`/v1/telemetry/tools/${signatureHash}`, { method: "GET" });
+ return deepCamelCase(await resp.json());
+ },
+ };
+
+ readonly feedback = {
+ getStats: async (): Promise<any> => {
+ const resp = await this._fetch("/v1/feedback", { method: "GET" });
+ return deepCamelCase(await resp.json());
+ },
+ getHints: async (toolName: string): Promise<ToolHints> => {
+ const resp = await this._fetch(`/v1/feedback/${encodeURIComponent(toolName)}`, { method: "GET" });
+ return deepCamelCase<ToolHints>(await resp.json());
+ },
+ };
+
+ readonly toin = {
+ getStats: async (): Promise<TOINStats> => {
+ const resp = await this._fetch("/v1/toin/stats", { method: "GET" });
+ return deepCamelCase<TOINStats>(await resp.json());
+ },
+ getPatterns: async (limit?: number): Promise<TOINPattern[]> => {
+ const qs = limit ? `?limit=${limit}` : "";
+ const resp = await this._fetch(`/v1/toin/patterns${qs}`, { method: "GET" });
+ return deepCamelCase<TOINPattern[]>(await resp.json());
+ },
+ getPattern: async (hashPrefix: string): Promise<any> => {
+ const resp = await this._fetch(`/v1/toin/pattern/${encodeURIComponent(hashPrefix)}`, { method: "GET" });
+ return deepCamelCase(await resp.json());
+ },
+ };
+
+ // ============================================================
+ // Lifecycle
+ // ============================================================
+
+ /** Close the client (no-op for HTTP client, included for API parity). */
+ close(): void {
+ // HTTP client is stateless — nothing to close
+ }
+
+ // ============================================================
+ // Internal HTTP helpers
+ // ============================================================
+
+ /**
+ * Raw fetch with proxy base URL, auth, and timeout.
+ * @internal
+ */
+ async rawFetch(
+ path: string,
+ options: { method: string; headers?: Record<string, string>; body?: any; stream?: boolean },
+ ): Promise<Response> {
+ const url = `${this.baseUrl}${path}`;
const headers: Record<string, string> = {
"Content-Type": "application/json",
+ ...options.headers,
};
if (this.apiKey) {
- headers["Authorization"] = `Bearer ${this.apiKey}`;
+ // Don't override provider auth headers
+ if (!headers["Authorization"] && !headers["x-api-key"]) {
+ headers["Authorization"] = `Bearer ${this.apiKey}`;
+ }
}
- const body: Record<string, unknown> = { messages, model };
- if (tokenBudget) {
- body.token_budget = tokenBudget;
+ let response: Response;
+ try {
+ response = await fetch(url, {
+ method: options.method,
+ headers,
+ body: options.body ? JSON.stringify(options.body) : undefined,
+ 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
+ }
+ throw mapProxyError(
+ response.status,
+ errorBody?.error?.type ?? "unknown",
+ errorBody?.error?.message ?? `HTTP ${response.status}`,
+ );
+ }
+
+ return response;
+ }
+
+ /** @internal */
+ private async _fetch(
+ path: string,
+ init: { method: string; body?: string; headers?: Record<string, string> },
+ ): Promise<Response> {
+ const url = `${this.baseUrl}${path}`;
+ const headers: Record<string, string> = {
+ "Content-Type": "application/json",
+ ...init.headers,
+ };
+ if (this.apiKey) {
+ headers["Authorization"] = `Bearer ${this.apiKey}`;
}
let response: Response;
try {
response = await fetch(url, {
- method: "POST",
+ method: init.method,
headers,
- body: JSON.stringify(body),
+ body: init.body,
signal: AbortSignal.timeout(this.timeout),
});
} catch (error) {
@@ -129,17 +578,35 @@ export class HeadroomClient implements HeadroomClientInterface {
try {
errorBody = (await response.json()) as ProxyErrorResponse;
} catch {
- // ignore parse errors on error responses
+ // ignore
}
- const errorType = errorBody?.error?.type ?? "unknown";
- const errorMessage =
- errorBody?.error?.message ?? `HTTP ${response.status}`;
+ throw mapProxyError(
+ response.status,
+ errorBody?.error?.type ?? "unknown",
+ errorBody?.error?.message ?? `HTTP ${response.status}`,
+ );
+ }
- if (response.status === 401) {
- throw new HeadroomAuthError(errorMessage);
- }
- throw new HeadroomCompressError(response.status, errorType, errorMessage);
+ return response;
+ }
+
+ private async _doCompress(
+ messages: OpenAIMessage[],
+ model: string,
+ tokenBudget?: number,
+ ): Promise<CompressResult> {
+ const body: Record<string, unknown> = { messages, model };
+ if (tokenBudget) {
+ body.token_budget = tokenBudget;
}
+ if (this.config) {
+ body.config = deepSnakeCase(this.config);
+ }
+
+ const response = await this._fetch("/v1/compress", {
+ method: "POST",
+ body: JSON.stringify(body),
+ });
const data = (await response.json()) as ProxyCompressResponse;
diff --git a/sdk/typescript/src/compress.ts b/sdk/typescript/src/compress.ts
index 1ff93b4e3..935cb9e26 100644
--- a/sdk/typescript/src/compress.ts
+++ b/sdk/typescript/src/compress.ts
@@ -1,51 +1,87 @@
+/**
+ * Universal compress function with hooks support.
+ * Accepts messages in any format: OpenAI, Anthropic, Vercel AI SDK, or Google Gemini.
+ */
+
import { HeadroomClient } from "./client.js";
-import type {
- CompressResult,
- CompressOptions,
-} from "./types.js";
+import type { CompressResult, CompressOptions } from "./types.js";
import { detectFormat, toOpenAI, fromOpenAI } from "./utils/format.js";
+import type { CompressionHooks, CompressContext, CompressEvent } from "./hooks.js";
+import { extractUserQuery, countTurns, extractToolCalls } from "./hooks.js";
/**
- * Compress an array of messages using the Headroom proxy or cloud.
+ * Compress an array of messages using the Headroom proxy.
*
* Accepts messages in any format: OpenAI, Anthropic, Vercel AI SDK, or Google Gemini.
* Detects the format automatically, compresses via the proxy, and returns
* compressed messages in the same format as the input.
- *
- * @example
- * ```typescript
- * import { compress } from 'headroom-ai';
- *
- * // Works with any message format:
- * const result = await compress(openaiMessages, { model: 'gpt-4o' });
- * const result = await compress(anthropicMessages, { model: 'claude-sonnet-4-5-20250929' });
- * const result = await compress(vercelMessages, { model: 'gpt-4o' });
- * const result = await compress(geminiContents, { model: 'gemini-2.0-flash' });
- *
- * // result.messages is in the same format as input
- * ```
*/
export async function compress(
messages: any[],
options: CompressOptions = {},
): Promise<CompressResult> {
- const { client: providedClient, model, tokenBudget, ...clientOptions } = options;
+ const {
+ client: providedClient,
+ model,
+ tokenBudget,
+ hooks,
+ ...clientOptions
+ } = options;
- // Detect input format
- const inputFormat = detectFormat(messages);
+ // Build hook context
+ const ctx: CompressContext = {
+ model: model ?? "gpt-4o",
+ userQuery: extractUserQuery(messages),
+ turnNumber: countTurns(messages),
+ toolCalls: extractToolCalls(messages),
+ provider: "",
+ };
+
+ // 1. Pre-compress hook
+ let processedMessages = messages;
+ if (hooks) {
+ processedMessages = await hooks.preCompress(messages, ctx);
+ }
+
+ // 2. Detect input format
+ const inputFormat = detectFormat(processedMessages);
- // Convert to OpenAI format (the proxy's lingua franca)
- const openaiMessages = toOpenAI(messages);
+ // 3. Convert to OpenAI format (the proxy's lingua franca)
+ const openaiMessages = toOpenAI(processedMessages);
- // Compress via proxy
+ // 4. Compute biases
+ let biases: Record<number, number> = {};
+ if (hooks) {
+ biases = await hooks.computeBiases(openaiMessages, ctx);
+ }
+
+ // 5. Compress via proxy
const client = providedClient ?? new HeadroomClient(clientOptions);
const result = await client.compress(openaiMessages, { model, tokenBudget });
- // Convert compressed messages back to original format
+ // 6. Convert compressed messages back to original format
const outputMessages = fromOpenAI(result.messages, inputFormat);
- return {
+ const finalResult: CompressResult = {
...result,
messages: outputMessages,
};
+
+ // 7. Post-compress hook
+ if (hooks) {
+ const event: CompressEvent = {
+ tokensBefore: result.tokensBefore,
+ tokensAfter: result.tokensAfter,
+ tokensSaved: result.tokensSaved,
+ compressionRatio: result.compressionRatio,
+ transformsApplied: result.transformsApplied,
+ ccrHashes: result.ccrHashes,
+ model: ctx.model,
+ userQuery: ctx.userQuery,
+ provider: ctx.provider,
+ };
+ await hooks.postCompress(event);
+ }
+
+ return finalResult;
}
diff --git a/sdk/typescript/src/errors.ts b/sdk/typescript/src/errors.ts
new file mode 100644
index 000000000..1231dd69b
--- /dev/null
+++ b/sdk/typescript/src/errors.ts
@@ -0,0 +1,114 @@
+/**
+ * Error hierarchy matching Python headroom.exceptions.
+ */
+
+export class HeadroomError extends Error {
+ details?: Record<string, any>;
+
+ constructor(message: string, details?: Record<string, any>) {
+ super(message);
+ this.name = "HeadroomError";
+ this.details = details;
+ }
+}
+
+export class HeadroomConnectionError extends HeadroomError {
+ constructor(message: string, details?: Record<string, any>) {
+ super(message, details);
+ this.name = "HeadroomConnectionError";
+ }
+}
+
+export class HeadroomAuthError extends HeadroomError {
+ constructor(message: string, details?: Record<string, any>) {
+ super(message, details);
+ this.name = "HeadroomAuthError";
+ }
+}
+
+export class HeadroomCompressError extends HeadroomError {
+ statusCode: number;
+ errorType: string;
+
+ constructor(statusCode: number, errorType: string, message: string, details?: Record<string, any>) {
+ super(message, details);
+ this.name = "HeadroomCompressError";
+ this.statusCode = statusCode;
+ this.errorType = errorType;
+ }
+}
+
+export class ConfigurationError extends HeadroomError {
+ constructor(message: string, details?: Record<string, any>) {
+ super(message, details);
+ this.name = "ConfigurationError";
+ }
+}
+
+export class ProviderError extends HeadroomError {
+ constructor(message: string, details?: Record<string, any>) {
+ super(message, details);
+ this.name = "ProviderError";
+ }
+}
+
+export class StorageError extends HeadroomError {
+ constructor(message: string, details?: Record<string, any>) {
+ super(message, details);
+ this.name = "StorageError";
+ }
+}
+
+export class TokenizationError extends HeadroomError {
+ constructor(message: string, details?: Record<string, any>) {
+ super(message, details);
+ this.name = "TokenizationError";
+ }
+}
+
+export class CacheError extends HeadroomError {
+ constructor(message: string, details?: Record<string, any>) {
+ super(message, details);
+ this.name = "CacheError";
+ }
+}
+
+export class ValidationError extends HeadroomError {
+ constructor(message: string, details?: Record<string, any>) {
+ super(message, details);
+ this.name = "ValidationError";
+ }
+}
+
+export class TransformError extends HeadroomError {
+ constructor(message: string, details?: Record<string, any>) {
+ super(message, details);
+ this.name = "TransformError";
+ }
+}
+
+// --- Proxy error mapping ---
+
+const ERROR_TYPE_MAP: Record<string, new (message: string, details?: Record<string, any>) => HeadroomError> = {
+ configuration_error: ConfigurationError,
+ provider_error: ProviderError,
+ storage_error: StorageError,
+ tokenization_error: TokenizationError,
+ cache_error: CacheError,
+ validation_error: ValidationError,
+ transform_error: TransformError,
+};
+
+/**
+ * Map a proxy error response to the correct HeadroomError subclass.
+ */
+export function mapProxyError(
+ status: number,
+ type: string,
+ message: string,
+): HeadroomError {
+ if (status === 401) return new HeadroomAuthError(message);
+ const ErrorClass = ERROR_TYPE_MAP[type];
+ if (ErrorClass) return new ErrorClass(message, { statusCode: status, errorType: type });
+ return new HeadroomCompressError(status, type, message);
+}
diff --git a/sdk/typescript/src/hooks.ts b/sdk/typescript/src/hooks.ts
new file mode 100644
index 000000000..cdcca3465
--- /dev/null
+++ b/sdk/typescript/src/hooks.ts
@@ -0,0 +1,113 @@
+/**
+ * Compression hooks matching Python headroom.hooks.
+ * Allows customizing compression behavior with pre/post hooks.
+ */
+
+export interface CompressContext {
+ model: string;
+ userQuery: string;
+ turnNumber: number;
+ toolCalls: string[];
+ provider: string;
+}
+
+export interface CompressEvent {
+ tokensBefore: number;
+ tokensAfter: number;
+ tokensSaved: number;
+ compressionRatio: number;
+ transformsApplied: string[];
+ ccrHashes: string[];
+ model: string;
+ userQuery: string;
+ provider: string;
+}
+
+/**
+ * Base class for compression hooks. Override methods to customize behavior.
+ *
+ * @example
+ * ```typescript
+ * class LoggingHooks extends CompressionHooks {
+ * postCompress(event: CompressEvent) {
+ * console.log(`Saved ${event.tokensSaved} tokens (${event.compressionRatio})`);
+ * }
+ * }
+ * ```
+ */
+export class CompressionHooks {
+ /**
+ * Called before compression. Modify messages before they're sent to the proxy.
+ */
+ preCompress(
+ messages: any[],
+ _ctx: CompressContext,
+ ): any[] | Promise<any[]> {
+ return messages;
+ }
+
+ /**
+ * Compute per-message compression biases.
+ * Return a map of message index -> bias (>1 = preserve more, <1 = compress more).
+ */
+ computeBiases(
+ _messages: any[],
+ _ctx: CompressContext,
+ ): Record<number, number> | Promise<Record<number, number>> {
+ return {};
+ }
+
+ /**
+ * Called after compression. Observe-only — cannot modify the result.
+ */
+ postCompress(_event: CompressEvent): void | Promise<void> {
+ // no-op default
+ }
+}
+
+/**
+ * Extract the last user message text from a messages array (any format).
+ */
+export function extractUserQuery(messages: any[]): string {
+ for (let i = messages.length - 1; i >= 0; i--) {
+ const msg = messages[i];
+ if (msg.role === "user") {
+ if (typeof msg.content === "string") return msg.content;
+ if (Array.isArray(msg.content)) {
+ const textPart = msg.content.find(
+ (p: any) => p.type === "text" || p.text,
+ );
+ if (textPart) return textPart.text ?? textPart.content ?? "";
+ }
+ }
+ }
+ return "";
+}
+
+/**
+ * Count conversation turns (user+assistant pairs).
+ */
+export function countTurns(messages: any[]): number {
+ return messages.filter((m) => m.role === "user").length;
+}
+
+/**
+ * Extract tool call names from messages.
+ */
+export function extractToolCalls(messages: any[]): string[] {
+ const names: string[] = [];
+ for (const msg of messages) {
+ if (msg.tool_calls) {
+ for (const tc of msg.tool_calls) {
+ names.push(tc.function?.name ?? tc.name ?? "unknown");
+ }
+ }
+ if (Array.isArray(msg.content)) {
+ for (const part of msg.content) {
+ if (part.type === "tool_use") names.push(part.name ?? "unknown");
+ if (part.type === "tool-call") names.push(part.toolName ?? "unknown");
+ }
+ }
+ }
+ return names;
+}
diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.ts
index 3f50d90ef..43123dc76 100644
--- a/sdk/typescript/src/index.ts
+++ b/sdk/typescript/src/index.ts
@@ -1,8 +1,21 @@
+// --- Core ---
export { compress } from "./compress.js";
export { HeadroomClient } from "./client.js";
+export type { ExtendedClientOptions, HeadroomParams } from "./client.js";
+export { simulate } from "./simulate.js";
+export type { SimulateOptions } from "./simulate.js";
+
+// --- Format utilities ---
export { detectFormat, toOpenAI, fromOpenAI } from "./utils/format.js";
export type { MessageFormat } from "./utils/format.js";
+// --- Case conversion utilities ---
+export { deepCamelCase, deepSnakeCase, snakeToCamel, camelToSnake } from "./utils/case.js";
+
+// --- Streaming utilities ---
+export { parseSSE, collectStream } from "./utils/stream.js";
+
+// --- Core types ---
export type {
TextContentPart,
ImageContentPart,
@@ -19,9 +32,79 @@ export type {
HeadroomClientInterface,
} from "./types.js";
+// --- Errors (full hierarchy) ---
export {
HeadroomError,
HeadroomConnectionError,
HeadroomAuthError,
HeadroomCompressError,
-} from "./types.js";
+ ConfigurationError,
+ ProviderError,
+ StorageError,
+ TokenizationError,
+ CacheError,
+ ValidationError,
+ TransformError,
+ mapProxyError,
+} from "./errors.js";
+
+// --- Config types ---
+export type {
+ HeadroomMode,
+ RelevanceTier,
+ ContentType,
+ BlockKind,
+ ToolCrusherConfig,
+ CacheAlignerConfig,
+ RollingWindowConfig,
+ ScoringWeights,
+ IntelligentContextConfig,
+ RelevanceScorerConfig,
+ AnchorConfig,
+ SmartCrusherConfig,
+ CacheOptimizerConfig,
+ CCRConfig,
+ PrefixFreezeConfig,
+ ReadLifecycleConfig,
+ CompressionProfile,
+ HeadroomConfig,
+} from "./types/config.js";
+
+// --- Data models ---
+export type {
+ WasteSignals,
+ CachePrefixMetrics,
+ TransformDiff,
+ DiffArtifact,
+ SimulationResult,
+ RequestMetrics,
+ Block,
+ SessionStats,
+ ValidationResult,
+ MetricsSummary,
+ HealthStatus,
+ ProxyStats,
+ MemoryUsage,
+ RetrieveResult,
+ RetrieveSearchResult,
+ CCRStats,
+ TelemetryStats,
+ ToolHints,
+ TOINStats,
+ TOINPattern,
+ MetricsQuery,
+ SummaryQuery,
+ StatsHistoryQuery,
+} from "./types/models.js";
+
+// --- Hooks ---
+export { CompressionHooks, extractUserQuery, countTurns, extractToolCalls } from "./hooks.js";
+export type { CompressContext, CompressEvent } from "./hooks.js";
+
+// --- SharedContext ---
+export { SharedContext } from "./shared-context.js";
+export type {
+ ContextEntry,
+ SharedContextStats,
+ SharedContextOptions,
+} from "./shared-context.js";
diff --git a/sdk/typescript/src/shared-context.ts b/sdk/typescript/src/shared-context.ts
new file mode 100644
index 000000000..c876d7f4a
--- /dev/null
+++ b/sdk/typescript/src/shared-context.ts
@@ -0,0 +1,188 @@
+/**
+ * SharedContext — compressed inter-agent context sharing.
+ * Matches Python headroom.shared_context.SharedContext.
+ */
+
+import { HeadroomClient } from "./client.js";
+import type { HeadroomClientOptions, CompressResult } from "./types.js";
+
+export interface ContextEntry {
+ key: string;
+ original: string;
+ compressed: string;
+ originalTokens: number;
+ compressedTokens: number;
+ agent: string | null;
+ timestamp: number;
+ transforms: string[];
+ savingsPercent: number;
+}
+
+export interface SharedContextStats {
+ entries: number;
+ totalOriginalTokens: number;
+ totalCompressedTokens: number;
+ totalTokensSaved: number;
+ savingsPercent: number;
+}
+
+export interface SharedContextOptions extends HeadroomClientOptions {
+ model?: string;
+ ttl?: number;
+ maxEntries?: number;
+}
+
+export class SharedContext {
+ private entries = new Map<string, ContextEntry>();
+ private client: HeadroomClient;
+ private model: string;
+ private ttl: number;
+ private maxEntries: number;
+
+ constructor(options: SharedContextOptions = {}) {
+ const { model, ttl, maxEntries, ...clientOptions } = options;
+ this.client = new HeadroomClient(clientOptions);
+ this.model = model ?? "claude-sonnet-4-5-20250929";
+ this.ttl = ttl ?? 3600;
+ this.maxEntries = maxEntries ?? 100;
+ }
+
+ /**
+ * Store content with compression.
+ */
+ async put(
+ key: string,
+ content: string,
+ options?: { agent?: string },
+ ): Promise<ContextEntry> {
+ this.evictExpired();
+ this.evictIfFull();
+
+ const messages = [{ role: "user" as const, content }];
+ let result: CompressResult;
+ try {
+ result = await this.client.compress(messages, { model: this.model });
+ } catch {
+ // If proxy unavailable, store uncompressed
+ result = {
+ messages,
+ tokensBefore: content.length / 4, // rough estimate
+ tokensAfter: content.length / 4,
+ tokensSaved: 0,
+ compressionRatio: 1.0,
+ transformsApplied: [],
+ ccrHashes: [],
+ compressed: false,
+ };
+ }
+
+ const compressed = result.compressed
+ ? typeof result.messages[0]?.content === "string"
+ ? result.messages[0].content
+ : JSON.stringify(result.messages[0]?.content ?? content)
+ : content;
+
+ const entry: ContextEntry = {
+ key,
+ original: content,
+ compressed,
+ originalTokens: result.tokensBefore,
+ compressedTokens: result.tokensAfter,
+ agent: options?.agent ?? null,
+ timestamp: Date.now() / 1000,
+ transforms: result.transformsApplied,
+ savingsPercent:
+ result.tokensBefore > 0
+ ? ((result.tokensBefore - result.tokensAfter) / result.tokensBefore) *
+ 100
+ : 0,
+ };
+
+ this.entries.set(key, entry);
+ return entry;
+ }
+
+ /**
+ * Get content by key. Returns compressed by default, full original if full=true.
+ */
+ get(key: string, options?: { full?: boolean }): string | null {
+ const entry = this.entries.get(key);
+ if (!entry) return null;
+
+ if (Date.now() / 1000 - entry.timestamp > this.ttl) {
+ this.entries.delete(key);
+ return null;
+ }
+
+ return options?.full ? entry.original : entry.compressed;
+ }
+
+ /**
+ * Get full entry metadata.
+ */
+ getEntry(key: string): ContextEntry | null {
+ const entry = this.entries.get(key);
+ if (!entry) return null;
+
+ if (Date.now() / 1000 - entry.timestamp > this.ttl) {
+ this.entries.delete(key);
+ return null;
+ }
+
+ return entry;
+ }
+
+ /**
+ * List all stored keys (excluding expired).
+ */
+ keys(): string[] {
+ this.evictExpired();
+ return Array.from(this.entries.keys());
+ }
+
+ /**
+ * Get aggregated statistics.
+ */
+ stats(): SharedContextStats {
+ this.evictExpired();
+ let totalOriginal = 0;
+ let totalCompressed = 0;
+
+ for (const entry of this.entries.values()) {
+ totalOriginal += entry.originalTokens;
+ totalCompressed += entry.compressedTokens;
+ }
+
+ const saved = totalOriginal - totalCompressed;
+ return {
+ entries: this.entries.size,
+ totalOriginalTokens: totalOriginal,
+ totalCompressedTokens: totalCompressed,
+ totalTokensSaved: saved,
+ savingsPercent: totalOriginal > 0 ? (saved / totalOriginal) * 100 : 0,
+ };
+ }
+
+ /**
+ * Clear all entries.
+ */
+ clear(): void {
+ this.entries.clear();
+ }
+
+ private evictExpired(): void {
+ const now = Date.now() / 1000;
+ for (const [key, entry] of this.entries) {
+ if (now - entry.timestamp > this.ttl) {
+ this.entries.delete(key);
+ }
+ }
+ }
+
+ private evictIfFull(): void {
+ while (this.entries.size >= this.maxEntries) {
+ const oldest = this.entries.keys().next().value;
+ if (oldest !== undefined) this.entries.delete(oldest);
+ }
+ }
+}
diff --git a/sdk/typescript/src/simulate.ts b/sdk/typescript/src/simulate.ts
new file mode 100644
index 000000000..97beefecd
--- /dev/null
+++ b/sdk/typescript/src/simulate.ts
@@ -0,0 +1,52 @@
+/**
+ * Simulation API — dry-run compression to see what would happen.
+ * Matches Python client.simulate() behavior.
+ */
+
+import { HeadroomClient } from "./client.js";
+import type { HeadroomClientOptions } from "./types.js";
+import type { SimulationResult } from "./types/models.js";
+import type { HeadroomConfig } from "./types/config.js";
+import { deepCamelCase, deepSnakeCase } from "./utils/case.js";
+import { detectFormat, toOpenAI } from "./utils/format.js";
+
+export interface SimulateOptions extends HeadroomClientOptions {
+ model?: string;
+ config?: HeadroomConfig;
+ client?: HeadroomClient;
+}
+
+/**
+ * Simulate compression without calling the LLM.
+ * Shows what compression would do: token savings, transforms, waste signals.
+ *
+ * @example
+ * ```typescript
+ * const sim = await simulate(messages, { model: 'gpt-4o' });
+ * console.log(`Would save ${sim.tokensSaved} tokens (${sim.estimatedSavings})`);
+ * console.log('Transforms:', sim.transforms);
+ * ```
+ */
+export async function simulate(
+ messages: any[],
+ options: SimulateOptions = {},
+): Promise<SimulationResult> {
+ const { client: providedClient, model, config, ...clientOptions } = options;
+
+ const openaiMessages = toOpenAI(messages);
+ const client = providedClient ?? new HeadroomClient(clientOptions);
+
+ const body: Record<string, any> = {
+ messages: openaiMessages,
+ model: model ?? "gpt-4o",
+ config: {
+ default_mode: "simulate",
+ generate_diff_artifact: true,
+ ...(config ? deepSnakeCase(config) : {}),
+ },
+ };
+
+ // Use the client's internal fetch to hit /v1/compress with simulation config
+ const result = await client.compressRaw(body);
+ return deepCamelCase<SimulationResult>(result);
+}
diff --git a/sdk/typescript/src/types.ts b/sdk/typescript/src/types.ts
index 747844476..b9c052671 100644
--- a/sdk/typescript/src/types.ts
+++ b/sdk/typescript/src/types.ts
@@ -1,3 +1,10 @@
+/**
+ * Core types for the Headroom TypeScript SDK.
+ * Error classes moved to errors.ts — re-exported here for backwards compatibility.
+ */
+
+import type { CompressionHooks } from "./hooks.js";
+
// --- Message types (OpenAI chat format) ---
export interface TextContentPart {
@@ -58,6 +65,8 @@ export interface CompressOptions {
client?: HeadroomClientInterface;
/** Token budget — compress to fit within this limit. Used for compaction. */
tokenBudget?: number;
+ /** Compression hooks for pre/post processing. */
+ hooks?: CompressionHooks;
}
export interface CompressResult {
@@ -89,40 +98,22 @@ export interface HeadroomClientInterface {
): 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;
- }
-}
+// --- Re-export errors for backwards compatibility ---
+
+export {
+ HeadroomError,
+ HeadroomConnectionError,
+ HeadroomAuthError,
+ HeadroomCompressError,
+ ConfigurationError,
+ ProviderError,
+ StorageError,
+ TokenizationError,
+ CacheError,
+ ValidationError,
+ TransformError,
+ mapProxyError,
+} from "./errors.js";
// --- Proxy response (internal) ---
diff --git a/sdk/typescript/src/types/config.ts b/sdk/typescript/src/types/config.ts
new file mode 100644
index 000000000..bd596d419
--- /dev/null
+++ b/sdk/typescript/src/types/config.ts
@@ -0,0 +1,183 @@
+/**
+ * Configuration types matching Python headroom.config dataclasses.
+ * All fields are optional — the proxy uses defaults for omitted values.
+ */
+
+// --- Enums ---
+
+export type HeadroomMode = "audit" | "optimize" | "simulate";
+
+export type RelevanceTier = "bm25" | "embedding" | "hybrid";
+
+export type ContentType =
+ | "json"
+ | "code"
+ | "logs"
+ | "text"
+ | "html"
+ | "diff"
+ | "search"
+ | "unknown";
+
+export type BlockKind =
+ | "system"
+ | "user"
+ | "assistant"
+ | "tool_call"
+ | "tool_result"
+ | "rag"
+ | "unknown";
+
+// --- Config interfaces ---
+
+export interface ToolCrusherConfig {
+ enabled?: boolean;
+ minTokensToCrush?: number;
+ maxArrayItems?: number;
+ maxStringLength?: number;
+ maxDepth?: number;
+ preserveKeys?: string[];
+ toolProfiles?: Record<string, Record<string, any>>;
+}
+
+export interface CacheAlignerConfig {
+ enabled?: boolean;
+ useDynamicDetector?: boolean;
+ detectionTiers?: ("regex" | "ner" | "semantic")[];
+ extraDynamicLabels?: string[];
+ entropyThreshold?: number;
+ datePatterns?: string[];
+ normalizeWhitespace?: boolean;
+ collapseBlankLines?: boolean;
+ dynamicTailSeparator?: string;
+}
+
+export interface RollingWindowConfig {
+ enabled?: boolean;
+ keepSystem?: boolean;
+ keepLastTurns?: number;
+ outputBufferTokens?: number;
+}
+
+export interface ScoringWeights {
+ recency?: number;
+ semanticSimilarity?: number;
+ toinImportance?: number;
+ errorIndicator?: number;
+ forwardReference?: number;
+ tokenDensity?: number;
+}
+
+export interface IntelligentContextConfig {
+ enabled?: boolean;
+ keepSystem?: boolean;
+ keepLastTurns?: number;
+ outputBufferTokens?: number;
+ useImportanceScoring?: boolean;
+ scoringWeights?: ScoringWeights;
+ recencyDecayRate?: number;
+ toinIntegration?: boolean;
+ toinConfidenceThreshold?: number;
+ compressThreshold?: number;
+ summarizationEnabled?: boolean;
+ summarizationModel?: string | null;
+ summaryMaxTokens?: number;
+ summarizeThreshold?: number;
+}
+
+export interface RelevanceScorerConfig {
+ tier?: RelevanceTier;
+ bm25K1?: number;
+ bm25B?: number;
+ embeddingModel?: string;
+ hybridAlpha?: number;
+ adaptiveAlpha?: boolean;
+ relevanceThreshold?: number;
+}
+
+export interface AnchorConfig {
+ anchorBudgetPct?: number;
+ minAnchorSlots?: number;
+ maxAnchorSlots?: number;
+ defaultFrontWeight?: number;
+ defaultBackWeight?: number;
+ defaultMiddleWeight?: number;
+ useInformationDensity?: boolean;
+ dedupIdenticalItems?: boolean;
+}
+
+export interface SmartCrusherConfig {
+ enabled?: boolean;
+ minItemsToAnalyze?: number;
+ minTokensToCrush?: number;
+ varianceThreshold?: number;
+ uniquenessThreshold?: number;
+ similarityThreshold?: number;
+ maxItemsAfterCrush?: number;
+ preserveChangePoints?: boolean;
+ useFeedbackHints?: boolean;
+ toinConfidenceThreshold?: number;
+ relevance?: RelevanceScorerConfig;
+ anchor?: AnchorConfig;
+ dedupIdenticalItems?: boolean;
+ firstFraction?: number;
+ lastFraction?: number;
+}
+
+export interface CacheOptimizerConfig {
+ enabled?: boolean;
+ autoDetectProvider?: boolean;
+ minCacheableTokens?: number;
+ enableSemanticCache?: boolean;
+ semanticCacheSimilarity?: number;
+ semanticCacheMaxEntries?: number;
+ semanticCacheTtlSeconds?: number;
+}
+
+export interface CCRConfig {
+ enabled?: boolean;
+ storeMaxEntries?: number;
+ storeTtlSeconds?: number;
+ injectRetrievalMarker?: boolean;
+ feedbackEnabled?: boolean;
+ minItemsToCache?: number;
+ injectTool?: boolean;
+ injectSystemInstructions?: boolean;
+ markerTemplate?: string;
+}
+
+export interface PrefixFreezeConfig {
+ enabled?: boolean;
+ minCachedTokens?: number;
+ sessionTtlSeconds?: number;
+ forceCompressThreshold?: number;
+}
+
+export interface ReadLifecycleConfig {
+ enabled?: boolean;
+ compressStale?: boolean;
+ compressSuperseded?: boolean;
+ minSizeBytes?: number;
+}
+
+export interface CompressionProfile {
+ bias?: number;
+ minK?: number;
+ maxK?: number | null;
+}
+
+export interface HeadroomConfig {
+ storeUrl?: string;
+ defaultMode?: HeadroomMode;
+ modelContextLimits?: Record<string, number>;
+ toolCrusher?: ToolCrusherConfig;
+ smartCrusher?: SmartCrusherConfig;
+ cacheAligner?: CacheAlignerConfig;
+ rollingWindow?: RollingWindowConfig;
+ cacheOptimizer?: CacheOptimizerConfig;
+ ccr?: CCRConfig;
+ prefixFreeze?: PrefixFreezeConfig;
+ contentRouterEnabled?: boolean;
+ intelligentContext?: IntelligentContextConfig;
+ generateDiffArtifact?: boolean;
+}
diff --git a/sdk/typescript/src/types/models.ts b/sdk/typescript/src/types/models.ts
new file mode 100644
index 000000000..58096733c
--- /dev/null
+++ b/sdk/typescript/src/types/models.ts
@@ -0,0 +1,314 @@
+/**
+ * Data models matching Python headroom.config result/metrics dataclasses.
+ */
+
+import type { BlockKind } from "./config.js";
+
+// --- Waste Signals ---
+
+export interface WasteSignals {
+ jsonBloatTokens: number;
+ htmlNoiseTokens: number;
+ base64Tokens: number;
+ whitespaceTokens: number;
+ dynamicDateTokens: number;
+ repetitionTokens: number;
+ total: number;
+}
+
+// --- Cache Prefix Metrics ---
+
+export interface CachePrefixMetrics {
+ stablePrefixBytes: number;
+ stablePrefixTokensEst: number;
+ stablePrefixHash: string;
+ prefixChanged: boolean;
+ previousHash?: string | null;
+}
+
+// --- Transform Diff ---
+
+export interface TransformDiff {
+ transformName: string;
+ tokensBefore: number;
+ tokensAfter: number;
+ tokensSaved: number;
+ itemsRemoved: number;
+ itemsKept: number;
+ details: string;
+ durationMs: number;
+}
+
+// --- Diff Artifact ---
+
+export interface DiffArtifact {
+ requestId: string;
+ originalTokens: number;
+ optimizedTokens: number;
+ totalTokensSaved: number;
+ transforms: TransformDiff[];
+}
+
+// --- Simulation Result ---
+
+export interface SimulationResult {
+ tokensBefore: number;
+ tokensAfter: number;
+ tokensSaved: number;
+ transforms: string[];
+ estimatedSavings: string;
+ messagesOptimized: any[];
+ blockBreakdown: Record<string, number>;
+ wasteSignals: Record<string, number>;
+ stablePrefixHash: string;
+ cacheAlignmentScore: number;
+}
+
+// --- Request Metrics ---
+
+export interface RequestMetrics {
+ requestId: string;
+ timestamp: string;
+ model: string;
+ stream: boolean;
+ mode: string;
+ tokensInputBefore: number;
+ tokensInputAfter: number;
+ tokensOutput?: number | null;
+ blockBreakdown: Record<string, number>;
+ wasteSignals: Record<string, number>;
+ stablePrefixHash: string;
+ cacheAlignmentScore: number;
+ cachedTokens?: number | null;
+ cacheOptimizerUsed?: string | null;
+ cacheOptimizerStrategy?: string | null;
+ cacheableTokens: number;
+ breakpointsInserted: number;
+ estimatedCacheHit: boolean;
+ estimatedSavingsPercent: number;
+ semanticCacheHit: boolean;
+ transformsApplied: string[];
+ toolUnitsDropped: number;
+ turnsDropped: number;
+ messagesHash: string;
+ error?: string | null;
+}
+
+// --- Block ---
+
+export interface Block {
+ kind: BlockKind;
+ text: string;
+ tokensEst: number;
+ contentHash: string;
+ sourceIndex: number;
+ flags: Record<string, any>;
+}
+
+// --- Session Stats ---
+
+export interface SessionStats {
+ totalRequests: number;
+ totalTokensBefore: number;
+ totalTokensAfter: number;
+ totalTokensSaved: number;
+ averageCompressionRatio: number;
+ cacheHits: number;
+ byMode: Record<string, { requests: number; tokensSaved: number }>;
+}
+
+// --- Validation Result ---
+
+export interface ValidationResult {
+ valid: boolean;
+ provider: string;
+ errors: string[];
+ warnings: string[];
+ config: Record<string, any>;
+}
+
+// --- Summary ---
+
+export interface MetricsSummary {
+ totalRequests: number;
+ totalTokensBefore: number;
+ totalTokensAfter: number;
+ totalTokensSaved: number;
+ averageCompressionRatio: number;
+ models: Record<string, number>;
+ modes: Record<string, number>;
+ errorCount: number;
+}
+
+// --- Health ---
+
+export interface HealthStatus {
+ status: "healthy" | "unhealthy";
+ version: string;
+ config: {
+ optimize: boolean;
+ cache: boolean;
+ rateLimit: boolean;
+ };
+}
+
+// --- Proxy Stats ---
+
+export interface ProxyStats {
+ requests: {
+ total: number;
+ cached: number;
+ rateLimited: number;
+ failed: number;
+ byProvider: Record<string, number>;
+ byModel: Record<string, number>;
+ };
+ tokens: {
+ input: number;
+ output: number;
+ saved: number;
+ cliTokensAvoided: number;
+ totalBeforeCompression: number;
+ savingsPercent: number;
+ };
+ latency: { averageMs: number; minMs: number; maxMs: number };
+ overhead: { averageMs: number; minMs: number; maxMs: number };
+ pipelineTiming: Record<
+ string,
+ { averageMs: number; maxMs: number; count: number }
+ >;
+ wasteSignals: Record<string, number>;
+ compression: {
+ ccrEntries: number;
+ ccrMaxEntries: number;
+ originalTokensCached: number;
+ compressedTokensCached: number;
+ ccrRetrievals: number;
+ };
+ cost: Record<string, any>;
+ feedbackLoop: {
+ toolsTracked: number;
+ totalCompressions: number;
+ totalRetrievals: number;
+ globalRetrievalRate: number;
+ };
+}
+
+// --- Memory Usage ---
+
+export interface MemoryUsage {
+ processMemory: { rss: number; vms: number; percent: number };
+ components: Record<string, { memoryMb: number; budgetMb: number }>;
+ totalTrackedMb: number;
+ targetBudgetMb: number;
+}
+
+// --- CCR Types ---
+
+export interface RetrieveResult {
+ hash: string;
+ originalContent: string;
+ originalTokens: number;
+ originalItemCount: number;
+ compressedItemCount: number;
+ toolName: string;
+ retrievalCount: number;
+}
+
+export interface RetrieveSearchResult {
+ hash: string;
+ query: string;
+ results: any[];
+ count: number;
+}
+
+export interface CCRStats {
+ store: {
+ entries: number;
+ maxEntries: number;
+ originalTokensCached: number;
+ compressedTokensCached: number;
+ retrievals: number;
+ };
+ recentRetrievals: Array<{
+ hash: string;
+ query: string | null;
+ itemsRetrieved: number;
+ totalItems: number;
+ toolName: string;
+ retrievalType: string;
+ }>;
+}
+
+// --- Telemetry ---
+
+export interface TelemetryStats {
+ enabled: boolean;
+ totalCompressions: number;
+ totalRetrievals: number;
+ globalRetrievalRate: number;
+ toolSignaturesTracked: number;
+ avgCompressionRatio: number;
+ avgTokenReduction: number;
+}
+
+export interface ToolHints {
+ toolName: string;
+ hints: {
+ maxItems: number;
+ minItems: number;
+ suggestedItems: any[];
+ aggressiveness: number;
+ skipCompression: boolean;
+ preserveFields: string[];
+ reason: string;
+ };
+ pattern: {
+ totalCompressions: number;
+ totalRetrievals: number;
+ retrievalRate: number;
+ fullRetrievalRate: number;
+ searchRate: number;
+ commonQueries: string[];
+ queriedFields: string[];
+ };
+}
+
+export interface TOINStats {
+ enabled: boolean;
+ patternsTracked: number;
+ totalCompressions: number;
+ totalRetrievals: number;
+ globalRetrievalRate: number;
+ patternsWithRecommendations: number;
+}
+
+export interface TOINPattern {
+ hash: string;
+ compressions: number;
+ retrievals: number;
+ retrievalRate: string;
+ confidence: number;
+ skipRecommended: boolean;
+ optimalMaxItems: number;
+}
+
+// --- Metrics Query ---
+
+export interface MetricsQuery {
+ startTime?: Date;
+ endTime?: Date;
+ model?: string;
+ mode?: string;
+ limit?: number;
+}
+
+export interface SummaryQuery {
+ startTime?: Date;
+ endTime?: Date;
+}
+
+export interface StatsHistoryQuery {
+ format?: "json" | "csv";
+ series?: "history" | "hourly" | "daily" | "weekly" | "monthly";
+}
diff --git a/sdk/typescript/src/utils/case.ts b/sdk/typescript/src/utils/case.ts
new file mode 100644
index 000000000..4cbe468f7
--- /dev/null
+++ b/sdk/typescript/src/utils/case.ts
@@ -0,0 +1,34 @@
+/**
+ * Case conversion utilities for proxy communication.
+ * Proxy uses snake_case (Python), SDK uses camelCase (TypeScript).
+ */
+
+export function snakeToCamel(str: string): string {
+ return str.replace(/_([a-z0-9])/g, (_, c) => c.toUpperCase());
+}
+
+export function camelToSnake(str: string): string {
+ return str.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);
+}
+
+export function deepCamelCase<T = any>(obj: any): T {
+ if (obj === null || obj === undefined) return obj as T;
+ if (Array.isArray(obj)) return obj.map(deepCamelCase) as T;
+ if (typeof obj === "object" && !(obj instanceof Date)) {
+ return Object.fromEntries(
+ Object.entries(obj).map(([k, v]) => [snakeToCamel(k), deepCamelCase(v)]),
+ ) as T;
+ }
+ return obj as T;
+}
+
+export function deepSnakeCase(obj: any): any {
+ if (obj === null || obj === undefined) return obj;
+ if (Array.isArray(obj)) return obj.map(deepSnakeCase);
+ if (typeof obj === "object" && !(obj instanceof Date)) {
+ return Object.fromEntries(
+ Object.entries(obj).map(([k, v]) => [camelToSnake(k), deepSnakeCase(v)]),
+ );
+ }
+ return obj;
+}
diff --git a/sdk/typescript/src/utils/stream.ts b/sdk/typescript/src/utils/stream.ts
new file mode 100644
index 000000000..c8a0bd0aa
--- /dev/null
+++ b/sdk/typescript/src/utils/stream.ts
@@ -0,0 +1,50 @@
+/**
+ * SSE (Server-Sent Events) stream parser for proxy streaming responses.
+ */
+
+/**
+ * Parse an SSE response body into an async generator of parsed JSON events.
+ */
+export async function* parseSSE<T = any>(
+ response: Response,
+): AsyncGenerator<T> {
+ const reader = response.body!.getReader();
+ const decoder = new TextDecoder();
+ let buffer = "";
+
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+
+ buffer += decoder.decode(value, { stream: true });
+ const lines = buffer.split("\n");
+ buffer = lines.pop()!;
+
+ for (const line of lines) {
+ if (line.startsWith("data: ")) {
+ const data = line.slice(6).trim();
+ if (data === "[DONE]") return;
+ try {
+ yield JSON.parse(data) as T;
+ } catch {
+ // skip non-JSON data lines (e.g. Anthropic event metadata)
+ }
+ }
+ }
+ }
+ } finally {
+ reader.releaseLock();
+ }
+}
+
+/**
+ * Collect all chunks from an async iterable into an array.
+ */
+export async function collectStream<T>(stream: AsyncIterable<T>): Promise<T[]> {
+ const chunks: T[] = [];
+ for await (const chunk of stream) {
+ chunks.push(chunk);
+ }
+ return chunks;
+}
diff --git a/sdk/typescript/test/adapters/gemini.test.ts b/sdk/typescript/test/adapters/gemini.test.ts
new file mode 100644
index 000000000..1e418bb85
--- /dev/null
+++ b/sdk/typescript/test/adapters/gemini.test.ts
@@ -0,0 +1,131 @@
+/**
+ * Tests for Gemini adapter — withHeadroom for Google Generative AI.
+ */
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { withHeadroom } from "../../src/adapters/gemini.js";
+
+const mockFetch = vi.fn();
+vi.stubGlobal("fetch", mockFetch);
+
+function mockCompressResponse(messages: any[]) {
+ return {
+ ok: true,
+ json: async () => ({
+ messages: [{ role: "user", content: "compressed content" }],
+ tokens_before: 500,
+ tokens_after: 100,
+ tokens_saved: 400,
+ compression_ratio: 0.2,
+ transforms_applied: ["smart_crusher"],
+ ccr_hashes: [],
+ }),
+ };
+}
+
+describe("Gemini withHeadroom", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("wraps generateContent with compression", async () => {
+ const originalResult = { response: { text: () => "Generated text" } };
+ const mockModel = {
+ generateContent: vi.fn().mockResolvedValue(originalResult),
+ };
+
+ mockFetch.mockResolvedValue(mockCompressResponse([]));
+
+ const wrapped = withHeadroom(mockModel, { baseUrl: "http://test:8787" });
+
+ const result = await wrapped.generateContent({
+ contents: [
+ { role: "user", parts: [{ text: "Hello Gemini" }] },
+ ],
+ });
+
+ // The original generateContent was called
+ expect(mockModel.generateContent).toHaveBeenCalled();
+ expect(result).toBe(originalResult);
+
+ // Compression was triggered
+ expect(mockFetch).toHaveBeenCalled();
+ });
+
+ it("wraps generateContentStream if available", async () => {
+ const originalResult = { stream: "mock stream" };
+ const mockModel = {
+ generateContent: vi.fn(),
+ generateContentStream: vi.fn().mockResolvedValue(originalResult),
+ };
+
+ mockFetch.mockResolvedValue(mockCompressResponse([]));
+
+ const wrapped = withHeadroom(mockModel, { baseUrl: "http://test:8787" });
+
+ const result = await wrapped.generateContentStream({
+ contents: [{ role: "user", parts: [{ text: "Stream test" }] }],
+ });
+
+ expect(mockModel.generateContentStream).toHaveBeenCalled();
+ expect(result).toBe(originalResult);
+ });
+
+ it("passes through other model methods", () => {
+ const mockModel = {
+ generateContent: vi.fn(),
+ countTokens: vi.fn().mockReturnValue(42),
+ };
+
+ const wrapped = withHeadroom(mockModel, { baseUrl: "http://test:8787" });
+ expect(wrapped.countTokens()).toBe(42);
+ });
+
+ it("uses model option for compression", async () => {
+ const mockModel = {
+ generateContent: vi.fn().mockResolvedValue({}),
+ };
+
+ mockFetch.mockResolvedValue(mockCompressResponse([]));
+
+ const wrapped = withHeadroom(mockModel, {
+ baseUrl: "http://test:8787",
+ model: "gemini-2.0-flash",
+ });
+
+ await wrapped.generateContent({
+ contents: [{ role: "user", parts: [{ text: "test" }] }],
+ });
+
+ const [, opts] = mockFetch.mock.calls[0];
+ const body = JSON.parse(opts.body);
+ expect(body.model).toBe("gemini-2.0-flash");
+ });
+
+ it("falls back gracefully on proxy failure", async () => {
+ const originalResult = { response: { text: () => "ok" } };
+ const mockModel = {
+ generateContent: vi.fn().mockResolvedValue(originalResult),
+ };
+
+ // Proxy fails, fallback returns original messages uncompressed
+ mockFetch.mockResolvedValue({
+ ok: true,
+ json: async () => ({
+ messages: [{ role: "user", content: "Hello Gemini" }],
+ tokens_before: 0,
+ tokens_after: 0,
+ tokens_saved: 0,
+ compression_ratio: 1.0,
+ transforms_applied: [],
+ ccr_hashes: [],
+ }),
+ });
+
+ const wrapped = withHeadroom(mockModel, { baseUrl: "http://test:8787" });
+ const result = await wrapped.generateContent({
+ contents: [{ role: "user", parts: [{ text: "Hello Gemini" }] }],
+ });
+
+ expect(result).toBe(originalResult);
+ });
+});
diff --git a/sdk/typescript/test/adapters/vercel-ai.test.ts b/sdk/typescript/test/adapters/vercel-ai.test.ts
index 36ec6b02d..8dd08ee79 100644
--- a/sdk/typescript/test/adapters/vercel-ai.test.ts
+++ b/sdk/typescript/test/adapters/vercel-ai.test.ts
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from "vitest";
import {
headroomMiddleware,
compressVercelMessages,
+ withHeadroom,
} from "../../src/adapters/vercel-ai.js";
const mockFetch = vi.fn();
@@ -171,3 +172,135 @@ describe("compressVercelMessages", () => {
expect(result.messages[1].content[0].type).toBe("text");
});
});
+
+describe("withHeadroom", () => {
+ beforeEach(() => {
+ mockFetch.mockReset();
+ });
+
+ it("returns a LanguageModelV3 with correct provider and modelId", () => {
+ const fakeModel = {
+ specificationVersion: "v3" as const,
+ provider: "openai",
+ modelId: "gpt-4o",
+ supportedUrls: {},
+ doGenerate: vi.fn(),
+ doStream: vi.fn(),
+ };
+
+ const wrapped = withHeadroom(fakeModel as any, {
+ baseUrl: "http://localhost:8787",
+ });
+
+ expect(wrapped.specificationVersion).toBe("v3");
+ expect(wrapped.modelId).toBe("gpt-4o");
+ expect(wrapped.provider).toBe("openai");
+ });
+
+ it("triggers compression on doGenerate", async () => {
+ mockFetch.mockResolvedValueOnce(
+ mockCompressResponse([{ role: "user", content: "compressed" }]),
+ );
+
+ const fakeModel = {
+ specificationVersion: "v3" as const,
+ provider: "test-provider",
+ modelId: "test-model",
+ supportedUrls: {},
+ doGenerate: vi.fn().mockResolvedValue({
+ text: "response",
+ usage: { promptTokens: 10, completionTokens: 5 },
+ finishReason: "stop",
+ rawCall: { rawPrompt: null, rawSettings: {} },
+ }),
+ doStream: vi.fn(),
+ };
+
+ const wrapped = withHeadroom(fakeModel as any, {
+ baseUrl: "http://localhost:8787",
+ });
+
+ await wrapped.doGenerate({
+ prompt: [
+ { role: "user", content: [{ type: "text", text: "hello world" }] },
+ ],
+ mode: { type: "regular" },
+ inputFormat: "prompt",
+ } as any);
+
+ // Proxy should have been called for compression
+ expect(mockFetch).toHaveBeenCalledOnce();
+ const [url] = mockFetch.mock.calls[0];
+ expect(url).toContain("/v1/compress");
+ });
+
+ it("passes options through to headroomMiddleware", async () => {
+ mockFetch.mockResolvedValueOnce(
+ mockCompressResponse([{ role: "user", content: "x" }]),
+ );
+
+ const fakeModel = {
+ specificationVersion: "v3" as const,
+ provider: "test",
+ modelId: "test-model",
+ supportedUrls: {},
+ doGenerate: vi.fn().mockResolvedValue({
+ text: "ok",
+ usage: { promptTokens: 5, completionTokens: 3 },
+ finishReason: "stop",
+ rawCall: { rawPrompt: null, rawSettings: {} },
+ }),
+ doStream: vi.fn(),
+ };
+
+ const wrapped = withHeadroom(fakeModel as any, {
+ baseUrl: "http://localhost:8787",
+ model: "claude-sonnet-4-5-20250929",
+ });
+
+ await wrapped.doGenerate({
+ prompt: [
+ { role: "user", content: [{ type: "text", text: "hi" }] },
+ ],
+ mode: { type: "regular" },
+ inputFormat: "prompt",
+ } as any);
+
+ const body = JSON.parse(mockFetch.mock.calls[0][1].body);
+ expect(body.model).toBe("claude-sonnet-4-5-20250929");
+ });
+
+ it("falls back when proxy is down", async () => {
+ mockFetch.mockRejectedValueOnce(new TypeError("fetch failed"));
+
+ const fakeModel = {
+ specificationVersion: "v3" as const,
+ provider: "test",
+ modelId: "test-model",
+ supportedUrls: {},
+ doGenerate: vi.fn().mockResolvedValue({
+ text: "ok",
+ usage: { promptTokens: 5, completionTokens: 3 },
+ finishReason: "stop",
+ rawCall: { rawPrompt: null, rawSettings: {} },
+ }),
+ doStream: vi.fn(),
+ };
+
+ const wrapped = withHeadroom(fakeModel as any, {
+ baseUrl: "http://localhost:8787",
+ fallback: true,
+ });
+
+ // Should not throw — fallback returns original messages
+ await wrapped.doGenerate({
+ prompt: [
+ { role: "user", content: [{ type: "text", text: "hello" }] },
+ ],
+ mode: { type: "regular" },
+ inputFormat: "prompt",
+ } as any);
+
+ expect(fakeModel.doGenerate).toHaveBeenCalled();
+ });
+});
diff --git a/sdk/typescript/test/client-expanded.test.ts b/sdk/typescript/test/client-expanded.test.ts
new file mode 100644
index 000000000..63e08e9e9
--- /dev/null
+++ b/sdk/typescript/test/client-expanded.test.ts
@@ -0,0 +1,333 @@
+/**
+ * Tests for expanded HeadroomClient — chat.completions, messages, metrics, CCR, etc.
+ * Uses mocked proxy (no real server needed).
+ */
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { HeadroomClient } from "../src/client.js";
+
+const mockFetch = vi.fn();
+vi.stubGlobal("fetch", mockFetch);
+
+function jsonResponse(data: any, ok = true) {
+ return {
+ ok,
+ status: ok ? 200 : 500,
+ json: async () => data,
+ text: async () => JSON.stringify(data),
+ };
+}
+
+describe("HeadroomClient constructor", () => {
+ it("accepts extended options", () => {
+ const client = new HeadroomClient({
+ baseUrl: "http://proxy:8787",
+ apiKey: "hdr-key",
+ providerApiKey: "sk-openai-key",
+ defaultMode: "optimize",
+ config: { smartCrusher: { enabled: true } },
+ });
+ expect(client).toBeDefined();
+ expect(client.providerApiKey).toBe("sk-openai-key");
+ });
+
+ it("has chat.completions sub-client", () => {
+ const client = new HeadroomClient();
+ expect(client.chat).toBeDefined();
+ expect(client.chat.completions).toBeDefined();
+ });
+
+ it("has messages sub-client", () => {
+ const client = new HeadroomClient();
+ expect(client.messages).toBeDefined();
+ });
+
+ it("has telemetry namespace", () => {
+ const client = new HeadroomClient();
+ expect(client.telemetry).toBeDefined();
+ expect(client.telemetry.getStats).toBeTypeOf("function");
+ });
+
+ it("has feedback namespace", () => {
+ const client = new HeadroomClient();
+ expect(client.feedback).toBeDefined();
+ expect(client.feedback.getStats).toBeTypeOf("function");
+ });
+
+ it("has toin namespace", () => {
+ const client = new HeadroomClient();
+ expect(client.toin).toBeDefined();
+ expect(client.toin.getStats).toBeTypeOf("function");
+ });
+});
+
+describe("HeadroomClient.health()", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("returns health status", async () => {
+ mockFetch.mockResolvedValue(
+ jsonResponse({
+ status: "healthy",
+ version: "0.5.18",
+ config: { optimize: true, cache: true, rate_limit: false },
+ }),
+ );
+
+ const client = new HeadroomClient({ baseUrl: "http://test:8787" });
+ const health = await client.health();
+
+ expect(health.status).toBe("healthy");
+ expect(health.version).toBe("0.5.18");
+ expect(health.config.optimize).toBe(true);
+ });
+});
+
+describe("HeadroomClient.proxyStats()", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("returns proxy stats with camelCase keys", async () => {
+ mockFetch.mockResolvedValue(
+ jsonResponse({
+ requests: { total: 100, cached: 10, rate_limited: 0, failed: 2 },
+ tokens: { input: 50000, output: 20000, saved: 30000 },
+ }),
+ );
+
+ const client = new HeadroomClient({ baseUrl: "http://test:8787" });
+ const stats = await client.proxyStats();
+
+ expect(stats.requests.total).toBe(100);
+ expect(stats.requests.rateLimited).toBe(0);
+ expect(stats.tokens.saved).toBe(30000);
+ });
+});
+
+describe("HeadroomClient.getMetrics()", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("returns request metrics from proxy", async () => {
+ mockFetch.mockResolvedValue(
+ jsonResponse({
+ recent_requests: [
+ { request_id: "r1", model: "gpt-4o", tokens_input_before: 1000, mode: "optimize" },
+ { request_id: "r2", model: "claude", tokens_input_before: 2000, mode: "audit" },
+ ],
+ }),
+ );
+
+ const client = new HeadroomClient({ baseUrl: "http://test:8787" });
+ const metrics = await client.getMetrics();
+
+ expect(metrics).toHaveLength(2);
+ expect(metrics[0].requestId).toBe("r1");
+ expect(metrics[0].tokensInputBefore).toBe(1000);
+ });
+
+ it("filters by model", async () => {
+ mockFetch.mockResolvedValue(
+ jsonResponse({
+ recent_requests: [
+ { request_id: "r1", model: "gpt-4o", mode: "optimize" },
+ { request_id: "r2", model: "claude", mode: "optimize" },
+ ],
+ }),
+ );
+
+ const client = new HeadroomClient({ baseUrl: "http://test:8787" });
+ const metrics = await client.getMetrics({ model: "gpt-4o" });
+
+ expect(metrics).toHaveLength(1);
+ expect(metrics[0].requestId).toBe("r1");
+ });
+
+ it("applies limit", async () => {
+ mockFetch.mockResolvedValue(
+ jsonResponse({
+ recent_requests: [
+ { request_id: "r1" },
+ { request_id: "r2" },
+ { request_id: "r3" },
+ ],
+ }),
+ );
+
+ const client = new HeadroomClient({ baseUrl: "http://test:8787" });
+ const metrics = await client.getMetrics({ limit: 2 });
+
+ expect(metrics).toHaveLength(2);
+ });
+});
+
+describe("HeadroomClient.getSummary()", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("returns aggregated summary", async () => {
+ mockFetch.mockResolvedValue(
+ jsonResponse({
+ requests: { total: 50, by_model: { "gpt-4o": 30 }, failed: 1 },
+ tokens: { total_before_compression: 100000, saved: 70000, savings_percent: 70 },
+ }),
+ );
+
+ const client = new HeadroomClient({ baseUrl: "http://test:8787" });
+ const summary = await client.getSummary();
+
+ expect(summary.totalRequests).toBe(50);
+ expect(summary.totalTokensSaved).toBe(70000);
+ expect(summary.errorCount).toBe(1);
+ });
+});
+
+describe("HeadroomClient.validateSetup()", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("returns valid when healthy", async () => {
+ mockFetch.mockResolvedValue(
+ jsonResponse({
+ status: "healthy",
+ config: { optimize: true },
+ }),
+ );
+
+ const client = new HeadroomClient({ baseUrl: "http://test:8787" });
+ const result = await client.validateSetup();
+
+ expect(result.valid).toBe(true);
+ expect(result.errors).toEqual([]);
+ });
+
+ it("returns invalid when unhealthy", async () => {
+ mockFetch.mockResolvedValue(
+ jsonResponse({
+ status: "unhealthy",
+ config: {},
+ }),
+ );
+
+ const client = new HeadroomClient({ baseUrl: "http://test:8787" });
+ const result = await client.validateSetup();
+
+ expect(result.valid).toBe(false);
+ expect(result.errors).toContain("Proxy unhealthy");
+ });
+});
+
+describe("HeadroomClient.retrieve()", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("retrieves by hash", async () => {
+ mockFetch.mockResolvedValue(
+ jsonResponse({
+ hash: "abc123",
+ original_content: "full data here",
+ original_tokens: 500,
+ original_item_count: 20,
+ compressed_item_count: 5,
+ tool_name: "search",
+ retrieval_count: 1,
+ }),
+ );
+
+ const client = new HeadroomClient({ baseUrl: "http://test:8787" });
+ const result = await client.retrieve("abc123") as any;
+
+ expect(result.hash).toBe("abc123");
+ expect(result.originalContent).toBe("full data here");
+ expect(result.originalTokens).toBe(500);
+ });
+
+ it("retrieves with query", async () => {
+ mockFetch.mockResolvedValue(
+ jsonResponse({
+ hash: "abc123",
+ query: "error logs",
+ results: [{ text: "ERROR: connection failed" }],
+ count: 1,
+ }),
+ );
+
+ const client = new HeadroomClient({ baseUrl: "http://test:8787" });
+ const result = await client.retrieve("abc123", { query: "error logs" }) as any;
+
+ expect(result.query).toBe("error logs");
+ expect(result.count).toBe(1);
+ });
+});
+
+describe("HeadroomClient.clearCache()", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("clears cache", async () => {
+ mockFetch.mockResolvedValue(jsonResponse({ status: "cleared" }));
+
+ const client = new HeadroomClient({ baseUrl: "http://test:8787" });
+ const result = await client.clearCache();
+
+ expect(result.status).toBe("cleared");
+ });
+});
+
+describe("HeadroomClient.close()", () => {
+ it("is a no-op (HTTP client is stateless)", () => {
+ const client = new HeadroomClient();
+ expect(() => client.close()).not.toThrow();
+ });
+});
+
+describe("HeadroomClient.compressRaw()", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("sends raw body to /v1/compress", async () => {
+ mockFetch.mockResolvedValue(
+ jsonResponse({
+ messages: [],
+ tokens_before: 100,
+ tokens_after: 50,
+ }),
+ );
+
+ const client = new HeadroomClient({ baseUrl: "http://test:8787" });
+ const result = await client.compressRaw({
+ messages: [{ role: "user", content: "test" }],
+ model: "gpt-4o",
+ config: { default_mode: "simulate" },
+ });
+
+ expect(result.tokens_before).toBe(100);
+
+ const [url] = mockFetch.mock.calls[0];
+ expect(url).toBe("http://test:8787/v1/compress");
+ });
+});
+
+describe("HeadroomClient config passthrough", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("sends config as snake_case in compress body", async () => {
+ mockFetch.mockResolvedValue(
+ jsonResponse({
+ messages: [{ role: "user", content: "hi" }],
+ tokens_before: 10,
+ tokens_after: 10,
+ tokens_saved: 0,
+ compression_ratio: 1.0,
+ transforms_applied: [],
+ ccr_hashes: [],
+ }),
+ );
+
+ const client = new HeadroomClient({
+ baseUrl: "http://test:8787",
+ config: {
+ smartCrusher: { enabled: true, minTokensToCrush: 100 },
+ },
+ });
+
+ await client.compress([{ role: "user", content: "hi" }]);
+
+ const [, opts] = mockFetch.mock.calls[0];
+ const body = JSON.parse(opts.body);
+ expect(body.config).toBeDefined();
+ expect(body.config.smart_crusher.enabled).toBe(true);
+ expect(body.config.smart_crusher.min_tokens_to_crush).toBe(100);
+ });
+});
diff --git a/sdk/typescript/test/config.test.ts b/sdk/typescript/test/config.test.ts
new file mode 100644
index 000000000..06be2c091
--- /dev/null
+++ b/sdk/typescript/test/config.test.ts
@@ -0,0 +1,275 @@
+/**
+ * Tests for configuration types — matches Python test_config.py patterns.
+ * Validates TypeScript interfaces match Python dataclass defaults and structure.
+ */
+import { describe, it, expect } from "vitest";
+import type {
+ HeadroomMode,
+ HeadroomConfig,
+ SmartCrusherConfig,
+ ToolCrusherConfig,
+ CacheAlignerConfig,
+ RollingWindowConfig,
+ IntelligentContextConfig,
+ ScoringWeights,
+ RelevanceScorerConfig,
+ AnchorConfig,
+ CacheOptimizerConfig,
+ CCRConfig,
+ PrefixFreezeConfig,
+ ReadLifecycleConfig,
+ CompressionProfile,
+} from "../src/types/config.js";
+
+describe("HeadroomMode", () => {
+ it("accepts valid mode values", () => {
+ const modes: HeadroomMode[] = ["audit", "optimize", "simulate"];
+ expect(modes).toEqual(["audit", "optimize", "simulate"]);
+ });
+});
+
+describe("ToolCrusherConfig", () => {
+ it("accepts default-like values", () => {
+ const config: ToolCrusherConfig = {
+ enabled: false,
+ minTokensToCrush: 500,
+ maxArrayItems: 10,
+ maxStringLength: 1000,
+ maxDepth: 5,
+ };
+ expect(config.enabled).toBe(false);
+ expect(config.minTokensToCrush).toBe(500);
+ expect(config.maxArrayItems).toBe(10);
+ expect(config.maxStringLength).toBe(1000);
+ expect(config.maxDepth).toBe(5);
+ });
+
+ it("all fields are optional", () => {
+ const config: ToolCrusherConfig = {};
+ expect(config.enabled).toBeUndefined();
+ });
+});
+
+describe("CacheAlignerConfig", () => {
+ it("accepts default-like values", () => {
+ const config: CacheAlignerConfig = {
+ enabled: false,
+ useDynamicDetector: true,
+ entropyThreshold: 0.7,
+ normalizeWhitespace: true,
+ collapseBlankLines: true,
+ };
+ expect(config.enabled).toBe(false);
+ expect(config.useDynamicDetector).toBe(true);
+ expect(config.entropyThreshold).toBe(0.7);
+ });
+});
+
+describe("RollingWindowConfig", () => {
+ it("accepts default-like values", () => {
+ const config: RollingWindowConfig = {
+ enabled: true,
+ keepSystem: true,
+ keepLastTurns: 2,
+ outputBufferTokens: 4000,
+ };
+ expect(config.keepSystem).toBe(true);
+ expect(config.keepLastTurns).toBe(2);
+ expect(config.outputBufferTokens).toBe(4000);
+ });
+});
+
+describe("ScoringWeights", () => {
+ it("accepts default-like values", () => {
+ const weights: ScoringWeights = {
+ recency: 0.20,
+ semanticSimilarity: 0.20,
+ toinImportance: 0.25,
+ errorIndicator: 0.15,
+ forwardReference: 0.15,
+ tokenDensity: 0.05,
+ };
+ const total =
+ weights.recency! +
+ weights.semanticSimilarity! +
+ weights.toinImportance! +
+ weights.errorIndicator! +
+ weights.forwardReference! +
+ weights.tokenDensity!;
+ expect(total).toBe(1.0);
+ });
+});
+
+describe("IntelligentContextConfig", () => {
+ it("accepts default-like values", () => {
+ const config: IntelligentContextConfig = {
+ enabled: true,
+ keepSystem: true,
+ keepLastTurns: 2,
+ outputBufferTokens: 4000,
+ useImportanceScoring: true,
+ toinIntegration: true,
+ toinConfidenceThreshold: 0.3,
+ compressThreshold: 0.10,
+ summarizationEnabled: false,
+ };
+ expect(config.enabled).toBe(true);
+ expect(config.compressThreshold).toBe(0.10);
+ expect(config.summarizationEnabled).toBe(false);
+ });
+});
+
+describe("RelevanceScorerConfig", () => {
+ it("default tier is hybrid", () => {
+ const config: RelevanceScorerConfig = { tier: "hybrid" };
+ expect(config.tier).toBe("hybrid");
+ });
+
+ it("accepts all tier values", () => {
+ const tiers: RelevanceScorerConfig["tier"][] = ["bm25", "embedding", "hybrid"];
+ expect(tiers).toHaveLength(3);
+ });
+});
+
+describe("AnchorConfig", () => {
+ it("accepts default-like values", () => {
+ const config: AnchorConfig = {
+ anchorBudgetPct: 0.25,
+ minAnchorSlots: 3,
+ maxAnchorSlots: 12,
+ defaultFrontWeight: 0.5,
+ defaultBackWeight: 0.4,
+ defaultMiddleWeight: 0.1,
+ useInformationDensity: true,
+ dedupIdenticalItems: true,
+ };
+ const total =
+ config.defaultFrontWeight! +
+ config.defaultBackWeight! +
+ config.defaultMiddleWeight!;
+ expect(total).toBe(1.0);
+ });
+});
+
+describe("SmartCrusherConfig", () => {
+ it("accepts default-like values", () => {
+ const config: SmartCrusherConfig = {
+ enabled: true,
+ minItemsToAnalyze: 5,
+ minTokensToCrush: 200,
+ varianceThreshold: 2.0,
+ uniquenessThreshold: 0.1,
+ similarityThreshold: 0.8,
+ maxItemsAfterCrush: 15,
+ preserveChangePoints: true,
+ useFeedbackHints: true,
+ dedupIdenticalItems: true,
+ };
+ expect(config.enabled).toBe(true);
+ expect(config.minItemsToAnalyze).toBe(5);
+ });
+
+ it("supports nested relevance config", () => {
+ const config: SmartCrusherConfig = {
+ relevance: { tier: "hybrid", relevanceThreshold: 0.25 },
+ anchor: { anchorBudgetPct: 0.25 },
+ };
+ expect(config.relevance!.tier).toBe("hybrid");
+ expect(config.anchor!.anchorBudgetPct).toBe(0.25);
+ });
+});
+
+describe("CacheOptimizerConfig", () => {
+ it("accepts default-like values", () => {
+ const config: CacheOptimizerConfig = {
+ enabled: true,
+ autoDetectProvider: true,
+ minCacheableTokens: 1024,
+ enableSemanticCache: false,
+ };
+ expect(config.enabled).toBe(true);
+ expect(config.minCacheableTokens).toBe(1024);
+ });
+});
+
+describe("CCRConfig", () => {
+ it("accepts default-like values", () => {
+ const config: CCRConfig = {
+ enabled: true,
+ storeMaxEntries: 1000,
+ storeTtlSeconds: 300,
+ injectRetrievalMarker: true,
+ feedbackEnabled: true,
+ minItemsToCache: 20,
+ injectTool: true,
+ injectSystemInstructions: false,
+ };
+ expect(config.enabled).toBe(true);
+ expect(config.storeMaxEntries).toBe(1000);
+ expect(config.injectTool).toBe(true);
+ });
+});
+
+describe("PrefixFreezeConfig", () => {
+ it("accepts default-like values", () => {
+ const config: PrefixFreezeConfig = {
+ enabled: true,
+ minCachedTokens: 1024,
+ sessionTtlSeconds: 600,
+ forceCompressThreshold: 0.5,
+ };
+ expect(config.enabled).toBe(true);
+ expect(config.sessionTtlSeconds).toBe(600);
+ });
+});
+
+describe("ReadLifecycleConfig", () => {
+ it("accepts default-like values", () => {
+ const config: ReadLifecycleConfig = {
+ enabled: true,
+ compressStale: true,
+ compressSuperseded: false,
+ minSizeBytes: 512,
+ };
+ expect(config.enabled).toBe(true);
+ expect(config.compressSuperseded).toBe(false);
+ });
+});
+
+describe("CompressionProfile", () => {
+ it("accepts default-like values", () => {
+ const profile: CompressionProfile = {
+ bias: 1.0,
+ minK: 3,
+ maxK: null,
+ };
+ expect(profile.bias).toBe(1.0);
+ expect(profile.maxK).toBeNull();
+ });
+});
+
+describe("HeadroomConfig", () => {
+ it("accepts full config with all nested objects", () => {
+ const config: HeadroomConfig = {
+ defaultMode: "audit",
+ modelContextLimits: { "gpt-4o": 128000 },
+ smartCrusher: { enabled: true },
+ cacheAligner: { enabled: false },
+ rollingWindow: { keepLastTurns: 2 },
+ cacheOptimizer: { enabled: true },
+ ccr: { enabled: true },
+ prefixFreeze: { enabled: true },
+ contentRouterEnabled: true,
+ intelligentContext: { enabled: true },
+ generateDiffArtifact: false,
+ };
+ expect(config.defaultMode).toBe("audit");
+ expect(config.smartCrusher!.enabled).toBe(true);
+ expect(config.modelContextLimits!["gpt-4o"]).toBe(128000);
+ });
+
+ it("all fields are optional", () => {
+ const config: HeadroomConfig = {};
+ expect(config.defaultMode).toBeUndefined();
+ });
+});
diff --git a/sdk/typescript/test/errors.test.ts b/sdk/typescript/test/errors.test.ts
new file mode 100644
index 000000000..d44322221
--- /dev/null
+++ b/sdk/typescript/test/errors.test.ts
@@ -0,0 +1,169 @@
+/**
+ * Tests for error hierarchy — matches Python test_exceptions.py patterns.
+ */
+import { describe, it, expect } from "vitest";
+import {
+ HeadroomError,
+ HeadroomConnectionError,
+ HeadroomAuthError,
+ HeadroomCompressError,
+ ConfigurationError,
+ ProviderError,
+ StorageError,
+ TokenizationError,
+ CacheError,
+ ValidationError,
+ TransformError,
+ mapProxyError,
+} from "../src/errors.js";
+
+describe("HeadroomError", () => {
+ it("has correct name and message", () => {
+ const err = new HeadroomError("test error");
+ expect(err.name).toBe("HeadroomError");
+ expect(err.message).toBe("test error");
+ expect(err).toBeInstanceOf(Error);
+ });
+
+ it("supports details", () => {
+ const err = new HeadroomError("test", { key: "value" });
+ expect(err.details).toEqual({ key: "value" });
+ });
+
+ it("details are optional", () => {
+ const err = new HeadroomError("test");
+ expect(err.details).toBeUndefined();
+ });
+});
+
+describe("HeadroomConnectionError", () => {
+ it("inherits from HeadroomError", () => {
+ const err = new HeadroomConnectionError("connection failed");
+ expect(err).toBeInstanceOf(HeadroomError);
+ expect(err).toBeInstanceOf(Error);
+ expect(err.name).toBe("HeadroomConnectionError");
+ });
+});
+
+describe("HeadroomAuthError", () => {
+ it("inherits from HeadroomError", () => {
+ const err = new HeadroomAuthError("unauthorized");
+ expect(err).toBeInstanceOf(HeadroomError);
+ expect(err.name).toBe("HeadroomAuthError");
+ });
+});
+
+describe("HeadroomCompressError", () => {
+ it("includes statusCode and errorType", () => {
+ const err = new HeadroomCompressError(500, "compression_error", "failed");
+ expect(err).toBeInstanceOf(HeadroomError);
+ expect(err.name).toBe("HeadroomCompressError");
+ expect(err.statusCode).toBe(500);
+ expect(err.errorType).toBe("compression_error");
+ expect(err.message).toBe("failed");
+ });
+});
+
+describe("ConfigurationError", () => {
+ it("inherits from HeadroomError", () => {
+ const err = new ConfigurationError("bad config");
+ expect(err).toBeInstanceOf(HeadroomError);
+ expect(err.name).toBe("ConfigurationError");
+ });
+});
+
+describe("ProviderError", () => {
+ it("inherits from HeadroomError", () => {
+ const err = new ProviderError("provider failed");
+ expect(err).toBeInstanceOf(HeadroomError);
+ expect(err.name).toBe("ProviderError");
+ });
+});
+
+describe("StorageError", () => {
+ it("inherits from HeadroomError", () => {
+ const err = new StorageError("db error");
+ expect(err).toBeInstanceOf(HeadroomError);
+ expect(err.name).toBe("StorageError");
+ });
+});
+
+describe("TokenizationError", () => {
+ it("inherits from HeadroomError", () => {
+ const err = new TokenizationError("token count failed");
+ expect(err).toBeInstanceOf(HeadroomError);
+ expect(err.name).toBe("TokenizationError");
+ });
+});
+
+describe("CacheError", () => {
+ it("inherits from HeadroomError", () => {
+ const err = new CacheError("cache miss");
+ expect(err).toBeInstanceOf(HeadroomError);
+ expect(err.name).toBe("CacheError");
+ });
+});
+
+describe("ValidationError", () => {
+ it("inherits from HeadroomError", () => {
+ const err = new ValidationError("invalid setup");
+ expect(err).toBeInstanceOf(HeadroomError);
+ expect(err.name).toBe("ValidationError");
+ });
+});
+
+describe("TransformError", () => {
+ it("inherits from HeadroomError", () => {
+ const err = new TransformError("transform failed");
+ expect(err).toBeInstanceOf(HeadroomError);
+ expect(err.name).toBe("TransformError");
+ });
+});
+
+describe("mapProxyError", () => {
+ it("maps 401 to HeadroomAuthError", () => {
+ const err = mapProxyError(401, "auth_error", "unauthorized");
+ expect(err).toBeInstanceOf(HeadroomAuthError);
+ expect(err.message).toBe("unauthorized");
+ });
+
+ it("maps configuration_error type", () => {
+ const err = mapProxyError(400, "configuration_error", "bad config");
+ expect(err).toBeInstanceOf(ConfigurationError);
+ });
+
+ it("maps provider_error type", () => {
+ const err = mapProxyError(502, "provider_error", "upstream failed");
+ expect(err).toBeInstanceOf(ProviderError);
+ });
+
+ it("maps storage_error type", () => {
+ const err = mapProxyError(500, "storage_error", "db down");
+ expect(err).toBeInstanceOf(StorageError);
+ });
+
+ it("maps tokenization_error type", () => {
+ const err = mapProxyError(500, "tokenization_error", "bad tokens");
+ expect(err).toBeInstanceOf(TokenizationError);
+ });
+
+ it("maps cache_error type", () => {
+ const err = mapProxyError(500, "cache_error", "cache issue");
+ expect(err).toBeInstanceOf(CacheError);
+ });
+
+ it("maps validation_error type", () => {
+ const err = mapProxyError(422, "validation_error", "invalid");
+ expect(err).toBeInstanceOf(ValidationError);
+ });
+
+ it("maps transform_error type", () => {
+ const err = mapProxyError(500, "transform_error", "transform broke");
+ expect(err).toBeInstanceOf(TransformError);
+ });
+
+ it("falls back to HeadroomCompressError for unknown types", () => {
+ const err = mapProxyError(500, "unknown_error", "something broke");
+ expect(err).toBeInstanceOf(HeadroomCompressError);
+ });
+});
diff --git a/sdk/typescript/test/hooks.test.ts b/sdk/typescript/test/hooks.test.ts
new file mode 100644
index 000000000..53d768aa5
--- /dev/null
+++ b/sdk/typescript/test/hooks.test.ts
@@ -0,0 +1,265 @@
+/**
+ * Tests for compression hooks — matches Python test_hooks.py patterns.
+ */
+import { describe, it, expect } from "vitest";
+import {
+ CompressionHooks,
+ extractUserQuery,
+ countTurns,
+ extractToolCalls,
+} from "../src/hooks.js";
+import type { CompressContext, CompressEvent } from "../src/hooks.js";
+
+describe("CompressionHooks defaults", () => {
+ it("preCompress returns messages unchanged", () => {
+ const hooks = new CompressionHooks();
+ const messages = [{ role: "user", content: "hello" }];
+ const ctx: CompressContext = {
+ model: "",
+ userQuery: "",
+ turnNumber: 0,
+ toolCalls: [],
+ provider: "",
+ };
+ const result = hooks.preCompress(messages, ctx);
+ expect(result).toBe(messages);
+ });
+
+ it("computeBiases returns empty object", () => {
+ const hooks = new CompressionHooks();
+ const messages = [{ role: "user", content: "hello" }];
+ const ctx: CompressContext = {
+ model: "",
+ userQuery: "",
+ turnNumber: 0,
+ toolCalls: [],
+ provider: "",
+ };
+ const result = hooks.computeBiases(messages, ctx);
+ expect(result).toEqual({});
+ });
+
+ it("postCompress is a no-op", () => {
+ const hooks = new CompressionHooks();
+ const event: CompressEvent = {
+ tokensBefore: 100,
+ tokensAfter: 50,
+ tokensSaved: 50,
+ compressionRatio: 0.5,
+ transformsApplied: [],
+ ccrHashes: [],
+ model: "",
+ userQuery: "",
+ provider: "",
+ };
+ // Should not throw
+ expect(() => hooks.postCompress(event)).not.toThrow();
+ });
+});
+
+describe("Custom hooks", () => {
+ it("preCompress can modify messages", () => {
+ class PrependHooks extends CompressionHooks {
+ preCompress(messages: any[], _ctx: CompressContext) {
+ return [
+ { role: "system", content: "Custom prefix" },
+ ...messages,
+ ];
+ }
+ }
+
+ const hooks = new PrependHooks();
+ const messages = [{ role: "user", content: "hello" }];
+ const ctx: CompressContext = {
+ model: "",
+ userQuery: "",
+ turnNumber: 0,
+ toolCalls: [],
+ provider: "",
+ };
+ const result = hooks.preCompress(messages, ctx);
+ expect(result).toHaveLength(2);
+ expect(result[0].role).toBe("system");
+ });
+
+ it("computeBiases can set position-aware biases", () => {
+ class BiasHooks extends CompressionHooks {
+ computeBiases(messages: any[], _ctx: CompressContext) {
+ const biases: Record<number, number> = {};
+ biases[0] = 2.0; // preserve first message
+ biases[messages.length - 1] = 1.5; // preserve last
+ return biases;
+ }
+ }
+
+ const hooks = new BiasHooks();
+ const messages = [
+ { role: "user", content: "first" },
+ { role: "assistant", content: "middle" },
+ { role: "user", content: "last" },
+ ];
+ const ctx: CompressContext = {
+ model: "",
+ userQuery: "",
+ turnNumber: 0,
+ toolCalls: [],
+ provider: "",
+ };
+ const biases = hooks.computeBiases(messages, ctx);
+ expect(biases[0]).toBe(2.0);
+ expect(biases[2]).toBe(1.5);
+ });
+
+ it("postCompress receives event data", () => {
+ let captured: CompressEvent | null = null;
+
+ class LogHooks extends CompressionHooks {
+ postCompress(event: CompressEvent) {
+ captured = event;
+ }
+ }
+
+ const hooks = new LogHooks();
+ const event: CompressEvent = {
+ tokensBefore: 1000,
+ tokensAfter: 200,
+ tokensSaved: 800,
+ compressionRatio: 0.2,
+ transformsApplied: ["smart_crusher"],
+ ccrHashes: ["abc123"],
+ model: "gpt-4o",
+ userQuery: "test query",
+ provider: "openai",
+ };
+
+ hooks.postCompress(event);
+ expect(captured).toEqual(event);
+ expect(captured!.tokensSaved).toBe(800);
+ });
+
+ it("hooks receive correct context", () => {
+ let capturedCtx: CompressContext | null = null;
+
+ class CtxHooks extends CompressionHooks {
+ preCompress(messages: any[], ctx: CompressContext) {
+ capturedCtx = ctx;
+ return messages;
+ }
+ }
+
+ const hooks = new CtxHooks();
+ const ctx: CompressContext = {
+ model: "gpt-4o",
+ userQuery: "test query",
+ turnNumber: 3,
+ toolCalls: ["tool_a", "tool_b"],
+ provider: "openai",
+ };
+ hooks.preCompress([], ctx);
+ expect(capturedCtx!.model).toBe("gpt-4o");
+ expect(capturedCtx!.turnNumber).toBe(3);
+ expect(capturedCtx!.toolCalls).toEqual(["tool_a", "tool_b"]);
+ });
+});
+
+describe("CompressEvent fields", () => {
+ it("has all expected fields", () => {
+ const event: CompressEvent = {
+ tokensBefore: 0,
+ tokensAfter: 0,
+ tokensSaved: 0,
+ compressionRatio: 0,
+ transformsApplied: [],
+ ccrHashes: [],
+ model: "",
+ userQuery: "",
+ provider: "",
+ };
+ expect(event.tokensBefore).toBe(0);
+ expect(event.transformsApplied).toEqual([]);
+ expect(event.ccrHashes).toEqual([]);
+ });
+});
+
+describe("CompressContext fields", () => {
+ it("has all expected fields with defaults", () => {
+ const ctx: CompressContext = {
+ model: "",
+ userQuery: "",
+ turnNumber: 0,
+ toolCalls: [],
+ provider: "",
+ };
+ expect(ctx.model).toBe("");
+ expect(ctx.turnNumber).toBe(0);
+ expect(ctx.toolCalls).toEqual([]);
+ });
+});
+
+describe("extractUserQuery", () => {
+ it("extracts last user message", () => {
+ const messages = [
+ { role: "user", content: "first" },
+ { role: "assistant", content: "response" },
+ { role: "user", content: "second" },
+ ];
+ expect(extractUserQuery(messages)).toBe("second");
+ });
+
+ it("returns empty for no user messages", () => {
+ expect(extractUserQuery([{ role: "system", content: "sys" }])).toBe("");
+ });
+
+ it("handles array content (text part)", () => {
+ const messages = [
+ { role: "user", content: [{ type: "text", text: "from part" }] },
+ ];
+ expect(extractUserQuery(messages)).toBe("from part");
+ });
+});
+
+describe("countTurns", () => {
+ it("counts user messages", () => {
+ const messages = [
+ { role: "user", content: "1" },
+ { role: "assistant", content: "r" },
+ { role: "user", content: "2" },
+ ];
+ expect(countTurns(messages)).toBe(2);
+ });
+});
+
+describe("extractToolCalls", () => {
+ it("extracts tool names from OpenAI format", () => {
+ const messages = [
+ {
+ role: "assistant",
+ content: null,
+ tool_calls: [
+ { id: "1", type: "function", function: { name: "search", arguments: "{}" } },
+ ],
+ },
+ ];
+ expect(extractToolCalls(messages)).toEqual(["search"]);
+ });
+
+ it("extracts from Anthropic format", () => {
+ const messages = [
+ {
+ role: "assistant",
+ content: [{ type: "tool_use", name: "lookup" }],
+ },
+ ];
+ expect(extractToolCalls(messages)).toEqual(["lookup"]);
+ });
+
+ it("extracts from Vercel format", () => {
+ const messages = [
+ {
+ role: "assistant",
+ content: [{ type: "tool-call", toolName: "fetch" }],
+ },
+ ];
+ expect(extractToolCalls(messages)).toEqual(["fetch"]);
+ });
+});
diff --git a/sdk/typescript/test/models.test.ts b/sdk/typescript/test/models.test.ts
new file mode 100644
index 000000000..b75c6ff8d
--- /dev/null
+++ b/sdk/typescript/test/models.test.ts
@@ -0,0 +1,318 @@
+/**
+ * Tests for data models — validates TypeScript interfaces match Python dataclass shapes.
+ * Matches Python test_config.py (Block, WasteSignals, TransformResult, RequestMetrics).
+ */
+import { describe, it, expect } from "vitest";
+import type {
+ WasteSignals,
+ CachePrefixMetrics,
+ TransformDiff,
+ DiffArtifact,
+ SimulationResult,
+ RequestMetrics,
+ Block,
+ SessionStats,
+ ValidationResult,
+ MetricsSummary,
+ HealthStatus,
+ RetrieveResult,
+ CCRStats,
+ TelemetryStats,
+ TOINPattern,
+} from "../src/types/models.js";
+
+describe("WasteSignals", () => {
+ it("has all fields", () => {
+ const ws: WasteSignals = {
+ jsonBloatTokens: 100,
+ htmlNoiseTokens: 50,
+ base64Tokens: 200,
+ whitespaceTokens: 30,
+ dynamicDateTokens: 10,
+ repetitionTokens: 20,
+ total: 410,
+ };
+ expect(ws.total).toBe(410);
+ });
+
+ it("total with all zeros", () => {
+ const ws: WasteSignals = {
+ jsonBloatTokens: 0,
+ htmlNoiseTokens: 0,
+ base64Tokens: 0,
+ whitespaceTokens: 0,
+ dynamicDateTokens: 0,
+ repetitionTokens: 0,
+ total: 0,
+ };
+ expect(ws.total).toBe(0);
+ });
+});
+
+describe("CachePrefixMetrics", () => {
+ it("has all fields", () => {
+ const m: CachePrefixMetrics = {
+ stablePrefixBytes: 4096,
+ stablePrefixTokensEst: 1024,
+ stablePrefixHash: "abc123",
+ prefixChanged: false,
+ };
+ expect(m.stablePrefixHash).toBe("abc123");
+ expect(m.prefixChanged).toBe(false);
+ expect(m.previousHash).toBeUndefined();
+ });
+
+ it("previousHash is optional", () => {
+ const m: CachePrefixMetrics = {
+ stablePrefixBytes: 0,
+ stablePrefixTokensEst: 0,
+ stablePrefixHash: "",
+ prefixChanged: true,
+ previousHash: "old_hash",
+ };
+ expect(m.previousHash).toBe("old_hash");
+ });
+});
+
+describe("TransformDiff", () => {
+ it("has all fields", () => {
+ const d: TransformDiff = {
+ transformName: "smart_crusher",
+ tokensBefore: 1000,
+ tokensAfter: 300,
+ tokensSaved: 700,
+ itemsRemoved: 15,
+ itemsKept: 5,
+ details: "Compressed 20 items to 5",
+ durationMs: 12.5,
+ };
+ expect(d.tokensSaved).toBe(700);
+ expect(d.durationMs).toBe(12.5);
+ });
+});
+
+describe("DiffArtifact", () => {
+ it("contains transforms list", () => {
+ const a: DiffArtifact = {
+ requestId: "req-123",
+ originalTokens: 5000,
+ optimizedTokens: 1500,
+ totalTokensSaved: 3500,
+ transforms: [
+ {
+ transformName: "smart_crusher",
+ tokensBefore: 5000,
+ tokensAfter: 1500,
+ tokensSaved: 3500,
+ itemsRemoved: 0,
+ itemsKept: 0,
+ details: "",
+ durationMs: 0,
+ },
+ ],
+ };
+ expect(a.transforms).toHaveLength(1);
+ expect(a.totalTokensSaved).toBe(3500);
+ });
+});
+
+describe("Block", () => {
+ it("supports all block kinds", () => {
+ const kinds = [
+ "system",
+ "user",
+ "assistant",
+ "tool_call",
+ "tool_result",
+ "rag",
+ "unknown",
+ ] as const;
+
+ for (const kind of kinds) {
+ const b: Block = {
+ kind,
+ text: "content",
+ tokensEst: 10,
+ contentHash: "hash",
+ sourceIndex: 0,
+ flags: {},
+ };
+ expect(b.kind).toBe(kind);
+ }
+ });
+
+ it("flags is a flexible record", () => {
+ const b: Block = {
+ kind: "tool_result",
+ text: "data",
+ tokensEst: 50,
+ contentHash: "h1",
+ sourceIndex: 3,
+ flags: { is_error: true, tool_name: "search" },
+ };
+ expect(b.flags.is_error).toBe(true);
+ expect(b.flags.tool_name).toBe("search");
+ });
+});
+
+describe("RequestMetrics", () => {
+ it("has all expected fields", () => {
+ const m: RequestMetrics = {
+ requestId: "r1",
+ timestamp: "2025-01-01T00:00:00Z",
+ model: "gpt-4o",
+ stream: false,
+ mode: "optimize",
+ tokensInputBefore: 5000,
+ tokensInputAfter: 1500,
+ blockBreakdown: { user: 2, tool_result: 3 },
+ wasteSignals: { json_bloat_tokens: 200 },
+ stablePrefixHash: "abc",
+ cacheAlignmentScore: 0.85,
+ cacheableTokens: 1000,
+ breakpointsInserted: 2,
+ estimatedCacheHit: true,
+ estimatedSavingsPercent: 70,
+ semanticCacheHit: false,
+ transformsApplied: ["smart_crusher"],
+ toolUnitsDropped: 0,
+ turnsDropped: 0,
+ messagesHash: "hash123",
+ };
+ expect(m.tokensInputBefore).toBe(5000);
+ expect(m.transformsApplied).toContain("smart_crusher");
+ });
+
+ it("optional fields can be null", () => {
+ const m: RequestMetrics = {
+ requestId: "r1",
+ timestamp: "2025-01-01",
+ model: "gpt-4o",
+ stream: false,
+ mode: "audit",
+ tokensInputBefore: 100,
+ tokensInputAfter: 100,
+ tokensOutput: null,
+ blockBreakdown: {},
+ wasteSignals: {},
+ stablePrefixHash: "",
+ cacheAlignmentScore: 0,
+ cachedTokens: null,
+ cacheOptimizerUsed: null,
+ cacheOptimizerStrategy: null,
+ cacheableTokens: 0,
+ breakpointsInserted: 0,
+ estimatedCacheHit: false,
+ estimatedSavingsPercent: 0,
+ semanticCacheHit: false,
+ transformsApplied: [],
+ toolUnitsDropped: 0,
+ turnsDropped: 0,
+ messagesHash: "",
+ error: null,
+ };
+ expect(m.tokensOutput).toBeNull();
+ expect(m.error).toBeNull();
+ });
+});
+
+describe("SimulationResult", () => {
+ it("has all fields", () => {
+ const s: SimulationResult = {
+ tokensBefore: 5000,
+ tokensAfter: 1500,
+ tokensSaved: 3500,
+ transforms: ["smart_crusher", "cache_aligner"],
+ estimatedSavings: "70%",
+ messagesOptimized: [],
+ blockBreakdown: { user: 2 },
+ wasteSignals: { json_bloat_tokens: 200 },
+ stablePrefixHash: "abc",
+ cacheAlignmentScore: 0.85,
+ };
+ expect(s.estimatedSavings).toBe("70%");
+ });
+});
+
+describe("HealthStatus", () => {
+ it("has all fields", () => {
+ const h: HealthStatus = {
+ status: "healthy",
+ version: "0.5.18",
+ config: { optimize: true, cache: true, rateLimit: false },
+ };
+ expect(h.status).toBe("healthy");
+ });
+});
+
+describe("RetrieveResult", () => {
+ it("has all fields", () => {
+ const r: RetrieveResult = {
+ hash: "abc123",
+ originalContent: "data",
+ originalTokens: 500,
+ originalItemCount: 20,
+ compressedItemCount: 5,
+ toolName: "search",
+ retrievalCount: 3,
+ };
+ expect(r.retrievalCount).toBe(3);
+ });
+});
+
+describe("CCRStats", () => {
+ it("has store and recentRetrievals", () => {
+ const s: CCRStats = {
+ store: {
+ entries: 10,
+ maxEntries: 1000,
+ originalTokensCached: 50000,
+ compressedTokensCached: 15000,
+ retrievals: 5,
+ },
+ recentRetrievals: [
+ {
+ hash: "abc",
+ query: null,
+ itemsRetrieved: 20,
+ totalItems: 100,
+ toolName: "search",
+ retrievalType: "full",
+ },
+ ],
+ };
+ expect(s.store.entries).toBe(10);
+ expect(s.recentRetrievals).toHaveLength(1);
+ });
+});
+
+describe("TelemetryStats", () => {
+ it("has all fields", () => {
+ const t: TelemetryStats = {
+ enabled: true,
+ totalCompressions: 500,
+ totalRetrievals: 50,
+ globalRetrievalRate: 0.1,
+ toolSignaturesTracked: 25,
+ avgCompressionRatio: 0.3,
+ avgTokenReduction: 0.7,
+ };
+ expect(t.globalRetrievalRate).toBe(0.1);
+ });
+});
+
+describe("TOINPattern", () => {
+ it("has all fields", () => {
+ const p: TOINPattern = {
+ hash: "abc123def456",
+ compressions: 100,
+ retrievals: 10,
+ retrievalRate: "10.0%",
+ confidence: 0.95,
+ skipRecommended: false,
+ optimalMaxItems: 8,
+ };
+ expect(p.confidence).toBe(0.95);
+ expect(p.skipRecommended).toBe(false);
+ });
+});
diff --git a/sdk/typescript/test/parity.test.ts b/sdk/typescript/test/parity.test.ts
new file mode 100644
index 000000000..9c9dab800
--- /dev/null
+++ b/sdk/typescript/test/parity.test.ts
@@ -0,0 +1,337 @@
+/**
+ * Python-TypeScript SDK parity tests.
+ *
+ * These tests verify that the TypeScript SDK produces identical behavior
+ * to the Python SDK when both talk to the same Headroom proxy.
+ *
+ * Requires:
+ * - HEADROOM_INTEGRATION=1 (env flag)
+ * - headroom proxy running on localhost:8787
+ * - OPENAI_API_KEY set in environment
+ *
+ * Run: HEADROOM_INTEGRATION=1 OPENAI_API_KEY=sk-... npx vitest run test/parity.test.ts
+ */
+import { describe, it, expect, beforeAll } from "vitest";
+import { compress, HeadroomClient, SharedContext, CompressionHooks, simulate } from "../src/index.js";
+import type { CompressResult, CompressEvent, CompressContext } from "../src/index.js";
+import { execSync } from "child_process";
+
+const INTEGRATION = process.env.HEADROOM_INTEGRATION === "1";
+
+// Sample data matching Python test fixtures
+const sampleMessages = [
+ { role: "system" as const, content: "You are a helpful assistant." },
+ { role: "user" as const, content: "What is the capital of France?" },
+ { role: "assistant" as const, content: "The capital of France is Paris." },
+];
+
+const sampleToolOutput = Array.from({ length: 80 }, (_, i) => ({
+ id: i + 1,
+ name: `server-${String(i + 1).padStart(3, "0")}`,
+ status: i % 10 === 7 ? "error" : "running",
+ cpu: Math.round(Math.random() * 100),
+ memory: Math.round(Math.random() * 32768),
+ region: ["us-east-1", "eu-west-1", "ap-southeast-1"][i % 3],
+ last_check: "2025-01-15T10:00:00Z",
+ uptime_days: Math.floor(Math.random() * 365),
+}));
+
+const messagesWithLargeToolOutput = [
+ { role: "system" as const, content: "You are a DevOps assistant." },
+ { role: "user" as const, content: "Show me all servers" },
+ {
+ role: "assistant" as const,
+ content: null,
+ tool_calls: [
+ {
+ id: "call_1",
+ type: "function" as const,
+ function: { name: "list_servers", arguments: "{}" },
+ },
+ ],
+ },
+ {
+ role: "tool" as const,
+ content: JSON.stringify(sampleToolOutput),
+ tool_call_id: "call_1",
+ },
+ { role: "user" as const, content: "Which servers have errors?" },
+];
+
+describe.skipIf(!INTEGRATION)("Python-TypeScript Parity", () => {
+ let pythonCompressResult: any;
+
+ beforeAll(() => {
+ // Run Python compress and capture result
+ const pythonScript = `
+import json, sys
+sys.path.insert(0, "${process.cwd()}/../..")
+from headroom import compress
+
+messages = json.loads('''${JSON.stringify(messagesWithLargeToolOutput)}''')
+result = compress(messages, model="gpt-4o")
+print(json.dumps({
+ "tokens_before": result.tokens_before,
+ "tokens_after": result.tokens_after,
+ "tokens_saved": result.tokens_saved,
+ "compression_ratio": result.compression_ratio,
+ "transforms_applied": result.transforms_applied,
+ "message_count": len(result.messages),
+}))
+`;
+ try {
+ const output = execSync(`python3 -c '${pythonScript.replace(/'/g, "'\\''")}'`, {
+ encoding: "utf-8",
+ timeout: 30000,
+ });
+ pythonCompressResult = JSON.parse(output.trim());
+ } catch (e) {
+ console.warn("Python compress failed, skipping parity checks:", e);
+ pythonCompressResult = null;
+ }
+ });
+
+ describe("compress() parity", () => {
+ it("small messages pass through unchanged (same as Python)", async () => {
+ const result = await compress(sampleMessages, { model: "gpt-4o" });
+
+ // Small messages should pass through — Python does the same
+ expect(result.messages).toHaveLength(3);
+ expect(result.messages[0].role).toBe("system");
+ expect(result.messages[2].role).toBe("assistant");
+ });
+
+ it("large tool output gets compressed (same as Python)", async () => {
+ const result = await compress(messagesWithLargeToolOutput, {
+ model: "gpt-4o",
+ });
+
+ // Both Python and TS should compress this significantly
+ expect(result.tokensSaved).toBeGreaterThan(0);
+ expect(result.compressionRatio).toBeLessThan(1);
+ expect(result.transformsApplied.length).toBeGreaterThan(0);
+
+ console.log(`TS: ${result.tokensBefore} → ${result.tokensAfter} (saved ${result.tokensSaved}, ratio ${result.compressionRatio})`);
+ });
+
+ it("matches Python compression characteristics", async () => {
+ if (!pythonCompressResult) return;
+
+ const tsResult = await compress(messagesWithLargeToolOutput, {
+ model: "gpt-4o",
+ });
+
+ console.log(`Python: ${pythonCompressResult.tokens_before} → ${pythonCompressResult.tokens_after}`);
+ console.log(`TS: ${tsResult.tokensBefore} → ${tsResult.tokensAfter}`);
+
+ // Token counts should be similar (same proxy)
+ // Allow 10% tolerance for non-determinism
+ const tokenDiff = Math.abs(tsResult.tokensBefore - pythonCompressResult.tokens_before);
+ expect(tokenDiff / pythonCompressResult.tokens_before).toBeLessThan(0.1);
+
+ // Both should have compressed
+ expect(tsResult.tokensSaved).toBeGreaterThan(0);
+ expect(pythonCompressResult.tokens_saved).toBeGreaterThan(0);
+
+ // Compression ratio should be similar
+ const ratioDiff = Math.abs(tsResult.compressionRatio - pythonCompressResult.compression_ratio);
+ expect(ratioDiff).toBeLessThan(0.15);
+ });
+
+ it("CompressResult has all fields matching Python", async () => {
+ const result = await compress(sampleMessages, { model: "gpt-4o" });
+
+ // Verify all fields present (matching Python CompressResult)
+ expect(result).toHaveProperty("messages");
+ expect(result).toHaveProperty("tokensBefore");
+ expect(result).toHaveProperty("tokensAfter");
+ expect(result).toHaveProperty("tokensSaved");
+ expect(result).toHaveProperty("compressionRatio");
+ expect(result).toHaveProperty("transformsApplied");
+ expect(result).toHaveProperty("ccrHashes");
+ expect(result).toHaveProperty("compressed");
+
+ expect(typeof result.tokensBefore).toBe("number");
+ expect(typeof result.tokensAfter).toBe("number");
+ expect(Array.isArray(result.transformsApplied)).toBe(true);
+ expect(Array.isArray(result.ccrHashes)).toBe(true);
+ });
+ });
+
+ describe("compress() with hooks parity", () => {
+ it("preCompress hook modifies messages before compression", async () => {
+ let preCompressCalled = false;
+
+ class TestHooks extends CompressionHooks {
+ preCompress(messages: any[], ctx: CompressContext) {
+ preCompressCalled = true;
+ // Prepend a system message
+ return [
+ { role: "system", content: "Hook-injected prefix" },
+ ...messages,
+ ];
+ }
+ }
+
+ const result = await compress(sampleMessages, {
+ model: "gpt-4o",
+ hooks: new TestHooks(),
+ });
+
+ expect(preCompressCalled).toBe(true);
+ // Hook added a message, so there should be 4 total
+ expect(result.messages).toHaveLength(4);
+ });
+
+ it("postCompress hook receives event with stats", async () => {
+ let capturedEvent: CompressEvent | null = null;
+
+ class LogHooks extends CompressionHooks {
+ postCompress(event: CompressEvent) {
+ capturedEvent = event;
+ }
+ }
+
+ await compress(messagesWithLargeToolOutput, {
+ model: "gpt-4o",
+ hooks: new LogHooks(),
+ });
+
+ expect(capturedEvent).not.toBeNull();
+ expect(capturedEvent!.tokensBefore).toBeGreaterThan(0);
+ expect(typeof capturedEvent!.compressionRatio).toBe("number");
+ expect(Array.isArray(capturedEvent!.transformsApplied)).toBe(true);
+ });
+ });
+
+ describe("SharedContext parity", () => {
+ it("put and get compressed content", async () => {
+ const ctx = new SharedContext({ model: "gpt-4o" });
+
+ const entry = await ctx.put("research", JSON.stringify(sampleToolOutput), {
+ agent: "agent-A",
+ });
+
+ expect(entry.key).toBe("research");
+ expect(entry.agent).toBe("agent-A");
+ expect(entry.originalTokens).toBeGreaterThan(0);
+ expect(entry.savingsPercent).toBeGreaterThanOrEqual(0);
+
+ // Get compressed
+ const compressed = ctx.get("research");
+ expect(compressed).not.toBeNull();
+
+ // Get full
+ const full = ctx.get("research", { full: true });
+ expect(full).toBe(JSON.stringify(sampleToolOutput));
+ });
+
+ it("stats aggregate correctly", async () => {
+ const ctx = new SharedContext({ model: "gpt-4o" });
+
+ await ctx.put("a", "Short content");
+ await ctx.put("b", JSON.stringify(sampleToolOutput));
+
+ const stats = ctx.stats();
+ expect(stats.entries).toBe(2);
+ expect(stats.totalOriginalTokens).toBeGreaterThan(0);
+ expect(stats.totalTokensSaved).toBeGreaterThanOrEqual(0);
+ });
+
+ it("clear removes all entries", async () => {
+ const ctx = new SharedContext({ model: "gpt-4o" });
+
+ await ctx.put("a", "data");
+ ctx.clear();
+
+ expect(ctx.keys()).toEqual([]);
+ expect(ctx.stats().entries).toBe(0);
+ });
+ });
+
+ describe("simulate() parity", () => {
+ it("returns simulation result without calling LLM", async () => {
+ const result = await simulate(messagesWithLargeToolOutput, {
+ model: "gpt-4o",
+ });
+
+ expect(result.tokensBefore).toBeGreaterThan(0);
+ expect(result.tokensAfter).toBeGreaterThan(0);
+ expect(typeof result.tokensSaved).toBe("number");
+ });
+ });
+
+ describe("HeadroomClient proxy API parity", () => {
+ it("health check works", async () => {
+ const client = new HeadroomClient();
+ const health = await client.health();
+
+ expect(health.status).toBe("healthy");
+ expect(health.version).toBeDefined();
+ });
+
+ it("proxy stats work", async () => {
+ const client = new HeadroomClient();
+ const stats = await client.proxyStats();
+
+ expect(stats.requests).toBeDefined();
+ expect(typeof stats.requests.total).toBe("number");
+ });
+
+ it("compress with config passthrough", async () => {
+ const client = new HeadroomClient({
+ config: {
+ smartCrusher: { enabled: true, maxItemsAfterCrush: 5 },
+ },
+ });
+
+ const result = await client.compress(
+ messagesWithLargeToolOutput as any[],
+ { model: "gpt-4o" },
+ );
+
+ expect(result.compressed).toBe(true);
+ expect(result.tokensSaved).toBeGreaterThan(0);
+ });
+ });
+});
+
+describe.skipIf(!INTEGRATION)("End-to-End: OpenAI via Proxy", () => {
+ it("chat.completions.create through proxy", async () => {
+ const client = new HeadroomClient({
+ providerApiKey: process.env.OPENAI_API_KEY,
+ });
+
+ const response = await client.chat.completions.create({
+ model: "gpt-4o-mini",
+ messages: [
+ { role: "system", content: "Reply in one word." },
+ { role: "user", content: "What is 2+2?" },
+ ],
+ });
+
+ expect(response.choices).toBeDefined();
+ expect(response.choices[0].message.content).toBeTruthy();
+ console.log("OpenAI response:", response.choices[0].message.content);
+ });
+
+ it("chat.completions.create compresses large context", async () => {
+ const client = new HeadroomClient({
+ providerApiKey: process.env.OPENAI_API_KEY,
+ });
+
+ const response = await client.chat.completions.create({
+ model: "gpt-4o-mini",
+ messages: [
+ ...messagesWithLargeToolOutput,
+ { role: "user", content: "How many servers have errors? Answer with just the number." },
+ ] as any[],
+ headroomMode: "optimize",
+ });
+
+ expect(response.choices).toBeDefined();
+ const answer = response.choices[0].message.content;
+ expect(answer).toBeTruthy();
+ console.log("Answer about error servers:", answer);
+ });
+});
diff --git a/sdk/typescript/test/shared-context.test.ts b/sdk/typescript/test/shared-context.test.ts
new file mode 100644
index 000000000..737aafb02
--- /dev/null
+++ b/sdk/typescript/test/shared-context.test.ts
@@ -0,0 +1,245 @@
+/**
+ * Tests for SharedContext — matches Python test_shared_context.py patterns.
+ * Uses mocked proxy (no real server needed).
+ */
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { SharedContext } from "../src/shared-context.js";
+import type { ContextEntry, SharedContextStats } from "../src/shared-context.js";
+
+// Mock fetch globally
+const mockFetch = vi.fn();
+vi.stubGlobal("fetch", mockFetch);
+
+function mockCompressResponse(
+ content: string,
+ tokensBefore = 100,
+ tokensAfter = 30,
+) {
+ return {
+ ok: true,
+ json: async () => ({
+ messages: [{ role: "user", content: `[compressed] ${content.slice(0, 20)}...` }],
+ tokens_before: tokensBefore,
+ tokens_after: tokensAfter,
+ tokens_saved: tokensBefore - tokensAfter,
+ compression_ratio: tokensAfter / tokensBefore,
+ transforms_applied: ["smart_crusher"],
+ ccr_hashes: [],
+ }),
+ };
+}
+
+describe("SharedContext put/get", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("put and get compressed content", async () => {
+ mockFetch.mockResolvedValue(mockCompressResponse("test data"));
+
+ const ctx = new SharedContext({ baseUrl: "http://test:8787" });
+ const entry = await ctx.put("key1", "test data");
+
+ expect(entry.key).toBe("key1");
+ expect(entry.originalTokens).toBe(100);
+ expect(entry.compressedTokens).toBe(30);
+ expect(entry.savingsPercent).toBe(70);
+
+ const result = ctx.get("key1");
+ expect(result).toContain("[compressed]");
+ });
+
+ it("get with full=true returns original", async () => {
+ mockFetch.mockResolvedValue(mockCompressResponse("full data"));
+
+ const ctx = new SharedContext({ baseUrl: "http://test:8787" });
+ await ctx.put("key1", "full data");
+
+ const full = ctx.get("key1", { full: true });
+ expect(full).toBe("full data");
+ });
+
+ it("get missing key returns null", () => {
+ const ctx = new SharedContext({ baseUrl: "http://test:8787" });
+ expect(ctx.get("nonexistent")).toBeNull();
+ });
+
+ it("overwrite key replaces entry", async () => {
+ mockFetch
+ .mockResolvedValueOnce(mockCompressResponse("first"))
+ .mockResolvedValueOnce(mockCompressResponse("second"));
+
+ const ctx = new SharedContext({ baseUrl: "http://test:8787" });
+ await ctx.put("key1", "first");
+ await ctx.put("key1", "second");
+
+ const full = ctx.get("key1", { full: true });
+ expect(full).toBe("second");
+ });
+
+ it("getEntry returns metadata", async () => {
+ mockFetch.mockResolvedValue(mockCompressResponse("metadata test"));
+
+ const ctx = new SharedContext({ baseUrl: "http://test:8787" });
+ await ctx.put("key1", "metadata test", { agent: "agent-A" });
+
+ const entry = ctx.getEntry("key1");
+ expect(entry).not.toBeNull();
+ expect(entry!.agent).toBe("agent-A");
+ expect(entry!.transforms).toEqual(["smart_crusher"]);
+ });
+
+ it("getEntry returns null for missing key", () => {
+ const ctx = new SharedContext({ baseUrl: "http://test:8787" });
+ expect(ctx.getEntry("missing")).toBeNull();
+ });
+});
+
+describe("SharedContext expiry", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("expired entry returns null on get", async () => {
+ mockFetch.mockResolvedValue(mockCompressResponse("expiring"));
+
+ const ctx = new SharedContext({ baseUrl: "http://test:8787", ttl: 1 });
+ await ctx.put("key1", "expiring");
+
+ // Manually expire by manipulating timestamp
+ const entry = ctx.getEntry("key1")!;
+ (entry as any).timestamp = Date.now() / 1000 - 10; // 10 seconds ago
+ // Re-set entry with expired timestamp via internal map
+ (ctx as any).entries.set("key1", entry);
+
+ expect(ctx.get("key1")).toBeNull();
+ });
+
+ it("expired entry is cleaned from getEntry", async () => {
+ mockFetch.mockResolvedValue(mockCompressResponse("expiring"));
+
+ const ctx = new SharedContext({ baseUrl: "http://test:8787", ttl: 1 });
+ await ctx.put("key1", "expiring");
+
+ const entry = ctx.getEntry("key1")!;
+ (entry as any).timestamp = Date.now() / 1000 - 10;
+ (ctx as any).entries.set("key1", entry);
+
+ expect(ctx.getEntry("key1")).toBeNull();
+ });
+});
+
+describe("SharedContext keys", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("lists active keys", async () => {
+ mockFetch.mockResolvedValue(mockCompressResponse("data"));
+
+ const ctx = new SharedContext({ baseUrl: "http://test:8787" });
+ await ctx.put("a", "data");
+ await ctx.put("b", "data");
+
+ expect(ctx.keys()).toEqual(["a", "b"]);
+ });
+
+ it("excludes expired keys", async () => {
+ mockFetch.mockResolvedValue(mockCompressResponse("data"));
+
+ const ctx = new SharedContext({ baseUrl: "http://test:8787", ttl: 1 });
+ await ctx.put("fresh", "data");
+ await ctx.put("stale", "data");
+
+ // Expire "stale"
+ const entry = (ctx as any).entries.get("stale");
+ entry.timestamp = Date.now() / 1000 - 10;
+
+ expect(ctx.keys()).toEqual(["fresh"]);
+ });
+});
+
+describe("SharedContext stats", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("aggregates statistics", async () => {
+ mockFetch.mockResolvedValue(mockCompressResponse("data", 200, 60));
+
+ const ctx = new SharedContext({ baseUrl: "http://test:8787" });
+ await ctx.put("a", "data");
+ await ctx.put("b", "data");
+
+ const stats = ctx.stats();
+ expect(stats.entries).toBe(2);
+ expect(stats.totalOriginalTokens).toBe(400);
+ expect(stats.totalCompressedTokens).toBe(120);
+ expect(stats.totalTokensSaved).toBe(280);
+ expect(stats.savingsPercent).toBe(70);
+ });
+
+ it("empty stats", () => {
+ const ctx = new SharedContext({ baseUrl: "http://test:8787" });
+ const stats = ctx.stats();
+ expect(stats.entries).toBe(0);
+ expect(stats.savingsPercent).toBe(0);
+ });
+});
+
+describe("SharedContext eviction", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("evicts oldest at capacity", async () => {
+ mockFetch.mockResolvedValue(mockCompressResponse("data"));
+
+ const ctx = new SharedContext({
+ baseUrl: "http://test:8787",
+ maxEntries: 2,
+ });
+ await ctx.put("first", "data");
+ await ctx.put("second", "data");
+ await ctx.put("third", "data"); // should evict "first"
+
+ expect(ctx.keys()).toEqual(["second", "third"]);
+ expect(ctx.get("first")).toBeNull();
+ });
+});
+
+describe("SharedContext clear", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("removes all entries", async () => {
+ mockFetch.mockResolvedValue(mockCompressResponse("data"));
+
+ const ctx = new SharedContext({ baseUrl: "http://test:8787" });
+ await ctx.put("a", "data");
+ await ctx.put("b", "data");
+
+ ctx.clear();
+ expect(ctx.keys()).toEqual([]);
+ expect(ctx.stats().entries).toBe(0);
+ });
+});
+
+describe("SharedContext fallback on proxy failure", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("stores uncompressed when proxy unavailable", async () => {
+ mockFetch.mockRejectedValue(new Error("connection refused"));
+
+ const ctx = new SharedContext({ baseUrl: "http://test:8787" });
+ const entry = await ctx.put("key1", "fallback data");
+
+ expect(entry.key).toBe("key1");
+ expect(entry.original).toBe("fallback data");
+ // Uncompressed — original equals compressed
+ expect(entry.compressed).toBe("fallback data");
+ });
+});
diff --git a/sdk/typescript/test/simulate.test.ts b/sdk/typescript/test/simulate.test.ts
new file mode 100644
index 000000000..67b442eb2
--- /dev/null
+++ b/sdk/typescript/test/simulate.test.ts
@@ -0,0 +1,84 @@
+/**
+ * Tests for simulation API.
+ */
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { simulate } from "../src/simulate.js";
+import type { SimulationResult } from "../src/types/models.js";
+
+const mockFetch = vi.fn();
+vi.stubGlobal("fetch", mockFetch);
+
+function mockSimulateResponse() {
+ return {
+ ok: true,
+ json: async () => ({
+ tokens_before: 5000,
+ tokens_after: 1500,
+ tokens_saved: 3500,
+ transforms: ["smart_crusher", "cache_aligner"],
+ estimated_savings: "70%",
+ messages_optimized: [{ role: "user", content: "compressed" }],
+ block_breakdown: { user: 2, assistant: 1, tool_result: 3 },
+ waste_signals: { json_bloat_tokens: 200, whitespace_tokens: 50 },
+ stable_prefix_hash: "abc123",
+ cache_alignment_score: 0.85,
+ transforms_applied: ["smart_crusher"],
+ ccr_hashes: [],
+ }),
+ };
+}
+
+describe("simulate", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("returns SimulationResult with all fields", async () => {
+ mockFetch.mockResolvedValue(mockSimulateResponse());
+
+ const result = await simulate(
+ [{ role: "user", content: "hello" }],
+ { baseUrl: "http://test:8787", model: "gpt-4o" },
+ );
+
+ expect(result.tokensBefore).toBe(5000);
+ expect(result.tokensAfter).toBe(1500);
+ expect(result.tokensSaved).toBe(3500);
+ expect(result.estimatedSavings).toBe("70%");
+ expect(result.stablePrefixHash).toBe("abc123");
+ expect(result.cacheAlignmentScore).toBe(0.85);
+ });
+
+ it("sends simulation config to proxy", async () => {
+ mockFetch.mockResolvedValue(mockSimulateResponse());
+
+ await simulate(
+ [{ role: "user", content: "test" }],
+ { baseUrl: "http://test:8787" },
+ );
+
+ const [url, opts] = mockFetch.mock.calls[0];
+ expect(url).toBe("http://test:8787/v1/compress");
+ const body = JSON.parse(opts.body);
+ expect(body.config.default_mode).toBe("simulate");
+ expect(body.config.generate_diff_artifact).toBe(true);
+ });
+
+ it("converts snake_case response to camelCase", async () => {
+ mockFetch.mockResolvedValue(mockSimulateResponse());
+
+ const result = await simulate(
+ [{ role: "user", content: "test" }],
+ { baseUrl: "http://test:8787" },
+ );
+
+ // Verify camelCase conversion
+ expect(result).toHaveProperty("tokensBefore");
+ expect(result).toHaveProperty("tokensAfter");
+ expect(result).toHaveProperty("estimatedSavings");
+ expect(result).toHaveProperty("blockBreakdown");
+ expect(result).toHaveProperty("wasteSignals");
+ expect(result).toHaveProperty("stablePrefixHash");
+ expect(result).toHaveProperty("cacheAlignmentScore");
+ });
+});
diff --git a/sdk/typescript/test/utils/case.test.ts b/sdk/typescript/test/utils/case.test.ts
new file mode 100644
index 000000000..323028e20
--- /dev/null
+++ b/sdk/typescript/test/utils/case.test.ts
@@ -0,0 +1,129 @@
+/**
+ * Tests for case conversion utilities.
+ */
+import { describe, it, expect } from "vitest";
+import {
+ snakeToCamel,
+ camelToSnake,
+ deepCamelCase,
+ deepSnakeCase,
+} from "../../src/utils/case.js";
+
+describe("snakeToCamel", () => {
+ it("converts simple snake_case", () => {
+ expect(snakeToCamel("hello_world")).toBe("helloWorld");
+ });
+
+ it("converts multiple underscores", () => {
+ expect(snakeToCamel("tokens_input_before")).toBe("tokensInputBefore");
+ });
+
+ it("handles already camelCase", () => {
+ expect(snakeToCamel("alreadyCamel")).toBe("alreadyCamel");
+ });
+
+ it("handles single word", () => {
+ expect(snakeToCamel("hello")).toBe("hello");
+ });
+
+ it("handles numbers", () => {
+ expect(snakeToCamel("bm25_k1")).toBe("bm25K1");
+ });
+});
+
+describe("camelToSnake", () => {
+ it("converts camelCase to snake_case", () => {
+ expect(camelToSnake("helloWorld")).toBe("hello_world");
+ });
+
+ it("converts multiple capitals", () => {
+ expect(camelToSnake("tokensInputBefore")).toBe("tokens_input_before");
+ });
+
+ it("handles already snake_case", () => {
+ expect(camelToSnake("already_snake")).toBe("already_snake");
+ });
+});
+
+describe("deepCamelCase", () => {
+ it("converts flat object", () => {
+ const result = deepCamelCase({
+ tokens_before: 100,
+ tokens_after: 50,
+ });
+ expect(result).toEqual({ tokensBefore: 100, tokensAfter: 50 });
+ });
+
+ it("converts nested objects", () => {
+ const result = deepCamelCase({
+ cache_metrics: {
+ stable_prefix_hash: "abc",
+ prefix_changed: true,
+ },
+ });
+ expect(result).toEqual({
+ cacheMetrics: {
+ stablePrefixHash: "abc",
+ prefixChanged: true,
+ },
+ });
+ });
+
+ it("converts arrays", () => {
+ const result = deepCamelCase([
+ { tool_name: "search" },
+ { tool_name: "read" },
+ ]);
+ expect(result).toEqual([
+ { toolName: "search" },
+ { toolName: "read" },
+ ]);
+ });
+
+ it("handles null and undefined", () => {
+ expect(deepCamelCase(null)).toBeNull();
+ expect(deepCamelCase(undefined)).toBeUndefined();
+ });
+
+ it("handles primitive values", () => {
+ expect(deepCamelCase(42)).toBe(42);
+ expect(deepCamelCase("hello")).toBe("hello");
+ expect(deepCamelCase(true)).toBe(true);
+ });
+});
+
+describe("deepSnakeCase", () => {
+ it("converts flat object", () => {
+ const result = deepSnakeCase({
+ tokensBefore: 100,
+ tokensAfter: 50,
+ });
+ expect(result).toEqual({ tokens_before: 100, tokens_after: 50 });
+ });
+
+ it("converts nested objects", () => {
+ const result = deepSnakeCase({
+ cacheMetrics: {
+ stablePrefixHash: "abc",
+ },
+ });
+ expect(result).toEqual({
+ cache_metrics: {
+ stable_prefix_hash: "abc",
+ },
+ });
+ });
+
+ it("round-trips with deepCamelCase", () => {
+ const original = {
+ tokens_before: 100,
+ cache_metrics: {
+ stable_prefix_hash: "abc",
+ items: [{ tool_name: "x" }],
+ },
+ };
+ const camel = deepCamelCase(original);
+ const back = deepSnakeCase(camel);
+ expect(back).toEqual(original);
+ });
+});
diff --git a/sdk/typescript/tsup.config.ts b/sdk/typescript/tsup.config.ts
index 4050c8156..adde1311e 100644
--- a/sdk/typescript/tsup.config.ts
+++ b/sdk/typescript/tsup.config.ts
@@ -6,6 +6,7 @@ export default defineConfig({
"adapters/vercel-ai": "src/adapters/vercel-ai.ts",
"adapters/openai": "src/adapters/openai.ts",
"adapters/anthropic": "src/adapters/anthropic.ts",
+ "adapters/gemini": "src/adapters/gemini.ts",
},
format: ["esm", "cjs"],
dts: true,