# Tokeasy

Tokeasy is a token-efficient agent toolkit for Claude Code, Codex, Copilot, Cursor, Windsurf and OpenClaw. Fewer round-trips, smaller context, same model — with savings accounting honest enough to bet a subscription on.

Five of the tools:

- `code_search` — glob + grep + read + imported-by in a single ranked call.
- `code_read` — AST-aware reads: long bodies stubbed, imports/types/signatures kept, full mode on demand.
- `code_edit` — batched multi-file edits, fuzzy matching that tolerates whitespace drift, post-edit TS/JSON/YAML/HTML/SQL syntax validation, and automatic expansion of `code_read` stub markers so you can edit straight off a stubbed read.
- `log_read` — logs and test/build output as a bounded digest that keeps every failure, with a receipt of what was left out and a way to get any of it back exactly. `waitMs` sleeps-then-reads (replaces `sleep N; tail file`) and `until:"regex"` polls and returns the moment a line matches (replaces `tail -f | grep X`).
- `git_context` — branch, ahead/behind, dirty files, recent commits, diffstat and merge state in one call.

`code_search` shows the whole function each hit sits in (bodies up to 80 lines), so the usual follow-up read isn't needed. `code_read` takes per-file selectors in one call: `"a.ts:40-80"`, `"a.ts:40+30"`, `"b.ts#handler"` or `"b.ts#Class.method"` (TS/JS/Python).

…plus the rest of the kit: databases (`sql_query` for Postgres, `data_query` for SQL over local JSONL/CSV/JSON/SQLite files), command output, cross-session memory, and an honest savings ledger. Subscribers get every tool, current and future — each one documents itself in your client, and anything gated tells you exactly how to enable it when you call it. Every result opens with a `[now: … UTC]` header so agents stop burning round-trips on `date`.

A license key is required — subscribe at https://tokeasy.net.

## OpenClaw

```json
{
  "plugins": {
    "entries": {
      "tokeasy": {
        "config": {
          "licenseKey": "tk-..."
        }
      }
    }
  }
}
```

OpenClaw installs also get exec steering (`interceptMode`), which routes raw shell habits to the covering tokeasy tool. Every mode parses the command and produces the *exact* replacement call, not generic prose:

- **`auto`** (default since 0.12.0) — when a tokeasy call is an *exact* equivalent of the command (see **Faithful swaps** below), runs it *inside the hook* and returns its result as the exec result, annotated `[tokeasy auto-swap → log_read]`. Falls back to a `redirect` block when the covering call can't run here. Everything else runs as a real exec (with its output digested in-run), and no text nudges are sent.
- **`nudge`** — lets the exec run and appends a one-line pointer to the covering tool. An exact equivalent reads `[tokeasy → log_read] use log_read({ path: "/srv/app.log", tailLines: 50 })`. Anything else gets the closest call, labelled `not an exact equivalent of this command; check its flags, paths and limits before switching`. Rate-limited per category via `nudgeIntervalMs` (default 5 min; `0` = ledger-only).
- **`redirect`** — blocks the exec and hands back the exact covering call to run instead (one retry hop). A bare `date` is answered *in the block reason* (`it's 16:41 UTC — …`) so the clock check never even spawns a shell.
- **`strict`** — legacy: blocks raw `cat`/`grep` on repo files outright.

### Codex approval compatibility

OpenClaw's codex extension auto-promotes its app-server approval policy from the implicit `never` to `untrusted` whenever any plugin registers a `before_tool_call` hook — which tokeasy does. On channels without an approval UI (Discord, headless gateways) that promotion makes every codex-native exec wait 120s for an approval that can never arrive, then fail the turn with no reply. Tokeasy neutralizes this at startup by pinning the policy to its pre-install default (`approvalPolicy=never`), restoring exactly the behavior the host had before tokeasy was installed. It backs off automatically whenever the operator has expressed any explicit codex policy: `plugins.entries.codex.config.appServer.approvalPolicy`/`mode` in `openclaw.json`, the `OPENCLAW_CODEX_APP_SERVER_APPROVAL_POLICY`/`MODE` env vars, or a managed `/etc/codex/requirements.toml`. Opt out with `codexApprovalCompat: false` in plugin config or `TOKEASY_CODEX_COMPAT=0`.

**Faithful swaps** (0.12.1): the hook only swaps or *blocks* (auto/redirect/escalate) a command when a strict whitelist finds a tokeasy call that returns exactly what the command would, losslessly and within the tool's limits:

| command | swapped to |
|---|---|
| `cat /abs/file` | `log_read({ path })`: digest, plus a handle to the whole file |
| `tail [-n N \| -N] file` | `log_read({ path, tailLines: N })` |
| `cd /repo && git log --oneline -n N` (N ≤ 50) | `git_context({ cwd, diff: "none", commits: N })` |

It also needs:
- a relative path to come with an absolute `cd /abs &&` or an exec `workdir`
- the target to be on the gateway (a text file under 32 MB, or a git work tree), so a missing file still gets the shell's own error
- the exec not to be sent to another host or node, a sandbox, a different env, a pty or the background (and no sandbox configured for any agent)

Everything else runs as a real exec. That includes grep/rg/find (`code_search` is case-insensitive and capped per file), test and build runs (`run_digest` has its own shell, cwd, env and timeout), `git status`/`git diff` (their path lists and diffs are capped), and any pipe, glob, variable, redirect or quoting. Before 0.12.1 the swap matched on shape and could hand back a different answer: `grep -v foo f` became a positive search, and `cat f | python3 x.py` lost the python stage.

A compound where the tokeasy tool covers only the read part, like `python3 job.py && tail -2 job.log`, still gets a split-suggestion nudge (`the read part of this is covered by log_read({…}) — split it out…`).

**Passive digest** (0.12.0, every mode except `off`; in-run since 0.12.1): a finished exec result over 4,000 characters is reshaped *before the model sees it*. A dumped code file becomes its AST outline, grep output is grouped by file, and anything else becomes an error-preserving digest. Only byte-identical lines collapse, so numbers are never lost. The digest carries a `log_read({handle})` pointer to the exact full output. It runs as an agent tool-result middleware for the `openclaw` runtime (manifest contract `agentToolResultMiddleware`), and replaces only the text the model sees. On hosts without that, it falls back to shrinking only the saved transcript and books no savings. `digestExecOver` sets the threshold (`0` disables), and `# tokeasy:raw` in a command skips it once. Explicit line-range reads (`sed -n 40,120p`) and running, background or approval results are left alone.

Blocks and auto-swaps only happen for licensed installs, and never for git commands that write (`commit`, `push`, `add`, `checkout`, …) or chains a tokeasy tool can't fully reproduce.

**Adaptive escalation** (on by default in `nudge` mode): if a category keeps reverting to raw exec after being nudged, tokeasy escalates *just that category* to `redirect` for the rest of the session (`adaptiveEscalation: false` to disable, `escalateAfter` to tune the threshold, default 3) — but only for faithfully-coverable commands, never a partial-coverage compound. The `run_digest` steer only appears when `allowRun` is enabled, so it never points at a disabled tool. `code_savings` reports **what happened next** after each block or nudge — the suggested tool used within 2 minutes, raw exec again, or neither — so you can see which redirects actually change behavior. (Measured on our own gateway over 30 days: 85% of blocks led to the suggested tool; 2% of text nudges did. That is why `auto` is now the default.)

MCP clients (Codex, Cursor, Windsurf, Copilot) have no hook to intercept, so tokeasy steers them the two ways an MCP server can: the initialize-response `instructions` block and tool descriptions both say "use *instead of* grep/cat/tail/git status/…". **Claude Code** can do better — see the `tokeasy hook` setup below.

## Use outside OpenClaw (MCP)

The package ships a stdio MCP server (`tokeasy-mcp`), so the same tools work in any MCP client. Set `TOKEASY_LICENSE_KEY` to your license key from https://tokeasy.net.

**Claude Code**

```bash
claude mcp add tokeasy -e TOKEASY_LICENSE_KEY=*** -- npx -y tokeasy
```

Optional, recommended: add tokeasy as a `PreToolUse` hook so Claude Code gets the same auto-swap as OpenClaw — a Bash command that a tokeasy tool fully covers (`git status`, `git log`, `tail -n 50 app.log`, `grep -rn foo src`) is answered by that tool's bounded output instead of running raw. Print the snippet with `npx -y tokeasy hook --print-config` and merge it into `~/.claude/settings.json`:

```json
{
  "hooks": {
    "PreToolUse": [
      { "matcher": "Bash", "hooks": [{ "type": "command", "command": "npx -y tokeasy hook", "timeout": 30 }] }
    ]
  }
}
```

The hook reads `TOKEASY_LICENSE_KEY` from the environment Claude Code runs it in, stays silent for unlicensed installs, git writes and partial chains, and fails open: any error means the command runs normally. `TOKEASY_HOOK_MODE=redirect` blocks with the covering call instead of running it; `off` disables it.

**Codex CLI** (`~/.codex/config.toml`)

```toml
[mcp_servers.tokeasy]
command = "npx"
args = ["-y", "tokeasy"]
env = { TOKEASY_LICENSE_KEY = "***" }
```

**VS Code GitHub Copilot** (`.vscode/mcp.json`)

```json
{
  "servers": {
    "tokeasy": {
      "command": "npx",
      "args": ["-y", "tokeasy"],
      "env": { "TOKEASY_LICENSE_KEY": "tk-..." }
    }
  }
}
```

**Cursor** (`.cursor/mcp.json`) **and Windsurf** (`~/.codeium/windsurf/mcp_config.json`)

```json
{
  "mcpServers": {
    "tokeasy": {
      "command": "npx",
      "args": ["-y", "tokeasy"],
      "env": { "TOKEASY_LICENSE_KEY": "tk-..." }
    }
  }
}
```

## Savings ledger

`code_savings` reports what the tools saved you, with honest labels: calls saved are **counted**, bytes returned are **measured**, and bytes saved are **estimated** — each number says which it is. Since 0.12.0 the bytes figure is **net**: a raw read is assumed to be a realistic `tail`/`head` (at most 32 KB), not the whole file, and the uncapped gross figure is shown beside it. A block is not counted as a saved call — the follow-up tool call is. The dollar figure is an estimate priced from posted list rates under session cache economics (avoided round-trips save transcript re-reads; smaller results save a cache write plus every later cache read), the model is auto-detected from your session, and every assumption is a named constant in the code, labeled in the output. Treat the figures as ballpark, not billing. If a number is a guess, it says so.

## Leaderboard & telemetry

Tokeasy reports your savings totals to an anonymized leaderboard at tokeasy.net. This is **on by default**; set `TOKEASY_TELEMETRY=0` to opt out.

What is sent (numbers only, at most once per 2 hours): `callsSaved`, `bytesSavedEstimate`, the estimated `usdSaved` (a running total — each report prices only the savings added since the last one, so changing models never re-prices your history), the pricing model name, your license key if you've set one, and a 12-character instance hash (SHA-256 of hostname + home directory) so your entry stays stable across sessions. Running several installs that share a hostname (containers, fleets)? Give each its own id via the `instanceId` plugin config or `TOKEASY_INSTANCE_ID` so their reports don't collide. **Never sent:** code, file paths, queries, file contents, or anything else from your machine. On the leaderboard you appear under a generated anonymous name; `code_savings` shows it (and your rank) when a report succeeds.

Everything else runs 100% on your machine — license checks send a key hash and instance hash, nothing more.
