ai-tools
5 min read 2

Inside AdiClaw: How I Built a Custom Inference Engine to Make Local AI Coding 10x Faster

A deep dive into Time-To-First-Token (TTFT) pre-warming, invariant prompt prefix caching, turn delta compression, and Apple Silicon Metal GPU acceleration for autonomous AI agents.

The Latency Trap in Modern AI Coding Assistants

If you have ever used an AI coding assistant in your terminal, you know the frustration of the “thinking freeze”:

  • You submit a quick question or a code change goal.

  • The CLI hangs for 3 to 6 seconds before a single word appears.

  • As the conversation continues across 5, 10, or 20 tool-calling turns, every single turn becomes progressively slower and more expensive.

  • Worse yet, if you attach real-world tools—like GitHub Model Context Protocol (MCP) servers, YouTube analytics, and local filesystem tools—the prompt balloons to thousands of tokens before your query is even evaluated.

Most CLI tools treat inference as a dumb pipe: take a prompt, ship it to an API endpoint or local runner, wait for the response, and dump it to stdout.

When building AdiClaw—an autonomous, sandboxed AI CLI coding assistant featuring in-memory staging and human-in-the-loop diff approvals—I realized that treating inference as a passive API call was the bottleneck. To build a tool that feels instantaneous, intelligent, and production-ready on local hardware, I needed to build a dedicated Inference Engine under the hood.

Here is the story of how I designed and implemented the AdiClaw Inference Engine from scratch.


The Architectural Blueprint

Instead of allowing high-level agent modes (Agent, Plan, Ask) to talk directly to model providers, the AdiClaw Inference Engine sits squarely in the middle as an intelligent orchestration and acceleration layer:

                        User Goal / Request
                                 │
                                 ▼
                     ┌───────────────────────┐
                     │   CLI Sub-Mode Router │
                     │  (Agent | Plan | Ask) │
                     └───────────┬───────────┘
                                 │
                                 ▼
                     ┌───────────────────────┐
                     │ AdiClaw Inference     │
                     │ Engine & Optimizer    │
                     │ - TTFT Pre-Warming    │
                     │ - Prefix Caching      │
                     │ - Turn Delta Compress │
                     │ - Metal GPU Offload   │
                     └───────────┬───────────┘
                                 │
         ┌───────────────────────┼───────────────────────┐
         ▼                       ▼                       ▼
 ┌───────────────┐       ┌───────────────┐       ┌───────────────┐
 │ Local Ollama  │       │  llama.cpp    │       │  OpenRouter   │
 │ (Metal / GPU) │       │ (Local GGUF)  │       │ (Cloud API)   │
 └───────┬───────┘       └───────┬───────┘       └───────┬───────┘
         │                       │                       │
         └───────────────────────┼───────────────────────┘
                                 ▼
                    ┌─────────────────────────┐
                    │ ToolExecutor (Staging)  │
                    │ - In-Memory Overlay     │
                    │ - Append-Only Tracker   │
                    └────────────┬────────────┘
                                 │
                                 ▼
                    ┌─────────────────────────┐
                    │   Interactive Review    │
                    │  (@clack/prompts + Diff)│
                    └────────────┬────────────┘
                                 │
                        [ Approved / Rejected ]
                                 │
                                 ▼
                    ┌─────────────────────────┐
                    │ Apply Changes to Disk   │
                    └─────────────────────────┘

The engine abstracts runtime selection, hardware detection, KV cache lifecycle, prompt optimization, stream transformations, and telemetry without breaking the Vercel AI SDK interface used by the rest of the app.


5 Engineering Pillars Behind the Speed

1. Eliminating Cold Starts with VRAM Pre-Warming & Keep-Alive

Local model runtimes like Ollama frequently page model weights out of memory if inactive for more than a few minutes. The first time a developer invokes a command, they are forced to wait several seconds just for weights to transfer from SSD into Unified RAM.

AdiClaw solves this with proactive Model Weight Pre-Warming:

  • During terminal boot (wakeup), the inference manager fires a lightweight, non-blocking zero-token warm-up signal directly to the active model.

  • It sets keep_alive: "2h", ensuring model layers remain resident in Unified RAM across prolonged coding sessions.

  • Developers can also trigger this on demand via the new /inference warmup command:

╰─ adiclaw > /inference warmup
⚡ Pre-warming model weights into unified memory...
✔ Pre-warmed model 'gemma4:latest' on 'ollama' in 6ms

Result: Time-To-First-Token (TTFT) for user prompts dropped from ~4,200ms on cold starts to under 200ms.

2. Invariant Prompt Prefix Caching

In an autonomous agent loop, every request consists of two distinct parts:

  1. The Invariant Prefix: System instructions, tool definitions, schemas, and workspace roots.

  2. The Dynamic Suffix: The immediate user request, file diffs, and current turn state.

When you have 40+ tools (filesystem tools, GitHub MCP tools, YouTube analytics tools), the schemas alone consume thousands of tokens. Recomputing attention over identical tool schemas on every single turn wastes compute.

I built a PromptPrefixCache that generates a deterministic SHA-256 fingerprint over invariant system prompts and tool schemas. By standardizing the prompt structure so the invariant prefix is always evaluated first, local runtimes (like Ollama and llama.cpp) can reuse the pre-computed Key-Value (KV) cache slots across turns.

// Fast invariant prefix fingerprinting
const prefixInvariant = contextOptimizer.buildInvariantPrefix(
  systemText,
  params.tools as any,
);
promptPrefixCache.checkPrefix(prefixInvariant);

Result: Across multi-turn agent sessions, subsequent turns achieve up to 75% prefix cache hit rates, cutting prompt processing latency dramatically.

3. Turn Delta Compression for Multi-Turn Agent Loops

During a complex coding session, an agent might run up to 40 steps. As it calls list_files, search_files, and read_file, thousands of characters of historical tool results accumulate. Sending full historical outputs on turn 15 is both slow and risky for context limits.

I implemented Turn Delta Compression in context-optimizer.ts:

  • Sliding Window: The most recent turns remain completely untouched with 100% granular detail so the model maintains accurate immediate context.

  • Older Turn Condensation: For turns older than the sliding window threshold, bulky tool results and repetitive stdout blocks are intelligently condensed down to compact previews.

// Compress older bulky outputs while preserving recent turn precision
if (part.type === "tool-result" && typeof part.result === "string" && part.result.length > maxChars) {
  const preview = part.result.slice(0, Math.floor(maxChars * 0.7));
  const omitted = part.result.length - preview.length;
  return {
    ...part,
    result: `${preview}\n... [${omitted} chars truncated from earlier turn history]`,
  };
}

This prevents the context window from bloating, protects token budgets, and keeps generation throughput high throughout long workflows.

4. Apple Silicon Metal GPU Acceleration & Performance Core Pinning

Running local LLMs on macOS Apple Silicon (M1/M2/M3/M4) offers a massive advantage: high-bandwidth Unified Memory architecture shared between CPU and GPU. However, default runtime configurations often underutilize this hardware.

I built a hardware detection module (hardware.ts) that inspects macOS hardware topologies via sysctl:

  • Performance Core Pinning: It identifies high-performance cores (hw.perflevel0.logicalcpu) versus efficiency cores (hw.perflevel1.logicalcpu) and pins computation threads strictly to performance cores, preventing efficiency-core stalls.

  • Metal GPU Offload: Automatically sets num_gpu: 99 on Apple Silicon to offload 100% of model layers to the GPU.

  • High-Throughput Batching: Configures num_batch: 1024 and num_ubatch: 512 for accelerated prompt processing.

  • High-Capacity 16K Context: Clamped context budgets can accidentally truncate tool schemas. By setting num_ctx: 16384, all 44+ MCP tools, codebase context, and prompt histories fit without truncation.

5. Transparent Stream Interception & Live Telemetry

To measure performance without altering application behavior, the engine wraps model streams using native web TransformStream pipelines (adapter.ts):

  • As stream chunks pass through, it captures the exact millisecond when the first token or tool-call arrives, calculating precise TTFT.

  • It counts output tokens and computes live generation throughput (Tokens Per Second - TPS).

  • When a run finishes, the telemetry collector updates rolling statistics and cache savings.

Developers can inspect live inference health right in the terminal via /inference or /status:

╭──────────────────────────────────────────────────────────╮
│ 🚀 INFERENCE ENGINE TELEMETRY                            │
│   Avg TTFT: 142 ms • Avg TPS: 84.6 tok/s                 │
│   Prefix Cache: 72.4% hit rate (18,400 tokens saved)     │
╰──────────────────────────────────────────────────────────╯

Benchmarks & Real-World Impact


Get Involved & Try It Out

AdiClaw is completely open source and built with Bun and TypeScript:

git clone https://github.com/Yuvadi29/adiclaw.git
cd adiclaw
bun install
bun run index.ts wakeup

Try running /inference or /ask on your own codebase and let me know your thoughts!

Enjoyed this?

Like, comment or subscribe on Substack to get the next one.