跳到正文

KlaatAI

klaatcode

Open-source AI coding agent for the terminal. Claude Code-grade accuracy with smart model routing — uses the right AI model for each task, cutting costs 10x. Supports Claude, GPT, Gemini, DeepSeek & more.

README 已保存到本站,可直接阅读

Documentation snapshot

README 快照

本页保存的是公开项目资料快照,阅读过程不需要连接 GitHub。

Klaat Code

The terminal-native AI coding agent, powered by Klaatu smart model routing. Claude Code-grade accuracy, at a fraction of the cost — and it’s reproducible, not a marketing claim.

npm install -g klaatcode
klaatcode

What is KlaatAI?

KlaatAI is an AI platform built around Klaatu-o1, a small, fast, agentic router model. Instead of sending every request to one large, expensive model, Klaatu-o1 reads what you’re asking, decides which model tier actually needs to handle it, and dispatches accordingly — automatically, per request. Three products sit on top of it: KlaatAI Web Chat (browser), Klaat Code (this CLI), and the KlaatAI API for developers building on the same router directly.

What is Klaatu?

Klaatu is the routing brain — a hosted service, not something that runs on your machine. Every message you send from Klaat Code goes to Klaatu, which classifies it and routes it through one of five cost tiers (nano → fast → code → reason → heavy), escalating automatically when a task turns out harder than it looked, and never charging you frontier prices for a trivial turn. Tool calls inside a single request — reads, edits, shell commands, searches — are free; only your messages count against quota. This is also the architectural reason Klaat Code can be open source without giving away the thing that makes it good: the client is a thin terminal to a service, the same relationship gh has to GitHub. The intelligence — routing decisions, model health tracking, pricing, the code-graph index — lives server-side, at klaatai.com.

What is Klaat Code, and how is it different?

Klaat Code is this repo: a terminal-native coding agent you install once and run in any project. It reads your code, edits files, runs commands, and verifies its own work — asking permission before anything risky. Functionally it sits in the same category as Claude Code, opencode, Codex CLI, and Aider — same agentic loop, same terminal-first philosophy — but six things are genuinely different:

  1. Smart per-request model routing. None of the above route per-message to a cost tier the way Klaatu does. You get frontier-level reasoning when a task needs it and pay nano/fast prices for everything else, automatically — not a model you pick once per session.
  2. A real code knowledge graph, not just grep. Your project is indexed into a call graph with semantic search; the agent queries symbols, callers, callees, and blast-radius instead of reading whole files — and plan_exploration uses that graph to plan the optimal file-read order before reading anything. Typically 5–15× fewer tokens per task.
  3. No Continue button, ever. Claude Code and Windsurf stop every 20 tool calls and make you click Continue; on Klaatu, tool rounds are free and unlimited — only your messages count against quota. And when a loop is genuinely stuck (same call, same args, same result), the server detects it and the CLI breaks it with recovery guidance instead of billing you for repetition.
  4. Cost you can see and cap. Real-time burn-rate monitoring (warns at 3× your session average), per-task cost attribution, per-phase token budgets that catch a stuck agent before it burns your budget exploring, a hard session cap, and --max-cost for CI. No other CLI watches spend rate.
  5. Context that knows what it forgot. Compaction in every CLI silently loses things; Klaat Code snapshots your task and files before compacting, verifies the summary afterwards, and tells the model exactly what was lost and where to recover it. /context shows what’s in the window vs. compacted away. Tool output is noise-filtered (progress bars, passing-test spam) before it ever costs you tokens.
  6. The comparison is reproducible. The benchmark below isn’t a claim — clone this repo, run bun run bench, and verify the numbers yourself against the same fixtures we used.

What’s new in each release: CHANGELOG.md.

Benchmarks

Same 33 fixtures, same prompts, same verify command, run against KlaatCode, Claude Code, opencode, Cursor, and Grok Build in one harness. Full methodology and honesty notes: bench/README.md. Interactive version with per-task drill-down: klaatai.com/benchmarks.

图片:Cumulative benchmark cost — Klaat Code vs Claude Code, Cursor, and opencode

Latest run — 2026-07-19, 33 tasks:

MetricKlaat CodeClaude Code (Sonnet 5)opencode (Nemotron 3 Ultra)Cursor (Composer 2.5 Fast)
Solved33/3333/3331/3333/33
Cost per solved task$0.027$0.146~$0.048 est~$0.094 est
Tokens per solved task51.7K171.5K89.1K~28.9K

5.4× cheaper than Claude Code, 1.8× cheaper than the nearest competitor, at a perfect solve rate. Promo-free and subsidized lanes are normalized to published per-token rates so the comparison reflects real token cost (details in the honesty notes). Grok Build’s refresh on this suite is pending an API rate-limit window; on the previous 30-task suite it solved 30/30 at ~$0.058 est.

Reproduce it:

git clone https://github.com/KlaatAI/klaatcode.git && cd klaatcode
bun install
bun run bench                              # klaatcode
bun bench/compare-agents.ts --agent claude # or opencode / grok / cursor

Install

Pick any method — all install a standalone compiled binary (no Node or Bun runtime required at runtime):

npm (Node ≥ 18 or Bun ≥ 1)

npm install -g klaatcode

macOS EACCES error? Prefix with sudo, or fix npm’s global prefix once:

mkdir -p ~/.npm-global && npm config set prefix ~/.npm-global
echo 'export PATH="$HOME/.npm-global/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc

One-line installer (macOS/Linux)

curl -fsSL https://klaatai.com/api/install | bash

Windows (PowerShell)

irm https://klaatai.com/api/install-windows | iex

Homebrew (macOS/Linux)

brew install KlaatAI/klaatcode/klaatcode

All methods install both klaatcode and klaatai — identical commands, use whichever you like.

Quick Start

klaatcode login                     # browser sign-in — your KlaatAI account, no API keys to manage
klaatcode                           # open current directory
klaatcode ~/projects/my-app         # open a specific project
klaatcode run "Fix all TS errors"   # headless / CI mode
klaatcode whoami                    # check auth

Features

Smart Model Routing

Each request is classified and routed to one of five tiers by Klaatu. You see which tier answered (badge in the header) and why.

/tier           # lock a tier, or open the picker
/tier smart     # restore automatic routing
/model          # switch between Klaatu and your own third-party models
/why            # explain the last routing decision
/cost           # session spend + what routing saved you
TierUsed for
nanoTrivial turns, completions
fastQuick questions, small edits
codeDefault — most coding work
reasonDebugging, architecture, tricky logic
heavyLarge refactors, hardest problems

The router escalates automatically when a task turns out harder than it looked and de-escalates when you don’t need the big guns. Tool rounds, retries, and failovers are never billed — one user message = one request.

Bring your own model. Don’t want Klaatu for a task? Add any OpenAI-compatible endpoint and switch to it per-session:

/model add gpt4o https://api.openai.com gpt-4o env:OPENAI_API_KEY
/model gpt4o

Post-Edit Diagnostics — the Model Sees Its Own Mistakes

After a successful edit, Klaat Code runs your project’s typechecker/linter on the changed file (auto-detects eslint/biome, ruff, gofmt, or a configured command) and hands any errors straight back to the model in the same turn — it fixes them before returning control to you, instead of costing you a round-trip.

Terminal UI with Real Syntax Highlighting

Markdown responses render with per-language syntax highlighting directly in the terminal. Code blocks show language labels and are mouse-selectable (drag to auto-copy).

  • Streaming responses with live token/cost counter
  • Slash-command autocomplete — type / for a fuzzy-filtered live suggestion strip
  • Collapsible tool output and thinking blocks — click to expand
  • Full mouse support: click, scroll, drag-select
  • 13 themes: dark, light, dracula, nord, ayu, catppuccin, gruvbox, neon, synthwave, ember, matrix, cobalt, midnight (/theme)
  • Vim keybindings (/vimmode on)
  • Sidebar: usage, context window fill, MCP servers, routing analytics
  • Diffs render as colored, syntax-highlighted unified-diff blocks — including multi-file patches

Real Plan Mode

Switch to Plan mode (Tab) and the model gets only read-only tools — it researches and proposes a plan, you approve, it switches back to Build with the full toolset to implement. No accidental edits while you’re just trying to think something through.

Built-in Tools

ToolWhat it does
read_fileRead files with line numbers, offset/limit for big files
write_fileCreate/overwrite files (parent dirs auto-created)
edit_file / multi_editSurgical string replacement, single or batched atomic
apply_patchMulti-file envelope-diff patch — add/update/delete/move, applied atomically
glob / grep / list_dirFind files and search code
run_commandExecute shell commands (permission-gated)
web_fetch / web_searchRead pages, search the web
todo_write / todo_readPersistent task list the agent maintains
ask_userThe agent can ask you a blocking multiple-choice question mid-task
delegate_taskSpawn a sub-agent for a scoped piece of work, optionally in the background
task_statusCheck on or list background sub-agents
plan_explorationPlan the optimal file-read order for a task from the code graph — before reading anything
project_graph_queryQuery the code graph: symbols, callers, callees
project_semantic_searchMeaning-based code search (Pro)
file_outlineSymbol outline of a file without reading it all
impact_checkBlast-radius analysis: what breaks if this changes
browser_*Navigate, read, and click pages (5 tools)

Multi-Agent Workflows

The agent can delegate scoped work to sub-agents with their own context — keeping your main conversation small and cheap. Sub-agent tool rounds are free like all tool calls.

> explore the auth and billing modules, then implement token refresh
✻ delegate_task: "map auth module structure" …
✻ delegate_task: "map billing module usage of tokens" …

Sub-agents can also run in the background (background: true): you keep chatting while they work, a ◔ N bg agents chip tracks them, and results are injected into the conversation when they finish (task_status / /agents to check in).

Context Management & Compaction

Long sessions stay affordable without losing the thread:

  • Every request is mechanically compacted: thinking blocks stripped, stale tool output truncated by usefulness (superseded file reads and consumed search results trimmed hardest), oldest turns dropped last.
  • Command output is noise-filtered before it enters context: progress bars collapse to their final frame, passing-test runs collapse to a count, repeated lines dedupe — failures and summaries always kept in full.
  • Older history is attention-ordered: the most relevant surviving turns sit at the start and end of the window, where models actually attend (“lost in the middle” mitigation). Recent turns and the system prompt never move.
  • Compaction budget scales to your active tier’s context window — a session pinned to nano compacts harder than one on heavy, so requests never overflow the smaller model’s window.
  • Automatic summarization kicks in past the budget: the session is summarized on the cheapest tier into task state, files touched, and decisions, then the conversation continues seamlessly.
  • Compaction self-check: critical state (your task, the files being modified) is snapshotted before summarizing and verified after — if the summary dropped something, a recovery note tells the model what it forgot and where to re-read it. No other CLI detects context loss.
  • /compact triggers it manually; /context shows what’s in the window vs. compacted away; the sidebar shows context-window fill so you’re never surprised.
  • Code-graph tools mean the agent rarely needs whole files in context in the first place.

Cost Guards & Runaway Protection

The viral horror stories — $6,500 overnight bills, agents looping on the same failing call — can’t happen here:

  • Burn-rate monitor: warns when spend runs 3× your session average (a loop or an oversized context, caught live).
  • Per-task cost + phase breakdown in /cost: see what each request cost and where the tokens went (explore / implement / verify).
  • Per-phase budgets: exploration that burns its budget without producing a single edit pauses and asks — the stuck-agent signature, caught before the bill.
  • Hard caps: maxSessionCost in config pauses agent rounds at your limit; klaatcode run --max-cost 0.50 for CI/cron (exit code 3).
  • Doom-loop breaker: the server flags identical repeated tool rounds; the CLI refuses them, injects recovery guidance, and stops after three strikes — while productive tool loops stay unlimited and free.

Sessions

Every conversation is saved as a transcript in ~/.klaatai/sessions/.

/sessions       # list saved sessions
/resume     # pick up exactly where you left off
/share          # export session to markdown

Permissions

Three-layer model — safe read-only tools run silently; everything else asks:

  • Allow once / this session / always / deny prompts, persisted to ~/.klaatai/permissions.json
  • Glob allow/deny lists for shell commands (rm -rf /, fork bombs, etc. denied by default)
  • Writes sandboxed to the project directory by default; hard-denied system paths (/etc, ~/.ssh, …) refused even with the sandbox off
{
  "allowed_commands": ["git status", "git diff *"],
  "denied_commands":  ["rm -rf /"],
  "trusted_tools": ["read_file", "glob", "grep"]
}

MCP (Model Context Protocol)

Full MCP client, both transports:

  • stdio — local servers, configured in .klaatai/mcp.json, built-in presets (filesystem, GitHub, Postgres, Puppeteer, Brave Search, Fetch, …)
  • Streamable HTTP — remote servers via "url" config or /mcp add ; SSE and JSON responses, session management, and OAuth 2.1 (discovery + dynamic client registration + PKCE browser flow) when the server requires auth — tokens cached in ~/.klaatai/mcp-oauth.json

Manage live with /mcp.

Git Integration

/diff           # show git diff
/review         # AI code review of current changes
/commit         # AI-generated commit message + confirm
/undo           # undo last AI file changes
/checkpoint     # snapshot project state
/rollback       # restore a checkpoint

Skills — Reusable Prompt Templates

Save prompts as .md files, invoke by name. Project skills in .klaatai/skills/, global in ~/.klaatai/skills/.

/skill list
/skill fix-types
/skill new fix-types     # create in $EDITOR

Hooks — Lifecycle Automation

Run shell commands on agent lifecycle events. Hooks receive a JSON payload on stdin (tool name, arguments, result) plus KLAATAI_* env vars, can be scoped with a matcher regex, and before_tool hooks can block a tool call (exit code 2, or print {"decision":"block","reason":"…"}).

// .klaatai/hooks.json
{
  "after_message": ["afplay /System/Library/Sounds/Glass.aiff"],
  "before_tool": [
    { "matcher": "run_command", "command": "./scripts/guard-shell.sh" }
  ],
  "after_tool":     ["notify-send \"$KLAATAI_TOOL_NAME done\""]
}

Events: before_message · after_message · before_tool · after_tool

Project Rules

.klaatai/rules.md in your repo is injected into every session — coding standards, architecture notes, dos and don’ts. /init auto-generates one from your tech stack. AGENTS.md is also respected.

Plugins

Custom tools as JavaScript modules — ~/.klaatai/plugins/*.js (global) or .klaatai/tools/*.js (project). /plugin list · /plugin reload.


Full CLI + Command Reference

This README covers the highlights. For every shell flag, slash command, config key, and MCP/hooks/skills detail: klaatai.com/docs.

Slash Commands

CommandDescription
/helpShow all commands
/tier [name]Lock a Klaatu routing tier, or open the picker
/modelSwitch between Klaatu and custom third-party models
/whyExplain last routing decision
/costSession cost, burn rate, per-task + per-phase breakdown
/contextWhat’s in the context window vs. compacted away
/compactSummarize context to free the window
/diff [file] · /review [ref] · /commitGit workflows
/undo · /checkpoint [label] · /rollback [id]Safety nets
/test [args]Run tests (auto-detects Bun/Vitest/Jest/pytest/Go/Cargo)
/skill · /hooksSkills and hooks
/initGenerate project rules from your stack
/sessions · /resume · /shareSession management
/mcpManage MCP servers
/agentsList agent personas + running background sub-agents
/permsReview tool permissions
/theme · /vimmode on|offUI
/logoutSign out and clear stored credentials
/doctorDiagnose auth, API, MCP, project health
/clearClear chat

Typing / shows a live, fuzzy-filtered autocomplete strip for all of the above.

Keyboard Shortcuts

ShortcutAction
ctrl+pCommand palette
ctrl+rFuzzy history search
ctrl+vAttach image from clipboard (screenshots)
ctrl+yCopy last AI response
ctrl+bCollapse/expand thinking blocks
ctrl+dQuit
ctrl+c / escCancel streaming
ctrl+x ctrl+eCompose message in $EDITOR
@Fuzzy file picker — inserts file reference
!cmdRun shell command, inject output
TabSwitch Build / Plan mode
Mouse dragSelect + auto-copy

Vim mode (/vimmode on)

KeyAction
escNORMAL mode
i / a / A / IINSERT mode
h / lMove cursor
j / kScroll chat
w / b / eWord motion
0 / $Line start / end
dd / DClear input / kill to EOL
gg / GTop / bottom
ctrl+u / ctrl+dHalf-page scroll

Headless / CI Mode

klaatcode run "Summarise CHANGELOG.md"                 # streams to stdout
echo "Explain this function" | klaatcode run -          # pipe input
klaatcode run "Fix type errors" --model fast            # with options
klaatcode run "Security-check auth.ts" < auth.ts        # in CI
# GitHub Actions
- name: Fix lint errors
  env:
    KLAATAI_API_KEY: ${{ secrets.KLAATAI_API_KEY }}
  run: klaatcode run --model code "Fix all ESLint errors and commit"

API Server Mode

klaatcode serve --port 4200
  • GET /v1/health — health check
  • GET /v1/info — session info
  • POST /v1/chat — chat with SSE streaming
  • POST /v1/run — single prompt → SSE stream

klaatcode web serves a browser UI on top of the same server.

Configuration

~/.klaatai/config.json:

{
  "baseUrl": "https://api.klaatai.com",
  "routingDisplay": "minimal",
  "theme": "dark",
  "vimMode": false
}
KeyValuesDescription
routingDisplayoff / minimal / fullRouting detail in chat header
themesee theme list aboveUI theme
vimModetrue / falseVim keybindings
sandboxproject / offWrite sandbox scope
diagnosticson / offPost-edit typecheck/lint feedback loop
customModelsarrayThird-party OpenAI-compatible models (see /model add)
outputFilteron / offNoise-filter command output (progress bars, passing-test spam) before it costs tokens
attentionOrderon / offArrange old history so the most relevant turns sit where models attend
maxSessionCostUSD numberHard session cost cap — pauses agent rounds when reached
phaseBudgetson / offPer-phase token budgets; pause a stuck explore phase before it burns the budget

Full reference, incl. every config key: klaatai.com/docs/configuration.

Directory Structure

~/.klaatai/
  credentials.json    # auth tokens (never committed, never shared)
  config.json         # user preferences
  permissions.json    # tool permission rules
  mcp.json            # global MCP servers
  mcp-oauth.json      # cached OAuth tokens for remote MCP servers
  hooks.json          # global lifecycle hooks
  sessions/           # saved session transcripts
  skills/             # global prompt skills (.md)
  plugins/            # custom tool plugins (.js)
  todos.json          # persistent todo list

.klaatai/             # project-level (in your repo)
  rules.md            # project rules (injected every session)
  mcp.json            # project MCP servers
  hooks.json          # project lifecycle hooks
  skills/             # project prompt skills
  tools/              # project tool plugins (.js)

How Authentication Works

Sign-in is browser-based OAuth against your KlaatAI account — there are no API keys to generate or paste. klaatcode login opens a browser tab, you authenticate with KlaatAI, and a short-lived JWT plus refresh token are stored locally in ~/.klaatai/credentials.json (mode 0600, never synced or logged). The CLI silently refreshes the token in the background and recovers automatically from expiry mid-session; klaatcode logout clears everything. Every chat request goes straight to Klaatu over HTTPS with that token — the server enforces your plan’s quota and never proxies your credentials anywhere else.

Contributing

We welcome contributions — see CONTRIBUTING.md for dev setup, the PR process, and what bun run bench:selfcheck needs to pass before a PR is reviewed.

Security

Found a vulnerability? Please don’t open a public issue — see SECURITY.md for how to report it responsibly.

Roadmap

  • LSP tool (go-to-definition, find-references, rename) alongside the existing code graph
  • Git worktree isolation for parallel/risky sub-agent work
  • Published SWE-bench Verified scores
  • Team-shared code graph, klaat org commands

Star History

License

Apache License 2.0 © KlaatAI — see LICENSE.

The KlaatAI, Klaat Code, and Klaatu names and logos are trademarks of KlaatAI and are not covered by this license — see LICENSE for the trademark notice.

Official distribution

获取与安装

暂未发现可确认的官方软件包地址

当前 README 快照没有出现 npm、PyPI、Crates.io、pub.dev 等官方包页链接。本站不会根据仓库名称猜测下载地址。

本站不托管项目文件;需要安装时,请以项目维护者发布的官方文档为准。

使用前核验

本站保存公开资料用于阅读,不代表安全审计或功能背书。安装前请核对许可证、依赖来源和发布签名,不要直接运行来源不明的二进制文件或高权限脚本。