headroom/sdk/typescript
github-actions[bot] a9515155c7
chore: release main (#1918)
🤖 I have created a release *beep* *boop*
---


<details><summary>0.31.0</summary>

##
[0.31.0](https://github.com/headroomlabs-ai/headroom/compare/v0.30.0...v0.31.0)
(2026-07-09)


### Features

* **cache:** provider-agnostic cache-mode delta + cc-agnostic prefix
comparison
([#1868](https://github.com/headroomlabs-ai/headroom/issues/1868))
([7c2f0ea](7c2f0ea079))
* **ccr:** wire retrieve-tool interception into OpenAI Responses handler
([#1898](https://github.com/headroomlabs-ai/headroom/issues/1898))
([62cd307](62cd3072a2))
* **compression:** add audit-safe mode with protected pattern matching
([#1899](https://github.com/headroomlabs-ai/headroom/issues/1899))
([bb112dd](bb112dd176))
* **content-router:** accept any real compression (remove min-savings
floor)
([#1771](https://github.com/headroomlabs-ai/headroom/issues/1771))
([6c31db9](6c31db97fb))
* **content-router:** lossless-first dispatch, cross-turn dedup, and A7
lossy-after-fold
([#1818](https://github.com/headroomlabs-ai/headroom/issues/1818))
([60af15f](60af15f96f))
* **proxy:** add provider-only HTTP proxy
([#1807](https://github.com/headroomlabs-ai/headroom/issues/1807))
([ebe0a3b](ebe0a3bd7b))
* **proxy:** add turn-hook extension point for buffered model turns
([#1891](https://github.com/headroomlabs-ai/headroom/issues/1891))
([ec950f7](ec950f7ef1))


### Bug Fixes

* **build:** enable Intel macOS pip installs via ort-load-dynamic
([#1538](https://github.com/headroomlabs-ai/headroom/issues/1538))
([32ce99e](32ce99e4b4))
* **cache:** avoid fallback session collisions
([#1827](https://github.com/headroomlabs-ai/headroom/issues/1827))
([0f606b6](0f606b6281))
* **ccr:** make expired retrieve misses terminal
([#1781](https://github.com/headroomlabs-ai/headroom/issues/1781))
([9cbdba4](9cbdba4dc1))
* **ccr:** preserve Anthropic re-stream shape
([#1854](https://github.com/headroomlabs-ai/headroom/issues/1854))
([f663894](f663894f60))
* **ccr:** preserve thinking blocks in buffered stream re-synthesis
([#1897](https://github.com/headroomlabs-ai/headroom/issues/1897))
([ede085c](ede085cc11))
* **cli/proxy:** preserve explicit HEADROOM_MIN_TOKENS=0 / MAX_ITEMS=0
([#1886](https://github.com/headroomlabs-ai/headroom/issues/1886))
([3a33af1](3a33af1af3))
* **code-compressor:** CJK-aware relevance-query symbol matching
([#1747](https://github.com/headroomlabs-ai/headroom/issues/1747))
([b38315c](b38315cf72))
* **codex:** discover updated Codex state stores
([#1889](https://github.com/headroomlabs-ai/headroom/issues/1889))
([9d42eba](9d42ebaa1a))
* **codex:** OpenCode Zen telemetry attribution
([#1648](https://github.com/headroomlabs-ai/headroom/issues/1648))
([f18c6bd](f18c6bd896))
* **content-detector:** detect and compress space-separated JSON objects
([#1742](https://github.com/headroomlabs-ai/headroom/issues/1742))
([5194bdc](5194bdc5a6))
* **content-router:** token-measure lossless folds at the acceptance
gate ([#1772](https://github.com/headroomlabs-ai/headroom/issues/1772))
([c5493ea](c5493ea93b))
* **copilot:** normalize subscription routing host
([#1836](https://github.com/headroomlabs-ai/headroom/issues/1836))
([afd9cbd](afd9cbdfaf))
* **copilot:** route mixed-model requests per model
([#1785](https://github.com/headroomlabs-ai/headroom/issues/1785))
([5af5e22](5af5e22862))
* **dashboard:** deduplicate repeated savings metrics
([#1804](https://github.com/headroomlabs-ai/headroom/issues/1804))
([88f935a](88f935a1eb))
* **dashboard:** distinguish unavailable RTK from zero stats in Docker
([#1900](https://github.com/headroomlabs-ai/headroom/issues/1900))
([87f6e93](87f6e93c14))
* **dashboard:** distinguish unavailable RTK from zero stats in Docker
([#1901](https://github.com/headroomlabs-ai/headroom/issues/1901))
([361adcd](361adcd1a0))
* **dashboard:** price proxy savings without litellm
([#1728](https://github.com/headroomlabs-ai/headroom/issues/1728))
([188e382](188e382b44))
* detect and clear stale ANTHROPIC_BASE_URL from crashed wrap sessions
([#1768](https://github.com/headroomlabs-ai/headroom/issues/1768))
([#1837](https://github.com/headroomlabs-ai/headroom/issues/1837))
([84509a4](84509a4b89))
* **docker:** persist headroom workspace in compose
([#1839](https://github.com/headroomlabs-ai/headroom/issues/1839))
([5e29c06](5e29c06aaf))
* **docker:** report source build version
([#1862](https://github.com/headroomlabs-ai/headroom/issues/1862))
([3807488](38074888ac))
* **evals:** default unparseable judge scores below pass threshold
([#1892](https://github.com/headroomlabs-ai/headroom/issues/1892))
([42ebbc6](42ebbc6cce))
* **install:** pass sc.exe create as raw command line so binPath=
quoting survives
([#1654](https://github.com/headroomlabs-ai/headroom/issues/1654))
([#1702](https://github.com/headroomlabs-ai/headroom/issues/1702))
([d6e0710](d6e0710228))
* **install:** persist --no-http2 override through install apply
([#1676](https://github.com/headroomlabs-ai/headroom/issues/1676))
([6fb5f3b](6fb5f3bc3d))
* **mcp:** isolate ClaudeRegistrar CLI config env
([#1888](https://github.com/headroomlabs-ai/headroom/issues/1888))
([1c947b1](1c947b1103))
* **mcp:** surface dead proxy state
([#1786](https://github.com/headroomlabs-ai/headroom/issues/1786))
([931eed8](931eed879d))
* **memory:** resolve Trae cwd metadata from user reminders
([#1737](https://github.com/headroomlabs-ai/headroom/issues/1737))
([#1887](https://github.com/headroomlabs-ai/headroom/issues/1887))
([3e85eb1](3e85eb1880))
* **opencode:** use local MCP config
([#1383](https://github.com/headroomlabs-ai/headroom/issues/1383))
([4bd3ddf](4bd3ddfaa5))
* **proxy/openai:** thread savings-profile kwargs into chat completions
([#1606](https://github.com/headroomlabs-ai/headroom/issues/1606))
([7ff842d](7ff842da17))
* **proxy/openai:** translate max_tokens -&gt; max_completion_tokens on
chat path
([#1774](https://github.com/headroomlabs-ai/headroom/issues/1774))
([285808b](285808b90e))
* **proxy:** bound Codex WS compression fallback latency
([#1802](https://github.com/headroomlabs-ai/headroom/issues/1802))
([d24a3f8](d24a3f8425))
* **proxy:** bound HF tokenizer load and offload token counting off
event loop
([#1738](https://github.com/headroomlabs-ai/headroom/issues/1738))
([46d5d68](46d5d685d9))
* **proxy:** cancel retry backoff on shutdown
([#1834](https://github.com/headroomlabs-ai/headroom/issues/1834))
([da2d8dc](da2d8dc9db))
* **proxy:** compress Anthropic user text blocks when enabled
([#1875](https://github.com/headroomlabs-ai/headroom/issues/1875))
([e36439a](e36439a941))
* **proxy:** freeze must forward cached (compressed) prefix
byte-identical — stop token-mode cache busting
([#1850](https://github.com/headroomlabs-ai/headroom/issues/1850))
([248ae0f](248ae0f3e0))
* **proxy:** fsync savings dir after atomic rename
([#1764](https://github.com/headroomlabs-ai/headroom/issues/1764))
([7de2c1e](7de2c1e4c2))
* **proxy:** keep cache_control bounded + stable so the freeze overlay
stops busting
([#1852](https://github.com/headroomlabs-ai/headroom/issues/1852))
([4820134](48201345be))
* **proxy:** persist lifetime cache-read savings across restarts
([#1665](https://github.com/headroomlabs-ai/headroom/issues/1665))
([908997e](908997ef61))
* **proxy:** preserve streaming passthrough beta headers
([#1783](https://github.com/headroomlabs-ai/headroom/issues/1783))
([0f553a8](0f553a8ebb))
* **proxy:** release _active_streams session lock on setup-phase errors
([#1864](https://github.com/headroomlabs-ai/headroom/issues/1864))
([2ccd831](2ccd831032))
* **proxy:** retry HTTP/2 stream resets instead of 502ing
([#1645](https://github.com/headroomlabs-ai/headroom/issues/1645))
([2ce19c2](2ce19c2c55))
* **proxy:** retry passthrough on transient upstream connection close
([#1513](https://github.com/headroomlabs-ai/headroom/issues/1513))
([5d14080](5d14080c94))
* **proxy:** route Foundry Anthropic messages
([#1878](https://github.com/headroomlabs-ai/headroom/issues/1878))
([739f654](739f654bbd))
* **proxy:** serve /favicon.ico locally instead of tunneling upstream
([#1787](https://github.com/headroomlabs-ai/headroom/issues/1787))
([#1847](https://github.com/headroomlabs-ai/headroom/issues/1847))
([3076e32](3076e32172))
* **proxy:** stop rtk stat failures from corrupting session baseline
([#1693](https://github.com/headroomlabs-ai/headroom/issues/1693))
([681b9a8](681b9a8c1a))
* **proxy:** strip 1m model suffix before upstream forwarding
([#1840](https://github.com/headroomlabs-ai/headroom/issues/1840))
([e22d745](e22d7453d4))
* **proxy:** subtract cache write premiums from net savings
([#1800](https://github.com/headroomlabs-ai/headroom/issues/1800))
([53a465b](53a465b121))
* **router:** honor MCP aliases in excluded tools
([#1822](https://github.com/headroomlabs-ai/headroom/issues/1822))
([#1863](https://github.com/headroomlabs-ai/headroom/issues/1863))
([140d6e4](140d6e4f96))
* **rtk:** link managed rtk onto PATH instead of mutating the hook
([#1698](https://github.com/headroomlabs-ai/headroom/issues/1698))
([140cb05](140cb05fbc))
* **streaming:** preserve server_tool_use sse blocks
([#1826](https://github.com/headroomlabs-ai/headroom/issues/1826))
([4ac5493](4ac54934cb))
* **toin:** publish skip compression recommendations
([#1782](https://github.com/headroomlabs-ai/headroom/issues/1782))
([be51008](be51008c70))
* **transforms:** normalize diff compressor context
([#1801](https://github.com/headroomlabs-ai/headroom/issues/1801))
([838c523](838c5234a8))
* **transforms:** pass through ragged tables instead of misaligning
columns
([#1713](https://github.com/headroomlabs-ai/headroom/issues/1713))
([c7665ca](c7665ca088))
* use rtk native Cursor hook instead of injecting .cursorrules
([#756](https://github.com/headroomlabs-ai/headroom/issues/756))
([#1846](https://github.com/headroomlabs-ai/headroom/issues/1846))
([1573f1f](1573f1fd07))
* **wrap:** replace stale-proxy detection with Vite-style port fallback
([#1406](https://github.com/headroomlabs-ai/headroom/issues/1406))
([b4205c6](b4205c68e6))


### Performance Improvements

* **proxy:** cap compression workers to CPU count
([#1803](https://github.com/headroomlabs-ai/headroom/issues/1803))
([0a3851b](0a3851b240))
* **savings:** batch tracker persistence off the request hot path
([#1817](https://github.com/headroomlabs-ai/headroom/issues/1817))
([451b9f0](451b9f0867))


### Dependencies

* bump the cargo-minor-patch group across 1 directory with 7 updates
([#1909](https://github.com/headroomlabs-ai/headroom/issues/1909))
([45601d9](45601d93bc))
* bump the npm-minor-patch group across 4 directories with 18 updates
([#1907](https://github.com/headroomlabs-ai/headroom/issues/1907))
([8872bbc](8872bbc6a2))
</details>

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-07-09 07:47:54 -07:00
..
examples typescript coverage 2026-04-06 21:24:36 +06:00
src feat(telemetry): add headroom_stack and install_mode identity fields 2026-04-17 17:12:38 +02:00
test test(sdk/ts): add HEADROOM_WORKSPACE_DIR precedence tests for derived helpers 2026-04-16 19:59:38 -05:00
.gitignore Add TypeScript SDK (headroom-ai npm package) 2026-03-26 15:41:56 -07:00
package-lock.json deps: bump the npm-minor-patch group across 4 directories with 18 updates (#1907) 2026-07-09 09:38:37 -04:00
package.json chore: release main (#1918) 2026-07-09 07:47:54 -07:00
README.md chore: remove committed node_modules + stray/internal markdown (repo hygiene) (#1528) 2026-06-27 23:32:54 -07:00
tsconfig.json Add TypeScript SDK (headroom-ai npm package) 2026-03-26 15:41:56 -07:00
tsup.config.ts typescript coverage 2026-04-06 21:24:36 +06:00
vitest.config.ts Add TypeScript SDK (headroom-ai npm package) 2026-03-26 15:41:56 -07:00

headroom-ai

Compress LLM context. Save tokens. Fit more into every request.

Install

npm install headroom-ai

Quick Start

import { compress } from 'headroom-ai';

const result = await compress(messages, { model: 'gpt-4o' });
console.log(`Saved ${result.tokensSaved} tokens (${((1 - result.compressionRatio) * 100).toFixed(0)}%)`);

// Use compressed messages with any LLM client
const response = await openai.chat.completions.create({
  model: 'gpt-4o',
  messages: result.messages,
});

Requires a running Headroom proxy (headroom proxy).

Framework Adapters

Vercel AI SDK

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 });
Advanced: using middleware directly
import { headroomMiddleware } from 'headroom-ai/vercel-ai';
import { wrapLanguageModel } from 'ai';

const model = wrapLanguageModel({
  model: openai('gpt-4o'),
  middleware: headroomMiddleware({ baseUrl: 'http://localhost:8787' }),
});

OpenAI SDK

import { withHeadroom } from 'headroom-ai/openai';
import OpenAI from 'openai';

const client = withHeadroom(new OpenAI());
const response = await client.chat.completions.create({
  model: 'gpt-4o',
  messages: longConversation,
});

Anthropic SDK

import { withHeadroom } from 'headroom-ai/anthropic';
import Anthropic from '@anthropic-ai/sdk';

const client = withHeadroom(new Anthropic());
const response = await client.messages.create({
  model: 'claude-sonnet-4-5-20250929',
  messages: longConversation,
  max_tokens: 1024,
});

Google Gemini

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.

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)

const response = await client.chat.completions.create({
  model: 'gpt-4o',
  messages: longConversation,
  headroomMode: 'optimize',
});

Messages (Anthropic-style)

const response = await client.messages.create({
  model: 'claude-sonnet-4-5-20250929',
  messages: longConversation,
  max_tokens: 1024,
  headroomMode: 'optimize',
});

Direct Compression

const result = await client.compress(messages, { model: 'gpt-4o', tokenBudget: 4000 });

Simulation (Dry Run)

See what compression would do without calling the LLM.

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:

const sim = await client.chat.completions.simulate({
  model: 'gpt-4o',
  messages,
});

Compression Hooks

Customize compression with pre/post hooks — matching the Python CompressionHooks API.

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.

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.

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

// 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.

// 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.

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.

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.

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

import { compress } from 'headroom-ai';

const result = await compress(messages, {
  model: 'gpt-4o',
  baseUrl: 'http://localhost:8787',  // proxy URL
  apiKey: 'your-api-key',             // optional, for authenticated endpoints
  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
});

Or use environment variables:

  • HEADROOM_BASE_URL — proxy URL
  • HEADROOM_API_KEY — optional API key for authenticated endpoints

Utilities

// Case conversion for proxy communication
import { deepCamelCase, deepSnakeCase } from 'headroom-ai';

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';

// Hook helpers
import { extractUserQuery, countTurns, extractToolCalls } from 'headroom-ai';

License

Apache-2.0