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


<details><summary>0.27.0</summary>

##
[0.27.0](https://github.com/chopratejas/headroom/compare/v0.26.0...v0.27.0)
(2026-06-22)


### Features

* **cli:** add headroom doctor setup diagnostics
([#926](https://github.com/chopratejas/headroom/issues/926))
([e45cf4e](e45cf4e061))
* **cli:** add headroom update command and release banner
([#1088](https://github.com/chopratejas/headroom/issues/1088))
([26be2c3](26be2c39cb))
* compression extraction — Rust knob exposure, CCR hardening, traffic
audits ([#818](https://github.com/chopratejas/headroom/issues/818))
([b7be381](b7be3814f1))
* measure and surface token throughput (tokens/sec) through the proxy
([#983](https://github.com/chopratejas/headroom/issues/983))
([0d89c67](0d89c674cd))
* output-token reduction — verbosity shaper, per-user learning,
counterfactual savings
([#965](https://github.com/chopratejas/headroom/issues/965))
([a99dc61](a99dc61424))
* **policy:** decay P_alive from idle time near cache TTL
([#856](https://github.com/chopratejas/headroom/issues/856) P3b)
([#1028](https://github.com/chopratejas/headroom/issues/1028))
([fe4f9ee](fe4f9ee478))
* **providers:** add Cortex Code (Snowflake CoCo) as a supported agent
([#1190](https://github.com/chopratejas/headroom/issues/1190))
([d9d0bf4](d9d0bf4b79))
* **proxy:** cc-switch reconciler — keep Headroom in the request path
alongside cc-switch
([#1030](https://github.com/chopratejas/headroom/issues/1030))
([e8fc8a0](e8fc8a0d18))
* **proxy:** hot-reload live env knobs so a reused proxy picks them up
without a restart
([#1090](https://github.com/chopratejas/headroom/issues/1090))
([6904d47](6904d47a01))
* **proxy:** make COMPRESSION_TIMEOUT_SECONDS configurable via env
([#946](https://github.com/chopratejas/headroom/issues/946))
([#991](https://github.com/chopratejas/headroom/issues/991))
([addebdb](addebdb29c))
* **transforms:** tabular + spreadsheet (.xlsx/.xls) compression
([#1128](https://github.com/chopratejas/headroom/issues/1128))
([d789a7c](d789a7c528))
* **vertex:** turnkey Claude Code + Vertex compression (+ fixes from the
Vertex review)
([#1113](https://github.com/chopratejas/headroom/issues/1113))
([0e05915](0e0591506c))


### Bug Fixes

* **ccr:** accept 12-char SmartCrusher hashes in tool injection
([#1095](https://github.com/chopratejas/headroom/issues/1095))
([#1141](https://github.com/chopratejas/headroom/issues/1141))
([9f7f3ad](9f7f3adfea))
* **ccr:** return stored content when headroom_retrieve query matches
nothing ([#1213](https://github.com/chopratejas/headroom/issues/1213))
([#1236](https://github.com/chopratejas/headroom/issues/1236))
([08fb845](08fb845fe3))
* **content-router:** honor target_ratio in compression cache + add
proxy --target-ratio flag
([#1108](https://github.com/chopratejas/headroom/issues/1108))
([8894ee0](8894ee0c18))
* **dashboard:** light-mode backgrounds + aligned savings tables
([#1064](https://github.com/chopratejas/headroom/issues/1064))
([5eae32b](5eae32ba47))
* **deps:** make litellm optional on Python 3.14
([#956](https://github.com/chopratejas/headroom/issues/956))
([#993](https://github.com/chopratejas/headroom/issues/993))
([b2f04e4](b2f04e4ef7))
* **e2e:** align Codex wrap e2e with global-only RTK guidance
([#1240](https://github.com/chopratejas/headroom/issues/1240))
([#1254](https://github.com/chopratejas/headroom/issues/1254))
([bc12ace](bc12acef59))
* **init:** set ENABLE_TOOL_SEARCH=true so Claude Code keeps deferring
tools ([#746](https://github.com/chopratejas/headroom/issues/746))
([#995](https://github.com/chopratejas/headroom/issues/995))
([500ec2b](500ec2b7fa))
* **kompress:** never block the request path on the cold-cache model
download ([#1161](https://github.com/chopratejas/headroom/issues/1161))
([3fc2a78](3fc2a78a5e))
* **memory:** use ONNX embedder for `wrap --memory` sync
([#1092](https://github.com/chopratejas/headroom/issues/1092))
([#1262](https://github.com/chopratejas/headroom/issues/1262))
([4f9feda](4f9fedaa7a))
* **openclaw:** wrap plugin export as {register} object for OpenClaw
2026.x compatibility
([#1218](https://github.com/chopratejas/headroom/issues/1218))
([2e6c442](2e6c442dc8))
* **providers:** update DeepSeek V3 context limit from 128K to 1M
([#1038](https://github.com/chopratejas/headroom/issues/1038))
([#1137](https://github.com/chopratejas/headroom/issues/1137))
([bcabc5c](bcabc5cb11))
* **proxy:** allow disabling periodic TOIN stats logging
([#1265](https://github.com/chopratejas/headroom/issues/1265))
([b5f63d8](b5f63d8fa9))
* **proxy:** honor HEADROOM_EXCLUDE_TOOLS for Codex /v1/responses tool
outputs ([#940](https://github.com/chopratejas/headroom/issues/940))
([#1053](https://github.com/chopratejas/headroom/issues/1053))
([f03e77b](f03e77bec0))
* **proxy:** preserve byte-faithful Anthropic tool forwarding
([#1222](https://github.com/chopratejas/headroom/issues/1222))
([1f18d59](1f18d59809))
* **proxy:** route Codex OAuth image requests
([#1215](https://github.com/chopratejas/headroom/issues/1215))
([381d771](381d771e46))
* **proxy:** scope CORS to loopback + gate operator/content endpoints
([#1226](https://github.com/chopratejas/headroom/issues/1226))
([bd55a42](bd55a426bc))
* **proxy:** stamp X-Client: codex on Responses endpoint for
unidentified callers
([#1036](https://github.com/chopratejas/headroom/issues/1036))
([b0cd032](b0cd0329c7))
* **proxy:** treat NODE_EXTRA_CA_CERTS as additive, not replacement
([#998](https://github.com/chopratejas/headroom/issues/998))
([#1031](https://github.com/chopratejas/headroom/issues/1031))
([c987283](c98728363a))
* **telemetry:** switch anonymous telemetry to opt-in (off by default)
([#1223](https://github.com/chopratejas/headroom/issues/1223))
([b998697](b99869778b))
* **tokenizers:** bound tiktoken vocab load so a stalled download cannot
hang requests
([#956](https://github.com/chopratejas/headroom/issues/956))
([#994](https://github.com/chopratejas/headroom/issues/994))
([7e86baf](7e86bafb90))
* **unwrap:** remove ANTHROPIC_BASE_URL + ENABLE_TOOL_SEARCH and init
hooks on unwrap
([#992](https://github.com/chopratejas/headroom/issues/992))
([5b84691](5b84691770))
* **wrap:** keep Codex RTK guidance global
([#1240](https://github.com/chopratejas/headroom/issues/1240))
([7c26a54](7c26a54d53))
* **wrap:** percent-encode non-ASCII cwd names in X-Headroom-Project
header ([#1071](https://github.com/chopratejas/headroom/issues/1071))
([9f712cc](9f712ccbd7))
* **wrap:** write env.ANTHROPIC_BASE_URL to settings.json so
daemon-spawned conversations inherit proxy
([#951](https://github.com/chopratejas/headroom/issues/951))
([#1078](https://github.com/chopratejas/headroom/issues/1078))
([a554c3a](a554c3a0e6))
</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-21 22:28:55 -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 the npm_and_yarn group across 3 directories with 3 updates (#1056) 2026-06-16 23:07:34 -07:00
package.json chore: release main (#1274) 2026-06-21 22:28:55 -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