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


<details><summary>0.26.0</summary>

##
[0.26.0](https://github.com/chopratejas/headroom/compare/v0.25.0...v0.26.0)
(2026-06-16)


### Features

* add Copilot BYOK provider wrapper utilities and CLI support
([#1041](https://github.com/chopratejas/headroom/issues/1041))
([e67ee2a](e67ee2af65))
* add dashboard agent usage stats
([#814](https://github.com/chopratejas/headroom/issues/814))
([6d3f39f](6d3f39f213))
* Add support for Mistral Vibe CLI
([#935](https://github.com/chopratejas/headroom/issues/935))
([0932b8b](0932b8bef4))
* attribute reread waste to over-compression via marker check
([#901](https://github.com/chopratejas/headroom/issues/901))
([f928576](f9285766dd))
* **bedrock:** cross-region + Converse compression; bundle proxy binary
in images ([#999](https://github.com/chopratejas/headroom/issues/999))
([0dc2e1c](0dc2e1cb3f))
* **dashboard:** surface compression-vs-cache net impact in Prefix Cache
panel ([#913](https://github.com/chopratejas/headroom/issues/913))
([2a4d300](2a4d300841))
* **evals:** adversarial-input robustness grid for compressors
([#918](https://github.com/chopratejas/headroom/issues/918))
([5939004](5939004185))
* **parser:** detect re-issued identical tool calls as reread waste
([#909](https://github.com/chopratejas/headroom/issues/909))
([7d4ae86](7d4ae86ec0))
* **policy:** batch deep edits through one cache-bust
([#856](https://github.com/chopratejas/headroom/issues/856) P3a)
([#1015](https://github.com/chopratejas/headroom/issues/1015))
([c2e52fe](c2e52fe743))
* **policy:** consume net-cost mutation gate in ContentRouter
([#856](https://github.com/chopratejas/headroom/issues/856) P2)
([#905](https://github.com/chopratejas/headroom/issues/905))
([553ade4](553ade4ec6))
* **proxy:** compress AWS Bedrock InvokeModel requests via configurable
upstream ([#720](https://github.com/chopratejas/headroom/issues/720))
([7edb27a](7edb27ab24))


### Bug Fixes

* **anthropic:** strip styled Claude model ids
([#651](https://github.com/chopratejas/headroom/issues/651))
([0c5c89d](0c5c89d05c))
* **anyllm:** forward openai api_base/api_key to the any-llm backend
([#942](https://github.com/chopratejas/headroom/issues/942))
([#954](https://github.com/chopratejas/headroom/issues/954))
([a7ee8a6](a7ee8a60a7))
* **cache:** guard None exemplar embeddings in dynamic detector
([#950](https://github.com/chopratejas/headroom/issues/950))
([1ec9320](1ec9320888))
* **cache:** name the missing piece in semantic detector guard
([#1018](https://github.com/chopratejas/headroom/issues/1018))
([3b0bcee](3b0bceecf4))
* **ci:** check out repo in PR Governance label job
([#1021](https://github.com/chopratejas/headroom/issues/1021))
([4558bc2](4558bc2465))
* **ci:** make PR governance advisory
([#1047](https://github.com/chopratejas/headroom/issues/1047))
([74dff94](74dff94fb8))
* **codex:** compute waste signals on the OpenAI Responses path
([#898](https://github.com/chopratejas/headroom/issues/898))
([b9e2761](b9e27614c6))
* **codex:** poll /wham/usage for subscription limits (handshake no
longer sends x-codex-* headers)
([#924](https://github.com/chopratejas/headroom/issues/924))
([8c00f71](8c00f7103c))
* **codex:** PR health label check state
([#986](https://github.com/chopratejas/headroom/issues/986))
([99c874d](99c874d423))
* **codex:** retag thread providers so history menu stays whole across
the proxy boundary
([#1034](https://github.com/chopratejas/headroom/issues/1034))
([74ae781](74ae781644))
* **codex:** write canonical hooks feature flag and migrate deprecated
codex_hooks ([#743](https://github.com/chopratejas/headroom/issues/743))
([dff6a19](dff6a19946))
* **compression:** convert tree-sitter byte offsets to char offsets
([#892](https://github.com/chopratejas/headroom/issues/892))
([b1f700f](b1f700fc27))
* **compression:** correct JSON array item counting and entropy gate
([#887](https://github.com/chopratejas/headroom/issues/887))
([d6f0f0f](d6f0f0f642))
* **compression:** keep container bodies compressible in code handler
([#890](https://github.com/chopratejas/headroom/issues/890))
([16ed73b](16ed73bca6))
* **compression:** measure short-value threshold on payload, not token
([#889](https://github.com/chopratejas/headroom/issues/889))
([65b0e8c](65b0e8c58d))
* **compression:** use thread-local tree-sitter parsers in code handler
([#893](https://github.com/chopratejas/headroom/issues/893))
([6cdb846](6cdb846200))
* **gemini:** surface functionResponse payloads to waste-signal
detection ([#897](https://github.com/chopratejas/headroom/issues/897))
([9b0c840](9b0c840dd7))
* **learn:** decode directory names with spaces in Windows project paths
([#997](https://github.com/chopratejas/headroom/issues/997))
([#1027](https://github.com/chopratejas/headroom/issues/1027))
([2d3701b](2d3701b59e))
* **learn:** scan subagent and workflow transcripts
([#1045](https://github.com/chopratejas/headroom/issues/1045))
([0ddd4ed](0ddd4ed9e9))
* **openclaw:** declare headroom_retrieve tool contract
([#947](https://github.com/chopratejas/headroom/issues/947))
([7c8c909](7c8c909c85))
* **policy:** correct warm-cache penalty in net_mutation_gain to (S +
dT) ([#903](https://github.com/chopratejas/headroom/issues/903))
([0632eba](0632eba6c3))
* **proxy:** add native Bedrock converse-stream route
([#917](https://github.com/chopratejas/headroom/issues/917))
([b08ec15](b08ec15b0d))
* **proxy:** keep codex image-generation WS turns alive through the
relay ([#1000](https://github.com/chopratejas/headroom/issues/1000))
([7dbbb40](7dbbb4077e))
* **proxy:** make budget enforcement actually work
([#885](https://github.com/chopratejas/headroom/issues/885))
([a14ab45](a14ab45cf0))
* **proxy:** read RTK gain stats globally by default
([#957](https://github.com/chopratejas/headroom/issues/957))
([b70fccb](b70fccbe17))
* route v1internal code assist requests to cloudcode-pa.googleapis…
([#821](https://github.com/chopratejas/headroom/issues/821))
([e20f16b](e20f16b1a6))
* **serena:** stop the Serena dashboard popup and make --no-serena
actually disable Serena
([#1003](https://github.com/chopratejas/headroom/issues/1003))
([919379a](919379a8a1))
* support Copilot Business subscription auth
([#641](https://github.com/chopratejas/headroom/issues/641))
([0b4a4bd](0b4a4bd483))
* wire HEADROOM_EXCLUDE_TOOLS / HEADROOM_TOOL_PROFILES into Click proxy
entrypoint ([#943](https://github.com/chopratejas/headroom/issues/943))
([9b7b436](9b7b436b04))
* **wrap:** avoid duplicate top-level keys when injecting codex provider
([#884](https://github.com/chopratejas/headroom/issues/884))
([dd22cfd](dd22cfd72a))


### Code Refactoring

* DRY cache logic, add thread safety, fix Bash exclusion
([#704](https://github.com/chopratejas/headroom/issues/704))
([e36fccd](e36fccd8cf))
</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-06-16 15:35:00 -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 ci: bump esbuild from 0.27.7 to 0.28.1 in /docs in the npm_and_yarn group across 1 directory (#936) 2026-06-12 23:16:29 -05:00
package.json chore: release main (#931) 2026-06-16 15:35:00 -07:00
README.md typescript coverage 2026-04-06 21:24:36 +06: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) or Headroom Cloud API key.

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',  // or https://api.headroom.ai
  apiKey: 'hr_...',                   // for Headroom Cloud
  timeout: 30000,                     // ms
  fallback: true,                     // return uncompressed if proxy is down (default)
  retries: 1,                         // retry on transient failures (default)
  tokenBudget: 4000,                  // compress to fit this limit
  hooks: new MyHooks(),               // pre/post compression hooks
});

Or use environment variables:

  • HEADROOM_BASE_URL — proxy/cloud URL
  • HEADROOM_API_KEY — Cloud API key

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