Skip to main content
Glama
README.md
<p align="center">
  <img src="brushrouterlogo.png" alt="BrushRouter — three AI mascots flying toward a raccoon carrying image.png" width="720">
</p>

# brushrouter

**Generate images with the AI you already pay for.** One CLI + MCP server that routes every request to the best image backend on the machine — your ChatGPT subscription, your Google login, your OpenRouter key — in that order, falling back automatically. Logins you already pay for first, the pay-per-image key last. No new API balance, no browser tabs, and no credential ever handed to a model.

```console
$ brushrouter gen "a red fox in snow" -o fox.png
✓ generated with gemini (gemini-3.1-flash-image-preview)
  /home/you/fox.png (image/png, 1250 KB)
```

It also ships a prompt library of 27 tested recipes and 137 vendored visual styles, because routing a bad prompt to a working backend just gets you a bad image faster.

- **Zero new spend** per image on routes that reuse a login you already pay for
- **One command to start** — `brushrouter setup` detects what's installed and connects it
- **No tokens exposed** — models never see your credentials, enforced by a redactor on every output
- **164-prompt library** — an agent asks for "a nice product shot" and gets a tested skeleton to fill in, not its own invention
- **MCP-native** — `brushrouter install` wires it into any agent's image work in one command

## Install

Requires Node.js 20+.

Run instantly with `npx`:

```bash
npx brushrouter setup
```

Or install via one-line script:

```bash
curl -fsSL https://raw.githubusercontent.com/avinaxhroy/brushrouter/main/install.sh | bash
```

Or globally via npm:

```bash
npm install -g brushrouter
brushrouter setup
```

Or manually from source:

```bash
git clone https://github.com/avinaxhroy/brushrouter.git
cd brushrouter
npm link
brushrouter setup
```

`setup` detects image backends, checks your PATH, and can offer login, MCP wiring, project rules and a test generation. In CI, without a TTY, or with `--non-interactive` or `--json`, it never prompts and only writes MCP settings or rules if you give `--yes`. `--dry-run` never prompts or writes. Setup exits nonzero if it finds no usable provider.

```bash
brushrouter setup --non-interactive --json
brushrouter doctor --json                  # health check; nonzero if no provider is ready
brushrouter doctor --fix --dry-run         # preview safe user-config repairs
brushrouter doctor --fix                   # apply repairs and diagnose again
```

Doctor does not probe disabled providers. It distinguishes verified connectivity from providers that are only configured. Repairs are opt-in and local: create missing user config, secure its permissions, or back up and replace malformed user config. They do not enable paid routes, sign you in, or install anything.

## Use

```bash
brushrouter gen "<prompt>" [options]

  -p, --provider <id>   Force a provider (see `brushrouter providers`)
  -f, --fallback        With --provider, fall back to others on failure
  -o, --out <path>      Output path (default: brushrouter-<timestamp>.png)
  -s, --size <WxH>      e.g. 1024x1024, auto
  -q, --quality <lvl>   low | medium | high | auto
      --background <b>  opaque | transparent (codex route sends the API field;
                        other routes ask for it in the prompt)
      --images <path>   Reference image for image-to-image (repeatable)
  -m, --model <id>      Pin a model for this call
      --seed <int>      Optional integer seed for reproducible generation
      --dry-run         Print the route order that would be attempted, then stop
      --force           Overwrite --out instead of writing a new versioned file
      --json            Machine-readable output
  -v, --verbose         Show routing decisions
```

All commands (`br` works everywhere as a shorthand for `brushrouter`):

```bash
br providers        # what is connected, and how
br routes           # which routes auto-routing may use
br models           # model ids (live for OpenRouter)
br prompts          # 27 recipes + 137 looks for briefing an image
br recipes validate # validate configured custom recipe and look directories
br doctor           # connectivity diagnosis for enabled providers
br setup            # first-run auto-connect
br login            # sign in to ChatGPT for the codex route (browser OAuth, no API key)
br vendor gptweb2api  # install the browserless ChatGPT-web gateway binary
br batch            # generate several prompts in parallel across backends
br history          # inspect, search, prune, or clear generation history
br replay [id|last] # replay a past generation with its prompt & seed (and optional overrides)
br stats            # provider latency (avg/p50/p95), success rates, and spend/usage stats
br init             # write a starter config
br install          # add brushrouter to detected agent MCP configs
br rules            # inject compact guidance into AGENTS.md / .cursorrules
br update           # update to latest version and verify health
br serve            # run as an MCP server on stdio
```

`brushrouter models [provider...] --json` lists static models and the live OpenRouter catalogue. Unknown providers fail; if a live listing fails, its provider has an `error` field (not a fake model). The command exits nonzero if none of the selected providers can be listed.

### Reference images

`--images` only works on routes that accept it; `brushrouter providers` marks the ones that don't. Passing it to a route that can't is an error when you forced the provider, a warning when auto-routing picked it.

| route | reference images | inpainting mask |
| --- | --- | --- |
| `codex-cli`, `codex`, `openrouter` | yes | no |
| `gemini` (CLI), `gemini-api` (AI Studio) | yes | no |
| `openai` | yes | PNG with alpha; transparent areas are edited |
| `fal` | yes | yes, with exactly one reference image |
| `replicate`, `comfyui` | with an editing model/workflow | with an inpainting model/workflow |
| `custom-http` | yes (`{image}` data URL in the request body template) | no |
| `gptweb2api` | no | no |

Pass `--mask` with `--images` for inpainting. The first reference is the base image; use a same-size mask and check the selected model's mask polarity. A masked request never falls back to text-only or unmasked editing. CLI batch accepts a per-item `mask` in JSON, or `--mask` as a default for all items.

Automatically named outputs use the extension that matches the image bytes. An explicitly requested filename is used as written; changing its extension does not convert the image.

```bash
brushrouter gen "replace the sky with clouds" --provider openai \
  --images photo.png --mask sky-mask.png -o edited.png
```

### Transparent backgrounds

```bash
brushrouter gen "a red paper lantern sticker" --background transparent -o sticker.png
```

The `codex` and `openai` (GPT Image) routes send transparency as an API field. Other routes ask in the prompt, so check the file. Even with the field set, the model decides — subject-shaped prompts (*sticker*, *isolated object*) are more likely to come back RGBA; full-scene wording may stay flattened.

### Codex size behavior

Codex doesn't take pixel dimensions and reads aspect ratio from the prompt. brushrouter appends your `-s 1672x941` as "width 1672 pixels, height 941 pixels (16:9)" — common aspect ratios land exactly or within 1px; other exact pixel counts aren't guaranteed.

### Pinning a model

`brushrouter models` lists what each provider can do; for OpenRouter the list is live, so it shows exactly what your key can reach.

```bash
brushrouter models openrouter
brushrouter gen "a red fox" -p openrouter -m x-ai/grok-imagine-image-2.0
```

A pin (`-m`, or `providers.<id>.model` in config) is never silently swapped. With no pin, brushrouter walks a preference list and takes the first model that works. Pins are honored by `codex-cli`, `codex`, `openrouter`, `gemini`, and `custom-http`; `gptweb2api` reports that it ignored the pin rather than pretending otherwise.

Models are resolved at runtime, not hardcoded — the Codex backend reads your `~/.codex/config.toml`, and a different model is only tried when the error is specifically "model not found". Quota (`429 usage_limit_reached`), auth (`401`), and regional/balance errors are reported as-is and never masked by a retry.

### Turning routes off

```bash
brushrouter routes                    # show state, in auto-routing order
brushrouter routes disable gptweb2api # skip it during auto-routing
brushrouter routes enable  gptweb2api
```

A disabled route is still reachable with `--provider <id>`. Non-interactive: `BRUSHROUTER_DISABLE=gemini,fal` and `BRUSHROUTER_ENABLE=openrouter`.

### History, replay, and usage stats

Every CLI, batch, replay, and MCP generation is recorded to an append-only JSONL manifest at `~/.config/brushrouter/history.jsonl` (mode `0600`, passed through the secret redactor before writing). Override the path with `BRUSHROUTER_HISTORY_PATH`, or disable logging with `BRUSHROUTER_NO_HISTORY=1` or `history.enabled: false` in config.

```bash
brushrouter history                         # recent 20 generations
brushrouter history show last               # full manifest + replay command for latest run
brushrouter history --provider openrouter --since 7d --failed
brushrouter history prune --keep 500        # or --before 30d (--dry-run to preview)

brushrouter replay last                     # replay latest prompt + seed + settings
brushrouter replay ~2 --provider fal --seed 42 --twist "at sunset"

brushrouter stats                           # latency (avg/p50/p95), success rate, spend
brushrouter stats --since 30d --json
```

Spend tracking prefers provider-reported costs (e.g. OpenRouter `usage.cost`), then custom per-image `pricing` overrides in config (e.g. `{ "openrouter/google/gemini-3.1-flash-image": 0.039 }`), marks subscription routes (`codex-cli`, `codex`, `gemini`, `gptweb2api`) as `$0 (subscription)`, and falls back to built-in estimates for common API models.

## Auth sources for ChatGPT routes

The `codex` and `codex-cli` routes use ChatGPT browser login — **no API key anywhere**. Credentials come from the first of:

1. `providers.codex.authFile` in config, or `BRUSHROUTER_CODEX_AUTH_FILE` (explicit)
2. **`~/.config/brushrouter/auth.json` — written by `brushrouter login`**
3. `~/.codex/auth.json` — Codex CLI / ChatGPT desktop app
4. `~/.local/share/opencode/auth.json` — OpenCode login
5. `~/.omp/agent/auth.json`, `~/.pi/agent/auth.json` — pi and oh-my-pi OAuth logins

`brushrouter login` opens a browser and signs in via the codex CLI's public OAuth client (PKCE, localhost:1455 callback) — nothing else to install, and the token refreshes itself. It prints `plan go/plus/...` so you know which subscription is billing the route. Sign out by deleting `~/.config/brushrouter/auth.json`. Free-plan users get a plain "plan-gated" message, not a raw 403.

## Providers

| id | needs | notes |
| --- | --- | --- |
| `codex-cli` | ChatGPT/Codex desktop app | **Native, preferred.** Drives the app's own signed CLI — already logged in, brushrouter never sees the token. |
| `codex` | ChatGPT login with a paid plan (`brushrouter login`, or any login on disk) | Direct backend call (`gpt-image-2`). Shares the Codex text quota. |
| `gemini` | Antigravity (`agy`) or Gemini CLI login | Delegates to the CLI; Google tokens never touch brushrouter. |
| `comfyui` | ComfyUI running locally | Off by default. Runs a built-in Flux Schnell workflow or a custom workflow. |
| `openrouter` | `sk-or-...` key | Off by default. Key auto-discovered from env or existing agent stores. |
| `fal` | fal.ai key | Defaults to Flux Schnell for text, Flux 2 for edits, and Flux LoRA for inpainting. |
| `openai` | `OPENAI_API_KEY` | Off by default. Direct Images API, default model `gpt-image-2.6-sunburst`; billed separately from ChatGPT. |
| `gemini-api` | `GEMINI_API_KEY` or `GOOGLE_API_KEY` | Off by default. Google AI Studio, default model `gemini-2.5-flash-image`; separate from the Google CLI route. |
| `replicate` | `REPLICATE_API_TOKEN` | Off by default. Defaults to `black-forest-labs/flux-schnell`. |
| `gptweb2api` | ChatGPT login (free plans work) + vendored gateway — `brushrouter vendor gptweb2api` | Off by default. Browserless web-session route, separate quota bucket (~2-3 free-plan images/day; see `docs/TECHNICAL.md`). |
| `custom-http` | your own endpoint | Template-based; point it at any image API. |

Default auto-routing order:

```text
codex-cli → codex → gemini → comfyui → openrouter → fal → openai → gemini-api → replicate → gptweb2api → custom-http
```

`openrouter`, `openai`, `gemini-api`, `replicate`, `comfyui`, `gptweb2api`, and `custom-http` are off by default. The `priority` list is authoritative — anything not listed is never auto-selected. If you already customized it, add the new routes you want auto-selected.

Set metered routes and their priority in your user config or environment. A checkout's config cannot enable a metered route or move it ahead of the routes you configured.

A route that is off is off for **every** path, including an explicit `--provider`: naming one is refused with a `PROVIDER_DISABLED` error that says how to turn it on. That matters most for the metered routes — `enabled: false` is the only thing between an agent holding a key and your credits, so it is not a preference a caller can talk its way past. Opt in once, deliberately:

```bash
brushrouter routes enable openrouter
brushrouter routes enable openai   # after setting OPENAI_API_KEY securely
```

OpenRouter runs two generation surfaces: multimodal chat models on `/chat/completions`, image-only models on `/images`. A "no endpoints found for output modalities" rejection is auto-retried on `/images`; auth, region, and credit errors are surfaced as they came.

### Configure editing backends

Set these options in your user config (`brushrouter init` creates a starter file):

- **fal:** Set `providers.fal.editModel` for an endpoint accepting `image_urls`, or `inpaintModel` for an endpoint accepting `image_url` and `mask_url`. A per-call `--model` overrides the relevant default.
- **Replicate:** Set `providers.replicate.model` to the editing model's `owner/name` (for models supporting the unversioned API) or `owner/name:<64-character version hash>`. Set `imageInput` and `maskInput` to the model's input field names. Set `imageInputArray: true` if the field takes an array. Pass other model-specific parameters in `inputs`; set `widthInput` and `heightInput` if the model accepts pixel dimensions.
- **ComfyUI:** Start ComfyUI, then run `brushrouter routes enable comfyui`. The default workflow needs `flux1-schnell.safetensors` as a diffusion model, `clip_l.safetensors` and `t5xxl_fp8_e4m3fn.safetensors` as text encoders, and `ae.safetensors` as its VAE. Override these with `model`, `clip`, `t5`, and `vae` under `providers.comfyui`. For editing, set `providers.comfyui.workflow` to the absolute path of a trusted workflow exported in **API format**. In node inputs, use `{prompt}`, `{image}` (or `{image1}`), `{image2}` for another reference, and `{mask}` for inpainting. You can also use `{seed}`, `{width}`, `{height}`, `{size}`, and `{model}`. A custom workflow needs `{seed}` to accept `--seed`. Use a `SaveImage` output node. Reference and mask files are uploaded to that ComfyUI server's input directory.

## The prompt library

An agent asked for "a nice product shot" will invent a worse prompt than one already tested. So the tool that routes the generation also hands the agent a skeleton to fill in.

164 entries:

| `kind` | what it is | count | source |
| --- | --- | --- | --- |
| `job` | a layout to fill in — a product shot, a character sheet | 27 | written here |
| `look` | a fixed visual system to borrow — an editorial or poster style | 137 | vendored, MIT |

```bash
brushrouter prompts                        # the map: what kinds of image exist
brushrouter prompts "product hero shot"    # 1 best match + 3 similar
brushrouter prompts --mode brainstorm "editorial" -n 4  # diverse contrasting directions
brushrouter prompts "flyer" -n 1           # force exactly one
brushrouter prompts -c infographic --full  # a whole category, full skeletons
brushrouter prompts --input image          # only recipes that can use a photo
brushrouter prompts --kind look "mono noir editorial"
brushrouter prompts --id logo-mark --full --set text=ACME --set subject="a peak" --twist "embossed foil"
brushrouter gen --recipe logo-mark --set text=ACME --twist "embossed foil" -o logo.png
brushrouter gen --recipe product-hero --look <look-id> --set subject="ceramic kettle" -o kettle.png
```

Design facts, briefly: every recipe works with no reference image (each has a text skeleton, plus an optional `image` upgrade naming what it accepts); unfilled `{slots}` are reported in `missing` rather than shipped to the image model; aesthetic slots (`lighting`, `mood`, `surface`, `grading`, `render`, `background`, `composition`, `type`) treat their curated options as creative suggestions so agents can invent freely while `ratio` stays strictly validated and auto-maps to exact aspect-ratio pixel dimensions on `gen`/`generate_image`. Any `job` layout can be composed with any `look` (`--look` / `look` / `composePrompt()`), merging the look's visual system, `STYLE LOCK`, `DO NOT REPRODUCE`, and MIT attribution; `--twist` / `twist` injects `CREATIVE DIRECTION — ...` right before `STYLE LOCK` and `AVOID`, and `--no-negatives` / `includeNegatives: false` drops `DO NOT REPRODUCE` / `AVOID` while keeping `STYLE LOCK`. A query that matches nothing still reports `matched: false` (never a random recipe), and returns `suggestions` (style-lock near-matches + nearest categories) so callers don't hit a dead end. Results are previews by default; `--full` returns the skeleton; `limit` is capped at 10 with `--offset` / `offset` for pagination.

Modes: `--mode categories` for a vague request, `--mode related` (default) for one best match plus alternatives, `--mode one` for a single entry, `--mode brainstorm` (or `--diverse` / `diverse: true`) for contrasting directions round-robined across categories and `job`/`look` kinds.

Custom recipes & looks: layer your own JSON files (single-entry or category bundles) on top of built-ins in `~/.config/brushrouter/recipes/` (or `BRUSHROUTER_EXTRA_RECIPES_DIRS`, colon/semicolon-separated) and project-local `.brushrouter/recipes/`. Trusted user/env dirs may override built-in ids; project-local `.brushrouter/recipes/` may only add new ids so an untrusted checkout cannot hijack built-in prompts. Set `BRUSHROUTER_NO_CUSTOM_RECIPES=1` to load built-ins only.

### Attribution

The 137 looks come from [VigoZhao/AI-Visual-Prompt-Cookbook](https://github.com/VigoZhao/AI-Visual-Prompt-Cookbook), published under MIT. They're vendored — pinned by commit, verified by hash, normalized into the same schema, shipped with the upstream licence and `ATTRIBUTION.md`. Every look carries its credit on the result itself, previews included; the licence requires it. Point `BRUSHROUTER_STYLES_FILE` at nothing and the library runs jobs-only instead of crashing.

Reproduce the data — neither source is read at runtime, neither is hand-edited:

```bash
npm run recipes:check    # validate every recipe and look against the schema
npm run styles:vendor    # re-vendor the looks from the pinned commit
npm run styles:check     # re-fetch upstream, recompute stylesSha256, compare
npm run corpus:analyze   # reproduce the structural findings behind the design
npm run corpus:check     # re-fetch upstream, recompute corpusSha256, compare
```

The 150-prompt corpus in `data/prompts/` is a development fixture, excluded from the npm tarball; nothing at runtime reads it. Schema, retrieval design, and failure modes are in [`docs/TECHNICAL.md`](docs/TECHNICAL.md).

## MCP server

`brushrouter install` detects and wires brushrouter into your installed agents (Claude Code, Claude Desktop, Cursor, Windsurf, OpenCode, Pi, Oh-My-Pi, DeepSeek Harness/DSH, CommandCode, Glass, shared MCP configs). Configs are backed up first (`.bak-...`), comments and formatting preserved, and no existing servers removed. Or add it by hand:

```json
{
  "mcpServers": {
    "brushrouter": { "command": "brushrouter", "args": ["serve"] }
  }
}
```

DeepSeek Harness (DSH) has no mcpServers JSON — its servers are YAML patch entries in `~/.dsh/profiles/<profile>/cordis.patch.yml` (profile defaults to `desktop`; set `BRUSHROUTER_DSH_PROFILE` to change). `brushrouter install --agent dsh` writes the marker-bounded, idempotent block for you, or by hand:

```yaml
- id: mcp-brushrouter
  name: "@deepseek-ai/dsh-mcp-client"
  config:
    serverName: brushrouter
    transport: stdio
    command: brushrouter
    args: ["serve"]
    toolCallTimeoutMs: 300000

```
Exposed tools:

- **`generate_image`** — `{ prompt?, recipe?, look?, values?, twist?, includeNegatives?, provider?, model?, fallback?, size?, quality?, background?, seed?, out?, images?, mask?, count?, concurrency?, async? }`. Accepts either a plain `prompt` or a direct `recipe`/`look` (failing fast if free slots are missing and auto-mapping `ratio` to `size`). Returns the saved path, history id, and image, all text through the redactor. `async: true` returns a `jobId` immediately instead of blocking for a minute or two.
- **`batch_generate_images`** — `{ prompts?, items?, outDir?, provider?, fallback?, concurrency?, embedImages?, async? }`. Generates multiple prompts in parallel across available providers; pass `items` with `prompt` (or `recipe`/`look`) and optional per-item `images` and `mask` (masks require a base image).
- **`image_result`** — `{ jobId }`. Collects an async `generate_image` or `batch_generate_images` job; poll again on a status while the job runs.
- **`find_image_prompts`** — `{ query?, category?, kind?, input?, shape?, mode?, diverse?, limit?, offset?, full?, id?, look?, twist?, includeNegatives?, format?, values?, seed? }`. Returns previews or a full skeleton (as text or structured JSON) to explore, brainstorm, or compose before generating.
- **`generation_history`** — `{ id?, query?, provider?, model?, status?, source?, since?, until?, limit?, offset?, format? }`. Lists or inspects recorded generations from the persistent manifest log.
- **`replay_generation`** — `{ id?, provider?, model?, seed?, size?, quality?, background?, prompt?, twist?, images?, mask?, noImages?, out?, fallback?, async? }`. Replays a past generation by id, prefix, `"last"`, `"~N"`, or saved path with optional overrides. By default replay reuses recorded reference images and masks; `noImages` drops both.
- **`usage_stats`** — `{ since?, until?, provider?, model?, source?, format? }`. Returns latency percentiles (`avg`/`p50`/`p95`/`min`/`max`), generation & attempt success rates, top error codes, model breakdown, daily trends, token totals, and USD spend.

Native MCP `prompts` and `resources` are also advertised on `initialize`:

- **`prompts/list`** & **`prompts/get`** — exposes every recipe and look as an MCP prompt with its slot arguments (plus optional `_look`, `_twist`, `_input`, `_noNegatives`).
- **`resources/list`** & **`resources/read`** — serves `brushrouter://categories`, `brushrouter://slots`, `brushrouter://recipes`, `brushrouter://recipes/<id>`, `brushrouter://history` (recent 50 generations), and `brushrouter://stats` (aggregated observability stats) as `application/json`.

An agent can either browse via `find_image_prompts` / native MCP `prompts` & `resources`, or pass `recipe`/`look`/`values`/`twist` directly to `generate_image` in a single tool call.

The `initialize` result also carries an `instructions` string telling the model when to use brushrouter (configurable via `instructions` in config or `BRUSHROUTER_INSTRUCTIONS`; `""` disables). And for rule-file agents, `brushrouter rules` injects ~60 tokens of guidance into the rule files of 12+ harnesses — AGENTS.md (Codex, OpenCode, Zed, Pi, Oh-My-Pi, DeepSeek Harness), CLAUDE.md (Claude Code), GEMINI.md (Gemini CLI), .cursorrules / .cursor rules (Cursor), .windsurfrules (Windsurf), .github/copilot-instructions.md (Copilot), .junie/guidelines.md (Junie) — demarcated so it updates in place:

```bash
brushrouter rules             # syncs guidance where the harness is detected (smart
                              # default: file exists OR the harness is installed)
brushrouter rules -v          # like dry-run detail: see what was skipped and why
brushrouter rules --dry-run   # preview changes
brushrouter rules --create    # create missing *project* rule files (e.g. AGENTS.md)
brushrouter rules --global    # restrict to global rule files (creates globals
                              # alongside --create; bare --create never does)
brushrouter rules --all       # target every known harness, even undetected ones
brushrouter rules --only codex-global,project-agents  # cherry-pick by target id
```

```markdown
<!-- BRUSHROUTER_START -->
## Image Generation (brushrouter)
Use the `brushrouter` MCP server (`generate_image`, `find_image_prompts`, or native MCP `prompts`/`resources`) or CLI `brushrouter gen "<prompt>" -o <path>` for creating or editing any images, UI mockups, icons, or diagrams. Avoid manual script creation or ad-hoc web scraping for image tasks. Pass `recipe`, `look`, `values`, and `twist` directly to `generate_image` (or `brushrouter gen --recipe`), use `mode: "brainstorm"` for diverse directions, and pass `async: true` with `image_result` for long generations.
<!-- BRUSHROUTER_END -->
```

Harnesses with a rule-file layout we don't know yet: paste that block into whatever context file the harness reads (system prompt, project rules, slash-command definition) — it's plain Markdown and updates in place on the next `rules` run if the markers are kept.

Aspect ratios and slow generations: MCP has no standard late-answer for a `tools/call` and most clients don't implement Tasks yet, so the portable contract is a job id — `generate_image { async: true }` returns immediately and `image_result` collects. `notifications/progress` and `tasks/status` may be emitted, but polling is the contract.

## Updating

```bash
brushrouter update          # pulls latest (git or npm global), refreshes links, runs doctor
brushrouter update --dry-run --json
```

Update reports failed pull, link or install steps and skips the health check on failure. In JSON mode the post-update `doctor` result is separate from the update result.

```bash
npm install -g brushrouter@latest
```

## Configuration

Nothing is hardcoded. Every path, binary, model, and endpoint is discovered at runtime, and every one can be overridden.

Precedence: **CLI flags → env → `./brushrouter.config.json` → `~/.config/brushrouter/config.json` → defaults.**

One exception: a *project* config may not set `baseUrl`, `url`, `cli`, `command`, `args`, `driver`, `authFile`, or `profile` — those are read only from user config, env, or a CLI flag. A project file travels with checkouts you didn't write, and a redirected `baseUrl` would hand your API key to whoever wrote it. Ignored keys are reported on stderr; per-project endpoints go in `BRUSHROUTER_CUSTOM_URL`.

```jsonc
// ~/.config/brushrouter/config.json
{
  "priority": ["codex-cli", "gemini", "openrouter"],
  "instructions": "brushrouter is the preferred tool for any image work...",  // MCP session guidance; "" disables
  "providers": {
    "codex-cli": { "cli": null, "model": null },   // null => auto-discover
    "openrouter": {
      "model": null,                                // pin one, or null to use the list below
      "models": ["google/gemini-3.1-flash-image"],  // your preference order
      "resolution": null                            // optional, for /images models
    },
    "gptweb2api": {
      "enabled": false,
      "bin": null,          // null => <config dir>/gptweb2api/gptweb2api
      "authFile": null,     // null => the codex-route credential ladder
      "projectId": null,    // ChatGPT project id (g-p-...) — parks gen chats in that workspace
      "idleMs": 600000      // gateway process exits after this idle time
    },
    "custom-http": {
      "enabled": true,
      "url": "https://api.example.com/v1/images",
      "body": "{\"prompt\": \"{prompt}\", \"size\": \"{size}\"}",
      "response": "json:data.0.url",   // or json:images.0.b64_json, or raw
      "keyHeader": "Authorization",
      "keyPrefix": "Bearer "
    }
  }
}
```

### Environment variables

| variable | purpose |
| --- | --- |
| `BRUSHROUTER_PRIORITY` | comma-separated auto-route order |
| `BRUSHROUTER_INSTRUCTIONS` | session guidance sent to MCP agents in `initialize` (empty string disables) |
| `BRUSHROUTER_DISABLE` / `BRUSHROUTER_ENABLE` | comma-separated routes to turn off / on (unknown name is an error, not a silent no-op) |
| `BRUSHROUTER_RECIPES_DIR` | use a different recipe directory (same schema) |
| `BRUSHROUTER_EXTRA_RECIPES_DIRS` | extra trusted custom recipe/look directories (path-delimiter separated) layered on top of built-ins |
| `BRUSHROUTER_NO_CUSTOM_RECIPES` | set to `1` to disable layered user/project custom recipe loading |
| `BRUSHROUTER_STYLES_FILE` | use a different vendored styles file |
| `BRUSHROUTER_APP_DIRS` | extra dirs to scan for app bundles (auto-discovery) |
| `BRUSHROUTER_MCP_CONFIGS` | extra agent MCP config paths for `install` |
| `BRUSHROUTER_CODEX_CLI` | explicit path to a Codex CLI binary |
| `BRUSHROUTER_CODEX_CLI_MODEL` | model for the native `codex-cli` route |
| `BRUSHROUTER_CODEX_MODEL` | model for the direct `codex` provider |
| `BRUSHROUTER_CODEX_AUTH_FILE` | explicit auth file for the direct `codex` provider |
| `BRUSHROUTER_CODEX_CLIENT_ID` | override the derived OAuth client id |
| `BRUSHROUTER_CODEX_ENDPOINT` | override the Codex responses endpoint |
| `BRUSHROUTER_OAUTH_TOKEN_ENDPOINT` | override the OAuth token endpoint |
| `BRUSHROUTER_ORIGINATOR` | `originator` header sent to the Codex backend |
| `BRUSHROUTER_GEMINI_CLI` / `BRUSHROUTER_GEMINI_MODEL` | Gemini CLI path / model |
| `BRUSHROUTER_OPENROUTER_KEY` / `BRUSHROUTER_OPENROUTER_MODEL` | OpenRouter key / pinned model |
| `BRUSHROUTER_OPENROUTER_MODELS` | comma-separated OpenRouter preference order |
| `BRUSHROUTER_OPENROUTER_RESOLUTION` | image resolution requested from OpenRouter |
| `BRUSHROUTER_FAL_KEY` / `BRUSHROUTER_FAL_MODEL` | fal.ai |
| `BRUSHROUTER_FAL_EDIT_MODEL` / `BRUSHROUTER_FAL_INPAINT_MODEL` | fal.ai edit / inpainting endpoints |
| `OPENAI_API_KEY` / `BRUSHROUTER_OPENAI_KEY` | OpenAI Images credential |
| `GEMINI_API_KEY` / `GOOGLE_API_KEY` / `BRUSHROUTER_GEMINI_API_KEY` | Google AI Studio credential |
| `REPLICATE_API_TOKEN` / `BRUSHROUTER_REPLICATE_KEY` | Replicate credential |
| `BRUSHROUTER_OPENAI_MODEL` / `BRUSHROUTER_GEMINI_API_MODEL` / `BRUSHROUTER_REPLICATE_MODEL` | direct API model defaults |
| `BRUSHROUTER_COMFYUI_URL` / `BRUSHROUTER_COMFYUI_MODEL` / `BRUSHROUTER_COMFYUI_WORKFLOW` | ComfyUI server (default `http://127.0.0.1:8188`), model, and API-format workflow path |
| `BRUSHROUTER_GPTWEB_COOKIE` | cookie fallback for the vendored gptweb2api route |
| `BRUSHROUTER_GPTWEB_PROJECT_ID` | ChatGPT project (`g-p-...`) that anchors gptweb2api generations |
| `BRUSHROUTER_CUSTOM_URL` / `BRUSHROUTER_CUSTOM_KEY` | custom HTTP |

Discovery scans `$PATH`, `/Applications`, `~/Applications`, the npm global root, and `~/.cache/codex-runtimes`, so a Codex CLI installed any of the usual ways is found without configuration.

## Security

A model never sees your credentials. Design constraint, not a setting:

- Keys live in the environment or a `0600` `~/.config/brushrouter/keys.json` inside a `0700` directory. Config files hold non-secret settings only.
- Every string brushrouter emits — CLI output, `--json`, errors, `doctor`, MCP results — passes through a redactor that strips known secret values and well-known token shapes (JWTs, `sk-...`, `ya29.…`, `Bearer ...`, refresh tokens), plus tokens registered by value from disk. The test suite asserts a fake secret survives no output path.
- `codex-cli` and `gemini` never read a token at all: they spawn a child process that owns its own authentication.
- What it does *not* confine: `--out` writes anywhere you say and `--images` reads any local file that sniffs as an image. Deliberate — the caller is your own agent, which already has those abilities; the MCP tool description states the capability rather than implying a sandbox.

## Limits

brushrouter doesn't pretend a broken backend works.

- Quota (`429 usage_limit_reached`) is reported as quota, with reset time, and never triggers a wasteful model retry.
- Auth (`401`, or not logged in) is reported as auth, with the command to fix it.
- A retired model (`404 model_not_found`) is the only case that tries the next model.
- A deprecated free tier (e.g. Google's retired Gemini CLI individual tier) is labeled as such.

The Codex **text quota and the native image path share a bucket**; when exhausted, the native route says so and routing moves on. The ChatGPT *web* Images bucket is separate, but reaching it needs the gptweb2api route — the app's own conduit is App-Attest protected and can't be forged.

## Why I built this

Image generation is the one thing I refuse to pay per image for. I already pay for ChatGPT and already have a Google login — two capable image generators sitting on this machine — and I was still opening a browser tab or topping up an API balance. So the route order falls straight out of "spend what I already pay for first". The other two rules: ship the prompts too (a free image from a bad prompt is a wasted call), and never let a model see a token or pretend a broken backend works.

## Development

```bash
npm test                        # 144 tests, no dependencies
npm run recipes:check           # validate every recipe and look against the schema
npm run styles:check            # re-fetch the pinned cookbook, verify stylesSha256
node bin/brushrouter.js doctor
```

Zero runtime dependencies, ESM, Node 20+.

## Credits and license

MIT for the code, for the recipe library in `data/recipes/`, and for the normaliser that produces `data/styles/`. We wrote the recipes.

The direct Codex backend image generation integration (`images/generations` and `images/edits` for `gpt-image-2`), subscription auth discovery patterns, and prompt-driven aspect ratio handling were learned from and inspired by [yuji-hatakeyama/opencode-gpt-imagegen](https://github.com/yuji-hatakeyama/opencode-gpt-imagegen).

The 137 looks in `data/styles/` are vendored from [VigoZhao/AI-Visual-Prompt-Cookbook](https://github.com/VigoZhao/AI-Visual-Prompt-Cookbook) at a pinned commit, MIT (`Copyright (c) 2026 VigoZhao`); upstream `LICENSE` and `ATTRIBUTION.md` ship with them.

The 150-prompt corpus in `data/prompts/` is a development fixture, not shipped and not covered by that licence — third-party text redistributed under its upstream terms (115 rows CC0, 35 rows CC-BY, authors credited in `data/prompts/ATTRIBUTION.md`; full terms in `data/prompts/LICENSES/`). Quote a prompt along with its `author` and `sourceUrl`.

## Disclaimer

This is an **unofficial, third-party** tool, not affiliated with or endorsed by OpenAI, Google, OpenRouter, fal.ai, OpenCode, or any other supported provider.

Use of this tool must comply with the terms of use, usage policies, and service agreements of whichever model providers or platforms you access through brushrouter.