This is the full developer documentation for Waibee Docs
# Waibee documentation
> Connect to models through Waibee Router, work with the Waibee Code agent, and browse the API reference and cookbook.
* Waibee Code
## Waibee Code
A coding agent. Install it on macOS, Linux, or Windows, set it up, and run your first tasks.
[Installation ](/code/install/)
[First run ](/code/quickstart/)[Code overview ](/code/)
macOS and Linux
`curl -fsSL https://raw.githubusercontent.com/waibee-main/waibee-code/main/install.sh | bash`
Windows · PowerShell
`irm https://raw.githubusercontent.com/waibee-main/waibee-code/main/install.ps1 | iex`
Verify the installation
`waibee version`
`waibee doctor`
* Waibee Router
## Waibee Router
One API for many models. Connect your app or set up a tool you already use.
[Quickstart ](/router/quickstart/)
[Router overview ](/router/)[API Reference ](/router/api/)
### Connect
[Integrations ](/router/integrations/)
#### API
[**Chat Completions**OpenAI · /v1/chat/completions](/router/api/operations/createchatcompletion/)[**Responses**OpenAI · /v1/responses](/router/api/operations/createresponse/)[**Messages**Anthropic · /v1/messages](/router/api/operations/createmessage/)
## Waibee Code features
### Interface and tasks
* [Chats in the terminal](/code/features/#interface)
[Several tasks in tabs, history search, keyboard and mouse control.](/code/features/#interface)
* [Web interface](/code/web/)
[Chats, files, and diffs in the browser. The agent runs on your computer.](/code/web/)
* [From another device](/code/web/#from-a-phone-or-tablet)
[Open the web interface on your local network, or from another network through a tunnel.](/code/web/#from-a-phone-or-tablet)
* [In your IDE](/code/ide/)
[The agent in Zed, JetBrains, and other editors that support ACP.](/code/ide/)
* [Scripts and CI](/code/headless/)
[Run tasks without the interface through waibee run. Results come as text or JSON.](/code/headless/)
* [Session history](/code/features/#session-history)
[Return to past tasks, branch a conversation, and export chats.](/code/features/#session-history)
* [Images](/code/features/#interface)
[Paste screenshots and pictures into a prompt. Needs a model that accepts images.](/code/features/#interface)
* [Steering mid-task](/code/features/#interface)
[Add to the current task or queue the next message.](/code/features/#interface)
* [Work until done](/code/goal/)
[Goal mode keeps going until the condition you set is met.](/code/goal/)
### Working in a project
* [Project edits](/code/features/#agent-tools)
[Reads files, makes targeted changes, and shows diffs right in the chat.](/code/features/#agent-tools)
* [Code navigation](/code/lsp/)
[Search, definitions, references, and diagnostics through LSP.](/code/lsp/)
* [Commands and tests](/code/features/#agent-tools)
[Runs builds and tests. Long commands can move to the background.](/code/features/#agent-tools)
* [Plans and notes](/code/features/#interface)
[Task steps, tables, and diagrams in the side panel.](/code/features/#interface)
* [Parallel agents](/code/features/#subagents)
[Separate workers for research, review, and other subtasks.](/code/features/#subagents)
* [Git and worktrees](/code/features/#agent-tools)
[Review changes and work in a separate copy of the project.](/code/features/#agent-tools)
* [Change review](/code/web/#reviewing-changes)
[Comment on diff lines and revert a file whole or hunk by hunk.](/code/web/#reviewing-changes)
* [Web search](/code/features/#web-search)
[Finds sources and reads pages without a separate key.](/code/features/#web-search)
### Extensions and settings
* [Model choice](/code/models/)
[Models through Waibee Router, with control over reasoning depth.](/code/models/)
* [Project instructions](/code/configuration/)
[Rules for your project in WAIBEE.md, AGENTS.md, and CLAUDE.md.](/code/configuration/)
* [Memory and context](/code/context-window/)
[Facts that carry over between sessions, and compaction of long conversations.](/code/context-window/)
* [Skills](/code/skills/)
[Instructions and materials the agent loads when a task needs them.](/code/skills/)
* [Custom commands](/code/skills/#custom-commands)
[Prompt templates with arguments that you call as /name.](/code/skills/#custom-commands)
* [Plugins](/code/plugins/)
[Commands, skills, agents, hooks, and MCP in one installable package.](/code/plugins/)
* [Hooks](/code/hooks/)
[Scripts that run before and after tool calls and on session events.](/code/hooks/)
* [MCP servers](/code/mcp/)
[External tools and services over one protocol.](/code/mcp/)
### Security
* [Approvals and rules](/code/permissions/)
[Pick a permission mode and set rules for allowed and denied commands.](/code/permissions/)
* [Domain restrictions](/code/permissions/#domain-restrictions)
[Block specific domains or allow requests to chosen ones only.](/code/permissions/#domain-restrictions)
* [File protection](/code/configuration/#excluding-paths)
[Keep paths out of reads and search with .waibeeignore. Secrets are covered by built-in rules.](/code/configuration/#excluding-paths)
* [Sandbox](/code/permissions/#sandbox)
[Stop commands from writing outside the project on macOS and Linux.](/code/permissions/#sandbox)
* [Audit log](/code/features/#audit-log)
[A record of what the agent did, with search, filters, and export to JSON, CSV, or Markdown.](/code/features/#audit-log)
## Waibee Code
* [Quickstart](/code/quickstart/)
* [Configuration](/code/configuration/)
* [Skills](/code/skills/)
* [MCP servers](/code/mcp/)
## Waibee Router
* [Choosing a model](/router/models/)
* [Authentication](/router/authentication/)
* [API Reference](/router/api/)
* [Cookbook](/router/cookbook/)
## Integrations
* [Claude Code](/router/integrations/claude-code/)
* [Codex](/router/integrations/codex/)
* [OpenCode](/router/integrations/opencode/)
* [OpenAI-compatible SDKs](/router/integrations/openai-compatible/)
**Docs for agents**Markdown and llms.txt
[llms.txt ](/llms.txt)[Full text ](/llms-full.txt)[Glossary ](/glossary/)
# Waibee Code
> A coding agent for the terminal, a local web interface, IDEs, and scripts.
Waibee Code reads your project, edits code, runs commands, and checks the result. You can work with it in the terminal, in the browser, and in your IDE, and it runs tasks from scripts with no interface at all. It is written in Rust, starts with the `waibee` command, and runs on macOS, Linux, and Windows. The agent reaches models through [Waibee Router](/router/), and you set your platform API key once.
Note
Waibee Code is in early beta. Features and commands may change between versions.
[](/media/code/tui-overview.png)
A demo project: the task, the edit, and the test run in one chat. Click a screenshot to open it full size.
## Ways to work
[Section titled “Ways to work”](#ways-to-work)
* **Terminal (TUI)**: an interactive chat. Start it with `waibee`.
* **[Local web interface](/code/web/)**: chats, files, diffs, and a terminal in the browser, while the agent runs on your computer. Start it from the shell with `waibee serve`. To continue your current TUI chats in the browser, type `/web` in the TUI. You can also open the page from a phone; see [network access](/code/web/#from-a-phone-or-tablet).
* **[Headless CLI](/code/headless/)**: run a task with no interface, for example `waibee run "review the changes"`. Use it in scripts and CI.
* **[IDEs over ACP](/code/ide/)**: work in Zed, JetBrains, and other editors that support the Agent Client Protocol.
[](/media/code/web-overview.png)
A demo project: the agent added search by title and checked it with tests. Click the screenshot to open it full size.
## What it can do
[Section titled “What it can do”](#what-it-can-do)
Open a feature to see how to set it up.
### Interface and tasks
* [Chats in the terminal](/code/features/#interface)
[Several tasks in tabs, history search, keyboard and mouse control.](/code/features/#interface)
* [Web interface](/code/web/)
[Chats, files, and diffs in the browser. The agent runs on your computer.](/code/web/)
* [From another device](/code/web/#from-a-phone-or-tablet)
[Open the web interface on your local network, or from another network through a tunnel.](/code/web/#from-a-phone-or-tablet)
* [In your IDE](/code/ide/)
[The agent in Zed, JetBrains, and other editors that support ACP.](/code/ide/)
* [Scripts and CI](/code/headless/)
[Run tasks without the interface through waibee run. Results come as text or JSON.](/code/headless/)
* [Session history](/code/features/#session-history)
[Return to past tasks, branch a conversation, and export chats.](/code/features/#session-history)
* [Images](/code/features/#interface)
[Paste screenshots and pictures into a prompt. Needs a model that accepts images.](/code/features/#interface)
* [Steering mid-task](/code/features/#interface)
[Add to the current task or queue the next message.](/code/features/#interface)
* [Work until done](/code/goal/)
[Goal mode keeps going until the condition you set is met.](/code/goal/)
### Working in a project
* [Project edits](/code/features/#agent-tools)
[Reads files, makes targeted changes, and shows diffs right in the chat.](/code/features/#agent-tools)
* [Code navigation](/code/lsp/)
[Search, definitions, references, and diagnostics through LSP.](/code/lsp/)
* [Commands and tests](/code/features/#agent-tools)
[Runs builds and tests. Long commands can move to the background.](/code/features/#agent-tools)
* [Plans and notes](/code/features/#interface)
[Task steps, tables, and diagrams in the side panel.](/code/features/#interface)
* [Parallel agents](/code/features/#subagents)
[Separate workers for research, review, and other subtasks.](/code/features/#subagents)
* [Git and worktrees](/code/features/#agent-tools)
[Review changes and work in a separate copy of the project.](/code/features/#agent-tools)
* [Change review](/code/web/#reviewing-changes)
[Comment on diff lines and revert a file whole or hunk by hunk.](/code/web/#reviewing-changes)
* [Web search](/code/features/#web-search)
[Finds sources and reads pages without a separate key.](/code/features/#web-search)
### Extensions and settings
* [Model choice](/code/models/)
[Models through Waibee Router, with control over reasoning depth.](/code/models/)
* [Project instructions](/code/configuration/)
[Rules for your project in WAIBEE.md, AGENTS.md, and CLAUDE.md.](/code/configuration/)
* [Memory and context](/code/context-window/)
[Facts that carry over between sessions, and compaction of long conversations.](/code/context-window/)
* [Skills](/code/skills/)
[Instructions and materials the agent loads when a task needs them.](/code/skills/)
* [Custom commands](/code/skills/#custom-commands)
[Prompt templates with arguments that you call as /name.](/code/skills/#custom-commands)
* [Plugins](/code/plugins/)
[Commands, skills, agents, hooks, and MCP in one installable package.](/code/plugins/)
* [Hooks](/code/hooks/)
[Scripts that run before and after tool calls and on session events.](/code/hooks/)
* [MCP servers](/code/mcp/)
[External tools and services over one protocol.](/code/mcp/)
### Security
* [Approvals and rules](/code/permissions/)
[Pick a permission mode and set rules for allowed and denied commands.](/code/permissions/)
* [Domain restrictions](/code/permissions/#domain-restrictions)
[Block specific domains or allow requests to chosen ones only.](/code/permissions/#domain-restrictions)
* [File protection](/code/configuration/#excluding-paths)
[Keep paths out of reads and search with .waibeeignore. Secrets are covered by built-in rules.](/code/configuration/#excluding-paths)
* [Sandbox](/code/permissions/#sandbox)
[Stop commands from writing outside the project on macOS and Linux.](/code/permissions/#sandbox)
* [Audit log](/code/features/#audit-log)
[A record of what the agent did, with search, filters, and export to JSON, CSV, or Markdown.](/code/features/#audit-log)
## In this section
[Section titled “In this section”](#in-this-section)
* [Installation](/code/install/): installing, updating, and uninstalling.
* [Quickstart](/code/quickstart/): your API key, the first run, and what to set up right away.
* [Local web interface](/code/web/): working in the browser and from a phone.
* [Features](/code/features/): agent tools, the terminal interface, search, and MCP.
* [Commands](/code/commands/): slash commands and CLI subcommands.
* [Choosing a model](/code/models/): which model families are available and which to use for what.
* [Goal mode](/code/goal/): the agent keeps working until a condition is met.
* [Best practices](/code/best-practices/): how to frame tasks and save context.
* [Headless mode and automation](/code/headless/): the agent as a command in scripts, CI, and other pipelines.
* [Finding extensions](/code/ecosystem/) and [Recommended extensions](/code/toolkit/): skills, plugins, and MCP servers.
* [Claude Code compatibility](/code/claude-code/): what carries over from `.claude/` and what does not.
* [Glossary](/glossary/): the terms used in these docs, in one place.
# ACP in the terminal (acpx)
> Running Waibee Code through acpx: sessions that persist between calls, machine-readable output, permissions in scripts and CI.
For scripts and CI, the main path is the built-in headless mode, `waibee run`: it needs nothing beyond the agent itself. See [Headless mode and automation](/code/headless/).
This page covers another option, in case you already know it: [acpx](https://acpx.sh/), a third-party headless client for the [Agent Client Protocol](https://agentclientprotocol.com/). The agent uses the same protocol to connect to editors; here, the command line drives it. To acpx, Waibee Code is an ordinary ACP agent started with `waibee acp`.
What acpx adds on top of `waibee run`:
* **Sessions persist between calls.** Each prompt remembers the previous one, while each call is still a single terminal command.
* **Several tasks in one folder.** Named sessions run in parallel without getting in each other’s way.
* **One interface and one event format across agents.** The ACP JSON stream is the same for every ACP agent, which helps when other agents live next to Waibee in your scripts.
## Installation
[Section titled “Installation”](#installation)
```bash
npm install -g acpx@latest
acpx --version
```
Without a global install: `npx acpx@latest`.
## Registering Waibee
[Section titled “Registering Waibee”](#registering-waibee)
Waibee is not one of acpx’s built-in adapters, so add it to the config:
\~/.acpx/config.json
```json
{
"agents": {
"waibee": {
"command": "waibee",
"args": ["acp"]
}
}
}
```
If `waibee` is not on your `PATH`, give the full path: `~/.local/bin/waibee` (macOS/Linux) or `%LOCALAPPDATA%\Programs\waibee\waibee.exe` (Windows). You can also put the config next to the project, in a `.acpxrc.json` file; `acpx config show` prints the current values.
The agent picks up the API key on its own: set it beforehand with `waibee auth login` or the `WAIBEE_API_KEY` environment variable, see [Quickstart](/code/quickstart/).
## First prompt
[Section titled “First prompt”](#first-prompt)
A one-off prompt that keeps no context:
```bash
acpx waibee exec 'In three points: what does this repository do?'
```
For prompts that build on earlier ones, create a session explicitly. This guards against creating sessions by accident in CI:
```bash
acpx waibee sessions new
acpx waibee 'find the slowest test and explain why'
acpx waibee 'fix it' # remembers the previous reply
```
Sessions are tied to the agent and the working folder. Keep parallel tasks apart with names:
```bash
acpx waibee sessions new --name backend
acpx waibee -s backend 'fix the timeout in checkout'
acpx waibee sessions # sessions in this folder
acpx waibee status # agent process, model, uptime
acpx waibee cancel # cancel the current prompt
```
## Permissions
[Section titled “Permissions”](#permissions)
In the terminal, the agent has no one to ask, so you set the approval policy with a flag. By default, acpx allows reads and asks about everything else; when there is no one to ask, it rejects the request, and the command fails with `PERMISSION_DENIED` even if a reply was already received.
| Flag | Behavior |
| ---------------------------- | ---------------------------------------------------------------- |
| `--approve-reads` | Allow reads and search, ask about the rest. The default |
| `--approve-all` | Allow everything: file edits and commands run without asking |
| `--deny-all` | Reject the approval requests passed to the client |
| `--permission-policy ` | A custom policy: lists of what to approve and deny automatically |
The flags only answer the questions Waibee Code asks, and it asks according to its [mode](/code/permissions/#four-modes). A session starts in the same mode as a new terminal session without the `--mode` flag, see [Switching modes](/code/permissions/#switching-modes). In `trust`, edits and most commands go through without asking, and neither `--approve-reads` nor `--deny-all` stops them. To set the session’s mode, run `acpx waibee set mode default`.
Use `--approve-all` only where unwanted changes cost nothing: a disposable clone, a worktree, a working copy in CI. Denials from `settings.json` apply regardless of the flag, see [Permissions](/code/permissions/).
## Output for scripts
[Section titled “Output for scripts”](#output-for-scripts)
| Format | What it prints |
| ---------------- | ------------------------------------------- |
| `--format text` | Readable progress of the work. The default |
| `--format quiet` | Only the final reply text |
| `--format json` | The ACP event stream as line-delimited JSON |
```bash
SUMMARY=$(acpx --format quiet waibee exec 'describe the changes on this branch in one paragraph')
echo "$SUMMARY"
```
`--json-strict` guarantees nothing but JSON on stdout, which helps when the output goes straight into `jq`. Two more useful flags: `--suppress-reads` (don’t print the contents of files the agent reads) and `--timeout `.
## Model and reasoning level
[Section titled “Model and reasoning level”](#model-and-reasoning-level)
```bash
acpx --model anthropic/claude-sonnet-5 waibee exec 'analyze this stack trace'
acpx waibee set model anthropic/claude-haiku-4.5 # for the current session
acpx waibee set thought_level high # reasoning effort
acpx waibee set mode acceptEdits # approval mode
```
The `mode` values are the same as for the `--mode` flag, see [Switching modes](/code/permissions/#switching-modes). The `thought_level` values are the same as for `/effort` in the TUI and depend on the model, see [Reasoning level](/code/models/#reasoning-level-effort).
## If this is for CI
[Section titled “If this is for CI”](#if-this-is-for-ci)
Compare it with `waibee run` first: that needs no Node and no separate install, and its [exit codes](/code/headless/#exit-codes) are built for goal mode. Ready-made pipeline recipes are in [Headless mode](/code/headless/). acpx makes sense when your CI needs a stateful conversation across steps, or when the pipeline already runs several agents through acpx.
Either way, keep in mind:
* **Limit time and turns** (`--timeout`, `--max-turns`): an agent in CI should not hang until the runner times out.
* **Run read-only checks in `default` mode with `--approve-reads`,** and edits in a separate step with an explicit `--approve-all`, so that a review job can’t produce a stray commit.
* **Check the exit code.** A nonzero code means a denied permission, a timeout, or an agent error, not “no findings”.
## Next steps
[Section titled “Next steps”](#next-steps)
* [Headless mode](/code/headless/): the built-in way to run the agent from scripts and CI.
* [IDEs (ACP)](/code/ide/): the same protocol in Zed and JetBrains.
* [Goal mode](/code/goal/): how to make the agent carry a task through to a checkable result.
# Autoresearch
> The autoresearch approach: the agent edits the code, measures a metric, and keeps only the changes that improved it.
Some tasks have a result you can express as a number: response time, bundle size, the share of passing tests, parsing accuracy, the cost of a run. If a script produces that number, you do not need to walk the agent through every step. It tries variants on its own, keeps the ones that improved the metric, and reverts the rest. This technique is called the autoresearch approach, after [Andrej Karpathy’s repository](https://github.com/karpathy/autoresearch), where it is demonstrated on training a language model.
How it differs from regular work: you do not review every edit. You set the metric and the rules once, and then read the experiment log and the final diff.
## When it fits
[Section titled “When it fits”](#when-it-fits)
* There is one number that honestly reflects the goal.
* A script computes that number without you.
* One measurement takes minutes, not hours: a run has to fit many attempts.
* The edit scope is narrow: one file or a few, and everything else is off-limits.
If a person sets the metric (“it feels nicer to use”), the approach does not work. Go back to the regular loop with a plan and tests. See [Development workflows](/code/workflows/).
## What it is made of
[Section titled “What it is made of”](#what-it-is-made-of)
| Part | What it is |
| ----------------- | ------------------------------------------------------------------------------------------------------- |
| Metric | One number and a direction: higher is better or lower is better |
| Evaluation script | One command that prints that number, for example `./bench.sh` |
| Edit scope | The files the agent is allowed to change |
| Correctness gate | Tests or a linter. A failure means a revert, whatever the gain |
| Log | A file that gets an entry after every attempt: the hypothesis, what changed, the metric, the conclusion |
The evaluation script, the data, and the tests are **not** in the edit scope. This is the main rule: otherwise the agent improves the measuring tool instead of the code.
## The loop
[Section titled “The loop”](#the-loop)
1. **Baseline.** Run the evaluation several times in a row without a single edit. Record the value and the spread between runs.
2. **Hypothesis.** One per iteration; the log shows what has already been tried.
3. **Edit** only inside the scope.
4. **Measure** and run the correctness gate.
5. **Decide.** A gain larger than the spread means a commit. Otherwise, `git reset --hard` or revert the files.
6. **Repeat** until the budget runs out or progress plateaus.
A commit for every successful step gives you a history of the experiments, and a revert costs one command.
## Measurement noise
[Section titled “Measurement noise”](#measurement-noise)
A metric is rarely stable: the same code on the same hardware gives different numbers. If you accept every improvement, half the “wins” will be noise, and the loop will go in circles.
That is why the baseline is measured several times, and a change is accepted only when the gain exceeds the observed spread. Recheck borderline cases with another run and compare the averages.
## Protecting the metric
[Section titled “Protecting the metric”](#protecting-the-metric)
The whole loop rests on one assumption: when the number goes up, the result gets better. This assumption breaks in two ways, and either one wastes the run.
**The agent edits the measuring tool.** The cheapest way to improve a metric is to improve how it is computed rather than the code. Sometimes directly (tweaking the formula, loosening a check), sometimes subtly: hardcoding answers for the inputs that appear in the evaluation, caching the result, catching an exception and returning a convenient value.
* Keep the evaluation script, the reference data, and the tests outside the edit scope. Check `git diff` after a run: if it touched those files, revert the iteration.
* Print only the final number in the evaluation output. If the expected answers are visible, sooner or later they end up in the code.
* Any failure of a previously passing test means a revert, no matter how big the gain.
* Review the commits, not only the final number. A thousand-line diff for one percent is usually not worth it.
**The metric itself is wrong.** It can rise while the result stays the same or gets worse: the wrong sign, averaging over the wrong rows, training on the same data used for evaluation, measuring a warm cache instead of a cold start.
* Before you start, test the measuring tool with a change that is known to be bad. Break something on purpose: the metric must drop. If it does not, it is too early to run the loop.
* Hold out a portion of the data or scenarios that the agent does not optimize against, and run it at the end. If the gain disappears, the solution is overfitted to the sample.
* Compare the metric with the goal yourself at least once every few iterations. If the number went up by a third and the behavior did not change, that is a reason to investigate the measuring tool, not to celebrate.
* The agent will degrade anything the metric does not cover without hesitation. Readability, memory, image size: if it matters, add it to the check explicitly.
## How to run it
[Section titled “How to run it”](#how-to-run-it)
There are two ways, and they differ in who enforces the loop rules.
**In a session.** You state the rules in the prompt, set a stop condition with [`/goal`](/code/goal/), and watch. It is quick to start, but nothing outside the agent enforces the rules. The model that checks the goal judges only by the conversation, so phrase the condition in terms of what the agent prints: “`./bench.sh` reported less than 80 ms”.
**With an external script.** Each iteration is a separate `waibee run --once` call. The script checks the result, so the built-in goal check is not needed. The script also makes the keep-or-revert decision. Here too, protect the measuring tool and its input data from the agent’s edits.
```bash
noise=0.004 # baseline spread, measured beforehand
best=$(./bench.sh) # higher is better
for i in $(seq 1 30); do
waibee run --once "read experiments.md, propose one hypothesis that has not been tried yet,
change only src/parser.rs, run ./bench.sh, and append a line to experiments.md" < /dev/null
score=$(./bench.sh)
if awk "BEGIN{exit !($score > $best + $noise)}" && cargo test -q; then
best=$score
git commit -qam "exp $i: $score"
else
git checkout -- src/parser.rs
fi
done
```
Set the budget explicitly: the number of iterations, the time, or both. In a script it is the loop counter; in a session it is the goal’s limit on auto-continuations. See [Goal mode](/code/goal/#limits-and-stopping).
## What gets optimized this way
[Section titled “What gets optimized this way”](#what-gets-optimized-this-way)
Build time, handler latency, bundle size, memory use, the accuracy of a parser or classifier on a labeled set, the share of passing tests during a migration, the number of linter warnings, the cost of a run in tokens.
## Pitfalls
[Section titled “Pitfalls”](#pitfalls)
* **The metric misses the goal.** An endpoint got faster but lost correctness in a rare case that is not in the set.
* **Noise taken for improvement.** The baseline was measured once, and no threshold was set.
* **Expensive evaluation.** A ten-minute measurement means only a handful of attempts per run, and the loop does not pay off.
* **Leaving the run unattended to the end.** Look at the log after the first five experiments: it shows right away whether the agent is fixing the task or going after the measuring tool.
## Where it comes from
[Section titled “Where it comes from”](#where-it-comes-from)
Andrej Karpathy popularized the approach in the [karpathy/autoresearch](https://github.com/karpathy/autoresearch) repository. There the agent looks for ways to train a small language model faster, and the whole setup rests on three files:
| File | Role |
| ------------ | ------------------------------------------------------------------------------------ |
| `train.py` | The only file the agent edits: the model, the optimizer, the training loop |
| `prepare.py` | Data preparation and evaluation. The agent does not touch it |
| `program.md` | Instructions for the agent: what to try, what to avoid. A person maintains this file |
Each training run takes exactly five minutes of wall-clock time, regardless of hardware. This has two consequences: experiments are comparable with each other whatever the agent changes (model size, batch size, architecture), and about a hundred of them accumulate overnight, roughly twelve an hour. The flip side: results from different hardware can no longer be compared.
There is one metric: `val_bpb`, bits per byte on a held-out set, lower is better. It does not depend on the vocabulary size, so architectures are compared fairly.
The work is split this way: the agent edits the code, and a person edits `program.md`, which records the direction of the search, the dead ends already explored, and the priority of hypotheses.
Three decisions from there carry over to any task: one file open to edits, a fixed cost per measurement, and a metric that holds up against whatever the agent changes. The original repository requires an NVIDIA GPU; for other platforms its README lists forks (macOS, MLX, Windows, AMD).
## Ready-made implementations
[Section titled “Ready-made implementations”](#ready-made-implementations)
Ready-made skills and plugins bring the loop to arbitrary tasks. One example is [autoresearch-claude-code](https://github.com/drivelineresearch/autoresearch-claude-code), a plugin for Claude Code and Codex. It includes things that take a while to write in your own script:
* a metric contract: the evaluation script prints a `METRIC name=number` line to stdout, and the loop takes the metric from there;
* a budget in numbers: a limit on runs, a limit on time, a target metric value;
* an attempt can record its parent, so you can return to it from a dead end instead of only moving forward from the latest one.
These toolkits use the Claude Code format, so they install in Waibee Code as regular [skills](/code/skills/) and [plugins](/code/plugins/).
Caution
autoresearch-claude-code keeps the loop going with a hook on the `Stop` event: the hook does not let the agent end its turn until the budget runs out. In Waibee Code, a blocking `Stop` extends the turn a limited number of times in a row. See [Hooks](/code/hooks/#what-a-hook-can-block-or-change). For a long loop with an explicit completion condition, use `/goal` or an external script. Check whether a specific set of hooks is compatible before you run it.
It is easier to start with your own script: the loop above fits in a couple dozen lines of bash, and the rules matter more than the implementation.
# Best practices
> How to work effectively with the Waibee Code agent: context, prompts, configuration, sessions, and automation.
Waibee Code reads files, runs commands, and edits code on its own until the task is done. Your part is to state the task precisely and give the agent a way to check the result.
Almost all the advice below comes from one constraint: the context window fills up fast, and the fuller it gets, the weaker the replies. See [Context window](/code/context-window/).
## Set up the project once
[Section titled “Set up the project once”](#set-up-the-project-once)
### WAIBEE.md
[Section titled “WAIBEE.md”](#waibeemd)
The agent reads `WAIBEE.md` at the start of every session, along with `CLAUDE.md` and `AGENTS.md`. The full list of files is in [Instruction files](/code/configuration/#instruction-files). Keep the file short: it is for what the agent can’t work out from the code on its own.
| Worth keeping | Not needed |
| -------------------------------------------------------------- | ------------------------------------------ |
| Non-standard build and test commands | What the code itself shows |
| Where your style departs from the language’s conventions | The language’s standard conventions |
| How to run the tests and the linter in this particular project | API documentation (a link is better) |
| Branch naming and PR conventions | Details that change often |
| Required environment variables | A description of every file in the project |
| Known pitfalls and non-obvious behavior | Obvious advice like “write carefully” |
Test every line with one question: would the agent start making mistakes without it? If not, delete it. If the agent keeps ignoring a rule, the file is probably too large and the rule gets lost among the rest. Keep `WAIBEE.md` in git.
You can move a long section into a separate file, but the cost depends on how you reference it. A line that contains only `@docs/db.md` pulls in the whole file, and it takes up context in every session (a file larger than 40 KB is not pulled in at all). The same path inside a sentence (“before migrations, read `@docs/db.md`”) stays plain text: the file does not enter the context, and the agent reads it itself when it needs it.
### Permissions
[Section titled “Permissions”](#permissions)
By default the agent asks for permission before edits and commands, except for recognized read-only commands and actions on the `allow` list. Pick the mode and the `allow`/`deny` lists to fit the task. See [Permissions](/code/permissions/).
### CLI or MCP
[Section titled “CLI or MCP”](#cli-or-mcp)
There are two ways to reach an external service: a command-line tool or an MCP server. The difference is cost. An MCP server’s tools take up room in every request, even if you use the server only once (see [The cost in context](/code/ecosystem/#the-cost-in-context)). A CLI costs nothing until the agent calls it, and the call goes through regular `Bash`.
**If there is a mature CLI, use the CLI.** MCP is for cases where there is no CLI, or where interactive authorization and a structured response matter.
| Task | Command instead of a server |
| --------------------------------------- | --------------------------------------------------------------------------------------------------------------- |
| GitHub: issues, PRs, reviews, workflows | `gh issue view 142`, `gh pr create --fill`, `gh pr diff`, `gh run list`, `gh api repos/{owner}/{repo}/...` |
| Git history and change analysis | `git log -S 'parseConfig' --oneline`, `git blame -L 40,80 file.rs`, `git diff main...HEAD --stat` |
| Postgres | `psql -c '\d+ orders'`, `psql -c 'explain analyze select ...'` |
| Kubernetes | `kubectl get pods -o wide`, `kubectl logs deploy/api --since=15m`, `kubectl describe pod X` |
| Docker | `docker compose ps`, `docker compose logs --tail=100 api` |
| AWS, GCP | `aws s3 ls s3://bucket/prefix/`, `aws logs tail /aws/lambda/fn --since 10m`, `gcloud run services describe api` |
| HTTP and JSON | `curl -s https://api.example.com/v1/health \| jq .`, `jq '.items[] \| .id' data.json` |
| Searching code and files | `rg 'TODO\(billing\)' -n`, `fd -e sql . migrations/` |
| Log analysis | `grep -c ERROR app.log`, `awk '{print $1}' access.log \| sort \| uniq -c \| sort -rn \| head` |
The agent learns an unfamiliar tool on its own: “figure out what `flyctl` can do with `flyctl --help`, and deploy the branch to a preview environment”.
MCP makes sense for Figma, Sentry, Jira, and the like: they either have no convenient CLI, need OAuth, or return structured data you would otherwise have to parse. Connecting a server is covered in [MCP](/code/mcp/), and ready-made sets in [Recommended extensions](/code/toolkit/).
Also check the language server with `/lsp`. A binary you install once (`rust-analyzer`, `gopls`, `pyright`, and similar) gives the agent precise go-to-definition, reference search, and diagnostics after each file edit. See [Language servers](/code/lsp/).
### Extend the agent
[Section titled “Extend the agent”](#extend-the-agent)
* **Install ready-made extensions.** Plugins (`/plugin`) bring skills, commands, hooks, and MCP servers in one package (see [Plugins](/code/plugins/)). Extensions written for Claude Code work too. Where to look for them is in [Finding extensions](/code/ecosystem/), and sets for different tasks are in [Recommended extensions](/code/toolkit/).
* **Write your own.** Turn a frequent prompt into a `/name` command, and move project knowledge and procedures into a skill. See [Skills and commands](/code/skills/).
* **What to use for what.** A skill is for knowledge and procedures; a command for a repeated prompt; a [subagent](/code/skills/#subagents) (`.waibee/agents/`) for an isolated context for a narrow task; a [hook](/code/hooks/) for actions that must always happen; [MCP](/code/mcp/) for connecting external tools and data.
* **Don’t install things just in case.** Every extension takes up room in the context and makes it harder for the agent to choose a tool. Keep installed what you use and turn off the rest. See [The cost in context](/code/ecosystem/#the-cost-in-context).
## State the task precisely
[Section titled “State the task precisely”](#state-the-task-precisely)
The more precise the prompt, the fewer corrections later. Name the files, the constraints, and an existing example to follow. The structure of a prompt and examples are in [Example prompts](/code/prompts/#what-makes-a-good-prompt).
There are several ways to pass context. `@` completes a file path in your prompt, and the agent reads the file itself. A screenshot pasted from the clipboard (`Cmd/Ctrl+V`) goes to the agent as an image. If you reference an image by path with `@`, the agent opens it with the `Read` tool, and the model sees the image too. For a link, the agent opens the page with `WebFetch`.
When you are getting to know an unfamiliar project, ask the agent questions the way you would ask a colleague: “how is logging set up?”, “what does this function on line 134 do?”, “which edge cases does this handler cover?”.
## Explore, plan, implement
[Section titled “Explore, plan, implement”](#explore-plan-implement)
On an unfamiliar or large task, don’t let the agent start editing right away: it risks solving the wrong problem. Walk it through in steps.
1. **Explore.** “read the `reports/` directory and explain how the report is built today”.
2. **Plan.** “what has to change to add CSV export? write a plan”. Check the plan and correct it if needed.
3. **Implement.** “follow the plan, add tests for an empty report and for Unicode, run them, and fix the failures”.
For a small, clear change (a typo, a log line, a rename), ask for it right away, without a plan.
## Give the agent a way to check the result
[Section titled “Give the agent a way to check the result”](#give-the-agent-a-way-to-check-the-result)
The agent stops when the result “looks done”. If only you can check it, the whole check falls on you. Give the agent something that delivers a verdict on its own: tests, a build exit code, a linter, a comparison with a reference, a screenshot. Then the agent runs the loop itself: it makes the change, runs the check, reads the result, and fixes what is wrong.
Ready-made prompts for [tests](/code/prompts/#tests), [debugging](/code/prompts/#debugging), and [checking the interface](/code/prompts/#interface) are collected on the examples page.
You decide how strictly to require a check: right in the prompt (“make the change and run the tests right away”); for the whole session with [`/goal`](/code/goal/) (the agent keeps taking turns until the goal is met or a stop condition is hit); or with a fresh look from a subagent that reviews the work. What to check yourself once the agent says “done” is in [The developer’s role](/code/validation/#what-to-check-in-the-result).
When a check gives a number (response time, size, accuracy) instead of pass or fail, you can let the agent run its own loop of experiments against that metric. See [Autoresearch](/code/autoresearch/).
## Start a large task with an interview
[Section titled “Start a large task with an interview”](#start-a-large-task-with-an-interview)
Before you take on something big, let the agent interview you with the `AskUserQuestion` tool and write the outcome to `SPEC.md`. A ready-made prompt for such an interview, and the signs of a good one, are in [The developer’s role](/code/validation/#interview-before-code).
This is the basis of the spec-driven approach. That approach and other ways to organize the work (test-driven, author and reviewer, an autonomous run) are covered in [Development workflows](/code/workflows/). What stays on you, and the signs that help you catch the agent’s mistakes, are in [The developer’s role](/code/validation/).
## While the agent works
[Section titled “While the agent works”](#while-the-agent-works)
**Correct it right away.** `Esc` stops the current turn. You don’t have to stop it, though: a message you write while the agent is working reaches it at the next step (see [Interface](/code/features/#interface)). If you correct the same thing twice, the context is already cluttered with failed attempts: open a new chat (`/new`) with a refined prompt.
**Watch the context.** A new chat between unrelated tasks, `/btw` for a side question, and other techniques are collected in [Saving context](/code/context-window/#saving-context).
**Hand code exploration to a subagent.** “use a subagent to find out how a dropped connection is handled during streaming”: the subagent reads the files it needs in its own context and returns a short summary without cluttering the main conversation. Use the same technique for review: “have a subagent check this change for edge cases”.
## Sessions and scale
[Section titled “Sessions and scale”](#sessions-and-scale)
Sessions are saved: name them (`/rename`), come back to them (`--resume`, `/sessions`), and use `/fork` to branch off a conversation.
For parallel work, open several chats (`Ctrl+N`) and keep their edits in separate git worktrees so they don’t collide. All chats and their subagents are visible in the agent overview: `Tab` with an empty input field. How to set up an author and reviewer pair is in [Development workflows](/code/workflows/#author-and-reviewer).
`waibee run "..."` works without a conversation: in CI, a git hook, or a script. For migrations and bulk edits, run it in a loop over a list of files, and try the prompt on two or three files first. If the loop reads its list from stdin, add `< /dev/null` to `waibee run`, or the first run will consume the rest of the list (see [Input from stdin](/code/headless/#input-from-stdin)). Flags, output formats, and exit codes are in [Headless mode](/code/headless/).
## Next steps
[Section titled “Next steps”](#next-steps)
Ready-made prompts for common tasks, including detailed multi-part prompts, are collected in [Example prompts](/code/prompts/).
# Claude Code compatibility
> Skills, commands, hooks, subagents, plugins, and settings from .claude work in Waibee Code. What is read and what differs.
Waibee Code reads configuration in Claude Code format. If you have used Claude Code, your setup carries over without changes: `CLAUDE.md` and the `.claude/` directory (`skills/`, `commands/`, `agents/`, `settings.json`), both in the project and in `~/.claude/`.
Waibee Code also has its own `.waibee/` directory with the same format. When names collide, the project wins over the global directory, and `.waibee/` wins over `.claude/`.
## What carries over
[Section titled “What carries over”](#what-carries-over)
| Feature | Read from | Details |
| -------------- | -------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Skills | `.claude/skills/` | `SKILL.md` with the fields `name`, `description`, `argument-hint`, `user-invocable`; `allowed-tools` is read but means something different, see [below](#what-works-differently) and [Skills](/code/skills/#skills) |
| Slash commands | `.claude/commands/` | Markdown with the substitutions `$ARGUMENTS`, `$1`, `` !`cmd` ``, see [Custom commands](/code/skills/#custom-commands) |
| Hooks | the `hooks` key in `.claude/settings.json` and `~/.claude/settings.json` | the same configuration format, exit codes, and JSON response; the differences are in [Claude Code compatibility](/code/hooks/#claude-code-compatibility) |
| Subagents | `.claude/agents/` | Markdown with frontmatter, see [Subagents](/code/skills/#subagents) |
| Plugins | `.claude-plugin/`, marketplace | `plugin.json` and `marketplace.json` in Claude Code format. `waibee plugin list` also shows plugins installed by Claude Code, see [Plugins](/code/plugins/) |
| MCP servers | `.mcp.json`, `.claude/settings.json`, `~/.claude/settings.json` | the `mcpServers` key, including an `oauth` block with `clientId` and `callbackPort`, see [MCP](/code/mcp/) |
| Instructions | `CLAUDE.md`, `CLAUDE.local.md`, `.claude/CLAUDE.md`, `~/.claude/CLAUDE.md` | `@` includes, see [Instruction files](/code/configuration/#instruction-files) |
| Rules | `.claude/rules/`, `~/.claude/rules/` | loaded at startup or by `paths`, like instructions in nested folders, see [Instruction files](/code/configuration/#instruction-files) |
| Settings | `.claude/settings.json`, `~/.claude/settings.json` | read as long as there is no `.waibee/settings.json` next to them, see [Settings](/code/configuration/#settings-settingsjson) |
| Permissions | `permissions.allow` and `permissions.deny` | `Bash(...)` rules are read the same way as in Claude Code: an exact command, a `:*` prefix, `*` anywhere, see [Rules in Claude Code format](/code/permissions/#rules-in-claude-code-format) |
| CLI commands | `waibee` flags and subcommands | `waibee -p`, `--output-format`, `--append-system-prompt`, `-r`, `--continue`, `waibee mcp add ` and `-- `, plus the Claude Code spellings from [Names from earlier versions](#names-from-earlier-versions). `-c` means something else, see [What works differently](#what-works-differently) |
## What works differently
[Section titled “What works differently”](#what-works-differently)
* **`allowed-tools` in a skill or command.** In Claude Code, this field allows the listed tools without approval and restricts nothing. In Waibee Code it does the opposite: it restricts the tool set for the turn the command starts and allows nothing without approval, see [Custom commands](/code/skills/#custom-commands).
* **`-c` is `--cwd`.** In Claude Code, `-c` continues the last session. Here `-c` (and `-C`) sets the working folder, and the long `--continue` continues the last session.
* **`dontAsk`.** In the settings file (`permissions.mode`), this spelling is read as `trust`, see [approval exceptions](/code/permissions/#four-modes). In a subagent’s `permissionMode` field, it keeps its Claude Code meaning: everything that would need approval is rejected.
* **Local project files.** Of the pair `.waibee/settings.local.json` and `.claude/settings.local.json`, only one file is read: if the first exists, the second is ignored. The third answer to a [permission request](/code/permissions/#approvals) creates `.waibee/settings.local.json`, and from then on the rules in `.claude/settings.local.json` stop applying, so move them to the new file. MCP servers are read from both files.
* **Hooks in `settings.local.json`.** Waibee Code does not read hooks from local files, in either `.claude/` or `.waibee/`. Move a hook that Claude Code takes from `.claude/settings.local.json` into `settings.json`, see [Where hooks are declared](/code/hooks/#where-hooks-are-declared).
## What does not carry over
[Section titled “What does not carry over”](#what-does-not-carry-over)
* **Hooks on other events.** Waibee Code supports the events in the [table](/code/hooks/#events). A hook on any other Claude Code event, such as `PermissionRequest`, is skipped silently. The other differences in hooks are collected in [Claude Code compatibility](/code/hooks/#claude-code-compatibility) on the hooks page.
* **Some `SKILL.md` fields.** Fields other than those listed in the table are not read, including `disable-model-invocation`: the agent can still load a skill with this field by itself.
* **Some settings.** The `model` key from `.claude/settings.json` is not used. The permission mode is set with the `permissions.mode` key; `permissions.defaultMode` and `permissions.ask` have no effect, see [Settings reference](/code/settings/#how-files-are-read).
* **Permission rules for other tools and for `Bash` parameters.** `Read(./.env)`, `WebFetch(domain:example.com)`, `Bash(timeout:*)`, or `Bash(run_in_background:true)` block nothing. To exclude files, use [`.waibeeignore`](/code/configuration/#excluding-paths); for domains, use the [domain filter](/code/permissions/#domain-restrictions).
* **Some subagent fields.** `color`, `memory`, `initialPrompt`, and a few other fields are accepted and do nothing, and of the `isolation` values only `worktree` works. The full list is in [Subagents](/code/skills/#subagents).
* **MCP servers from `~/.claude.json` and the `mcpServers` field in `plugin.json`.** These are not read. Servers come from `settings.json` and `.mcp.json`, and a plugin’s servers come from its own `.mcp.json`, see [MCP](/code/mcp/).
* **`lspServers`** in a plugin manifest are not read: Waibee Code decides which language servers to start from its own list, see [Language servers](/code/lsp/).
* **Output styles** (`/output-style`) are not supported.
## Names from earlier versions
[Section titled “Names from earlier versions”](#names-from-earlier-versions)
Names that come from Claude Code or from early versions of Waibee Code still work and mean the same as the current ones.
Tools:
| Earlier name | Current name | Parameters |
| ------------ | ----------------- | ---------------------------------- |
| `Task` | `Agent` | `agent` instead of `subagent_type` |
| `LoadSkill` | `Skill` | `name` instead of `skill` |
| `AskUser` | `AskUserQuestion` | |
| `KillJob` | `TaskStop` | `job_id` instead of `task_id` |
| `LoadTools` | `ToolSearch` | |
| `lsp` | `LSP` | |
An earlier name matches calls when it appears in a hook’s `matcher`, in `permissions.allow` and `permissions.deny` rules, in the `--allowed-tools` and `--disallowed-tools` flags, in a subagent’s `tools` and `disallowedTools` fields, and in a skill’s or command’s `allowed-tools`. Saved sessions with earlier names open as usual. A hook whose `matcher` matched only the earlier name gets the earlier name and the earlier parameters: `Task.*` sees `Agent` as `Task`, and sees `TaskStop` under its own name.
Commands and flags:
| Spelling | Meaning |
| ------------------------------------------------------------------------- | ------------------------------------------------------------- |
| `waibee -p ""`, `--print` | `waibee run ""`, see [Headless mode](/code/headless/) |
| `--permission-mode ` | `--mode ` |
| `--dangerously-skip-permissions` | `bypassPermissions` mode |
| `--allowedTools`, `--disallowedTools` | `--allowed-tools`, `--disallowed-tools` |
| `waibee upgrade` | `waibee update` |
| `waibee plugins`, `plugin i`, `plugin uninstall`, `plugin marketplace rm` | `waibee plugin`, `install`, `remove`, `marketplace remove` |
| `waibee mcp add -s shared` | the `project` scope |
In a hook, `"blocking": false` means the same as `"async": true`, and `"blocking": true` the same as `"async": false`.
# Commands
> TUI slash commands and CLI subcommands in Waibee Code.
## Slash commands (TUI)
[Section titled “Slash commands (TUI)”](#slash-commands-tui)
Type `/` to open the command menu: the list filters as you type, and Tab completes. `/help` always shows the full list with descriptions.
### Conversation and agent work
[Section titled “Conversation and agent work”](#conversation-and-agent-work)
| Command | Action |
| ----------------- | -------------------------------------------------------------------------- |
| `/help` | All commands and keyboard shortcuts |
| `/guide` | A tour of the interface; take it as many times as you like |
| `/goal` | [Goal mode](/code/goal/): the agent keeps working until a condition is met |
| `/btw ` | A short side question that does not go into the conversation history |
| `/tasks` | The current chat’s plan: the tasks the agent recorded with `TodoWrite` |
| `/diff` | A summary of changes since the last commit (`git diff --stat HEAD`) |
| `/again` | Resend the last message |
### Model and context
[Section titled “Model and context”](#model-and-context)
| Command | Action |
| ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `/model [name]` | Choose a model; with a name, switches right away. See [Choosing a model](/code/models/) |
| `/effort [level]` | Set a reasoning level, or open the Faster to Smarter slider with no argument. Typing `/effort `hints the current model’s accepted levels. See [Reasoning level](/code/models/#reasoning-level-effort) |
| `/compact [what to keep]` | Compact the history. Text after the command says what the summary must keep. See [Context window](/code/context-window/) |
| `/status` | Session, context window, counted tokens, and extensions |
| `/config` | Show what the current session runs with: model, reasoning level, permission mode, sandbox, context window, and folder. View only; change these in `/settings` |
### Sessions
[Section titled “Sessions”](#sessions)
| Command | Action |
| ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `/new` | New chat |
| `/cd` | Work in another directory: `/cd ../other-project`, with Tab completion for the directory. If nothing has been said in the chat yet, the chat moves; a conversation already in progress stays where it is, and the directory opens in a new tab next to it. To start the agent in the right folder from the beginning, use `waibee -c ` |
| `/sessions` | Sessions in this folder (`/sessions all` shows all of them) |
| `/resume` | Return to the last session in this folder |
| `/fork` | Branch the session to try another path; both branches are kept |
| `/rewind` | Pick one of your messages and go back to before it in a fork. The message returns to the input to edit. Files are not rolled back. See [Session history](/code/features/#session-history) |
| `/rename` | Set the session title; with no argument, resets it |
| `/export` | Save the conversation to the current folder: JSON copies the raw JSONL log (one JSON object per line) to a `.json` file, and Markdown contains only the main agent’s turns, without subagents |
| `/copy` | Copy the last reply to the clipboard. `/copy code` copies the code blocks from the agent’s replies, `all` all of the agent’s replies in Markdown, `plain` the same replies as plain text, and `panel` the open side panel page |
### Settings and extensions
[Section titled “Settings and extensions”](#settings-and-extensions)
| Command | Action |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `/settings` | Change the main settings and save them to the global file; see the [Settings reference](/code/settings/) |
| `/security` | Open `/settings` at the security section: the sandbox and the [domain filter](/code/permissions/#domain-restrictions) |
| `/sandbox [profile]` | Choose a [sandbox](/code/permissions/#sandbox) profile; with a profile name, turns it on right away. The command does not change a profile pinned with the `--sandbox` flag or the `WAIBEE_SANDBOX` variable |
| `/memory` | Agent memory: global and project notes. `/memory add [user\|project] ` records a fact right away; with no scope, it goes into project memory |
| `/agents` | Subagents available in this folder, with each one’s model and tools |
| `/plugin` | Plugins: browse, install, and remove |
| `/hooks` | [Hooks](/code/hooks/): view, add, disable, and delete |
| `/web` | Open the current sessions in the browser; see [Local web interface](/code/web/) |
| `/mcp` | MCP servers: status, sign-in, and adding servers |
| `/lsp` | The project’s language servers and how to install them |
| `/reload` | Reload skills, commands, subagents, hooks, plugins, and MCP servers; prints what changed |
### Utility
[Section titled “Utility”](#utility)
| Command | Action |
| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `/login`, `/auth`, `/api-key` | Set or update the API key |
| `/doctor` | Check the machine: sign-in, shell, paths, and sandbox |
| `/bug [what happened]` | Build a zip archive for a bug report in the session folder: diagnostics, the last day of the log, and this conversation. Check the archive before you send it |
| `/update` | Install an available update and restart. If the agent was installed by a package manager, prints the update command; see [Updating](/code/install/#updating) |
| `/changelog` | What is new in this version |
| `/quit`, `/exit` | Exit. If the agent is working or messages are waiting in the queue, asks first |
Four more names work but do not show in the menu: `/retry` (same as `/again`), `/plugins` (same as `/plugin`), `/release-notes` (same as `/changelog`), and `/clear` (same as `/new`).
### Several commands on one line
[Section titled “Several commands on one line”](#several-commands-on-one-line)
One line can name several of your own commands or skills in a row: `/plan /review parser walkthrough` runs both, each gets the same trailing text, and everything goes in one turn. The number of names per line is limited, and built-in commands such as `/model` cannot be chained this way. The first name that matches nothing ends the chain and stays as text, so `/etc/hosts is broken` goes through as a plain line.
## CLI subcommands
[Section titled “CLI subcommands”](#cli-subcommands)
| Command | What it does |
| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `waibee run "..."` | A one-off run with no interface; see [Headless mode](/code/headless/) and the [Goal mode](/code/goal/#in-headless-mode) flags. `waibee -p "..."` means the same |
| `waibee serve` | The local web interface; see [Local web interface](/code/web/) |
| `waibee acp` | The ACP server, started by an editor or acpx; see [IDEs (ACP)](/code/ide/) and [ACP in the terminal](/code/acpx/) |
| `waibee auth` | The API key: `login` sets or replaces it, `logout` deletes it, and `status` says whether a key is set and where it comes from, exiting with code `1` if there is no key. `login` prompts for the key, takes it from `--key `, or reads it from stdin with `--from-stdin`. Interactive sessions reload the key, but `WAIBEE_API_KEY` takes precedence over the saved key. A running `waibee run` has to be restarted |
| `waibee config` | [Read and change settings](/code/configuration/#reading-and-changing-settings) (`get [key]`, `set `), the settings file path (`path`), [configuration and sandbox check](/code/configuration/#checking-the-configuration) (`check [--json]`), [folder trust](/code/permissions/#folder-trust) (`trust`), and the [domain filter](/code/permissions/#domain-restrictions): `netsec status`, `enable`, `disable`, `allow `, `block `, `remove ` |
| `waibee mcp` | MCP servers: `add `, `add -- [args]`, `add-json`, `get`, `list [--json]`, `remove [-s ]`, `login [--no-browser]`, `logout`. `status` is another name for `list`. Flags and examples are in [MCP](/code/mcp/#cli-commands) |
| `waibee plugin` | Plugins and marketplaces: `install` (`i`), `list [--json]`, `details`, `validate`, `update`, `remove` (`uninstall`), `enable`, `disable`, `marketplace add\|list\|update\|remove`. You can also write the command as `waibee plugins`; see [Plugins](/code/plugins/) |
| `waibee models` | List models (`list`, the default); `--all` adds alpha and deprecated versions, and `--provider ` keeps only one provider’s models, such as `anthropic`. `info ` prints the details of one model as JSON, and `refresh` updates the list |
| `waibee sessions` | Recent sessions with their IDs |
| `waibee storage` | Disk usage (`status [--json]`) and cleanup (`clean`); see [Disk space](/code/waibee-directory/#disk-space) |
| `waibee audit` | The action log; see [Audit log](/code/features/#audit-log) |
| `waibee doctor` | Check the environment; `--json` for scripts |
| `waibee bundle` | An archive for a bug report; see [Diagnostics and cleanup](/code/features/#diagnostics-and-cleanup) |
| `waibee update` | Check for an update; `--install` installs it, `--force` reinstalls the current version, and `--channel` chooses the channel; see [Updating](/code/install/#updating). `waibee upgrade` is the same |
`waibee --version` prints the version, build, and platform.
`waibee "task"` with no subcommand runs the task the same way as `waibee run` with text output. `-` in place of the task text reads it from stdin, as in [headless](/code/headless/) mode. A single word that looks like a subcommand is not treated as a task: to send it to the agent, write `waibee -- `; see [Headless mode](/code/headless/).
TUI startup flags:
| Flag | What it does |
| ------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `-r`, `--resume [id]` | Open a session by its ID from `waibee sessions`; with no value, the last session in this folder |
| `--continue` | Open the last session in this folder |
| `-c`, `-C`, `--cwd ` | Working folder |
| `-m`, `--model ` | Model: an alias or a full ID |
| `--mode`, `--permission-mode ` | Permission mode for this run; see [Switching modes](/code/permissions/#switching-modes) |
| `--dangerously-skip-permissions`, `--yolo` | `bypassPermissions` mode for this run. Not accepted together with `--mode` |
| `--sandbox ` | [Sandbox](/code/permissions/#sandbox) profile for this run: `off`, `workspace-write`, or `restricted`; [a managed profile takes precedence](/code/configuration/#settings-settingsjson) |
| `--no-audit` | Do not write the audit log for this run |
| `--bare` | Do not load skills, custom commands and agents, plugins, MCP servers, hooks, instructions, or memory; see [Unattended runs](/code/headless/#unattended-runs) |
`--bare`, `-C`, `-m`, `--sandbox`, and `--no-audit` also apply to `waibee serve` and `waibee acp`, where `-m` sets the model for new sessions.
## See also
[Section titled “See also”](#see-also)
Besides the built-in commands, you can add your own: commands, skills, and subagents in [Skills and commands](/code/skills/), extension packages in [Plugins](/code/plugins/), automatic actions in [Hooks](/code/hooks/), and external tools in [MCP](/code/mcp/).
# Configuration files
> Which files Waibee Code reads and where settings, instructions, and memory live.
Waibee Code reads its configuration from two directories: its own **`.waibee/`** and the Claude Code-compatible **`.claude/`**, both in the project and globally. The global directory depends on the OS. The read order and the merge rules depend on the file type; see below.
## Instruction files
[Section titled “Instruction files”](#instruction-files)
Instructions are Markdown files with rules for how the agent works. Waibee Code’s own format is **`WAIBEE.md`**; `CLAUDE.md` and `AGENTS.md` are read as they are.
Global files load first: `WAIBEE.md`, `CLAUDE.md`, and `AGENTS.md` from the data directory (`~/.waibee/` on macOS and Linux) and `~/.claude/CLAUDE.md`. Then the agent walks every folder from the root of the disk down to the working folder and looks in each for:
| File | Purpose |
| ------------------------------------------------------------- | ----------------------------------------------- |
| `WAIBEE.md` | Project instructions, native format |
| `WAIBEE.local.md` | Personal instructions, usually in `.gitignore` |
| `CLAUDE.md`, `CLAUDE.local.md` | Instructions in Claude Code format |
| `AGENTS.md` | A format that several agents read |
| `.waibee/WAIBEE.md`, `.waibee/CLAUDE.md`, `.claude/CLAUDE.md` | Instructions inside the configuration directory |
Instructions in nested folders, such as `src/CLAUDE.md` or `src/AGENTS.md`, are added the first time the agent reads a file under them. After context compaction, they are added again on the next such read. During the startup load, a file with the same content as one already loaded is not added a second time. The “Instruction files” check in `waibee doctor` shows how many files were loaded at startup and roughly how many tokens they take, and warns you if two files declare the same `##` section.
Rules from Markdown files in `~/.claude/rules/` and `.claude/rules/` load in the same order: global ones first, then those from the folders from the root of the disk down to the working folder. A rule without `paths` in its YAML frontmatter is read at startup; a rule with `paths` is read the first time a matching file is read. After compaction, a rule with `paths` is added again on the next matching read.
A line `@` includes the contents of another file. The reference must take up the whole line: `@path` in the middle of a sentence stays text. The path must contain `/`, start with `~/`, or end in `.md`, `.txt`, `.json`, `.yml`, `.yaml`, or `.toml`; otherwise the line is read as a mention. A relative path resolves from the folder of the file that holds the reference. Includes nest up to 5 levels. A file larger than 40 KB and a circular include are replaced with a comment, and a path that does not exist stays in the text as is.
## Settings (settings.json)
[Section titled “Settings (settings.json)”](#settings-settingsjson)
Settings are read from four layers in this order:
1. **Global**: `~/.waibee/settings.json`, or `~/.claude/settings.json` if it does not exist.
2. **Project**: `.waibee/settings.json`, or `.claude/settings.json` if it does not exist. Committed to the repository.
3. **Local**: `.waibee/settings.local.json`, or `.claude/settings.local.json` if it does not exist. Personal, in `.gitignore`.
4. **Managed**: the organization’s read-only file: `/Library/Application Support/waibee/managed.json` on macOS, `/etc/waibee/managed.json` on Linux, `C:\ProgramData\waibee\managed.json` on Windows.
The managed file is checked before the model, MCP servers, and hooks start. If it cannot be read, the JSON is corrupted, it holds a value other than an object, or a key has the wrong type, the launch stops with code `2`. stderr shows the path and the reason. This applies in the terminal, `waibee run`, ACP, and `waibee serve`. An empty file counts as `{}`; a missing file does not stop the launch.
`waibee doctor`, `waibee config check`, `waibee update`, and `waibee auth` work even with a corrupted managed file and report it, so you can check and repair the environment.
For most keys, the value from the last layer that sets it wins. The exceptions:
* The `permissions.allow`, `permissions.granted`, and `permissions.deny` lists are merged across all layers. The `env` and `aliases` objects are merged by key: a key with the same name comes from the last layer.
* The `tui` block is replaced as a whole if it differs from the built-in values. The `privacy.redact` block is replaced as a whole when extra patterns or `disable_default_patterns: true` are set.
* `true` for `storage.auto_cleanup` and `files.skip_integrity_check` in one layer is not overridden by `false` in a later one. The other way around, `false` for `goal.auto_goal`, `audit.enabled`, and `updates.check` is not overridden by `true` in a later one.
* If `netsec.enabled` is on in one layer, `false` in a later one does not turn it off. The `netsec.blocked_domains` lists are merged.
* A non-empty `netsec.allowed_domains` replaces the list from the previous layer; an empty list keeps the previous value.
* A project or local `sandbox.profile: "off"` does not turn off a profile enabled earlier. An explicit `sandbox.profile` in the managed file takes precedence over all other layers, the `--sandbox` flag, and the `WAIBEE_SANDBOX` variable, including when the managed file sets `off`. On a conflict with the flag or the variable, the agent writes one line to stderr and applies the managed value. Without a managed profile, the order is `--sandbox`, then `WAIBEE_SANDBOX`, then the settings.
* `sandbox.allow_write` is taken only from the global settings.
* `sandbox.require` is on if `true` is set in the global or the managed file. The managed file can turn the requirement on but cannot lift a global one. The project and local files do not change this key.
* `sandbox.network.allowed_domains` replaces the previous list as a whole. A missing key keeps the previous layer’s list, and an explicit `[]` blocks all addresses; if no layer has the key, commands in the `restricted` profile have no network access. The list from the managed file takes precedence over all layers; an untrusted folder cannot set this key. This is a separate setting from `netsec.allowed_domains`; see [The restricted profile](/code/permissions/#the-restricted-profile).
* `sandbox.network.allow_unix_sockets` is replaced as a whole by the same rules; `[]` removes the exceptions. Path and platform restrictions are described under [the restricted profile](/code/permissions/#the-restricted-profile).
Only one file of each pair takes effect: `.claude/settings.json` is read only while there is no `.waibee/settings.json` next to it, and its `model` key is not used. The same goes for the local pair: as soon as `.waibee/settings.local.json` appears, `.claude/settings.local.json`, where Claude Code keeps personal `allow` rules, stops being read. The new file is created, for example, by the third answer to an [approval prompt](/code/permissions/#approvals) (“Allow … in this project from now on”): move the rules you need from `.claude/settings.local.json` into it. Hooks and MCP servers are collected differently. Hooks are read from both `settings.json` files of the global pair and both of the project pair, but not from `settings.local.json` or the managed file. MCP servers are read from every file of every layer and also from `.mcp.json` at the project root; `.mcp.json` holds no other settings. The order of the files with servers is described in [MCP](/code/mcp/#which-files-are-read).
The first settings change made from the agent creates `~/.waibee/settings.json` and moves into it whatever was in effect from `~/.claude/settings.json`, except `model`. From then on, settings are read only from the new file. Hooks and MCP servers from `~/.claude/settings.json` still apply.
The global directory depends on the system: `~/.waibee` on macOS and Linux, `%APPDATA%\waibee` on Windows. To override it, set an absolute path in `WAIBEE_DATA_DIR`; see [The .waibee directory](/code/waibee-directory/#global).
Project files (`.waibee/`, `.claude/`, `.mcp.json`) are read only from the folder where the agent was started: parent folders are not searched. If you start the agent from a subfolder of the repository, the project settings are not picked up. `waibee doctor` prints what was read in this run and what was looked for and not found: the “Where servers are read from” check lists every file with MCP servers by its full path.
Some keys from the files of an untrusted folder do not take effect; see [Folder trust](/code/permissions/#folder-trust). All keys and their allowed values are listed in the [Settings reference](/code/settings/).
With the sandbox on, changing the global, project, or local settings file on disk does not change the sandbox, permissions, or hooks of a running session. The managed policy is checked again, though; explicit changes made through the interface are applied separately. How the configuration itself is protected from commands and file edits is described in [Sandbox](/code/permissions/#sandbox).
### Reading and changing settings
[Section titled “Reading and changing settings”](#reading-and-changing-settings)
The Context section of `/settings` and the web Settings page offer `context.compact_at`, `context.idle_compact`, and `context.prompt_cache`. Their values are in the [Settings reference](/code/settings/#context-and-memory).
`waibee config get [key]` prints every setting as `section.label = value`, or just the value if you give a key. `waibee config set ` changes one setting:
```bash
waibee config get
waibee config get context.prompt_cache
waibee config set context.prompt_cache 1h
```
A value outside the allowed choices is refused. A mistyped key gets a suggestion for the closest one.
### Checking the configuration
[Section titled “Checking the configuration”](#checking-the-configuration)
```bash
waibee config check
waibee config check --json
```
The command prints JSON: indented for reading without `--json`, on one line for scripts with `--json`. It contains the merged `settings`, the layers in `layers`, and a preliminary `sandbox` check. Values of environment variables and headers, as well as detected secrets, are masked, including inside strings and hook commands.
Each layer has `layer`, `path`, and `exists`. The layer names are `managed`, `user`, `user compatibility` (`~/.claude/settings.json`), `project` and `project local` (one each for `.waibee/` and `.claude/`), and `project shared MCP` (`.mcp.json`). The paths of the compatible files are listed as candidates: both being present does not mean both were read.
`sandbox` holds `profile`, the `mechanism` (Seatbelt or the Landlock ABI version), the `verdict`, and the `reason` the profile was chosen: `managed policy` (the managed file), `command line or WAIBEE_SANDBOX` (the flag or the variable), or `settings`. If a launch with this profile is impossible, the `refusal` field explains why.
The `sandbox.outside_sandbox` field lists what stays outside the sandbox: MCP servers and language servers, opening files in external programs, git operations with worktrees, internal git operations, updates, work with plugin registries, diagnostics, tools inside the agent process, and the agent’s own services. The `engages` value applies to child commands, not to all of these actions.
| `sandbox.verdict` | Meaning |
| ----------------- | ------------------------------------------------------------------------------------------ |
| `engages` | The chosen profile can restrict commands |
| `falls back` | Commands are not restricted: the profile is `off`, or an optional mechanism is unavailable |
| `refuses` | A launch with this profile is impossible |
The check does not start the model, MCP servers, or hooks. An error in the managed file is written to `managed_error`, and `sandbox.verdict` becomes `refuses`; the report is printed to stdout before the exit with code `2`, and the error text goes to stderr, so parse stdout separately from stderr. If a required sandbox cannot be provided, the exit code is also `2`. For `restricted`, a successful check does not guarantee that the run will start; whether the sandbox was enabled shows up in the [meta of a headless run](/code/headless/#event-stream-stream-json).
## Memory
[Section titled “Memory”](#memory)
The agent keeps its own memory separately from your instructions, also in Markdown:
| File | What it stores |
| ------------------------------------------------------------ | ----------------------------------------- |
| `~/.waibee/memory/USER.md` | Facts about you: preferences, role, style |
| `.waibee/memory/MEMORY.md` at the root of the git repository | Facts about this project |
The agent adds to memory on its own as it works; the `memory.auto` key turns this off. The `/memory` command shows the remembered facts with their source and date and opens the files for editing. `/memory add ` writes a fact to the project memory, and `/memory add user ` to the memory about you.
`memory.max_bytes`, 2 KB by default, sets the threshold at which old automatic entries are removed; see [Settings reference](/code/settings/#context-and-memory). What you add through `/memory add` or by editing the file is never pushed out and can exceed the threshold.
### What goes into memory
[Section titled “What goes into memory”](#what-goes-into-memory)
The agent saves what will outlast the current task:
* a lasting preference: “I generally prefer short answers”;
* a direct request to remember: “remember, I use a screen reader”;
* the same thing said in different conversations about different tasks.
It does not save what only matters now: how to carry out the current task and report on it, the format of a single report, a password or token for this session, or requests to get around system rules.
Only your own words count, so an example from documentation, a line from a log, or the agent’s reply never becomes a fact about you.
The model picks the facts, so something said outright is remembered more reliably than a hint: “in all projects”, “in future conversations”, “remember”. If a fact matters, write it yourself with `/memory add`.
## Excluding paths
[Section titled “Excluding paths”](#excluding-paths)
A **`.waibeeignore`** file in the folder where the agent was started excludes paths from reading and search. The format is the same as `.gitignore`.
Some rules apply even without this file. They exclude:
* `.git`;
* keys and certificates: `*.pem`, `*.key`, `*.p12`, `*.pfx`, `*.ppk`, `*.jks`, `*.keystore`, `id_rsa*`, `id_ed25519*`, `.ssh/`, `.gnupg/`;
* files with credentials: `.env*` (except `.env.example` and `.env.sample`), `.netrc`, `.npmrc`, `.pypirc`, `.pgpass`, `.git-credentials`, `.docker/config.json`, `.kube/config`, credentials for `gh`, `gcloud`, Azure, AWS, Terraform, and RubyGems, and macOS keychains;
* agent settings that hold MCP server tokens and keys: `.mcp.json`, `~/.claude.json`, Claude Code credentials, `settings.local.json` in `.claude/`, `settings.json` in `~/.claude/` and `~/.waibee/`, `.waibee/state/` and `.waibee/secrets.json`, the same `settings.json`, `secrets.json` and `state/` in the [data directory](/code/waibee-directory/#global) wherever it is, and Codex files.
The agent can read the project’s own `.claude/settings.json` and `.waibee/settings.json`: they hold hooks and permission rules, and without them it cannot explain why a hook did not fire.
Secrets are excluded by default so that an instruction from an external source cannot extract them by reading a file. Your rules come after the default ones, so a line such as `!.env.local` makes the path readable and searchable again. The agent settings from the last item cannot be reopened this way: `!` has no effect on them.
In `bypassPermissions` mode, the default rules for secrets are lifted, and the agent can read `.env` and the project’s keys. The rules in your `.waibeeignore` and the excluded agent settings still apply there; see [Permissions](/code/permissions/#four-modes).
The shell command check blocks access to secrets it can recognize, such as `cat .env`. It checks only against the default list, so `!` in `.waibeeignore` does not override it. An arbitrary program can read the file some other way, and only [permissions and the sandbox](/code/permissions/) can restrict it.
## Extension directories
[Section titled “Extension directories”](#extension-directories)
| Directory | What it contains |
| ------------------- | --------------------- |
| `.waibee/skills/` | Skills (`SKILL.md`) |
| `.waibee/commands/` | Custom slash commands |
| `.waibee/agents/` | Subagent definitions |
Each of them is also searched for in `.claude/` and in the global `~/.waibee/` and `~/.claude/`; see [Skills and commands](/code/skills/) for details. Plugins are described on the [Plugins](/code/plugins/) page.
# Context window
> How the context fills up, history compaction, manual and automatic compaction, and ways to save context.
The agent keeps the whole conversation in the model’s context window: every message, every file it read, the output of every command. The window fills up fast, and the fuller it gets, the weaker the replies: the agent starts forgetting early instructions and makes more mistakes.
## Fill indicator
[Section titled “Fill indicator”](#fill-indicator)
The status bar shows how full the window is, as a bar and a percentage. The indicator changes color as the window nears automatic compaction. In a subagent’s window, the indicator shows that subagent’s own context. `/status` shows how many tokens are used and the window size of the current model.
## Subagent context window
[Section titled “Subagent context window”](#subagent-context-window)
Each subagent has its own window. It starts with an empty history and does not receive the main agent’s conversation. The window size depends on the subagent’s model: if its definition sets the `model` field, it is that model’s window; otherwise it is the window of the main agent’s current model. You cannot set the window size as a number. A subagent compacts its history on its own, by the same rules as the main agent.
## History compaction
[Section titled “History compaction”](#history-compaction)
During compaction, older turns are replaced with a summary, and recent messages stay as they are. A limited selection of your recent messages from the compacted part is added to the summary. Long messages are shortened; older ones may survive only as part of the summary. Compaction does not touch the system prompt with your instructions (`WAIBEE.md`, `CLAUDE.md`). The saved conversation does not change and stays available in the interface, including after you resume the session.
* **Automatically.** Compaction starts at the share of the window set by `context.compact_at`: 20 to 70 percent, 70 percent by default.
* **By hand.** `/compact` requests compaction of the context; a short history stays as it is. After the command, you can say what must survive compaction: `/compact keep the list of failed tests and the log path`.
The session’s own model writes the summary using the conversation already in its prompt cache. This gives it the full conversation to work from and improves the summary. Most of the input is read from the cache. There is no separate summary model. [`helper.model`](/code/settings/#helper-model) chooses the model for titles and other small background jobs. Old configurations with `compaction.model` still work.
The context window and the [per-message limits](/code/settings/#per-message-limits) are different constraints. The limits are not set by default. If a limit is set, compaction does not reset it: compaction frees room in the request, but the tokens and time already spent still count, and the limit can stop the work before the task is done.
### Compaction while idle
[Section titled “Compaction while idle”](#compaction-while-idle)
In an interactive session, Waibee Code may compact the conversation while you are away. This does not run in `waibee run` or in a subagent. It starts 54 minutes after the last request, only when all of these hold:
* the context contains at least 200k tokens;
* `context.prompt_cache` is not `5m`;
* the model supports prompt caching (Anthropic models and `waibee/auto`).
It happens at most once per pause. Stop cancels it, and a message sent meanwhile waits until it finishes. The chat then shows a line such as “context shortened while idle 300k → 30k”, with the real token counts. Set `context.idle_compact` to `false` to turn it off. It is on by default.
## Prompt cache
[Section titled “Prompt cache”](#prompt-cache)
`context.prompt_cache` applies only to Anthropic models and `waibee/auto`. It accepts `auto`, `5m`, or `1h`:
* `auto` keeps the main agent’s cache for an hour.
* `5m` keeps it for five minutes. This is cheaper for short sessions.
* `1h` keeps it for an hour. This is cheaper for long sessions with pauses.
Subagents and `waibee run` always use five minutes, including with `auto` or `1h`. Changing the setting can rewrite the cache once.
The [Context settings](/code/settings/#context-and-memory) are in the Context section of `/settings`, the web Settings page, and `waibee config`.
## Saving context
[Section titled “Saving context”](#saving-context)
* Start a new chat (`Ctrl+N` or `/new`) between unrelated tasks: a clean context is almost always better than a long one full of unrelated history.
* Ask a small side question with `/btw`: the answer appears in a popup and does not go into the history.
* Hand code exploration to a subagent: it reads files in its own window and returns a short summary without cluttering the main conversation.
For more techniques, see [Best practices](/code/best-practices/).
# Finding extensions
> Catalogs of skills, registries of plugins and MCP servers, how official sources differ from third-party ones, and what to check before you install.
Waibee Code reads the Claude Code format, so skills, commands, subagents, plugins, and MCP servers written for Claude Code install without changes. The exceptions are listed in [Claude Code compatibility](/code/claude-code/#what-does-not-carry-over) and in the note under [Plugins](#plugins). For specific picks, see [Recommended extensions](/code/toolkit/).
## Skills
[Section titled “Skills”](#skills)
A skill is a directory with a `SKILL.md` file that goes into `.waibee/skills/` or `.claude/skills/`, in a project or globally. To install a skill, you can copy its directory. The sources below help you find one.
| Source | What it is |
| --------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| [skills.sh](https://skills.sh/) | A catalog with search and a CLI. Ranked by installs: a skill installed hundreds of thousands of times usually at least works |
| [skillsmp.com](https://skillsmp.com/) | An aggregator of skills from GitHub, with search by category and profession, and an API |
| [ComposioHQ/awesome-claude-skills](https://github.com/ComposioHQ/awesome-claude-skills) | A curated list by section: code, documents, data, media, business |
| Authors’ repositories | Sets built around a particular approach, for example [mattpocock/skills](https://github.com/mattpocock/skills) |
| GitHub search | Search for the file name `SKILL.md` plus your topic |
The skills.sh CLI installs a skill with one command and detects which agents you have installed:
```bash
npx skills find # search the catalog
npx skills add / # into the project
npx skills add / -g # globally
npx skills list
```
By default, the files go into the agent’s directory inside the project; the `-g` flag installs into your home directory. Waibee Code picks up `.claude/skills/`, so an install “for Claude Code” works with no extra steps. If the CLI did not find Claude Code on your machine, select it in the list of agents during the install.
## Plugins
[Section titled “Plugins”](#plugins)
A plugin brings skills, commands, subagents, hooks, and MCP servers in one package. A registry is a repository with a `marketplace.json` manifest. You register it by `owner/repo`, a git URL, or a local path; see [Plugins](/code/plugins/#marketplace) for details:
```bash
waibee plugin marketplace add mattpocock/skills
waibee plugin install mattpocock-skills@mattpocock
waibee plugin list
```
This works for any repository with a registry manifest, including your team’s internal repository, as long as `git` can access it. Anthropic’s registries are added the same way:
```bash
waibee plugin marketplace add anthropics/claude-plugins-official # the official registry
waibee plugin marketplace add anthropics/claude-plugins-community # third-party plugins that authors submit to Anthropic
waibee plugin marketplace add anthropics/skills # Anthropic skills, such as document-skills
waibee plugin marketplace add anthropics/claude-code # a demo set
```
A plugin from a registry is installed at the commit pinned in its entry. To browse plugins before you install them, see [claude.com/plugins](https://claude.com/plugins). Many plugins also have a registry of their own: superpowers, for example, installs from `obra/superpowers-marketplace`; see [Starter set](/code/toolkit/#starter-set).
Note
You don’t need plugins with language servers: Waibee Code connects language servers itself, see [Language servers](/code/lsp/). A plugin that contains only language servers does not install, and the command tells you why.
## MCP servers
[Section titled “MCP servers”](#mcp-servers)
| Source | What it is |
| ------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| [mcp.so](https://mcp.so/) | A community catalog with search by category, tag, and launch method |
| [smithery.ai](https://smithery.ai/) | A catalog with its own connection: the server runs through the Smithery service, which handles authorization, keys, and sessions |
| [registry.modelcontextprotocol.io](https://registry.modelcontextprotocol.io/) | The protocol’s official registry, still in preview. It is designed as a data source for other catalogs |
| [glama.ai/mcp](https://glama.ai/mcp/servers) | A catalog with search and server ratings for license, quality, and maintenance |
| [modelcontextprotocol/servers](https://github.com/modelcontextprotocol/servers) | Reference implementations of the protocol: Filesystem, Git, Fetch, and others. For third-party servers, the README points to the official registry |
| [punkpeye/awesome-mcp-servers](https://github.com/punkpeye/awesome-mcp-servers) | A list on GitHub, split by topic |
| The service’s documentation | Most large services have their own server, linked from their documentation |
To connect a server, see [MCP](/code/mcp/).
### Official and third-party
[Section titled “Official and third-party”](#official-and-third-party)
The difference is who is responsible for the server.
**Official** servers are built by the owner of the service. They are updated along with its API, usually support OAuth (`waibee mcp login`), and their permissions are limited to what your account is allowed to do. Examples: Sentry, Playwright from Microsoft, Figma, Atlassian, GitHub.
**Third-party** servers are built by the community. They often appear before the official one and cover what the vendor has not gotten to. The trade-off: they can lag behind the API, usually need a personal token in the config, and live only as long as the author wants to maintain them.
To tell them apart, check the repository owner (the service’s organization or a personal account), a link from the official documentation, and the domain in the server URL. If a service has both, start with the official server and switch to a third-party one only when something is missing.
## Before you install
[Section titled “Before you install”](#before-you-install)
Skills, plugins, and MCP servers run with your permissions and see your code. Installing them from unverified sources is the same as running someone else’s script.
* Check the author, the date of the last change, and the open issues in the repository.
* Read what is inside: `SKILL.md`, `plugin.json`, `.mcp.json`. The files are short; it takes a few minutes.
* Pass secrets through environment variables (`${VAR}`), not as a string in the config.
* For an MCP server, narrow its permissions with `permission_level` and the `disabled_tools` list; see [MCP](/code/mcp/#permissions-and-security).
* Install into one project first, not globally. If you like it, move it over.
* A useful check: ask the agent to read the extension’s contents and tell you what it does and where it connects over the network.
## The cost in context
[Section titled “The cost in context”](#the-cost-in-context)
Every installed skill keeps a short description in the context, and the agent loads the full text when it needs the skill. MCP servers put their tool descriptions into every request. While there are few, they go in full. Once there are many, the conversation keeps one line per tool with its name and purpose, and the agent loads the full description before a call; see [Tools on demand](/code/mcp/#tools-on-demand).
So twenty extensions installed “just in case” take up part of the window before your first prompt, and they also get in the way: with a dozen similar tools, it is harder for the agent to pick the right one.
Keep installed only what you use. You can turn off the rest without removing it:
```bash
waibee plugin disable
waibee mcp list # check what is connected
```
Hence the rule for choosing between a server and a command-line tool: a CLI costs nothing until the agent calls it; see [CLI or MCP](/code/best-practices/#cli-or-mcp). For how the window is spent in general, see [Context window](/code/context-window/).
## Web search
[Section titled “Web search”](#web-search)
Plain web search needs no extension: the built-in `WebSearch` searches without a separate API key, and `WebFetch` opens a page by its link; see [Features](/code/features/#web-search).
# Features
> Tools, interface, code navigation, context management, MCP, and search in Waibee Code.
## Agent tools
[Section titled “Agent tools”](#agent-tools)
The agent has tools for working with code and the system: reading and writing files (`Read`, `Write`, `Edit`, `NotebookEdit`), running commands (`Bash`, plus `BashOutput` and `TaskStop` for background commands), navigation and code (`Glob`, `Grep`, `LSP`, `REPL`), the web (`WebSearch`, `WebFetch`), tasks (`TodoWrite`), subagents (`Agent` starts one, `TaskPeek` shows its progress, `Say` lets a subagent write to the main agent), skills and tools on demand (`Skill`, `ToolSearch`, `CallTool`), git worktrees (`EnterWorktree`, `ExitWorktree`), and interaction (`AskUserQuestion`, `Open`, `SidePanel`).
`Read` opens PNG, JPEG, GIF, WebP, BMP, and TIFF images. Large images are downscaled before sending, and the number of images is capped by what the model supports. If a file does not fit, the error says why.
If the model supports PDF, the agent can pass a small PDF to it whole, images and diagrams included. For reads by line range, large documents, and models without PDF support, the agent uses the text layer. `Grep` on a PDF path searches that layer and reports the same line numbers as reading a fragment with `Read`. If native reading is unavailable and a scan has no text layer, you need OCR or page-to-image conversion; document skills help with that.
## Interface
[Section titled “Interface”](#interface)
This section covers the terminal. For how to run the agent in the browser, in an IDE, or from a script, see [Ways to work](/code/#ways-to-work). All keys are listed below, under [Keys](#keys).
* **Multiple chats**: each chat is a separate agent session with its own draft and attachments. The tab bar is always visible, even with one chat, and has a `+` for a new chat; you can click a tab. `!` on a tab means the chat is waiting for your answer, and `●` means something new happened in a background chat.
* **Terminal tab title**: shows `▶` while working, `●` when waiting for you, and `✓` when a turn finished while the terminal was not in focus, along with the session title and project. Windows Terminal, Ghostty, WezTerm, and ConEmu also show a progress indicator.
* **Messages while the agent works**: your text joins the work at the agent’s next step. While a message waits, it shows above the input field, and you can bring it back into the field or remove it. `Ctrl+Enter` or `Ctrl+X Ctrl+S` stops the model’s current reply and sends the queued text right away: what was already written stays in the conversation, and long-running commands and subagents move to the background. With an empty input field, `Ctrl+J` does the same, including in the Zed terminal, which intercepts `Ctrl+Enter`; with text in the field, `Ctrl+J` starts a new line. Typing `!` before new text does the same thing. `/model` and `/effort` typed during a turn take effect from the agent’s next request. Most built-in commands run immediately, while `/compact`, `/goal`, `/again`, `/reload`, `/resume`, and your own commands and skills wait in the queue and run when the turn ends. `/fork` is not accepted during a turn. Messages with images also wait for the turn to end. For what in the queue survives a restart, see [Recovery after a restart](#recovery-after-a-restart).
* **Clickable links and paths**: a URL opens in the browser, and a file path opens in the IDE whose terminal the agent runs in, at the right line if one follows a colon. Outside an IDE, the path opens in the program from `VISUAL` or `EDITOR`, without jumping to the line, or in the system default program if neither is set. No modifier key is needed. Where the terminal supports hyperlinks, the terminal itself also highlights the URL under the cursor. Setting `WAIBEE_NO_HYPERLINKS` to any value turns those links off, and a click then opens the URL through waibee itself. Inside tmux, terminal hyperlinks need the line `set -as terminal-features ',xterm-ghostty:hyperlinks'` in the tmux config, with your terminal in place of `xterm-ghostty`: without it, tmux swallows the escape sequence.
* **Agent overview** (`Tab` with an empty input field): a dashboard of all chats and their subagents, grouped by status. A finished subagent stays in the list: each chat shows the running ones and a few of the most recently finished. `Enter` opens a chat or a subagent view.
* **Working with a subagent**: press `Enter` on its row in the overview to open its window. It works like the main chat: the chat tabs are at the top, the subagent’s name and task are below them, and the first line of its conversation is what the main agent wrote to it. The status bar shows its model, context, and tokens. You can write to it directly: if it has already finished, the reply comes to you and the main agent does not start a new turn; if it is still working for the main agent, your message joins that work and the main agent gets the result. `Esc` or `Ctrl+C` stops it while it works, and `Esc` takes you back once it has finished. Your message appears in its conversation. A continuation is marked with the name or ID of the earlier agent, and an activity indicator runs next to the current action. Any subagent can also tell the main agent something along the way, when a finding changes the next steps, and when it finishes it reports how long it worked and how much it spent. Its window shows how long it has been silent, and shows separately when it is waiting for an answer to a permission request. Results of recent subagents stay available after they finish.
* **Agent questions** (`AskUserQuestion`): a question appears between the conversation and the input field, like a permission request, so the conversation stays visible and scrollable. The options are numbered, and the last one is always a custom answer: start typing on it, and the text goes into the field. If multiple choice is allowed, the answer is the checked options together with what you typed; the browser works the same way. What you type in the field is kept however you leave it, and clearing the field removes that answer. There can be several questions, switched with tabs; whatever you did not answer goes to the agent as “not answered” rather than as a default option. A question from a background chat waits in that chat’s tab.
* **Side panel** (`Ctrl+Y`): the agent puts large reference material there (plans, tables, diagrams) as separate pages, so it does not clutter the chat. Pressing `Ctrl+Y` again cycles through the panel’s pages and then hides it. You can drag the panel’s edge with the mouse.
* **Task list** (`Ctrl+T`): the open items of the plan for your last message show next to the chat. A finished plan and a plan for one of your earlier messages leave no list behind; the whole plan is always in `/tasks`. `Ctrl+T` hides the list and shows it again; the key is written on the list itself. A hidden list comes back with your next message. If you write after a turn that left items open, the agent is reminded of them and closes or clears the plan.
* **Edit diffs**: `Write`/`Edit` cards show the diff right in the chat. A turn that changed files with these tools ends with their names, such as “edited a.rs · b.rs”. It lists the first five names and a count of the rest. Changes made by shell commands are not listed. `/diff` prints a `git diff --stat HEAD` summary.
* **Long tool output** (`Ctrl+O`): a large result collapses into a preview with a line count. `Ctrl+O` shows the full output of every tool in the window on screen (the main chat or a subagent’s window), and pressing it again collapses it back.
* **Status line**: shows the permission mode (`»` means `trust`), the model with its reasoning level in parentheses, such as `opus-5.5 (medium)`, how full the context is, and how many subagents are running and how many are waiting for your answer. While the agent works, the line under the conversation shows how long the turn has run and how many tokens it has written. `Ctrl+S` opens a detailed panel, like `/status`.
* **Pasting images** (`Cmd+V` / `Ctrl+V`): attaches an image to the message from the clipboard or from a copied file path. If the model does not accept images, waibee warns you and suggests switching models with `/model`.
* **Search**: past sessions (`Ctrl+P`), words inside all saved sessions (`Ctrl+F`; `Enter` opens the match), and what you typed before (`Ctrl+R`).
* **Help** (`?` with an empty input field, `Ctrl+H`, or `/help`): commands and the main chat keys.
* **Splash screen**: a splash screen shows at startup, and any key dismisses it. Turn it off with the `tui.show_splash: false` key or the `WAIBEE_NO_SPLASH=1` variable; `WAIBEE_REDUCED_MOTION=1` removes both the splash screen and the indicator animations.
[](/media/code/tui-plan.png)
A demo session: the plan stays next to the chat while you discuss the next edit.
### Mouse
[Section titled “Mouse”](#mouse)
Click a session in the list to open it, or a model to choose it. In settings, you can click toggles and arrows; in dialogs, answer options and buttons. Clicking a command suggestion inserts it into the input field. The wheel scrolls the history, lists, the side panel, and a long permission request. While you are scrolled up in the history, the bottom shows how many new lines have arrived. Selecting and copying with the mouse is covered under [Selecting and copying](#selecting-and-copying).
Clicks and the wheel work if the terminal passes mouse events to the application. This includes IDE terminals; if the terminal intercepts a gesture itself, use the keyboard. In the built-in terminal of a JetBrains IDE (Rider, PyCharm, IntelliJ IDEA) on Windows, waibee leaves the mouse off: that terminal sends mouse events in a form Windows turns into characters in the input field. Scroll the history there with `PageUp` and `PageDown`. Lists and dialogs adapt to the window size.
## Keys
[Section titled “Keys”](#keys)
`?` with an empty input field or `Ctrl+H` shows the main keys in the app; all of them are listed here. `Cmd`, `Shift+Enter`, and `Ctrl+Enter` reach the app only if the terminal passes these combinations through. `Alt+Enter`, `Ctrl+J`, and `Ctrl+X Ctrl+S` work everywhere.
### Chats and navigation
[Section titled “Chats and navigation”](#chats-and-navigation)
| Keys | Action |
| --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Ctrl+N` | New chat |
| `Ctrl+W` | Close the chat. If work is in progress or there is a conversation, it asks first. Closing the last chat closes waibee |
| `Shift+←` `Shift+→` | Previous or next chat |
| `[` `]` with an empty input field | The same |
| `Alt+1` … `Alt+9` | Chat by number, if the terminal passes these combinations. On macOS, if characters get typed instead of switching, use `Shift+←/→` |
| `Tab` with an empty input field | Agent overview; `Tab`, `Esc`, or `q` returns to the chat |
| `Shift+Tab` | Next permission mode |
| `Ctrl+P` | Past sessions |
| `Ctrl+F` | Search for words in all saved sessions |
| `Ctrl+Y` | Side panel: next page, then hide |
| `Ctrl+T` | Hide or show the task list |
| `Ctrl+O` | Show the full output of all tools, or collapse it |
| `Ctrl+S` | Status panel, like `/status` |
| `Ctrl+B` | Move running commands and subagents to the background; inside tmux with the `Ctrl+B` prefix, press it twice |
| `?` with an empty input field, `Ctrl+H` | Help |
| `PageUp` `PageDown` | Scroll the history by half a page |
| `End` with an empty input field | Jump back to the newest output |
| `Esc` twice with an empty input field, while no turn runs | Open [rewind](#session-history), like `/rewind` |
| `Esc` | The first that applies: clear the selection; stop a running subagent in its window, or leave a finished subagent’s window; close suggestions; interrupt the turn; remove images attached to the message. When it closes suggestions or interrupts the turn, `Esc` also removes those images |
| `Ctrl+C` | Interrupt the turn, or stop a running subagent in its window. When the agent is idle: copy if there is a selection; otherwise, pressed twice in a row, exit waibee. A second `Ctrl+C` while a turn is being canceled exits immediately. On the update screen, cancels the update |
You can also exit with `/quit`.
### Message
[Section titled “Message”](#message)
| Keys | Action |
| ------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Enter`, `Cmd+Enter` | Send. While the agent works, the message joins the queue |
| `Alt+Enter`, `Shift+Enter`, `Ctrl+J` with text in the field | New line |
| `Ctrl+Enter`, `Ctrl+X` then `Ctrl+S`, `Ctrl+J` with an empty field | Stop the current reply and send the queued text now, including text restored after a restart; what was written stays, and long-running commands move to the background |
| `!` at the start of the text while the agent works | Send this message now |
| `↑` `↓` | Move a line up or down in multiline text, then through earlier prompts. In an empty field, `↑` first brings back the last queued message |
| `Ctrl+R` | Search earlier prompts: `Ctrl+R` or `↑` for older, `↓` for newer, `Enter` keeps the match in the field, `Esc` clears the field |
| `/` in an empty field, `@` | Command and file suggestions: `↑` `↓` select, `Tab` inserts. `Enter` sends the line if it already ends in a full command or skill name; otherwise it inserts the suggestion |
| `Ctrl+V`, `Cmd+V`, `Shift+Insert` | Paste an image from the clipboard, an image file from a copied path, or text |
| `←` `→` | Move the cursor by a character |
| `Alt+←` `Alt+→`, `Ctrl+←` `Ctrl+→`, `Alt+B` `Alt+F` | Move the cursor by a word |
| `Ctrl+A` or `Home`, `Ctrl+E` or `End` | Move the cursor to the start or end of the whole text |
| `Backspace`, `Delete` | Delete the character to the left or right, or the selected text. On macOS, `Delete` is `Fn+Backspace` |
| `Alt+Backspace`, `Ctrl+Backspace` | Delete the word to the left |
| `Alt+D`, `Ctrl+Delete`, `Alt+Delete` | Delete the word to the right |
| `Ctrl+U`, `Cmd+Backspace` | Delete everything before the cursor |
| `Ctrl+K`, `Cmd+Delete` | Delete everything after the cursor |
| `Ctrl+G` | Restore the last chunk deleted with the keys in the three rows above |
| `Shift+↑` `Shift+↓`, `Shift+Home` `Shift+End` | Select by lines, or to the start or end of the text |
| `Ctrl+Shift+←` `Ctrl+Shift+→`, `Alt+Shift+←` `Alt+Shift+→` | Select by words |
| `↑` in an empty field when images are attached to the message | Image picker: `←` `→` select, `Delete` removes, `Esc` or `Enter` finishes |
### Selecting and copying
[Section titled “Selecting and copying”](#selecting-and-copying)
| Action | What happens |
| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Dragging with the mouse | Selects text in the conversation, the side panel, a window, or the command in a permission request; it is copied when you release. At the window edge, the history scrolls |
| Double-click and triple-click | Select the area around the pointer, or the whole line |
| `Cmd+C` | Copy the selection, including in the input field |
| `Ctrl+C` with a selection | Copy, if the agent is idle. During a turn, `Ctrl+C` interrupts the turn |
| Right-click | Copy the selection, or paste text from the clipboard if nothing is selected |
| `Esc` | Clear the selection |
| `Option` plus drag in iTerm2, `Fn` plus drag in Terminal.app, `Shift` plus drag in other terminals | Selection by the terminal itself, bypassing the app |
### Permission requests and questions
[Section titled “Permission requests and questions”](#permission-requests-and-questions)
Permission request:
| Keys | Action |
| --------------------- | -------------------------------------------------------------------------------------------------- |
| `1` … `4` | Choose an answer by number. A risky command has two answers |
| `↑` `↓`, then `Enter` | Choose an answer with the arrows and confirm |
| `Esc` | Reject |
| `Tab` | Reject with an explanation: `Enter` sends the refusal with your text, `Esc` returns to the answers |
| `Ctrl+O` | Show the whole command; press again to return to the answer options |
| `PageUp` `PageDown` | Scroll a long command; on a MacBook, `Fn+↑` `Fn+↓` |
For how a request behaves while you are typing, see [Approvals](/code/permissions/#approvals).
Agent question:
| Keys | Action |
| -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `1` … `9` | Choose an option. With single choice, the next question comes up, and a lone question is sent right away. With multiple choice, the number checks or unchecks the option. The number after the last option opens a custom answer |
| `↑` `↓` | Move through the options |
| Space | Check or uncheck an option, if multiple choice is allowed |
| `Enter` | Choose the option under the cursor and move on. With multiple choice and nothing checked, checks the option under the cursor. On the last tab, sends the answers |
| `Tab` or `→`, `Shift+Tab` or `←` | Next or previous question |
| `Esc` | Send what has been chosen so far. In the custom answer field, keeps the text and leaves the field without sending |
### Lists and windows
[Section titled “Lists and windows”](#lists-and-windows)
Most lists share the same keys, and letter keys also work in the Russian keyboard layout:
| Keys | Action |
| ----------------------------------- | ------------------------ |
| `↑` `↓`, `j` `k`, `Ctrl+P` `Ctrl+N` | Move through the list |
| `PageUp` `PageDown` | Page through |
| `Enter` | Open or select |
| `Esc`, `q` | Close or go back a level |
In windows with a text field (the model picker, `Ctrl+F` search), letters go into the field, and `Esc` closes the window. These windows have their own keys:
| Window | Keys |
| ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Past sessions (`Ctrl+P`, `/sessions`) | `Enter` open, `d` delete with confirmation, `f` or `*` star, `S` starred only, `a` this folder or all, `g` and `G` to the first and last. Only `Esc` closes it |
| `/settings` | `Enter` toggle or start editing, `←` `→` change the value while editing, `s` save without closing, `Esc` save changes and close; while editing, `Esc` cancels the edit |
| Status panel (`Ctrl+S`) | `c` copy the session ID |
| `/memory` | `a` add a note, `d` forget, `u` restore a forgotten note, `Enter` open the file in the editor |
| `/fork` | `n` new branch, `d` delete a branch, `Enter` switch to a branch |
| `/rewind` | `↑` `↓` select a message, `Enter` go back to before it in a fork, `Esc` close |
| `/effort` | `←` `→` move from Faster to Smarter, `Enter` save for this model, `s` keep for this session only, `Esc` cancel |
| `/export` | `↑` `↓` choose JSON or Markdown, `Enter` write the file |
| API key entry (`/login`) | `Enter` check and save, `Ctrl+U` clear, `Ctrl+H` show or hide the key |
| Proposed goal | `y` or `Enter` pin, `e` put `/goal …` in the input field to edit, `n` or `Esc` dismiss |
| Closing a chat | `y` close, `n` or `Esc` keep |
The keys for `/plugin`, `/mcp`, and `/hooks` are on the [Plugins](/code/plugins/#managing-plugins), [MCP](/code/mcp/#adding-a-server-from-the-agent), and [Hooks](/code/hooks/#how-hooks-run) pages.
## Language servers (LSP)
[Section titled “Language servers (LSP)”](#language-servers-lsp)
The `LSP` tool lets the agent work with symbols through a language server instead of text search: definitions, references, types, and diagnostics right after an edit. Rust, Go, Python, TypeScript/JavaScript, C/C++, and Lua are supported. A server starts on its own if its program is on your `PATH`; `/lsp` shows which servers are ready and which you need to install. More in [Language servers](/code/lsp/).
## Context management
[Section titled “Context management”](#context-management)
The agent compacts older history at the threshold set by `context.compact_at`, and `/compact` requests it by hand. In an interactive session, it may also compact while you are away. See [Context window](/code/context-window/) for the conditions and the prompt cache settings.
## Data protection
[Section titled “Data protection”](#data-protection)
Your organisation’s data protection policy (DLP) on the Waibee router can alert, mask, or block sensitive data. Under the message, the chat shows what the policy did, with the kinds of data and their counts:
| Notice | Meaning |
| -------------------------------- | ------------------------------------------------ |
| ”sent as written” (`alert`) | The model received the value |
| ”masked before sending” (`mask`) | The value was masked before it reached the model |
| ”not sent” (`block`) | The request was not sent |
The notice adds “in a tool result” when all of that data came from a tool. The values you typed are also marked in the message text in the colour of the policy’s reaction: in bold in the terminal, with a tooltip in the web interface. The notices of sent and masked data stay when you reopen the conversation.
A message the policy lets through once its sensitive data is confirmed is sent, and the data then shows as “sent as written”. A blocked request ends with “not sent: your organisation’s data policy blocks what this request holds”. A blocked message you typed stays on screen above the “not sent” notice, and its text comes back to the input field, so you can remove the data and send it again. The blocked message is not kept in the saved conversation. A message the policy still holds after the confirmation ends with “not sent: your organisation’s data policy held it even when acknowledged” and comes back to the input field the same way.
## Provider content filter
[Section titled “Provider content filter”](#provider-content-filter)
If the provider’s content filter stops a reply before anything was shown, Waibee Code retries once on its own. Otherwise, the text shown so far stays, tool calls in that reply do not run, and the turn ends with:
> The provider’s filter stopped this reply. /again to retry, /model to switch models.
The web shows this note with **Try again** and **Switch model** buttons. A `/goal` does not continue after the stop. `waibee run` exits with code `1`.
## Subagents
[Section titled “Subagents”](#subagents)
The `Agent` tool starts a subagent: a full agent with a separate context for a narrow task. An agent definition is a Markdown file with frontmatter in `.waibee/agents/` or `.claude/agents/`; its fields and tool set are covered under [Subagents](/code/skills/#subagents).
[](/media/code/tui-agents.png)
A demo session: two subagents check a task in parallel. The overview shows what they are doing and the state of the other chats.
## MCP
[Section titled “MCP”](#mcp)
External tool servers connect over the Model Context Protocol, using the `stdio`, `http`, or `sse` transport. You declare servers in `settings.json` or `.mcp.json` and manage them with `/mcp` in the TUI and `waibee mcp` in the shell. More in [MCP](/code/mcp/).
## Memory
[Section titled “Memory”](#memory)
The agent keeps its own memory about you and the project, separate from your instructions, and adds to it on its own. `/memory` opens it for editing, and `/memory add ` records a fact right away. For what goes into memory and where it is stored, see [Configuration files](/code/configuration/#memory).
## Web search
[Section titled “Web search”](#web-search)
The `WebSearch` tool searches the internet, and it needs no key: the router runs the search, the same way it does for any other client ([Web search](/router/web-search/)). The agent passes up to five queries in one call, one for each facet of the question, and each runs as a separate search. The pages found appear right under the call: with site icons in the browser, as a numbered list in the terminal. Each search is billed separately from tokens, as described on the router page.
For each query, search returns a one-line summary, titles, and URLs, but not the page text, so before relying on a result, the agent has to open it with `WebFetch`, which downloads a page by URL and turns it into readable text. `WebFetch` needs no key, is always available, and respects the allowed and blocked domain lists. Those lists do not affect search: the router receives only the query text from the model.
## Session history
[Section titled “Session history”](#session-history)
Conversations are saved locally. `/sessions` opens the sessions for the current folder, `/sessions all` shows all of them, and `/resume` returns to the last session in this folder. `/fork` branches the conversation so you can try a different approach. The project files stay shared between the branches.
`/rewind` opens a list of your own messages in this session, newest first, with their time. You can also open it by pressing `Esc` twice on an empty input while no turn is running. Use `↑` and `↓` to select a message, `Enter` to go back, or `Esc` to close the list.
Going back forks the conversation before the chosen message. The fork opens in the same tab, with the message back in the input to edit. Only the conversation goes back: files are not rolled back. The old conversation stays in `/sessions`. In the web interface, the fork button on a message does the same.
`/export` saves the conversation to a file; see the [Commands reference](/code/commands/). Searching for words inside sessions in the terminal is covered above, under “Interface”; in the browser, the search in the session list does the same.
### Recovery after a restart
[Section titled “Recovery after a restart”](#recovery-after-a-restart)
A session survives a Waibee Code restart, including after a crash. When it opens again:
* messages and commands that were waiting in the queue return to the queue, but queued images do not;
* the restored queue is not sent to the agent on its own: `Ctrl+Enter` or a new message sends it, and `↑` in an empty field brings a message back into the field to edit;
* a large conversation file, and a file cut off by a crash on its last line, open as usual.
If the sessions folder stops accepting writes, a warning that the session is not being saved appears at the end of the turn. Unsaved records wait in memory and are written as soon as writes succeed again; exiting waibee before that loses them.
## Audit log
[Section titled “Audit log”](#audit-log)
The log helps you work out what the agent did: which tools it ran, which files it changed, and which actions were denied. It is stored locally, and recording is on by default. In the web interface, the log is in the security section.
In the terminal, you can watch new events, search the log, and export entries:
```bash
waibee audit tail --follow
waibee audit tail --since 1d --refused
waibee audit grep "permission_denied"
waibee audit export --format csv --output audit.csv
```
| Command | Flags |
| -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `waibee audit tail` | `--since ` time window, `1h` by default; `--follow` wait for new events; `--event ` only events of this type, such as `permission_denied`; `--session ` only this session; `--refused` only refusals: blocked addresses and paths, denied actions, and failed calls |
| `waibee audit grep ` | `--regex` search for a regular expression; `--since `, `7d` by default; `--event ` |
| `waibee audit show [YYYY-MM-DD]` | the log for one day, today by default |
| `waibee audit export` | `--from`, `--to` dates as `YYYY-MM-DD`, the last 7 days by default; `--format json`, `csv`, or `md`, `json` by default; `-o`, `--output ` instead of printing to the terminal |
| `waibee audit status` | recording state, log location, and the number of events today |
| `waibee audit disable`, `enable` | turn recording off and on, in the settings |
A duration is a number with a unit: `30m`, `2h`, `7d`. The `--no-audit` flag turns off recording for a single run.
## Diagnostics and cleanup
[Section titled “Diagnostics and cleanup”](#diagnostics-and-cleanup)
`waibee doctor` checks your environment. `waibee bundle` builds a zip archive for a bug report: diagnostics, the last day of the audit log, the tail of the log, recent crash reports, and settings without keys. A conversation goes into the archive only if you name it: `--session `. A conversation over 1 MB keeps only the whole entries of its first and last \~500 KB; add `--full-transcript` to include it whole, with keys removed the same way. Other arguments: a crash ID (`waibee bundle `) to make sure that crash’s report is included; `--audit ` instead of one day, such as `3d`; `--note ` with a description of the problem; `-o`, `--output ` instead of the default name in the current folder. `/bug` in the terminal and in the browser builds the same archive with the current conversation included. Check the archive before you send it: the paths in it contain your username.
To see disk usage and clean up old data, use `waibee storage`. The cleanup steps are in [The .waibee directory](/code/waibee-directory/#disk-space).
# Goal mode
> How the agent keeps working until a condition is met: /goal, the check after every turn, limits, and how to phrase a good condition.
Normally the agent replies and hands control back to you. Goal mode changes that: you set a completion condition once, and the agent keeps working turn after turn until the condition is met.
After each turn, an evaluator model reads the conversation and answers “met” or “not met” with a short explanation. If the goal is not met, the explanation is passed to the agent as a hint, and the agent starts the next turn on its own. If it is met, the goal is cleared automatically.
```text
/goal all tests in tests/auth pass and the linter is clean
```
## When it helps
[Section titled “When it helps”](#when-it-helps)
A goal makes sense when the work has a checkable end and many similar steps:
* migrating a module to a new API until every call site compiles and the tests are green;
* implementing a spec until every acceptance criterion is met;
* working through a long list of linter warnings until the list is empty;
* splitting a large file into modules until each one fits the line limit.
When not to use it: a short edit, open-ended exploration with no clear result (“see what could be improved”), or a task where you judge success by eye. In these cases the loop circles around a vague condition and wastes tokens.
## Commands
[Section titled “Commands”](#commands)
| Command | What it does |
| ----------------------------------- | ----------------------------------------------------------------------------------------------------- |
| `/goal` | Shows the active goal, the number of turns taken, and the limit |
| `/goal ` | Sets the goal. A new goal replaces the previous one. The condition should describe a checkable result |
| `/goal clear` | Clears the goal. `off`, `stop`, `reset`, `none`, and `cancel` also work |
| `/goal --model ` | Sets the goal with a different evaluator model |
The goal takes effect from the next turn: setting it does not start any work, so send your prompt as usual. While a goal is active, the status bar shows a `goal` label, and `/goal` and `/status` show the condition and progress.
The [browser](/code/web/) has no command for this: a target button next to the input field sets the goal. The same button shows the current condition and clears it, and in the session list, sessions that run toward a goal show the same target.
One goal per session. `/new` starts a session with no goal.
## Writing the condition
[Section titled “Writing the condition”](#writing-the-condition)
The evaluator judges by the conversation alone: it does not run commands or read files itself. So the condition must be checkable from what the agent has already shown in the chat. “All tests in `tests/auth` pass” works, because the agent runs the tests and their output ends up in the conversation. “The code is cleaner” does not work: there is nothing to confirm it with.
The evaluator requires evidence: command output, a file and line, or a returned value. The agent saying “done” does not count as evidence, and without evidence the answer is “not met”.
What to include in the condition:
* **One measurable state.** A test result, a build exit code, an empty list, a number of files.
* **How to check it.** How the agent should show it: “`make test` exits without errors”, “`git status` is clean”.
* **Boundaries.** What must not change along the way: “don’t touch other tests”, “no new dependencies”.
Bad: `do it properly`, `fix the bugs`, `improve performance`. Good: `make lint and make test pass without errors, and the public API of the auth module is unchanged`.
## Auto goal
[Section titled “Auto goal”](#auto-goal)
If no goal is set, the agent may suggest a condition itself, once per session, on the first prompt longer than a couple of words. A suggestion does not always appear: it is meant for substantial multi-step work with a checkable result. For questions, explanations, and small edits, the agent suggests nothing and replies as usual.
When there is a suggestion, it appears in an approval dialog together with how it will be checked. `y` or `Enter` sets it as is, `e` puts `/goal ` into the input field for editing, and `n` or `Esc` declines it. In the browser, the suggestion appears as a line above the input field: one button sets it, and the cross declines it. To turn the suggestion off entirely:
.waibee/settings.json
```json
{ "goal": { "auto_goal": false } }
```
## Limits and stopping
[Section titled “Limits and stopping”](#limits-and-stopping)
* **Turn limit.** The [`goal.max_iterations`](/code/settings/#goal-mode-and-background-commands) key sets the number of turns with a goal check, including the first; the `--goal-max-iterations` flag sets it for one run. When the limit runs out, the goal is cleared and work stops.
* **Work does not converge.** If the agent calls no tools for several turns in a row and the goal is still not met, the goal is cleared.
* **Evaluator failures.** A check that fails with an error gives no verdict, so the agent does not start the next turn on its own and waits for you. If the check fails several times in a row, the goal is cleared instead of leaving the session hanging.
* **Provider content filter.** A goal does not continue after the provider’s filter stops a reply. See [Provider content filter](/code/features/#provider-content-filter).
* **Permissions stay the same.** A goal does not widen permissions: if the permission mode asks before running commands, it asks on every turn. For unattended work, switch the mode to `trust` with Shift+Tab: in `acceptEdits` commands still ask. See [Permissions](/code/permissions/).
* **Manual stop.** `/goal clear` at any time. `Esc` interrupts the current turn, but the goal stays set.
The limit, the evaluator model, and the auto goal are set with the `goal.*` keys; see the [Settings reference](/code/settings/#goal-mode-and-background-commands). Project settings override global ones, so you can keep the limit and the evaluator model next to the code they judge. For a single use, set the same things on the spot: `/goal --model ` in the TUI, `--goal-model` and `--goal-max-iterations` in headless mode. By default the evaluator is the [helper model](/code/settings/#helper-model) selected at the moment the goal was set.
Evaluator calls also use tokens, but most of the cost comes from the loop itself: the agent works as many turns as it needs, so a goal with a vague condition is expensive.
## In headless mode
[Section titled “In headless mode”](#in-headless-mode)
If no goal is set, the agent may pick one for the task and set it without asking. Auto selection does not guarantee a goal: for a simple task it may skip the loop.
| Call | What happens to the goal |
| -------------------------------- | ----------------------------------------------- |
| `waibee run "a large task"` | Tries to pick a goal automatically |
| `waibee run --goal "..." "task"` | Uses yours; auto selection does not run |
| `waibee run --once "task"` | No auto goal selection |
| `waibee run "ok"` | A short prompt runs without auto goal selection |
The same `"auto_goal": false` as in the TUI turns auto selection off entirely.
```bash
waibee run "move the auth module to the new client" \
--goal "make test passes, the old client is not used in any file"
waibee run "..." --goal-max-iterations 20 # your own limit on turns with a goal check
waibee run "..." --goal-model # your own evaluator model
waibee run "..." --once # no auto goal selection
```
`--goal-max-iterations` and `--goal-model` also apply to an automatically selected goal, not only to one set with the `--goal` flag.
**What you see on screen.** In `text` format, the condition and the progress of the check go to stderr, and the reply stays in stdout, so `$(waibee run ...)` captures only the reply:
```text
goal: tests in tests/auth pass - proved by: make test exits without errors
continuing: the tests ran, but two in auth::session fail
goal met
```
The evaluator’s reason comes as a paragraph, and the terminal shows only its first line. If the goal is cleared without being met, the last line is `goal aborted:` with the reason: `max_iterations`, `not_converging`, or `consecutive_eval_failures`. In the event stream (`--output-format stream-json`), the same information arrives as `goal_*` events; see [Event stream](/code/headless/#event-stream-stream-json).
If the active goal is not met, the run exits with code `1`, even when the agent chose the goal itself. For a predictable success criterion in CI, set `--goal` explicitly. `--once` turns off auto selection, but an explicitly set goal and a restored goal stay in effect. The full table of [exit codes](/code/headless/#exit-codes) is in the headless guide.
## Next steps
[Section titled “Next steps”](#next-steps)
* [Best practices](/code/best-practices/): how to frame a task and ask for proof of the result.
* [The developer’s role](/code/validation/): what to check yourself when the agent works for a long time.
* [Development workflows](/code/workflows/): where a goal fits into your workflow.
# Headless mode and automation
> waibee run: the agent as a command in a script, in CI, or in someone else's pipeline. Output formats, exit codes, permissions, ready-made recipes.
`waibee run` runs the agent with no interface: a prompt goes in, and the result comes out on stdout. There is no TUI, so you can call the agent from a Makefile, a git hook, a CI step, or another program, including another agent.
Compaction while idle does not run here. With Anthropic models and `waibee/auto`, `waibee run` always uses a five-minute prompt cache, whatever `context.prompt_cache` is set to. See [Context window](/code/context-window/).
```bash
waibee run "explain what calc.py does in one sentence"
cat task.md | waibee run - # prompt from stdin
git diff | waibee run "review this diff" # prompt and data from stdin
```
`waibee "..."` with no subcommand does the same in `text` format. `waibee -p "..."` (or `--print`) also means `waibee run`: `-p` goes before the subcommand, and `--continue` and `--resume ` work with it. The other subcommands are listed in [CLI subcommands](/code/commands/#cli-subcommands).
A word that matches a subcommand runs that subcommand: `waibee doctor` checks the environment instead of sending a prompt. A single word that looks like a subcommand (`waibee sesions`) and a single word starting with `-` don’t reach the agent either: the run exits with code `2` and suggests what you meant. To send such a word as a prompt, put `--` before it: `waibee -- doctor`.
The agent works in your real project: it reads files, runs commands, and edits code. With no `--mode` flag and no `permissions.mode` in settings, the run uses `trust` mode: edits and most commands go through without asking. The run never asks anything and never waits for a person. A call that needs approval is rejected: the agent gets the denial and keeps working, and the denial is recorded in `permission_denials`. See [Permissions in headless mode](#permissions-in-headless-mode).
## Input from stdin
[Section titled “Input from stdin”](#input-from-stdin)
`-` in place of the prompt reads the prompt from stdin, up to 1 MiB. If stdin is a terminal or nothing ever arrives on it, the run exits with code `2`.
If you give a prompt and stdin is not a terminal, whatever arrives on stdin reaches the agent as a separate block after the prompt. That is how `git diff | waibee run "review this diff"` gives the agent both the request and the diff. This block is also capped at 1 MiB. An empty, closed stdin is skipped silently; an open stream with no data is skipped after three seconds with a warning on stderr. `< /dev/null` removes the wait. A stream that never closes (`tail -f log | waibee run "..."`) is read for a limited time; then the run goes ahead with what it has read and says so on stderr.
The run inherits the shell’s stdin. In the loop `while read -r f; do waibee run "fix $f"; done < files.txt`, the first run takes the rest of `files.txt` as data for its prompt, and the loop ends after the first file. Write `waibee run "fix $f" < /dev/null` and the list stays with the loop.
## Output formats
[Section titled “Output formats”](#output-formats)
```bash
waibee run "..." # reply text
waibee run --output-format json "..." # one final record
waibee run --output-format stream-json "..." # event stream, one record per line
```
Without the flag, the output is text. `--format json` is the old spelling of the event stream, the same as `--output-format stream-json`; the two flags are not accepted together. `waibee -p --output-format json "..."` also prints one record.
### Single record: json
[Section titled “Single record: json”](#single-record-json)
`--output-format json` prints one line when the run finishes. A shortened example:
```json
{"type":"result","result":"`calc.py` defines an `add(a, b)` function and, when run as a script, adds the two numbers given as command-line arguments and prints the result.","session_id":"s1","agent_id":"a1","num_turns":3,"stop_reason":"end_of_turn","is_error":false,"duration_ms":6855,"ttft_ms":2729,"permission_denials":[],"usage":[{"model":"anthropic/claude-sonnet-5.5","purpose":"turn","input_tokens":8,"output_tokens":154,"cache_creation_input_tokens":0,"cache_read_input_tokens":45306}]}
```
`result` holds the main agent’s last reply: the text it wrote after its last tool call or, if it replied once more without a tool (for example, after the goal check), only that last reply. `num_turns` counts the turns the main agent started, including a final interrupted or failed turn and the schema correction of the reply; subagent turns and internal context updates are not counted. The other fields are the same as in `done` in the stream below, and `usage` holds the `models` rows from the `usage` event. To get the reply: `waibee run --output-format json "..." | jq -r .result`.
### Event stream: stream-json
[Section titled “Event stream: stream-json”](#event-stream-stream-json)
Below is a shortened example of the stream; events may carry extra fields.
```jsonl
{"type":"meta","protocol":"waibee/1","session_id":"s1","model":"anthropic/claude-sonnet-5.5","permission_mode":"default","sandbox":{"profile":"workspace-write","reason":"command line or WAIBEE_SANDBOX","mechanism":"macos/seatbelt","verdict":"engages"},"tools":["Read","Glob","Grep"],"bare":true}
{"type":"text","agent_id":"a1","text":"`calc.py` defines an `add` function for two floats and, when run as a script, prints the sum of its first two command-line arguments."}
{"type":"usage","models":[{"model":"anthropic/claude-sonnet-5.5","purpose":"turn","input_tokens":8,"output_tokens":148,"cache_creation_input_tokens":3284,"cache_read_input_tokens":6214}]}
{"type":"result","session_id":"s1","agent_id":"a1","result":"`calc.py` defines an `add` function for two floats and, when run as a script, prints the sum of its first two command-line arguments.","num_turns":3,"stop_reason":"end_of_turn","is_error":false,"duration_ms":6156,"ttft_ms":2329,"permission_denials":[],"usage":[{"model":"anthropic/claude-sonnet-5.5","purpose":"turn","input_tokens":8,"output_tokens":148,"cache_creation_input_tokens":3284,"cache_read_input_tokens":6214}]}
{"type":"done","session_id":"s1","agent_id":"a1","num_turns":3,"stop_reason":"end_of_turn","is_error":false,"duration_ms":6156,"ttft_ms":2329,"permission_denials":[]}
```
After a successful start, the stream opens with `meta`. Its `sandbox` field holds the outcome of turning on the sandbox, and [waibee config check](/code/configuration/#checking-the-configuration) checks the sandbox in advance. `tools` lists the tools available at start, and `bare` shows whether the [run without extensions](#unattended-runs) is on.
At the end come `usage`, then one `result` (as in the single-record format), and right after it one `done`. Take the final reply from `result.result`: the `text` events joined together can contain intermediate replies. For example: `jq -r 'select(.type == "result") | .result' events.jsonl`. How the stream ends on a startup error or a signal is described [below](#signals-and-shutdown).
| Event | Fields | Meaning |
| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `meta` | `protocol`, `session_id`, `model`, `permission_mode`, `cwd`, `started_at`, `version`, `platform`, `sandbox`, `tools`, `bare` | The run started |
| `text` | `agent_id`, `text` | A fragment of the agent’s reply |
| `tool_call` | `agent_id`, `call_id`, `tool`, `args` | A tool call. For an MCP tool called through `CallTool`, this holds the name and arguments of the tool itself |
| `tool_result` | `agent_id`, `call_id`, `content`, `is_error`, `elapsed_ms`, `sources` | The result of the call with the same `call_id`. `sources` is present if the tool returned sources, as web search does |
| `injected` | `agent_id`, `text`, `origin` | A message to the agent that did not come from the prompt: a reply from a `Stop` hook, a notice that a background command or subagent finished, and the like |
| `reminder` | `agent_id`, `text` | An internal note added to the agent’s context |
| `sub_agent_started` | `agent_id`, `parent_agent_id`, `call_id`, `task`, `model`, `agent_name`, `depth` | A subagent started |
| `sub_agent_done` | `agent_id`, `call_id`, `summary`, `usage`, `duration_ms`, `is_error`, `ended` | A subagent finished |
| `goal_changed` | `agent_id`, `condition` | A goal was set or cleared (`condition: null`) |
| `goal_evaluated` | `agent_id`, `decision` (`met` or `not_met`), `reason` | The result of a goal check |
| `goal_achieved` | `agent_id`, `duration_secs` | The goal was met |
| `goal_aborted` | `agent_id`, `reason` | The goal was dropped without being met |
| `error` | `agent_id`, `class`, `message`, `retryable` | An error. `class` names its kind, for example `startup` if the run never reached the agent’s work, or `execution` if work already under way failed; `retryable` says whether a retry makes sense. An error on its own does not necessarily end the run |
| `usage` | `models` | Token usage by model, see below |
| `result` | as in `done`, plus `result`, `usage`, and `structured_output` | The outcome of the run |
| `done` | `agent_id`, `session_id`, `stop_reason`, `is_error`, `num_turns`, `duration_ms`, `ttft_ms`, `permission_denials`, and the stop-reason fields | The last line of the stream |
`ttft_ms` is the time to the first text, reasoning fragment, or tool call; it is `null` if there were none. Reasoning does not appear in the output. Ignore unknown event types and extra fields.
`stop_reason` in `result` and `done` tells you how the work ended:
| Value | What happened |
| ---------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `end_of_turn` | The agent finished its reply on its own |
| `max_turns` | The turn limit ran out; the number is in the `turn_limit` field |
| `input_budget`, `output_budget`, `time_budget` | A [run limit](#run-limits) ran out. The amount used and the limit are in neighboring fields: `billable_input_tokens` and `billable_input_limit`, `output_tokens` and `output_limit`, `elapsed_seconds` and `elapsed_limit` |
| `cut_short` | The work was stopped; the reason is in `stop_class`, see below |
| `cancelled` | A signal interrupted the run |
| `error` | An error, including a goal that was not met or a reply that failed schema validation when the turn ended normally |
| `stop_class` | Reason |
| -------------------- | ---------------------------------------------------------------- |
| `loop` | The agent [went in circles](/code/how-it-works/#the-agent-loop) |
| `hook` | A `PostToolUse` hook stopped the work, see [Hooks](/code/hooks/) |
| `max_tokens` | The model’s reply kept hitting the length limit |
| `stream_interrupted` | The model’s response stream kept breaking off |
| `content_filter` | The provider’s content filter blocked the reply |
| `tool_call_lost` | The model ended its reply with a tool call that never arrived |
| `empty_response` | The model returned an empty reply several times in a row |
`is_error: true` means the process exits with a nonzero code, see [Exit codes](#exit-codes).
A subagent run shows up as `sub_agent_started` and `sub_agent_done` lines. Both carry the `call_id` of the `Agent` call that started the subagent, and the subagent’s own `text`, `tool_call`, and `tool_result` carry its `agent_id`, so you can nest its work under the call. `sub_agent_done` has no `ended` field if the subagent finished on its own; otherwise `ended` holds the reason: `failed` (then `is_error: true`), `cancelled`, `max_turns`, or a value from the tables above. Every `sub_agent_started` gets a `sub_agent_done` before `done`, including a background subagent the run did not wait for. Text mode prints only the main agent’s reply.
While a goal is active, `goal_*` events show its progress. In `text` format, the same information goes to stderr as lines; see the example in [Goal mode](/code/goal/#in-headless-mode).
The `usage` line comes before `result` when counters are available. `models` has one row per pair of model and `purpose`. The purpose is `turn` for turns of the agent and its subagents; helper calls carry their own purpose: `compaction` (history compaction), `session_title` (the title), `memory_extraction` and `memory_consolidation` (memory), `goal_evaluation` and `goal_suggestion` (checking and suggesting a goal), `page_distillation` (a page summary for `WebFetch`), `web_search` (web search). `input_tokens` is fresh input; the cache is counted separately. `null` in a cache counter means there is no data, not zero usage.
### Output that follows a JSON Schema
[Section titled “Output that follows a JSON Schema”](#output-that-follows-a-json-schema)
`--json-schema ` validates the final reply. The schema is parsed before the first request to the model; invalid JSON or an invalid schema ends the run with code `2`. A reply wrapped entirely in one code block, with no language or with `json`, is read without the wrapper.
alert-schema.json
```json
{
"type": "object",
"properties": {
"summary": {"type": "string"},
"files": {"type": "array", "items": {"type": "string"}}
},
"required": ["summary", "files"],
"additionalProperties": false
}
```
```bash
waibee run --once --output-format json --json-schema alert-schema.json \
"Describe the purpose of the project and list the main files" < /dev/null
```
If the reply is JSON and matches the schema, the `result` object gets a `structured_output` field. On a mismatch, the agent gets the validation error and corrects its reply once. If the reply still fails validation, `result` and `done` get `schema_error` and `is_error: true`, and the process exits with code `1`. A real `stop_reason`, such as `max_turns` or `time_budget`, is kept; only a normal `end_of_turn` becomes `error`. The correction draws on the shared turn and time limits; if a limit has already been reached, no new request is made.
### Last reply to a file
[Section titled “Last reply to a file”](#last-reply-to-a-file)
`-o ` or `--output-last-message ` atomically writes only the text from `result.result`. The stdout format stays the same. On an error, the reply the agent managed to get is written too, if the write fits within the shutdown time; after an interruption, the file is not guaranteed to exist.
### stdout, stderr, and the log
[Section titled “stdout, stderr, and the log”](#stdout-stderr-and-the-log)
**Only the result goes to stdout.** stderr gets the permission mode at the start of the run (in `text` format), what was skipped in an untrusted folder, and the progress of the goal check. The program’s own warnings go to the log in `logs/` in the [data directory](/code/waibee-directory/#global); with `RUST_LOG` or `DEBUG=1` in the environment, they are also printed to stderr. That is why `$(waibee run ...)` captures only the reply.
## Exit codes
[Section titled “Exit codes”](#exit-codes)
| Code | Meaning |
| ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `0` | The work is done: the goal was met or, with no goal, the agent finished its reply on its own (`stop_reason: end_of_turn`) or a [hook](/code/hooks/) stopped or blocked it |
| `1` | The work failed: the goal was not met, a limit was hit, the work was cut short (`cut_short`, except a stop by a hook), a model or agent error occurred, or the final reply failed schema validation or could not be written to the file |
| `2` | An invocation, environment, or authentication error: an unknown flag or flag value (including `--effort` and `--max-turns 0`), an unknown model in `-m` or `--goal-model`, an unknown name in `--tools`, a rule in `--allowed-tools` or `--disallowed-tools` that does not parse, a `--cwd` folder that does not exist, `--no-session-persistence` together with `--resume` or `--continue`, an invalid schema, a missing or rejected router key, a session that is not found or is in use, empty stdin with `-`, an invalid `WAIBEE_DATA_DIR`, a [managed settings error](/code/configuration/#settings-settingsjson), or an [unavailable required sandbox](/code/permissions/#sandbox). The reason is written to stderr |
| `130` | The first `SIGINT`, including `Ctrl+C` |
| `143` | `SIGTERM` |
In a pipeline, `--goal` defines what counts as success, and the exit code decides whether the step fails. See [Goal mode](/code/goal/).
### Data policy and provider filter stops
[Section titled “Data policy and provider filter stops”](#data-policy-and-provider-filter-stops)
A message your organisation’s DLP policy lets through once its sensitive data is confirmed is sent, and `waibee run` goes on, as the terminal does. A blocked request ends with “not sent: your organisation’s data policy blocks what this request holds”. See [Data protection](/code/features/#data-protection).
If the provider’s content filter stops a reply before anything was shown, Waibee Code retries once. Otherwise, the text shown so far stays, tool calls in that reply do not run, and the turn ends with “The provider’s filter stopped this reply. /again to retry, /model to switch models.” A goal does not continue after it, and `waibee run` exits with code `1`.
### Signals and shutdown
[Section titled “Signals and shutdown”](#signals-and-shutdown)
`SIGINT` and `SIGTERM` interrupt reading stdin, preparing the run, the agent’s work, and shutdown. The stream ends with one `result` and one `done` with `stop_reason: cancelled` and `is_error: true`; the single-record format prints one `result`. Startup errors go through the same output, but with `stop_reason: error` and their own exit code. Before preparation finishes, there may be no `meta` event.
Shutdown has a time limit, so a hung MCP server or hook cannot hold the process. `SIGKILL` gives the program no chance to print the final records.
## One pass or a checked result
[Section titled “One pass or a checked result”](#one-pass-or-a-checked-result)
By default, the agent tries not to stop at its first reply: it picks a completion condition for the task and checks whether the condition is met. The extra calls cost time and tokens, and a check by a model does not replace tests. How the automatic goal works is described in [Goal mode](/code/goal/#in-headless-mode).
```bash
waibee run "move the auth module to the new client" # works until the result passes a check
waibee run --once "explain what this file does" # one pass, no check
```
Use `--once` for questions and one-off lookups: there is nothing to check.
## Flags and argument order
[Section titled “Flags and argument order”](#flags-and-argument-order)
Global flags can go before or after `run`. Flags that belong to `run` go after the subcommand:
```bash
waibee -m haiku run --once "summarize the README in three points"
waibee -C ~/projects/api run --output-format stream-json "which endpoints are declared?"
```
`waibee run -m haiku --once "summarize the README"` works too.
| Flag | Where | Purpose |
| --------------------------------------------------------------------------- | --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `-m`, `--model` | before or after `run` | Model: an alias (`haiku`) or a full ID |
| `-c`, `-C`, `--cwd` | before or after `run` | The project’s working folder |
| `--mode`, `--permission-mode` | before or after `run` | Permission mode: `default`, `acceptEdits`, `trust`, `bypassPermissions` |
| `--dangerously-skip-permissions`, `--yolo` | before or after `run` | `bypassPermissions` mode. Not accepted together with `--mode` |
| `--sandbox` | before or after `run` | The [sandbox](/code/permissions/#sandbox) profile for this run: `off`, `workspace-write`, or `restricted`; [the managed profile takes precedence](/code/configuration/#settings-settingsjson) |
| `--no-audit` | before or after `run` | Don’t write the audit log for this run |
| `--bare` | before or after `run` | Run without extensions and instructions, see [Unattended runs](#unattended-runs) |
| `--output-format` | after `run` | Text (`text`), a single record (`json`), or a stream (`stream-json`), see [Output formats](#output-formats) |
| `--json-schema ` | after `run` | [Validate the final JSON](#output-that-follows-a-json-schema) |
| `-o`, `--output-last-message ` | after `run` | [Write the last reply](#last-reply-to-a-file) |
| `--no-session-persistence`, `--ephemeral` | after `run` | Don’t save the session, see [Unattended runs](#unattended-runs) |
| `--effort` | after `run` | Reasoning level for this run, from `none` to `max`; the `/effort` choice in settings stays as it is |
| `--resume ` | after `run` | Continue the session with this ID, see [Continuing a session](#continuing-a-session) |
| `--continue` | after `run` | Continue the last session in this folder |
| `--append-system-prompt ` | after `run` | Append instructions to the end of the system prompt |
| `--tools ` | after `run` | Choose the [set of built-in tools](#tool-set) |
| `--allowed-tools ` | after `run` | An `allow` rule for this run, for example `'Bash(npm test:*)'`. The flag can be repeated, and tools can be listed with commas: `'Read,Grep'` |
| `--disallowed-tools ` | after `run` | A `deny` rule for this run; a name without a pattern [removes the tool](/code/permissions/#denying-a-tool). The flag can be repeated, and tools can be listed with commas: `'Bash,Write'` |
| `--max-turns`, `--max-input-tokens`, `--max-output-tokens`, `--max-seconds` | after `run` | Run limits, see [Run limits](#run-limits) |
| `--once` | after `run` | Turn off the automatic goal; a goal set explicitly or restored with the session still applies |
| `--goal` | after `run` | Completion condition, see [Goal mode](/code/goal/) |
| `--goal-max-iterations` | after `run` | The cap on turns with a goal check, including the first; also applies to an automatically picked goal |
| `--goal-model` | after `run` | The checker model; also applies to an automatically picked goal |
## Continuing a session
[Section titled “Continuing a session”](#continuing-a-session)
```bash
waibee run --continue "now add tests for empty input"
waibee run --resume 3f2a "what is left to do?"
```
`--continue` continues the last session in this folder or, if there is none, starts a new one. `--resume` finds a session by the beginning of its ID, taken from `waibee sessions` or from the `session_id` field of the output. An empty ID or a prefix shared by two sessions is rejected, and a session that is not found ends the run with code `2`: no new session is started in its place. A session open in another process, such as in a terminal tab, also gives code `2`. A continued run works in the folder where the session ran; if that folder no longer exists, the run uses the folder it was started from and says so on stderr.
How the model is chosen on resume is described in [Choosing a model](/code/models/).
## Run limits
[Section titled “Run limits”](#run-limits)
By default, neither tokens nor time stop a run; only the turn cap [`max_turns`](/code/settings/#per-message-limits) does. If you need a limit, set it with a flag:
```bash
waibee run --max-seconds 900 --max-output-tokens 200000 "move the auth module to the new client"
```
| Flag | What it limits |
| --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| `--max-turns` | Turns of the main agent; any integer from `1`. The value `0` is rejected with code `2`, even though `max_turns: 0` in settings means the default cap |
| `--max-input-tokens` | Billable input tokens: fresh input and cache writes, not cache reads |
| `--max-output-tokens` | Output tokens |
| `--max-seconds` | Time limit from the start of the run; preparation and reading stdin can take up to 10 more seconds |
The flag applies to this run and overrides the setting. The same limits for every message are set in settings, see [Per-message limits](/code/settings/#per-message-limits).
Token limits count the turns of the main agent and its subagents. Helper calls (history compaction, the title, memory, the goal check, page summaries, web search) don’t count toward them, though they use tokens too; their usage shows in the [`usage`](#event-stream-stream-json) line under its own `purpose`.
When a turn or token limit is hit, the final record holds the reply the agent managed to get. `--max-seconds` cancels the model request and external commands at the deadline, without a separate final turn; preparation and reading stdin are allowed up to 10 more seconds. Without the flag, this deadline comes from `max_run_seconds` in settings.
In these cases `result` and `done` have `is_error: true`, and `stop_reason` names the limit: `max_turns`, `input_budget`, `output_budget`, or `time_budget`. A hard deadline always gives code `1`; cleanup time is limited, see [Signals and shutdown](#signals-and-shutdown).
## Permissions in headless mode
[Section titled “Permissions in headless mode”](#permissions-in-headless-mode)
`waibee run` picks the mode by the [headless rule](/code/permissions/#headless), including with `--resume` and `--continue`: with no `--mode` and no `permissions.mode` in settings, the mode is `trust`. The mode is named at the start of the run: as a `permission mode: ` line on stderr in `text` format, and as the `permission_mode` field of `meta` in `stream-json` format.
The run never waits for an answer. An action that needs approval is rejected: the agent gets the denial as the call result and keeps working. `result` and `done` list each such denial in `permission_denials`: the tool (`tool`), `call_id`, the arguments (`args`), and the reason (`reason`); with no denials, the list is `[]`. The reason may suggest a broader mode, no higher than `trust`, in which the call would have gone through; `bypassPermissions` is never suggested. There is no folder trust question either: in an untrusted folder, the folder’s hooks, MCP servers, and plugin don’t start, and stderr says what was skipped. The details, including what is rejected in every mode, are in [Permissions](/code/permissions/#headless).
What this means for automation:
* **Allow what the task needs up front.** `allow` rules in `settings.json`, or `--allowed-tools` for a single run, remove the question for specific commands without opening up everything. After the run, check `permission_denials`: it shows what the agent was missing.
* **Set a step timeout.** It caps the total time of the task and its external commands.
* **Restrict permissions separately from the prompt.** Asking the agent to “only analyze” does not technically prevent writes. For a review, run with `--mode default`: changes that need approval are rejected. Also check for `allow` rules that may permit writes.
* **Run edits in a disposable copy.** A separate clone, a worktree, or a CI container: nothing is lost there if the agent does the wrong thing.
* **Deny dangerous actions explicitly.** `deny` rules and `--disallowed-tools` (for example, `'Bash(git push:*)'`) apply in every mode.
* **Limit turns and time.** `--goal-max-iterations`, `--max-turns`, and `--max-seconds` keep the work from dragging on until the runner times out.
## Unattended runs
[Section titled “Unattended runs”](#unattended-runs)
`--bare` turns off skills, custom commands and agents, plugins, MCP servers, hooks, instruction files (`WAIBEE.md`, `CLAUDE.md`, `AGENTS.md`), and memory from the project and the home folder, including `.claude`. This applies to the main agent and to subagents. The built-in `waibee` skill, which describes the program itself, stays. Settings from the [data directory](/code/waibee-directory/#global), authentication, and managed policy stay; project settings and compatible settings files are not read.
`deny` rules from the repository settings don’t apply in such a run: set the denials you need with `--disallowed-tools` or in the data directory settings. No MCP servers connect at all, including those from global settings, and there is no flag to connect a server for a single run.
`--no-session-persistence` (also `--ephemeral`) writes no history, internal files, or session lock, and generates no title or memory. It cannot be combined with `--resume` or `--continue`. The audit log stays on according to its own settings; `--no-audit` turns it off separately.
### Tool set
[Section titled “Tool set”](#tool-set)
`--tools` chooses the built-in tools once, at start: names separated by spaces or commas (`"Read,Grep,Glob"`), `default` for the usual set, or `""` for no built-in tools. An unknown name gives code `2`. This flag does not change MCP tools. `--allowed-tools` allows calls without approval and does not define the tool set. Removing a tool with `deny` is covered in [Denying a tool](/code/permissions/#denying-a-tool).
### Example: triaging an alert
[Section titled “Example: triaging an alert”](#example-triaging-an-alert)
Pass the alert text on stdin. The agent only needs to read the project and query the monitoring system. Commands run in the [`restricted` sandbox](/code/permissions/#the-restricted-profile), which lets them reach only allowed domains, and an `allow` rule removes the question for `curl`. Save the schema from the [example above](#output-that-follows-a-json-schema) to `alert-schema.json`. Set the `WAIBEE_API_KEY` key through your pipeline secrets.
alert.sh
```bash
export WAIBEE_NO_UPDATE_CHECK=1
export WAIBEE_DATA_DIR="$(mktemp -d)"
cat > "$WAIBEE_DATA_DIR/settings.json" <<'EOF'
{ "sandbox": { "network": { "allowed_domains": ["prometheus.example.com"] } } }
EOF
waibee --bare --sandbox restricted config check --json > config-check.json
if ! jq -e '.sandbox.profile == "restricted" and .sandbox.verdict == "engages"' config-check.json > /dev/null; then
jq .sandbox config-check.json >&2
exit 2
fi
rc=0
waibee run --once --bare --no-session-persistence \
--mode default --sandbox restricted --tools "Read,Grep,Glob,Bash" \
--allowed-tools 'Bash(curl:*)' \
--max-turns 12 --max-seconds 300 \
--output-format stream-json --json-schema alert-schema.json \
-o alert-answer.json \
--append-system-prompt "Triage the alert and find the code related to it. Query metrics with curl against https://prometheus.example.com. In summary, give the cause and what to check; in files, list the paths. Keep confirmed facts separate from assumptions." \
- < alert.txt > events.jsonl || rc=$?
jq -r 'select(.type == "result") | "stop_reason: \(.stop_reason) \(.stop_class // "")"' events.jsonl >&2
jq -c 'select(.type == "result") | .permission_denials[]' events.jsonl >&2
[ "$rc" -eq 0 ] || exit "$rc"
jq 'select(.type == "result") | .structured_output' events.jsonl > alert-report.json
```
`events.jsonl` holds the progress of the work, `alert-answer.json` the last text, and `alert-report.json` the validated object for the next step. The agent’s exit code is saved in `rc` instead of ending the script, so the stop reason and the permission denials make it into the step log; then the script exits with the same code. Code `1` means the run did not succeed, and `2` means an invocation, environment, or authentication error; either can happen after work has started, see [Exit codes](#exit-codes).
Allowed domains can be set only in settings, so the script writes them to a separate [data directory](/code/waibee-directory/#global): `--bare` reads settings from there, not from the repository. The preliminary check confirms the resulting profile with managed policy taken into account. The agent’s own network traffic, including requests to the model, is outside the sandbox. Turning off automatic update checks is covered in [settings](/code/settings/#updates).
In a container or a Kubernetes pod on Linux, the `restricted` profile needs the following from the environment:
* a kernel with Landlock ABI V4 enabled (usually 6.7 or newer) on x86\_64 or aarch64;
* user namespaces allowed, along with the `unshare` and `setns` system calls for the user and network namespaces. Docker’s default seccomp profile blocks them: you need a profile that allows them, or `--security-opt seccomp=unconfined`. In Kubernetes, this is the pod’s or container’s `securityContext.seccompProfile`, and unprivileged user namespaces must be enabled on the node;
* egress from the pod to `api.waibee.com` for the agent itself, and to the domains in `allowed_domains` for commands.
`waibee config check` verifies this in advance: where namespaces are blocked, `sandbox.verdict` is `refuses`, and the reason names what to allow. If a required sandbox mechanism is unavailable, the run exits with code `2` and names the mechanism. List internal services with private IP addresses in `allowed_domains` by address, see [network restrictions](/code/permissions/#the-restricted-profile). Addresses are checked at request time. A pod NetworkPolicy does not replace this check: it restricts the whole pod, while the sandbox restricts the agent’s commands inside it.
## Use cases
[Section titled “Use cases”](#use-cases)
| Task | How to set it up |
| ------------------------------- | ----------------------------------------------------------------------------------------------- |
| Reviewing a PR diff | `git diff origin/main \| waibee run "check this diff for risks"`, result to a file or a comment |
| Investigating a failing test | A prompt with the command that runs it: the agent reproduces the failure and explains the cause |
| Drafting a CHANGELOG | A prompt over `git log` between tags, output to the release file |
| Bulk edits over a list of files | A bash loop with one call per file; try it on two or three files first |
| Overnight task with a check | `--goal "make lint and make test pass"`; the exit code decides whether to keep fixing |
| Triaging an alert or a log | The log text in the prompt; out comes a hypothesis and a place in the code |
| A tool inside another agent | `--once --output-format json`, the reply in the `result` field (example below) |
| Pre-commit check | A git hook with a read-only prompt that returns a nonzero code when there are findings |
Keep the prompts for these use cases in [custom commands](/code/skills/) in `.waibee/commands/` rather than in the shell: that way they are versioned with the project.
## Calling from another program
[Section titled “Calling from another program”](#calling-from-another-program)
The agent is an ordinary process: start it, read stdout, and parse the JSON.
ask.py
```python
import json
import subprocess
TIMEOUT_SECONDS = 600
def ask(prompt: str, cwd: str = ".") -> str:
process = subprocess.run(
["waibee", "run", "--once", "--output-format", "json", prompt],
cwd=cwd,
stdin=subprocess.DEVNULL,
capture_output=True,
text=True,
timeout=TIMEOUT_SECONDS,
)
if process.returncode != 0:
raise RuntimeError(f"waibee run exited with code {process.returncode}: "
f"{process.stderr.strip()[-500:]}")
return json.loads(process.stdout)["result"]
print(ask("In one sentence: what does calc.py do?"))
```
`stdin=subprocess.DEVNULL` keeps the agent from reading the calling program’s stdin as data for the prompt.
This is how the agent is plugged into another agent or a service as a tool. It can do what the caller cannot: work in another repository, with its files, commands, and tests.
For a conversation that keeps context between runs instead of one-off calls, see [ACP in the terminal](/code/acpx/).
## In CI
[Section titled “In CI”](#in-ci)
.github/workflows/review\.yml
```yaml
- name: Install the agent
run: curl -fsSL https://raw.githubusercontent.com/waibee-main/waibee-code/main/install.sh | bash
- name: Review the diff
env:
WAIBEE_API_KEY: ${{ secrets.WAIBEE_API_KEY }}
WAIBEE_NO_UPDATE_CHECK: "1"
run: |
git diff origin/${{ github.base_ref }}...HEAD | \
waibee run --once --bare --mode default --tools "Read,Grep,Glob" \
--max-seconds 600 \
"List the risks in this diff: logic errors, data loss, broken contracts. Only findings that matter, no retelling of the diff." \
> review.md
cat review.md >> $GITHUB_STEP_SUMMARY
```
A diff from someone else’s branch is untrusted input, so the step is locked down: `--mode default` rejects anything that would need approval, `--tools` limits the agent to reading and search, `--bare` skips hooks, MCP servers, and instructions from the repository, and `--max-seconds` ends the work before the step times out.
What to keep in mind in CI:
* **Pass the key only through secrets.** `WAIBEE_API_KEY` goes in the step environment, never in code.
* **Set a step timeout.** Keep `--max-seconds` comfortably below it so the agent can print its final records before the runner kills the step, see [Run limits](#run-limits).
* **A fresh clone is not trusted.** Hooks, MCP servers, and the plugin from the repository don’t start in an untrusted folder, and `waibee run` does not ask about it: stderr gets a line saying what was skipped. If you need them, run `waibee config trust` before the run, see [Folder trust](/code/permissions/#folder-trust).
* **Servers with interactive authentication won’t connect in CI.** The reason goes to the log, not to the step output; `DEBUG=1` shows it on stderr. Keep a separate config for CI without them, see [MCP](/code/mcp/).
* **Don’t mix reading and writing in one step.** Let the review only read; make edits in a separate step that commits the result explicitly.
## Next steps
[Section titled “Next steps”](#next-steps)
* [Goal mode](/code/goal/): the completion condition and exit codes.
* [Permissions](/code/permissions/): `allow` and `deny` rules.
* [Best practices](/code/best-practices/): wording that leaves the agent nothing to guess.
# Hooks
> Hook events, their input and output, configuration in settings.json, and blocking hooks.
A hook is a command that runs on a specific agent event. You declare hooks in `settings.json` under the `hooks` key.
A rule in `WAIBEE.md` is a request: the agent usually follows it but can miss it, especially when the context is full. A hook is run by the application when its event fires, regardless of what the model decides. That makes hooks a good fit for automatic checks, but they are not guaranteed to run if the process crashes. For example, a forced exit with a second `Ctrl+C` can skip `SessionEnd`.
## Events
[Section titled “Events”](#events)
| Event | When it fires |
| ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `SessionStart` | Before the first request of a session, while its history is empty. Does not fire when you resume a session that has history |
| `SessionEnd` | Exiting the terminal, closing each of its tabs, the end of `waibee run`, closing or deleting a session in an IDE, logging out, and disconnecting the editor. `/clear` and closing a session in the browser do not trigger it |
| `UserPromptSubmit` | You sent a prompt, before the model is called. Also fires on the task a subagent receives |
| `PreToolUse` | Before a tool call. The only place where a call can be denied or rewritten |
| `PostToolUse` | After a tool call: successful, failed, or denied |
| `PreCompact`, `PostCompact` | Before context compaction and after the summary is ready |
| `Stop` | The main agent finishes its turn; a blocking hook can ask it to continue |
| `SubagentStart`, `SubagentStop` | A subagent’s first request and the end of its turn |
| `Notification` | The agent is waiting for your approval of a tool call. Does not fire in headless mode, where such a call is denied right away |
An unknown event name is silently ignored, so the only sign of a typo in the key is that the hook never fires.
## Configuration
[Section titled “Configuration”](#configuration)
```json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{ "command": "./scripts/audit.sh" }
]
}
]
}
}
```
* **`matcher`** (optional): a tool name or several names separated by `|` (`Write|Edit`); these match only the whole name. Any other `matcher` is a regular expression searched for in the name: all tools of an MCP server are `mcp____.*`. `"*"` or an empty string means “any”. An invalid expression matches nothing. `matcher` applies only to events with a tool (`PreToolUse`, `PostToolUse`, `Notification`); on all other events the hook always fires.
* **`command`**: a shell command. An entry without one is skipped.
* **`async`** (default `false`): `true` makes the hook fire-and-forget. By default a hook is blocking: the agent waits for it and reads the result.
* **`enabled`** (default `true`): `false` turns the hook off without removing the entry.
You can leave out the nested `hooks` list: the entry `{ "matcher": "Bash", "command": "./scripts/audit.sh" }` means the same as the example above.
Earlier tool names in `matcher` and the `blocking` field from early versions are also understood; see [Names from earlier versions](/code/claude-code/#names-from-earlier-versions).
### Where hooks are declared
[Section titled “Where hooks are declared”](#where-hooks-are-declared)
Hooks are read from the `hooks` key in all of these places at once:
1. `~/.claude/settings.json`;
2. `~/.waibee/settings.json` (on Windows, `%APPDATA%\waibee\settings.json`);
3. the project’s `.claude/settings.json` and `.waibee/settings.json`, only after the folder is trusted; see [Folder trust](/code/permissions/#folder-trust);
4. enabled plugins; see [Plugins](/code/plugins/#structure-and-compatibility);
5. the `hooks` field in a subagent’s definition, only while that subagent runs; see [Subagents](/code/skills/#subagents).
`settings.local.json` files and the organization’s managed file do not define hooks. The same hook (same command, `matcher`, and mode) declared in several settings files runs once.
## How hooks run
[Section titled “How hooks run”](#how-hooks-run)
The command runs through `bash -c` in the session folder. On Windows it runs in Git Bash or the `bash` on `PATH`; without them, in the built-in shell of Waibee Code, and as a last resort in `cmd /C`. The hook gets the event JSON on `stdin` (see [Hook input](#hook-input)) and these environment variables:
| Variable | Value |
| ------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `HOOK_EVENT` | the event name |
| `TOOL_NAME` | the tool name; empty on events without a tool |
| `TOOL_INPUT` | the whole event JSON, as on `stdin`, not only the call’s arguments. A value that is too long is truncated; the full JSON is always on `stdin` |
| `SESSION_ID` | the session ID |
| `CWD`, `PROJECT_DIR`, `CLAUDE_PROJECT_DIR` | the session folder |
| `TRANSCRIPT_PATH` | the conversation file; empty if the session is not written to disk |
| `TIMESTAMP` | the start time in UTC, in RFC 3339 format |
| `CLAUDE_PLUGIN_ROOT` | the plugin directory, for plugin hooks only |
Environment variables whose names contain `KEY`, `TOKEN`, `SECRET`, `PASSWORD`, `CREDENTIAL`, `AUTH`, `SESSION`, `COOKIE`, or `PRIVATE` do not reach the hook, except service variables such as `SSH_AUTH_SOCK` and `GIT_AUTHOR_EMAIL`. If a hook needs such a variable, declare it in the `env` key of the settings; see [Settings reference](/code/settings/#extensions-and-environment).
The agent waits 60 seconds for a blocking hook; the `timeout` field is not read. An async hook has no time limit. Blocking hooks of one event run one after another, in the order they are declared.
The `/hooks` command shows the configured hooks and adds a new one through a form: the event, the tools, the command, whether to wait for the hook, and where to save it (“this project” writes to `.waibee/settings.json`, “every project” to `~/.waibee/settings.json`). The form offers `PreToolUse`, `PostToolUse`, `UserPromptSubmit`, `Stop`, and `SubagentStop`; hooks on other events go into the file by hand. Keys: `n` adds a hook, `Enter` goes a level deeper, Space turns a hook off without removing the entry, `d` removes the entry, and `Esc` or `Backspace` goes a level back. In the form, `Tab` moves between fields, `Enter` saves, and `Esc` cancels. Hooks from `.claude/` and from plugins are shown here but cannot be changed. The same is available on the extensions page in the [browser](/code/web/).
A blocking hook answers with its exit code:
| Code | Meaning |
| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| `0` | Continue as usual if there is no decision. If `stdout` holds JSON, it is parsed (see below); a `deny` decision in it works like code `2` |
| `2` | A blocking decision; the effect depends on the event. The reason is taken from `stderr` |
| `126`, `127` | The hook was not found or is not executable: this is a broken configuration, not a decision |
| anything else | Continue without a decision from the hook; a warning goes to the log |
An async hook (`"async": true`) is started and forgotten: neither its exit code nor its output is read. That is enough for notifications and logging, and it delays nothing.
### A broken hook
[Section titled “A broken hook”](#a-broken-hook)
A hook that has a typo in its path, is not executable, fails to start, or hangs until the timeout does not count as a decision:
* on `PreToolUse`, it counts as a denial. This is a security boundary, and a broken check must not quietly let calls through;
* on every other event, the agent shows a warning and keeps working. A wrong path in a `UserPromptSubmit` hook will not block all your prompts.
### Several calls in one response
[Section titled “Several calls in one response”](#several-calls-in-one-response)
The model can call several tools in one response. Then the `PreToolUse` hooks run one after another for all the calls, and only after that do the approved tools run. Calls that only read run at the same time; calls that change something (an edit, a write, a command that does more than read, an MCP tool above `read_only`) run one at a time, in the order the model wrote them.
So a hook can deny a call but cannot hold it until a neighboring call finishes. At that point the neighboring call has not started yet: a hook that waits for it only waits out the timeout, and the call is denied. If the `read_only` tools of one MCP server must not run at the same time, the queue belongs in the server itself. The other option: the hook denies the second call with a reason such as “call these one at a time”, and the model repeats the call on its next turn.
## Hook input
[Section titled “Hook input”](#hook-input)
`stdin` receives JSON on a single line. Fields common to all events:
| Field | Value |
| ----------------- | ----------------------------------------------------------------- |
| `hook_event_name` | the event name, for example `PreToolUse` |
| `session_id` | the session ID |
| `cwd` | the session folder |
| `transcript_path` | the conversation file, if the session is written to disk |
| `tool_name` | the tool name, on `PreToolUse`, `PostToolUse`, and `Notification` |
Fields of individual events:
| Event | Fields |
| ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `SessionStart`, `SubagentStart` | `model`: the model of the session or subagent |
| `UserPromptSubmit` | `prompt`: the prompt text |
| `PreToolUse` | `tool_input`: the call’s arguments |
| `PostToolUse` | `tool_input`; `tool_response`: the tool result as text; `is_error`; `elapsed_ms`: how long the call took. A denied call has `denied: true` instead of `elapsed_ms`, and `tool_response` holds the denial text |
| `Stop`, `SubagentStop` | `agent_id`; `stop_hook_active`: a hook has already asked to continue in this turn; `aborted`. With `aborted: false`, also `last_assistant_message`, the model’s last text. With `aborted: true`, the turn was cut short by an error or a limit, and `reason` names the cause |
| `PreCompact` | `agent_id`; `trigger`: `manual` for `/compact`, `auto` for automatic compaction; `custom_instructions`: the text after `/compact`; `input_tokens`, `context_limit`, `history_len` |
| `PostCompact` | `agent_id`, `trigger`, `history_len` |
| `Notification` | `kind`: `permission_required`; `command`: the command or `null`; `reason`: why approval is needed |
| `SessionEnd` | `reason`: `prompt_input_exit` (exiting the terminal, the end of `waibee run`), `close`, `delete`, `logout`, `disconnect` (IDE) |
Paths in `tool_input` are absolute, even if the model wrote a path relative to the project folder. This applies to `file_path` in `Read`, `Write`, and `Edit`, `notebook_path` in `NotebookEdit`, and `path` in `Glob` and `Grep`. A `Bash` command reaches the hook as is. In `PostToolUse`, `tool_input` already includes the `updatedInput` changes from `PreToolUse` hooks.
A hook whose `matcher` matched only an earlier tool name gets the earlier name and the earlier parameter names; see [Names from earlier versions](/code/claude-code/#names-from-earlier-versions).
An example for `PreToolUse`:
```json
{
"tool_input": {
"file_path": "/home/me/proj/src/main.rs",
"old_string": "foo",
"new_string": "bar"
},
"hook_event_name": "PreToolUse",
"session_id": "0b6f3c1e-8a55-4c1e-9f7e-2d2f1c9a7b10",
"cwd": "/home/me/proj",
"transcript_path": "/home/me/.waibee/sessions/0b6f3c1e-8a55-4c1e-9f7e-2d2f1c9a7b10.jsonl",
"tool_name": "Edit"
}
```
A script reads the field it needs with `jq`: `jq -r '.tool_input.file_path'`.
## What a hook can block or change
[Section titled “What a hook can block or change”](#what-a-hook-can-block-or-change)
Code `2` or a `deny` decision blocks sending the prompt on `UserPromptSubmit` and the tool call on `PreToolUse`. On `PostToolUse`, it appends the reason to the result and ends the turn after the current calls, but it does not undo a tool that already ran. On `PreCompact`, code `2` or the JSON `{"decision":"block","reason":"reason"}` leaves the history uncompacted and shows the reason. On `Stop` and `SubagentStop`, it asks the agent to continue. On `SessionStart`, `SubagentStart`, `PostCompact`, `Notification`, and `SessionEnd`, blocking changes nothing, and for a denied call the `PostToolUse` hook’s answer is ignored.
Other decisions are set by JSON on the `stdout` of a blocking hook:
| Field | Event | Effect |
| --------------------------------------------------------- | ------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `hookSpecificOutput.permissionDecision` | `PreToolUse` | `allow` removes the question the mode would have asked, but does not approve a command the check cannot parse; `ask` asks you (in headless mode, and for a subagent that is not allowed to ask, such a call is denied); `deny` forbids the call. `defer` and no decision leave the usual permission check. `deny` rules, protected paths, and a subagent’s `plan` mode apply whatever the hook answers. If there are several hooks, the strictest decision wins |
| `reason` or `hookSpecificOutput.permissionDecisionReason` | `PreToolUse` | The reason for the decision, shown to the model |
| `hookSpecificOutput.updatedInput` | `PreToolUse` | Replaces the call’s arguments entirely, also without `permissionDecision`. Every hook gets the original arguments; the last `updatedInput` wins |
| `hookSpecificOutput.updatedToolOutput` | `PostToolUse` | Replaces the tool result before the model and the interface see it |
| `hookSpecificOutput.additionalContext` | `SessionStart`, `SubagentStart`, `UserPromptSubmit`, `PostToolUse`, `Stop`, `SubagentStop` | Adds context for the model: before the request, to the tool result, or to the next request. On its own, it does not make the agent continue |
| `continue: false` plus `stopReason` | `UserPromptSubmit`, `PreToolUse`, `PostToolUse` | Rejects the prompt, denies the call, or ends the turn after the current calls |
`permissionDecision` is also read at the top level of the JSON. The `decision` field is understood the same way as `permissionDecision`, and `decision: "block"` means `deny`. `reason` inside `hookSpecificOutput` is not read: put the reason at the top level or in `permissionDecisionReason`.
No hook decision lets through a call that a `deny` rule or an absolute ban blocks: such a call is denied without a question, whatever the hook answers.
If one step of cleaning up arguments depends on the result of another, combine them in one hook: the next hook does not get the previous hook’s changes.
When a turn ends normally, `Stop` and `SubagentStop` hooks also accept `{"decision":"block","reason":"what is left to do"}`. The reason goes to the model for the next request. The number of such continuations in a row is limited; after the limit, the turn ends. After an error or a forced stop, a hook does not resume work.
The detail that matters most: **plain output on `stdout` does not reach the model**. A hook that prints text in the hope of adding to the context changes nothing: it needs JSON with `additionalContext`. Non-JSON on `stdout` sets no decision: on `PreToolUse`, the usual permission check stays.
## Examples
[Section titled “Examples”](#examples)
### Formatting after every edit
[Section titled “Formatting after every edit”](#formatting-after-every-edit)
The most common case. The agent does not spend a turn running the formatter, and the diff stays clean.
```json
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [{ "command": "make fmt", "async": true }]
}
]
}
}
```
`async` earns its place here: the agent does not need the formatter’s result, and without the flag every edit waits for `make fmt` to finish.
### Protecting paths from edits
[Section titled “Protecting paths from edits”](#protecting-paths-from-edits)
Migrations, lock files, generated code, another team’s module: things the agent should not touch without you. The `deny` list in permissions covers commands; this hook covers files.
```json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Write|Edit",
"hooks": [{ "command": "./scripts/guard-paths.sh" }]
}
]
}
}
```
scripts/guard-paths.sh
```bash
#!/usr/bin/env bash
# Exit 2 blocks the tool call; stderr becomes the reason shown to the agent.
path=$(jq -r '.tool_input.file_path // empty')
case "$path" in
*/migrations/*|*/package-lock.json)
echo "this path is edited by hand only" >&2
exit 2
;;
esac
```
The file must be executable (`chmod +x`) and sit where the config says: on `PreToolUse`, a hook that is not found counts as a denial, and every edit will be blocked.
### Adding context to every prompt
[Section titled “Adding context to every prompt”](#adding-context-to-every-prompt)
A `UserPromptSubmit` hook can add to your input. It helps when you keep repeating the same things: the current branch, the task number, the state of the working copy. The context goes in the `additionalContext` field; the agent does not read the command’s plain output.
```json
{
"hooks": {
"UserPromptSubmit": [
{ "hooks": [{ "command": "./scripts/git-context.sh" }] }
]
}
}
```
scripts/git-context.sh
```bash
#!/usr/bin/env bash
# Plain stdout is ignored; only additionalContext reaches the model.
jq -n --arg ctx "$(git status --short --branch)" \
'{hookSpecificOutput: {hookEventName: "UserPromptSubmit", additionalContext: $ctx}}'
```
### A notification when the agent is done
[Section titled “A notification when the agent is done”](#a-notification-when-the-agent-is-done)
You no longer have to watch the terminal during a long task.
```json
{
"hooks": {
"Stop": [
{ "hooks": [{ "command": "osascript -e 'display notification \"Done\" with title \"Waibee Code\"'", "async": true }] }
]
}
}
```
On Linux, use `notify-send` instead. You can also skip the notification and send a message to a messenger with `curl`.
### A command log
[Section titled “A command log”](#a-command-log)
Every `Bash` run goes into one file. This helps when you work in `trust` mode or want to see what happened in a long session.
```json
{
"hooks": {
"PostToolUse": [
{
"matcher": "Bash",
"hooks": [{ "command": "jq -r '.tool_input.command' >> .waibee/commands.log", "async": true }]
}
]
}
}
```
### Checking for secrets before a write
[Section titled “Checking for secrets before a write”](#checking-for-secrets-before-a-write)
A `PreToolUse` hook stops a write if the content looks like a key or a token. That is cheaper than scrubbing it from the git history.
```json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Write|Edit",
"hooks": [{ "command": "./scripts/no-secrets.sh" }]
}
]
}
}
```
Caution
A hook runs with your permissions and fires on every matching event. If the [sandbox](/code/permissions/) is on, writes from a hook are restricted the same way as from an ordinary agent command. Keep commands fast: the timeout is 60 seconds, and a blocking `PreToolUse` hook adds its time to every tool call. Put heavy checks on a narrow `matcher` rather than on every tool, and mark anything whose result the agent does not need with `"async": true`.
## Claude Code compatibility
[Section titled “Claude Code compatibility”](#claude-code-compatibility)
A hook brought over from Claude Code for one of the events in the [table](#events) works without changes, blocking included, except for the differences below. The event names, the configuration format, the exit codes, and the `hookSpecificOutput` fields are the same. `~/.claude/settings.json` is read too, `CLAUDE_PROJECT_DIR` and `CLAUDE_PLUGIN_ROOT` are exported, and `decision: "block"` is understood.
Differences:
* **Plain output on `stdout` does not become context.** In Claude Code, a `UserPromptSubmit` or `SessionStart` hook can print text; here it needs JSON with `additionalContext`.
* **Only hooks with `command` work.** The `type` field is not read: any entry with `command` runs, and Claude Code hooks of other types (`http`, `prompt`, `agent`, `mcp_tool`) without `command` are skipped.
* **The timeout is always 60 seconds.** The `timeout` field is not read.
* **A broken `PreToolUse` hook denies the call** instead of letting it through with a warning.
* **Hooks from `settings.local.json` are not read**; see [Where hooks are declared](#where-hooks-are-declared).
* **The input JSON has only the fields listed in [Hook input](#hook-input).** For example, it has no `permission_mode` or `tool_use_id`, `SessionStart` has no `source`, and `tool_response` in `PostToolUse` is text.
Claude Code has more events than this table. A hook on any other event, such as `PermissionRequest` or `PostToolUseFailure`, does not fire here.
# How the agent works
> How Waibee Code works: the agent loop, tools, permissions, context, instructions, and memory.
You give Waibee Code a task, and it does the work itself: it reads files, runs commands, edits code, and checks the result until the task is done.
## The agent loop
[Section titled “The agent loop”](#the-agent-loop)
On every turn, the agent goes through the same loop:
1. Reads the task and the current context.
2. Decides what to do next and calls a tool: read a file, search the code, run a command, make an edit.
3. Reads the tool’s result.
4. Repeats until the task is done or it needs you.
You can step in at any moment: stop the turn, correct the direction, or interject mid-turn by typing a message.
The agent guards against going in circles. If the same call or the same result keeps showing up among a tool’s recent calls, the next call is rejected and the agent gets a hint to change its approach. Polling a background command is allowed more repeats. A successful shell command does not count as a repeat unless it reads a file, and a successful file edit resets the count. If this happens a second time within one prompt, the work stops: the agent takes one last turn without tools and replies with what it has so far. A subagent behaves the same way, and the main agent receives its reply marked as unfinished. The threshold is not configurable.
## Tools
[Section titled “Tools”](#tools)
The agent works with your project through tools: reading and writing files, running shell commands, searching the code, the language server (LSP), web requests, subagents, and more. The full list is under [Features](/code/features/#agent-tools).
## Permissions
[Section titled “Permissions”](#permissions)
Actions that change the system (file edits, commands) require approval by default. How often the agent asks depends on the permission mode (`default`, `acceptEdits`, `trust`, `bypassPermissions`) and on the lists of allowed and denied commands. More in [Permissions](/code/permissions/).
## Context
[Section titled “Context”](#context)
The agent keeps the whole conversation, including files it read and command output, in the model’s context window. The window fills up fast, so the agent compacts older history on its own, and you help it save space. How this works and what to do is in [Context window](/code/context-window/).
## Instructions and memory
[Section titled “Instructions and memory”](#instructions-and-memory)
The agent takes your rules from instruction files (`WAIBEE.md`, `CLAUDE.md`, `AGENTS.md`), which it reads at the start of a session. Separately, it keeps a memory: facts about you and the project that survive restarts. For which files are read and in what order, see [Configuration files](/code/configuration/); for where they live, see [The .waibee directory](/code/waibee-directory/).
## Extensions
[Section titled “Extensions”](#extensions)
You can extend the agent with [skills, custom commands, and subagents](/code/skills/), [hooks](/code/hooks/), [MCP servers](/code/mcp/), and [plugins](/code/plugins/).
# IDEs (ACP)
> Connecting Waibee Code to editors over the Agent Client Protocol.
Waibee Code speaks the [Agent Client Protocol](https://agentclientprotocol.com/) and runs in any ACP client with the `waibee acp` command. The editor runs this command itself; you don’t need to run it by hand. To make the agent appear in the editor, add it to the editor’s ACP agent config. The first step differs between Zed and JetBrains, but the entry is the same (an `agent_servers` block). It’s best to set up your [API key](/code/quickstart/) beforehand.
## Zed
[Section titled “Zed”](#zed)
1. Run `agent: open settings` → **Add Agent** → **Add Custom Agent** (this opens `~/.config/zed/settings.json`).
2. Add the entry:
\~/.config/zed/settings.json
```json
{
"agent_servers": {
"Waibee Code": {
"type": "custom",
"command": "waibee",
"args": ["acp"]
}
}
}
```
3. Open the agent panel and choose **Waibee Code**.
4. **API key.** Not set yet? Use the agent’s **Reauthenticate** option (the ⋮ menu): Zed opens a terminal where `waibee auth login` asks for the key. Or put the key in the entry as `"env": { "WAIBEE_API_KEY": "sk_live_..." }`.
## JetBrains (AI Assistant 2026.1+)
[Section titled “JetBrains (AI Assistant 2026.1+)”](#jetbrains-ai-assistant-20261)
1. Open the **AI Chat** window.
2. Open the **⋮** menu (top right) → **Add Custom Agent** (this opens `~/.jetbrains/acp.json`).
3. Add the same entry as for Zed. If the IDE can’t find `waibee`, set `command` to the full path: `~/.local/bin/waibee` (macOS/Linux) or `%LOCALAPPDATA%\Programs\waibee\waibee.exe` (Windows).
4. Save. **Waibee Code** appears in AI Chat (if it doesn’t, restart the IDE).
5. **API key.** JetBrains has no sign-in from the chat, so set the key beforehand: run `waibee auth login`, or add `"env": { "WAIBEE_API_KEY": "sk_live_..." }` to the entry.
## What goes through the editor
[Section titled “What goes through the editor”](#what-goes-through-the-editor)
* **Mode, model, and reasoning effort.** The agent exposes these session settings to the editor (effort only for models that support it), and the editor decides which of them to show. The modes are the same as for the `--mode` flag, see [Switching modes](/code/permissions/#switching-modes). The `--model` flag in `args` (`["acp", "--model", "opus"]`) sets the model for new sessions; a reopened session continues on its own model, and the editor’s model picker changes it.
* **Commands.** Of the built-in commands, `/compact`, `/reload`, and `/help` work in the editor, along with your own commands and skills. The other built-in commands are available only in the terminal.
* **Files and commands.** If the editor supports it, the agent reads and writes files through the editor. When a [sandbox](/code/permissions/#sandbox) is in effect, `Bash` commands run locally under its restrictions; otherwise they may run in the editor’s terminal. Permission checks apply as usual.
* **The editor’s MCP servers.** Servers the editor passes to the agent (Zed passes its own) connect for as long as the ACP server runs and are available to its sessions alongside the servers from [settings](/code/mcp/). Their tools run at the `execute` level, see [Permissions](/code/mcp/#permissions-and-security).
## Subagents in the IDE
[Section titled “Subagents in the IDE”](#subagents-in-the-ide)
JetBrains AIR shows each subagent as a separate session: its turn, tool calls, and permission requests appear there, and the main agent keeps an `Agent` call card. Zed and other ACP clients show only that card, with the result. In those clients, a permission request from a subagent arrives in the main session, labeled with the subagent’s name. You can’t write to a subagent from the IDE: do that in its window in the terminal or in its panel in the browser.
## Other clients
[Section titled “Other clients”](#other-clients)
Any [ACP client](https://agentclientprotocol.com/get-started/clients) connects the same way: the command `waibee` with the argument `acp`. That covers Neovim, Obsidian, and others. VS Code has no built-in ACP support, but an [ACP extension](https://github.com/formulahendry/vscode-acp) adds it.
The same protocol works without an editor: the [acpx](/code/acpx/) client gives the agent JSON output and sessions that persist between calls, which is handy for scripts and CI.
# Installation
> Install, update, and uninstall Waibee Code on macOS, Linux, and Windows.
The installer downloads the executable for your platform from the latest release, verifies its checksum, and saves it to `~/.local/bin` (macOS and Linux) or `%LOCALAPPDATA%\Programs\waibee` (Windows).
[Latest version **v0.5.0**](https://github.com/waibee-main/waibee-code/releases)
macOS and Linux
`curl -fsSL https://raw.githubusercontent.com/waibee-main/waibee-code/main/install.sh | bash`
Windows (PowerShell)
`irm https://raw.githubusercontent.com/waibee-main/waibee-code/main/install.ps1 | iex`
If the install folder is not on your `PATH`, the installer adds it. On macOS and Linux it appends a line to `~/.zshrc`, `~/.bashrc`, or `~/.profile`, depending on your shell; on Windows it adds the folder to your user `PATH`. The `waibee` command is available in new terminal windows. In the current one, `source` that file or open the terminal again.
Environment variables change how the installer behaves:
| Variable | What it does |
| ----------------------- | --------------------------------------------------------------------------------------- |
| `WAIBEE_INSTALL_DIR` | A different install folder. Without it, macOS and Linux use `XDG_BIN_HOME` if it is set |
| `WAIBEE_VERSION` | Install a specific version, such as `v1.2.3`, instead of the latest |
| `WAIBEE_NO_MODIFY_PATH` | Leave `PATH` alone: the installer only prints what to add |
## Prebuilt binaries
[Section titled “Prebuilt binaries”](#prebuilt-binaries)
To install by hand, download the archive for your platform from the repository’s [releases page](https://github.com/waibee-main/waibee-code/releases). Builds are available for macOS (ARM and Intel), Linux (x86\_64 and ARM64, plus a separate x86\_64 musl build for Alpine), and Windows (x64 and ARM64). The checksums are there too: a `.sha256` file for each archive and a combined `SHA256SUMS`.
## Verifying the installation
[Section titled “Verifying the installation”](#verifying-the-installation)
`waibee --version`
`waibee doctor`
`waibee doctor` checks your system, settings, API key, and connection to Waibee Router. If any check fails, the command exits with code 1. Right after installation there is no API key yet, so the “API key” check fails: set a key as described in the [Quickstart](/code/quickstart/) and run `waibee doctor` again.
## Updating
[Section titled “Updating”](#updating)
By default, the TUI checks for a new version every time it starts. How the new version gets installed depends on how you installed the agent and where it runs:
* **Installer or release archive, TUI.** The agent downloads the new version, verifies its checksum, replaces the executable, and restarts. Press `Ctrl+C` on the update screen to skip the update and start the current version.
* **Package manager.** The agent does not replace the file itself; it prints that package manager’s update command. If the installed version is below the minimum supported one, the agent exits and prints that command.
* **IDE over ACP.** The new version installs in the background and takes effect on the next start.
* **`waibee run`.** Installs nothing and only notes the new version in the log. In scripts and CI, update explicitly.
Without a network connection, the agent starts on the version it has. To turn off automatic checks, see the [update settings](/code/settings/#updates).
If a new version comes out while a session is open, the status line tells you, and `/update` installs it and restarts the TUI. When you start the TUI on a new version after running an older one, it opens the changelog; to see it at any time, use `/changelog`.
```bash
waibee update # check only
waibee update --install # download and install
waibee update --install --force # reinstall even if this is the latest version
waibee update --channel beta # check another channel: stable, beta, or nightly
```
Without `--channel`, the channel comes from [`updates.channel`](/code/settings/#updates). `waibee update --install` does not restart anything that is already running: open sessions stay on the old version until they restart.
## Uninstalling
[Section titled “Uninstalling”](#uninstalling)
1. Run `waibee auth logout` to delete the saved API key.
2. Delete the executable: `~/.local/bin/waibee` or `%LOCALAPPDATA%\Programs\waibee\waibee.exe`.
3. If you no longer need your sessions, memory, and settings, delete the data directory: `~/.waibee` on macOS and Linux, `%APPDATA%\waibee` on Windows. For what it contains, see [The .waibee directory](/code/waibee-directory/#global).
# Language servers (LSP)
> A language server lets the agent work with symbols precisely: definitions, references, types, and diagnostics after edits.
The `LSP` tool connects the agent to language servers, the same ones your IDE uses: rust-analyzer, gopls, pyright, and others. `Grep` finds matching lines; a language server answers questions about symbols.
## Why it is more precise than search
[Section titled “Why it is more precise than search”](#why-it-is-more-precise-than-search)
| Question | With text search | With a language server |
| -------------------------------- | ------------------------------------------------------------------------ | --------------------------------------------- |
| Where is `save` defined | Dozens of matches: methods of different classes, strings, comments | One place, for this exact symbol |
| Who calls this function | Matches by name, including functions with the same name in other modules | Calls to this exact function |
| What does this expression return | No answer | The type, as the compiler sees it |
| What will a rename break | No answer | The list of places that have to change |
| Is the edit correct | Only after you run the build | Errors arrive right after the file is written |
After every write through `Write` or `Edit`, the agent briefly waits for the server’s response, and new errors come back with the result of the edit. The agent fixes a typo in a name, a type mismatch, or a missing import in the same turn, without running the compiler. While the server is starting and indexing the project, edits are not checked, and the result says so.
Exact symbol locations save the agent from reading a dozen files to find the right place; see [Context window](/code/context-window/).
## What the tool does
[Section titled “What the tool does”](#what-the-tool-does)
* diagnostics for a file;
* go to definition, to type definition, and to implementation;
* find references;
* hover with the type and documentation;
* the list of symbols in a file and a symbol search across the whole project;
* rename preview: the tool shows the edits, and the agent applies them with `Edit`;
* code actions;
* server status and restart.
`LSP` only reads and never changes anything itself, so it does not ask for approval. The language server itself runs outside the [sandbox](/code/permissions/#sandbox), with your permissions. A symbol query waits a limited time for the project to finish indexing, and the agent can extend that time.
## Turning it on
[Section titled “Turning it on”](#turning-it-on)
A server starts on its own when two conditions are met: its program is installed, and the project root has the language’s marker file. The project root is the root of the git repository or, outside a repository, the directory where the agent was started. The program is looked up in `PATH`, and in a [trusted folder](/code/permissions/#folder-trust) first in the project directories `node_modules/.bin`, `.venv/bin`, `venv/bin`, `.venv/Scripts`, `venv/Scripts` (the layout of a Python virtual environment on Windows), `.tools/bin`, and `bin`.
| Language | Server | Marker in the root | Installation |
| ---------------------- | -------------------------- | ---------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
| Rust | rust-analyzer | `Cargo.toml` | `rustup component add rust-analyzer` or `brew install rust-analyzer` |
| Go | gopls | `go.mod`, `go.work` | `go install golang.org/x/tools/gopls@latest` |
| Python | pyright | `pyproject.toml`, `setup.py`, `setup.cfg`, `requirements.txt`, `.venv` | `npm i -g pyright` or `pip install pyright` |
| TypeScript, JavaScript | typescript-language-server | `tsconfig.json`, `jsconfig.json`, `package.json` | `npm i -g typescript-language-server typescript` |
| C, C++ | clangd | `compile_commands.json`, `compile_flags.txt`, `CMakeLists.txt` | `brew install llvm`, `apt install clangd`, or `winget install LLVM.LLVM` |
| Lua | lua-language-server | `.luarc.json`, `*.rockspec` | `brew install lua-language-server` or `winget install LuaLS.lua-language-server` |
Other servers are not supported: there is no setting for your own list of servers. `/lsp` shows the servers whose marker was found and, for each one, whether it is ready, and if not, the install command for this machine.
If no server is ready, the `LSP` tool is not in the agent’s list, and the agent searches with `Grep`. Readiness is checked once per Waibee Code launch, so a server you install while working shows up after a restart.
Servers start on the first `LSP` call or on the first edit of a file in a language that has a server. To start them together with the session, turn on `lsp.prewarm`; see the [Settings reference](/code/settings/#extensions-and-environment).
Note
You don’t need separate plugins with language servers: the `lspServers` field in a plugin manifest is ignored. See [Claude Code compatibility](/code/claude-code/).
## Using it
[Section titled “Using it”](#using-it)
Usually the agent queries the server on its own. Asking directly helps where it would otherwise reach for grep:
* “use `LSP` to find all references to `PaymentProvider` and show where the interface is implemented”.
* “show what breaks if `parseConfig` is renamed to `loadConfig`: preview first, then we decide”.
* “after the edit, run diagnostics on the changed files and fix only the new errors”.
On an unfamiliar project, check `/lsp` at the start of the session: if the server is not installed, the agent searches by text only.
## Where it won’t help
[Section titled “Where it won’t help”](#where-it-wont-help)
* The language is not in the table: `Grep` and `Glob` remain. For a map of the definitions in a file, use the same `Grep` in `content` mode with a pattern like `^\s*(pub |export |async )*(fn|class|def|struct|type)\b`.
* A monorepo where the language marker sits only in a subdirectory (`backend/go.mod`): edits in that language are not checked. If the root has no marker at all, there is no `LSP` tool.
* Untyped dynamic code: the value is built at runtime, so the server has nothing to resolve.
* Templates, configs, migrations: text search fits better there.
* Large projects: the first indexing takes time, and rust-analyzer and pyright use a lot of memory on them.
# MCP
> Connecting external tool servers over the Model Context Protocol.
MCP (Model Context Protocol) connects tools from external servers to the agent. The agent sees the `create_issue` tool of the `github` server as `mcp__github__create_issue` and calls it the same way as its built-in tools: through the same permission checks and hooks, and every call is written to the audit log. The text of a server’s response is marked as external data, the same as the content of a fetched web page.
Transports:
* `stdio`: the agent starts the server as a process and talks to it over stdin and stdout;
* `http`: Streamable HTTP;
* `sse`: the older HTTP+SSE transport, where the server sends an event stream over GET and names the address for POST in it. The scheme, host, and port of that address must match `url`. An `http` entry whose server answers the first request with 400, 404, or 405 switches to this transport on its own.
HTTP redirects are followed only when the scheme, host, and port match; headers and the token are never sent to a different address.
Add a server in `/mcp`, on the extensions page in the browser, with `waibee mcp add`, or by editing a settings file.
## Server entry
[Section titled “Server entry”](#server-entry)
\~/.waibee/settings.json
```json
{
"mcp": {
"servers": {
"github": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": { "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}" },
"permission_level": "read_only",
"disabled_tools": ["create_issue"]
},
"docs": {
"type": "http",
"url": "https://mcp.example.com",
"headers": { "Authorization": "Bearer ${DOCS_TOKEN}" }
}
}
}
}
```
| Field | Value |
| ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `type` | `stdio`, `http`, or `sse`; `streamable-http` means the same as `http`. Without the field, an entry with `url` is read as `http`, and any other entry as `stdio`. An unknown value is read as `stdio` |
| `command`, `args`, `env` | the launch command, its arguments, and environment variables, for `stdio` |
| `url`, `headers` | the address and headers, for `http` and `sse` |
| `auth` | `{"type": "oauth"}` to sign in with OAuth. See [OAuth](#oauth). You can add `scopes`, `client_id`, `callback_port`, `redirect_uri` |
| `timeout_ms` | how long to wait for a response to a tool call, in milliseconds; `0` removes the limit. Without the field, see [Call timeout](#call-timeout) |
| `disabled` | `true` turns the server off: it does not start, and the model does not see its tools |
| `disabled_tools` | names of the server’s tools that the model does not see and cannot call |
| `permission_level` | `read_only`, `edit`, `execute` (default), or `dangerous`. See [Permissions](#permissions-and-security) |
`${VAR}` and `${VAR:-default}` are expanded in `command`, `args`, `env`, `url`, and `headers` on connection, from the environment the agent runs in. A variable with no value and no fallback stays in the string as is.
Do not write a secret into the file; write a reference to a variable. `.mcp.json` lives in the repository, and a key written there goes out to the whole team.
An entry in Claude Code format is read as is, including the `"oauth": {"clientId": "...", "callbackPort": 8765}` block: it means the same as `client_id` and `callback_port` in `auth`.
### Call timeout
[Section titled “Call timeout”](#call-timeout)
The time to wait for a tool call’s response comes from the first of these that is set:
1. `timeout_ms` in the server entry;
2. the `mcp.default_timeout_ms` key next to `servers`: a shared timeout in milliseconds for every server without its own `timeout_ms`;
3. the `WAIBEE_MCP_TOOL_TIMEOUT_SECS` environment variable, in seconds;
4. 300000 ms, which is five minutes.
At any level, `0` removes the limit. A call that does not respond in time ends with an error.
\~/.waibee/settings.json
```json
{
"mcp": {
"default_timeout_ms": 600000,
"servers": { }
}
}
```
## Which files are read
[Section titled “Which files are read”](#which-files-are-read)
Servers are read from the `mcpServers` or `mcp.servers` key in each of these files. If a name appears twice, the entry from the file lower in the list wins:
1. `~/.claude/settings.json`
2. `~/.waibee/settings.json` (on Windows, `%APPDATA%\waibee\settings.json`)
3. the project’s `.mcp.json`
4. the project’s `.claude/settings.json`, then `.waibee/settings.json`
5. the project’s `.claude/settings.local.json`, then `.waibee/settings.local.json`
6. the organization’s managed file. See [Configuration](/code/configuration/#settings-settingsjson)
Claude Code servers from `~/.claude.json` are not read. Move them to `~/.waibee/settings.json` or add them with `waibee mcp add`.
Project files are taken only from the directory the agent was started in. Parent directories are not searched, so a session opened in a subfolder of a repository does not see the `.mcp.json` at its root. `waibee doctor` prints every candidate file marked `read`, `missing`, or `untrusted` in the “Where servers are read from” check. After you change directory ([`/cd`](/code/commands/)), and when you switch to a tab with a different directory, the TUI connects the servers from that directory’s files.
Servers from project files start only in a folder you trust. See [Folder trust](/code/permissions/#folder-trust). Global files do not depend on trust.
Servers of enabled plugins are added under the name `plugin__`. Only the plugin can change their entry: such a server shows up in `/mcp` but cannot be edited there. Do not edit files in an installed plugin’s directory; an update overwrites them. Such a server is turned off together with its plugin. See [Plugins](/code/plugins/).
## Adding a server from the agent
[Section titled “Adding a server from the agent”](#adding-a-server-from-the-agent)
The `/mcp` overlay in the TUI shows the servers, their status, and their tools, and it is also where you add, change, and remove a server.
| Key | Action |
| ---------- | -------------------------------------------------------------------------- |
| `a` | Add a server: a three-step wizard (name and scope, transport, address) |
| `e` | Change the selected server with the same wizard |
| `E` | Open the settings file in an external editor |
| Space | Turn the server on or off |
| `Enter` | Expand the server’s tools. There, Space turns an individual tool on or off |
| `d` | Delete the entry, with confirmation |
| `l` | Sign in with OAuth |
| `o` | Sign out of OAuth |
| `Esc`, `q` | Back, from tools to servers, then close |
The wizard asks for a scope: global (`~/.waibee/settings.json`), the repository (`.mcp.json`), or personal for the project (`.waibee/settings.local.json`). Editing a server and turning a server or tool off are written to the scope’s standard file. If the entry came from another file, edit it there by hand: it may override your changes.
The last step of the wizard sets up OAuth sign-in and `KEY=VALUE` pairs: environment variables for `stdio`, headers for `http` and `sse`.
On the extensions page in the [browser](/code/web/), the form connects to the server first and saves the entry only if the server responds. The exception is a server with OAuth enabled that asks you to sign in: it is saved without the check, and you sign in on the same page.
`/reload` picks up an edit to a file on disk: it connects new servers and reconnects changed ones.
## CLI commands
[Section titled “CLI commands”](#cli-commands)
```bash
waibee mcp add # remote server, http
waibee mcp add -- [args] # local server, stdio
waibee mcp add-json '' # entry in .mcp.json format
waibee mcp list [--json] # servers and the file of each; without --json, also sign-in status
waibee mcp get [--json] # one server
waibee mcp login # OAuth sign-in, --no-browser for an SSH session
waibee mcp logout # forget the token
waibee mcp remove [-s ]
```
Examples:
```bash
# stdio: everything after -- goes to the command, including its own flags
waibee mcp add github -e 'GITHUB_PERSONAL_ACCESS_TOKEN=${GITHUB_TOKEN}' \
-- npx -y @modelcontextprotocol/server-github
# http: address and headers
waibee mcp add docs https://mcp.example.com -H 'Authorization: Bearer ${DOCS_TOKEN}'
# server with OAuth: sign in as a separate step
waibee mcp add tracker https://mcp.example.com/mcp --oauth
waibee mcp login tracker
```
Flags of `add`:
| Flag | What it sets |
| --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `-s`, `--scope` | The file the entry is written to: `user` (default) for `~/.waibee/settings.json`, `project` for `.mcp.json`, `local` for `.waibee/settings.local.json`. |
| `-t`, `--transport` | `stdio`, `http`, or `sse`. Without the flag, an address means `http` and a command means `stdio`. `--type` means the same as `--transport` |
| `-e`, `--env KEY=VALUE` | An environment variable for `stdio` |
| `-H`, `--header 'Name: value'` | A header for `http` and `sse`. The form `Name=value` is also accepted |
| `--url`, `--command`, `--arg` | The address, the command, and its arguments as flags, instead of the form after the name |
| `--oauth` | OAuth sign-in, only for `http` and `sse` |
| `--client-id`, `--client-secret`, `--callback-port` | A client the provider issued in advance. See [Pre-registered client](#pre-registered-client) |
A name starts with a letter or digit and consists of Latin letters, digits, and the characters `.-_`. At the end, `add` prints the path of the file it wrote to.
`--arg`, `--env`, and `--header` can be repeated. A variable is split at the first `=`, and a header at the first `:` or `=`, so the remaining characters stay in the value: `--env 'URL=https://host/?a=b'` writes the whole address. The quotes are needed: without them, the shell expands the variable itself, and the secret ends up in the file.
Only `stdio` has environment variables, and only `http` and `sse` have headers. The command rejects a mismatched flag and writes nothing. An address together with a command is also rejected: a server has one or the other.
`waibee mcp add-json` takes a server entry in the form it has in `.mcp.json`, validates it, and writes it as is, so fields that `add` has no flags for are kept. The same `-s` flag as in `add` chooses the file, `user` by default. The client secret from the entry (`auth.client_secret`, or `oauth.clientSecret` as in Claude Code) does not go into the file; it goes to the secret store:
```bash
waibee mcp add-json docs '{"type":"http","url":"https://mcp.example.com","timeout_ms":600000}'
```
`waibee mcp list` shows, under each server, the file it was read from and its OAuth sign-in: until when it is valid, or that it has expired, with the command to sign in again.
`waibee mcp list --json` and `waibee mcp get` keep `${VAR}` references but replace literal values with `•••`: the values of environment variables (`NAME=VALUE`), headers, and recognized secret flags, and arguments like `GITHUB_TOKEN=…` or `Authorization: …`. In a URL, the password or a lone token before `@` and the parameter values after `?` are hidden; fields with tokens and the OAuth secret are not printed. The URL path and ordinary arguments stay visible, so check the output before you share it. In JSON, a server has `name`, `type`, the address or the command with arguments, `env` or `headers`, the `scope`, and the `file`.
`waibee mcp remove ` and the `d` key in `/mcp` remove the entry from the standard file of the active server’s scope. `-s` chooses the scope to remove from. Entries with the same name in other files stay; if the standard file has no entry, the command names the source file so you can remove it by hand.
## OAuth
[Section titled “OAuth”](#oauth)
`waibee mcp login ` (or `l` in `/mcp`) opens a browser to sign in to an `http` or `sse` server. Sign-in to a server that does not publish OAuth metadata is rejected. The token is saved on disk and refreshes on its own. The `auth` field is not required for this: the saved token is used on every connection, and the `Authorization` header from `headers` is then not sent. If `auth` is set and there is no token yet, the server does not connect and asks you to run `waibee mcp login`. Sign-in has a time limit: if you miss it, run `waibee mcp login` again.
A token is bound to the address it was obtained for. A server with the same name at a different address, for example one added again or declared in the project’s `.mcp.json`, does not get the token and asks for its own sign-in.
### Signing in without a browser
[Section titled “Signing in without a browser”](#signing-in-without-a-browser)
In an SSH session, a browser does not open on that machine. `waibee mcp login --no-browser` prints the sign-in address: open it in a browser on your computer and sign in. At the end, the browser goes to an address like `http://127.0.0.1:/callback?code=...&state=...`, and the page does not load, because the remote machine is the one waiting for the response. Copy the address from the browser’s address bar and paste it into the terminal. Only the callback address of this sign-in is accepted, in full, with the `code` and `state` parameters.
### Pre-registered client
[Section titled “Pre-registered client”](#pre-registered-client)
Usually Waibee Code registers itself on the server as a new client. Some servers admit only clients the provider has approved. If the provider issued you a client ID, pass it when you add the server:
```bash
waibee mcp add docs https://mcp.example.com/mcp \
--client-id --callback-port 8765 --client-secret
waibee mcp login docs
```
* `--client-id`: sign-in goes as this client, and registration is skipped.
* `--callback-port`: a fixed port for the callback address, if the client is registered with one. Without the flag, a free port is chosen.
* `--client-secret`: the client has a secret. The flag takes no value: the secret comes from the `MCP_CLIENT_SECRET` variable, and if it is not set, the command asks for it in the terminal. It works only together with `--client-id`. `add-json` has the same flag; the client ID must then be in the entry itself.
The secret does not go into the settings file: it is kept in the system keychain, or, if that is unavailable, in the [data directory](/code/waibee-directory/#global). The secret is bound to the server name and the client ID, but not to the URL: if the address changes with the same pair, the secret is kept. The secret is deleted together with the server, but while the same server with the same client is recorded in another scope, the secret stays.
### If sign-in fails
[Section titled “If sign-in fails”](#if-sign-in-fails)
* **The server has no sign-in.** `waibee mcp login` replies that no sign-in is needed, and `/reload` connects the server.
* **The server does not register the client.** The response says the server refused to register Waibee Code as a client: some servers admit only approved ones. If the provider issues client IDs, a [pre-registered client](#pre-registered-client) helps.
## Permissions and security
[Section titled “Permissions and security”](#permissions-and-security)
`permission_level` sets the level of all the server’s tools. Whether a call asks for approval depends on the level and the [mode](/code/permissions/#four-modes):
| Level | Asks |
| ------------------- | ---------------------------------------- |
| `read_only` | never |
| `edit` | in `default` |
| `execute` (default) | in `default` and `acceptEdits` |
| `dangerous` | in every mode except `bypassPermissions` |
A rule in `permissions.allow` that matches the tool name (`"^mcp__github__"`) skips the approval for `edit` and `execute`, but not for `dangerous`. A rule in `permissions.deny` forbids the tool in every mode. See [Denying a tool](/code/permissions/#denying-a-tool). In headless mode, a call that would need approval is rejected. See [Headless](/code/permissions/#headless).
Tools from `disabled_tools` and from a disabled server do not appear in the list the model sees. If you turn off a tool or server during a session, it can no longer be called, but the description the model received earlier stays in its requests until a new session.
A `permissions.deny` rule with a plain name, such as `mcp__github__create_issue`, or `mcp__github__*` for the whole server, also removes the tool from the list when the session starts. A rule with a regular expression (`^mcp__github__`) leaves the tool in the list, and the call is refused when the model makes it. See [Denying a tool](/code/permissions/#denying-a-tool).
The [sandbox](/code/permissions/#sandbox) does not apply to MCP servers: a `stdio` server runs with your permissions, with no restrictions on writing.
## Calls and subagents
[Section titled “Calls and subagents”](#calls-and-subagents)
Calls to `read_only` tools from one model response run in parallel, including calls to the same server; the rest run one at a time in the order of the response. There is no setting for the number of concurrent calls. For how long to wait for a response, see [Call timeout](#call-timeout).
A subagent uses the main agent’s connections. The `mcpServers` field in its definition sets servers of its own that start only for it. See [Subagents](/code/skills/#subagents).
## Tools on demand
[Section titled “Tools on demand”](#tools-on-demand)
The tool set the model sees is assembled on the first request of a session and does not change until the session ends. Tools of MCP servers connected by that point go into it directly, as long as their descriptions together take up little space. If there are many descriptions, or a server connected later, for example after `/reload`, the agent gets a list of such tools in the conversation: the name and purpose of each. To call a tool from this list, the model first loads its description with the `ToolSearch` tool, then calls it through `CallTool`.
A call through `CallTool` goes under the tool’s own name: the same permissions, `permission_level`, hooks, and audit log as a direct call, and the interface shows it as a call to that tool.
## Resources and prompts
[Section titled “Resources and prompts”](#resources-and-prompts)
The agent reads resources on its own: `ListMcpResources` shows the servers’ resources, and `ReadMcpResource` reads one by `server` and `uri`. Text arrives as untrusted content with the same size limit as a tool result; images are passed to the model, and other binary data is named by address and type. Both tools work at the `read_only` level, or at the server’s `permission_level` if one is set explicitly.
Each server prompt becomes a `/mcp____` command in the terminal, the browser, the IDE, and `waibee run`. Arguments are separated by spaces, in the order the server declared them. The prompt’s messages go to the agent as your prompt. If a required argument is missing, an extra one is passed, the server responds with an error, or the prompt text is larger than 50 KB, no request goes to the model and the run ends with an error; `waibee run` exits with code `1`.
## Where to find servers
[Section titled “Where to find servers”](#where-to-find-servers)
Registries and catalogs of MCP servers, the difference between official and third-party ones, and what to check before installing are in [Finding extensions](/code/ecosystem/#mcp-servers). Common combinations are collected in [Recommended extensions](/code/toolkit/).
# Choosing a model
> Which model families the agent can use, what to pick for each task, how /effort works, and what it costs.
The agent is not tied to one model: the list comes from the [Waibee Router](/router/models/) catalog and depends on your access. By default the agent runs on `sonnet`. You can change the model at any time. The conversation history stays, and your choice is remembered for later sessions.
When you reopen a session, it continues on its last model if that model is available, in the terminal, the browser, an IDE, and `waibee run`. In the terminal and with `waibee run`, the `--model` flag overrides this choice; with `waibee serve` and `waibee acp`, it sets the model for new sessions only.
```text
/model open the model picker
/model sonnet switch by alias
/effort high reasoning level
```
The aliases `sonnet`, `opus`, and `haiku` point to the latest model in their family, so you don’t have to update them when new versions come out. If a family is not available to you, its alias points to `waibee/auto`. Define your own aliases in `settings.json`; they override the built-in ones:
.waibee/settings.json
```json
{ "aliases": { "fast": "anthropic/claude-haiku-4.5" }, "model": "sonnet" }
```
## Tiers within a family
[Section titled “Tiers within a family”](#tiers-within-a-family)
Almost every family has three tiers. Choosing a tier is more practical than choosing a specific version: versions change often, tiers don’t.
* **flagship:** the highest quality, the most expensive and slowest;
* **mid-size:** the best tradeoff for everyday work;
* **fast:** for mechanical operations and large volumes of similar calls.
`/model` shows the models available to you and marks the ones that don’t accept images. The context window and prices of each model are in the router catalog (see [Models](/router/models/)), and `/status` shows the window size of the current model.
## Choosing for the task
[Section titled “Choosing for the task”](#choosing-for-the-task)
| Task | What to use |
| ------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------- |
| Planning, exploring an unfamiliar codebase, a hard bug | Flagship, with a high `/effort` if needed |
| Everyday development: edits, tests, refactoring from a description | Mid-size tier. This is a sensible default |
| Bulk mechanical changes, renames, working through linter output | A fast, cheap model |
| Images and screenshots | A model that supports images |
| PDFs with diagrams or scans | A model that supports PDFs; the conditions for reading them are in [Features](/code/features/#agent-tools) |
| A long autonomous run with a [goal](/code/goal/) | Mid-size tier: the cost depends on the number of calls, the context length, and cache hits |
A workable pattern: think through the hard part with a flagship, hand the implementation to a mid-size model, and give the review back to a strong one. Switching with `/model` does not reset the context, so changing models partway through a task is fine.
`waibee/auto` is a separate option: the router picks the model for each request (Autorouting). Next to it, the status bar shows which model replied, even when the reply consisted only of tool calls.
A [subagent](/code/skills/#subagents) gets its model from the `model` field in its definition; without that field, it runs on the main agent’s model. This way background routine work can run on a cheap model while the main conversation uses a strong one.
Changing `/model` also applies to empty tabs that have no conversation yet. A subagent without its own model gets the main agent’s current model when it starts, including a choice made while a permission prompt was waiting.
If the selected model still does not respond after retries, or is no longer available, an available helper model may continue the current turn. The notification names both models; the next turn goes back to the selected one.
## Reasoning level (/effort)
[Section titled “Reasoning level (/effort)”](#reasoning-level-effort)
Reasoning models think a task through before they answer. `/effort` controls how much effort goes into that.
| Level | When |
| ---------------- | -------------------------------------------------- |
| `none` | No reasoning needed: simple edits, mechanical work |
| `minimal`, `low` | A little thinking without a noticeable delay |
| `medium` | A sensible tradeoff |
| `high`, `xhigh` | Complex logic, a tangled bug, design |
| `max` | The highest level; not every model has it |
The list shows only the levels the selected model supports, and some models have no selector at all. By default a model starts at `none`, or at its lowest level if it cannot switch reasoning off.
Type `/effort `to see hints for the levels the current model accepts. With an argument, such as `/effort high`, it sets the level directly. With no argument, `/effort` opens a slider from **Faster** to **Smarter**:
* `←` and `→` move the slider.
* `Enter` saves the level for this model.
* `s` keeps the level for this session only.
* `Esc` cancels.
The model sheet in the web interface has the same slider. A choice there is saved for the model.
The status line shows the level next to the model, for example `opus-5.5 (medium)`. If you run `/model` or `/effort` during a turn, the change applies from the agent’s next request.
A higher level costs more and takes longer to reply: reasoning tokens are billed as output. Raise it for a specific hard task, not for the whole session.
## Cost and usage
[Section titled “Cost and usage”](#cost-and-usage)
* **Tokens per session** are shown in `/status`: input, output, the cache hit rate, and the average per turn. For actual charges, see your account dashboard.
* **Prompt caching** reuses the stable prefix with Anthropic models and `waibee/auto`. Choose the cache duration with `context.prompt_cache`: five minutes is cheaper for short sessions, an hour for long ones with pauses. See [Prompt cache](/code/context-window/#prompt-cache).
* **Context gets more expensive as the conversation grows.** Every turn sends the accumulated history, so `/compact` helps in long sessions. See [Context window](/code/context-window/).
* **A large context window does not replace a precise prompt.** A megabyte of files in context costs money and distracts the model from what matters.
## Next steps
[Section titled “Next steps”](#next-steps)
* [Quickstart](/code/quickstart/): your first commands in the TUI.
* [Context window](/code/context-window/): why a conversation gets more expensive and how to manage it.
* [Best practices](/code/best-practices/): how to phrase tasks so a mid-size model is enough.
# Permissions
> Approval modes, allow and deny lists, and behavior in headless mode.
The permission mode decides which actions the agent takes right away and which it asks you to approve. Read and search tools (`Read`, `Grep`, `Glob`, `WebSearch`, `WebFetch`) and read-only commands (`ls`, `cat`, `grep`, `git status`, `kill -0 ` to check whether a process is alive) need no approval. File access restrictions and dangerous commands are checked separately.
In the `default` and `acceptEdits` modes, commands that write need approval unless an `allow` rule permits them. Even redirecting output to a file counts as writing, and so does the file `script` records a session to. Printing a secret token and running a program through `find -exec` also need approval.
## Four modes
[Section titled “Four modes”](#four-modes)
`Bash` runs shell commands, and `REPL` runs code in a persistent Python, Node, or bash session. The protected paths and high-risk commands mentioned in the table are described right below it.
| Mode | File edits | Commands (`Bash`, `REPL`) |
| ------------------- | --------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| `default` | asks | asks, except read-only ones |
| `acceptEdits` | doesn’t ask, except for protected paths | asks, except read-only ones and `mkdir`, `touch`, `mv`, `cp` inside the project and outside protected paths |
| `trust` | doesn’t ask, except for protected paths | doesn’t ask, except for high-risk commands |
| `bypassPermissions` | doesn’t ask | doesn’t ask |
Further restrictions:
* **Destructive commands are always rejected.** `rm -rf /` and the directories right under the root (`/usr`, `/etc`), the home folder however it is written, including its full path, the working folder and its parents (`rm -rf .`, `..`, `*`), `find / -delete`, running downloaded code (`curl ... | sh`, `curl ... | python3`, `eval "$(curl ...)"`, `source <(curl ...)`), a fork bomb, and stopping the Waibee Code process itself by its PID or by the `waibee` name, or the terminal that runs it by its PID (`kill`, `pkill`, `killall`, `taskkill`, `taskkill /T`, `Stop-Process`, also inside `powershell -Command` and `cmd /C`): the agent won’t run these in any mode, and no `allow` list changes that. The agent knows its own PID, and commands get it in the `WAIBEE_PID` variable.
* **Deleting through a variable asks in every mode.** Only the shell knows what `rm -rf "$OUT"` will delete, so it asks even in `bypassPermissions`, and neither an `allow` rule nor a hook can answer for you. Headless mode rejects it. `"${OUT:?}"` fails if the variable is empty and counts as a regular delete.
* **Writing outside the project and to protected paths asks.** Editing or creating a file outside the working folder (temporary folders don’t count), or in a file that later runs code or configures the agent (`.git/`, `.claude/`, `.waibee/`, `.mcp.json`, `.vscode/`, `.husky/`, shell startup files), requires approval in `default`, `acceptEdits`, and `trust`, even if an `allow` rule permits the edit. The path is checked both as written and by where it leads through symbolic links, and names are compared case-insensitively. The same goes for commands that write there: output redirection, `tee`, `cp`, `mv`, `install`, `ln`. In `bypassPermissions` this goes through without asking.
* **Working folder of commands.** `cd` and environment variables in `Bash` and `REPL` persist between calls. In `Bash` and a bash `REPL` session, leaving the project returns the working folder to the session folder, with a message in the result; environment variables persist. In Python and Node, the folder is not returned automatically.
* **High-risk commands ask.** `sudo`, `curl` and `wget` that send a file or a request body (`curl -d @file`), `ssh-keygen`, feeding a file to the shell without downloading (`base64 -d | sh`), writing to shell startup files, a command whose program name comes from an unknown variable: in `default`, `acceptEdits`, and `trust` these ask, even if the mode promises not to. The same applies to `systemd-run`, even with a read-only command: the service manager runs it outside the calling process’s sandbox. `git -c` options that run a program, `awk` calling `system`, `sed` with the `e` command or flag, and alias definitions ask too. An explicit `allow` rule skips the question, and it has to cover every part of the line: with the rule `Bash(curl:*)`, the command `cat ~/.ssh/id_rsa | curl --data-binary @- …` still asks. In `bypassPermissions` they run without asking.
* **Secrets in `bypassPermissions`.** In this mode the agent can read the project’s secret files, such as `.env` and keys: the built-in [path exclusions](/code/configuration/#excluding-paths) for secrets do not apply in it, while the rules in your `.waibeeignore` do. The agent’s own API key, its settings, and the credentials of other agents (Claude Code, Codex, `.mcp.json`) stay closed in every mode.
Deleting a specific path (`rm -rf /tmp/build`) and a regular download with `curl` or `wget` are not high-risk: in `default` and `acceptEdits` they ask, and in `trust` they run without asking.
How MCP tools ask depends on their server’s permission level; see [MCP](/code/mcp/#permissions-and-security).
## Switching modes
[Section titled “Switching modes”](#switching-modes)
In the TUI, `Shift+Tab` cycles through the modes: `default` → `acceptEdits` → `trust` → `bypassPermissions`. The current mode shows in the status bar and as a glyph in the input line.
The interface marks `bypassPermissions` as the riskiest mode. The first time a session enters `bypassPermissions`, a single line explains what it means. Every mode change is written to the audit log along with the surface it was made from.
Your choice of mode takes effect immediately in the current chat, whether in the terminal, the browser, or an IDE, and is remembered in the global settings as `permissions.last_picked`; `bypassPermissions` is not remembered. A new session in the terminal, the browser, or an IDE starts with the first of these that is set:
1. The `--mode` flag of this launch in the terminal.
2. `permissions.mode` from the project settings or the managed file. In an untrusted folder, the project’s mode applies only if it is no broader than `permissions.mode` from the global settings (`default` if that is not set).
3. The remembered choice, `permissions.last_picked`.
4. `permissions.mode` from the global settings.
5. `default`.
A mode set in `/settings` or in the browser settings is written to `permissions.mode` in the global settings and resets the remembered choice. How `waibee run` picks a mode is described in [Headless](#headless). Set the default mode in `settings.json` (or through `/settings`):
```json
{
"permissions": {
"mode": "default"
}
}
```
The valid values are the same in the settings, the `--mode` flag, IDEs, the browser, and the audit log: `"default"`, `"acceptEdits"`, `"trust"`, `"bypassPermissions"`. The Claude Code spelling `"dontAsk"` in a settings file is read as `trust`, and an IDE that sends `dontAsk` is refused. For how this mode differs in Claude Code, see [Claude Code compatibility](/code/claude-code/).
A reopened session keeps the mode it was left in, but no broader than the currently selected mode. An explicit `--mode` overrides it; for `waibee run` the cap works differently; see [Headless](#headless).
A subagent runs in the stricter of two modes: the session’s current mode and the mode from its definition. If you switch the session’s mode while a subagent is working, its next action is checked against the new mode. `permissionMode: plan` in an agent definition makes the agent read-only: it may only read and run commands that change nothing. `permissionMode: dontAsk` means the same as in Claude Code: such a subagent asks nothing, and anything that would need approval is rejected with a reason.
## Allow and deny lists
[Section titled “Allow and deny lists”](#allow-and-deny-lists)
Fine-grained rules are regular expressions:
```json
{
"permissions": {
"mode": "default",
"allow": ["^git ", "^cargo "],
"deny": ["rm -rf", "sudo"]
}
}
```
* **`deny`** blocks matching commands during the permission check. No mode, including `bypassPermissions`, turns these rules off. The check covers every command the line runs: each part of a compound command, inside `$(...)`, subshells, loops, and `if`, after `sudo`, `timeout`, and variable assignments, and inside `sh -c`. So neither `git status && sudo rm x` nor `echo $(sudo rm x)` slips through.
* **`allow`** automatically approves matching edits and commands where there would otherwise be a question, including high-risk commands. Approval does not apply if the command contains substitutions (`$(...)`) or other suspicious constructs, or if the shell cannot parse the line. In a compound command, every part that changes something must match; read-only parts such as `| tail -5` pass without a rule of their own. For a high-risk command, every part must match.
An `allow` rule for `curl` or `wget` does not cover the file the command sends: for `allow` to approve it, reading that file has to be allowed separately, and the checks on protected files apply independently.
If the program name comes from a variable set on the same line (`S="git show"; $S HEAD`), the check runs on the command itself, `git show`.
A `PreToolUse` hook’s response does not bypass the rules. An action in `deny` is forbidden whatever the hook answers. `allow` only removes the question the mode would ask: writing to a protected path still asks, and a subagent in `plan` mode changes nothing. See [Hooks](/code/hooks/).
### Rules in Claude Code format
[Section titled “Rules in Claude Code format”](#rules-in-claude-code-format)
`Bash(...)` rules are read the same way Claude Code reads them, so rules from `.claude/settings.json` work without changes:
| Rule | Matches | Does not match |
| ------------------------------------ | ------------------------------------ | --------------------------- |
| `Bash(npm run build)` | only `npm run build` | `npm run build --watch` |
| `Bash(npm run:*)`, `Bash(npm run *)` | `npm run build` and `npm run` itself | `npm install` |
| `Bash(ls*)` | `ls -la`, `lsof` | |
| `Bash(git * main)` | `git push origin main` | `git log` |
| `Bash(* --version)` | `node --version` | `node -v` |
| `Bash(*)` | any command | other tools, such as `Read` |
`*` means any text and can appear anywhere in a rule. A space and `*` at the end of a rule also match the command with no arguments, if the rule has no other `*`. `\*` in a rule is a literal asterisk. A `Bash(...)` rule is matched only against the command text, never against the tool name.
An `allow` rule does not yet strip a leading `timeout`: `timeout 30 npm test` under the rule `Bash(npm test *)` asks for approval. Claude Code rules on parameters of the `Bash` tool, such as `Bash(timeout:*)` or `Bash(run_in_background:true)`, have no effect: the check sees only the command.
Claude Code rules for other tools, such as `Read(./.env)` or `WebFetch(domain:example.com)`, block nothing: paths and domains are not part of the check. Files are closed off by [`.waibeeignore`](/code/configuration/#excluding-paths), and domains by the [domain filter](#domain-restrictions).
### Denying a tool
[Section titled “Denying a tool”](#denying-a-tool)
A tool name with no pattern in `permissions.deny` removes the tool from the set the model sees when the session starts. `mcp__github__*` likewise removes every tool of the `github` server. For example:
```json
{
"permissions": {
"deny": ["WebFetch", "mcp__github__*"]
}
}
```
`--disallowed-tools WebFetch` sets the same denial for one run. The exclusions are chosen at startup and passed on to subagents.
Rules with parameters (`Bash(git push *)`) and regular expressions (`^WebFetch$`, `^mcp__github__`) are checked at call time and do not remove the tool from the model’s list. A regular expression is matched against both the command and the tool name: without anchors, `Write|Edit` also matches `NotebookEdit`. An MCP tool name has the form `mcp____`, so `^mcp__github__` blocks calls to every tool of the `github` server.
Tool names that come from Claude Code or earlier versions of Waibee Code also match calls in permission rules; see [Names from earlier versions](/code/claude-code/#names-from-earlier-versions).
You can also list an MCP tool in `disabled_tools` in the server’s entry, or turn the server off; see [MCP](/code/mcp/). Calls to such a tool are forbidden immediately, but the tool set is fixed at the session’s first request: a description the model has already received stays with it until a new session. Choosing the built-in tools for one headless run is covered in [Tool set](/code/headless/#tool-set).
## Approvals
[Section titled “Approvals”](#approvals)
In the terminal, the question appears right in the conversation, between the conversation and the input field, and the call it is about stays visible above it. A question has four answers, the same in the terminal, the browser, and an IDE over ACP:
1. **Allow once.**
2. **Allow for the rest of this session.** Covers this command and its subcommand, such as `git commit` or `cargo test`, and for edits, the tool itself.
3. **Allow in this project from now on.** The same as for the session, but remembered for the current project in `.waibee/settings.local.json`.
4. **Deny.**
Neither the second nor the third answer opens up a risky command such as `git push --force`, and writing to a protected path still asks. Risky commands get only one-time approval or denial.
`Tab` on any answer opens a line for an explanation: the agent gets the denial together with your note on what to do instead. A denial applies only to the current call. For a permanent ban, add a `deny` rule to your settings; see [Allow and deny lists](#allow-and-deny-lists).
A prompt or question never takes a key you typed for a message. While the input field has text, the prompt waits behind it, and `↑` or `↓` opens it. Right after it appears, a prompt ignores `Enter`, digits, and the space bar, and a letter it does not use goes to the input field. The answer keys are listed in [Keys](/code/features/#keys).
If a session was waiting for an approval or an answer when it closed, it asks again after you reopen it and continues the turn with your answer. A command that had already started does not run again.
## Domain restrictions
[Section titled “Domain restrictions”](#domain-restrictions)
You can block requests to specific domains or allow only selected ones. Filtering is off by default. Turn on “filter domains” in the “security” section of `/settings` (`/security` goes straight there) and fill in “allowed domains” or “blocked domains”. The same lists are available in the web interface.
From the terminal, for example, you can block a domain:
```bash
waibee config netsec block example.com # add to the blocked list
waibee config netsec allow api.example.com # add to the allowed list
waibee config netsec enable # turn the filter on; disable turns it off
waibee config netsec status # whether the filter is on, and both lists
```
Give the domain name without `https://`, a port, or a path. The rules work like this:
* A blocked domain is closed together with its subdomains. A block takes priority over an allow.
* A non-empty allow list permits only the listed addresses. `example.com` means one domain; `*.example.com` also covers its subdomains.
* An empty allow list leaves access to every address that is not blocked.
The restrictions are checked when `WebFetch` loads pages, including redirects, and when the agent connects to the address of an HTTP MCP server. In shell commands, the addresses that can be recognized in the command text are checked. This is not a firewall for the programs that run. Model requests and web search itself are not subject to these lists.
`waibee config netsec remove example.com` removes a domain from both lists. The settings are saved globally; a project can add its own rules on top. See [the order in which settings apply](/code/configuration/#settings-settingsjson).
## Folder trust
[Section titled “Folder trust”](#folder-trust)
A repository can carry hooks, MCP servers, and a plugin, and all of them run commands on your machine. Reading a repository is not the same as agreeing to run it, so in an unfamiliar folder these files wait for your answer first.
What waits for trust:
* `.claude/settings.json` and `.waibee/settings.json` in this folder: their hooks and MCP servers;
* `.mcp.json` in this folder;
* a plugin that lives in the repository (`*.claude-plugin/`, `.claude-plugin/`): its hooks and servers;
* `hooks` and `mcpServers` in a subagent file from this folder;
* a language server the repository brings with it in `node_modules/.bin`, `.venv/bin`, or `bin`: in an untrusted folder, servers come only from `$PATH`;
* anything in the folder’s settings that widens permissions or changes where requests go: `permissions.allow`, `permissions.granted`, `env`, `netsec.allowed_domains`, `sandbox.network.allowed_domains`, `sandbox.network.allow_unix_sockets`, `network.proxy`, `api_key`, and `files.skip_integrity_check`.
`sandbox.allow_write` is a separate case that has nothing to do with trust: this list is read only from your global settings. It never works in a repository’s settings, because the agent edits the project file itself, and a repository could grant itself write access anywhere.
While the folder is untrusted, its settings can only narrow things. `deny` is always read, a stricter `permissions.mode` always applies, and settings that have no effect on execution work as usual.
What always works: your own `~/.claude` and `~/.waibee`, plugins you installed, and the skills, commands, agent prompts, and `tools` lists from the repository. These are text, and the agent reads them.
The first interactive launch in such a folder asks once and lists what is held back. Answering `y` writes the path to `trusted_folders` in the global settings file, and from then on the folder and everything in it is trusted. Any other answer leaves everything off, and the question comes back next time.
From a script or in CI, the same is done with a command:
```bash
waibee config trust # the current folder
waibee config trust /path # a specific folder
waibee config trust --list # what is already trusted
waibee config trust --remove # revoke trust
```
A launch that cannot show the question or read the answer does not ask: stdin is not a terminal (ACP, a script, a pipe), or stderr is redirected. What was skipped is written to stderr. `waibee doctor` shows such files as `untrusted` and says what to do.
You can’t add a hook or an MCP server in an untrusted folder: the write is rejected on the spot, and the message names the command to run. That is better than silently writing a file that won’t run anyway.
A working copy that a subagent opens with `isolation: worktree` is a separate folder: trust in the repository does not carry over to it, and the trusted repository’s hooks don’t run inside it.
## Protected files
[Section titled “Protected files”](#protected-files)
Built-in rules exclude secrets from reading and search: for example, `.env`, private keys, and the `.ssh` directory. A `.waibeeignore` file lets you add your own exclusions. The rules and their limits are covered in [Excluding paths](/code/configuration/#excluding-paths).
## Sandbox
[Section titled “Sandbox”](#sandbox)
Permissions decide whether a command runs. The sandbox limits what a command can do once it is running. The limits apply to commands and their child processes.
| Profile | Writes | Command network |
| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- |
| `off` (default) | No sandbox limits | No sandbox limits |
| `workspace-write` | The project, worktrees in the Waibee data directory, temporary folders, package manager caches, and `allow_write`, except the protected configuration below | No sandbox limits |
| `restricted` | Same as `workspace-write` | Through a proxy to allowed addresses, see [below](#the-restricted-profile) |
`read-only` is not implemented yet: the agent won’t start with it.
```text
/sandbox choose a profile
/sandbox workspace-write turn it on right away
```
The choice is saved to the global `settings.json` and applies to commands started from then on. `/sandbox` does not turn on or save a profile the machine cannot enforce; it names the reason instead. You can set the same by hand:
\~/.waibee/settings.json
```json
{
"sandbox": {
"profile": "workspace-write",
"allow_write": ["~/sdk-cache", "/opt/shared-cache"],
"require": false
}
}
```
`allow_write` adds directories where writing is allowed: if a build runs into an unfamiliar cache, the denial names the path. A leading `~` means your home folder, and a relative path is resolved from the project folder: `"../shared"` opens the `shared` folder next to the project the agent works in. Folders that code later runs from, such as `~/.cargo`, `~/.gradle`, or `~/.local/bin`, are never opened as a whole: for build caches, their subfolders are open, and that is already done by default.
`workspace-write` uses Seatbelt on macOS and Landlock on Linux (kernel 5.13 or later with Landlock enabled). If the mechanism is unavailable, the agent warns and continues without restricting commands; `require: true` stops such a launch instead. Windows has no such mechanism; WSL2 has the same requirements as Linux.
With the sandbox on, `Write`, `Edit`, and `NotebookEdit` cannot change the configuration of Waibee Code, Claude Code, and git: settings, hooks, skills, agents, commands, `.mcp.json`, `.git/config`, and `.git/hooks`, even inside an allowed directory. On macOS, with Seatbelt in effect, commands can’t change them either. On Linux, commands can still change these files inside an allowed directory: Landlock cannot forbid writes to part of a directory that is open for writing. Make such changes by hand.
To pin the profile for one launch, use the `--sandbox ` flag or the `WAIBEE_SANDBOX` variable; `/sandbox` then does not change it. [Managed settings take precedence](/code/configuration/#settings-settingsjson). `/status` and `/doctor` show the current state; before a launch, you can check it with [waibee config check](/code/configuration/#checking-the-configuration).
### The restricted profile
[Section titled “The restricted profile”](#the-restricted-profile)
\~/.waibee/settings.json
```json
{
"sandbox": {
"profile": "restricted",
"network": {
"allowed_domains": ["example.com", "*.example.org"]
}
}
}
```
`sandbox.network.allowed_domains` sets the addresses commands can connect to through an HTTP proxy or a CONNECT tunnel. Give the domain without a scheme, port, or path. `example.com` allows only that domain; `*.example.org` also allows `example.org` itself and its subdomains; case does not matter. Every new address, including one reached through a redirect, is checked separately. An address that is not allowed gets HTTP `403` with the reason for the denial. HTTPS goes through CONNECT without TLS decryption.
If an allowed domain resolves to a private or reserved IP address, including the cloud metadata address, the connection to that IP is rejected unless the IP itself is listed in `sandbox.network.allowed_domains`. A domain pattern does not grant this.
Unix sockets are closed by default. On macOS, `sandbox.network.allow_unix_sockets` opens only the listed absolute socket paths, without access to the whole directory; `~` and relative paths are not accepted. On Linux, a non-empty list prevents `restricted` from starting: seccomp cannot filter Unix sockets by path. `SSH_AUTH_SOCK` is removed from a child command’s environment unless its socket path is in the list.
This list is required for command network access regardless of `netsec.enabled`. The rules for an empty list and for merging layers are described in [Configuration files](/code/configuration/#settings-settingsjson). The [netsec filter](#domain-restrictions) works separately and does not add its allowances here.
| System | What enforces the restriction |
| ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| macOS 11 or later | Seatbelt allows outgoing TCP only to the local proxy; other direct TCP connections, UDP, and raw sockets are closed, and binding a network socket is forbidden |
| Linux on x86\_64 and aarch64 | Landlock ABI V4 (usually kernel 6.7 or later), seccomp, and separate user and network namespaces leave the command access to the proxy only. Direct connections, UDP, raw sockets, and binding a network socket are closed |
Removing or replacing `HTTP_PROXY`, `HTTPS_PROXY`, and other proxy variables does not lift the kernel restrictions. The commands’ child processes inherit them.
`restricted` always stops the launch with exit code `2` if the restriction cannot be enforced, even with `sandbox.require: false`. On macOS, a working Seatbelt is required: a missing `sandbox-exec` or a failure to apply the policy, including inside a Seatbelt that is already in effect, prevents the launch. On Linux, Landlock with TCP rules, seccomp, and creating and entering both namespaces (`unshare` and `setns`) must all work. An old kernel, a disabled mechanism, an unsupported architecture, or a restriction imposed by a container stops the launch and names the reason. On Windows, this profile does not start. The agent starts the proxy for commands itself at launch; if the proxy fails to start, the launch stops too.
### What the sandbox does not cover
[Section titled “What the sandbox does not cover”](#what-the-sandbox-does-not-cover)
The sandbox restricts `Bash` and `REPL` commands, background commands, and hook commands. With a profile on, edits through `Write`, `Edit`, and `NotebookEdit` are checked separately against the allowed directories.
The sandbox does not restrict reading files: on its own, it does not close off `.env` or your home folder. Read tools follow the [path exclusion rules](/code/configuration/#excluding-paths).
With the sandbox in effect, `Bash` in an IDE runs locally in the same sandbox; without an active restriction, it may use the editor’s terminal. The agent’s own network traffic, model requests, tools inside the agent’s process, MCP servers, and language servers are outside the `restricted` network restriction. Opening files in an external program and worktree operations also run outside the sandbox. The full list of these exceptions is in [waibee config check](/code/configuration/#checking-the-configuration).
An allowed address can accept any data or forward it further. CONNECT does not restrict ports and does not inspect the tunnel’s contents or the server name inside TLS (SNI). Explicitly allowed Unix sockets and macOS system communication channels can give access to a local service that has its own network access. Connections that are already open or passed in are also outside this guarantee. The profile restricts new network connections from commands, not every way data can leave the machine. To run untrusted code, use a separate environment.
## Headless
[Section titled “Headless”](#headless)
A new `waibee run` takes its mode from `permissions.mode` in `settings.json`, or `trust` if that is not set. With `--resume` and `--continue`, the mode the session was left in is restored, but no broader than this cap. An explicit `--mode` (`--permission-mode`) or `--dangerously-skip-permissions` (`--yolo`, which is `bypassPermissions`) flag overrides the mode. The mode remembered from the terminal, the browser, or an IDE does not set the cap for headless. The run names its mode at the start; see [Permissions in headless mode](/code/headless/#permissions-in-headless-mode).
If an action needs approval, headless rejects it: there is no interactive prompt and no waiting for an answer, and that includes the folder trust question. The agent gets the denial and work continues, and in JSON output the denials are listed in `permission_denials`. So an edit outside the project or in a protected path does not run in headless in any mode except `bypassPermissions`; the [sandbox limits](#sandbox) apply there too. If the call would pass in a broader mode no higher than `trust`, the denial names that mode; `bypassPermissions` is never suggested. Allow the commands you need with specific `allow` rules or with the `--allowed-tools` flag for one run, or repeat the task interactively. A CI step timeout limits the total time the agent works.
`deny` lists and the rejection of destructive commands apply here too. More on running from scripts: [Headless mode](/code/headless/).
# Plugins
> What plugins add, installing and managing them, and marketplaces.
A plugin is a directory with a `plugin.json` manifest. It adds skills, subagents, slash commands, hooks, and MCP servers. A plugin declares its MCP servers in `.mcp.json` at its root: the `mcpServers` field in `plugin.json` is not read. Plugins do not add LSP servers. See [Language servers](/code/lsp/).
## Managing plugins
[Section titled “Managing plugins”](#managing-plugins)
You can install and remove plugins right in the agent, without leaving for the terminal. The `/plugin` command with arguments mirrors the CLI:
```text
/plugin install
/plugin remove
/plugin enable
/plugin disable
/plugin update # or --all
/plugin list
/plugin marketplace add
/plugin marketplace list
/plugin marketplace remove
```
`/plugin` without arguments and `/plugin list` open the plugin browser, with installed plugins, marketplaces, and load errors on separate tabs.
| Key | Action |
| --------------------------- | ------------------------------------------------- |
| `↑` `↓`, `j` `k` | Move through the list |
| `Tab`, `Shift+Tab`, `←` `→` | Switch tabs |
| `Enter` | Show what the plugin adds |
| `PageUp` `PageDown` | Scroll the details |
| Space | Enable or disable |
| `u` | Update the selected plugin |
| `d`, `Delete` | Remove a plugin or marketplace, with confirmation |
| `Esc`, `q` | Close |
Plugins installed through Claude Code (in `~/.claude`) are visible and work. You can enable and disable them here, and Claude Code’s files stay unchanged. They are updated and removed in Claude Code; removing one from here only disables it.
The same actions in the terminal, plus a few commands that `/plugin` does not have:
```bash
waibee plugin install # plugin@marketplace, owner/repo, git URL, or local path
waibee plugin list [--json] # what loads in this folder
waibee plugin details # what the plugin adds
waibee plugin validate # check before publishing
waibee plugin update # or --all
waibee plugin remove
waibee plugin disable # enable to turn it back on
```
`list` shows the plugins that load in the current folder, including those installed through Claude Code: the `FROM` column says where a plugin comes from (`waibee` or `claude-code`), and `STATE` says whether it is enabled. With `--json`, each plugin has `id`, `name`, `version`, `origin`, `enabled`, and `path`. `details` lists the plugin’s skills, commands, subagents, hooks, and MCP servers, also with `--json`.
`details`, `enable`, and `disable` take the plugin name or its ID: for a plugin installed by Claude Code, that is `@`. `enable` and `disable` work on Claude Code plugins too.
Command names from Claude Code work as well. See [Names from earlier versions](/code/claude-code/#names-from-earlier-versions).
Plugins are installed into `~/.waibee/plugins//`. Installing from a git source requires `git` in `PATH`.
Start a local path with `./`, `../`, or `~/`, or make it absolute; the directory does not need `git init`. A name without such a prefix is not treated as a path: the command replies with a hint showing both working forms. The `owner/repo` form always means a repository on GitHub, never a directory with that name.
## Marketplace
[Section titled “Marketplace”](#marketplace)
A plugin marketplace is registered by `owner/repo`, git URL, or local path. Its name is read from `marketplace.json` in the `.claude-plugin/` or `.waibee-plugin/` directory, or at the root of the repository. After registration, plugins install with the short form `@`.
```bash
waibee plugin marketplace add
waibee plugin marketplace list
waibee plugin marketplace update [] # reread the marketplace from its source; without a name, all of them
waibee plugin marketplace remove
```
Marketplaces added in Claude Code also appear in the list, and you can install plugins from them, but you can remove them only there.
## Validating before publishing
[Section titled “Validating before publishing”](#validating-before-publishing)
`waibee plugin validate ` checks a plugin or marketplace directory before you publish it:
* `plugin.json` in the directory, in `.claude-plugin/`, or in `.waibee-plugin/` can be read, or, if there is none, the directory contains at least one of `skills/`, `commands/`, `agents/`, `hooks/hooks.json`, or `.mcp.json`;
* the paths the manifest names (`skills`, `commands`, `agents`, `hooks`) exist;
* the plugin’s `.mcp.json` and `hooks/hooks.json` are valid JSON;
* every plugin in the marketplace’s `marketplace.json` has a name and a source that Waibee Code can install, no plugin is listed twice, and local sources (`./...`) exist.
A missing description, author, or version is a warning. An error ends the command with a nonzero exit code; a warning does so only with `--strict`. `--json` prints the report as JSON.
## Structure and compatibility
[Section titled “Structure and compatibility”](#structure-and-compatibility)
Plugins are looked up in project directories whose names end in `.waibee-plugin` or `.claude-plugin`, globally in `~/.waibee/plugins/`, and among Claude Code plugins in `~/.claude`. The `plugin.json` manifest sits at the plugin root or in its `.waibee-plugin/` or `.claude-plugin/` subdirectory. It is optional: without it, the plugin name comes from the marketplace entry or the directory name, and skills, commands, and hooks come from the standard subdirectories. The `skills/`, `commands/`, and `agents/` subdirectories are picked up even if the manifest does not list them. Hooks are read from the object in the manifest’s `hooks` field and from `hooks/hooks.json`.
A plugin’s commands, skills, and subagents get its name as a prefix: `/:`. MCP servers get the name `plugin__`, so their tools are named `mcp__plugin____`. Long names are shortened with a hash appended; in `permissions.allow` and `permissions.deny`, write the actual tool name.
A plugin that lives inside a repository provides its skills, commands, and subagents right away, but its hooks and MCP servers start only after the folder is trusted. See [Folder trust](/code/permissions/#folder-trust). An installed plugin is not affected.
`plugin.json` fields:
| Field | Value |
| ----------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name` | the plugin name, required |
| `version`, `description`, `homepage`, `license` | strings; a marketplace plugin with `version` updates when the version changes, and without it, when its directory in the source or its marketplace entry changes. A plugin installed straight from a git repository updates with every change to the repository |
| `author` | a string, or an object with `name` and `email` |
| `skills`, `commands`, `agents` | a path or list of paths to directories beyond the standard ones |
| `hooks` | hooks in the same format as in the [settings](/code/hooks/#configuration), or a path to a JSON file with them, relative to the plugin root |
A path from the manifest that leads outside the plugin directory, including through a symbolic link, is not loaded; `waibee plugin validate` reports an error for such a path.
`marketplace.json` fields: the marketplace `name`, `description`, and the `plugins` list. Each plugin has `name` and `source`. A source is either a string: `./path` inside the marketplace, a directory name inside `metadata.pluginRoot`, `owner/repo` on GitHub, or a git URL. Or an object:
| `source` | Fields | What gets installed |
| ---------------- | --------------------------- | -------------------------------------------------------- |
| `github` | `repo`, `ref`, `sha` | a repository on GitHub |
| `url` (or `git`) | `url`, `ref`, `sha` | a repository by git URL |
| `git-subdir` | `url`, `path`, `ref`, `sha` | one directory of a repository; `url` can be `owner/repo` |
| `path` | `path` | a directory inside the marketplace |
`url` is an `https://`, `http://`, `ssh://`, `git://`, `file://`, or `user@host:path` address. `ref` is a branch or tag, and `sha` is a full 40-character commit: with it, exactly that commit is installed. For `git-subdir`, only that directory is downloaded. Waibee Code does not install `npm`, `archive`, or `command` sources: such a plugin is unavailable, and the rest of the marketplace works. A path that leads outside the marketplace (`../`, absolute) is not accepted.
The other fields of an entry describe the plugin the same way as the `plugin.json` fields. If the plugin has no `plugin.json` of its own, the entry serves as its description. If it has one, `skills`, `commands`, and `agents` from the entry are added to it, and `hooks` from the entry replace the hooks for the same event. If the plugin has its own `plugin.json`, an entry with `"strict": false` cannot name components: installing such a plugin fails.
A plugin that contains only language servers (`lspServers`, `.lsp.json`) is not installed: Waibee Code connects the servers itself. See [Language servers](/code/lsp/).
The format is compatible with Claude Code: Claude Code marketplaces and manifests are read as is. A disabled plugin adds nothing: no skills, commands, hooks, or MCP servers.
To see which marketplaces exist and what to check before installing, read [Finding extensions](/code/ecosystem/#plugins).
# Example prompts
> Sample prompts for common tasks, and what makes a prompt precise.
Common tasks and how to phrase them for the agent. The techniques behind them are covered in [Best practices](/code/best-practices/) and [Development workflows](/code/workflows/). Short prompts are grouped by task type; detailed multi-line examples are in [Large requests](#large-requests).
## What makes a good prompt
[Section titled “What makes a good prompt”](#what-makes-a-good-prompt)
You don’t need all four parts every time, but the larger the task, the more of them you need.
| Part | Why | Example |
| ------------------ | --------------------------------------------------- | -------------------------------------------------------- |
| Location | So the agent doesn’t read half the project | ”in `export/stream.py`, especially the buffering” |
| Constraints | So the change doesn’t spread | ”no new dependencies, don’t change the public interface” |
| Example to follow | So the result matches what the project already does | ”following `pages/settings.tsx`” |
| Definition of done | So the agent checks itself | ”after the change, run `make test` and show the output” |
## Getting to know a project
[Section titled “Getting to know a project”](#getting-to-know-a-project)
* “walk me through the project: where an incoming request starts, which layers it passes through, and where it ends. if there is an architecture, sketch a diagram”.
* “explain what `internal/billing/` is responsible for, and show who calls it”.
* “use a subagent to find out how authorization works in the project, and return a short summary: where the entry point is, what the roles are, where sessions are stored”.
## Understanding code
[Section titled “Understanding code”](#understanding-code)
* “what does `retryWithBackoff` do, and where is it called from? show the chain up to the external call”.
* “if `withRetry` is removed, what breaks? check by actual calls, not by name”.
* “why is this a blocking call and not a queue? look at the change history of this file and explain how it ended up this way”.
## Debugging
[Section titled “Debugging”](#debugging)
* “the stream cuts off on long responses. first reproduce this with a failing test in `stream/`, then fix the cause instead of swallowing the exception”.
* “`test_pricing.py` went red after the last commit. find the change that broke it and fix it without touching the test itself”.
* “here is the error stack trace \[paste]. find the place in the code, explain the condition under which this happens, and propose a fix. don’t change anything yet”.
## Tests
[Section titled “Tests”](#tests)
* “write a failing test for the bug in issue #142: a user without permission sees someone else’s order. show that it is red, then make it green”.
* “cover `orders.go` with tests for canceling a paid order and canceling it twice; no mocks, use a test transaction”.
* “check that the tests in `test_auth.py` test behavior, not implementation. rewrite any test that would break on a harmless refactor”.
## Refactoring
[Section titled “Refactoring”](#refactoring)
* “in `pages/settings.tsx`, the form has validation and is split into sections. repeat this structure for the profile page, don’t change how the existing forms behave, keep the tests green”.
* “extract the pagination repeated in three handlers into a shared helper; behavior stays the same, and the tests must pass”.
* “go through the branch’s diff and remove what isn’t needed: interfaces with a single implementation, wrappers with no logic, comments that repeat the code”.
## Performance
[Section titled “Performance”](#performance)
Say how you measure the result, or the agent optimizes blindly.
* “`make bench` prints the build time. it is 94 seconds now. get it down to 60, change only the build configuration, run the benchmark after each change, and show the numbers”.
* “the `/v1/reports` endpoint takes 2.4 s on the data from `fixtures/large.json`. find where the time goes, show measurements before and after, don’t change the behavior”.
* “run a loop of experiments: edit only `src/parser.rs`, the metric is the output of `./bench.sh`, keep a change only if it beats the baseline by more than the noise, and revert the rest”.
This kind of loop is covered in detail in [Autoresearch](/code/autoresearch/).
## External libraries
[Section titled “External libraries”](#external-libraries)
* “we need to hook up the payment provider’s webhooks. first pull the current documentation for their SDK, show which version and which methods you will use, and only then write code”.
* “compare two ways to do this: with the built-in scheduler and with a separate queue. for each: what we’ll have to maintain, where it breaks. give the conclusion as one table, no code”.
## Interface
[Section titled “Interface”](#interface)
* “\[screenshot] make the table match this mockup. then open the page in a browser, take a screenshot of the result, list the differences, and fix them”.
* “test the sign-up form in a browser: empty fields, an email address that is too long, a double click on the button. show what happens in each case”.
* “this page has an element that appears on hover and shows a tooltip \[screenshot]. make the same one in the header, and take the styles from existing components”.
## Bulk edits
[Section titled “Bulk edits”](#bulk-edits)
Start with two files, then do all of them: it is cheaper to catch a bad prompt that way.
* “twelve handlers in `src/api/` return errors in different ways. bring them to the format from `handlers/orders.go`. start with two files, show the diff, and we’ll continue from there”.
* “collect the list of files that still use the old logging client and write it to `todo.txt`. don’t change anything yet”.
## Review
[Section titled “Review”](#review)
* “use a fresh subagent to check this branch’s diff against `SPEC.md`: are all items implemented, are edge cases covered by tests, is anyone else’s code affected. only discrepancies, no style nitpicks”.
* “go through my last change and find edge cases and race conditions I may have missed; for each, show the line and how to reproduce it”.
* “look at the diff through the eyes of someone who will maintain it a year from now: what will be unclear, where is a name or an explanation of the reason missing”.
## Git and PRs
[Section titled “Git and PRs”](#git-and-prs)
* “make a commit from what is staged, with a message about the substance of the change; then open a PR with `gh` and put the checklist from `SPEC.md` in the description”.
* “show how this branch differs from `main`, and write a PR description: what changed and why”.
## Defining the task
[Section titled “Defining the task”](#defining-the-task)
* “I want to move email sending into a separate service. interview me with the `AskUserQuestion` tool about the boundaries, the message format, and what to do with the current templates. skip the obvious. write the outcome to `SPEC.md`”.
* “read `SPEC.md` and tell me what is missing before implementation can start: which decisions haven’t been made, which cases aren’t described”.
## Large requests
[Section titled “Large requests”](#large-requests)
A short prompt works while the task fits into one thought. Once there are several (what to do, what not to do, in what order, how to check), write a longer prompt in blocks: context, task, constraints, order of work, definition of done, response format. Such a prompt takes longer to write, but it replaces several follow-up clarifications, and you can reuse it in a new session.
Analyzing a large change before starting:
```text
Context: a billing service, the entry point is in `internal/billing/`, amounts are
stored as integer cents, rounded down. Tests run with `make test`, the linter with `make lint`.
Task: add partial refunds for an order. A refund is created for an amount,
not for line items. The total of all refunds cannot exceed the amount paid.
Constraints: don't add new dependencies, don't change the public interfaces
of `OrderService`, change the DB schema only through a migration.
Order: first read `internal/billing/` and show where payment happens today
and where the operation history is kept. Then propose a plan and stop,
I'll review it. We write code after I approve.
Keep in mind: a repeated request with the same ID, a refund on an order that
was already refunded, a race between two refunds, rounding when dividing.
```
Implementing a spec in a new session:
```text
Read SPEC.md and implement the "Partial refunds" section.
Rules: for each acceptance criterion, a failing test first, then the code.
Don't touch files outside `internal/billing/` and `migrations/`. If the spec
doesn't cover something, don't fill in the gaps: stop and ask.
Done means: `make test` and `make lint` are green, every acceptance criterion
is covered by a test, and you have shown the output of both commands.
At the end, give a list: spec item, the test that checks it.
```
Investigating an incident with attached data:
```text
[paste the stack trace]
[paste the log excerpt from the minute before]
What we know: the error reproduces on roughly one request in a thousand,
it started after Tuesday's release, and only on long responses.
Work step by step: find the place from the stack trace in the code, explain
what combination of circumstances makes it reachable, check the hypothesis
against the code and the log, and only then propose a fix. If data is missing,
say what you need.
Don't change anything yet.
```
Length alone does not help: a prompt with no constraints and no definition of done stays vague, however many lines it has.
## What to avoid
[Section titled “What to avoid”](#what-to-avoid)
| Prompt | What’s wrong with it |
| ------------------- | ------------------------------------------------------------ |
| ”make it look nice” | No criterion; the agent stops at the first plausible version |
| ”study the project” | It reads hundreds of files and fills up the context |
| ”fix the tests” | It may “fix” them by editing the tests themselves |
| ”optimize the code” | Without a metric, optimization turns into a matter of taste |
| ”finish the rest” | The scope is undefined, so the diff is unpredictable |
# Quickstart
> Set your API key and start Waibee Code.
## 1. API key
[Section titled “1. API key”](#1-api-key)
Create an API key in the console: [chat.waibee.com/api-keys](https://chat.waibee.com/api-keys). You don’t have to save it in advance: the first time you run `waibee` without a key, it asks you to paste one.
To save the key from the shell:
```bash
waibee auth login
```
The command stores the key in the system keychain. If the keychain is unavailable, it uses a [file on disk](/code/waibee-directory/#global).
You can also pass the key in an environment variable. It takes precedence over the saved key:
```bash
export WAIBEE_API_KEY="sk_live_..."
```
## 2. Interactive mode
[Section titled “2. Interactive mode”](#2-interactive-mode)
Run `waibee` with no arguments in your project directory. The TUI opens: describe the task in plain language, and the agent reads files, proposes edits, and runs commands.
```bash
cd my-project
waibee
```
If no key is saved yet, the TUI asks for one first and then shows a short tour of the interface. Open the tour again at any time with `/guide`.
If the project has its own hooks, MCP servers, or plugins, the first run in that folder asks whether you trust it. Until you agree, they don’t run; see [Folder trust](/code/permissions/#folder-trust).
## 3. What to set up first
[Section titled “3. What to set up first”](#3-what-to-set-up-first)
These are all commands inside the TUI. `/help` lists every command, and typing `/` opens the command menu.
| Command | What it’s for |
| ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `/guide` | A tour of the interface. Come back to it whenever you forget something |
| `/model` | Choose a model; see [Choosing a model](/code/models/) |
| `/effort` | Reasoning level, from `none` to `max`. The available levels depend on the model; see [Choosing a model](/code/models/#reasoning-level-effort) |
| `/sandbox` | Limit where the agent’s commands can write; see [Permissions](/code/permissions/#sandbox) |
| `/settings` | The main settings: model, interface language, permission mode, sandbox, domain filter, limits, interface appearance, audit log, and storage cleanup. Set the other keys in `settings.json`; see the [Settings reference](/code/settings/). The language comes from `LC_ALL`, or from `LANG` if `LC_ALL` is not set: a value starting with `ru` turns on Russian, anything else gives English |
| `/status` | Session state: model, context window, and tokens used |
These keys and commands help from the start:
* **Shift+Tab** cycles through the four approval modes. The bottom bar shows the current mode; for details, see [Permissions](/code/permissions/).
* **`@`** opens a list of project files and inserts a path into your prompt; the agent reads the contents itself. `Ctrl+V` (`Cmd+V` on macOS) attaches an image from the clipboard or from a copied file path.
* **↑** scrolls through your earlier messages. If a message is still waiting in the queue, ↑ brings it back into the input field to edit.
* **Esc** first closes a dialog or the suggestion list, or clears the selection. If none of those is open, it interrupts the current turn.
* **`/compact`** requests compaction of the conversation; a short history stays as it is. See [Context window](/code/context-window/).
All terminal keys are listed under [Keys](/code/features/#keys).
Later, as you need them: [`/goal`](/code/goal/) makes the agent keep working until a condition is met, and `/sessions` and `/resume` take you back to earlier conversations. The full reference is in [Commands](/code/commands/).
## 4. The same in the browser
[Section titled “4. The same in the browser”](#4-the-same-in-the-browser)
Waibee Code has a local web interface: the agent runs on your computer, and you talk to it in the browser. To continue your current chats there, type `/web` in the open TUI:
```text
/web
```
Open the link it prints. In the browser you can review the diff, send the agent comments on specific lines, and work with several sessions. The **Open on your phone** button shows a QR code for your phone.
For a standalone server, run `waibee serve` from the shell. It does not connect to the chats of a TUI that is already running. More in [Local web interface](/code/web/).
## 5. Headless mode
[Section titled “5. Headless mode”](#5-headless-mode)
A one-off run with a prompt and no interface:
```bash
waibee run "add tests for the auth module"
```
A run like this asks no questions. The mode comes from your settings, and without a setting it is `trust`; see [Permissions in headless mode](/code/headless/#permissions-in-headless-mode). `--mode default` rejects actions that need approval, but explicitly allowed actions, including writes, still go through.
The result goes to stdout, so you can call the agent from scripts, git hooks, CI, and other programs. Output formats, exit codes, and ready-made recipes are in [Headless mode and automation](/code/headless/).
## 6. IDEs and terminal clients
[Section titled “6. IDEs and terminal clients”](#6-ides-and-terminal-clients)
Waibee Code connects to editors over the Agent Client Protocol (Zed, JetBrains, and others); see [IDEs (ACP)](/code/ide/). The same protocol works from the command line through acpx, with sessions that persist between calls and JSON output for scripts; see [ACP in the terminal](/code/acpx/).
# Settings reference
> Every settings.json key: allowed values, defaults, and what each one does.
This page lists every `settings.json` key that Waibee Code reads. For where the files live and the order in which they layer over each other, see [Configuration files](/code/configuration/#settings-settingsjson). You can also change the main keys in the terminal with the `/settings` command, which saves them to the global file; its keys are described in [Keys](/code/features/#keys).
## How files are read
[Section titled “How files are read”](#how-files-are-read)
* A file must be valid JSON: comments and a trailing comma after the last element are not allowed. An error in the managed file [stops the launch](/code/configuration/#settings-settingsjson); on an error in any other layer, the agent falls back to the global settings or the defaults. To check the resulting configuration, use [waibee config check](/code/configuration/#checking-the-configuration).
* An unknown key causes no error and has no effect. This includes Claude Code keys that have no equivalent here, such as `permissions.defaultMode` and `permissions.ask`: the mode is set with the `permissions.mode` key.
* Usually the value comes from the last layer that sets it. The exceptions and how lists are merged are described in [Configuration files](/code/configuration/#settings-settingsjson).
* In a folder you do not trust, some keys from its files do not take effect; see [Folder trust](/code/permissions/#folder-trust).
* With the sandbox on, changes to a file on disk do not change the permissions and hooks of a running session; see [Configuration files](/code/configuration/#settings-settingsjson).
## Model
[Section titled “Model”](#model)
| Key | Values | Default | What it does |
| --------------------- | -------------------------------------------------------------------- | ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `model` | an alias (`sonnet`, `opus`, `haiku`, or your own) or a full model ID | `sonnet` | The main agent’s model; see [Choosing a model](/code/models/). Not read from `.claude/settings.json` |
| `aliases` | an object `{"name": "model id"}` | built-in `sonnet`, `opus`, `haiku` | Your own short model names |
| `thought_level` | `none`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max` | depends on the model | The reasoning level; `off` is read as `none`. Applies while the current model matches `thought_level_model`. The `/effort` command writes both keys itself |
| `thought_level_model` | a full model ID | the value of `model` | The model that `thought_level` applies to |
## Context and memory
[Section titled “Context and memory”](#context-and-memory)
| Key | Values | Default | What it does |
| ---------------------- | ------------------------------- | --------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `context.compact_at` | 20 to 70, percent of the window | `70` | When automatic [compaction](/code/context-window/#history-compaction) starts |
| `context.idle_compact` | `true`, `false` | `true` | Allow [compaction while idle](/code/context-window/#compaction-while-idle) |
| `context.prompt_cache` | `auto`, `5m`, `1h` | `auto` | How long Anthropic models and `waibee/auto` keep the [prompt cache](/code/context-window/#prompt-cache); `auto` is an hour for the main agent |
| `helper.model` | a model | the [helper model](#helper-model) | The model for chat titles and other small background jobs |
| `title.auto` | `true`, `false` | `true` | Give a chat a title automatically |
| `memory.auto` | `true`, `false` | `true` | Add to [memory](/code/configuration/#memory) during work |
| `memory.model` | a model | `helper.model`, or the [helper model](#helper-model) without it | The model that picks facts for memory |
| `memory.max_bytes` | bytes | `2048` | The threshold at which old automatic entries are removed; manual entries can exceed it |
| `read.max_bytes` | bytes | `262144` (256 KB) | How much `Read` returns to the model per call |
### Helper model
[Section titled “Helper model”](#helper-model)
`helper.model` picks the model for chat titles and other small background jobs. Old configurations with `compaction.model` still work. This does not choose a summary model: [compaction](/code/context-window/#history-compaction) uses the session’s own model and its cached conversation.
Other background jobs include picking facts for memory, the [goal](/code/goal/) check, summarizing pages for `WebFetch`, and web search. By default, these use an available helper model, or the session’s main model if the helper model is not in the router’s catalog. Helper calls run at the lowest reasoning level the model accepts. Use `memory.model` for memory and `goal.evaluator_model` for the goal check.
## Per-message limits
[Section titled “Per-message limits”](#per-message-limits)
By default, neither tokens nor time stop the work on a message: the agent works until it is done, and only the turn limit guards against endless work. A spending limit applies only if you set one. Limits count per message you send, together with all the subagents it started, and start over with the next message.
| Key | Values | Default | What it does |
| ---------------------------- | ---------- | ---------------------- | ---------------------------------------------------------------------------------------------------------------- |
| `max_turns` | an integer | `10000` | How many turns the main agent gets. For example, `1` limits the work to one turn; `0` restores the default limit |
| `sub_agent_max_turns` | a number | same as the main agent | How many turns each subagent gets if its definition has no `maxTurns` |
| `max_billable_input_per_run` | tokens | none | The limit on billable input tokens: fresh input and cache writes. Tokens read from the cache do not count |
| `max_output_per_run` | tokens | none | The limit on output tokens |
| `max_run_seconds` | seconds | none | The limit on working time; in headless mode, it is a [hard stop deadline](/code/headless/#run-limits) |
\~/.waibee/settings.json
```json
{
"max_run_seconds": 3600,
"max_billable_input_per_run": 5000000
}
```
The same fields are in `/settings`; an empty field means “no limit”. For a single `waibee run`, flags set the limits; see [Run limits](/code/headless/#run-limits).
In an interactive chat, when a limit is reached, the agent takes one last turn without tools and replies with what it has done so far, and the chat shows a line saying which limit was reached. The next message continues the work. How a headless run ends is described in [Run limits](/code/headless/#run-limits).
## Permissions and security
[Section titled “Permissions and security”](#permissions-and-security)
| Key | Values | Default | What it does |
| ------------------------------------------- | ------------------------------------------------------ | ----------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `permissions.mode` | `default`, `acceptEdits`, `trust`, `bypassPermissions` | `default`, `trust` in headless mode | The mode a session starts in; see [Permissions](/code/permissions/) |
| `permissions.allow` | a list of regular expressions | empty | What is approved without a question |
| `permissions.granted` | a list of regular expressions | empty | Permanent permissions from the [approval card](/code/permissions/#approvals). Written to `.waibee/settings.local.json`; they do not allow risky commands |
| `permissions.deny` | a list of regular expressions | empty | What is forbidden in any mode, including whole tools; see [Denying a tool](/code/permissions/#denying-a-tool) |
| `trusted_folders` | a list of paths | empty | Folders you trust. Read only from the global and managed files |
| `sandbox.profile` | `off`, `workspace-write`, `restricted` | `off` | The [sandbox](/code/permissions/#sandbox) profile. The managed file’s precedence is described in [Configuration files](/code/configuration/#settings-settingsjson) |
| `sandbox.allow_write` | a list of paths | empty | Extra directories the sandbox allows writes to. Read only from the global file |
| `sandbox.require` | `true`, `false` | `false` | Do not start where the chosen sandbox cannot be provided. Read from the global and managed files; see the [merge rules](/code/configuration/#settings-settingsjson) |
| `sandbox.network.allowed_domains` | a list of domains | empty | Allowed addresses for commands in the [restricted](/code/permissions/#the-restricted-profile) profile. The merge rules and the empty-list rule are described in [Configuration files](/code/configuration/#settings-settingsjson) |
| `sandbox.network.allow_unix_sockets` | a list of absolute paths | empty | Unix socket exceptions in [restricted](/code/permissions/#the-restricted-profile): exact paths on macOS; on Linux, a non-empty list prevents the launch. The merge rules are described in [Configuration files](/code/configuration/#settings-settingsjson) |
| `netsec.enabled` | `true`, `false` | `false` | Turn on the [domain filter](/code/permissions/#domain-restrictions) |
| `netsec.allowed_domains` | a list of domains | empty | Allow only these domains |
| `netsec.blocked_domains` | a list of domains | empty | Block these domains |
| `files.skip_integrity_check` | `true`, `false` | `false` | Turn off the `Edit` check: without it, the agent edits a file it has not read or that changed after it was read. `true` in any of the files turns the check off |
| `privacy.redact.additional_sensitive_keys` | a list of name patterns | empty | Which other fields to mask in the audit log and crash reports |
| `privacy.redact.additional_command_regexes` | a list of regular expressions | empty | Which other string fragments to mask in the same places |
| `privacy.redact.disable_default_patterns` | `true`, `false` | `false` | Do not apply the built-in masking list. `privacy` keys are read only from the global and managed files |
| `api_key` | an `sk_live_...` key | none | The API key. The `WAIBEE_API_KEY` variable takes precedence over this key, and the system keychain is checked after it. Keeping the key in the keychain is safer: `waibee auth login`. That command and `waibee auth logout` remove the key from this field |
## Extensions and environment
[Section titled “Extensions and environment”](#extensions-and-environment)
| Key | Values | Default | What it does |
| --------------------------- | ------------------------------ | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `mcpServers`, `mcp.servers` | an object of servers | empty | [MCP servers](/code/mcp/): the entry fields are described there |
| `mcp.default_timeout_ms` | milliseconds, `0` for no limit | none | The tool call timeout for every MCP server whose entry has no `timeout_ms` of its own. Without this key, the default timeout applies; see [MCP](/code/mcp/) |
| `hooks` | an object of events | empty | [Hooks](/code/hooks/). Read only from `settings.json`: they have no effect in `settings.local.json` or the managed file |
| `env` | an object `{"NAME": "value"}` | empty | Environment variables for the agent and its commands. A variable already set in the environment is not overwritten. `WAIBEE_DATA_DIR` cannot be set this way |
| `lsp.prewarm` | `true`, `false` | `false` | Start [language servers](/code/lsp/) when the session starts instead of on first use |
## Network
[Section titled “Network”](#network)
| Key | Values | Default | What it does |
| ------------------------------ | ------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `network.proxy` | a URL | none | A proxy for the agent’s HTTP requests. Without it, model requests, update checks, and MCP server logins go through `HTTPS_PROXY`, `HTTP_PROXY`, or `ALL_PROXY` from the environment, honoring `NO_PROXY`, while `WebFetch` connects directly: it does not read environment variables, only this key |
| `network.connect_timeout_secs` | seconds | `10` | The connection timeout |
| `network.request_timeout_secs` | seconds | `120` | The timeout for a non-streaming request. It does not apply to streamed model responses |
## Log and storage
[Section titled “Log and storage”](#log-and-storage)
| Key | Values | Default | What it does |
| ----------------------------- | --------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `audit.enabled` | `true`, `false` | `true` | Keep the audit log. `false` in any of the files turns it off |
| `audit.max_size_mb` | MB | `100` | The log file size after which the same day’s entries continue in the next file. This key does not limit the log’s total size |
| `storage.audit_max_age_days` | days | `90` | How many days to keep the audit log. Older days are removed automatically when the day changes, without `auto_cleanup`. Read only from the global file |
| `storage.cache_max_age_days` | days | `7` | How long to keep the cache during scheduled cleanup |
| `storage.tool_outputs_max_mb` | MB | `50` | The size of saved tool results after which `waibee storage status` warns you |
| `storage.auto_cleanup` | `true`, `false` | `false` | Clean up storage in the background at launch, with the retention periods of [`waibee storage clean all`](/code/waibee-directory/#disk-space). `true` in any of the files turns cleanup on |
## Goal mode and background commands
[Section titled “Goal mode and background commands”](#goal-mode-and-background-commands)
| Key | Values | Default | What it does |
| ------------------------------ | --------------- | --------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| `goal.evaluator_model` | a model | the [helper model](#helper-model) | The model that checks the [goal](/code/goal/) |
| `goal.max_iterations` | a number | `50` | The limit on turns with a goal check, including the first |
| `goal.auto_goal` | `true`, `false` | `true` | Suggest a goal from the first prompt. In the terminal the agent asks; `waibee run` sets it without asking. `false` in any of the files turns this off |
| `background.max_jobs` | a number | `10` | How many background commands run at the same time. They stop together with the session |
| `background.job_output_max_kb` | KB | `256` | How much of the latest output is kept for each stream of a background command |
## Interface
[Section titled “Interface”](#interface)
| Key | Values | Default | What it does |
| ------------------ | ----------------- | ------------------- | -------------------------------------------------------------------------------------------------- |
| `tui.language` | `en`, `ru` | the system language | The interface language. Change it in `/settings` in the terminal, or in the sidebar in the browser |
| `tui.show_splash` | `true`, `false` | `true` | The splash screen at launch |
| `tui.centered` | `true`, `false` | `false` | Keep the interface in a centered column in a wide terminal |
| `tui.center_width` | number of columns | `100` | The width of that column |
## Updates
[Section titled “Updates”](#updates)
| Key | Values | Default | What it does |
| ----------------- | --------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| `updates.channel` | `stable`, `beta`, `nightly` | `stable` | The channel [`waibee update`](/code/install/#updating) installs from. Read only from the global file; automatic checks at launch do not depend on it |
| `updates.check` | `true`, `false` | `true` | Check for updates automatically at startup and in the TUI. `false` in any layer turns the checks off, and later layers do not turn them back on |
`WAIBEE_NO_UPDATE_CHECK=1` or `DISABLE_AUTOUPDATER=1` in the environment also turns off all automatic checks. With the checks off, the agent runs the installed version and does not check the minimum supported version. You need to update it yourself; the explicit `waibee update` and `/update` commands stay available.
The agent writes the keys `permissions.last_picked`, `updates.last_check`, `updates.last_seen_version`, `has_completed_onboarding`, `tour_seen`, and `tour_seen_web` itself to remember state between launches. You do not need to edit them by hand.
## Tool set
[Section titled “Tool set”](#tool-set)
There is no separate key that sets the main agent’s tool set. A built-in tool is turned off with a rule in `permissions.deny`, and an MCP server’s tool with the `disabled_tools` key in the server’s entry; see [Denying a tool](/code/permissions/#denying-a-tool). For a single headless run, there is the [—tools](/code/headless/#tool-set) flag. For the duration of one command or skill, the `allowed-tools` field narrows the set, and for a subagent the `tools` and `disallowedTools` fields do; see [Skills and commands](/code/skills/).
# Skills and commands
> Custom skills and slash commands: how to create them, where to keep them, and how to invoke them.
Skills and commands are your own extensions to the agent, written as Markdown files. They share one mechanism: a command also works as a skill, so the agent can load it on its own based on its description, and you can invoke it by hand with `/name`.
## Custom commands
[Section titled “Custom commands”](#custom-commands)
A command is a Markdown file in a `commands/` directory (inside `.waibee/` or `.claude/`, in the project or globally in `~`). The file name becomes the command name unless the frontmatter has `name`: `review.md` is invoked as `/review`. A subdirectory adds a prefix: `deploy.md` in `commands/ops/` is invoked as `/ops:deploy`.
The body of the file is a prompt template that gets filled in on invocation. Arguments:
* `$ARGUMENTS` inserts the whole string after the command name,
* `$1`, `$2` insert individual arguments in order,
* `` !`command` `` inserts the output of a shell command at the time of invocation. The command must be fast and print little; otherwise the text gets a `[!substitution ...]` marker instead.
If the template uses `$ARGUMENTS` or positional substitutions, the arguments go only into those places. If there are no substitutions, the argument string is appended to the prompt.
Optional frontmatter configures the command:
```markdown
---
description: Short description for the command list
argument-hint:
allowed-tools: Read, Grep, Bash
---
Check branch $1 for conflicts with main and describe what needs fixing.
```
* `description` appears in the command list.
* `argument-hint` tells you which arguments are expected.
* `allowed-tools` limits the tool set for the turn the command starts. If you [invoke several commands in one line](/code/commands/), their sets are combined; a command without a limit leaves the combined set unlimited. In Claude Code this field means something else. See [What works differently](/code/claude-code/#what-works-differently).
That is how invocation with `/name` works. When the agent loads a command or skill on its own with the `Skill` tool, it gets the text with the arguments filled in: the tool set is not limited, and `` !`command` `` does not run.
Skill, command, and subagent directories can be symbolic links, so you can keep a shared set in one place.
## Skills
[Section titled “Skills”](#skills)
A skill is a command with extra files next to it: a `.waibee/skills//` directory with a `SKILL.md` file and any supporting material. The skill name comes from the `name` field, or from the directory name if the field is missing. A standalone `.md` file directly in `skills/` is also read as a skill.
SKILL.md
```markdown
---
name: deploy
description: Deploy the current branch to staging
allowed-tools: [Read, Bash, Edit]
argument-hint: "[environment]"
---
When asked to deploy: show git status, run the tests, then deploy.
```
Frontmatter fields: `name`, `description`, `allowed-tools`, `argument-hint`, and `user-invocable` (`true` by default). `user-invocable: false` removes the skill from the `/` menu, but the agent can still load it on its own. Other fields are not read.
The agent keeps the short descriptions of all skills in context at all times and loads the full content only when a skill is needed. That way, knowledge for a specific task does not take up space in every session.
One skill is built in: `waibee` describes the commands of the app itself, and the agent loads it when you ask about Waibee Code. It is not in the `/` menu, and it stays even with `--bare`.
## Subagents
[Section titled “Subagents”](#subagents)
A subagent is a separate agent that the main one starts with the `Agent` tool for a narrow task in a separate context. Unless its definition says otherwise, it runs on the same model and at the same reasoning level as the main agent, and it spends from the same budget as the request that started it. The number of concurrent subagents is limited; the rest wait in a queue. Put the definition in `.waibee/agents/.md`:
.waibee/agents/code-reviewer.md
```markdown
---
name: code-reviewer
description: Reviews a diff for correctness and style, without edits
tools: [Read, Glob, Grep]
effort: high
skills: [code-standards]
---
You are a reviewer. Read the diff and point out problems. Do not change anything.
```
The body of the file becomes the subagent’s system prompt. It replaces the opening part that describes the agent’s role, and the general working rules stay. The subagent also gets the project instructions (`WAIBEE.md`, `CLAUDE.md`) unless its definition has `omitClaudeMd`. Compaction does not touch the system prompt, so the body, like `WAIBEE.md`, stays in full until the run ends. The task the main agent passes to `Agent` arrives as the first message and gets summarized during compaction, so put standing rules in the body. To the model it is still a request: back up a rule that must not be broken with a hook in the `hooks` field. An edit to the file takes effect from the subagent’s next run.
The frontmatter is read as YAML, so a list can go on one line or on separate lines with a dash. Files are also found in subdirectories of `agents/`. A file with neither `name` nor `description` does not count as a subagent and is skipped; if only `name` is missing, the name comes from the file name.
| Field | What it does |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name`, `description` | the name for `Agent` and the line used to pick the agent |
| `model` | a model of its own instead of the parent’s: an alias or `provider/model`. `inherit` and an unknown name without `/` give the parent’s model |
| `tools` | what is available to the subagent. `["*"]` is the parent’s whole set; `mcp__` or `mcp____*` is every tool of a server at once |
| `disallowedTools` | what to subtract from the available set; the same masks, plus `mcp__*` for all of MCP |
| `permissionMode` | the permission mode; it can only narrow the session’s permissions. `plan` leaves only reading, `dontAsk` rejects everything that would need approval |
| `maxTurns` | the cap on turns for one run. Without the field, `sub_agent_max_turns` applies. See [Per-message limits](/code/settings/#per-message-limits) |
| `timeoutSecs` | how many seconds to give a run; the overall `max_run_seconds` applies even without this field. When time runs out, the subagent is not cut off: it replies with what it has found so far |
| `effort` | how hard the subagent thinks: `none`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max`; the set depends on the model. See [Choosing a model](/code/models/#reasoning-level-effort). Without the field, it thinks at the same level as the main agent if they share a model; a different model has its own default level |
| `skills` | skills that sit in its context from the first turn |
| `omitClaudeMd` | do not put the project instructions in its prompt |
| `hooks` | hooks in the settings format, only for the duration of its run. They are added to the project’s hooks rather than replacing them |
| `background` | run in the background: the parent’s turn goes on, and the result arrives on the next turn |
| `isolation: worktree` | work in a separate git working copy; the subagent names the branch and path in its reply |
| `mcpServers` | MCP servers for it alone: a name from the settings or a server definition inline. `tools` does not filter their tools, but `disallowedTools` still hides them |
Without `tools`, a subagent gets the default set: `Read`, `Write`, `Edit`, `NotebookEdit`, `Bash` with `BashOutput` and `TaskStop`, `REPL`, `Glob`, `Grep`, `LSP`, `Skill`, `ToolSearch`, `CallTool`, `TodoWrite`, `WebFetch`, `WebSearch`, `Say`, and the parent’s MCP tools. A subagent gets `Say` even with its own `tools` list, unless `disallowedTools` forbids it: it is the subagent’s channel to the main agent. Six tools are never available to it, even with `["*"]`: `Agent`, `TaskPeek`, `SidePanel`, `AskUserQuestion`, `EnterWorktree`, `ExitWorktree`. It does not start subagents of its own, and it cannot ask a person either: the parent does that. A name in `tools` that matches no tool shows in `/agents` and in the result the main agent gets, with the reason: a typo, a tool turned off in the settings or in `/mcp`, an MCP server that is not connected, or an old tool name (then it also says which name to use).
The built-in subagents `Explore` and `Plan` only read: they have `Read`, `Glob`, `Grep`, `LSP`, `Skill`, `ToolSearch`, `TodoWrite`, `WebFetch`, `WebSearch`, and `Say`. Your own definition with the same name replaces the built-in one.
Tool names in the `tools`, `disallowedTools`, and `allowed-tools` lists can also be written the old way. See [Names from earlier versions](/code/claude-code/#names-from-earlier-versions).
The main agent can clarify the task for a running subagent, or continue a finished one, through `Agent` with the `resume` field and the ID of the earlier agent. For a running subagent, the clarification goes into the current conversation; a finished one continues with its saved history after rereading the definition with the earlier name. If the definition can no longer be found anywhere, it cannot be continued. A subagent that hits a limit does not stop mid-sentence: it replies with what it found and says where it stopped. You can follow its progress and the clarifications in the terminal and in the [browser](/code/web/).
The `TaskPeek` tool lets the main agent check on a subagent’s progress at any time without interrupting it.
You can also write to a subagent yourself: in the terminal, open it in Agent View (`Tab`); in the browser, in the agent panel. If the subagent is still working for the main agent, your message goes into that work, and the result goes to the main agent. If it has already finished, it replies to you, and the main agent neither learns about this conversation nor wakes up. If the main agent needs to know something, the subagent tells it with the `Say` tool, and that wakes the main agent.
The working copy stays after the run: deleting it means losing what the subagent did. Once you have taken the work, remove the copy as usual with `git worktree remove ` and `git branch -D `.
If the `tools` list matched nothing and the subagent’s own MCP servers added no working tools, the agent refuses to start the subagent and explains why.
`hooks` and `mcpServers` of a subagent defined by a file from this repository run only after the folder is trusted. See [Folder trust](/code/permissions/#folder-trust). The other fields are always read, and a subagent from your `~/.claude` or `~/.waibee` is not affected.
The Claude Code fields `color`, `memory`, `initialPrompt`, `cacheTtl`, `observer`, `observerMessage`, `observeSubagents`, and `isolation: remote` are accepted but do nothing. Memory is still available to a subagent: it gets the facts from `USER.md` and `MEMORY.md` without that field.
## Where it all lives
[Section titled “Where it all lives”](#where-it-all-lives)
Commands and skills are looked up in the project and globally, in `.waibee/` and in the compatible `.claude/`. When names collide, the project wins over the global location, and `.waibee/` wins over `.claude/`. A typed `/name` is looked up among commands first, then among skills. The agent loading a skill on its own does the opposite: it takes a skill before a command with the same name.
`/help` lists the available commands. `/reload` picks up a new or changed file: it rereads commands, skills, subagents, hooks, and MCP servers without a restart. You can also install skills and commands as a whole set. See [Plugins](/code/plugins/).
You do not have to create the file by hand: on the extensions page in the [browser](/code/web/), you can create a skill, command, or subagent through a form. By default the file goes into the folder of the session you are working with, but you can choose your home folder instead, which makes it available in every project. The same page lets you turn off a skill without deleting its file, and delete commands and subagents.
You do not have to write everything from scratch: skills already exist for common tasks. Catalogs and ways to install them are in [Finding extensions](/code/ecosystem/), and ready-made sets are in [Recommended extensions](/code/toolkit/).
# Recommended extensions
> What people install most: a starter set plus picks for development, interfaces, writing, media, and task tracking.
Below are extensions people install on top of the agent, grouped by the kind of work. Within each table, the order runs from most useful to supplementary. We did not build any of them: listing one is not a Waibee recommendation or a guarantee of quality. Before installing, run through a [quick check of the source](/code/ecosystem/#before-you-install).
These are examples, not a ready-made set. A working set depends on your stack (React and Postgres need different things than Go and Kafka), on where your tasks and designs live, and on your habits. Pick one or two extensions for your task and find the rest in the catalogs. See [Finding extensions](/code/ecosystem/).
Instructions “for Claude Code” in these repositories also work for Waibee Code: `npx skills add ...` puts files in `.claude/skills/`, and plugin marketplaces are added with `waibee plugin marketplace add`. Installing from Anthropic’s official marketplace (`...@claude-plugins-official`) does not work yet. See [Plugins](/code/ecosystem/#plugins).
## How to choose
[Section titled “How to choose”](#how-to-choose)
The lists below are long, but you need to install only a few things from them.
* **Start with three things:** the language server for your language (built in, only the binary is needed; see [Language servers](/code/lsp/)), Context7 for up-to-date library docs, and a browser for the agent. Add the rest as tasks call for it.
* [The cost of extensions in context](/code/ecosystem/#the-cost-in-context).
* **One at a time.** Install it, work with it for a week, then keep it or remove it.
* **A rule of your own in `WAIBEE.md` often works better than someone else’s skill.**
* **Check that an extension affects the result.** If nothing changed after you removed it, you do not need it.
## Starter set
[Section titled “Starter set”](#starter-set)
Useful in almost any work.
| Extension | What it gives you |
| ------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Context7](https://context7.com/) (MCP) | Up-to-date library docs in context. It covers the model’s main weakness: its knowledge of API versions goes stale |
| [Playwright MCP](https://github.com/microsoft/playwright-mcp) | A browser for the agent: open a page, click, fill in a form, take a screenshot, read the console and network requests. Official, from Microsoft |
| [anthropics/skills](https://github.com/anthropics/skills) | Anthropic’s official skills: working with `pdf`, `docx`, `xlsx`, `pptx`, creating your own skills (`skill-creator`) and MCP servers (`mcp-builder`), testing web apps |
| [superpowers](https://github.com/obra/superpowers) | Process skills: working through a task before code, TDD, systematic debugging, verification before declaring work done |
| [find-skills](https://github.com/vercel-labs/skills) | The agent searches the catalog for a skill that fits the task and offers to install it. The most installed skill on skills.sh |
| [agent-browser](https://github.com/vercel-labs/agent-browser) | A browser for the agent as a command-line tool: the agent calls it through `Bash`, and no server sits in context. It also has an MCP server mode |
| Tools instead of servers: `gh`, `aws`, `kubectl`, `psql` | Many tasks get done without MCP and without a standing cost in context. See [CLI or MCP](/code/best-practices/#cli-or-mcp) |
```bash
npx skills add anthropics/skills -l # see what is inside
npx skills add anthropics/skills -s xlsx # install the one you need
npx skills add vercel-labs/skills -s find-skills
waibee plugin marketplace add obra/superpowers-marketplace
waibee plugin install superpowers@superpowers-marketplace
```
An example of adding MCP servers in `settings.json`; the full syntax is in [MCP](/code/mcp/):
settings.json
```json
{
"mcp": {
"servers": {
"context7": {
"type": "http",
"url": "https://mcp.context7.com/mcp",
"headers": { "Authorization": "Bearer ${CONTEXT7_API_KEY}" }
},
"playwright": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@playwright/mcp@latest"]
}
}
}
}
```
## Development
[Section titled “Development”](#development)
| Extension | What it gives you |
| ------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| [mattpocock/skills](https://github.com/mattpocock/skills) | A set built around discipline: an interview before code (`grill-me`, `grill-with-docs`), TDD, bug triage, review along two axes, architecture work |
| [Sentry MCP](https://github.com/getsentry/sentry-mcp) | Production errors and traces right in the session: work through an incident without gathering data by hand. Official, from Sentry |
| [GitHub MCP](https://github.com/github/github-mcp-server) | Issues, PRs, reviews, and Actions. Official. If `gh` is enough, start with it: it costs less context |
| [CodeGraph](https://github.com/colbymchenry/codegraph) (MCP) | A prebuilt graph of symbols and calls. The agent gets the code it needs in one request instead of a dozen searches |
| [ponytail](https://github.com/DietrichGebert/ponytail) | Pushes back on overengineering: first check whether the thing is needed at all and whether something ready already exists nearby. Plus a review of the diff for anything extra |
| Database MCP: [Postgres](https://github.com/crystaldba/postgres-mcp), [Supabase](https://github.com/supabase-community/supabase-mcp) | The schema, query plans, and analysis of slow spots without pasting dumps into the chat. Grant read-only access |
| [Grafana MCP](https://github.com/grafana/mcp-grafana) | Dashboards, metrics, and logs in context while working through an incident. Official |
| [DeepWiki](https://deepwiki.com/) (MCP) | Questions about someone else’s public repository without cloning it: how it is built, where things live |
| Autoresearch skills | An autonomous loop of experiments against a metric. See [Autoresearch](/code/autoresearch/) |
Sentry connects over OAuth, so the config needs no token:
settings.json
```json
{
"mcp": {
"servers": {
"sentry": { "type": "http", "url": "https://mcp.sentry.dev/mcp" }
}
}
}
```
```bash
waibee mcp login sentry
npx skills add mattpocock/skills
# or as a plugin:
waibee plugin marketplace add mattpocock/skills
waibee plugin install mattpocock-skills@mattpocock
```
After installation, mattpocock/skills asks you to run `/setup-matt-pocock-skills` in the agent once.
Before installing anything for code navigation, check `/lsp`: if the language server binary is installed, the agent already jumps to definitions and finds usages without external tools. See [Language servers](/code/lsp/).
## Frontend and interfaces
[Section titled “Frontend and interfaces”](#frontend-and-interfaces)
By default the model drifts toward an averaged look: the same fonts, gradients, cards inside cards. The extensions below set boundaries and give you a way to check the result.
| Extension | What it gives you |
| -------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Figma MCP](https://help.figma.com/hc/en-us/articles/32132100833559-Guide-to-the-Figma-MCP-server) | The design file as the source of truth: variables, components, layout, code generation from a selected frame, integration with Code Connect. Official |
| [Playwright MCP](https://github.com/microsoft/playwright-mcp) | A visual check: the agent opens the result, takes a screenshot, and compares it with the design on its own |
| [impeccable](https://github.com/pbakaus/impeccable) | Commands for each stage of the work: `critique`, `typeset`, `colorize`, `animate`, `audit` (accessibility, performance, responsiveness). The `npx impeccable detect` tool finds common layout flaws without the agent |
| [hallmark](https://github.com/Nutlope/hallmark) | Generates and reworks interfaces with checks against the telltale signs of AI-made layouts |
| [vercel-labs/agent-skills](https://github.com/vercel-labs/agent-skills) | Rules for a specific stack: `react-best-practices`, `web-design-guidelines`, `react-view-transitions`, deploying and optimizing on Vercel |
| [ui-skills](https://github.com/ibelick/ui-skills) | Skills for design engineers, picked by category with `npx ui-skills` |
| Anthropic skills: `frontend-design`, `theme-factory`, `brand-guidelines` | Styling and themes for interfaces and artifacts, from [anthropics/skills](https://github.com/anthropics/skills) |
| [Chrome DevTools MCP](https://github.com/ChromeDevTools/chrome-devtools-mcp) | Page performance measurements, network, console: useful when the question is “why is it slow” rather than “how does it look” |
| The `webapp-testing` skill from [anthropics/skills](https://github.com/anthropics/skills) | Runs scenarios against a local app through Playwright, with screenshots and browser logs |
| [ego-lite](https://github.com/citrolabs/ego-lite) | A browser where the agent works in its own Spaces, separate from your tabs. It can still reach your logins and tabs through `ego-browser` |
| [namethatui.com](https://namethatui.com/) | A reference of interface element names: describe an element in your own words and get its name plus wording you can paste into a prompt |
```bash
npx skills add nutlope/hallmark
npx skills add citrolabs/ego-lite
npx impeccable install # then in the agent: /impeccable init
```
With Figma, the plan and client restrictions matter. The remote server (`https://mcp.figma.com/mcp`) is available on all plans, but only to clients in the [Figma catalog](https://www.figma.com/mcp-catalog/); Waibee Code is not listed there. The call limit depends on the seat type: View and Collab seats get a much lower limit than Dev and Full. The limit applies only to tools that read Figma data; the numbers are in the [rate limits table](https://developers.figma.com/docs/figma-mcp-server/rate-limits-access/). The local server through the desktop app works with a Dev or Full seat on a paid plan. The third-party [Framelink](https://github.com/GLips/Figma-Context-MCP) works with a personal Figma API token and returns layout and styles, but not what depends on Dev Mode and Code Connect.
## Writing and documentation
[Section titled “Writing and documentation”](#writing-and-documentation)
| Extension | What it gives you |
| ----------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| Anthropic skills: `docx`, `pdf`, `pptx`, `xlsx`, `doc-coauthoring`, `internal-comms` | Reading and building documents and spreadsheets right in the files, co-writing a document, the format for internal announcements and emails |
| [no-ai-slop](https://github.com/petergyang/no-ai-slop) | Finds and removes the telltale phrasing of AI text and keeps the meaning |
| A skill of your own for the project’s style | Editorial rules in `SKILL.md`: banned phrases, agreed terms, before-and-after examples |
| The `writing-guidelines` skill from [vercel-labs/agent-skills](https://github.com/vercel-labs/agent-skills) | A ready set of rules for technical writing, if you do not have your own yet |
| [Context7](https://context7.com/) (MCP) | Technical writing with current code examples instead of outdated ones |
```bash
npx skills add petergyang/no-ai-slop
npx skills add anthropics/skills -s docx -s pdf -s pptx -s xlsx
```
Keep general style principles in `WAIBEE.md`, and move long lists of phrasing into a skill: only its short description stays in context, and the agent loads the full text only when it works on writing.
## Media and presentations
[Section titled “Media and presentations”](#media-and-presentations)
| Extension | What it gives you |
| -------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Slidev](https://sli.dev/) | Presentations from Markdown. The agent writes `slides.md`, and you get slides and an export to PDF or PPTX (`pptx` produces images, `pptx-editable` produces editable elements) |
| [claude-video](https://github.com/bradautomates/claude-video) | The `/watch` command: the agent downloads a video, analyzes the frames and transcript, and answers questions about the content |
| [video-shotcraft](https://github.com/Vincentwei1021/video-shotcraft) | Product videos with Remotion: storyboard, motion, sound, a ready template |
| [OpenMontage](https://github.com/calesthio/OpenMontage) | End-to-end video production: script, footage search, editing, assembly |
| [palmier-pro](https://github.com/palmier-io/palmier-pro) | A video editor for macOS 26 on Apple Silicon with an MCP server: the agent works on the timeline together with you |
```bash
pnpm create slidev
npx skills add bradautomates/claude-video -g
npx skills add Vincentwei1021/video-shotcraft
```
A Slidev presentation is a text file in the repository, so edits show up in the diff.
## Tasks and processes
[Section titled “Tasks and processes”](#tasks-and-processes)
For people who write requirements and reports more often than code.
| Extension | What it gives you |
| ----------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| Jira and Confluence | Three options; see below |
| [Notion MCP](https://developers.notion.com/guides/mcp/get-started-with-mcp) | The official remote server `https://mcp.notion.com/mcp` with OAuth: search, read, and edit pages, create pages and databases |
| [Linear MCP](https://linear.app/docs/mcp) | The official remote server `https://mcp.linear.app/mcp` with OAuth |
| Anthropic skills `xlsx`, `pptx`, `docx` plus [Postgres MCP](https://github.com/crystaldba/postgres-mcp) with read-only access | Export data, run the numbers and put them in a table, build a report or document from a template |
| [mattpocock/skills](https://github.com/mattpocock/skills) | Framing the work: an interview, a spec from the conversation, a breakdown into linked tasks with dependencies |
| [Playwright MCP](https://github.com/microsoft/playwright-mcp) | Check a scenario in the interface yourself, without taking a developer’s time |
| [Firecrawl](https://github.com/firecrawl/firecrawl-mcp-server) or [Exa](https://github.com/exa-labs/exa-mcp-server) (MCP) | Gathering material from external sources for market and competitor analysis |
| [Slidev](https://sli.dev/) | A report or analysis as slides, from text you have already written |
| [no-ai-slop](https://github.com/petergyang/no-ai-slop) | Emails, descriptions, and documents without recognizable clichés |
More on Jira, because there are three options and they are not equivalent:
| Option | When it fits |
| --------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Official Atlassian remote server](https://support.atlassian.com/rovo/docs/getting-started-with-the-atlassian-remote-mcp-server/) | Atlassian Cloud. Sign-in over OAuth (`waibee mcp login`), with the same permissions as your account, and no separate token to store |
| [sooperset/mcp-atlassian](https://github.com/sooperset/mcp-atlassian) | Third-party. Works with Cloud as well as with Server and Data Center, where the official server is unavailable. Runs through `uvx`, with authorization by API token or personal access token |
| [jira-cli](https://github.com/ankitpokhrel/jira-cli) | When you need speed and no standing cost in context: `jira issue view WAIB-1`, `jira issue list -a$(jira me)`, `jira issue create`. Works with both Cloud and Server |
The first option is the simplest and is usually enough. If you host Jira yourself, take the second or the third. The third takes no context until the agent uses it. See [CLI or MCP](/code/best-practices/#cli-or-mcp).
A working combination: the interview and the spec in one session, implementation in another, and review in a third. See [The developer’s role](/code/validation/).
# The developer's role
> What changes when the agent writes the code: framing the task through an interview, a shared project vocabulary, checking the result.
When the agent writes the code, less of your time goes into typing it and more into three things: framing the task precisely, choosing the right tool, and checking the result.
To choose, you need to know what exists: which [approaches](/code/workflows/) there are, which [skills and MCP servers](/code/ecosystem/) solve your problem, and where the agent is weak. Otherwise all you can do is accept whatever it proposes.
Checking matters because the agent delivers a correct result and a wrong one with the same confidence.
## What you do
[Section titled “What you do”](#what-you-do)
| Stage | Your part |
| ---------------- | ------------------------------------------------------------------------------ |
| Before you start | The scope of the task: what is in, what is out, what the constraints are |
| Framing | How to check the result: a test, a build, a metric, a reference |
| Along the way | Correcting course early, before the context fills up with failed attempts |
| At the end | Checking against the task, not the diff: is what you asked for actually solved |
## Interview before code
[Section titled “Interview before code”](#interview-before-code)
On a task larger than one file, start with a conversation: let the agent ask questions until no open choices remain.
```text
I want [short description]. Interview me with the AskUserQuestion tool: implementation, interface,
edge cases, tradeoffs. Skip the obvious and dig into the hard parts.
When we have covered everything, write the spec to SPEC.md.
```
What separates a good interview from a bad one is the questions. If the agent asks about things already visible in the code, the interview is empty. The valuable questions are the ones you do not have an answer to yet: what to do on a repeated request, who owns the data, which requirement wins in a conflict.
The outcome should be a spec that names the files and interfaces, lists explicitly what is out of scope, and ends with a verification step. It is best carried out in a new session with a clean context.
Ready-made skills for this kind of interview: `grill-me` from mattpocock/skills and `brainstorming` from superpowers. See [Recommended extensions](/code/toolkit/#development).
## A shared project vocabulary
[Section titled “A shared project vocabulary”](#a-shared-project-vocabulary)
Terminology is the second source of mismatches. If an entity has three different names, one in your head, one in the task, and one in the code, the agent will keep asking or guessing.
Write down the domain vocabulary where the agent will read it: in `WAIBEE.md` or in a separate file included with `@path`. You gain twice: explanations get shorter, which makes them cheaper in context, and names in the code stop drifting apart. Keep decisions you have made, with their reasons, next to it so the agent does not reinvent them.
## What to check in the result
[Section titled “What to check in the result”](#what-to-check-in-the-result)
| What you check | Typical agent mistake |
| --------------------- | ----------------------------------------------------------------------------- |
| Is it the right task | A related task was done instead; the spec was skimmed |
| Edge cases | Empty input, a timeout, a retry, concurrent access |
| Trust boundaries | No input validation; permissions checked at the wrong layer |
| Cause, not symptom | An exception swallowed; a retry layered over the bug |
| Reuse | A new helper written where a ready one sits next to it |
| Tests | The test is fitted to the implementation: it checks calls instead of behavior |
| Scope | Neighboring files rewritten along the way, without being asked |
| Unneeded abstractions | An interface with one implementation, a config for a constant |
| Evidence | ”Done” claimed without test or command output |
The last item is the cheapest to apply. Ask for output rather than a report: what was run and what came back. Reading output is faster than rechecking everything yourself.
## A second pair of eyes
[Section titled “A second pair of eyes”](#a-second-pair-of-eyes)
The agent that wrote the code is a poor reviewer: it defends its own solution. Hand the review to a subagent or a second session whose context holds only the diff and the criteria. Ready-made wording is in [Example prompts](/code/prompts/#review).
One caveat: a reviewer asked to find problems always finds them, even in sound work. If you chase every comment, you get the opposite of what you want: extra layers, defensive code, and tests for impossible cases. State plainly what counts as a finding, and mark everything else as optional.
## What automation will not catch
[Section titled “What automation will not catch”](#what-automation-will-not-catch)
Tests and metrics check what is written into them. These slip past:
* The task is solved neatly, but it is the wrong task.
* The solution is correct, but it does not fit where the project is heading.
* The metric improved through something the metric does not cover. See [Autoresearch](/code/autoresearch/).
* The cost of maintenance: the code works, but in six months nobody will be able to make sense of it.
# The .waibee directory
> What Waibee Code stores and where: WAIBEE.md, settings.json, skills, commands, subagents, and memory.
Project settings live in `.waibee/` or the compatible `.claude/`. Global settings and session data are stored separately, in your user data directory. The load order is described in [Configuration files](/code/configuration/).
## In the project
[Section titled “In the project”](#in-the-project)
| Path | Purpose | When it is used | Where it belongs |
| ----------------------------- | ---------------------------------------------------- | ----------------------------- | ------------------------------------- |
| `WAIBEE.md` | Project instructions | At the start of every session | Committed |
| `WAIBEE.local.md` | Personal instructions on top of the project ones | At the start of a session | Local, usually in `.gitignore` |
| `.waibeeignore` | Paths excluded from reading and search | On reads and searches | Committed |
| `.waibee/settings.json` | Permissions, MCP, hooks, compaction | Always | Committed |
| `.waibee/settings.local.json` | Personal settings | Always | Local, usually in `.gitignore` |
| `.waibee/skills/` | Skills (`SKILL.md`): domain knowledge and procedures | When needed | Committed |
| `.waibee/commands/` | Custom slash commands | When you call `/name` | Committed |
| `.waibee/agents/` | Subagent definitions | When called through `Agent` | Committed |
| `.waibee/memory/MEMORY.md` | Project memory | At the start of a session | Review the contents before committing |
Project memory lives in the root of the git repository, even if the agent was started in a subfolder.
## Global
[Section titled “Global”](#global)
The default data directory is `~/.waibee` on macOS and Linux and `%APPDATA%\waibee` on Windows. The `WAIBEE_DATA_DIR` variable sets a different **absolute** path. A relative path is not accepted: the agent exits with an error before the session starts.
| Path inside the data directory | What it holds |
| --------------------------------- | --------------------------------------------------------------------------------------- |
| `settings.json` | Settings for all projects |
| `WAIBEE.md` | Instructions for all projects |
| `skills/`, `commands/`, `agents/` | Your skills, commands, and subagents for all projects |
| `plugins/` | Installed plugins |
| `memory/USER.md` | Memory about you |
| `sessions/` | Saved conversations |
| `history` | Everything you typed: `↑` and `Ctrl+R` read from it |
| `worktrees/` | The agent’s working copies |
| `storage/tool_outputs/` | Full results of large tool calls |
| `logs/`, `audit/`, `crashes/` | Diagnostics, the action log, and crash reports |
| `cache/` | Cache, such as the model catalog |
| `state/` | Internal state: locks for open sessions and the [`waibee serve`](/code/web/) link token |
| `detached/` | Replies from background subagents that the session has not collected yet |
The API key is stored in the system keychain. If the keychain is unavailable, it goes to `secrets.json` in the data directory. Do not commit this file, the input history, or sessions.
### Disk space
[Section titled “Disk space”](#disk-space)
```bash
waibee storage status
waibee storage clean sessions --older-than 30d --dry-run
```
The first command shows disk usage (`--json` for scripts). The second only lists the sessions it would delete. Check the list and drop `--dry-run` if they can go. `--yes` skips the confirmation.
| `waibee storage clean …` | What it deletes | Default `--older-than` |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------- |
| `sessions` | Saved conversations | `30d` |
| `audit` | Audit log | `90d` |
| `crashes` | Crash reports | `30d` |
| `logs` | Program logs | `14d` |
| `tool-outputs` | Saved tool results | `7d` |
| `cache` | The whole cache: it gets rebuilt | none |
| `all` | Everything above: the audit log and cache by the retention periods in the [settings](/code/settings/#log-and-storage), the rest by the periods in this table | none |
`storage.auto_cleanup` turns on cleanup at startup, with the `clean all` retention periods; it is off by default. Stale locks and tool results older than seven days are cleaned up regardless of this key. Worktrees are counted separately in the stats: cleaning up sessions does not delete working copies.
## Claude Code compatibility
[Section titled “Claude Code compatibility”](#claude-code-compatibility)
Waibee Code also reads all of this from `.claude/`: `CLAUDE.md`, `.claude/settings.json`, and Claude Code skills, commands, and subagents are picked up unchanged. More in [Claude Code compatibility](/code/claude-code/).
The exact rules for settings layers, the order of instruction files, and how memory works are in [Configuration files](/code/configuration/).
# Local web interface
> Waibee Code in the browser: chats, files, diffs, and a terminal. Run it locally with waibee serve or /web, and reach it from your phone.
In the browser, Waibee Code gives you chats, a file and diff viewer, and a terminal for running commands. The agent and the web server run on your computer, and models are called through [Waibee Router](/router/).
By default, the page opens only on this computer. To use it from a phone or another device, turn on [network access](#from-a-phone-or-tablet) separately.
## Starting the server
[Section titled “Starting the server”](#starting-the-server)
From the shell, start the server with `waibee serve`. It creates new sessions and opens saved ones from disk.
```bash
waibee serve
```
The command prints a link with a token. Open it to see your list of sessions. Closing the browser does not stop a session: the work goes on in the `waibee serve` process.
| Flag | What it does |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `--port ` | Port instead of 8787 |
| `--host 0.0.0.0` | Listen on the whole network from the start. Usually unnecessary: a button in the interface does the same |
| `--read-only` | Read-only: every write is rejected, including the browser terminal |
| `--new-token` | Issue a new link: the old one stops working |
| `--model ` | Model for new sessions: an alias (`sonnet`) or a full ID. A saved session opens on its own model; change it with the model picker in that conversation |
A separately started `waibee serve` does not see chats already open in the terminal. To work on them from the browser, type `/web` in the TUI: it starts a server on the current sessions and prints a link. If port 8787 is taken, `/web` picks a free one.
[](/media/code/web-overview.png)
A demo project: the agent added search by title and checked it with tests. Click the screenshot to open it full size.
The sessions in the browser are the same as in the terminal. The browser adds what a text screen lacks: a diff with comments on selected lines, a file tree next to the conversation, diagrams and tables in a side panel, and sign-in from a phone by link or QR code.
## What’s inside
[Section titled “What’s inside”](#whats-inside)
* **Session list.** Running sessions and recent saved ones, with their folder and time, most recently active first. Search looks for words in your messages and the agent’s replies across every session on disk, so it finds older ones too. Star the sessions you need and delete the ones you don’t.
* **Session folder.** Choosing a folder moves an empty chat. If the conversation has already started, the folder opens in a new session and the earlier history stays where it was.
* **Conversation.** A resumed session keeps its history, tool call durations, and compaction marks. The agent’s reply streams in as it is generated. Tool calls appear as cards: file edits show a colored diff, commands show their output, and long output has an expand button. Permission requests come to the page, and you can answer them there with the same four answers as in the terminal, including a refusal with an explanation; see [Approvals](/code/permissions/#approvals). A card does not steal your typing: while the input field has text, focus stays there. The keys for cards and questions are under [Keys](#keys). Below the input field you can see how full the context window is, and the **Summarise now** button requests compaction, like `/compact`; a short history stays as it is.
* **While the agent works.** A new message joins a queue above the input field and goes to the agent at its next step. The “Send now” button stops the model’s current reply and sends the queued text right away: what was already written stays in the conversation, and long-running commands keep going in the background. Commands and messages with images wait for the next turn and keep their order. Closing a session stops it without sending the queue. For what in the queue survives a `waibee serve` restart, see [Recovery after a restart](/code/features/#recovery-after-a-restart).
* **Commands.** Of the built-in commands, the browser supports `/model` and `/effort` (they open the model and reasoning level pickers), `/compact`, `/bug`, `/again`, `/memory add`, and `/reload`, plus your own commands and skills. The other built-in commands are terminal-only; see the [Commands reference](/code/commands/).
* **Model and effort.** The model sheet has a slider from Faster to Smarter, like `/effort` in the terminal. A choice there is saved for the model. See [Reasoning level](/code/models/#reasoning-level-effort).
* **Go back to a message.** The fork button on a message branches the conversation before that message, like `/rewind`. The fork opens with the message in the input to edit. Files are not rolled back, and the old conversation stays in the session list; see [Session history](/code/features/#session-history).
* **Data protection.** Under a message, the chat shows whether your organisation’s DLP policy sent data as written, masked it, or blocked it, with the kinds of data and counts. The values are also marked in the message text, with the policy’s reaction in a tooltip. The exact notices are in [Data protection](/code/features/#data-protection).
* **Stopped replies.** If the provider’s filter stops a reply before anything was shown, Waibee Code retries once. Otherwise, the text shown so far stays and tool calls in that reply do not run. The note says “The provider’s filter stopped this reply.” and offers **Try again** and **Switch model**. A `/goal` does not continue after it.
* **Changed files.** After a turn that changed files with `Edit` or `Write`, their names appear under the turn’s receipt and open the file when clicked. The list shows the first five names and a count of the rest. Changes made by shell commands are not listed.
* **Returned messages.** If sending fails, the text and images come back to the input field. If you cancel a command that has not been answered yet, the `/name arguments` line you typed comes back.
* **Attachments.** You can attach text files and images up to 20 MiB, if the model accepts them. For text larger than 256 KiB, only the beginning is attached, with a truncation mark. Unsupported files and files that could not be read are skipped with a notice.
* **Goal.** The target button next to the input field pins a condition the agent works toward on its own, shows the pinned condition, and removes it. If a condition fits the work at hand, the agent proposes one itself, and you accept it with one click. See [Goal mode](/code/goal/) for details.
* **Files and terminal.** The project tree, a file viewer and editor, and a shell in the session folder. Open tabs keep working while another tab is in front: the terminal stays alive and edits are not lost.
* **Agent panel.** The column on the right: pages the agent writes itself (plans, tables, diagrams) and running subagents with their progress. Open a subagent to read its conversation and send it a follow-up. Continued work is marked as addressed to the same agent, and you can continue a finished subagent even after `waibee serve` restarts. An empty column collapses.
* **Extensions.** Everything this folder picked up: MCP servers, plugins, skills, commands, agent definitions, hooks, and instruction files. You can turn MCP servers, plugins, skills, and hooks on and off in place. You can also create a skill, command, or agent here, and an MCP server gets a connection check before it is saved; see [MCP](/code/mcp/#adding-a-server-from-the-agent).
* **Security.** The sandbox profile, the folders the agent can write to, allowed and blocked domains, and protected paths. You can change the profile and the domain lists here, and the change is global, for the whole machine. Below is a log of what was refused and what failed, with a time window, a text search, and a “refused or failed / everything” toggle.
* **Other pages.** Settings and themes, interface language, agent memory, the API key, diagnostics (`waibee doctor` as a page), background tasks with the option to stop any of them, and a list of what is new in the latest version.
The Context section of the Settings page offers `context.compact_at`, `context.idle_compact`, and `context.prompt_cache`. They are also in `/settings` and `waibee config`. See [Context settings](/code/settings/#context-and-memory) for the allowed values, and [Context window](/code/context-window/) for compaction while idle and cache duration.
## Reviewing changes
[Section titled “Reviewing changes”](#reviewing-changes)
Open the **Review** tab and pick a file. Changed files are listed with line counts; removed lines are marked red and added lines green. To ask the agent to rework a fragment, select lines in the line number column and send a comment: it goes to the agent together with a reference to those lines. You can revert unwanted changes for a whole file or for a single diff hunk.
## From a phone or tablet
[Section titled “From a phone or tablet”](#from-a-phone-or-tablet)
By default, the server answers only on this machine. The page runs commands in your name, so network access is a separate switch.
The agent keeps working while you are away from your desk. From your phone you can see what it is doing, answer a permission request, or steer it in the right direction. This is useful when:
* **You stepped away from the computer.** The agent runs on your work machine, the phone is on the same Wi-Fi network, and you don’t need a tunnel.
* **The agent lives on a machine that never sleeps.** A home server, a Mac mini, or a Raspberry Pi on a 64-bit OS: `aarch64` builds exist for both Linux and macOS.
* **Your laptop stayed at home.** A long task keeps running where you started it, and you follow it on the go through a tunnel. The machine must not go to sleep: a closed laptop does not continue the work.
**Same Wi-Fi network.** Click **Open on your phone**, then **Open on this network**. The server starts answering on its network address too, and a QR code appears on the page: point your phone’s camera at it. Nothing needs a restart. If the machine has several addresses, pick the right one in the list under the code: on a laptop with a VPN, the top address is not always the one the phone can see.
**Another network.** You need a tunnel program: it connects from inside the machine to the outside and gives you an address that opens from anywhere. The **Open a public address** button (**Open an address for your own devices** for Tailscale) uses the first installed program from the table that manages to open an address. You can pick a different one next to the button.
| Program | Install (macOS) | Who can open the link | Replies |
| ------------- | ---------------------------------------------------------- | ----------------------------------------------- | -------------------- |
| `tailscale` | `brew install tailscale && sudo tailscale up` | only your own devices signed in to your tailnet | streamed |
| `ngrok` | `brew install ngrok && ngrok config add-authtoken ` | anyone with the link | streamed |
| `cloudflared` | `brew install cloudflared` | anyone with the link | polled, with a delay |
`cloudflared` needs no account, but it does not pass the event stream through, so the agent’s replies arrive with a delay. On ngrok’s free plan, the first visit shows an ngrok page: click **Visit Site** on it once.
If none of the programs is installed, the page shows the install command for your system (`winget` on Windows) and a link to the program’s site. Installed one without closing the page? Click **Check again**: no restart needed. Close the public address with its button; it does not survive a server stop.
**As an app.** You can install the page on your phone from the browser menu (“Add to Home Screen”): it opens without the address bar and keeps the session.
**Watch only.** The link comes in a second variant that shows the conversation but rejects every write, including sending messages and using the terminal. Use it to show your work to a colleague without handing over control. The “can act / watch only” toggle is above the QR code. A page opened with this link says that access is view-only and does not offer actions that would be rejected anyway.
## Access and security
[Section titled “Access and security”](#access-and-security)
* **Token.** It is in the link the first time you open it. After that it lives in a cookie and does not stay in the address bar. Without the token the page does not open. After several wrong attempts, the address is temporarily blocked.
* **Who is connected.** The same window shows the addresses of recent connections and their permissions. Through a tunnel, you see the tunnel program’s address, not each device’s.
* **The same permissions, visible and changeable.** The browser gives the agent nothing beyond what the terminal does: the same approval mode and the same sandbox apply. But the mode and the sandbox profile can be switched from the page, so anyone who opened the full link can loosen both approvals and the sandbox.
* **One link for everyone.** You cannot revoke access for a single device. Stopping the server does not cancel the link: the token is stored in `~/.waibee/state/serve.token` (`%APPDATA%\waibee\state\serve.token` on Windows) and survives restarts. If the link ended up in the wrong hands, restart with `--new-token`: a new link is issued and the old one stops opening the page. The watch-only link changes along with it.
* **Public address.** While it is open, anyone with the link can open the page (except with Tailscale). Close it when you are done.
## Keys
[Section titled “Keys”](#keys)
On Windows and Linux, press shortcuts that use `Cmd` with `Ctrl` instead; on macOS both work. Letter keys also work in the Russian keyboard layout.
| Keys | Action |
| ----------------------------------------- | --------------------------------------------------------------------------------------------------------- |
| `Cmd+K` | Palette: sessions, commands, settings, and search through past messages |
| `Cmd+P` | Open a project file by name |
| `Cmd+S` | Save the file in the editor |
| `Cmd+/` | Keyboard shortcuts |
| `Cmd+1` … `Cmd+9` | Open a session by its position in the list |
| `g`, then `h`, `e`, `m`, `s`, `k`, or `,` | Home, extensions, memory, security, API key, or settings. Does not work while focus is in the input field |
Input field:
| Keys | Action |
| ----------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Enter` | Send |
| `Shift+Enter` | New line |
| `/`, `@` | Command and file suggestions; `Tab` or `Enter` inserts the selected one, `↑` `↓` move through the list |
| `↑` in an empty field | Bring the last queued message back into the field; with no queue, scroll through earlier prompts |
| `↑` on the first line while a permission request is waiting | Go to the request |
| `!` at the start of a message while the agent works | Send right away: calls that have not started yet are postponed, and the running command moves to the background and keeps going |
| `Esc` | The first that applies: close suggestions, send the answers already chosen for a question, reject a permission request, stop the turn. In a subagent’s window, stops only that subagent |
Permission request, when focus is on the card:
| Keys | Action |
| ---------- | -------------------------------------------------------------------- |
| `y` | Allow once |
| `Y` | Allow for the rest of this session |
| `p` | Allow in this project from now on |
| `n`, `Esc` | Reject this call; the turn continues |
| `Tab` | Reject with an explanation: `Enter` sends the refusal with your text |
A risky command offers only `y` and `n`. Right after a card appears, the answer keys other than `Esc` do nothing for a moment, so a stray keypress does not answer for you.
Agent question:
| Keys | Action |
| ------------------ | ------------------------------------------------------------------------ |
| `1` … `9` | Choose an option; the number after the last option opens a custom answer |
| `↑` `↓` | Move through the options |
| Space | Check an option, if multiple choice is allowed |
| `Enter` | Choose the option under the cursor and move on |
| `Tab`, `Shift+Tab` | Next or previous question |
| `Esc` | Send what has been chosen so far; the turn continues |
Files and changes:
| Keys | Action |
| ------------------------ | ------------------------------------------------------------- |
| `F2` | Rename a file or folder in the tree, or a session in the list |
| `Delete`, `Backspace` | Delete a file or folder in the tree, after confirmation |
| `↑` `↓` in a diff | Move between lines; with `Shift`, extend the selection |
| Space, `Enter` in a diff | Select a line to comment on |
## Next steps
[Section titled “Next steps”](#next-steps)
* [Features](/code/features/): agent tools and the terminal interface.
* [Permissions](/code/permissions/): approval modes and the sandbox.
* [Goal mode](/code/goal/): working until a condition is met.
* [IDEs (ACP)](/code/ide/): the same agent in your editor.
# Development workflows
> Ways to work with the agent, from a short prompt to Spec-Driven Development and TDD.
There are many ways to work with the agent, from a short prompt to a strict process. The larger the task and the higher the cost of a mistake, the more structure pays off.
## Short prompt
[Section titled “Short prompt”](#short-prompt)
A small, clear change (a typo, a log line, a rename) only needs a description in plain words. It is fast, but the result is hard to reproduce, so do not rely on it for a large task.
## Explore, plan, implement
[Section titled “Explore, plan, implement”](#explore-plan-implement)
For unfamiliar or large code, the agent first studies it and proposes a plan, you review the plan, and only then do the edits begin. This lowers the risk that the agent solves the wrong problem. See [Best practices](/code/best-practices/).
## Spec-Driven Development (SDD)
[Section titled “Spec-Driven Development (SDD)”](#spec-driven-development-sdd)
For large or high-stakes work, a spec in a file is the source of truth. The conversation from one session does not carry into the next, but the file stays.
A spec covers the intent (why the work is needed), the scope (what is in and what is out), the acceptance criteria (when the work counts as done), the edge cases, and the conventions the project follows.
The workflow:
1. Let the agent interview you (the `AskUserQuestion` tool) and save the result to `SPEC.md`. See [Interview before code](/code/validation/#interview-before-code).
2. Do the task in a new session, so the agent works from the spec instead of fragments of a conversation.
3. Hold the agent to the acceptance criteria with [`/goal`](/code/goal/) so it does not stop early.
4. Check the result against the spec, not only the diff: did it solve the right problem, and did it handle the edge cases?
The approach pays off on changes that span many files or services, on recurring tasks, and wherever you need an audit trail. For a small fix or a prototype it is overkill. Start with one task rather than moving the whole project onto the process at once.
You do not have to set up the process by hand: open toolkits define it as agent commands. For example, [GitHub Spec Kit](https://github.com/github/spec-kit) takes you from requirements to implementation with `/speckit-specify`, `/speckit-plan`, `/speckit-tasks`, and `/speckit-implement`, and it supports several agents. For Claude Code it installs skills into `.claude/skills/`, and Waibee Code reads them as regular [skills](/code/skills/).
## Test-Driven Development (TDD)
[Section titled “Test-Driven Development (TDD)”](#test-driven-development-tdd)
First comes a failing test that pins down the behavior you want, and then the agent makes it pass. The test is the acceptance criterion: “make this test pass without breaking the others.” TDD pairs well with a spec whose acceptance criteria include the tests.
## Author and reviewer
[Section titled “Author and reviewer”](#author-and-reviewer)
One agent writes the code, and another reviews it in a clean context and sends back comments. Keep the reviewer in a second chat or hand the review to a subagent. Why this works, and how not to drown in comments, is covered in [A second pair of eyes](/code/validation/#a-second-pair-of-eyes).
## Autonomous run with a check
[Section titled “Autonomous run with a check”](#autonomous-run-with-a-check)
If you have a reliable check (tests, a build, a linter), make it the condition with `/goal`, let the agent work until the check passes, and then review the outcome yourself. In a script or CI, `waibee run --goal "definition of done" "task"` does the same. See [Headless mode](/code/headless/). The longer the agent works without you, the more an independent check matters before you call the task done.
## Autoresearch
[Section titled “Autoresearch”](#autoresearch)
A special case of the autonomous run: the check returns a number instead of pass or fail. The agent then runs the loop on its own: hypothesis, edit, measurement, keep or revert. It suits speed, size, accuracy, and anything else a script can measure. The loop rules and how to protect the metric are in [Autoresearch](/code/autoresearch/).
## What stays with you
[Section titled “What stays with you”](#what-stays-with-you)
Every approach above hands the writing of code to the agent, but not the responsibility for the result. Framing the task, choosing the approach, and checking the result stay with you. See [The developer’s role](/code/validation/).
# Glossary
> Terms used in the Waibee docs: tokens, context window, prompt caching, effort, tool calling, ACP, MCP.
Terms that come up across the documentation. Each links to the page that covers it in detail.
## Platform
[Section titled “Platform”](#platform)
**Waibee Router** is a gateway to language models. Requests in OpenAI or Anthropic format go to one address, and one key opens every model in the catalog. See the [Router overview](/router/).
**Waibee Code** is our coding agent. It runs in the terminal and in a [local web interface](/code/web/), connects to IDEs, and runs from scripts. It reads and edits files and runs commands. It is written in Rust and gets its models through the router. See the [Code overview](/code/).
**Provider** is the company that trained and serves a model: Anthropic, OpenAI, Google, and others. The provider comes first in a model ID: `anthropic/claude-sonnet-4.6`.
**Catalog** is the list of models available to your key, with each model’s context window, prices, and capabilities. `GET /v1/models` returns it, and it changes over time, so take model IDs from it rather than hardcoding them for good. See [Models](/router/models/).
## Tokens and context
[Section titled “Tokens and context”](#tokens-and-context)
**Token** is the unit a model measures text in: anywhere from a single character to a whole word. How text splits into tokens depends on the model, and Russian text usually takes more tokens than English text of the same length. Prices and limits are counted in tokens, not characters. See [Tokens and usage](/router/usage/).
**Context window** (`context_length` in the catalog) is the most tokens a model accepts in one request. Everything counts toward it: the system instruction, the whole conversation history, tool definitions, and attached files. By default, a request that does not fit is rejected with `400` and the code `provider_context_length_exceeded`. On Responses, `truncation: "auto"` allows truncation if the model supports it.
**Output limit** (`max_completion_tokens` in the catalog, the `max_tokens` field in a request) is the most tokens in one response. When a model hits it, the response stops mid-sentence and `finish_reason` comes back as `length`. Structured outputs show it most: the JSON is left unclosed.
**Usage** is the block of counters in a response: how many tokens went to input, how many to output, and how many were read from the cache. It is what the cost of a request is calculated from, and it shows whether caching works.
**Compaction** shrinks the conversation history when the context window fills up: older turns are replaced with a summary, and recent messages stay. The agent does it on its own; to run it by hand, use `/compact`. See [Context window](/code/context-window/).
## Models
[Section titled “Models”](#models)
**Model ID** has the form `/`, for example `anthropic/claude-sonnet-4.6`. A name without the provider is accepted by `/v1/messages`, because that is how the Anthropic SDKs name models, and by `/v1/systemone`, where the TypeSafe SDK names them that way. See [ID format](/router/models/#id-format).
**Model family** is one provider’s lineup, with tiers inside it: a flagship for hard tasks, a mid-size model for everyday work, and a fast one for mechanical work. Choosing a tier is more practical than choosing a specific version: versions change often. See [Choosing a model](/code/models/).
**Autorouting** is the `waibee/auto` mode: you pass this ID instead of a specific model, and the router picks one that suits the request. The `model` field in the response holds the model that actually ran, so log it. See [Autorouting](/router/autorouting/).
**Reasoning model** thinks a task through before it starts answering. This reasoning does not appear in the response text, but it takes time and is billed as output. On hard logic it noticeably improves accuracy; on simple tasks it only makes the request more expensive.
**Effort** (`reasoning_effort` on Chat Completions, `output_config.effort` on Messages, `reasoning.effort` on Responses, `/effort` in the agent) is how much effort goes into reasoning. The set of levels, including `max`, depends on the model. Raise it for a specific hard task instead of keeping it high all the time. See [Reasoning](/router/reasoning/).
## Working with the API
[Section titled “Working with the API”](#working-with-the-api)
**Chat Completions** is the `POST /v1/chat/completions` endpoint in OpenAI format. It is the most common option: almost every SDK and tool is built for it.
**Messages** is the `POST /v1/messages` endpoint in Anthropic format. The Anthropic SDKs and Claude Code use it.
**Responses** is the `POST /v1/responses` endpoint in OpenAI Responses format. Codex CLI and the OpenAI Agents SDK speak it, and its response is built from items rather than messages: text, a tool call, reasoning. See [Responses API](/router/responses-api/).
**Prompt** is what you send to a model: instructions, the conversation history, and data. **System prompt** is a separate instruction about the role and rules of behavior. It comes before the conversation and usually stays the same between requests, which makes it worth caching.
**Message role** tells the model who said something: `user` is the person, `assistant` is the model itself, `system` is an instruction, `tool` is the result of a tool call. The router keeps no history: every request is sent in full, with all the previous messages.
**Streaming** delivers a response in parts as it is generated, over Server-Sent Events. Use it where a person waits for the answer on screen: the first words appear right away instead of after the whole text is generated. Token counters arrive at the end of the stream. See [Streaming](/router/streaming/).
**Tool calling** (function calling) is how you give a model access to your code. You describe functions, the model returns its intent to call one of them with arguments, you run it, and you send the result in the next request. The model itself runs nothing and never reaches into your system. The exception is web search, which the router runs. See [Tool calling](/router/tool-calling/).
**Structured outputs** is a response that follows a JSON Schema instead of free text. It saves you from parsing text with regular expressions, but it guarantees only the shape: the model fills in required fields even where there is no data, so checks on meaning stay on your side. See [Structured outputs](/router/structured-outputs/).
**Prompt caching** reuses the unchanged beginning of a request. Repeat requests with the same beginning read it from the cache, cheaper and faster. It works only when the prefix matches exactly, so everything that changes goes after the cached block. See [Prompt caching](/router/prompt-caching/).
**`finish_reason`** tells you why the model stopped: `stop` is a finished response, `tool_calls` is a request to call a tool, and `length` means the response hit the output limit. On Messages the same field is called `stop_reason`, with the values `end_turn`, `tool_use`, and `max_tokens`. Always check it: without that, a cut-off response looks like a normal one.
**DLP** (data loss prevention) checks a request for sensitive data: secrets and personal data. It can warn, mask what it finds, or block the whole request (`403`, code `dlp_violation`). Turn it on for a request with the `plugins.dlp` field. If the API key has a policy from the group administrator, the check runs without that field too: the policy sets the minimum strictness, and the request’s config can only raise it. See [Plugins](/router/plugins/).
## Agent
[Section titled “Agent”](#agent)
**TUI** is the agent’s interactive interface in the terminal: the conversation, slash commands, suggestions, and a panel that shows progress.
**Headless** runs the agent as a single command with no interface: `waibee run "..."`. A prompt goes in and the result comes out on stdout, so you can call the agent from scripts, git hooks, CI, and other software. See [Headless mode](/code/headless/).
**Turn** is one cycle of work: a request to the model, tool calls, a reply. A turn ends when control comes back to you.
**Goal mode** is a completion condition you set with `/goal`. The agent keeps working turn after turn until the goal is met or a limit runs out, and after each turn a separate model checks whether the goal is met. It is useful for long work with a checkable result, such as “the tests and the linter pass”. See [Goal mode](/code/goal/).
**Permission mode** (approval mode) decides which actions the agent takes right away and which it asks about. There are four modes, from `default` to `bypassPermissions`, where the usual approvals are off. A hook or a command the agent cannot parse can still require approval. You can switch modes as you go. In headless runs with no `--mode` flag and no setting in `settings.json`, the mode is `trust`, and actions that need approval are rejected. See [Permissions](/code/permissions/).
**Subagent** is a full agent that the main one starts for a narrow task in a separate context. By default it runs on the same model as the main agent, and the subagent’s definition can set a different one. It keeps the main conversation clean and lets routine work run on a cheaper model. See [Subagents](/code/skills/#subagents).
**Skill** is a reusable instruction in its own file that the agent loads when it needs it. Project knowledge then lives in the repository rather than in someone’s head or a one-off prompt. See [Skills and commands](/code/skills/).
**MCP** (Model Context Protocol) is an open protocol for connecting external tools: databases, trackers, a browser, internal services. The agent gets their tools the same way as its built-in ones. See [MCP](/code/mcp/).
**ACP** (Agent Client Protocol) is the protocol the agent uses to talk to clients: editors such as Zed and JetBrains, and terminal clients. It is why the same agent works in different interfaces. See [IDEs (ACP)](/code/ide/).
**Hook** is your script that the agent runs on an event: before a tool call, after a file edit, at the end of a session. Project rules then apply automatically, without asking for them in a prompt. See [Hooks](/code/hooks/).
**LSP** (Language Server Protocol) is how an IDE understands code: precise go-to-definition, a list of references, compiler errors. The agent uses the same language servers, so it asks them instead of guessing from the text. See [Language servers](/code/lsp/).
# Waibee Router
> One gateway to LLM providers. API, integrations, and routing.
Waibee Router is a gateway to LLMs: one API and one key for models from different providers. It accepts requests in **OpenAI Chat Completions** (`POST /v1/chat/completions`), **Anthropic Messages** (`POST /v1/messages`), and **OpenAI Responses** (`POST /v1/responses`) format, so a client that already works with these APIs switches to Waibee by changing the base URL and the API key.
## Three request formats
[Section titled “Three request formats”](#three-request-formats)
All three formats share one [catalog](/router/models/) and one balance. Which models and capabilities are available depends on the request format and the model.
| Format | Path | Who it is for |
| ------------------------------------------ | ---------------------- | -------------------------------------------------------------------------------------- |
| OpenAI Chat Completions | `/v1/chat/completions` | The default: almost every client and library understands it |
| Anthropic Messages | `/v1/messages` | Clients built on the Anthropic SDK, including Claude Code |
| [OpenAI Responses](/router/responses-api/) | `/v1/responses` | Clients on the newer OpenAI format: Codex CLI, Agents SDK, `client.responses.create()` |
Chat Completions and Responses are both OpenAI formats, and the same official SDK covers both: `client.chat.completions.create()` and `client.responses.create()`. Responses is built around items instead of messages, so reasoning, tool calls, and text arrive as separate items, each with its own status.
If your client understands Chat Completions and you have no preference, use it: it is the most widely supported. Use Responses if your tool speaks it or you need items.
## Getting started
[Section titled “Getting started”](#getting-started)
* [Quickstart](/router/quickstart/): your first request in five minutes.
* [Authentication](/router/authentication/): API keys and Bearer tokens.
* [Responses format](/router/responses-api/): items, multi-turn conversations, and what the router does not do on this format.
## Integrations
[Section titled “Integrations”](#integrations)
How to connect Waibee to Waibee Code, Claude Code, Codex CLI, OpenCode, and other tools and SDKs: [Integrations](/router/integrations/).
## Features
[Section titled “Features”](#features)
* [Web search](/router/web-search/): the model searches the web on its own, and the router runs the search for it. Works on all three formats.
* [Autorouting](/router/autorouting/): the router picks a model for the request.
* [Tool calling](/router/tool-calling/): functions, the call loop, and streaming.
* [Structured outputs](/router/structured-outputs/): a response that strictly follows a JSON Schema.
* [Reasoning](/router/reasoning/): reasoning levels and what they cost.
* [Images and PDFs](/router/attachments/): attachments in a request.
* [Streaming](/router/streaming/): streamed responses and errors mid-stream.
* [Prompt caching](/router/prompt-caching/): reusing a stable prefix.
* [Embeddings](/router/embeddings/): text vectors in OpenAI Embeddings format on `POST /v1/embeddings`.
* [Decisions (System One)](/router/decisions/): typed responses from the TypeSafe Jev model on `POST /v1/systemone`.
* [Plugins](/router/plugins/): DLP, which checks a request for sensitive data.
## In practice
[Section titled “In practice”](#in-practice)
* [Cookbook](/router/cookbook/): ready-made code for common tasks, from tool calling to timeouts and retries in a service.
* [Migrating to Waibee](/router/migration/): what to change in your code when you move from OpenAI, Anthropic, or another gateway.
## Reference
[Section titled “Reference”](#reference)
* [Models](/router/models/): IDs, the catalog, and prices.
* [Tokens and usage](/router/usage/): counters and cost estimates.
* [Limits](/router/limits/): request size, rate, response time, and retries.
* [Errors](/router/errors/): error formats, codes, and what to do about them.
* [FAQ](/router/faq/): common questions.
* [API Reference](/router/api/): the full reference of endpoints, parameters, and errors.
* [Glossary](/glossary/): terms used across the documentation.
# Images and PDFs
> How to pass an image or a PDF in a request to /v1/chat/completions, /v1/messages, and /v1/responses, the limits, and how to check support.
Images and PDFs go directly in the message, alongside the text. Encode the file in base64 and put it in the request: the router has no separate file upload.
To check whether a model supports them, look in `GET /v1/models`:
* images: `capabilities.modality_input` includes `image`;
* PDFs: `capabilities.features` includes `pdf_input`.
See [Models](/router/models/).
## Images on Chat Completions
[Section titled “Images on Chat Completions”](#images-on-chat-completions)
The message content becomes an array of blocks. Pass the image in an `image_url` block with a `data:` URL:
image.sh
```bash
B64=$(base64 < chart.png | tr -d '\n')
curl https://api.waibee.com/v1/chat/completions \
-H "Authorization: Bearer $WAIBEE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "google/gemini-3.6-flash",
"messages": [{ "role": "user", "content": [
{ "type": "text", "text": "What is in the image? One word." },
{ "type": "image_url", "image_url": { "url": "data:image/png;base64,'"$B64"'" } }
] }]
}'
```
One message can hold several blocks: text and images go in the order you list them.
## PDFs on Chat Completions
[Section titled “PDFs on Chat Completions”](#pdfs-on-chat-completions)
Pass the document in a `file` block: the file name plus its content in `file_data`.
```json
{
"role": "user",
"content": [
{ "type": "file", "file": {
"filename": "report.pdf",
"file_data": "data:application/pdf;base64,"
} },
{ "type": "text", "text": "Find the total amount in the document." }
]
}
```
## Images and PDFs on Messages
[Section titled “Images and PDFs on Messages”](#images-and-pdfs-on-messages)
The Anthropic format uses `image` and `document` blocks with a `source` object:
```json
{
"role": "user",
"content": [
{ "type": "document", "source": {
"type": "base64",
"media_type": "application/pdf",
"data": ""
} },
{ "type": "text", "text": "What code is given in the document?" }
]
}
```
For an image, the block type is `image`, and `media_type` matches the format (`image/png`, `image/jpeg`, `image/webp`).
## Images and PDFs on Responses
[Section titled “Images and PDFs on Responses”](#images-and-pdfs-on-responses)
On `POST /v1/responses`, pass an image in an `input_image` block with a `data:` URL in `image_url`, and a PDF in an `input_file` block with `filename` and `file_data` in the same form as on Chat Completions.
## Limits
[Section titled “Limits”](#limits)
The size of a single file and of the whole request body is limited; the values and error codes are in [Limits](/router/limits/#request-size). Going over returns `413`.
The per-file limit applies to the original size, before encoding. The body limit applies to what goes over the network, and base64 makes a file about a third larger: two files that are each within the limit can together exceed the body size.
## What to keep in mind
[Section titled “What to keep in mind”](#what-to-keep-in-mind)
* **Attachments are billed as input tokens.** Each model has its own conversion rules: a PDF page or a large image can cost several thousand tokens. Check the actual cost in `usage`; see [Tokens and usage](/router/usage/).
* **Shrink images before sending.** The model scales the image down to its resolution limit anyway, and the extra pixels turn into extra tokens and latency.
* **Scans are read by the model, not by a separate OCR step.** Quality drops noticeably on poor scans and handwriting: if this is your main use case, test the results on your own files.
* **Split multi-page PDFs.** Splitting a document and asking about a specific section is usually cheaper and more accurate than sending a hundred pages in one request.
* **Cache a document you reuse.** If you ask several questions about one file, mark the document block with `cache_control`; see [Prompt caching](/router/prompt-caching/).
# Authentication
> API keys and Bearer tokens for accessing Waibee Router.
Every API request needs an API key of the form `sk_live_...`. Create one in the console: [chat.waibee.com/api-keys](https://chat.waibee.com/api-keys). Send it as a Bearer token in the `Authorization` header.
## Header
[Section titled “Header”](#header)
```http
Authorization: Bearer sk_live_...
```
The `POST /v1/messages` endpoint accepts both `x-api-key` (the header clients built on the Anthropic SDK send) and `Authorization: Bearer`. If both arrive, `x-api-key` is used. All other endpoints accept only `Authorization: Bearer`.
```http
x-api-key: sk_live_...
```
## Checking a key
[Section titled “Checking a key”](#checking-a-key)
```bash
curl https://api.waibee.com/v1/models \
-H "Authorization: Bearer $WAIBEE_API_KEY"
```
On success you get `200` with the list of models. A wrong key returns `401` with the code `invalid_api_key`, and a missing header returns `401` with the code `authentication_required`:
401.json
```json
{ "error": { "code": "invalid_api_key", "message": "Invalid API key", "extra": {} } }
```
On `/v1/responses` the codes are the same and the envelope is in Responses format; see [Errors](/router/errors/#format). On `/v1/chat/completions` and `/v1/messages`, a rejected key comes back in a short form, without a code:
```json
{ "error": "unauthorized" }
```
Caution
Requests made with your key are paid from your balance. Treat the key like a password: keep it in environment variables or CI secrets, not in code.
# Autorouting
> waibee/auto: the router picks a model for each request. What affects the choice, stability within a conversation, and errors.
With autorouting, the router picks the model instead of your client. Pass `waibee/auto` in the `model` field instead of a specific ID.
autorouting.sh
```bash
curl https://api.waibee.com/v1/chat/completions \
-H "Authorization: Bearer $WAIBEE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "waibee/auto",
"messages": [{ "role": "user", "content": "Reply with one word: ok" }]
}'
```
The `model` field in the response holds **the model that actually ran**, not `waibee/auto`:
```json
{
"model": "google/gemini-3.7-flash",
"choices": [{ "index": 0, "finish_reason": "stop",
"message": { "role": "assistant", "content": "ok" } }],
"usage": { "prompt_tokens": 6, "completion_tokens": 75, "total_tokens": 81 }
}
```
Autorouting works on all three endpoints: `POST /v1/chat/completions`, `POST /v1/messages`, and `POST /v1/responses`.
A short question goes to a cheap model, a hard task to a strong one, and a request with an image to a model that accepts images. You do not have to watch the catalog or change IDs when new models appear.
## What affects the choice
[Section titled “What affects the choice”](#what-affects-the-choice)
The router looks at the request itself:
| Signal | Effect |
| ---------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
| Text of the request and the system prompt | Estimates how hard the task is: a quick lookup or system design |
| Attachments | An image or audio in the input leaves only models with that modality |
| `tools` | Requires tool calling support |
| `reasoning_effort` or `reasoning.effort`, or `thinking` with `budget_tokens` on `/v1/messages` | Requires a reasoning model |
| `response_format` (`text.format` on `/v1/responses`) | `json_schema` requires structured outputs support, and `json_object` requires `response_format` support |
| `cache_control` markers | Leaves only models that understand `cache_control`, currently Anthropic models |
| Request size | Drops models whose context window is too small |
The router picks among the models your group allows for autorouting. This is a separate setting: autorouting can pick a model you cannot request by name, and the other way around.
If autorouting is available to your group, `waibee/auto` is in the [catalog](/router/models/#autorouting).
## Stability within a conversation
[Section titled “Stability within a conversation”](#stability-within-a-conversation)
The router recognizes a continuing conversation by its content and tries to keep the model it picked for it. It can switch models, for example when the conversation no longer fits that model’s context window.
This matters most with `cache_control` markers: the cache is held by a specific model, and switching to another one would reset cache hits. See [Prompt caching](/router/prompt-caching/).
Note
The selection rules and the set of signals change over time. The model that ran is always in the `model` field of the response.
## Errors
[Section titled “Errors”](#errors)
Selection errors apply only to `waibee/auto` and come with status `422`.
| Code | When |
| ---------------------------------- | ------------------------------------------------------------------------------------- |
| `auto_routing_no_match` | No suitable model is left after filtering by capabilities and policies |
| `auto_routing_request_too_large` | The request does not fit the context window of any available model |
| `auto_routing_caching_unavailable` | Prompt caching was requested, but no suitable model supports it |
| `auto_routing_missing_context` | Internal selection error: retry the request, and if it happens again, contact support |
The details of the rejection are in `extra` (in `details` on `/v1/messages` and `/v1/responses`): which filter emptied the list of models, which capabilities were required, and what to do about it.
422
```json
{
"error": {
"code": "auto_routing_request_too_large",
"message": "No model matches the auto-routing requirements",
"extra": {
"required_capabilities": [],
"filter_step_dropped_at": "context",
"pool_size_initial": 73,
"pool_size_after_filter": 0,
"recommendation": "The request is too large...",
"auto_routing_decision_id": "e0e62376-55c2-4e06-98cb-90dc6640d451",
"tier_attempted": "standard"
}
}
}
```
If you get these errors regularly, specify the model explicitly; see [Models](/router/models/). Include `auto_routing_decision_id` when you contact support.
`waibee/auto` requires a minimum balance. Below it, the request is rejected with `402` and the code `insufficient_funds`, and `message` names the amount required. Top up your balance or specify the model explicitly.
## What to keep in mind
[Section titled “What to keep in mind”](#what-to-keep-in-mind)
* **The cost of a request depends on the model picked.** Calculate it from the `model` and `usage` pair in the response; see [Tokens and usage](/router/usage/).
* **Where you need reproducible results, specify the model explicitly.** Tests, benchmarks, prompt comparisons, and a prompt tuned for a specific model only make sense on a fixed model.
# Cookbook
> Ready-to-run code for common tasks: tool calling, a cached context, extracting data from text, images, and PDFs, maximum reasoning, streaming, parallel requests, a fallback model, timeouts, and retries.
Working code for common tasks. Each recipe shows how features work together and where people usually get them wrong. Every feature has its own page with the details, linked at the start of the recipe.
The examples are in Python and read the key from the environment:
```bash
export WAIBEE_API_KEY="sk_live_..."
pip install openai httpx
```
## Tool calling loop
[Section titled “Tool calling loop”](#tool-calling-loop)
The model asks for a call, you run the function, return the result, and repeat. The detail that matters is the step limit: without it, a confused model goes around in circles at your expense. See [Tool calling](/router/tool-calling/).
tool\_loop.py
```python
import json
import os
from openai import OpenAI
client = OpenAI(base_url="https://api.waibee.com/v1", api_key=os.environ["WAIBEE_API_KEY"])
TOOLS = [
{
"type": "function",
"function": {
"name": "get_order",
"description": "Order status by order number",
"parameters": {
"type": "object",
"properties": {"order_id": {"type": "string"}},
"required": ["order_id"],
},
},
}
]
def get_order(order_id: str) -> dict:
if not isinstance(order_id, str) or not order_id.strip():
raise ValueError("order_id must be a non-empty string")
return {"order_id": order_id, "status": "shipped", "eta_days": 2}
HANDLERS = {"get_order": get_order}
MAX_STEPS = 5
def call_tool(name: str, raw_arguments: str) -> str:
handler = HANDLERS.get(name)
if handler is None:
return json.dumps({"error": f"tool {name} does not exist"}, ensure_ascii=False)
try:
arguments = json.loads(raw_arguments)
if not isinstance(arguments, dict):
raise ValueError("arguments must be a JSON object")
result = handler(**arguments)
except (ValueError, TypeError) as error:
return json.dumps({"error": f"invalid arguments: {error}"}, ensure_ascii=False)
return json.dumps(result, ensure_ascii=False)
def answer(question: str) -> str:
messages = [{"role": "user", "content": question}]
for _ in range(MAX_STEPS):
choice = client.chat.completions.create(
model="waibee/auto", messages=messages, tools=TOOLS
).choices[0]
if choice.finish_reason != "tool_calls":
return choice.message.content
messages.append(choice.message)
messages += [
{
"role": "tool",
"tool_call_id": call.id,
"content": call_tool(call.function.name, call.function.arguments),
}
for call in choice.message.tool_calls
]
raise RuntimeError(f"tools are being called in a loop, {MAX_STEPS} steps used up")
print(answer("What is the status of order A-1042? Answer in one sentence."))
```
```text
Order A-1042 has been shipped and is expected to arrive in 2 days.
```
The model’s message goes into the history as is, and each call gets its own `role: "tool"` message with the matching `tool_call_id`.
The model passes `arguments` as a string, so the example checks both the JSON syntax and the function arguments. An array, `null`, a missing `order_id`, or an extra field raises an error. The handler returns it to the model as a `role: "tool"` message, so the model can fix the call on the next step. The loop itself keeps going.
## Repeat questions about one document
[Section titled “Repeat questions about one document”](#repeat-questions-about-one-document)
When a large, unchanging context repeats in every request, mark it for caching: the first request pays for the write, and the rest read it at a lower price. See [Prompt caching](/router/prompt-caching/).
cached\_context.py
```python
import os
import pathlib
from openai import OpenAI
client = OpenAI(base_url="https://api.waibee.com/v1", api_key=os.environ["WAIBEE_API_KEY"])
POLICY = pathlib.Path("policy.txt").read_text(encoding="utf-8")
def ask(question: str) -> tuple[str, int]:
response = client.chat.completions.create(
model="anthropic/claude-haiku-4.5",
messages=[
{
"role": "user",
"content": [
# The cached block goes first, the changing question after it.
{"type": "text", "text": POLICY, "cache_control": {"type": "ephemeral"}},
{"type": "text", "text": f"{question} Answer in one line."},
],
}
],
)
# prompt_tokens_details is missing when the provider sent no breakdown.
details = response.usage.prompt_tokens_details
cached = getattr(details, "cached_tokens", 0) or 0
return response.choices[0].message.content, cached
for question in ["What is the return period?", "Who pays for return shipping?"]:
answer, cached = ask(question)
print(f"cached {cached:>6} tokens | {answer.splitlines()[0][:50]}")
```
```text
cached 0 tokens | The return period is 14 days from the date the cus
cached 23760 tokens | # Return Shipping Cost
```
The first request writes the cache, and the second reads the whole document from it. The 50-character cut in `print` is only there for the example.
## Extracting data with a schema
[Section titled “Extracting data with a schema”](#extracting-data-with-a-schema)
A schema sets the shape of the response, but it says nothing about whether the content is plausible: the model fills in a required field even where the text has no data for it. So describe “unknown” in the schema explicitly, and check the meaning in your own code. See [Structured outputs](/router/structured-outputs/).
extract.py
```python
import json
import os
from openai import OpenAI
client = OpenAI(base_url="https://api.waibee.com/v1", api_key=os.environ["WAIBEE_API_KEY"])
INVOICE_SCHEMA = {
"type": "object",
"properties": {
"company": {"type": "string"},
"amount": {"type": "number"},
"currency": {"type": "string", "enum": ["RUB", "USD", "EUR"]},
# An explicit null: otherwise the model invents a date the text does not have.
"due_date": {"type": ["string", "null"], "description": "ISO 8601 or null"},
},
"required": ["company", "amount", "currency", "due_date"],
"additionalProperties": False,
}
def extract_invoice(text: str) -> dict:
choice = client.chat.completions.create(
model="openai/gpt-5.4-mini",
messages=[{"role": "user", "content": text}],
response_format={
"type": "json_schema",
"json_schema": {"name": "invoice", "strict": True, "schema": INVOICE_SCHEMA},
},
).choices[0]
if choice.finish_reason == "length":
raise ValueError("response cut off by the token limit, JSON is incomplete")
invoice = json.loads(choice.message.content)
if invoice["amount"] <= 0: # the schema checks the shape, not plausibility
raise ValueError(f"implausible amount: {invoice['amount']}")
return invoice
print(extract_invoice("Invoice from Romashka LLC for 154,200 rubles, due by August 15, 2026."))
print(extract_invoice("Invoice from Acme Inc, 1200 EUR, no due date specified."))
```
```text
{'company': 'Romashka LLC', 'amount': 154200, 'currency': 'RUB', 'due_date': '2026-08-15'}
{'company': 'Acme Inc', 'amount': 1200, 'currency': 'EUR', 'due_date': None}
```
## Image to structured data
[Section titled “Image to structured data”](#image-to-structured-data)
A screenshot, a photo of a receipt, a picture of a table: the model reads the image, and the schema brings the response into the shape you need.
receipt.py
```python
import base64
import json
import os
import pathlib
from openai import OpenAI
client = OpenAI(base_url="https://api.waibee.com/v1", api_key=os.environ["WAIBEE_API_KEY"])
RECEIPT_SCHEMA = {
"type": "object",
"properties": {
"merchant": {"type": "string"},
"total": {"type": "number"},
"currency": {"type": "string"},
"items": {
"type": "array",
"items": {
"type": "object",
"properties": {"name": {"type": "string"}, "price": {"type": "number"}},
"required": ["name", "price"],
"additionalProperties": False,
},
},
},
"required": ["merchant", "total", "currency", "items"],
"additionalProperties": False,
}
def read_receipt(path: pathlib.Path) -> dict:
image = base64.b64encode(path.read_bytes()).decode()
choice = client.chat.completions.create(
model="google/gemini-3.6-flash",
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "Extract the receipt data according to the schema."},
{"type": "image_url", "image_url": {"url": f"data:image/png;base64,{image}"}},
],
}
],
response_format={
"type": "json_schema",
"json_schema": {"name": "receipt", "strict": True, "schema": RECEIPT_SCHEMA},
},
).choices[0]
receipt = json.loads(choice.message.content)
# The model reads the image rather than adding up, so the items may not match the total.
if abs(sum(item["price"] for item in receipt["items"]) - receipt["total"]) > 0.01:
raise ValueError(f"item prices do not add up to the total {receipt['total']}")
return receipt
print(read_receipt(pathlib.Path("receipt.png")))
```
```text
{'merchant': 'COFFEE HOUSE', 'total': 10.5, 'currency': 'EUR', 'items': [{'name': 'Espresso', 'price': 2.8}, {'name': 'Croissant', 'price': 3.2}, {'name': 'Orange juice', 'price': 4.5}]}
```
Comparing the sum of the items with the total is a cheap check that a schema cannot do: it catches both a skipped line and a misread digit. You need a model that accepts images as input: `image` in `capabilities.modality_input` in the [catalog](/router/models/#catalog). See [Images and PDFs](/router/attachments/).
## Extracting data from PDFs
[Section titled “Extracting data from PDFs”](#extracting-data-from-pdfs)
The document goes straight into the message; there is no separate file upload. Each document is its own request, so a failure on one file does not stop the rest. See [Images and PDFs](/router/attachments/).
invoices.py
```python
import base64
import os
import pathlib
from openai import OpenAI, OpenAIError
client = OpenAI(base_url="https://api.waibee.com/v1", api_key=os.environ["WAIBEE_API_KEY"])
def read_invoice(path: pathlib.Path) -> str:
document = base64.b64encode(path.read_bytes()).decode()
response = client.chat.completions.create(
model="anthropic/claude-haiku-4.5",
messages=[
{
"role": "user",
"content": [
{
"type": "file",
"file": {
"filename": path.name,
"file_data": f"data:application/pdf;base64,{document}",
},
},
{"type": "text", "text": "Return the document's amount and currency, with no explanation."},
],
}
],
)
return response.choices[0].message.content.strip()
for path in sorted(pathlib.Path("invoices").glob("*.pdf")):
try:
print(f"{path.name}: {read_invoice(path)}")
except OpenAIError as error: # one failed document must not stop the processing
print(f"{path.name}: skipped, {error}")
```
```text
a.pdf: 154200 RUB
b.pdf: 1200 EUR
```
## A task that needs maximum reasoning
[Section titled “A task that needs maximum reasoning”](#a-task-that-needs-maximum-reasoning)
This recipe passes `max` through `output_config.effort` on `/v1/messages`, so it needs the Anthropic SDK (`pip install anthropic`). Use it where a mistake costs more than waiting: untangling convoluted logic, deriving a formula, reviewing a tricky invariant. See [Reasoning](/router/reasoning/).
hard.py
```python
import os
import anthropic
# Base URL without /v1: the SDK adds the path itself.
client = anthropic.Anthropic(
base_url="https://api.waibee.com",
api_key=os.environ["WAIBEE_API_KEY"],
timeout=600.0,
)
TASK = (
"A basket holds 12 balls: 5 red, 4 blue, 3 white. Three are drawn in a row without "
"replacement. What is the probability that all three are different colors? Answer in one "
"line: the fraction in lowest terms and its decimal value."
)
response = client.messages.create(
model="anthropic/claude-sonnet-5",
max_tokens=8192,
# The SDK passes the field through as is.
extra_body={"output_config": {"effort": "max"}},
messages=[{"role": "user", "content": TASK}],
)
answer = "".join(block.text for block in response.content if block.type == "text")
print(answer.strip())
print(f"[{response.usage.output_tokens} output tokens, including reasoning]")
```
```text
**P(all three different colors) = 3/11 ≈ 0.2727** (since C(5,1)·C(4,1)·C(3,1)/C(12,3) = 60/220 = 3/11)
[303 output tokens, including reasoning]
```
At `max`, the model is silent while it thinks, so do not set a low client timeout: a short read timeout cuts off a live request. `thinking` blocks come in `content` before the text, so the answer is assembled only from blocks of type `text`.
## Streaming a response to the user
[Section titled “Streaming a response to the user”](#streaming-a-response-to-the-user)
The text prints as it is generated, and the token counters arrive in the last chunk, which has no content. See [Streaming](/router/streaming/).
stream.py
```python
import os
from openai import OpenAI
client = OpenAI(base_url="https://api.waibee.com/v1", api_key=os.environ["WAIBEE_API_KEY"])
stream = client.chat.completions.create(
model="anthropic/claude-haiku-4.5",
messages=[{"role": "user", "content": "Three ways to cache HTTP responses, one line each."}],
stream=True,
)
usage = None
for chunk in stream:
if chunk.usage: # last chunk: counters only, no text
usage = chunk.usage
for choice in chunk.choices:
if choice.delta.content:
print(choice.delta.content, end="", flush=True)
print()
if usage:
print(f"[tokens: input {usage.prompt_tokens}, output {usage.completion_tokens}]")
```
You do not need to pass `stream_options` to get the counters: the router adds them to the stream on its own.
## Many requests in parallel
[Section titled “Many requests in parallel”](#many-requests-in-parallel)
You set the limit on concurrent requests: without one, the client runs into the limits and gets `429` or `503` instead of a result. See [Limits](/router/limits/).
batch.py
```python
import asyncio
import os
from openai import AsyncOpenAI
client = AsyncOpenAI(base_url="https://api.waibee.com/v1", api_key=os.environ["WAIBEE_API_KEY"])
MAX_CONCURRENCY = 4
async def summarize(text: str, limiter: asyncio.Semaphore) -> str:
async with limiter:
response = await client.chat.completions.create(
model="anthropic/claude-haiku-4.5",
messages=[{"role": "user", "content": f"In one sentence, what is this about: {text}"}],
)
return response.choices[0].message.content
async def summarize_all(texts: list[str]) -> list[str | BaseException]:
limiter = asyncio.Semaphore(MAX_CONCURRENCY)
# return_exceptions: one failed request must not wipe out the whole batch of results.
return await asyncio.gather(
*(summarize(text, limiter) for text in texts), return_exceptions=True
)
TICKETS = [
"Customer cannot log in: the password was reset, but the email never arrives.",
"Payment went through twice, one transaction needs a refund.",
"The app crashes when opening the profile on Android 13.",
]
for ticket, result in zip(TICKETS, asyncio.run(summarize_all(TICKETS))):
if isinstance(result, BaseException):
print(f"! {ticket[:30]}: {result}")
else:
print(f"- {result}")
```
For long queues, add the retries from the [Timeouts and retries in a service](/router/cookbook/#timeouts-and-retries-in-a-service) recipe.
## Fallback model on failure
[Section titled “Fallback model on failure”](#fallback-model-on-failure)
A request has no routing fields, so the fallback chain lives on the client side. Tell the cases apart: when a model is unavailable, moving to the next one helps, but an error in the request itself repeats on any model. See [Errors](/router/errors/).
fallback.py
```python
import os
from openai import APIStatusError, OpenAI
client = OpenAI(base_url="https://api.waibee.com/v1", api_key=os.environ["WAIBEE_API_KEY"])
# Order matters: the preferred model first, then the fallbacks.
MODELS = ["anthropic/claude-sonnet-4.6", "openai/gpt-5.4-mini", "google/gemini-3.6-flash"]
FALLBACK_STATUSES = frozenset({404, 429, 502, 503})
def complete(messages: list[dict], models: list[str] = MODELS):
for model in models:
try:
return client.chat.completions.create(model=model, messages=messages)
except APIStatusError as error:
if error.status_code not in FALLBACK_STATUSES or (
error.status_code == 429
and error.response.json().get("error", {}).get("code") != "provider_rate_limited"
):
raise # an error in the request itself: another model will not help
raise RuntimeError(f"no model responded: {', '.join(models)}")
response = complete([{"role": "user", "content": "Answer in one word: fallback"}])
print(f"{response.model}: {response.choices[0].message.content}")
```
On `429`, the recipe switches models only for `provider_rate_limited`. On `api_key_limit_exceeded`, check the key’s spending limit and when it resets.
The alternative to a chain of your own is `waibee/auto`: the router picks a model that suits the request. See [Autorouting](/router/autorouting/).
## Timeouts and retries in a service
[Section titled “Timeouts and retries in a service”](#timeouts-and-retries-in-a-service)
What sets production code apart from an example: a long read timeout (reasoning models stay silent for minutes), your own retries that decide by error code, and reading the counters. See [Limits](/router/limits/) and [Tokens and usage](/router/usage/).
client.py
```python
import os
import random
import time
import httpx
from openai import APIConnectionError, APIStatusError, APITimeoutError, OpenAI
from openai.types.chat import ChatCompletion
client = OpenAI(
base_url="https://api.waibee.com/v1",
api_key=os.environ["WAIBEE_API_KEY"],
# Reasoning models stay silent for minutes: a short read timeout cuts off a live request.
timeout=httpx.Timeout(connect=10.0, read=600.0, write=30.0, pool=10.0),
max_retries=0, # we retry ourselves to decide by error code
)
MAX_ATTEMPTS = 3
RETRIABLE_STATUSES = frozenset({408, 429, 500, 502, 503})
def is_retriable(error: APIStatusError) -> bool:
# The key's spending limit lifts only when the counter resets: a retry will not help.
return error.status_code in RETRIABLE_STATUSES and error.code != "api_key_limit_exceeded"
def complete(**kwargs) -> ChatCompletion:
for attempt in range(MAX_ATTEMPTS):
last_attempt = attempt == MAX_ATTEMPTS - 1
try:
return client.chat.completions.create(**kwargs)
except APIStatusError as error:
if last_attempt or not is_retriable(error):
raise
except (APITimeoutError, APIConnectionError):
if last_attempt:
raise
# Random jitter spreads out client retries so they do not land in one wave.
time.sleep(2**attempt + random.random())
raise AssertionError("unreachable: the loop either returned a response or raised")
response = complete(
model="waibee/auto",
messages=[{"role": "user", "content": "Answer in one word: ready"}],
)
usage = response.usage
cached = getattr(usage.prompt_tokens_details, "cached_tokens", 0) or 0
print(
f"model {response.model}: input {usage.prompt_tokens}, output {usage.completion_tokens}, "
f"cached {cached}"
)
```
```text
model anthropic/claude-haiku-4.5: input 13, output 5, cached 0
```
Log `response.model` together with `usage`: on `waibee/auto`, it is the only way to find out later which model answered and what it cost.
# Decisions (System One)
> POST /v1/systemone in System One API format. Typed decisions with the TypeSafe Jev model, choice, score, and noul questions, limitations, and DLP.
`POST /v1/systemone` answers typed questions about data. You send a state (`state`) and a set of questions, and in one call the model answers each of them with probabilities. The request and the response follow TypeSafe’s System One API, so the TypeSafe SDK connects by changing the address and the key.
The endpoint serves only models of the `decision` class; currently that is TypeSafe Jev. `GET /v1/models?output_modalities=decisions` returns their list; see [Models](/router/models/#model-classes).
## First request
[Section titled “First request”](#first-request)
```bash
curl https://api.waibee.com/v1/systemone \
-H "Authorization: Bearer $WAIBEE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "jev-latest",
"state": "Customer writes: I want my money back for order 1042",
"questions": {
"route": {
"type": "choice",
"instructions": "Which team handles this ticket?",
"criteria": {"sales": "buying", "refunds": "money back", "shipping": "delivery"}
},
"urgency": {
"type": "score",
"instructions": "How urgent is it?",
"criteria": ["not urgent", "somewhat urgent", "very urgent"]
}
}
}'
```
```json
{
"model": "typesafe/jev-1.13-20260917",
"answers": {
"route": {
"type": "choice",
"choice": "refunds",
"probabilities": {"sales": 0, "refunds": 1, "shipping": 0},
"confidence": 1
},
"urgency": {
"type": "score",
"score": 1.09,
"legend": {"0": "not urgent", "1": "somewhat urgent", "2": "very urgent"},
"probabilities": {"0": 0.03, "1": 0.85, "2": 0.12},
"confidence": 0.78
}
},
"usage": {"input_tokens": 377, "output_tokens": 55}
}
```
The answer to each question is in `answers` under the same key the question was sent with.
## From Python
[Section titled “From Python”](#from-python)
You do not need a separate SDK; any HTTP client will do:
```python
import os
import httpx
response = httpx.post(
"https://api.waibee.com/v1/systemone",
headers={"Authorization": f"Bearer {os.environ['WAIBEE_API_KEY']}"},
json={
"model": "jev-latest",
"state": "Customer writes: I want my money back for order 1042",
"questions": {
"route": {
"type": "choice",
"instructions": "Which team handles this ticket?",
"criteria": {"sales": "buying", "refunds": "money back", "shipping": "delivery"},
},
},
},
timeout=30,
)
response.raise_for_status()
route = response.json()["answers"]["route"]
print(route["choice"], route["confidence"])
```
## TypeSafe SDK
[Section titled “TypeSafe SDK”](#typesafe-sdk)
The TypeSafe SDK works with Waibee without changes to the calling code: set the Waibee key and address. The SDK appends `/v1/systemone` to the address itself, so give the address without `/v1`.
```python
from typesafe_sdk import Noul, TypeSafeClient
with TypeSafeClient(api_key="sk_live_...", base_url="https://api.waibee.com") as client:
result = client.system_one(
"I was charged twice.",
{"billing": Noul(instructions="Is this about billing?")},
)
print(result.nouls["billing"].noul)
```
Instead of arguments, you can use the `TYPESAFE_API_KEY` and `TYPESAFE_BASE_URL` environment variables. The SDK’s default model is `jev-latest`, and the router accepts it as is.
`client.models.list()` does not work with Waibee: `GET /v1/models` responds in OpenAI format, while the SDK expects TypeSafe format. To list decision models, use `GET /v1/models?output_modalities=decisions`.
## Request
[Section titled “Request”](#request)
| Field | What it sets |
| ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| `model` | The ID of a `decision` class model from the catalog. An ID without the provider is read as a TypeSafe model: `jev-latest` is `typesafe/jev-latest` |
| `state` | What to evaluate: a string, a JSON object, or an array |
| `questions` | A “key → question” map with at least one question. You choose the keys |
| `plugins` | [DLP](/router/plugins/) settings, as in chat requests |
A question has three fields:
| Field | What it sets |
| -------------- | ------------------------------------------------------------------- |
| `type` | `choice`, `score`, or `noul` |
| `instructions` | Required. What is being asked: a string, a JSON object, or an array |
| `criteria` | Options or levels; the shape depends on the type |
The router drops other fields, at the top level and inside a question, and does not pass them to the model.
## Question types
[Section titled “Question types”](#question-types)
| `type` | What the question asks | `criteria` | What the answer contains |
| -------- | ---------------------------- | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `choice` | Which option from a set fits | An “option → when to choose it” object | `choice` with the key of the chosen option, `probabilities` across options, `confidence` |
| `score` | Which level of a scale fits | An array of levels, from lowest to highest | `score` on the scale of level numbers, `legend` with a description of each number, `probabilities` across levels, `confidence` |
| `noul` | Whether a statement is true | Optional: an object with the keys `true` and `false` | `noul`, the probability that the statement is true, from 0 to 1 |
An option or level description, like `instructions`, can be a string, a JSON object, or an array. The model checks how many options and levels are allowed and what else a question requires: a question that breaks its rules is rejected with `400`. How to phrase questions and read probabilities is covered in the [TypeSafe documentation](https://docs.typesafe.ai/).
## Response
[Section titled “Response”](#response)
* `model` names the version of the model that responded. With `jev-latest`, it is a specific version, for example `typesafe/jev-1.13-20260917`.
* `answers` has an entry for each key in `questions`, in the form the model returned it.
* `usage` has tokens only: `input_tokens` and `output_tokens`. `output_tokens` is present only if the model returned it. If the model returned no counters, the response has no `usage`.
* `plugins.dlp` is present if DLP in `mask` or `alert` mode found something; see [DLP](#dlp).
## Limitations
[Section titled “Limitations”](#limitations)
* **Text volume** is limited to 15 MB for `state` and the questions together. Their whole JSON counts: keys, quotes, and `type` fields are included, unlike in chat requests, where only the text counts. Going over returns `413` with the code `text_content_too_large`; see [Limits](/router/limits/).
* **Nesting** of `state`, `instructions`, and option descriptions: no deeper than 64 levels. A deeper request is rejected with `422` and the code `validation_error`.
* **Decision models only.** A model of another class on this endpoint is rejected with `400` and the code `model_endpoint_mismatch`, and so is a decision model on the chat endpoints.
* **No `waibee/auto`.** [Autorouting](/router/autorouting/) picks only among chat models, so `waibee/auto` is rejected here with `400` and the code `feature_not_supported`.
* **No streaming.** The response always arrives in full.
## DLP
[Section titled “DLP”](#dlp)
Your key’s DLP policy and the `plugins.dlp` field work here the same way as for chat; see [Plugins](/router/plugins/). Since there are no messages here, a few things differ:
* Each string in `state`, `instructions`, and `criteria` is checked the same way as a `user` message. Keys are checked too: question keys and any object key inside `state`, `instructions`, and `criteria`. Numbers are checked; booleans are not.
* A finding names the path to the string, and its `message_index` is `-1`:
| Where it was found | `location` |
| ----------------------------- | ----------------------------------- |
| `state` as a string | `state` |
| A field inside `state` | `state.customer.email` |
| An element of a `state` array | `state[2]` |
| A question’s `instructions` | `questions.route.instructions` |
| An option description | `questions.route.criteria.sales` |
| A scale level | `questions.urgency.criteria[1]` |
| An option key | `questions.route.criteria{sales}` |
| A key inside `state` | `state.customers{john@example.com}` |
| A question key | `questions{route}` |
* `report_scope` narrows nothing: the response has all findings, and `block` rejects the whole request with `403` and the code `dlp_violation`.
* With `mask`, the model receives a token instead of the value found. The value is restored in the response: if the response quotes your text, as `legend` does for `score`, you see your own words.
* A direct `mask` or `block` finding in a key or number rejects the request with `403 dlp_violation`. A protected value repeated in a `state` key or number hides its containing object and keeps the request going. In `questions`, the response names questions and options by their keys, so a repeated value in a key or number also gives `403 dlp_violation` with a safe place name. Under `alert`, the request stays unchanged and the finding is reported.
## Errors
[Section titled “Errors”](#errors)
Errors come in Chat Completions format: an `error` object with the fields `code`, `message`, and `extra`. Codes are shared across all endpoints: [Errors](/router/errors/).
# Embeddings
> POST /v1/embeddings in OpenAI Embeddings format. Request, response, float and base64, limitations, and DLP.
`POST /v1/embeddings` turns text into vectors. The request and the response match OpenAI Embeddings, so a client built on the OpenAI SDK connects by changing the base URL and the key.
The endpoint serves only models of the `embedding` class. `GET /v1/models?output_modalities=embeddings` returns their list; see [Models](/router/models/#model-classes).
## First request
[Section titled “First request”](#first-request)
```bash
curl https://api.waibee.com/v1/embeddings \
-H "Authorization: Bearer $WAIBEE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "openai/text-embedding-3-small",
"input": ["First text", "Second text"]
}'
```
```json
{
"object": "list",
"data": [
{"object": "embedding", "embedding": [-0.0171966552734375, -0.015472412109375, -0.0038166046142578125], "index": 0},
{"object": "embedding", "embedding": [-0.006717681884765625, 0.014984130859375, 0.000751495361328125], "index": 1}
],
"model": "text-embedding-3-small",
"usage": {"prompt_tokens": 4, "total_tokens": 4}
}
```
The vectors here are shortened: with `openai/text-embedding-3-small`, each has 1536 numbers.
## With the OpenAI SDK
[Section titled “With the OpenAI SDK”](#with-the-openai-sdk)
```python
from openai import OpenAI
client = OpenAI(api_key="sk_live_...", base_url="https://api.waibee.com/v1")
response = client.embeddings.create(
model="openai/text-embedding-3-small",
input=["First text", "Second text"],
encoding_format="float",
)
for item in response.data:
print(item.index, len(item.embedding))
```
Without `encoding_format`, the SDK requests `base64` on its own and decodes the response, so `item.embedding` holds the same list of numbers.
## float and base64
[Section titled “float and base64”](#float-and-base64)
`encoding_format` accepts `float` and `base64`. Without the field, `float` applies: the vector arrives as a list of numbers.
With `base64`, each vector arrives as a string: float32 values in little-endian byte order, the same layout OpenAI uses. After decoding, the numbers match the `float` response.
If you set `encoding_format="base64"` in the SDK explicitly, the SDK does not decode the string, so decode it yourself:
```python
import base64
import struct
response = client.embeddings.create(
model="openai/text-embedding-3-small",
input="First text",
encoding_format="base64",
)
raw = base64.b64decode(response.data[0].embedding)
vector = struct.unpack(f"<{len(raw) // 4}f", raw)
print(len(vector))
```
## Request
[Section titled “Request”](#request)
| Field | What it sets |
| ----------------- | -------------------------------------------------------------------------------------------------- |
| `model` | The ID of an `embedding` class model from the catalog |
| `input` | A string or an array of 1 to 2048 non-empty strings |
| `encoding_format` | `float` or `base64`. Without the field, `float` |
| `dimensions` | The vector length, an integer from 1. Passed to the model only if set; not every model supports it |
| `plugins` | [DLP](/router/plugins/) settings, as in chat requests |
The router drops other fields, such as `user`, and does not pass them to the model.
## Response
[Section titled “Response”](#response)
* `data` holds one vector for each element of `input`, in the same order. `index` is the element’s position in the input.
* `model` names the model that responded.
* `usage` has tokens only: `prompt_tokens` and `total_tokens`. Embeddings have no output tokens. If the model returned no counters, the response has no `usage`.
* `plugins.dlp` is present if DLP in `mask` or `alert` mode found something; see [DLP](#dlp).
## Limitations
[Section titled “Limitations”](#limitations)
* **Text only.** Token arrays and multimodal elements in `input` are rejected with `422` and the code `validation_error`. So are an empty array, an empty string, and more than 2048 elements.
* **Text volume** is limited the same way as for chat: 15 MB for the whole `input`. Going over returns `413` with the code `text_content_too_large`; see [Limits](/router/limits/).
* **Embedding models only.** A chat model on this endpoint is rejected with `400` and the code `model_endpoint_mismatch`, and so is an embedding model on `/v1/chat/completions`, `/v1/messages`, or `/v1/responses`.
* **No `waibee/auto`.** [Autorouting](/router/autorouting/) picks only among chat models, so `waibee/auto` is rejected here with `400` and the code `feature_not_supported`.
* **No streaming.** The response always arrives in full.
LangChain
By default, LangChain’s `OpenAIEmbeddings` splits text into tokens and sends token arrays, which the endpoint does not accept. Create it with `check_embedding_ctx_length=False` so that `input` carries strings.
## DLP
[Section titled “DLP”](#dlp)
Your key’s DLP policy and the `plugins.dlp` field work here the same way as for chat; see [Plugins](/router/plugins/). Since there are no messages here, a few things differ:
* Each element of `input` is checked the same way as a `user` message.
* A finding names the element: `input[1]` for an array, `input` for a string. Its `message_index` is `-1`.
* `report_scope` narrows nothing: the response has all findings, and `block` on any element rejects the whole request with `403` and the code `dlp_violation`.
* With `mask`, the model receives a token instead of the value found, and the vector is computed from the text with the token. Nothing is restored in the response: there is nothing to restore in a vector.
A finding in the second input element
```json
{
"category": "pii",
"entity_type": "EMAIL",
"message_index": -1,
"location": "input[1]",
"start": 5,
"end": 21,
"confidence": 0.99
}
```
## Errors
[Section titled “Errors”](#errors)
Errors come in Chat Completions format: an `error` object with the fields `code`, `message`, and `extra`. Codes are shared across all endpoints: [Errors](/router/errors/).
# Errors
> Error format and codes on /v1/chat/completions, /v1/messages, /v1/responses, /v1/embeddings, and /v1/systemone, by HTTP status.
The error format depends on the endpoint: `/v1/chat/completions` responds in OpenAI style, `/v1/messages` in Anthropic style, and `/v1/responses` in Responses style. The HTTP status and the machine-readable code `error.code` are the same on all three.
## Format
[Section titled “Format”](#format)
Chat Completions (OpenAI): an `error` object with the fields `code`, `message`, and `extra`. `extra` holds the details of the rejection, if there are any.
```json
{ "error": { "code": "model_not_found", "message": "Model 'nope/nope' is not available. Check the model name and try again.", "extra": {} } }
```
[`/v1/embeddings`](/router/embeddings/) and [`/v1/systemone`](/router/decisions/) respond in the same format.
Messages (Anthropic): an object with `type: "error"` and a nested `error` with the fields `type`, `code`, and `message`. The Anthropic error type is coarse, with several causes mapped to one type, so it comes with a `code` that has the same value as in the OpenAI format. The details of the rejection, if there are any, are in `details`.
```json
{ "type": "error", "error": { "type": "not_found_error", "code": "model_not_found", "message": "Model 'nope/nope' is not available. Check the model name and try again." } }
```
Responses: an `error` object with the fields `type`, `code`, and `message`, plus the optional `param` and `details`. `details` holds the same details as `extra` in the OpenAI format.
```json
{ "error": { "type": "not_found_error", "code": "model_not_found", "message": "Model 'nope/nope' is not available. Check the model name and try again." } }
```
An API key rejection on `/v1/chat/completions` and `/v1/messages` comes in a different, short form; see [unauthorized](#unauthorized).
## Codes
[Section titled “Codes”](#codes)
| HTTP | `code` | When |
| ------------------- | ---------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `400` | `invalid_model`, `feature_not_supported`, `provider_bad_request` | The request is invalid, or the requested feature is not supported |
| `400` | `model_endpoint_mismatch` | The endpoint does not serve this model’s class, see [Model classes](/router/models/#model-classes) |
| `400` | `invalid_output_modalities` | Unknown `output_modalities` value in `GET /v1/models` |
| `400` | `provider_context_length_exceeded` | The input does not fit in the model’s context window |
| `400` | `dlp_multi_choice_unsupported` | `n` is greater than 1 in a request with DLP |
| `401` | `authentication_required`, `invalid_api_key` | No API key, or the key is not valid. On `/v1/chat/completions` and `/v1/messages` the response has no code, see [unauthorized](#unauthorized) |
| `402` | `insufficient_funds` | Not enough funds for the request |
| `403` | `policy_violation` | The request is blocked by an access policy |
| `403` | `dlp_violation` | The request is blocked by DLP, see [Plugins](/router/plugins/#block-error) |
| `403` | `provider_forbidden` | The model’s provider refused the request because of its content |
| `404` | `model_not_found` | The model is not in the catalog |
| `408` | `provider_timeout` | The model did not respond in time |
| `413` | `payload_too_large`, `file_too_large`, `text_content_too_large` | The body, an attachment, or the text is too large, see [Limits](/router/limits/) |
| `413` | `provider_payload_too_large` | The provider’s limit for this model is lower than ours, and the request did not fit in it |
| `422` | `validation_error` | The request failed validation (for example, `model` is not in the `/` format) |
| `429` | `provider_rate_limited` | The model limited the request rate |
| `429` | `api_key_limit_exceeded` | The key’s spending limit is reached. The time the counter resets is in `extra.reset_at` |
| `500`, `502`, `503` | `internal_service_error` | An error on our side |
| `502` | `provider_unavailable`, `provider_model_down` | The model is temporarily unavailable |
| `503` | `service_unavailable` | The router is under load. The retry interval is in the `Retry-After` header |
| `503` | `dlp_policy_unavailable` | The DLP policy for the key could not be fetched. The retry interval is in `Retry-After` |
The `waibee/auto` model has its own `422` codes (`auto_routing_no_match`, `auto_routing_request_too_large`, `auto_routing_caching_unavailable`, `auto_routing_missing_context`); see [Autorouting](/router/autorouting/#errors).
## Messages and Responses types
[Section titled “Messages and Responses types”](#messages-and-responses-types)
| HTTP | `error.type` | When |
| -------------------------- | ----------------------- | ----------------------------------------------------------------------------------------------------------- |
| `400`, `413`, `422` | `invalid_request_error` | The request is invalid or too large |
| `401` | `authentication_error` | No API key, or the key is not valid. On `/v1/messages` the body is short, see [unauthorized](#unauthorized) |
| `402`, `429` | `rate_limit_error` | Not enough funds, the key’s spending limit is used up, or the model limited the request rate |
| `403` | `permission_error` | The request is blocked by an access policy, DLP, or the provider’s moderation |
| `404` | `not_found_error` | The model is not in the catalog |
| `408`, `500`, `502`, `503` | `api_error` | A model timeout or outage, an internal error, or load |
Exceptions to the table:
* on `/v1/messages`, the code `provider_unavailable` comes as `overloaded_error`, and on `/v1/responses` as `api_error`;
* `invalid_model` comes as `not_found_error`;
* `auto_routing_*` and `dlp_multi_choice_unsupported` come as `api_error`.
One type covers several causes: `permission_error` comes for both `policy_violation` and `dlp_violation`. So branch on `code`, not on the type.
The `param` field on `/v1/responses` names the parameter that caused the rejection. It is not always present; see [Responses format](/router/responses-api/).
## What to do
[Section titled “What to do”](#what-to-do)
### unauthorized
[Section titled “unauthorized”](#unauthorized)
`401`. The API key is missing, wrong, revoked, or expired. The response shape depends on the endpoint. On `/v1/chat/completions` and `/v1/messages`, the body is short, `{"error":"unauthorized"}`, with no `code` field. On `/v1/responses`, `/v1/embeddings`, `/v1/systemone`, and `GET /v1/models`, the usual envelope comes back with the code `authentication_required` (the `Authorization` header is missing or malformed) or `invalid_api_key` (the key is not valid). How to pass the key: [Authentication](/router/authentication/).
### insufficient\_funds
[Section titled “insufficient\_funds”](#insufficient_funds)
`402`. There are not enough funds for the request. Top up your balance; retries will not help. `waibee/auto` needs a minimum balance; see [Autorouting](/router/autorouting/#errors).
### model\_not\_found
[Section titled “model\_not\_found”](#model_not_found)
`404`. The model is not in your key’s catalog. Check the ID against `GET /v1/models`; see [Models](/router/models/).
### validation\_error
[Section titled “validation\_error”](#validation_error)
`422`. The request failed validation. `message` names up to three fields and the reason, for example `Invalid request: body.max_tokens: Field required`, and the full list is in `extra.errors` (in `details.errors` on `/v1/messages` and `/v1/responses`). Common causes are a model name without the provider prefix and too many messages or tools. See [Limits](/router/limits/).
### feature\_not\_supported
[Section titled “feature\_not\_supported”](#feature_not_supported)
`400`. The request asks for a feature the router does not provide:
* a provider’s server tool (`web_fetch`, `code_execution`, MCP), see [Tool calling](/router/tool-calling/);
* the `:online` or `:batch` suffix in the model name;
* `waibee/auto` on `/v1/embeddings` and `/v1/systemone`;
* server-side history storage on `/v1/responses`, see [Responses format](/router/responses-api/#what-the-router-does-not-do).
The field that caused the rejection comes as `param`: in `extra` on Chat Completions, in `details` on Messages, and directly in `error` on Responses.
### model\_endpoint\_mismatch
[Section titled “model\_endpoint\_mismatch”](#model_endpoint_mismatch)
`400`. The model is in the catalog, but this endpoint does not serve its class: an embeddings model on `/v1/chat/completions`, a chat model on `/v1/embeddings`, or a decisions model on any endpoint other than `/v1/systemone`. `extra` holds `model`, `model_class`, and `endpoint`; on `/v1/messages` and `/v1/responses` they are in `error.details`. Send the request to the endpoint for the class in `model_class`, or pick a model of the class you need. See [Model classes](/router/models/#model-classes).
### invalid\_output\_modalities
[Section titled “invalid\_output\_modalities”](#invalid_output_modalities)
`400`. `output_modalities` in `GET /v1/models` has a value the router does not recognize. The accepted values come in `extra.accepted`: `text`, `embeddings`, `decisions`, and `all`. See [Filtering by class](/router/models/#filtering-by-class).
### provider\_bad\_request
[Section titled “provider\_bad\_request”](#provider_bad_request)
`400`. The model rejected the request body. If the reason concerns your request, it comes in `message`: fix the body accordingly, because retrying the same request will not help.
### provider\_context\_length\_exceeded
[Section titled “provider\_context\_length\_exceeded”](#provider_context_length_exceeded)
`400`. The input does not fit in the model’s context window. Shorten the history or the attachments, or pick a model with a larger `context_length`. See [Models](/router/models/).
### provider\_rate\_limited
[Section titled “provider\_rate\_limited”](#provider_rate_limited)
`429`. The model limited the request rate. Retry with exponential backoff, and under sustained load spread it across models. See [Limits](/router/limits/).
### api\_key\_limit\_exceeded
[Section titled “api\_key\_limit\_exceeded”](#api_key_limit_exceeded)
`429`. The key’s spending limit for the period is reached. `extra.reset_at` holds the time the counter resets, and retries before then are pointless. You need another key or a higher limit.
### policy\_violation
[Section titled “policy\_violation”](#policy_violation)
`403`. The request is blocked by an access policy: for example, the model is not allowed for your group.
### dlp\_violation
[Section titled “dlp\_violation”](#dlp_violation)
`403`. DLP blocked the request because it found sensitive data in it. The findings are listed in `extra.dlp` (in `details.dlp` on `/v1/messages` and `/v1/responses`). See [Plugins](/router/plugins/#block-error).
The status is the same as for `policy_violation`, but the fix is different: the cause is the content of the request, not the key’s permissions. Remove what was found from the request or replace it with a placeholder. Another key will not help.
The check may be broader than what you sent in `plugins.dlp`, and it may even run without that field: a key can have its own policy, and that policy applies as the minimum. See [API key policy](/router/plugins/#api-key-policy).
### dlp\_policy\_unavailable
[Section titled “dlp\_policy\_unavailable”](#dlp_policy_unavailable)
`503`. The DLP policy for your key could not be fetched, so the request was rejected rather than let through unchecked. Retry after the interval in `Retry-After`.
### payload\_too\_large
[Section titled “payload\_too\_large”](#payload_too_large)
`413`. The whole request body is too large. The codes `file_too_large` and `text_content_too_large` mean that a single attachment or the total text is over the limit. The values are in [Limits](/router/limits/).
### provider\_forbidden
[Section titled “provider\_forbidden”](#provider_forbidden)
`403`. The model’s provider refused to process the content of the request, usually because its own moderation flagged it. The refusal concerns the text, not your key or your permissions. Rephrase the request or pick another model.
### provider\_payload\_too\_large
[Section titled “provider\_payload\_too\_large”](#provider_payload_too_large)
`413`. The request passed our [limits](/router/limits/) but not the provider’s, which is lower for some models. Shorten the input or pick a model with a larger context.
### provider\_timeout
[Section titled “provider\_timeout”](#provider_timeout)
`408`. The model did not respond in time. Retry; this happens more often on reasoning models with a high effort level. See [Reasoning](/router/reasoning/).
### provider\_unavailable
[Section titled “provider\_unavailable”](#provider_unavailable)
`502`. The model did not serve the request: it is unavailable or overloaded, it could not be reached, or its response did not match the request. Retry. If the error keeps happening on one model, try another; if it happens on all of them, contact support. `provider_model_down` means the same thing.
### service\_unavailable
[Section titled “service\_unavailable”](#service_unavailable)
`503`. The router is under load. Retry after the interval in the `Retry-After` header.
### internal\_service\_error
[Section titled “internal\_service\_error”](#internal_service_error)
`500`, less often `502` or `503`. An error on our side. Retry the request; if the error keeps happening, contact support and include the value of the `x-waibee-trace-id` header from the response.
### auto\_routing\_\*
[Section titled “auto\_routing\_\*”](#auto_routing_)
`422`. Errors in picking a model for `waibee/auto`, covered in [Autorouting](/router/autorouting/#errors).
# FAQ
> Common questions about Waibee Router.
## How do I specify the model?
[Section titled “How do I specify the model?”](#how-do-i-specify-the-model)
As `/` from the `GET /v1/models` catalog, for example `anthropic/claude-sonnet-4.6`. A name without the provider is accepted by `/v1/messages` (Claude models) and `/v1/systemone` (TypeSafe models); see [Model ID format](/router/models/#id-format). `waibee/auto` leaves the choice of model to the router; see [Autorouting](/router/autorouting/).
## Which API formats are supported?
[Section titled “Which API formats are supported?”](#which-api-formats-are-supported)
Three: OpenAI Chat Completions (`POST /v1/chat/completions`), OpenAI Responses (`POST /v1/responses`), and Anthropic Messages (`POST /v1/messages`). How they differ: [Three request formats](/router/#three-request-formats).
Models of other classes have two more endpoints: [embeddings](/router/embeddings/) in OpenAI Embeddings format (`POST /v1/embeddings`) and [decisions](/router/decisions/) in System One API format (`POST /v1/systemone`).
## How do I authenticate?
[Section titled “How do I authenticate?”](#how-do-i-authenticate)
With an `sk_live_...` key in the `Authorization: Bearer` header. `/v1/messages` also accepts `x-api-key`. See [Authentication](/router/authentication/).
## How do I turn on streaming?
[Section titled “How do I turn on streaming?”](#how-do-i-turn-on-streaming)
Set `"stream": true`. Chat Completions and Responses end the stream with the line `data: [DONE]`, and Messages with the `message_stop` event. Event formats: [Streaming](/router/streaming/) and [Responses](/router/responses-api/#streaming).
## Is reasoning effort `max` supported?
[Section titled “Is reasoning effort max supported?”](#is-reasoning-effort-max-supported)
Yes, on all three endpoints: in `reasoning_effort` on `/v1/chat/completions`, in `output_config.effort` on `/v1/messages`, and in `reasoning.effort` on `/v1/responses`. The router passes the level to the model, and whether it accepts `max` depends on the model. See [Reasoning](/router/reasoning/).
## Is tool calling supported?
[Section titled “Is tool calling supported?”](#is-tool-calling-supported)
Yes, on all three endpoints, with up to 10,000 tools per request. Of the server tools, only web search works. See [Tool calling](/router/tool-calling/).
## Can I get a response that strictly follows a JSON Schema?
[Section titled “Can I get a response that strictly follows a JSON Schema?”](#can-i-get-a-response-that-strictly-follows-a-json-schema)
Yes: `response_format` with the type `json_schema` on `/v1/chat/completions`, and `output_config.format` on `/v1/messages`. See [Structured outputs](/router/structured-outputs/).
## Is there a requests-per-second limit?
[Section titled “Is there a requests-per-second limit?”](#is-there-a-requests-per-second-limit)
There is no fixed limit per key. You get `429` when the model has limited the request rate (`provider_rate_limited`) or the key’s spending limit is used up (`api_key_limit_exceeded`). What to do in each case: [Request rate](/router/limits/#request-rate).
## Is there prompt caching?
[Section titled “Is there prompt caching?”](#is-there-prompt-caching)
Yes. Claude models cache when you add a `cache_control` marker, and OpenAI models cache a repeated prefix on their own. See [Prompt caching](/router/prompt-caching/).
## What are the request limits?
[Section titled “What are the request limits?”](#what-are-the-request-limits)
The body can be up to 100 MB, one attachment up to 50 MB, and the text up to 15 MB. A request holds up to 100,000 messages and up to 10,000 tools. Details: [Limits](/router/limits/).
## Where can I find the error codes?
[Section titled “Where can I find the error codes?”](#where-can-i-find-the-error-codes)
In [Errors](/router/errors/). Chat Completions returns errors in OpenAI format, Messages in Anthropic format, and Responses in its own format with a `param` field.
# All integrations
> Set up apps and SDKs to work with Waibee Router.
Pick an app or SDK to see how to connect it to Waibee Router.
## Apps
[Section titled “Apps”](#apps)
* [Waibee Code](/router/integrations/waibee-code/)
* [Claude Code](/router/integrations/claude-code/)
* [Codex CLI](/router/integrations/codex/)
* [OpenCode](/router/integrations/opencode/)
* [Hermes Agent](/router/integrations/hermes/)
* [pi](/router/integrations/pi/)
## SDKs and compatible clients
[Section titled “SDKs and compatible clients”](#sdks-and-compatible-clients)
* [OpenAI](/router/integrations/openai-compatible/)
* [Anthropic](/router/integrations/anthropic-compatible/)
To call the API directly, start with the [Quickstart](/router/quickstart/).
# Anthropic-compatible clients
> Any Anthropic Messages API client works with Waibee Router once you change the base URL.
A client that uses the Anthropic Messages API connects to Waibee with no code changes. You set two values:
* **Base URL**: `https://api.waibee.com`
* **API key**: `sk_live_...`
Requests go to `POST /v1/messages`. Pass the key in `x-api-key` or in `Authorization: Bearer`; see [Authentication](/router/authentication/). The `max_tokens` field is required.
Specify the model as `/` from the [catalog](/router/models/). The router converts Anthropic names without a prefix, such as `claude-sonnet-4-6` or the same name with a date at the end, to the catalog form on its own. A ready-made recipe for Claude Code is on a [separate page](/router/integrations/claude-code/).
## SDK
[Section titled “SDK”](#sdk)
python
```python
import anthropic
client = anthropic.Anthropic(
base_url="https://api.waibee.com",
api_key="sk_live_...",
)
msg = client.messages.create(
model="anthropic/claude-sonnet-4.6",
max_tokens=1024,
messages=[{"role": "user", "content": "Hello!"}],
)
print(msg.content[0].text)
```
node
```ts
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic({
baseURL: "https://api.waibee.com",
apiKey: process.env.WAIBEE_API_KEY,
});
const msg = await client.messages.create({
model: "anthropic/claude-sonnet-4.6",
max_tokens: 1024,
messages: [{ role: "user", content: "Hello!" }],
});
console.log(msg.content[0].text);
```
## curl
[Section titled “curl”](#curl)
```bash
curl https://api.waibee.com/v1/messages \
-H "x-api-key: $WAIBEE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "anthropic/claude-sonnet-4.6",
"max_tokens": 1024,
"messages": [{ "role": "user", "content": "Hello!" }]
}'
```
Tip
The response comes in Anthropic format (`content`, `stop_reason`, `usage`), and with `"stream": true` the stream arrives as SSE events in Anthropic format. All parameters are described in the [API Reference](/router/api/).
# Claude Code
> Connect Claude Code to Waibee Router through the Anthropic Messages API.
Claude Code speaks the **Anthropic Messages API**. Waibee Router accepts requests in the same format on `POST /v1/messages`, so Claude Code connects to it through environment variables, with no changes to the client itself.
## Environment variables
[Section titled “Environment variables”](#environment-variables)
| Variable | Value |
| ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ANTHROPIC_BASE_URL` | The router’s base URL, without the `/v1/messages` suffix (the client adds the path itself). |
| `ANTHROPIC_AUTH_TOKEN` | Your Waibee API key (`sk_live_...`). Sent as `Authorization: Bearer`. |
| `ANTHROPIC_API_KEY` | An empty string, so the client does not send a different key from the environment in `x-api-key`. If both headers arrive, the router takes the key from `x-api-key`. |
```bash
export WAIBEE_API_KEY="sk_live_..."
export ANTHROPIC_BASE_URL="https://api.waibee.com"
export ANTHROPIC_AUTH_TOKEN="$WAIBEE_API_KEY"
export ANTHROPIC_API_KEY=""
claude
```
Note
Claude Code reads the variables from the shell environment or from the `env` block in `~/.claude/settings.json`. The `env` block in the project settings (`.claude/settings.local.json`) takes effect only after the first launch, once you confirm folder trust. So for the first launch, set the variables in your shell profile (`~/.zshrc`) or in `~/.claude/settings.json`; otherwise Claude Code opens the Anthropic sign-in screen. Do not put the key in the project’s `.claude/settings.json`: that file is committed to the repository.
A key from the variable takes precedence over a saved claude.ai sign-in. If Claude Code warns about two authentication sources at startup, run `/logout`, and only the Waibee key remains.
## Choosing a model
[Section titled “Choosing a model”](#choosing-a-model)
* **For one run:** `claude --model `. Both catalog IDs and Anthropic names without a prefix work; see [Anthropic-compatible clients](/router/integrations/anthropic-compatible/).
* **By role:** `ANTHROPIC_DEFAULT_OPUS_MODEL`, `ANTHROPIC_DEFAULT_SONNET_MODEL`, and `ANTHROPIC_DEFAULT_HAIKU_MODEL` set the models behind the `opus`, `sonnet`, and `haiku` aliases, and `CLAUDE_CODE_SUBAGENT_MODEL` sets the subagent model. They accept both short Anthropic names and catalog IDs.
* **Background tasks:** with the key in `ANTHROPIC_AUTH_TOKEN`, Claude Code runs them on the main model. To run them on a cheaper one, set it in `ANTHROPIC_DEFAULT_HAIKU_MODEL`.
For Claude models, pass the short Anthropic names: `claude-sonnet-4-6`, `claude-haiku-4-5`. Claude Code interprets catalog IDs its own way: it does not recognize `anthropic/claude-haiku-4.5`, warns about it, and keeps the session within 200,000 tokens. It also mistakes `anthropic/claude-sonnet-4.6` for the deprecated Claude Sonnet 4. For a model Claude Code does not know, the `CLAUDE_CODE_MAX_CONTEXT_TOKENS` variable sets the context window.
## Extension for VS Code and Cursor
[Section titled “Extension for VS Code and Cursor”](#extension-for-vs-code-and-cursor)
The extension checks the key before it starts Claude Code, and it takes the variables from its own `claudeCode.environmentVariables` setting in the editor’s user settings. Values from `~/.claude/settings.json` do not reach this check.
settings.json
```json
{
"claudeCode.environmentVariables": [
{ "name": "ANTHROPIC_BASE_URL", "value": "https://api.waibee.com" },
{ "name": "ANTHROPIC_AUTH_TOKEN", "value": "sk_live_..." }
]
}
```
## Checking the setup
[Section titled “Checking the setup”](#checking-the-setup)
In a Claude Code session, run `/status`. The `Anthropic base URL` line should show `https://api.waibee.com`, and the `Auth token` line should name `ANTHROPIC_AUTH_TOKEN`.
The router has no `/v1/messages/count_tokens` endpoint. Without it, Claude Code estimates tokens from the character count, so `/context` shows approximate numbers.
# Codex CLI
> Connect Codex CLI to Waibee Router through the Responses API.
Codex CLI speaks the **Responses API** and no other format. Waibee Router accepts this format on `POST /v1/responses`, so Codex connects to it through its own config, with no changes to the client itself.
## Configuration
[Section titled “Configuration”](#configuration)
Add the provider to `~/.codex/config.toml`:
\~/.codex/config.toml
```toml
model = "openai/gpt-5.1-codex"
model_provider = "waibee"
model_reasoning_effort = "low"
[model_providers.waibee]
name = "Waibee"
base_url = "https://api.waibee.com/v1"
env_key = "WAIBEE_API_KEY"
wire_api = "responses"
```
Define the provider in `~/.codex/config.toml` specifically. Codex does not read the `model_provider` and `model_providers` keys from a project’s `.codex/config.toml`, and in a trusted project it warns about this at startup.
`model_reasoning_effort` is required here. Some reasoning models cannot run with reasoning turned off. If the config does not set an effort level, Codex sends the request without one. Such a model reads that as a request to turn reasoning off and rejects it:
```json
{"error": {"code": "provider_bad_request", "message": "Reasoning is mandatory for this endpoint and cannot be disabled."}}
```
Pick a level the model supports; for `openai/gpt-5.1-codex` these are `low`, `medium`, and `high`.
```bash
export WAIBEE_API_KEY="sk_live_..."
codex
```
On Windows, set the variable with `setx WAIBEE_API_KEY "sk_live_..."`. It appears only in new terminal windows, so start Codex from a new window.
| Field | What it holds |
| ---------- | ----------------------------------------------------------------------------------------------------------------- |
| `base_url` | The base URL with the `/v1` suffix. The client adds the `/responses` path itself. |
| `env_key` | The name of the environment variable Codex reads the key from. The key itself does not go in the config. |
| `wire_api` | Only `"responses"`, which is also the default. With `"chat"`, Codex does not start: it no longer has that option. |
## Choosing a model
[Section titled “Choosing a model”](#choosing-a-model)
`model` takes an ID from the [catalog](/router/models/) in the form `provider/model`. A model being in the catalog does not guarantee that it supports Responses.
```toml
model = "anthropic/claude-sonnet-5"
```
To set the model for one run, use the flag:
```bash
codex --model anthropic/claude-sonnet-5
```
The reasoning level is set by `model_reasoning_effort` from the configuration above, for example `low`, `medium`, or `high`. The router passes the value to the model as is.
## Context window
[Section titled “Context window”](#context-window)
Codex has no table of context windows for catalog models. For a model it does not know, it assumes a window of 272,000 tokens, and that number decides when the client starts compacting the session history. If the model’s window is smaller, declare it yourself, using the model’s `context_length` from the [catalog](/router/models/). For example, for a model with a 200,000-token window:
\~/.codex/config.toml
```toml
model_context_window = 200000
```
This key cannot raise the window above 272,000: for a model it does not know, Codex caps the value at that limit.
Codex has no setting for the maximum response length: its config has no key like `model_max_output_tokens`.
## Checking the setup
[Section titled “Checking the setup”](#checking-the-setup)
```bash
codex exec "Say OK and nothing else"
```
If the model replies, the setup works.
## Token usage
[Section titled “Token usage”](#token-usage)
Codex resends the whole conversation on every turn. The router does not store history, and Codex does not use server-side state, so a long session is billed as many requests with growing input.
[Prompt caching](/router/prompt-caching/) softens this: from the second turn on, the unchanged beginning of the conversation is billed at a reduced price. In a typical session most of the input is cached, and you can see it in the response:
```json
"usage": {
"input_tokens": 9492,
"input_tokens_details": {"cached_tokens": 9344},
"output_tokens": 10
}
```
## Web search
[Section titled “Web search”](#web-search)
By default, Codex puts the built-in `web_search` tool in every request. The router runs the search: Codex receives a response built from the results, along with a `waibee:web_search` item that holds the query and the list of sources. Codex calls its own tools as usual, and the search does not interfere with them.
Successful searches are billed separately from tokens. If you do not need search, remove the tool with the line `web_search = "disabled"` in `~/.codex/config.toml`.
How many searches the model makes, what they cost, and what happens when search is unavailable: [Web search](/router/web-search/).
## Troubleshooting
[Section titled “Troubleshooting”](#troubleshooting)
**`Model metadata for ... not found`** at startup. Codex keeps its own table of known models, and our IDs are not in it. The warning is about that table, not about the router’s response: requests go through, tools are called, and responses arrive. Along with the metadata, Codex also loses the model’s real context window. See [Context window](/router/integrations/codex/#context-window).
You cannot get rid of the warning by replacing `env_key` with a `[model_providers.waibee.auth]` block that runs a command: Codex then tries to refresh the model catalog in its own format, fails to parse our response, and prints it in full to the log. The warning stays anyway. Keep `env_key`.
**`codex exec` refuses to run outside a git repository.** Add `--skip-git-repo-check` or run it inside a repository.
**HTTP 400 with `feature_not_supported`.** The request uses an unsupported feature, or the model does not work on Responses. The response names the reason. Details: [Responses format](/router/responses-api/#what-the-router-does-not-do).
**HTTP 402.** Your balance does not have enough funds; see [Errors](/router/errors/#insufficient_funds).
## Next steps
[Section titled “Next steps”](#next-steps)
* [Responses format](/router/responses-api/): the format itself, streaming, tool calling
* [Errors](/router/errors/): codes and what to do about them
* [Limits](/router/limits/): maximum sizes and request rate
# Hermes Agent
> Connect Hermes Agent by Nous Research to Waibee Router through config.yaml, with no plugins.
[Hermes Agent](https://hermes-agent.nousresearch.com/) is an agent by Nous Research with a terminal interface, gateways to messengers, its own skills, and a scheduler. It can take its model from any OpenAI-compatible endpoint, so Waibee connects with a config change.
Install Hermes (see [its documentation](https://hermes-agent.nousresearch.com/docs/)):
```bash
curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash
```
## 1. API key
[Section titled “1. API key”](#1-api-key)
Hermes reads the key from its own `.env`:
\~/.hermes/.env
```bash
WAIBEE_API_KEY=sk_live_...
```
## 2. Provider in config.yaml
[Section titled “2. Provider in config.yaml”](#2-provider-in-configyaml)
\~/.hermes/config.yaml
```yaml
model:
provider: "custom"
base_url: "https://api.waibee.com/v1"
api_key: "${WAIBEE_API_KEY}"
default: "anthropic/claude-sonnet-4.6"
```
`provider: "custom"` is the option for any OpenAI-compatible endpoint, so `base_url` goes **with** the `/v1` suffix: requests go to `POST /v1/chat/completions`.
The same without an editor:
```bash
hermes config set model.provider custom
hermes config set model.base_url https://api.waibee.com/v1
hermes config set model.api_key '${WAIBEE_API_KEY}'
hermes config set model.default anthropic/claude-sonnet-4.6
```
## 3. Run
[Section titled “3. Run”](#3-run)
```bash
hermes doctor # check the configuration and the key
hermes # interactive session
hermes chat -q "what does this repository do?" --oneshot # one-off request
hermes chat -q "..." -m google/gemini-3.6-flash # a different model for one run
```
Give the full model ID as it appears in the catalog: `/`. `waibee/auto` works too; then the router picks the model. See [Autorouting](/router/autorouting/).
Available IDs:
```bash
curl -s https://api.waibee.com/v1/models \
-H "Authorization: Bearer $WAIBEE_API_KEY" | jq -r '.data[].id'
```
## API key through OpenAI variables
[Section titled “API key through OpenAI variables”](#api-key-through-openai-variables)
The second working option is to present Waibee to Hermes as the OpenAI API with a different address.
\~/.hermes/config.yaml
```yaml
model:
provider: "openai-api"
default: "anthropic/claude-sonnet-4.6"
api_mode: "chat_completions"
```
\~/.hermes/.env
```bash
OPENAI_API_KEY=sk_live_...
OPENAI_BASE_URL=https://api.waibee.com/v1
```
The advantage of this option: the interactive model picker (`hermes model`) loads its list from `GET /v1/models`, so you see the catalog right in the picker.
## What is supported
[Section titled “What is supported”](#what-is-supported)
* Hermes tools (reading files, running commands, search) work as usual: Hermes calls them through tool calling. See [Tool calling](/router/tool-calling/).
* `agent.reasoning_effort` sets the reasoning level; see [Reasoning](/router/reasoning/).
## Troubleshooting
[Section titled “Troubleshooting”](#troubleshooting)
**`HTTP 401: {"error":"unauthorized"}` with `provider: "custom"`.** If the `WAIBEE_API_KEY` variable is not set, Hermes leaves the string `${WAIBEE_API_KEY}` as is and sends it instead of the key. Check `hermes config get model.api_key`.
**`422 validation_error`.** The ID has no provider prefix. Use the full ID, for example `anthropic/claude-sonnet-4.6`.
**`404 model_not_found`.** The model is not in your key’s catalog. Check the ID against `GET /v1/models`, called with the same key that Hermes uses. See [Models](/router/models/).
**`hermes doctor` says the key is not configured.** Check the path to `.env` in the `hermes doctor` output (by default `~/.hermes/.env`) and the substitution in `model.api_key`: `doctor` does not recognize `WAIBEE_API_KEY`.
# OpenAI-compatible clients
> Connect Chat Completions and Responses clients to Waibee Router.
Chat Completions and Responses clients connect once you set the base URL and API key. On Responses, send the history with every request; there is no server-side state. You set two values:
* **Base URL**: `https://api.waibee.com/v1`
* **API key**: `sk_live_...`
OpenAI has two formats, and the router serves both:
| Format | Endpoint | SDK method |
| ---------------- | --------------------------- | ---------------------------------- |
| Chat Completions | `POST /v1/chat/completions` | `client.chat.completions.create()` |
| Responses | `POST /v1/responses` | `client.responses.create()` |
Which one to use: [router overview](/router/#three-request-formats). How the second one works: [Responses format](/router/responses-api/).
Tools that use the Anthropic format have a [separate page](/router/integrations/anthropic-compatible/).
## SDK
[Section titled “SDK”](#sdk)
python
```python
from openai import OpenAI
client = OpenAI(
base_url="https://api.waibee.com/v1",
api_key="sk_live_...",
)
```
node
```ts
import OpenAI from 'openai';
const client = new OpenAI({
baseURL: 'https://api.waibee.com/v1',
apiKey: process.env.WAIBEE_API_KEY,
});
```
One client serves both endpoints:
python
```python
chat = client.chat.completions.create(
model="anthropic/claude-sonnet-4.6",
messages=[{"role": "user", "content": "ping"}],
)
resp = client.responses.create(
model="openai/gpt-5.1-codex",
input="ping",
)
print(resp.output_text)
```
## curl
[Section titled “curl”](#curl)
```bash
curl https://api.waibee.com/v1/chat/completions \
-H "Authorization: Bearer $WAIBEE_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "model": "anthropic/claude-sonnet-4.6", "messages": [{ "role": "user", "content": "ping" }] }'
```
A Responses request differs in the path and the body:
```bash
curl https://api.waibee.com/v1/responses \
-H "Authorization: Bearer $WAIBEE_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "model": "openai/gpt-5.1-codex", "input": "ping" }'
```
## Editors and agents
[Section titled “Editors and agents”](#editors-and-agents)
Tools such as **Cline** and **Continue** take a custom OpenAI-compatible endpoint in their settings. The general recipe:
| Setting | Value |
| ------------------- | --------------------------------------------------------------- |
| Provider / API type | OpenAI-compatible |
| Base URL | `https://api.waibee.com/v1` |
| API key | `sk_live_...` |
| Model | `/`, for example `anthropic/claude-sonnet-4.6` |
Tip
The router rejects an ID without the provider prefix with `422 validation_error`. Available IDs: [Models](/router/models/). The value `waibee/auto` leaves the choice of model to the router; see [Autorouting](/router/autorouting/).
# OpenCode
> Add Waibee to OpenCode as an OpenAI-compatible provider.
[OpenCode](https://opencode.ai) connects any OpenAI-compatible endpoint as a provider. Waibee Router serves `POST /v1/chat/completions`, so you only need to define the provider in `opencode.json`, either in the project root or in `~/.config/opencode/opencode.json` to make it available in every project.
## Configuration
[Section titled “Configuration”](#configuration)
opencode.json
```json
{
"$schema": "https://opencode.ai/config.json",
"provider": {
"waibee": {
"npm": "@ai-sdk/openai-compatible",
"name": "Waibee",
"options": {
"baseURL": "https://api.waibee.com/v1",
"apiKey": "{env:WAIBEE_API_KEY}"
},
"models": {
"anthropic/claude-sonnet-4.6": { "name": "Claude Sonnet 4.6" },
"openai/gpt-5.2": { "name": "GPT-5.2" },
"waibee/auto": { "name": "Auto (Waibee routing)" }
}
}
}
}
```
Caution
`baseURL` ends with `/v1`, not `/v1/chat/completions`: the client adds the path itself.
## API key
[Section titled “API key”](#api-key)
```bash
export WAIBEE_API_KEY="sk_live_..."
opencode
```
The `{env:WAIBEE_API_KEY}` syntax substitutes the key from the environment. If the variable is not set, OpenCode substitutes an empty string, and the router responds with `401`.
## Choosing a model
[Section titled “Choosing a model”](#choosing-a-model)
The `/models` command in OpenCode opens the model list. Pick a model from the `Waibee` provider, for example `waibee/auto` for [Autorouting](/router/autorouting/).
Models are added by hand
OpenCode does not fetch the catalog automatically: only the models listed in the `models` block are available. Add each model you need by hand, always with an ID in the `/` format.
To avoid adding models one at a time, you can build `models` from the catalog automatically:
```bash
curl -s https://api.waibee.com/v1/models \
-H "Authorization: Bearer $WAIBEE_API_KEY" \
| jq '[.data[] | {key: .id, value: {name: .name}}] | from_entries'
```
Paste the result into the `models` field of your provider in `opencode.json`.
# pi
> Connect the pi agent to Waibee Router through ~/.pi/agent/models.json, with no plugins.
[pi](https://pi.dev) is a coding agent for the terminal. It can work with any provider, so Waibee connects through a single config file, with no extension to write.
Install pi (see [its documentation](https://pi.dev/docs/latest/)):
```bash
npm install -g --ignore-scripts @earendil-works/pi-coding-agent
```
## 1. API key
[Section titled “1. API key”](#1-api-key)
```bash
export WAIBEE_API_KEY="sk_live_..."
```
## 2. Provider in models.json
[Section titled “2. Provider in models.json”](#2-provider-in-modelsjson)
pi reads custom providers from `~/.pi/agent/models.json`. Create the file if it does not exist. A minimal working config has the address, the protocol, the key, and at least one model ID:
\~/.pi/agent/models.json
```json
{
"providers": {
"waibee": {
"baseUrl": "https://api.waibee.com",
"api": "anthropic-messages",
"apiKey": "$WAIBEE_API_KEY",
"models": [
{ "id": "anthropic/claude-sonnet-4.6" },
{ "id": "waibee/auto" }
]
}
}
}
```
This is enough to start working. The other model fields are optional and affect what pi shows and allows: without them, it assumes a context window of 128,000 tokens, an output limit of 16,384, zero cost, and no reasoning or image input.
pi does not request a catalog for a custom provider, so the model list lives in the config. Take the IDs, context windows, and prices from `GET /v1/models`; see [Models](/router/models/).
### Generate the config from the catalog
[Section titled “Generate the config from the catalog”](#generate-the-config-from-the-catalog)
To avoid copying models by hand, build the file from the catalog. The script converts prices from per token to per million, which is what pi expects:
```bash
curl -s https://api.waibee.com/v1/models \
-H "Authorization: Bearer $WAIBEE_API_KEY" -o /tmp/waibee-models.json
jq '{providers: {waibee: {
baseUrl: "https://api.waibee.com",
api: "anthropic-messages",
apiKey: "$WAIBEE_API_KEY",
models: [ .data[]
| { id: .id,
name: .name,
reasoning: (((.capabilities.features // []) | index("reasoning")) != null),
input: ([(.capabilities.modality_input // [])[] | select(. == "text" or . == "image")]
| if length == 0 then ["text"] else . end),
contextWindow: (.context_length // 128000),
maxTokens: (.max_completion_tokens // 16384),
cost: {
input: ((.pricing.prompt // "0") | tonumber * 1000000),
output: ((.pricing.completion // "0") | tonumber * 1000000),
cacheRead: ((.pricing.input_cache_read // "0") | tonumber * 1000000),
cacheWrite: ((.pricing.input_cache_write // "0") | tonumber * 1000000) } } ] } } }' \
/tmp/waibee-models.json > /tmp/waibee-provider.json
```
Open `/tmp/waibee-provider.json` and move the `providers.waibee` object into `~/.pi/agent/models.json`, keeping the other providers and settings. If the file does not exist yet, create the `~/.pi/agent/` directory and copy the result there as `models.json`. When new models appear, you can run the generation again and update only `providers.waibee`.
### Describe models by hand
[Section titled “Describe models by hand”](#describe-models-by-hand)
This works if you need a short list with exact parameters. The values below only show the shape: query the catalog yourself for context windows and prices instead of copying them from here.
\~/.pi/agent/models.json
```json
{
"providers": {
"waibee": {
"name": "Waibee Router",
"baseUrl": "https://api.waibee.com",
"api": "anthropic-messages",
"apiKey": "$WAIBEE_API_KEY",
"models": [
{
"id": "anthropic/claude-sonnet-4.6",
"name": "Claude Sonnet 4.6",
"reasoning": true,
"input": ["text", "image"],
"contextWindow": 1000000,
"maxTokens": 128000,
"cost": { "input": 3, "output": 15, "cacheRead": 0.3, "cacheWrite": 3.75 }
}
]
}
}
}
```
`api: "anthropic-messages"` sends requests to `POST /v1/messages`, so `baseUrl` goes **without** `/v1`: the client adds the path itself. A model being in the catalog does not guarantee that it supports Messages.
## 3. Run
[Section titled “3. Run”](#3-run)
```bash
pi --list-models | grep waibee # check that the provider was picked up
pi --provider waibee --model anthropic/claude-sonnet-4.6
```
In interactive mode, switch models with the `/model` command. To avoid passing the flags every time, set defaults:
\~/.pi/agent/settings.json
```json
{ "defaultProvider": "waibee", "defaultModel": "anthropic/claude-sonnet-4.6" }
```
A one-off run with no interface:
```bash
pi -p --provider waibee --model anthropic/claude-sonnet-4.6 "which endpoints are declared in this repository?"
```
## Config fields
[Section titled “Config fields”](#config-fields)
| Field | Value |
| ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| `baseUrl` | `https://api.waibee.com` for `anthropic-messages`, `https://api.waibee.com/v1` for `openai-completions` |
| `api` | Protocol: `anthropic-messages` or `openai-completions` |
| `apiKey` | `"$WAIBEE_API_KEY"` reads the environment variable, `!command` runs a command that returns the key, and a plain string is used as the key |
| `models[].id` | Required. An ID from the catalog, strictly `/` |
| `models[].cost` | Prices per million tokens. The field is optional, but if it is present, all four keys are required: `input`, `output`, `cacheRead`, `cacheWrite` |
| `models[].reasoning` | `true` enables the `--thinking` levels for the model. Without it, only `off` is available |
| `models[].input` | `["text"]` or `["text", "image"]` |
| `models[].contextWindow`, `models[].maxTokens` | Context window and output limit |
To look up IDs, context windows, and prices quickly:
```bash
curl -s https://api.waibee.com/v1/models \
-H "Authorization: Bearer $WAIBEE_API_KEY" | jq -r '.data[] | "\(.id)\t\(.context_length)\t\(.pricing.prompt)"'
```
Catalog prices are per token, and pi expects them per million: multiply by 1,000,000. See [Tokens and usage](/router/usage/).
## Using the OpenAI-compatible endpoint
[Section titled “Using the OpenAI-compatible endpoint”](#using-the-openai-compatible-endpoint)
If you prefer Chat Completions, define the same provider like this:
\~/.pi/agent/models.json
```json
{
"providers": {
"waibee-openai": {
"baseUrl": "https://api.waibee.com/v1",
"api": "openai-completions",
"apiKey": "$WAIBEE_API_KEY",
"models": [
{ "id": "anthropic/claude-haiku-4.5" }
]
}
}
}
```
One file can hold several providers, and they do not interfere with each other.
Both options work. `anthropic-messages` is preferable: [prompt caching](/router/prompt-caching/) for Claude models works natively on it.
## Reasoning level
[Section titled “Reasoning level”](#reasoning-level)
```bash
pi --provider waibee --model anthropic/claude-sonnet-4.6 --thinking high
```
The values are `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, and `max`. pi sends `xhigh` and `max` only to models that have a `thinkingLevelMap` in `models.json`. Without it, pi lowers the level to one the model supports. Details: [Reasoning](/router/reasoning/).
## Troubleshooting
[Section titled “Troubleshooting”](#troubleshooting)
**The provider is missing from `--list-models`, and `--provider waibee` returns `Unknown provider`.** The file failed schema validation, and pi dropped every provider in it. pi names the reason: in interactive mode with a `models.json error` message, and in the `--list-models` output with the warning `Warning: errors loading models.json`. A common cause is an incomplete `cost`: all four keys are required, even when they are zero.
**`401 unauthorized`.** `WAIBEE_API_KEY` is not exported in the same shell where pi runs. Without the key, pi does not show the provider’s models in `/model` either. Check that the variable is set without printing the key itself: `test -n "$WAIBEE_API_KEY" && echo "key is set"`.
**`422 validation_error` or `404 model_not_found`.** `models[].id` has a name without the provider. On `openai-completions`, the router rejects such a name with `422`. On `anthropic-messages`, it treats the name as an Anthropic model, and models from other families return `404`. Use the full ID from the catalog, for example `anthropic/claude-sonnet-4.6`.
**The cost in the interface looks implausible.** pi calculates it from the `cost` block in your config, not from the router’s data. Update the numbers from the catalog.
# Waibee Code
> Waibee's own agent: the router is already connected, there is nothing to configure, and all it needs is an API key.
Waibee Code is our agent for the terminal, IDEs, and the browser. You do not need to connect it to the router: the agent has no other address. The only setup left is the API key.
```bash
waibee auth login
```
The key is stored in the system keychain, or, if the keychain is unavailable, in the `secrets.json` file in the [data directory](/code/waibee-directory/#global). The `WAIBEE_API_KEY` environment variable takes precedence over the stored key, which is convenient in CI.
## What you get
[Section titled “What you get”](#what-you-get)
The other clients in this section connect to the router through a compatible API, and that works. Waibee Code was built for the router, so it knows things about it that a compatible client cannot:
* **Autorouting.** You pick `waibee/auto` in `/model` like any other model, and the interface shows which model actually responded. If the selected model disappears from your account’s catalog, the terminal interface switches the session to `waibee/auto`. Details: [Autorouting](/router/autorouting/).
* **Prompt caching.** The agent places the cache breakpoints itself, based on the structure of its own requests. Details: [Prompt caching](/router/prompt-caching/).
* **Counters.** Token usage and how full the context window is show in the interface as you work, without going to the console.
* **Router errors.** A reached limit, insufficient funds, or an unavailable model shows up as a clear message rather than a response code.
## Next steps
[Section titled “Next steps”](#next-steps)
* [Waibee Code documentation](/code/): installation, ways to work, permissions, the web interface.
* [Quickstart](/code/quickstart/): from the API key to the first run.
* [Local web interface](/code/web/): chats, files, and diffs in the browser on your own computer.
* [Models](/router/models/): what is available to your key.
# Limits
> Limits on request size and structure, response time, request rate, per-key spending limits, and retries.
The router checks request size and structure before it calls the model. A request that is too large returns `413`; a request with an invalid structure returns `422` with the code `validation_error`.
## Request size
[Section titled “Request size”](#request-size)
| Limit | Value | Code when exceeded |
| ------------------------------------------------------------------------------------------------------------------------------------------ | ------ | ------------------------ |
| Whole request body | 100 MB | `payload_too_large` |
| One inline file (image, PDF), original size before base64 | 50 MB | `file_too_large` |
| All text in the request: messages, system prompt, tool descriptions, `input` on `/v1/embeddings`, `state` and questions on `/v1/systemone` | 15 MB | `text_content_too_large` |
The model also limits context size: see `context_length` and `max_completion_tokens` in the [catalog](/router/models/). Input that does not fit in the model’s context window returns `400` with the code `provider_context_length_exceeded`.
## Request structure
[Section titled “Request structure”](#request-structure)
| Limit | Value |
| ------------------------------------------------------------------------------------ | --------------- |
| Model ID length | 200 characters |
| Messages per request (`input` items on `/v1/responses`) | up to 100,000 |
| Tools (`tools`) per request | up to 10,000 |
| `input` items on `/v1/embeddings` | up to 2048 |
| Nesting depth of `state`, `instructions`, and option descriptions on `/v1/systemone` | up to 64 levels |
How many tools a specific model accepts is up to its provider, and that number may be lower. When the provider rejects the request, the router returns its own code, such as `provider_bad_request`; the reason may be given in `message`.
## Response time
[Section titled “Response time”](#response-time)
A non-streaming response must arrive within 5 minutes. For long generations, use `"stream": true`. Web search has a budget of 240 seconds. Without streaming, running out of it returns `408 provider_timeout`; in a stream, the budget is checked between steps and may end the response as incomplete.
## Request rate
[Section titled “Request rate”](#request-rate)
There is no fixed requests-per-second limit per key. The two `429` codes call for different handling:
| Code | What happened | What to do |
| ------------------------ | ---------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- |
| `provider_rate_limited` | The model limited the request rate | Retry with a delay. Under sustained load, spread it across several models |
| `api_key_limit_exceeded` | The key’s spending limit for the period is used up. `extra.reset_at` holds the time the counter resets (UTC, ISO 8601) | Wait for the reset, raise the key’s limit, or use another key |
Under peak load, the router responds with `503`, the code `service_unavailable`, and a `Retry-After` header.
## Retries
[Section titled “Retries”](#retries)
* **Retry only transient failures:** `408`, `429`, `500`, `502`, `503`. Other `4xx` codes are request errors, and a retry returns the same response. With `api_key_limit_exceeded`, retrying before `extra.reset_at` is pointless too.
* **Use exponential backoff with jitter.** When every client retries at the same moment, they create a second wave of load; random jitter added to the delay spreads it out.
* **Respect `Retry-After`.** If the header is present, wait at least that long before retrying.
* **Cap the number of attempts**, for example at three. After that, return the error to your own client.
* **A dropped connection does not cancel generation.** An interrupted stream is billed in full; see [Tokens and usage](/router/usage/#streaming). A retry after the drop is billed again.
For the full list of codes and error formats, see [Errors](/router/errors/).
# Migrating to Waibee
> What to change in your code when you move from OpenAI, Anthropic, or another gateway: the base URL, the key, and model IDs.
The router accepts requests in OpenAI and Anthropic formats, so when you migrate, you change the base URL, the key, and the model IDs. Your request code stays the same.
The public API has six endpoints: `GET /v1/models`, `POST /v1/chat/completions`, `POST /v1/responses`, `POST /v1/messages`, [`POST /v1/embeddings`](/router/embeddings/), and [`POST /v1/systemone`](/router/decisions/). There are no file uploads, batch processing, or token counting.
## From OpenAI
[Section titled “From OpenAI”](#from-openai)
```diff
client = OpenAI(
-base_url="https://api.openai.com/v1",
-api_key=os.environ["OPENAI_API_KEY"],
+base_url="https://api.waibee.com/v1",
+api_key=os.environ["WAIBEE_API_KEY"],
)
response = client.chat.completions.create(
-model="gpt-5.2",
+model="openai/gpt-5.2",
messages=[{"role": "user", "content": "Hello!"}],
)
```
What to keep in mind:
* **Model names carry a provider prefix.** `gpt-5.2` without the prefix is rejected with `422`; use `openai/gpt-5.2`. The exact IDs are in `GET /v1/models`.
* **Models from other vendors work with the same code.** The same client calls `anthropic/...` and `google/...` without switching SDKs.
* **`stream_options` is not required.** The counters arrive in the stream on their own, in the last chunk before `[DONE]`.
* **Responses does not store history on the server.** `previous_response_id`, `conversation`, `"store": true`, and `"background": true` are rejected with `feature_not_supported`; send the whole conversation in `input`. See [Responses](/router/responses-api/#what-the-router-does-not-do).
## From Anthropic
[Section titled “From Anthropic”](#from-anthropic)
```diff
client = anthropic.Anthropic(
-base_url="https://api.anthropic.com",
-api_key=os.environ["ANTHROPIC_API_KEY"],
+base_url="https://api.waibee.com",
+api_key=os.environ["WAIBEE_API_KEY"],
)
```
What to keep in mind:
* **The base URL has no `/v1`:** the SDK adds the path itself.
* **Short Claude model names work.** The router reads a name without a provider, in the form the SDK sends it (`claude-sonnet-4-6`), as `anthropic/claude-sonnet-4.6`. On `/v1/messages`, a short name always means an Anthropic model.
* **`cache_control`, `thinking`, `output_config`, and `document` blocks pass through as is.** You can pass the `max` level on all three endpoints; support depends on the model.
* **There is no MCP connector.** The `mcp_servers` field and MCP tools are rejected with `feature_not_supported`.
## From another gateway
[Section titled “From another gateway”](#from-another-gateway)
If your client is already set up for an OpenAI-compatible gateway, change the address and the key:
| Setting | Value |
| -------- | ----------------------------------------------------------------------------------------------------- |
| Base URL | `https://api.waibee.com/v1` for Chat Completions and Responses, `https://api.waibee.com` for Messages |
| API key | `sk_live_...` from the Waibee console |
| Model ID | `/` from `GET /v1/models` |
What the router does not have, in case you relied on it:
* **Routing fields in the request body** (provider lists, ordering, fallback chains). You choose a model by its explicit ID or through [Autorouting](/router/autorouting/). Build a fallback chain on the client side; see the [recipe](/router/cookbook/#fallback-model-on-failure).
* **Some of the provider’s server-side tools.** Web search works on all three endpoints, and the router runs it. Page fetching, code execution, and MCP tools are rejected with `feature_not_supported`. See [Tool calling](/router/tool-calling/).
* **Cost fields in the response.** Calculate cost from `usage` and the catalog prices. See [Tokens and usage](/router/usage/).
## Checking after the switch
[Section titled “Checking after the switch”](#checking-after-the-switch)
```bash
# 1. The key and access to the catalog
curl -s https://api.waibee.com/v1/models \
-H "Authorization: Bearer $WAIBEE_API_KEY" | jq -r '.data[].id' | head
# 2. One request on the model your code uses
curl -s https://api.waibee.com/v1/chat/completions \
-H "Authorization: Bearer $WAIBEE_API_KEY" -H "Content-Type: application/json" \
-d '{"model":"openai/gpt-5.2","messages":[{"role":"user","content":"ping"}]}' | jq '.model, .usage'
```
Then run your integration tests. The router has its own error codes (for example, `provider_rate_limited` and `insufficient_funds`); they are listed in [Errors](/router/errors/).
## Setting up ready-made tools
[Section titled “Setting up ready-made tools”](#setting-up-ready-made-tools)
To connect Claude Code, Codex CLI, OpenCode, and other clients, see [Integrations](/router/integrations/).
# Models
> Model IDs, model classes, and the catalog with capabilities and prices from /v1/models.
You name a model in a request by an ID of the form `/`, for example `anthropic/claude-sonnet-4.6`. Take exact IDs from the `GET /v1/models` catalog instead of writing them from memory: the list of models changes.
## ID format
[Section titled “ID format”](#id-format)
* `/v1/chat/completions`, `/v1/responses`, and `/v1/embeddings` accept only the full ID. A name without the provider (`claude-sonnet-4.6`) is rejected with `422` and the code `validation_error`.
* `/v1/messages` also accepts the short Claude model name that clients built on the Anthropic SDK send by default: `claude-sonnet-4-6` or `claude-haiku-4-5-20251001`. The router adds `anthropic/`, drops the trailing date, and replaces the hyphen between version digits with a dot, which gives `anthropic/claude-haiku-4.5`. It normalizes names like `anthropic/claude-sonnet-4-6` to the catalog form the same way on every endpoint.
* `/v1/systemone` accepts a TypeSafe model name without the provider, the way the TypeSafe SDK sends it: `jev-latest` is read as `typesafe/jev-latest`.
* The `:online` and `:batch` suffixes in a model name are not supported; the request is rejected with `feature_not_supported`.
Otherwise, the ID must match the catalog exactly, including the suffix after the colon if there is one. A name put together from memory or by guessing will fail; see [model\_not\_found](/router/errors/#model_not_found).
## Autorouting
[Section titled “Autorouting”](#autorouting)
The special ID `waibee/auto` hands the choice of model to the router: it picks one for the request and returns the model that actually ran in the response. If autorouting is available to your group, `waibee/auto` is in the catalog. This entry has no prices: the request is billed at the rates of the model that was picked. See [Autorouting](/router/autorouting/) for details.
## Catalog
[Section titled “Catalog”](#catalog)
`GET /v1/models` returns the models available to your key. Without parameters, it lists chat models; models of other classes are listed with [`output_modalities`](#filtering-by-class). Each entry has:
| Field | What it describes |
| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id` | The ID for the `model` field in a request |
| `name` | A human-readable name |
| `context_length` | The size of the context window |
| `max_completion_tokens` | The most tokens in a response |
| `pricing` | Prices in dollars per token, separately for input, output, cache reads, and cache writes |
| `model_class` | The model class: `chat`, `embedding`, or `decision`; see [Model classes](#model-classes) |
| `capabilities.modality_input` | What the model accepts as input (`text`, `image`, `audio`, `video`) |
| `capabilities.modality_output` | What it produces as output |
| `capabilities.features` | Supported capabilities: `tools`, `parallel_tool_calls`, `pdf_input`, `reasoning`, `response_format`, `structured_outputs`. Check that the value you need is present instead of comparing the whole set: the list may grow |
| `reasoning` | The reasoning levels the model accepts and the default level; `null` if the model does not reason. See [Reasoning](/router/reasoning/#model-levels) |
```bash
curl https://api.waibee.com/v1/models \
-H "Authorization: Bearer $WAIBEE_API_KEY"
```
```json
{
"object": "list",
"data": [
{
"id": "anthropic/claude-sonnet-4.6",
"object": "model",
"name": "Anthropic: Claude Sonnet 4.6",
"context_length": 1000000,
"max_completion_tokens": 128000,
"pricing": {
"prompt": "0.000003",
"completion": "0.000015",
"input_cache_read": "0.0000003",
"input_cache_write": "0.00000375",
"input_cache_write_1h": "0.000006"
},
"model_class": "chat",
"capabilities": {
"modality_input": ["image", "text"],
"modality_output": ["text"],
"features": ["pdf_input", "reasoning", "response_format", "structured_outputs", "tools"]
},
"reasoning": {
"efforts": ["none", "low", "medium", "high", "max"],
"default": "medium"
}
}
]
}
```
The response is compatible with OpenAI’s `GET /v1/models`, so clients that read this endpoint pick up the list on their own. Embedding and decision models are not in this list without the parameter, so a chat client will not offer them in its model picker.
## Choosing a model
[Section titled “Choosing a model”](#choosing-a-model)
1. Call `GET /v1/models` and find the `id` you need.
2. Match `capabilities` against your task: image input shows in `modality_input`, while [tool calling](/router/tool-calling/), [structured outputs](/router/structured-outputs/), [reasoning](/router/reasoning/), and [PDF](/router/attachments/) show in `features`.
3. If you need [prompt caching](/router/prompt-caching/), check `pricing`: models that support it have separate `input_cache_read` and `input_cache_write` prices.
4. Put the `id` into the `model` field of a request to the endpoint for its class; see [Model classes](#model-classes).
How to calculate the cost of a request from `pricing`: [Tokens and usage](/router/usage/#estimating-cost).
## Model classes
[Section titled “Model classes”](#model-classes)
The model class in the `model_class` field determines which endpoint the model works on:
| `model_class` | What the model does | Endpoints |
| ------------- | ------------------------------------------ | ------------------------------------------------------- |
| `chat` | Replies to a conversation with text | `/v1/chat/completions`, `/v1/messages`, `/v1/responses` |
| `embedding` | Turns text into a vector | [`/v1/embeddings`](/router/embeddings/) |
| `decision` | Answers typed questions with probabilities | [`/v1/systemone`](/router/decisions/) |
A model sent to an endpoint of another class is rejected with `400` and the code `model_endpoint_mismatch`: for example, an embedding model on `/v1/chat/completions` or a chat model on `/v1/embeddings`. The response’s `extra` holds `model`, `model_class`, and `endpoint` (on `/v1/messages` and `/v1/responses`, in `error.details`); see [Errors](/router/errors/#model_endpoint_mismatch).
`waibee/auto` picks only among chat models and appears only in their list.
## Filtering by class
[Section titled “Filtering by class”](#filtering-by-class)
The `output_modalities` parameter sets which classes of models `GET /v1/models` returns:
| Value | What the list contains |
| ------------ | ------------------------------------- |
| `text` | Chat models. The same as no parameter |
| `embeddings` | Embedding models |
| `decisions` | Decision models |
| `all` | Models of all classes |
Separate values with commas; case does not matter. An empty value works like `text`.
```bash
curl "https://api.waibee.com/v1/models?output_modalities=embeddings,decisions" \
-H "Authorization: Bearer $WAIBEE_API_KEY"
```
An unknown value is rejected with `400` and the code `invalid_output_modalities`, and the accepted values come back in `extra.accepted`:
```json
{
"error": {
"code": "invalid_output_modalities",
"message": "Unknown output_modalities: bogus.",
"extra": {"accepted": ["text", "embeddings", "decisions", "all"]}
}
}
```
# Plugins
> Request-level plugins. DLP: detecting, masking, and blocking sensitive data.
The router can run a request through extra plugins. You turn a plugin on for a single request with the `plugins` field in the body. One plugin is available today: **DLP** (data loss prevention).
## DLP
[Section titled “DLP”](#dlp)
DLP looks for sensitive data in a request (secrets and PII) and reacts according to the mode you choose. It checks `user` messages, tool results (`tool`), tool call arguments, and readable reasoning sent back in the history. Ordinary model answers in the history are checked too: in `mask` and `block` modes a finding there is masked, and the request goes through. The new answer the model writes is not checked. The system prompt is checked only when the key has a [policy](/router/plugins/#api-key-policy).
```json
{
"model": "anthropic/claude-sonnet-4.6",
"messages": [{ "role": "user", "content": "my email is user@example.com" }],
"plugins": {
"dlp": {
"mode": "mask"
}
}
}
```
The `plugins` field is optional, but leaving it out does not turn the check off: an API key can have its own DLP policy set by the group administrator. See [API key policy](/router/plugins/#api-key-policy).
Every `plugins.dlp` field (stop words, custom patterns, exceptions, `report_scope`) and its format is described in the [API Reference](/router/api/).
On `/v1/chat/completions`, DLP does not work with `n` greater than one: such a request is rejected with `400` and the code `dlp_multi_choice_unsupported`.
### Modes
[Section titled “Modes”](#modes)
Without `mode`, `alert` applies.
| `mode` | Behavior |
| ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `alert` | Findings come back in the response (`plugins.dlp`). Nothing is masked, withheld, or refused for the person |
| `mask` | Matches are replaced with [masks](/router/plugins/#masks) before the request reaches the model and restored in response text and tool call arguments. Reasoning keeps masks |
| `block` | A blocking finding can reject the request with `403` and the code `dlp_violation`; `extra.dlp` lists the findings. Model history, reasoning sent back, and `keep_masks` have the exceptions described here |
### Reasoning sent back
[Section titled “Reasoning sent back”](#reasoning-sent-back)
DLP scans readable text in `reasoning`, `reasoning_details`, `thinking` blocks on `/v1/messages`, and `reasoning` items on `/v1/responses`, regardless of role. In `mask` mode, response reasoning keeps masks as the provider sent them, including during streaming. Send retained signed blocks back unchanged to preserve their signatures.
* Unsigned reasoning text with a `mask` finding is masked again. A `block` finding replaces the whole text field with a withholding note.
* A signed block with a direct `mask` or `block` finding is removed whole after its tool loop has closed. This includes Responses reasoning items carrying `encrypted_content`. If tool results follow the block with no later user message, a direct finding instead rejects the request before the model call with `403` `dlp_violation`. On `/v1/messages`, text beside a `tool_result` does not close this tool loop.
* When a finding in a signed block comes only from a value found elsewhere in the request, an open tool loop continued with the same provider keeps that block and the previously seen prefix byte for byte unchanged. Newly added tool results are protected. After the loop closes, the block is removed; switching providers also removes foreign signed blocks.
When a Responses reasoning item is removed, subsequent model items are adjusted too; see [Responses API](/router/responses-api/#plugins).
### Data types (`entity_types`)
[Section titled “Data types (entity\_types)”](#data-types-entity_types)
Secrets and credentials: `ACCESS_TOKEN`, `API_KEY`, `BEARER_TOKEN`, `CERTIFICATE`, `JWT`, `PASSWORD`, `PRIVATE_KEY`, `PUBLIC_KEY`, `UNKNOWN_SECRET`.
PII and identifiers: `BANK_ACCOUNT`, `CREDIT_CARD`, `DOB`, `EMAIL`, `ID_NUMBER`, `IP_ADDRESS`, `MAC_ADDRESS`, `MEDICAL_ID`, `PHONE_NUMBER`, `POSTAL_CODE`, `SSN`, `SWIFT_BIC`, `TAX_ID`, `VEHICLE_VIN`, and the Russian `KPP`, `OGRN`, `OGRNIP`, and `OMS`. The detectors work on English and Russian text.
The field is optional. Without it, every type is checked except `UNKNOWN_SECRET`. That one is found by entropy analysis rather than a pattern, so it gives false positives on long random strings and is checked only when you list it.
The list is merged with the key’s policy
`entity_types` does not narrow the check to the list you send. If the key has a policy, its categories are added to yours, and the request is checked against the union. If you do not send the field, the policy’s categories apply, not the full list. A block on a category you did not ask for is expected behavior, not a bug.
### Masks
[Section titled “Masks”](#masks)
In `mask` mode the model sees a mask instead of the value. Here is one email address on its way through a conversation:
1. You send `my email is anna@example.com` with `"mode": "mask"`. The model receives `my email is `.
2. The model repeats the mask in its answer. You get `anna@example.com` back.
3. You ask the model to summarize the conversation and send `"keep_masks": true`. The summary you get keeps the mask instead of the address.
4. Later you send that summary and ask “what is my email?” with DLP on. The original message is no longer in the request, but the model repeats the mask from the summary, and you get the address back.
A mask has the form ``: the data type, the id of the encryption key, and the encrypted value in base64url. The same value sent with the same API key always gives the same mask, so the provider’s prompt cache keeps working. An email address is encrypted in lower case.
A mask belongs to the API key that produced it. The router turns it back into the value only in a request made with the same key and with DLP on: `plugins.dlp` in the request or a [policy](/router/plugins/#api-key-policy) on the key. This also works for a mask from an earlier request. Another API key, including one of the same group, gets the mask as plain text. So does the same key after it is reissued.
When the answer revealed at least one mask, the response carries `plugins.dlp_masked: true`: beside the findings in a regular response, on the last event of a stream. A client can use it to mark an answer that shows a protected value.
A value found directly under `mask` or `block` is protected when it appears elsewhere in the same request, including in model replies, tool results, system text, tool descriptions, and router web search traces sent back on the next turn. Repeated values add no findings to the report. A value found only by an `alert` rule does not protect its repetitions; the request stays unchanged.
In `mask` and `block`, a repeated value in an image or an old tool call can hide that containing part. If there is no containing part to hide, the router returns `403 dlp_violation` naming the place without the value. This covers free request parameters (`stop`, `metadata`, `tool_choice`, `user`, `safety_identifier`, `prompt_cache_key`, `web_search_options`), a declared tool name, and a key or number in SystemOne `questions`.
### Keeping masks: `keep_masks`
[Section titled “Keeping masks: keep\_masks”](#keeping-masks-keep_masks)
`plugins.dlp.keep_masks` (default `false`): with `true`, the response keeps masks in text, reasoning, and tool call arguments, the same in a stream and without one. Send it when you store the answer and send it back later, as with a summary in step 3: the stored text then holds masks, not values.
This includes a numeric tool parameter: it reaches you as the mask string, not the original number.
With `keep_masks: true` under `block`, a finding in message text is masked instead of rejecting the request. A finding in a place that cannot be replaced, such as an image URL, still rejects it.
`"dlp": {"keep_masks": true}` on its own does not turn DLP on. If the key has no policy, nothing is checked and nothing is revealed.
### When a mask is not revealed
[Section titled “When a mask is not revealed”](#when-a-mask-is-not-revealed)
The response then carries the mask as plain text, with no error. This happens when:
* the request had no DLP: no `plugins.dlp` and no policy on the key;
* `keep_masks` is `true`;
* the mask was made by another API key, or by this key before it was reissued;
* the mask was changed, or its key id is unknown;
* in a stream, a mask from an earlier request longer than 4096 characters arrived split between chunks. The same mask in a response without streaming is revealed.
Show such a mask to the person as a value hidden by DLP rules, and do not pass it to a tool or write it to a file.
This also applies to a damaged or cut fragment starting with `` does not count as a mask.
### Long history
[Section titled “Long history”](#long-history)
If the conversation history exceeds a DLP resource limit, the router replaces its oldest parts with findings until the rest fits. System and developer text stays in the request. The response carries `plugins.dlp_withheld` with the number of replaced parts (`leaves`) and their message indexes (`message_indexes`). If nothing can be removed, the whole request goes through. Only new content over the value or byte limit gets `413 scan_limit_exceeded` before the model call. In `alert`, the request stays unchanged and only an alert is recorded.
### Files in DLP requests
[Section titled “Files in DLP requests”](#files-in-dlp-requests)
The router does not decode inline text files. A text file in a `data:` URL or base64 `source`, or a file with no type, gets `400 feature_not_supported`. An untyped file passes as binary when its first bytes match `%PDF`, PNG (`\x89PNG`), JPEG (`\xff\xd8\xff`), `GIF8`, `OggS`, `ID3`, `fLaC`, ZIP (`PK\x03\x04`), RIFF with `WEBP` or `WAVE`, or `ftyp` at bytes 5-8. A file with a declared binary type also passes without its bytes being scanned. Send text files as text when DLP applies.
## API key policy
[Section titled “API key policy”](#api-key-policy)
An API key can have a DLP policy set by the group administrator. It acts as a **floor on strictness**: whether or not you send `plugins.dlp`, the request is checked at least against the policy. Clients written to the OpenAI and Anthropic standards have no field for a DLP config at all, and the policy applies to them too.
Your config still applies, but it can only make the check stricter:
| Field | How the merge treats it |
| -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `mode` | Applies to the rules you declared. If the policy has the same rule, the stricter mode wins: `alert` is weaker than `mask`, and `mask` is weaker than `block` |
| `entity_types` | The categories are combined. If you do not send the field, the policy’s categories apply |
| `stop_words` | The lists of forbidden literals are combined |
| `regexes` | The lists of custom patterns are combined |
| `allowlist` | Applies only to findings from your rules. An exception does not cancel a finding from a policy rule. A value you declare both as a stop word and as an exception stays forbidden |
| `report_scope` | Stays yours: it chooses only which findings come back, not whether the request is blocked |
Under a policy, two more fields are reset: `injected_context_names` and `acknowledged`. The first takes a marked message out of the check, which under a policy would be a way around it; the second has no effect even without a policy.
The reaction to a finding is set by whoever declared the rule that fired. If you listed `entity_types`, your mode applies to those categories, your stop words, and your patterns, and the administrator’s mode covers the rest of the policy’s categories. If you did not send `entity_types`, your mode applies to all of the policy’s categories.
You cannot see the contents of the administrator’s policy, and no separate error tells you that your settings were weakened: the stricter setting applies. A change to the administrator’s settings reaches the check in about a minute.
### When the policy is unavailable
[Section titled “When the policy is unavailable”](#when-the-policy-is-unavailable)
If the key’s policy cannot be fetched, the request is rejected with `503` and the code `dlp_policy_unavailable`, and the `Retry-After` header gives the interval before a retry. The check does not turn itself off: a request whose policy is unknown does not reach the model.
## Block error
[Section titled “Block error”](#block-error)
dlp\_violation, /v1/chat/completions
```json
{
"error": {
"code": "dlp_violation",
"message": "Request blocked: sensitive data detected",
"extra": {
"dlp": [
{
"category": "pii",
"entity_type": "EMAIL",
"message_index": 0,
"location": "messages[0].content",
"start": 12,
"end": 28,
"confidence": 0.99
}
],
"findings_count": 1,
"block_scope": "in_report_scope"
}
}
}
```
On `/v1/messages`, the body is in Anthropic format: the error type is `permission_error`, the machine-readable code sits next to it in the `code` field, and the findings are in `details`.
dlp\_violation, /v1/messages
```json
{
"type": "error",
"error": {
"type": "permission_error",
"code": "dlp_violation",
"message": "Request blocked: sensitive data detected",
"details": {
"dlp": [
{
"category": "pii",
"entity_type": "EMAIL",
"message_index": 0,
"location": "messages[0].content",
"start": 12,
"end": 28,
"confidence": 0.99
}
],
"findings_count": 1,
"block_scope": "in_report_scope"
}
}
}
```
A finding describes where the match is and what kind it is: the category (`secret`, `pii`, `custom`), the entity type, and the position in the text. It does not contain the values themselves, and they cannot be recovered from the response. A stop word finding has the entity type `STOP_WORD`, and a finding from your pattern has `CUSTOM_REGEX`; both have the category `custom`.
The `block_scope` field tells you where the reason for the block is: `in_report_scope` if it is among the listed findings, and `outside_report_scope` if it is in a part of the request we do not return.
`403` here is not about key permissions
With other vendors, `403` means the key lacks permissions, and the first reflex is to check access or try another key. Here the cause is the content of the request: the same key goes through as soon as the sensitive data is gone from the request. Tell the cases apart by the `dlp_violation` code, not by the status alone.
A block always comes as a regular HTTP response, including with `stream: true`. The decision is made before the stream opens, so a block never arrives as an event inside the stream.
## Embeddings and decisions
[Section titled “Embeddings and decisions”](#embeddings-and-decisions)
`/v1/embeddings` and `/v1/systemone` use the same modes, data types, and key policy. They have no messages: each element of `input` and each string in `state`, `instructions`, and `criteria` is checked the same way as a `user` message. On `/v1/systemone`, keys are checked too: the question keys and any object key inside `state`, `instructions`, and `criteria`. Numbers are checked; booleans are not; see [Decisions](/router/decisions/#dlp).
* A finding’s `location` is the path to the element (`input[1]`, `state.customer.email`), and `message_index` is `-1`.
* `report_scope` narrows nothing, and `block` rejects the whole request.
* On `/v1/systemone`, a direct `mask` or `block` finding in a key or number rejects the request. A repeated protected value in a `state` key or number hides its containing object; in a `questions` key or number it returns `403 dlp_violation` because there is no containing part to hide.
* Findings in `mask` and `alert` modes come back in the response’s `plugins.dlp`.
For details, see [Embeddings](/router/embeddings/#dlp) and [Decisions](/router/decisions/#dlp).
# Prompt caching
> Reusing a stable prompt prefix: how to turn it on, which models support it, and the usage fields.
If your requests repeat a large unchanging part (a system instruction, tool definitions, a long context), you can cache it. Repeat requests with the same prefix read it from the cache, which is cheaper and faster than processing it again.
Caching is explicit: you turn it on with markers in the request itself. There is no separate flag or parameter for it: the router passes the markers to the provider as is.
## Turning it on
[Section titled “Turning it on”](#turning-it-on)
Mark the block to cache with a `cache_control` marker in Anthropic format. The marker works on `/v1/chat/completions` and `/v1/messages`, in three places: `system` blocks, `tools` definitions, and `content` blocks inside messages.
The `ttl` field sets how long the cache lives: `"5m"` (the default) or `"1h"`.
```bash
curl https://api.waibee.com/v1/messages \
-H "x-api-key: $WAIBEE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "anthropic/claude-sonnet-4.6",
"max_tokens": 1024,
"system": [
{
"type": "text",
"text": "",
"cache_control": { "type": "ephemeral", "ttl": "1h" }
}
],
"messages": [{ "role": "user", "content": "Briefly summarize the main points" }]
}'
```
On `/v1/chat/completions`, put the marker on a `content` block:
```bash
curl https://api.waibee.com/v1/chat/completions \
-H "Authorization: Bearer $WAIBEE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "anthropic/claude-sonnet-4.6",
"messages": [{ "role": "user", "content": [
{ "type": "text", "text": "", "cache_control": { "type": "ephemeral" } },
{ "type": "text", "text": "Give me a TL;DR" }
] }]
}'
```
## Which models
[Section titled “Which models”](#which-models)
Claude models (Anthropic) support explicit caching. To check, look in the catalog: in `GET /v1/models`, the model’s `pricing` has `input_cache_read` and `input_cache_write` entries, the separate prices for reading and writing the cache. OpenAI models cache a repeated prefix automatically, with no markers, and the result shows up only in `usage`.
## Usage fields
[Section titled “Usage fields”](#usage-fields)
Cache hits show up in `usage`, and the fields depend on the endpoint.
`/v1/messages`:
```json
"usage": {
"input_tokens": 13,
"output_tokens": 4,
"cache_creation_input_tokens": 8802,
"cache_read_input_tokens": 0,
"cache_creation": { "ephemeral_1h_input_tokens": 8802, "ephemeral_5m_input_tokens": 0 }
}
```
`/v1/chat/completions`:
```json
"usage": {
"prompt_tokens": 8814,
"completion_tokens": 4,
"prompt_tokens_details": { "cached_tokens": 0, "cache_write_tokens": 8804 }
}
```
The first request writes the cache (`cache_creation_input_tokens` or `cache_write_tokens` is greater than zero). The next request with the same prefix reads from the cache (`cache_read_input_tokens` or `cached_tokens`).
## What to keep in mind
[Section titled “What to keep in mind”](#what-to-keep-in-mind)
* **The prefix must match byte for byte.** The beginning of the request up to the marker is cached; put everything that changes after it.
* **Lifetime.** The cache lives `5m` or `1h` from the last access. When it expires or the prefix changes, the cache is written again.
* **The minimum size and the number of cache points** are set by the model’s provider, not by the router: a prefix that is too short is not cached, and the number of `cache_control` markers per request is limited.
* **Autorouting.** With the `waibee/auto` model, the router tries to keep the same model while the cache is alive. How this works, and which error comes back if no model with caching is found: [Autorouting](/router/autorouting/).
Reading from the cache costs less than ordinary input, and writing to the cache costs more. Both prices are in the model’s `pricing` in the catalog.
# Quickstart
> Your first request to Waibee Router in five minutes.
Waibee Router supports **OpenAI Chat Completions** (`POST /v1/chat/completions`) and **Responses** (`POST /v1/responses`), as well as **Anthropic Messages** (`POST /v1/messages`). For your first request you need a Waibee API key (`sk_live_...`; see [Authentication](/router/authentication/) for where to get one) and the address `https://api.waibee.com`.
## 1. Set the key
[Section titled “1. Set the key”](#1-set-the-key)
```bash
export WAIBEE_API_KEY="sk_live_..."
```
## 2. Send your first request (OpenAI format)
[Section titled “2. Send your first request (OpenAI format)”](#2-send-your-first-request-openai-format)
* curl
chat-completion.sh
```bash
curl https://api.waibee.com/v1/chat/completions \
-H "Authorization: Bearer $WAIBEE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "anthropic/claude-sonnet-4.6",
"messages": [{ "role": "user", "content": "Answer in one word: what is the capital of France?" }]
}'
```
* Python
client.py
```python
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.waibee.com/v1",
api_key=os.environ["WAIBEE_API_KEY"],
)
response = client.chat.completions.create(
model="anthropic/claude-sonnet-4.6",
messages=[{"role": "user", "content": "Answer in one word: what is the capital of France?"}],
)
print(response.choices[0].message.content)
```
Install the client with `pip install openai`: the router accepts the official SDK as is.
* Node
client.mjs
```js
import OpenAI from 'openai';
const client = new OpenAI({
baseURL: 'https://api.waibee.com/v1',
apiKey: process.env.WAIBEE_API_KEY,
});
const response = await client.chat.completions.create({
model: 'anthropic/claude-sonnet-4.6',
messages: [{ role: 'user', content: 'Answer in one word: what is the capital of France?' }],
});
console.log(response.choices[0].message.content);
```
Install the client with `npm install openai`.
The response:
response.json
```json
{
"id": "gen-...",
"object": "chat.completion",
"created": 1791678193,
"model": "anthropic/claude-sonnet-4.6",
"choices": [
{
"index": 0,
"finish_reason": "stop",
"message": { "role": "assistant", "content": "Paris" }
}
],
"usage": { "prompt_tokens": 19, "completion_tokens": 4, "total_tokens": 23 }
}
```
## 3. Anthropic format
[Section titled “3. Anthropic format”](#3-anthropic-format)
The same request to `POST /v1/messages`, the format the Anthropic SDKs and Claude Code use.
messages.sh
```bash
curl https://api.waibee.com/v1/messages \
-H "x-api-key: $WAIBEE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "anthropic/claude-sonnet-4.6",
"max_tokens": 1024,
"messages": [{ "role": "user", "content": "Answer in one word: what is the capital of France?" }]
}'
```
Here the `max_tokens` field is required, and the response comes back in Anthropic shape: `content`, `stop_reason`, `usage`.
## Model ID
[Section titled “Model ID”](#model-id)
`model` has the form `/`; take it from the `GET /v1/models` catalog:
* `anthropic/claude-sonnet-4.6`
* `openai/gpt-5.2`
* `waibee/auto` ([Autorouting](/router/autorouting/): the router picks the model for the request)
The catalog, short names on `/v1/messages`, and what happens with a wrong name: [Models](/router/models/).
## Switching from another provider
[Section titled “Switching from another provider”](#switching-from-another-provider)
To use Waibee from a client compatible with the OpenAI or Anthropic API, change only the base URL and the key:
```diff
client = OpenAI(
-base_url="https://api.openai.com/v1",
-api_key=os.environ["OPENAI_API_KEY"],
+base_url="https://api.waibee.com/v1",
+api_key=os.environ["WAIBEE_API_KEY"],
)
```
Step-by-step setup for specific tools is in [Integrations](/router/integrations/).
# Reasoning
> Reasoning levels: reasoning_effort on Chat Completions, output_config.effort on Messages, reasoning.effort on Responses, response fields, and token accounting.
Reasoning models “think” before they answer: they generate internal reasoning that is not part of the main text but is billed as output. The depth of reasoning is set by the effort level: a higher level gives more accurate answers on hard tasks, at the cost of a longer wait and a more expensive request.
To check whether a model reasons, look in `GET /v1/models`: its `capabilities.features` includes `reasoning`. See [Models](/router/models/).
## Chat Completions
[Section titled “Chat Completions”](#chat-completions)
Set the level with the `reasoning_effort` field.
reasoning.sh
```bash
curl https://api.waibee.com/v1/chat/completions \
-H "Authorization: Bearer $WAIBEE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "openai/gpt-5.4-mini",
"reasoning_effort": "high",
"messages": [{ "role": "user", "content": "What is 17*23? Answer with a number." }]
}'
```
| Value | Meaning |
| --------- | -------------------------------------------- |
| `none` | Reasoning is off |
| `minimal` | The minimum, for simple tasks |
| `low` | A little |
| `medium` | A reasonable trade-off |
| `high` | A lot, for hard tasks |
| `xhigh` | A great deal |
| `max` | The highest level, on models that support it |
The available levels depend on the model. The router passes the value to the model as is; some models reject a level outside their list with `400` `feature_not_supported` and name the levels they accept. If the field is not passed, the model’s default behavior applies.
### Model levels
[Section titled “Model levels”](#model-levels)
The levels a model accepts are listed in the [catalog](/router/models/#catalog): models with `reasoning` in `capabilities.features` have a `reasoning` field.
* `efforts`: the levels the model accepts, from weakest to strongest. `none` in the list means reasoning can be turned off. An empty list means the model always reasons and accepts no level.
* `default`: the level to pick by default. It is `none` if the model does not reason without a level, and `null` if the provider does not say.
The provider may reject a level that is not in `efforts` with `400`. For models without reasoning and for `waibee/auto`, the field is `null`.
Clients that send a `reasoning` object instead of a string also work: the router takes `effort` from it. The object’s other fields may not be applied, so `reasoning_effort` is more predictable.
## Messages
[Section titled “Messages”](#messages)
On `POST /v1/messages`, set the level with the `effort` field inside `output_config`.
```bash
curl https://api.waibee.com/v1/messages \
-H "x-api-key: $WAIBEE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "anthropic/claude-sonnet-5",
"max_tokens": 2048,
"output_config": { "effort": "high" },
"messages": [{ "role": "user", "content": "What is the probability of drawing two red balls in a row without replacement from 5 red, 3 blue, and 2 white?" }]
}'
```
The reasoning arrives in a separate `thinking` block before the response text:
```json
{
"type": "message",
"content": [
{ "type": "thinking", "thinking": "..." },
{ "type": "text", "text": "..." }
]
}
```
The `thinking` field in the request (Anthropic’s extended thinking configuration) is also passed to the model unchanged, but on newer Claude models `output_config.effort` is preferred.
## Responses
[Section titled “Responses”](#responses)
On `POST /v1/responses`, set the level with the `effort` field inside the `reasoning` object. The request goes to the model as is, and the router does not check the value. The reasoning arrives as a separate item in `output`; see [Responses API](/router/responses-api/).
## Reasoning in a Chat Completions response
[Section titled “Reasoning in a Chat Completions response”](#reasoning-in-a-chat-completions-response)
The format depends on the model, so the response can contain two fields:
| Field | Contents |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `reasoning` | The reasoning text as a string, if the model exposes it |
| `reasoning_details` | An array of blocks in the model’s format: `reasoning.text` with the text, `reasoning.summary` with a summary of the reasoning, or `reasoning.encrypted` with an encrypted blob |
If the provider omits `reasoning` or sends an empty string, the router fills it by concatenating the `text` of `reasoning.text` blocks and the `summary` of `reasoning.summary` blocks in `reasoning_details`, without a separator. Encrypted blocks contribute no text. This also applies to streaming deltas.
Some model families do not expose their reasoning and send only encrypted blocks. You cannot read them, but you can pass them back in the next request if your client supports it. Plain text looks like this:
```json
{
"message": {
"role": "assistant",
"content": "391",
"reasoning": "17 * 20 = 340, plus 17 * 3 = 51, total 391.",
"reasoning_details": [{ "type": "reasoning.text", "text": "...", "index": 0 }]
}
}
```
When streaming, these fields arrive in fragments inside `delta`, like ordinary text.
## DLP and reasoning
[Section titled “DLP and reasoning”](#dlp-and-reasoning)
With [DLP in mask mode](/router/plugins/#reasoning-sent-back), reasoning keeps the provider’s placeholders, including in streaming responses. Send signed reasoning back unchanged: editing it can invalidate its signature. DLP scans the readable reasoning you send back.
## Tokens and cost
[Section titled “Tokens and cost”](#tokens-and-cost)
Reasoning is billed as output and counts toward output tokens. Which `usage` field shows the amount on each endpoint: [Tokens and usage](/router/usage/).
## What to keep in mind
[Section titled “What to keep in mind”](#what-to-keep-in-mind)
* **The first token arrives later.** At high levels the model is silent while it thinks: on hard requests that is tens of seconds or more. In interactive interfaces, turn on [streaming](/router/streaming/) so the connection does not look stuck, and do not set client timeouts too low.
* **Pick the level for the task, not “just in case”.** Data extraction, short answers, and tool calls usually do not improve with high effort, but they cost more.
* **`max_tokens` includes the reasoning.** A limit that is too tight cuts the response off before the model gets to the text.
* **Reasoning does not replace instructions.** If the answer is consistently wrong, a more precise prompt helps more than a higher level.
# Responses API
> The Responses API format on Waibee Router. Items instead of messages, multi-turn conversations, and what is not supported.
`POST /v1/responses` accepts requests in **Responses** format.
For a comparison of the three formats, see the [router overview](/router/#three-request-formats). For how to connect a client and which SDK method to call, see [OpenAI-compatible clients](/router/integrations/openai-compatible/).
## First request
[Section titled “First request”](#first-request)
```bash
curl https://api.waibee.com/v1/responses \
-H "Authorization: Bearer $WAIBEE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "openai/gpt-5.1-codex",
"input": "Say hello",
"max_output_tokens": 64
}'
```
With the official OpenAI SDK:
```python
from openai import OpenAI
client = OpenAI(api_key="sk_live_...", base_url="https://api.waibee.com/v1")
response = client.responses.create(
model="openai/gpt-5.1-codex",
input="Say hello",
max_output_tokens=64,
)
print(response.output_text)
```
Take `model` from the shared [model catalog](/router/models/), but being in the catalog does not guarantee that a model is available on Responses. If you get `feature_not_supported`, use `/v1/chat/completions`.
## Items instead of messages
[Section titled “Items instead of messages”](#items-instead-of-messages)
Chat Completions works with a list of messages. Responses works with **items**: a message, a function call, a call result, a piece of reasoning. Each has its own `type`, `id`, and `status`.
```json
{
"model": "openai/gpt-5.1-codex",
"input": [
{"type": "message", "role": "user", "content": "What is in the README file?"}
],
"instructions": "Keep your answers short."
}
```
`instructions` plays the role of the system prompt and sits at the top level, not inside the list.
The response comes back as an `output` list of the same items:
```json
{
"id": "resp_0fe6078d9f604fdc8768e83bec097248",
"status": "completed",
"output": [
{
"type": "message",
"role": "assistant",
"content": [{"type": "output_text", "text": "It is the project README."}]
}
],
"usage": {"input_tokens": 14, "output_tokens": 6, "total_tokens": 20}
}
```
The router issues the response ID. The IDs of the items inside `output` come from the model. You can send those items back in full.
## Multi-turn conversations
[Section titled “Multi-turn conversations”](#multi-turn-conversations)
The router does not store the conversation. Each new request carries **the whole conversation** in `input`: what you sent before, plus the items from the previous response’s `output`, plus the new turn.
```json
{
"model": "openai/gpt-5.1-codex",
"input": [
{"type": "message", "role": "user", "content": "What is in the README file?"},
{"type": "message", "role": "assistant",
"content": [{"type": "output_text", "text": "It is the project README."}]},
{"type": "message", "role": "user", "content": "And in the CHANGELOG?"}
]
}
```
This has two practical consequences.
The input grows with every turn, and a long session is billed as a series of ever larger requests. [Prompt caching](/router/prompt-caching/) softens this: the unchanged beginning of the conversation is billed at a lower price, and the cached share shows in `usage.input_tokens_details.cached_tokens`.
Fields that ask the server to remember the conversation for you are rejected; the list is below, under [What the router does not do](#what-the-router-does-not-do).
## Tool calling
[Section titled “Tool calling”](#tool-calling)
Declare tools in `tools`; the call loop lives in the same `input` items.
```json
{
"model": "openai/gpt-5.1-codex",
"input": [{"type": "message", "role": "user", "content": "What is the weather in Limassol?"}],
"tools": [
{
"type": "function",
"name": "get_weather",
"description": "Weather in a city",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"]
}
}
]
}
```
The model replies with a `function_call` item:
```json
{"type": "function_call", "name": "get_weather",
"arguments": "{\"city\":\"Limassol\"}", "call_id": "call_a1"}
```
You run the call yourself and send the result in the next request, appending both the `function_call` itself and its output to `input`:
```json
{
"input": [
{"type": "message", "role": "user", "content": "What is the weather in Limassol?"},
{"type": "function_call", "name": "get_weather",
"arguments": "{\"city\":\"Limassol\"}", "call_id": "call_a1"},
{"type": "function_call_output", "call_id": "call_a1", "output": "+28, clear"}
]
}
```
`call_id` links the call to its result. The loop repeats until the model replies with a message.
How the same thing works on the other formats: [Tool calling](/router/tool-calling/).
### Web search
[Section titled “Web search”](#web-search)
The router runs the built-in `{"type": "web_search"}` tool: the sources it finds arrive in `waibee:web_search` items alongside the response. The item format, limits, and cost: [Web search](/router/web-search/#what-the-response-contains).
## Streaming
[Section titled “Streaming”](#streaming)
With `"stream": true`, the response arrives as named events:
```plaintext
event: response.created
data: {"type":"response.created","response":{...}}
event: response.output_text.delta
data: {"type":"response.output_text.delta","delta":"Hel"}
event: response.completed
data: {"type":"response.completed","response":{...,"usage":{...}}}
data: [DONE]
```
The stream opens with a `response.created` event. A generation that runs to the end closes it with `response.completed` or `response.incomplete`; `response.incomplete` means the response is incomplete, for example because it hit the `max_output_tokens` limit or ran out of web search turns. The reason, if given, is in `response.incomplete_details.reason`. If the generation fails, the last event is `error`, with the same error object as in a response with an HTTP status. However the stream ends, `data: [DONE]` follows.
The order of intermediate events depends on the model. Skip event types you do not recognize instead of treating them as errors.
Streaming on the other formats: [Streaming](/router/streaming/).
## What the router does not do
[Section titled “What the router does not do”](#what-the-router-does-not-do)
The format can store conversation history on the server. The router does not, so four fields are rejected with the code `feature_not_supported` and HTTP 400:
| Field | Rejected when |
| ---------------------- | ------------------- |
| `store` | the value is `true` |
| `previous_response_id` | set |
| `conversation` | set |
| `background` | the value is `true` |
An item in the `input` array with type `item_reference` is also rejected with HTTP 400 and `feature_not_supported`, with `param` set to `input`. The same applies to an item with `id`, no `role`, and `type` absent or `null`. Send the full item in `input`.
```json
{
"error": {
"type": "invalid_request_error",
"code": "feature_not_supported",
"message": "'store' is not supported: this endpoint is stateless. Send the whole conversation in `input`.",
"param": "store"
}
}
```
The `param` field names the parameter that got the request rejected. `"store": false` with none of the other fields is the normal form of a request, and it works.
Reading and deleting a stored response (`GET` and `DELETE` on `/v1/responses/{id}`), canceling a request, and background execution are unavailable for the same reason: they all rely on server-side state.
## Plugins
[Section titled “Plugins”](#plugins)
[DLP](/router/plugins/) works here the same way as on the other two formats: you pass the config in the `plugins` field of the request body, and rules the administrator assigned to your key apply in any case.
Two field names differ, because the format itself names them differently:
| In the examples on the Plugins page | Here |
| ----------------------------------- | -------------- |
| `messages` | `input` |
| a system prompt inside `messages` | `instructions` |
A finding names the field you sent: `input[0].content` or `instructions`. A string in the `input` array is named by its index, `input[1]`, and an `input` sent as a string is named `input`. When a request is blocked, the findings arrive in `error.details.dlp`.
In mask mode, response `reasoning` items and reasoning events keep placeholders. DLP scans their readable text when you send the items back. The [rules for reasoning sent back](/router/plugins/#reasoning-sent-back) describe which blocks are removed and when a signed block causes `403` `dlp_violation`.
When DLP removes a signed `reasoning` item, it strips `id` from subsequent model items up to the next user, system, or developer message, tool result, or kept `reasoning` item, which keeps its `id`. `call_id` is preserved; built-in tool calls without `call_id` in that span are removed.
## Error format
[Section titled “Error format”](#error-format)
Errors come in Responses’ own format, so client SDKs parse them as usual:
```json
{
"error": {
"type": "invalid_request_error",
"code": "validation_error",
"message": "..."
}
}
```
When streaming, an error arrives as an `error` event with a body of the same shape, and then the stream closes with `data: [DONE]`.
When the model itself rejects a request, `message` carries its explanation: what is missing from the body or what should not be there. If the explanation concerns our side rather than your request, a generic string comes instead.
Codes and statuses are shared across all formats: [Errors](/router/errors/).
## Integrations
[Section titled “Integrations”](#integrations)
* [Codex CLI](/router/integrations/codex/): connecting OpenAI’s agent
# Streaming
> Streaming responses over Server-Sent Events on /v1/chat/completions and /v1/messages: the event format, keep-alive, and errors mid-stream.
To stream a response, set `"stream": true`. The router sends it as a Server-Sent Events (SSE) stream: tokens arrive as they are generated instead of in one block at the end. The stream format matches the endpoint. The `/v1/responses` stream is covered in [Responses API](/router/responses-api/#streaming).
## Chat Completions
[Section titled “Chat Completions”](#chat-completions)
`POST /v1/chat/completions` returns an OpenAI-compatible stream. Each event is a `data:` line with a `chat.completion.chunk` object, and the text is in `choices[].delta.content`. The stream ends with a `data: [DONE]` line.
```bash
curl https://api.waibee.com/v1/chat/completions \
-H "Authorization: Bearer $WAIBEE_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "model": "anthropic/claude-sonnet-4.6", "stream": true,
"messages": [{ "role": "user", "content": "Hello!" }] }'
```
```plaintext
data: {"object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","content":"Hello! How"}}]}
data: {"object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":" are"}}]}
data: [DONE]
```
## Messages
[Section titled “Messages”](#messages)
`POST /v1/messages` returns a stream of Anthropic-format events. Each event is a pair of `event:` and `data:` lines. The events come in this order: `message_start`, then `content_block_start`, a series of `content_block_delta` events with text, `content_block_stop`, `message_delta`, and `message_stop`. If the response has several blocks (reasoning, text, a tool call), the three `content_block_*` events repeat for each one. This format has no `data: [DONE]` line: the stream ends after `message_stop`.
```bash
curl https://api.waibee.com/v1/messages \
-H "x-api-key: $WAIBEE_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "model": "anthropic/claude-sonnet-4.6", "stream": true, "max_tokens": 1024,
"messages": [{ "role": "user", "content": "Hello!" }] }'
```
```plaintext
event: message_start
data: {"type":"message_start","message":{"role":"assistant","content":[]}}
event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hello! How"}}
event: message_stop
data: {"type":"message_stop"}
```
## Errors mid-stream
[Section titled “Errors mid-stream”](#errors-mid-stream)
An error before the stream starts (API key, balance, validation, DLP, the model rejecting the request) comes as an ordinary HTTP response with a code from [Errors](/router/errors/).
Once the stream has started, the HTTP status stays `200`, and the error arrives as an `error` event:
* `/v1/chat/completions`: `event: error`, with a chunk in `data` that has an `error` field (`code` and `message`) and `finish_reason: "error"`, followed by `data: [DONE]`;
* `/v1/messages`: `event: error` with the body `{"type": "error", "error": {"type": ..., "code": ..., "message": ...}}`. Use `error.code` to find the cause: one `error.type` covers several codes;
* `/v1/responses`: see [Responses API](/router/responses-api/#error-format).
## What to keep in mind
[Section titled “What to keep in mind”](#what-to-keep-in-mind)
* The stream can contain SSE comment lines (they start with `:`). These are keep-alives: the router sends them while the model is silent, for example while it reasons. Ignore them.
* Which events carry token counters depends on the stream format; see [Tokens and usage](/router/usage/#streaming).
* The official SDKs (`openai`, `anthropic`) parse the stream for you: turn on streaming in the call (`stream=True`), and the text arrives in parts. See [Integrations](/router/integrations/openai-compatible/).
# Structured outputs
> Responses that follow a JSON Schema: response_format on Chat Completions, output_config.format on Messages, text.format on Responses.
Structured outputs make the model answer with JSON of a given shape. You describe the keys, types, and required fields once in a schema, and you do not have to parse free text.
To check whether a model supports them, look in `GET /v1/models`: `capabilities.features` includes `structured_outputs` (strict schema) or `response_format` (JSON mode without a schema). See [Models](/router/models/).
## Chat Completions
[Section titled “Chat Completions”](#chat-completions)
Pass the schema in `response_format` with the type `json_schema`.
structured.sh
```bash
curl https://api.waibee.com/v1/chat/completions \
-H "Authorization: Bearer $WAIBEE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "openai/gpt-5.4-mini",
"messages": [
{ "role": "user", "content": "Extract the data: Ivan Petrov, 34 years old, Berlin, senior backend." }
],
"response_format": {
"type": "json_schema",
"json_schema": {
"name": "person",
"strict": true,
"schema": {
"type": "object",
"properties": {
"name": { "type": "string" },
"age": { "type": "integer" },
"city": { "type": "string" },
"role": { "type": "string" }
},
"required": ["name", "age", "city", "role"],
"additionalProperties": false
}
}
}
}'
```
The response is an ordinary message, with the JSON as a string in `content`:
response.json
```json
{
"choices": [{
"index": 0,
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": "{\"name\":\"Ivan Petrov\",\"age\":34,\"city\":\"Berlin\",\"role\":\"senior backend\"}"
}
}],
"usage": { "prompt_tokens": 66, "completion_tokens": 28, "total_tokens": 94 }
}
```
`json_schema` fields:
| Field | Purpose |
| -------- | -------------------------------------------------------------------------------------- |
| `name` | The schema name. The model sees it and treats it as a hint about what the object means |
| `strict` | `true` requires an exact match with the schema |
| `schema` | The schema itself, in JSON Schema format |
The simpler `{"type": "json_object"}` mode requires only valid JSON, with no schema. Use it when you do not need the response in a particular shape.
## Messages
[Section titled “Messages”](#messages)
On `POST /v1/messages`, set the structure with the `format` field inside `output_config`:
```json
{
"model": "anthropic/claude-sonnet-5",
"max_tokens": 1024,
"output_config": {
"format": {
"type": "json_schema",
"schema": {
"type": "object",
"properties": { "city": { "type": "string" }, "temp_c": { "type": "number" } },
"required": ["city", "temp_c"]
}
}
},
"messages": [{ "role": "user", "content": "It is 19 degrees in Berlin. Format the answer to the schema." }]
}
```
The response is a text block with the JSON inside: `{"city":"Berlin","temp_c":19}`.
`output_config` is passed to the provider as is, so the fields it accepts depend on the model. The reasoning level is set there too; see [Reasoning](/router/reasoning/).
## Responses
[Section titled “Responses”](#responses)
On `POST /v1/responses`, set the schema with the `format` field inside the `text` object, with `type: "json_schema"`. The request goes to the model as is, and the JSON comes back as text in a `message` item of the `output` list.
## What to keep in mind
[Section titled “What to keep in mind”](#what-to-keep-in-mind)
* **A schema constrains the shape, not the meaning.** The model fills in every required field even when the input has no data for it: give “unknown” an explicit value (`null` in the list of types, or a flag field).
* **Keep the schema flat.** Deep nesting and large `oneOf` lead to refusals and extra tokens noticeably more often. Two requests with simple schemas are often easier.
* **A schema does not replace validation.** Parse the response with your own validator: you still need it to tell a model failure from a usable response.
* **The length limit cuts off the JSON.** If the response hits `max_tokens`, you get an unclosed string with `finish_reason: "length"`. Check for this separately from parse errors.
* **Do not combine with streaming unless you need to.** Partial JSON in a stream cannot be fully parsed until generation ends anyway.
* **Function arguments have their own schema.** Structured outputs describe the model’s response, not tool calls; see [Tool calling](/router/tool-calling/).
# Tool calling
> Tool calling: describing functions, the call loop, several calls in one response, streaming, and limitations.
A model does not run functions itself. It receives their descriptions and returns an intent: a function name and arguments in JSON. You run the code and send the result in the next request. The model then either asks for another call or answers with text.
To check whether a model supports tool calling, look in `GET /v1/models`: its `capabilities.features` must include `tools`. See [Models](/router/models/).
## The three-step loop
[Section titled “The three-step loop”](#the-three-step-loop)
1. Send a request with the `tools` field.
2. Get a response with `finish_reason: "tool_calls"` and a `tool_calls` array. Run the functions on your side.
3. Send a request with the same history plus the assistant message and the results in `role: "tool"` messages.
The router keeps no history: each request is sent in full, including earlier calls and their results.
### 1. Request with tools
[Section titled “1. Request with tools”](#1-request-with-tools)
step-1.sh
```bash
curl https://api.waibee.com/v1/chat/completions \
-H "Authorization: Bearer $WAIBEE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "google/gemini-3.6-flash",
"messages": [{ "role": "user", "content": "What is the weather in Berlin?" }],
"tools": [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Current weather in a city",
"parameters": {
"type": "object",
"properties": {
"city": { "type": "string", "description": "City" },
"unit": { "type": "string", "enum": ["c", "f"] }
},
"required": ["city"]
}
}
}]
}'
```
### 2. Response with a call
[Section titled “2. Response with a call”](#2-response-with-a-call)
response.json
```json
{
"choices": [{
"index": 0,
"finish_reason": "tool_calls",
"message": {
"role": "assistant",
"tool_calls": [{
"id": "29veklzD",
"type": "function",
"function": { "name": "get_weather", "arguments": "{\"city\":\"Berlin\"}" }
}]
}
}],
"usage": { "prompt_tokens": 37, "completion_tokens": 86, "total_tokens": 123 }
}
```
Two things trip people up most often:
* `arguments` is a **string** of JSON, not an object. You have to parse it, and it may fail validation: handle a parse error as an ordinary failure, not as an exceptional case.
* The call `id` is required in step 3. The model uses it to match the result to the call.
### 3. Result back to the model
[Section titled “3. Result back to the model”](#3-result-back-to-the-model)
step-3.sh
```bash
curl https://api.waibee.com/v1/chat/completions \
-H "Authorization: Bearer $WAIBEE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "google/gemini-3.6-flash",
"messages": [
{ "role": "user", "content": "What is the weather in Berlin?" },
{ "role": "assistant", "tool_calls": [{
"id": "29veklzD", "type": "function",
"function": { "name": "get_weather", "arguments": "{\"city\":\"Berlin\"}" } }] },
{ "role": "tool", "tool_call_id": "29veklzD",
"content": "{\"temp_c\": 19, \"cond\": \"cloudy\"}" }
],
"tools": [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Current weather in a city",
"parameters": {
"type": "object",
"properties": {
"city": { "type": "string", "description": "City" },
"unit": { "type": "string", "enum": ["c", "f"] }
},
"required": ["city"]
}
}
}]
}'
```
The response comes back as ordinary text with `finish_reason: "stop"`. Pass the `tools` definitions in this request too: without them, the model cannot call the tool again if it needs more data.
The content of a `role: "tool"` message is an arbitrary string. JSON works better than free text: it is less ambiguous and saves the tokens that explanations would take.
## Several calls in one response
[Section titled “Several calls in one response”](#several-calls-in-one-response)
A model can return several items in `tool_calls` at once. Run all of them and add a separate `role: "tool"` message for each `tool_call_id`. The order of the result messages does not matter, but every call needs an answer: a missing result usually causes a validation error on the model’s side.
To turn off parallel calls, pass `parallel_tool_calls: false`. Models with `parallel_tool_calls` in `capabilities.features` understand it.
## Controlling the choice: `tool_choice`
[Section titled “Controlling the choice: tool\_choice”](#controlling-the-choice-tool_choice)
| Value | Behavior |
| ----------------------------------------------------------- | --------------------------------------------------------------------------------- |
| `"auto"` | The model decides whether to call a tool or answer with text. This is the default |
| `"none"` | The model sees the tools but cannot call them |
| `"required"` | The model must call at least one tool |
| `{"type": "function", "function": {"name": "get_weather"}}` | The model must call this function |
The values are passed to the model as is, so the supported options depend on the model family. `"auto"` and `"none"` work everywhere.
## Anthropic Messages format
[Section titled “Anthropic Messages format”](#anthropic-messages-format)
On `POST /v1/messages`, tools are described differently: the `name`, `description`, and `input_schema` fields sit at the top level, with no `function` wrapper.
```bash
curl https://api.waibee.com/v1/messages \
-H "x-api-key: $WAIBEE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "anthropic/claude-haiku-4.5",
"max_tokens": 512,
"tools": [{
"name": "get_weather",
"description": "Current weather in a city",
"input_schema": {
"type": "object",
"properties": { "city": { "type": "string", "description": "City" } },
"required": ["city"]
}
}],
"messages": [{ "role": "user", "content": "What is the weather in Berlin?" }]
}'
```
The call arrives as a `tool_use` block with `stop_reason: "tool_use"`, and the arguments are in `input` as an already parsed object:
```json
{
"type": "message",
"stop_reason": "tool_use",
"content": [{
"type": "tool_use",
"id": "toolu_011Q2fbw78h7hDJT2mBJjEfx",
"name": "get_weather",
"input": { "city": "Berlin" }
}]
}
```
Return the result as a `tool_result` block inside a user message:
```json
{
"role": "user",
"content": [{
"type": "tool_result",
"tool_use_id": "toolu_011Q2fbw78h7hDJT2mBJjEfx",
"content": "{\"temp_c\": 19, \"cond\": \"cloudy\"}"
}]
}
```
## Web search
[Section titled “Web search”](#web-search)
Built-in web search is also declared in `tools`, but the three-step loop does not apply to it: the router runs the search inside your single request. How to turn it on and what the response contains: [Web search](/router/web-search/).
## Streaming
[Section titled “Streaming”](#streaming)
With `"stream": true`, a call arrives in parts. In `delta.tool_calls`, the first fragment carries `id` and `name`, and the following ones carry only pieces of `arguments`. Assemble them by the `index` field until you have valid JSON.
```plaintext
data: {"choices":[{"index":0,"delta":{"role":"assistant","tool_calls":[
{"index":0,"id":"zmahjJWU","type":"function",
"function":{"name":"get_weather","arguments":""}}]}}]}
data: {"choices":[{"index":0,"delta":{"tool_calls":[
{"index":0,"function":{"arguments":"{\"city\":\"Berlin\"}"}}]}}]}
data: {"choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}],"usage":{...}}
data: [DONE]
```
The call is complete when a chunk with `finish_reason: "tool_calls"` arrives. For the stream format, see [Streaming](/router/streaming/).
## Limitations
[Section titled “Limitations”](#limitations)
* The number of tools in one request is limited; see [Limits](/router/limits/#request-structure).
* Web search is the only server-side tool available, on all three endpoints (see above). Server-side `web_fetch_*` and `code_execution_*` are rejected with `feature_not_supported` (400). Implement the equivalent as your own function on the client side.
* MCP is not supported: a tool of type `mcp*` and the `mcp_servers` field on `/v1/messages` are rejected with `feature_not_supported` (400).
* Argument schemas are passed to the provider unchanged. How strictly the model follows a schema depends on the model. If you need a guaranteed structure for the **response** rather than for arguments, see [Structured outputs](/router/structured-outputs/).
## What helps in practice
[Section titled “What helps in practice”](#what-helps-in-practice)
* **Write descriptions for a human reader.** The name, the function description, and the field descriptions are the only instructions the model has for deciding when to call a tool and with what. One precise sentence works better than a list of implementation details.
* **Narrow the schema.** Use `enum` instead of a free-form string, put required fields in `required`, and leave out parameters that are optional “just in case”.
* **Cap the number of iterations.** A “call, result, call” loop may never converge: limit the number of rounds and end the conversation with a clear error.
* **Check `finish_reason`.** Run tools only when it is `tool_calls`; otherwise the response is ordinary text.
* **Keep the tool count low.** Dozens of similar functions in one request raise the chance that the model picks the wrong one, and they bloat the input.
# Tokens and usage
> The usage fields on each endpoint, where to find cache and reasoning tokens, and how to estimate the cost of a request.
Token counters come in the `usage` object. The cost of a request is calculated from them, with the per-token prices from the model catalog. Occasionally `usage` does not arrive; see [What to account for](#what-to-account-for). The set of fields depends on the endpoint: the three chat formats count input differently, and embeddings and decisions have their own short `usage`.
## Chat Completions
[Section titled “Chat Completions”](#chat-completions)
```json
"usage": {
"prompt_tokens": 68,
"completion_tokens": 30,
"total_tokens": 98,
"prompt_tokens_details": {
"cached_tokens": 0,
"cache_write_tokens": 0,
"audio_tokens": 0,
"video_tokens": 0
},
"completion_tokens_details": {
"reasoning_tokens": 0,
"audio_tokens": 0,
"image_tokens": 0
}
}
```
| Field | What it counts |
| -------------------------------------------- | ----------------------------------------------------------------- |
| `prompt_tokens` | All input, including cached tokens |
| `completion_tokens` | All output, including reasoning |
| `total_tokens` | Input plus output |
| `prompt_tokens_details.cached_tokens` | The part of the input read from the cache, billed at a lower rate |
| `prompt_tokens_details.cache_write_tokens` | The part of the input written to the cache |
| `completion_tokens_details.reasoning_tokens` | The part of the output spent on reasoning |
The nested fields are **parts** of the matching total, not additions to it. Uncached input is `prompt_tokens - cached_tokens - cache_write_tokens`.
## Messages
[Section titled “Messages”](#messages)
```json
"usage": {
"input_tokens": 65,
"output_tokens": 137,
"cache_read_input_tokens": 0,
"cache_creation_input_tokens": 0,
"cache_creation": { "ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 0 }
}
```
Messages follows the Anthropic convention: `input_tokens` is **only the uncached** input, and the cache comes in separate fields. To get the full input, add them up:
```plaintext
total input = input_tokens + cache_read_input_tokens + cache_creation_input_tokens
```
`cache_creation` splits the cache write by lifetime (5 minutes and 1 hour), because they have different rates. See [Prompt caching](/router/prompt-caching/). Reasoning is included in `output_tokens`; see [Reasoning](/router/reasoning/).
## Responses
[Section titled “Responses”](#responses)
```json
"usage": {
"input_tokens": 14,
"input_tokens_details": { "cached_tokens": 0 },
"output_tokens": 6,
"output_tokens_details": { "reasoning_tokens": 0 },
"total_tokens": 20
}
```
Here `input_tokens` includes the cached part, as on Chat Completions, and `cached_tokens` shows how many of them were read from the cache. Reasoning tokens are in `output_tokens_details.reasoning_tokens` and are included in `output_tokens`.
## Web search
[Section titled “Web search”](#web-search)
If the request turned on [web search](/router/web-search/), `usage` on all three chat endpoints contains a `server_tool_use` block. The `web_search_requests` field counts the searches that ran:
```json
"server_tool_use": { "web_search_requests": 1, "web_fetch_requests": 0 }
```
## Embeddings and decisions
[Section titled “Embeddings and decisions”](#embeddings-and-decisions)
`/v1/embeddings` counts only input: its `usage` has `prompt_tokens` and `total_tokens`. `/v1/systemone` returns `input_tokens` and `output_tokens`. For details, see [Embeddings](/router/embeddings/#response) and [Decisions](/router/decisions/#response).
## Streaming
[Section titled “Streaming”](#streaming)
With `"stream": true`, the counters arrive in the stream events, with no separate request needed:
* `/v1/chat/completions`: the last chunk before `data: [DONE]` carries `usage`;
* `/v1/messages`: save `usage` from `message_start` and update it with the fields from `message_delta`. Input and cache counts may appear only in `message_start`, and the final output count arrives in `message_delta`;
* `/v1/responses`: the final event (`response.completed` or `response.incomplete`) carries the final `usage` inside `response`.
If the client drops the connection midway, generation runs to the end and is billed in full. You cannot cancel a request by closing the connection.
## Estimating cost
[Section titled “Estimating cost”](#estimating-cost)
Per-token prices are in the `pricing` of each model in `GET /v1/models` and match your plan:
```json
"pricing": {
"prompt": "0.000002",
"completion": "0.00001",
"input_cache_read": "0.0000002",
"input_cache_write": "0.0000025"
}
```
The cost of a request is a sum of products: uncached input times `prompt`, cache reads times `input_cache_read`, cache writes times `input_cache_write`, and output times `completion`. Some models have separate rates for reasoning (`internal_reasoning`), images, audio, and one-hour cache writes (`input_cache_write_1h`), and a fixed price per request (`request`). Reasoning, images, and audio with their own rate are subtracted from the output, so each token is billed once.
For some models, the price depends on the input size: above a certain number of input tokens, different rates apply. The catalog shows only the base rates, so for a long request, an estimate from the catalog may differ from the actual charge.
Searches run by the router are billed on top of tokens at their own price, which is not in the model catalog. See [Web search](/router/web-search/).
The response has no cost field: calculate it from `usage` and the catalog, or see the actual charges in the console.
## What to account for
[Section titled “What to account for”](#what-to-account-for)
* **Tokens are not characters.** On average, Russian text costs more than English text of the same length, because how text splits into tokens depends on the model.
* **Attachments are tokens too.** An image or a PDF turns into input tokens by the model’s rules. See [Images and PDFs](/router/attachments/).
* **Tools add to the input.** The `tools` definitions are sent in every request of the loop and count as part of the prompt.
* **The cache changes how input is billed, not how much there is.** The tokens do not go away; some of them are billed at the cache read price.
* **Occasionally the `usage` block does not arrive at all.** Tokens without counters are not billed, but the web searches that ran are charged and show up in the spending history.
# Web search
> The model searches the web on its own, and the router runs the search for it. How to turn it on, what the response contains, and what it costs.
A model can search the web on its own, and the router runs the search for it. You ask for it the way you already would on your endpoint, and you get back a finished response with a list of sources.
This is not an ordinary tool call: you do not receive a request from the model, run the search, and send the result back. The router does all three steps itself, inside your single request.
Web search works on all three endpoints. Only two things differ: how you ask for it and what form the sources take.
## Turning it on
[Section titled “Turning it on”](#turning-it-on)
On `POST /v1/chat/completions`, use the `web_search_options` field. An empty object is enough, and you can set `max_uses` inside it. Instead of the field, you can pass `web_search` in `tools`:
```bash
curl https://api.waibee.com/v1/chat/completions \
-H "Authorization: Bearer $WAIBEE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "openai/gpt-5.4-mini",
"web_search_options": {},
"messages": [{ "role": "user", "content": "What is the latest Python version? One line." }]
}'
```
On `POST /v1/messages`, search is a tool in Anthropic format. The `max_uses` field is optional, and any tool version Anthropic releases works:
```bash
curl https://api.waibee.com/v1/messages \
-H "x-api-key: $WAIBEE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "anthropic/claude-haiku-4.5",
"max_tokens": 512,
"tools": [{ "type": "web_search_20250305", "name": "web_search", "max_uses": 2 }],
"messages": [{ "role": "user", "content": "What is the latest Python version? One line." }]
}'
```
On `POST /v1/responses`, it is the `web_search` tool in `tools`:
```json
"tools": [{ "type": "web_search" }]
```
## What the response contains
[Section titled “What the response contains”](#what-the-response-contains)
On chat completions and messages, sources come in the same shape as from the built-in search of OpenAI and Anthropic. A client written for their search reads the response without changes.
On `/v1/chat/completions`, sources are citations in `message.annotations`:
```json
"annotations": [
{
"type": "url_citation",
"url_citation": {
"url": "https://www.python.org/downloads/release/python-3148/",
"title": "Python Release Python 3.14.8 | Python.org",
"start_index": 0,
"end_index": 0
}
}
]
```
Both indexes are always `0`. The OpenAI schema requires these fields, so they are present, but they point at no real span of text: a source supports the response as a whole, not particular words in it.
On `/v1/messages`, sources are `server_tool_use` and `web_search_tool_result` blocks before the response text.
On `/v1/responses`, the sources found come in `waibee:web_search` items in `output`, next to the response. A search that finds nothing is still billed, but it may have no item of its own:
```json
{
"type": "waibee:web_search",
"id": "ws_call_abc",
"status": "completed",
"action": {
"type": "search",
"query": "latest python release",
"sources": [{ "type": "url", "url": "https://www.python.org/downloads/" }]
}
}
```
The `waibee:` prefix is ours: the Responses format allows custom item types under their own prefix. The intermediate turns, where the model asks for a search and gets the results, are not returned to you.
With `"stream": true`, sources arrive in the same stream: as an annotation in `delta` on chat completions, a pair of blocks on messages, and a pair of events on responses. It stays one stream however many searches the model makes: one opening event and one closing event.
## How many searches the model makes
[Section titled “How many searches the model makes”](#how-many-searches-the-model-makes)
By default, the model makes up to **10 searches** per request. To set your own number, use the `max_uses` field on any of the three surfaces: in `web_search_options` or the tool entry on chat completions, and in the tool entry on messages and responses. The lower of your number and our maximum applies, and our maximum is **20**. A number above the maximum is not an error: it is lowered to 20.
When the limit runs out, the model is told so and answers with what it has found.
If search is unavailable, the request does not fail. The model gets an empty result marked as unavailable and answers without it.
The output limit you set covers the whole request, not each search separately. If it runs out while the model is still searching, the response comes back marked as cut off:
| Endpoint | How it is marked |
| ---------------------- | --------------------------- |
| `/v1/chat/completions` | `finish_reason: "length"` |
| `/v1/messages` | `stop_reason: "max_tokens"` |
| `/v1/responses` | `status: "incomplete"` |
## What it costs
[Section titled “What it costs”](#what-it-costs)
Each search that runs is billed at its own rate, separately from tokens, including a search that finds nothing. A failed search is not billed. The number of searches run is in `usage`; see [Tokens and usage](/router/usage/).
Two more things show up on the bill:
* **Input tokens grow noticeably.** Search results go into the model’s input for the next step, which adds a few thousand tokens per request.
* **If a request fails after a search, you still pay for the searches that ran and the tokens of the generation steps that completed.**
## What to know up front
[Section titled “What to know up front”](#what-to-know-up-front)
* **Search results do not carry over to the next request.** Your history and the response text go into it, but the search results do not. If the conversation needs a fact later, it has to be in the response text. When you send search blocks on messages or `waibee:web_search` items on responses back in the history, the router removes them.
* **The model must support tool calling.** The model asks for a search with a tool call, so its `capabilities.features` must include `tools`; see [Models](/router/models/).
* **Of the built-in search settings, the router reads only `max_uses`.** The other fields of the tool entry and of `web_search_options` (domains, location, context size) are not applied.
* **Your own function named `web_search` stays yours.** The router does not replace it or intercept calls to it.
* **On `/v1/chat/completions`, search does not work with `n` greater than 1.** The request runs without search.