Contex Compiler v0.2.0-beta • Internal Reference Manual

TensLab Developer Docs

Internal reference guide to integrating Contex Context Compiler (@tens-lab/core), drop-in middleware, 12 adaptive codecs, WASM Rust core, and CLI tools. Currently in closed private beta.

Overview

Introduction

TensLab (Contex Compiler) is a token-aware structural context compiler for AI applications and Retrieval-Augmented Generation (RAG) pipelines. It intercepts raw structured data (JSON search results, database rows, IT tickets, candidate records, e-commerce orders) before it reaches LLM APIs.

By stripping structural JSON syntax noise ({}, [], "key":, quotes, colons, commas) into single-declaration schemas (@schema, @dict, @enum, @time), Contex slashes prompt tiktoken spend by 76% median (up to 96% in multi-turn loops) while preserving 100% factual retrieval recall.

Why Flat JSON Breaks LLM Context Windows
In standard LLM REST payloads, structural JSON syntax overhead accounts for 40% to 70% of total prompt BPE tokens. Every repeated key string like "estimate_hours" or "current_company" across 100 RAG search rows burns thousands of unnecessary input tokens. Contex declares schema keys once in a single preamble.
Product Architecture

The Dual-Format Engine Pipeline

TensLab operates a two-layer context format architecture designed for standard LLM REST text APIs and local WASM binary persistence:

LLM TEXT FORMAT
Contex Compact Prompt
Token-optimized text payload sent directly over HTTP REST APIs to OpenAI (GPT-4o, o3-mini), Anthropic (Claude 3.5), and Gemini. Strips JSON syntax into clean tab-separated schemas.
76% Median Token Cut
LOCAL WASM CODEC
TENS IR Binary Stream
High-density WebAssembly binary IR byte stream (0x54 0x45 0x4E 0x53 ...) used locally inside Node.js, browser WASM modules, and disk storage at 149μs/row.
149 μs / row latency
Ecosystem

Monorepo Package Suite

The TensLab monorepo consists of 5 modular TypeScript & Rust packages under the @tens-lab/* scope:

Package Name Type Description Version
@tens-lab/core TypeScript SDK Main compiler engine (compile()), schema registry, and Contex Compact formatters. v0.2.0
@tens-lab/middleware Wrapper SDK Drop-in client wrapper for OpenAI, Anthropic, Gemini, and Llama 3 SDKs. v0.2.0
@tens-lab/wasm Rust WASM Core Native WebAssembly compilation layer (contex.rs) for ultra-fast local binary encoding. v0.2.0
@tens-lab/cli Terminal Tool CLI diagnostic tool (npx @tens-lab/cli doctor) for prompt token audits. v0.2.0
Core SDK

Core Compiler API (@tens-lab/core)

The compile() function is the primary entry point for compiling structured RAG datasets into Contex Compact format.

compile_rag_tickets.ts
import { compile } from '@tens-lab/core'

// 1. Raw RAG dataset (e.g. IT support tickets returned from vector database)
const rawTickets = [
  { id: 1, title: 'Login page unresponsive', status: 'open', priority: 'critical', assignee: 'alice' },
  { id: 2, title: 'API rate limiting bug', status: 'in_progress', priority: 'high', assignee: 'bob' }
]

// 2. Compile into Contex Compact format for GPT-4o tiktoken optimization
const compactPrompt = compile(rawTickets, {
  model: 'gpt-4o',
  format: 'contex'
})

console.log(compactPrompt)
// Output:
// @dict 0:critical 1:alice 2:bob
// @schema id  title  status  priority  assignee
// 1  Login page unresponsive  open  @0  @1
// 2  API rate limiting bug  in_progress  high  @2
Compression Engine

12-Layer Adaptive Codec Pipeline

Contex automatically analyzes data shapes in real time and applies optimal codec combinations:

CODEC N1
N1 TAP (Token-Aware Parser)
Strips JSON curly braces, quotes, and colons into single-declaration schemas.
40–60% Token Cut
CODEC N2
N2 Semantic Dedup
Extracts frequent string values into global dictionary index preambles (@dict).
65–75% Token Cut
CODEC N3
N3 Null Elision
Replaces sparse missing or null cells with lightweight underscore markers (_).
50–70% Token Cut
CODEC N5
N5 Enum Compactor
Compresses column-level string enumerations into single-letter key aliases (@enum).
60–80% Token Cut
CODEC X1
X1 Context Chains
Sends only state deltas across multi-turn conversation loops rather than re-sending full history.
96.0% Token Cut
CODEC X2
X2 Semantic Diffing
Tracks meaning-aware change vectors (@sdiff) across concurrent agent swarms.
85–95% Token Cut
Specification

Contex Compact Format Grammar

The Contex Compact format follows a strict, token-optimized grammar designed for LLM text tokenizers:

contex_spec_v3.1.txt
# Contex Compact Spec Grammar v3.1
@time  <column_name>=<iso_timestamp_anchor>
@enum  <column_name>: A=<val_1> B=<val_2> C=<val_3>
@repeat <column_name>=<val> x<count> <delta_diffs>
@dict  0:<frequent_val_0> 1:<frequent_val_1> 2:<frequent_val_2>
@schema <key_1> <key_2> <key_3> ... <key_N>
<val_11> <val_12> <val_13> ... <val_1N>
<val_21> <val_22> <val_23> ... <val_2N>
Integration

Drop-in Middleware (@tens-lab/middleware)

Install and wrap standard OpenAI, Anthropic, or Gemini SDK initialization without changing your application code:

npm install @tens-lab/middleware @tens-lab/core
openai_middleware_wrapper.ts
import createClient from '@tens-lab/middleware'

const client = createClient({
  provider: 'openai',
  apiKey: process.env.OPENAI_API_KEY,
  compress: true, // Enables automatic WASM Contex compilation
})

const response = await client.chat.completions.create({
  model: 'gpt-4o',
  messages: [
    { role: 'user', content: 'Your raw RAG context here' }
  ]
})
WebAssembly

Rust WASM Core Engine (@tens-lab/wasm)

High-speed Rust WebAssembly compilation layer (contex.rs) enabling 149μs per-row binary serialization:

contex.rs
use contex_core::TensEncoder;

pub fn encode_rag_payload(data: &str) -> Result<Vec<u8>, TensError> {
    let encoder = TensEncoder::new();
    let binary_stream = encoder.encode_json(data)?;
    Ok(binary_stream)
}
CLI Diagnostics

CLI Terminal Doctor (@tens-lab/cli)

Run instant diagnostic token audits on your local prompt files:

npx @tens-lab/cli doctor ./data/sample_tickets.json
Security

WASM Privacy Guarantee

Contex executes 100% locally inside your Node.js or browser process. Your data never touches TensLab servers or external proxies.

Zero Network Proxy Overhead
Unlike third-party LLM gateways that route your API traffic through remote servers, TensLab operates as an in-process WASM library. Zero network latency added.
Support

FAQ & Troubleshooting

Q: Does Contex Compact format affect reasoning accuracy?
A: No. In 100% Needle-in-a-Haystack benchmarks evaluated on Llama 3.1 70B and GPT-4o, Contex format achieved 100% exact factual recall parity.

Q: Which models are supported?
A: All text-based LLMs including GPT-4o, o3-mini, Claude 3.5 Sonnet, Gemini 2.0 Flash, DeepSeek R1, and Llama 3.