TZRO

What's TZRO v2.1 STABLE

An ultra-lightweight, compiled native Go token shield and context optimization engine (<50 MB RAM, zero ML dependencies). It eliminates cloud API rate limits, locks KV-cache prompt prefixes (benchmarked at 70–99% cache read hit rates across 8 models), and provides sub-millisecond local codebase discovery.

The 12.5x Cache Miss Penalty & Context Explosion

Autonomous AI coding agents (Claude Code, Cursor, Antigravity, Aider, Cline) consume massive volumes of tokens during multi-turn developer interactions. In standard workflows:

  • Transient Tool Bloat: Directory listings, raw source files dumped for inspection, verbose build logs, repetitive stack traces, and JSON API payloads account for 60% to 90% of all tokens consumed.
  • Context Rot & Degradation: As contexts exceed 100k+ tokens, model reasoning degrades (~2% instruction-following loss per 100k tokens), leading to hallucinated APIs and lost system constraints.
  • The 12.5x KV-Cache Penalty: Major providers (Anthropic, OpenAI) offer a 90% discount on cached prompt prefixes (\(P_{\\text{read}} = 0.10 \\times P_{\\text{base}}\)), but penalize cache misses by charging a 25% surcharge for cache writes (\(P_{\\text{write}} = 1.25 \\times P_{\\text{base}}\)). A single unaligned byte or reordered tool schema invalidates the cache, making subsequent turns 12.5× more expensive ($1.25 vs $0.10).
  • Heavy ML Sidecar Bloat: Traditional context compression tools (e.g. Headroom) rely on Python runtimes and PyTorch models consuming 4.8 GB+ RAM with 60-second cold starts, rendering them unusable on standard developer laptops and CI runners.
🛡️
The Financial Shield

Prompt caching is the single highest-leverage economic mechanism in agentic coding. TZRO v2 guarantees prefix stability so that 70%–99% of your prompt tokens hit the provider's cached rate instead of triggering 12.5x write penalties.

Two-Plane Native Architecture

TZRO v2 operates across two synchronized planes that sit between your coding agent and upstream cloud providers:

⚡

1. The Passive Plane (Loopback Proxy :7878)

A high-throughput, transparent HTTP/HTTPS reverse proxy listening on 127.0.0.1:7878. It intercepts outgoing LLM calls, locks KV-cache prefixes in deterministic byte order, prunes source files via Tree-sitter AST, crushes uniform JSON into markdown tables, elides stack traces, and enforces Zero-Cloud DLP.

🔍

2. The Active Plane (Local Discovery & Compaction)

Deterministic, sub-millisecond local tools executed directly on your workstation: tzro probe (<5ms symbol search), tzro expand (on-demand body retrieval), tzro context (ranked task context assembly), tzro impact (pre-edit blast radius), and tzro compact (evidence contract compaction).

Data Flow Architecture
┌─────────────────────────────────────────────────────────────┐
│  Developer / Agent (Cursor, Claude Code, Antigravity, CLI)  │
└──────────────────────────────┬──────────────────────────────┘
                               │ (Transparent Loopback Proxy / CLI)
                               ▼
┌─────────────────────────────────────────────────────────────┐
│                 TZRO v2 LOCAL TOKEN SHIELD                  │
│                                                             │
│  1. KV-Cache Prefix Lock Guard (70-99% Cache Read Hit Rate)  │
│  2. Tree-Sitter AST Skeletonizer (70-90% Token Reduction)   │
│  3. Sub-Millisecond Local Discovery (`tzro probe`)          │
│  4. Local SQLite FTS5 Content-Hash Store (`tzro expand`)    │
│  5. Smart JSON Crusher & Stack Trace Elider                 │
│  6. Zero-Cloud DLP / Secret Masking                         │
│  7. Tabular Data Engine (`tzro ingest` / `tzro query`)      │
└──────────────────────────────┬──────────────────────────────┘
                               │ (Dense, High-Signal, Cache-Locked Payload)
                               ▼
┌─────────────────────────────────────────────────────────────┐
│           Cloud LLM Provider (Anthropic / OpenAI)           │
│           ~80% Token Reduction / Zero Rate Limits           │
└─────────────────────────────────────────────────────────────┘

Performance & Footprint Comparison

Unlike Python-based compression proxies that consume gigabytes of VRAM and minutes to start, TZRO v2 is a single static Go binary with zero external runtime dependencies:

Metric PyTorch Sidecars (e.g. Headroom) Unoptimized Agent Loops TZRO v2 (Token Shield)
System Memory (RAM) ~4.8 GB RAM N/A < 50 MB RAM (Native Go)
Cold Start Latency ~60 seconds 0 ms < 10 ms (Instant)
GPU Dependency Required for inference None Zero GPU required
Prompt Cache Stability Unstable (turn shifts) 12.5x miss penalties 70%–99% Cache Read Hits
Code Read Token Burn 0% (Full raw files) 0% (Full raw files) 70%–90% Reduction
Codebase Discovery 10 turns (~250k tokens) 10 turns (~250k tokens) 1 turn via tzro probe (<500 tok)

Quickstart & Agent Integration

TZRO connects seamlessly into your existing developer environment without changing your habits.

1
Single-Line Installation

Download and install the pre-compiled binary for your architecture (macOS arm64/x86_64, Linux):

Shell
curl -fsSL https://get.tzro.ai | sh

Or install from source with Go 1.22+ and SQLite FTS5:

Shell
CGO_ENABLED=1 go install ./cmd/tzro
2
Start the Token Shield Daemon

Launch the transparent loopback reverse proxy on port 7878:

Shell
# Start proxy daemon on port 7878:
tzro start --port 7878

# Inspect live status, shielded tokens, and memory footprint:
tzro status
3
Connect Your AI Coding Agents

Configure your agent clients to route API calls through http://127.0.0.1:7878:

Claude Code / Anthropic

Shell
export ANTHROPIC_BASE_URL=http://localhost:7878

Cursor / OpenAI / Aider / Cline

Shell
export OPENAI_BASE_URL=http://localhost:7878/v1

Antigravity Native Lifecycle Hooks

Add hook configuration to .agents/hooks.json or ~/.gemini/config/hooks.json to compact tool outputs natively:

JSON
{
  "tzro-token-shield": {
    "enabled": true,
    "PostToolUse": [
      {
        "matcher": "run_command",
        "hooks": [{ "type": "command", "command": "tzro hook compact" }]
      }
    ]
  }
}
💡
Automatic Setup

Run tzro init --hooks auto to automatically detect installed agent environments and configure hooks.

Core Token Shield Subsystems

1. KV-Cache Prefix Lock Guard

Modern frontier LLMs (Claude 3.5/3.7, GPT-4o, DeepSeek-V3) support prompt caching. However, cache hit rates are fragile: even a 1-byte difference in timestamp formatting, an reordered tool schema, or reordered system prompt invalidates the entire cache prefix, resulting in a 12.5x price increase for the turn.

The KV-Cache Prefix Lock Guard intercepts outgoing request payloads and enforces byte-for-byte prefix reproducibility:

  • Top-pins static system instructions, repository context (AGENTS.md), and tool declarations in deterministic byte order at the head of the payload.
  • Isolates dynamic turn variables (timestamps, ephemeral session tokens) to trailing user messages.
  • Benchmarked at 70%–85% cache hit rates in real agent workflows and up to 99% under controlled multi-turn evaluation across 8 models via OpenRouter.

2. Tree-Sitter AST Skeletonizer

When an agent reads a 2,000-line source file just to understand an interface or signature, sending the full file burns cloud tokens needlessly. TZRO's native C Tree-sitter parsers support 10 languages: Go, TypeScript, JavaScript, Python, Rust, Java, C/C++, Ruby, PHP, and C#.

The skeletonizer parses the AST, preserves package headers, imports, structs, interfaces, exported method signatures, and docstrings, while replacing function bodies with cryptographic hashes:

Go (Skeletonized)
package auth

// TokenClaims represents the JWT payload metadata.
type TokenClaims struct {
    UserID    string   `json:"sub"`
    Roles     []string `json:"roles"`
    ExpiresAt int64    `json:"exp"`
}

// ValidateToken verifies signature and expiry against current time.
func ValidateToken(raw string) (*TokenClaims, error) {
    // [body elided: #8f2a1c]
}

The full body is indexed in local SQLite FTS5. The agent can expand only the specific function body it needs to edit using tzro expand #8f2a1c, achieving a 70%–90% token reduction on file inspections.

3. Smart JSON Crusher & Stack Trace Elider

Smart JSON Crusher: Detects repetitive JSON objects (e.g. database query results or API lists) and flattens them into compact Markdown tables. Repeated keys that waste thousands of tokens are collapsed into table headers, slashing token consumption by up to 80%.

Stack Trace Elider: Strips internal framework and standard library stack frames from test failures and panics, preserving the root-cause assertion and user-code lines without context waste.

4. Zero-Cloud Data Loss Prevention (DLP)

Configured in .tzro/privacy.json, TZRO's on-device DLP policy engine protects sensitive credentials:

🔒

Automatic Secret Masking

Shannon entropy analysis and regex detectors identify API keys (sk-, ghp_, AKIA...), private keys, passwords, and private IP addresses before request egress.

🔄

Local Re-hydration

Masked placeholders are mapped in memory and re-hydrated locally into returned code diffs without exposure to third-party model providers.

Local Codebase Discovery & Retrieval

Sub-Millisecond Symbol Discovery (tzro probe)

Standard agents burn 5–10 turns and 250k+ cloud tokens scanning directories, reading files, and running greps to locate symbols. tzro probe replaces this with a single on-device call using embedded ripgrep and Tree-sitter AST queries in <5ms:

Shell
# Locate symbols, methods, and line ranges in <5ms:
tzro probe "jwt token validation"

Output returns exact line coordinates, symbol kinds, and body hashes:

Output
Found 1 match for "jwt token validation":
- ValidateToken (function in auth/jwt.go:45-78) [Hash: #8f2a1c]

Body Expansion & Line Slicing (tzro expand)

Retrieve only the specific function body or stored artifact lines needed:

Shell
# Expand an elided function body by hash:
tzro expand 8f2a1c

# Slice specific line ranges from stored artifacts:
tzro expand art_9503e3ba620ad4bf --lines 10-40

Search across code, architectural decision records (ADRs), product specs, design documents, logs, and stored artifacts in a single query with content-hash deduplication:

Shell
tzro search "rate limit token bucket"

Tabular Data & SQL Engine (tzro ingest / tzro query)

Dumping full CSV, TSV, or JSON data files into prompt context is an anti-pattern that burns tens of thousands of tokens. Import data into embedded SQLite and run targeted SQL queries:

Shell
# Import CSV file or pipe stdin:
tzro ingest metrics.csv --name daily_metrics
cat report.json | tzro ingest -

# Query data with read-only SQL:
tzro query daily_metrics "SELECT endpoint, COUNT(*), AVG(CAST(latency_ms AS REAL)) FROM daily_metrics GROUP BY endpoint"

Delivers 97%+ token reduction on tabular workloads by returning only computed query results.

Task Context & Change Impact

Task Context Assembly (tzro context)

Assembles a ranked, token-budgeted context pack containing relevant symbol definitions, AST call graphs, TypeScript path alias resolutions (tsconfig.json), and nearby test coverage in a single turn:

Shell
tzro context "implement rate limiting middleware" --budget 2000

Pre-Edit Change Impact Graph (tzro impact)

Before modifying shared utilities, interfaces, or types, analyze the structural blast radius:

Shell
# Analyze blast radius of specific files before editing:
tzro impact pkg/kvlock/kvlock.go

# Or analyze uncommitted git changes automatically:
tzro impact

Outputs direct callers, downstream dependent modules, and existing test suites that cover the affected call paths.

Agent Session Continuity (tzro session)

Eliminates transcript re-reading when handing off tasks across agents or resuming work after interruptions. Saves state to a portable, git-aware Schema v2 manifest:

Shell
# Save current agent task state:
tzro session save --objective "refactor proxy" --constraints "zero external deps"

# Check session freshness against git tree:
tzro session status

# Load session manifest in a new turn:
tzro session load .tzro/session.json

Evidence Contract Compactor (tzro compact --run)

Execute test and build commands through the compactor to enforce strict evidence contracts:

Shell
# Direct command execution with verified exit-code capture and 10-line inline cap:
tzro compact --run "go test -v ./..."

# Or pipe stdout directly:
go test ./... 2>&1 | tzro compact

Guarantees exit-code confidence, surfaces root-cause diagnostics within a 10-line inline cap, and stores complete failure logs in SQLite with an expansion hash.

Diagnostics & CLI Reference

System Doctor (tzro doctor)

Runs synthetic health checks across the proxy, upstream provider latency, SQLite FTS5 capability, and agent lifecycle hooks:

Shell
tzro doctor

Signal Density Benchmarking (tzro bench signal-density)

Empirically benchmark task signal density per token across optimization strategies with hard spend limit circuit breakers:

Shell
tzro bench signal-density --max-cost 1.50

CLI Command Matrix

Command Purpose Token Impact
tzro context "<task>" --budget <n> Assembles ranked context pack with AST & call graph Replaces 5–10 exploration turns (<2k tokens)
tzro impact [files...] Computes change-impact graph, callers, and tests before edits Prevents broken refactors and missing test runs
tzro probe "<query>" Fast local symbol discovery via ripgrep + Tree-sitter 0 cloud tokens (<500 tokens output)
tzro search "<query>" Unified search across code, specs, ADRs, logs, artifacts <500 tokens across heterogeneous sources
tzro skeleton <file> Skeletons code file, eliding function bodies into hashes 70%–90% token reduction
tzro expand <hash-or-art-id> Retrieves elided code body or stored artifact with line slices Fetches only required ~20 lines
tzro compact [--run "<cmd>"] Evidence compactor with exit code confidence, 10-line cap 80% token reduction on test/build logs
tzro session save / load Git-aware agent session manifest with freshness validation Eliminates full transcript re-reads
tzro ingest <file> Import CSV/TSV/JSON into SQLite, returns table pointer 97%+ token reduction on tabular data
tzro query <table> "<sql>" Execute read-only SQL against imported tabular data Fetches only query results
tzro start --port 7878 Launches transparent loopback reverse proxy Locks KV-cache prefix (70–99% hit rate)
tzro status Displays real-time shielded tokens, memory, and proxy metrics Diagnostic monitoring
tzro doctor Synthetic health check for proxy, routes, FTS5, and hooks Instant diagnostic verification
⚠️
Archived v1.0 Documentation Legacy Build

You are viewing archived documentation for TZRO v1, which focused on local model inference arbitrage (quantized 4B/1B GGUF models) and containerized task execution. For the modern, zero-dependency native Go Token Shield & Context Optimization Engine, switch to TZRO v2 Documentation.

TZRO v1: Local Inference Arbitrage v1.0 ARCHIVED

The original local task routing prototype. Offload execution-level agent work (file traversal, parsing, and execution) to a grammar-locked local GGUF engine to preserve cloud token budgets.

Intelligent Task Offloading

Today's agentic coding workflows are fragile. A cloud-only "generate-and-run" chat loop means every directory listing, every file parse, every grep runs through a frontier API — burning tokens, hitting daily rate limits, and freezing your workflow mid-task. This is token-maxing: feeding a $15/MTok model with work a local 3B can handle in milliseconds.

tzro implements Inference Arbitrage — the principle that the right model for the job is rarely the most expensive one. By routing execution-level work and even code generation to a grammar-locked local engine (via tzro_code), you preserve your cloud budget for what actually requires frontier reasoning: architectural planning, complex judgment, and interactive user dialogue.

💡
The Core Insight

Directory traversal, file parsing, JSON formatting, and database sync are routing decisions, not frontier reasoning. A 4-bit quantized 3B model handles them perfectly — at zero API cost.

The Cloud Plans, Local Executes

The division of labor is explicit and non-negotiable:

☁️

Cloud — The Planner

Handles non-sensitive abstract graph compilation. Generates DAG workflows, makes architectural decisions, synthesizes final outputs. This is where frontier reasoning lives.

⚙️

Local Go Engine — The Executor

Handles execution and code generation: directory indexing, file parsing, tool dispatch, database sync, source file generation with compilation validation, and structured output generation. All behind 127.0.0.1.

Dimension Cloud-Only Loop tzro Cooperative Model
Cost per file scan ~$0.02–$0.08 $0.00 (local)
Rate limit exposure High — daily freezes Near-zero for execution tasks
Data residency Code leaves premises 100% loopback — code never leaves
Execution durability Stateless — lost on disconnect Checkpointed in SQLite

The 5-Minute Plug-and-Play Quickstart

Zero habit change. tzro plugs directly into your existing client tools — Claude Code, Cursor, Windsurf, GitHub Copilot, OpenCode, or Antigravity IDE — via its transparent proxy (`tzro start`). You keep using your tools exactly as before; the proxy silently intercepts execution-level work and routes it locally.

1
Single-Line Bootstrap

One command provisions everything. No package manager, no dependency tree, no build step.

Shell
curl -fsSL https://get.tzro.ai | sh

Behind the scenes, the bootstrap script performs:

  • Provisions the ~/.tzro/ directory (bin/, cache/, models/)
  • Downloads the standalone tzro CLI binary
  • Fetches the worker model — Agents-A1 4B GGUF (~3 GB)
  • Fetches the router model — MiniCPM5 1B GGUF (~1.2 GB) for fast classification
  • Fetches the vision projector — mmproj F32 GGUF for multimodal input
  • Initializes the local SQLite state database (~/.tzro/tzro.db)
  • Bypasses macOS Gatekeeper quarantine on downloaded binaries
  • Adds ~/.tzro/bin to your $PATH via shell profile detection
📦
What Gets Installed

Total footprint: ~5 GB (3 models + binaries + DB). Everything lives in ~/.tzro/. No root access required. Uninstall is rm -rf ~/.tzro.

2
Transparent Proxy Setup

Run tzro start --port 7878 to launch the transparent proxy. Then simply point your AI client's API base URL to http://127.0.0.1:7878.

Shell
# Start the proxy in the background
tzro start --port 7878

You'll also be asked to select an integration tier that controls how aggressively agents delegate work to the local engine:

Tier Delegation Trigger Best For
Conservative 8+ sequential tool calls Testing the waters, sensitive workflows
Balanced (recommended) 3+ sequential tool calls Most developers — good cost/quality tradeoff
Aggressive 2+ sequential tool calls Maximum local execution, lowest cloud spend
⚡
Workspace Discovery

The proxy auto-discovers project structure, existing .agents/ configs, and any tzro.db state from prior runs.

3
Trigger a Discovery Query

With the transparent proxy running, your AI client can now execute CLI commands like tzro probe or tzro query to explore the codebase instantly. Try it:

Shell
# From Claude Code, Cursor, or any AI client connected to the proxy:
"Use tzro to build markdown documentation for this entire directory."

# Or directly via CLI:
tzro probe "architecture"

The local engine executes the discovery query via embedded ripgrep and Tree-sitter AST parsing in <5ms, returning exact file coordinates and symbol scopes with zero cloud tokens.

Local Security & Sandbox Transparency

We assume you're skeptical of running a local executable that intercepts AI tool calls. Good. Here's the complete security architecture — no hand-waving, no "trust us" appeals. Least-Privilege Security-by-Design at every layer.

Data Sovereignty

100% of code parsing, file edits, and tool manipulations remain local behind the loopback interface. Sensitive corporate data never leaves the premises.

🔒

Loopback-Only Binding

The MCP server binds exclusively to 127.0.0.1. No external network interfaces are exposed. Zero attack surface from outside the machine.

💾

Local SQLite State

All execution state, memory, and knowledge graph data persists in ~/.tzro/tzro.db — a single file on your disk. No cloud sync, no telemetry.

🛡️
Zero Telemetry Guarantee

tzrod makes exactly zero outbound network requests during normal operation. Model weights are fetched once during bootstrap. Everything else is local. Verify this yourself: sudo lsof -i -P | grep tzrod.

Containerized Execution

When tasks require code execution beyond simple file operations, TZRO dynamically orchestrates short-lived, task-scoped container sandboxes leveraging local Podman socket routes.

  • Ephemeral containers — spun up per-task, destroyed on completion. No persistent state leakage between executions.
  • Rootless Podman — no Docker daemon, no root access. Runs entirely in userspace via podman --rootless.
  • Resource-capped — each container is CPU/memory-limited to prevent runaway processes from impacting your development environment.
Shell
# How tzro spawns a sandboxed execution container:
podman run --rm --read-only \
  --network=none \
  --memory=512m --cpus=1.0 \
  -v /project:/workspace:ro \
  tzro-sandbox:latest \
  sh -c "$TASK_COMMAND"

Grammar Gating (GBNF)

For structured output calls — tool dispatch, classification, parameter extraction, and validator passes — the local LLM is constrained by logit-level GBNF grammar rules that mathematically prevent arbitrary command injection. These are the security-critical call sites where output format matters.

On constrained calls, the model's output is restricted strictly to predefined JSON schemas. It cannot produce output outside the grammar — this is enforced at the logit sampling level, not by post-hoc filtering. If the grammar says the output must be a JSON object with keys tool, args, and reasoning, then that is the only structure the model can physically produce. Free-form generation calls (synthesis, reasoning text) are not grammar-constrained.

GBNF Grammar
# Example: Tool dispatch grammar constraint
root   ::= "{" ws "\"tool\":" ws tool-name "," ws
             "\"args\":" ws json-object "," ws
             "\"reasoning\":" ws string ws "}"
tool-name ::= "\"read_file\"" | "\"list_dir\"" | "\"search_files\"" | "\"web_search\""
🔐
Why This Matters

Traditional LLM guardrails rely on prompt instructions ("don't run dangerous commands") which can be jailbroken. GBNF constraints are mathematical — the model literally cannot emit tokens outside the defined grammar. It's the difference between asking someone nicely not to open a door and welding the door shut.

Network Isolation

Mounted target repositories default to read-only parameters, and network interfaces inside execution containers are entirely decoupled (network=none) to block supply-chain leaks.

  • Read-only mounts — project directories are mounted with :ro flag by default. Write access requires explicit opt-in via task configuration.
  • Network decoupled — containers run with --network=none. No DNS resolution, no HTTP requests, no exfiltration vector.
  • No package installation — containers have no access to package registries. No npm install, no pip install, no supply-chain attacks.

Local Hardware Optimization

Running a local LLM sidecar will not freeze your laptop or disrupt your multitasking workflow. Here's exactly how we ensure that.

💻
Target Hardware Profile

tzrod is optimized for standard developer laptops — 16 GB RAM, 8-core CPU, no dedicated GPU required. The 4-bit quantized Qwen-3B model uses ~1.8 GB RAM at inference time.

Speculative Decoding

tzrod uses n-gram speculative decoding forward-projections to speed up local 3B–4B generation velocities by 1.8× on standard CPUs.

The technique works by maintaining a rolling n-gram cache of recently generated token sequences. When the model begins generating a new sequence, the speculative decoder proposes multiple candidate continuations in parallel based on n-gram frequency statistics. The main model then verifies these candidates in a single forward pass — accepting correct predictions for free and rejecting mismatches with zero wasted compute.

⚡

1.8× Throughput Boost

Measured on Apple M-series and Intel i7/i9 CPUs. JSON-structured output (tool dispatch) benefits most due to predictable token patterns.

🧠

Zero Quality Loss

Speculative decoding is mathematically lossless. Accepted predictions produce identical output to standard autoregressive generation.

Warm KV Prefix-Sharing

System prompts and tool schemas are pin-locked into KV Cache slot 0, eliminating redundant compilation on every request. The result: compilation times consistently under <100ms.

When tzrod starts, it pre-compiles the system prompt, all registered tool schemas, and the GBNF grammar into a persistent KV Cache prefix. This prefix is shared across all subsequent inference calls without re-processing. Only the user-specific context (task prompt, file contents, intermediate outputs) needs fresh computation.

Architecture
┌─────────────────────────────────────────────────────────┐
│  KV Cache Slot 0 (pin-locked, persistent)               │
│  ├── System Prompt          ~420 tokens                  │
│  ├── Tool Schemas (26 tools) ~1,800 tokens               │
│  └── GBNF Grammar           ~200 tokens                  │
├─────────────────────────────────────────────────────────┤
│  KV Cache Slot 1 (dynamic, per-request)                 │
│  ├── Task Prompt                                        │
│  ├── File Contents / Context                            │
│  └── Intermediate Outputs                               │
└─────────────────────────────────────────────────────────┘

Zero-Latency Attention Preemption

The AttentionScheduler instantly pauses background processing tasks and dumps their state to disk ($slot_0.bin) the exact millisecond a user triggers a foreground prompt.

This ensures an interactive foreground Time-to-First-Token (TTFT) of ≤ 450ms — regardless of how many background DAG nodes are currently executing. Your interactive coding session is never degraded by background work.

🎯
How Preemption Works

When a foreground prompt arrives, the AttentionScheduler: (1) signals the active background inference to yield, (2) serializes its KV state to $slot_0.bin, (3) loads the foreground context into the attention buffer, and (4) generates the response. Once the foreground response is complete, the background task resumes from its serialized state with zero recomputation.

Metric Without Preemption With AttentionScheduler
Foreground TTFT 2–8s (waits for background) ≤ 450ms (instant preempt)
Background state loss Full recomputation Zero — state serialized
Context switch overhead N/A ~30ms (KV dump + load)

Debugging & Visibility

Cooperative execution trades wall-clock latency for extreme cost savings — pennies vs. multi-dollar cloud bills. We don't pretend this is free. What we do provide is total visibility into what the background engine is doing, so you always know it isn't hanging.

Fullscreen TUI Dashboard

Launch the interactive terminal dashboard to visualize parallel Kahn Topological Sort execution levels, node states, and real-time progress:

Shell
tzro tui

The Bubble Tea TUI shows:

  • DAG visualization — nodes rendered by topological level with dependency edges
  • Node status — pending, running, completed, failed, or skipped (with color coding)
  • Live output streaming — real-time stdout from actively executing nodes
  • Resource metrics — CPU, memory, and token generation throughput

Token Tracking & Benchmark Comparison

Every task execution carries a TokenTracker embedded in its Go context, separately accumulating local and cloud token usage (prompt, completion, duration, tokens/sec) across all inference calls within that task. This infrastructure powers the offline benchmark comparison suite.

Shell — Benchmark Comparison
# Run the comparison suite against a specific task category
tzro compare --category docgen --output ./results/

# Example per-task output:
  ✓ 3500 cloud tokens, 8200 local tokens, $0.0525, 14200ms, 12 tool calls

# Summary output:
Cloud token savings (ReAct → Cooperative): 72%
Cost savings: $0.5250 → $0.1470 (saved $0.3780)

The comparison harness runs each benchmark task under multiple conditions and attributes savings into three independently measured buckets:

Savings Bucket What It Measures Formula
DAG structural Savings from parallelization and topological compilation cloud_react − cloud_dag_raw
Pipeline compaction Savings from the 5-layer compaction pipeline cloud_dag_raw − cloud_dag
Local offloading Savings from routing execution to the local model cloud_dag − cooperative
📊
Benchmark-Only Instrumentation

Cost attribution is computed post-hoc by the comparison report generator using cross-condition deltas — it is not embedded in per-task production output. Token tracking is always active, but dollar-cost estimation is only surfaced through the tzro compare CLI and the generated markdown reports.

Logs & Compliance Audit

For debugging execution issues or generating compliance documentation:

Shell
# Live engine logs — see every tool dispatch, node transition, and error
tail -f ~/.tzro/logs/engine.log

# Generate a compliance audit report (HTML) for security review
tzro audit --compliance-html

# Inspect a specific task execution trace
tzro task status <taskId> --offline

The compliance audit generates a standalone HTML document covering:

  • Data flow attestation — proof that no data left loopback during the session
  • Tool execution log — every tool invoked, arguments passed, and outputs returned
  • Grammar constraint verification — confirmation that all LLM outputs matched GBNF schemas
  • Container lifecycle audit — creation, execution, and teardown timestamps for all sandboxes
⚠️
Latency Expectations

Local execution prioritizes cost savings over wall-clock speed. A task that takes 3 seconds on a frontier API might take 12–18 seconds locally on a 3B model. The tradeoff: that 3-second cloud call costs $0.08–$0.25. The local run costs $0.00 and doesn't count against your rate limit.