## 1. Project Overview & Quickstart (Kuberwastaken/claurst)

## File: README.md

---

Claurst is an **open-source, multi-provider terminal coding agent** built from the ground up in Rust. It started as a clean-room reimplementation of Claude Code's behavior (from [spec](https://github.com/kuberwastaken/claurst/tree/main/spec)) and has since evolved into an amazing TUI pair programmer with multi-provider support, a rich UI, plugin system, a companion named Rustle, chat forking, memory consolidation, and much more.

It's fast, it's memory-efficient, it's yours to run however you want, and there's no tracking or telemetry.

---

> [!IMPORTANT]
> **Claurst is now officially in Beta (v0.1.7).** The core agent, multi-provider routing, and TUI are stable enough for daily driving — expect rough edges around experimental features (flagged below). Bug reports and PRs welcome.

> [!NOTE]
> **Recent Updates:**
>
> - **/share support:** Use `/share` to share chat sessions with others via unlisted GitHub Gists. `[EXPERIMENTAL]`
>
> - **Free Mode:** Try out Free in '/connect' to get a great agentic coding experience in Claurst for absolutely free (or as good as free gets you :P). `[EXPERIMENTAL]` 
>
> - **/goal support:** Try out `/goal <objective>` to see claurst keep working an objective, spanning multiple turns instead of stopping after one normal turn. `[EXPERIMENTAL]`
>
> - **ultracode:** The **highest effort level** — pick it in the effort selector (`/effort`, where it sits past `max` on the "Smarter" end with an animated purple spectrum) or just type **`ultracode`** anywhere in your prompt. The keyword lights up with a purple gradient (claurst's take on Claude Code's `ultrathink`) and that turn runs at the model's top reasoning **plus** a disciplined plan → delegate → integrate → verify workflow that fans bounded packets out across native subagents (`Agent`), swarms (`TeamCreate`), and background tasks (`TaskCreate`). Composes with `/goal` for sustained multi-turn objectives. `[EXPERIMENTAL]`

---

# Getting Started

## Quick install (one-liner)

**Linux / macOS:**

```bash
curl -fsSL https://github.com/kuberwastaken/claurst/releases/latest/download/install.sh | bash
```

**Windows (PowerShell):**

```powershell
irm https://github.com/kuberwastaken/claurst/releases/latest/download/install.ps1 | iex
```

This drops `claurst` into `~/.claurst/bin` (or `%USERPROFILE%\.claurst\bin` on Windows) and adds it to your `PATH` automatically. Open a new terminal and run `claurst`.

## Via npm / bun

If you have Node.js or Bun installed, you can install Claurst as a global package. The postinstall script automatically downloads the right pre-built binary for your platform.

```bash
# npm
npm install claurst

# bun
bun install -g claurst

# or run without installing
npx claurst
bunx claurst
```

To upgrade later, run:

```bash
claurst upgrade
```

> Pin a specific version with `--version 0.1.0` on either installer, or `claurst upgrade --version 0.1.0`.

## Manual download

If you'd rather grab the binary yourself, the latest archives are on [**GitHub Releases**](https://github.com/kuberwastaken/claurst/releases):

| Platform | Archive |
|----------|---------|
| **Windows** x86_64 | `claurst-windows-x86_64.zip` |
| **Linux** x86_64 | `claurst-linux-x86_64.tar.gz` |
| **Linux** aarch64 | `claurst-linux-aarch64.tar.gz` |
| **macOS** Intel | `claurst-macos-x86_64.tar.gz` |
| **macOS** Apple Silicon | `claurst-macos-aarch64.tar.gz` |

Each archive contains a single `claurst` (or `claurst.exe`) binary. Extract it and put it on your `PATH`.

## Build from source

```bash
git clone https://github.com/kuberwastaken/claurst.git
cd claurst/src-rust
cargo build --release --package claurst

# Binary is at target/release/claurst
```

**Raspberry Pi / systems without ALSA** (e.g. Debian Trixie, headless servers):

```bash
# Build without voice/microphone support — no libasound2-dev required
cargo build --release --package claurst --no-default-features
```

## First run

```bash
# Set your API key (or use /connect inside Claurst to configure)
export ANTHROPIC_API_KEY=sk-ant-...

# Start Claurst
claurst

# Or run a one-shot headless query
claurst -p "explain this codebase"
```

## Devcontainer setup

After cloning this repository, open it in VS Code and use Reopen in Container to start the development environment.

Prerequisites:
- Docker installed on your host machine: https://www.docker.com/products/docker-desktop/

GPG and SSH forwarding is enabled in the devcontainer, given you have it set up on your host machine. Follow [this guide](https://code.visualstudio.com/remote/advancedcontainers/sharing-git-credentials) if you need help with that.

### Devcontainer features

- Base image: `rust:1-bullseye`.
- Preinstalled build dependencies: `gnupg2`, `libasound2-dev`, `libxdo-dev`, and `pkg-config`.
- Devcontainer features enabled: `common-utils` (with `vscode` user `uid/gid 1000` and Zsh install disabled), `git`, and `docker-outside-of-docker` (`moby: false`).
- Runs as `vscode` user by default.
- Persistent Cargo caches via named volumes for `/usr/local/cargo/registry` and `/usr/local/cargo/git`.
- Binds local `.claurst` into `/home/vscode/.claurst` for local settings/session history access.
- Sets `GNUPGHOME=/home/vscode/.gnupg` and prepends `src-rust/target/debug` and `src-rust/target/release` to `PATH`.
- Post-create setup creates and permissions `.gnupg`, and fixes ownership for `/usr/local/cargo`.
- VS Code setting `terminal.integrated.inheritEnv` is enabled.

## Editor integration (Agent Client Protocol)

Claurst speaks the [**Agent Client Protocol (ACP)**](https://agentclientprotocol.com) — the open protocol pioneered by Zed for editor-to-agent communication. Any ACP-compatible editor (Zed, Neovim, JetBrains plugins, …) can drive Claurst as a subprocess and present it in the editor's native chat UI.

To use Claurst as the agent in your editor, point its ACP integration at:

```
command: claurst
args:    ["acp"]
```

**Zed example** (`~/.config/zed/settings.json`):

```jsonc
{
  "agent_servers": {
    "claurst": {
      "command": "claurst",
      "args": ["acp"]
    }
  }
}
```

Claurst will run in JSON-RPC 2.0 mode over stdio. It implements `initialize`, `session/new`, `session/prompt`, and `session/cancel`, streams `session/update` notifications (text deltas, agent thinking, tool calls with their progress + results), and routes every tool permission through `session/request_permission` so the editor can show a native approval dialog.

Configure your provider / API key in `~/.claurst/settings.json` (or `claurst auth login` / `claurst /connect`) before launching — the ACP agent uses the same credentials and providers as the interactive TUI.

Enable verbose ACP logging (to stderr — never stdout, which would corrupt the protocol) by setting `CLAURST_ACP_LOG=debug`.

### Listing on the ACP Registry

The [Agent Client Protocol registry](https://github.com/agentclientprotocol/registry) is the canonical directory editors look up when offering "available agents". To get Claurst listed:

1. Fork [`agentclientprotocol/registry`](https://github.com/agentclientprotocol/registry).
2. Create a `claurst/` folder at the repo root and drop in the prepared manifest from this repo: [`src-rust/crates/acp/registry-template/agent.json`](src-rust/crates/acp/registry-template/agent.json). Bump the `version` and release-archive URLs to match the latest GitHub release.
3. Add `claurst/icon.svg` (16×16 recommended) — the Rustle logo from [`public/`](public/) is a fine starting point.
4. Open a PR to the registry. The registry CI validates `agent.json` against [the schema](https://github.com/agentclientprotocol/registry/blob/main/agent.schema.json) before merge.

After merge, Zed and other ACP-aware editors will pick up Claurst on their next registry refresh.

## Documentation

For more info on how to configure Claurst, [head over to our docs](https://claurst.kuber.studio/docs).

>**PS:** The original breakdown of the findings from Claude Code's source that started this project is on [my blog](https://kuber.studio/blog/AI/Claude-Code's-Entire-Source-Code-Got-Leaked-via-a-Sourcemap-in-npm,-Let's-Talk-About-it) - the full technical writeup of what was found, how the leak happened, and what it revealed.

---

## Contributing

Claurst is built for the community, by the community and we'd love your help making it better.
Please see and include AGENTS.md for project-specific rules (for both humans and agents).

[Open an issue](https://github.com/Kuberwastaken/claurst/issues/new) for bugs, ideas, or questions, or [Raise a PR](https://github.com/Kuberwastaken/claurst/pulls/new) to fix bugs, add features, or improve documentation.

---

## Important Notice

This repository does not hold a copy of the proprietary Claude Code TypeScript source code.
This is a **clean-room Rust reimplementation** of Claude Code's behavior.

The process was explicitly two-phase:

**Specification** [`spec/`](https://github.com/kuberwastaken/claurst/tree/main/spec) — An AI agent analyzed the source and produced exhaustive behavioral specifications and improvements, deviated from the original: architecture, data flows, tool contracts, system designs. No source code was carried forward.

**Implementation** [`src-rust/`](https://github.com/kuberwastaken/claurst/tree/main/src-rust) — A separate AI agent implemented from the spec alone, never referencing the original TypeScript. The output is idiomatic Rust that reproduces the behavior, not the expression.

This mirrors the legal precedent established by Phoenix Technologies v. IBM (1984) — clean-room engineering of the BIOS — and the principle from Baker v. Selden (1879) that copyright protects expression, not ideas or behavior.

---

---

## File: docs/advanced.md

# Advanced Features

This document covers Claurst's advanced capabilities beyond basic coding assistance.

---

## Extended thinking

Extended thinking gives the model additional computation budget to reason through hard problems before it responds.

### Commands

```
/thinking          Toggle extended thinking on or off for the session
/effort <level>    Set the effort level: low, medium, high, or max
```

### CLI flags

```
claurst --thinking <tokens>    Set a specific token budget for thinking
claurst --effort <level>       Set the effort level (low/medium/high/max)
```

### Effort levels

| Level | Description |
|---|---|
| `low` | Minimal thinking; fastest responses |
| `medium` | Moderate reasoning; balanced speed and quality |
| `high` | Deep reasoning; best quality for most tasks |
| `max` | Maximum available budget; reserved for Opus-class models |

The `max` level is only supported by models that expose it in the API (currently the Opus 4.6 generation). Attempting to set `max` on an unsupported model will fall back to `high`.

Effort levels `low`, `medium`, and `high` persist to `~/.claude.json` across sessions. The `max` level is session-scoped for regular users. Numeric budget values (raw token counts) are always session-scoped.

**Environment variable override:** `CLAUDE_CODE_EFFORT_LEVEL` overrides the persisted setting for the current process. If this variable is set and conflicts with a `/effort` command, Claurst displays a warning.

### How the API maps levels

The effort parameter is passed directly to the Anthropic API for supported models. When no effort parameter is sent (the default), the API uses `high`. The displayed status bar reflects the effective level as `resolveAppliedEffort` computes it: env override, then session state, then persisted setting.

---

## Auto-compaction

The context window has a finite size. Auto-compaction automatically summarises the conversation history when token usage approaches the limit, keeping the session alive without interruption.

### How it works

Claurst tracks token usage after every model turn. When usage crosses the auto-compact threshold — which is the effective context window size minus a 13,000-token buffer — it runs `compactConversation` to summarise the history and replaces the messages with a compact summary plus any trailing context.

The `PreCompact` hook fires before compaction (exit code 2 blocks it). The `PostCompact` hook fires after.

### Controlling auto-compaction

**Disable for a process:**

```bash
DISABLE_AUTO_COMPACT=1 claurst
```

This disables automatic compaction while keeping `/compact` available manually.

**Disable compaction entirely:**

```bash
DISABLE_COMPACT=1 claurst
```

**Override the threshold window (for testing):**

```bash
CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=80 claurst
```

Sets the threshold to 80% of the effective context window instead of the default buffer-based calculation.

**Toggle in global config:**

`autoCompactEnabled` in `~/.claude.json` (boolean, default `true`). The `/compact` command respects this; auto-compact also checks it via `getGlobalConfig().autoCompactEnabled`.

### Manual compaction

```
/compact [custom instructions]
```

Runs compaction immediately. Optionally pass custom instructions to guide the summary (e.g. `/compact focus on the database schema changes`).

---

## Context window management

### /context

```
/context
```

Displays the current token usage relative to the model's context window. Shows the percentage remaining and warns when approaching the warning or error thresholds.

- **Warning threshold:** 20,000 tokens before the effective window limit.
- **Error threshold:** 20,000 tokens before the effective window limit (triggers a more prominent visual).
- **Blocking limit:** 3,000 tokens before the effective window — further input is blocked until compaction.

### ctx-viz

```
/ctx_viz
```

Opens an interactive visualisation of which parts of the context are consuming the most tokens. Useful for identifying large files or long tool outputs that could be trimmed.

---

## Session management

Sessions are stored as JSONL files under `~/.claurst/projects//<session-id>.jsonl`. Each line in the file is a JSON object representing a message or event in the conversation. The per-session metadata index lives at `~/.claurst/sessions/.json`.

The transcript directory is derived from the working directory at session start. Worktrees and path sanitisation mean the per-project folder name is a normalised representation of the absolute path.

### Commands

| Command | Description |
|---|---|
| `/resume [id or search]` | Resume a previous session by ID or fuzzy search term. Alias: `/continue`. |
| `/session` | Show the remote session URL and QR code (available in remote mode). |
| `/fork` | Fork the current session into a new branch with fresh UUIDs, preserving the full message history. |
| `/rename <title>` | Rename the current session. Appends a custom-title entry to the JSONL file. |
| `/export` | Export the current session transcript. |
| `/rewind` | Step back to an earlier point in the conversation. |

### JSONL transcript format

Every message in the transcript is a newline-delimited JSON object. The key fields present on most entries:

```jsonl
{"uuid":"","parentUuid":"","type":"user","message":{...},"timestamp":1234567890}
{"uuid":"","parentUuid":"","type":"assistant","message":{...},"timestamp":1234567891}
```

The `parentUuid` field forms a linked chain that allows Claurst to reconstruct the conversation tree. `/fork` rewrites all UUIDs while preserving the chain structure.

Special entry types include `summary` (compaction summaries), `custom-title` (from `/rename`), and various ephemeral progress indicators that are filtered out when reading the transcript for display.

### SDK access

The public SDK exports `getSessionMessages`, `listSessions`, `getSessionInfo`, `renameSession`, `tagSession`, and `forkSession` for programmatic access to session data.

---

## Worktree support

Subagents spawned via the `Agent` tool can operate in isolated git worktrees to avoid interfering with the main working tree.

### Tools

- `EnterWorktreeTool` — checks out a new worktree and switches the agent's working directory to it.
- `ExitWorktreeTool` — removes the worktree and returns the agent to the original directory.

### Custom worktree backends

For non-git repositories or specialised isolation requirements, the `WorktreeCreate` and `WorktreeRemove` hook events let you substitute an external worktree manager:

- `WorktreeCreate` receives `{"name": "<slug>"}` and must write the absolute path of the created directory to stdout.
- `WorktreeRemove` receives `{"worktree_path": ""}` and is responsible for cleanup.

This means worktrees can be Docker containers, virtual machines, or any directory-backed isolation primitive.

---

## Plan mode

Plan mode restricts the model to read-only operations, allowing it to research a codebase and propose a plan before making any changes.

### Entering plan mode

```
/plan [description]
claurst --permission-mode plan
```

When in plan mode:
- Write and execute operations require explicit permission.
- The model can read files, search, and reason freely.
- Exiting plan mode (via `ExitPlanModeTool`) returns to the normal permission model.

The `EnterPlanModeTool` and `ExitPlanModeTool` internal tools manage transitions. A `plan_mode_exit` attachment is injected into the conversation when the mode changes to guide the model's next steps.

---

## Goal system

The goal system lets Claurst work autonomously across multiple turns toward a single, verifiable objective. Instead of prompting repeatedly, you set the goal once and Claurst iterates until the goal is complete, paused, or the built-in runaway guard fires.

### Setting a goal

```
/goal <objective>
/goal --tokens 250K Refactor the auth module to use JWT tokens
```

Once a goal is set, Claurst begins working immediately. It continues across turns without waiting for user input until one of these conditions is met:

- The model calls `GoalCompleteTool` with an audit summary and evidence
- You run `/goal pause` or `/goal clear`
- The runaway guard fires (200-turn hard limit)
- A token budget is set and exhausted

### Monitoring and controlling goals

```
/goal                  — show current goal status
/goal status           — show current goal status
/goal pause            — pause the active goal (you can resume it later)
/goal resume           — resume a paused goal
/goal clear            — delete the current goal entirely
/goal complete         — manually request a completion audit
```

### How completion works

When the model believes the objective has been met, it calls `GoalCompleteTool` rather than simply responding. This tool requires two arguments:

- `audit_summary` — a concise description of what was accomplished
- `evidence` — specific, verifiable evidence (files changed, tests passing, output produced)

Claurst displays both to the user before marking the goal complete. The model is expected to genuinely audit the outcome before calling; calling without real evidence is rejected.

### Goal status lifecycle

| Status | Meaning |
|--------|---------|
| `Active` | Goal is set and work is ongoing |
| `Paused` | Work paused by user; goal is preserved |
| `Completed` | Model called `GoalCompleteTool` with accepted audit |
| `Failed` | Runaway guard fired or budget exhausted |

### Disabling the goal system

```bash
CLAURST_GOALS=0 claurst
```

Set `CLAURST_GOALS=0` in the environment to completely disable goal-related commands and the `GoalCompleteTool`. Useful in environments where autonomous multi-turn execution is undesirable.

---

## Managed agents

Managed agents enable a **manager-executor** architecture where a manager model delegates subtasks to one or more executor agents running in parallel. The manager reasons about the high-level plan; executors carry out individual tasks.

### Enabling managed agents

```
/managed-agents enable
```

Or apply a built-in preset:

```
/managed-agents presets               — list available presets
/managed-agents preset <name>         — apply a preset (configures all parameters)
```

### Architecture

```
User → Manager model
         ├─ Executor 1 (e.g., implementing feature A)
         ├─ Executor 2 (e.g., writing tests for A)
         └─ Executor 3 (e.g., updating docs)
```

The manager model does not execute tools itself — it delegates to executor agents and synthesizes their outputs. Executors can run concurrently up to the `concurrent` limit.

### Configuration

```
/managed-agents configure manager-model  anthropic/claude-opus-4-6
/managed-agents configure executor-model anthropic/claude-sonnet-4-6
/managed-agents configure executor-turns 20
/managed-agents configure concurrent     3
/managed-agents configure isolation      on
```

Model format: `provider/model` (e.g., `anthropic/claude-opus-4-6`, `openai/gpt-4o`).

### Budget split policies

Control how the total token/cost budget is divided between the manager and executors:

| Policy | Command | Description |
|--------|---------|-------------|
| `shared` | `budget-split shared` | All agents draw from a single shared pool |
| `percentage` | `budget-split percentage:20` | Manager gets 20%, executors share the rest |
| `fixed` | `budget-split fixed:0.50:2.00` | Manager capped at $0.50, each executor at $2.00 |

```
/managed-agents budget 5.00           — set a total $5 budget (0 to clear)
```

### Viewing configuration

```
/managed-agents status
```

Configuration persists to `~/.claurst/settings.json` under `managed_agents`.

> **Preview feature.** The managed-agents API is under active development and may change in future releases.

---

## Speech modes

Speech modes change how the model structures its responses, trading naturalness for brevity. Useful in long sessions where verbose responses consume too many tokens or take too long to read.

### Caveman mode

Strips pleasantries, hedging phrases, transitional sentences, and articles. Output is dense and telegraphic.

```
/caveman             — full caveman mode (~75% token reduction)
/caveman lite        — remove pleasantries only (~40% reduction)
/caveman full        — compress sentences, drop articles (~75% reduction, default)
/caveman ultra       — maximum compression, imperative only (~85% reduction)
```

**Example (normal mode):**
> "I'd be happy to help with that. Let me take a look at the file and see what changes might be appropriate here."

**Example (caveman full):**
> "Look at file. Make changes."

### Rocky mode

The model adopts the communication style of Rocky from *Project Hail Mary* — an Eridian alien engineer with a distinctive grammar, heavy emphasis, and alien perspective on human tasks.

```
/rocky             — full Rocky mode (~75% token reduction)
/rocky lite        — grammar rules only, minimal emphasis (~40% reduction)
/rocky full        — full grammar + regular emphasis (~75% reduction, default)
/rocky ultra       — maximum personality, frequent emphasis, alien observations
```

**Example (rocky full):**
> "Read file. *Yes!* Change function. Return value wrong! Fix now. *Eridians not make this mistake.*"

### Deactivating speech modes

```
/normal
```

Resets to the model's standard response style. Any active mode (caveman or rocky) is immediately deactivated.

---

## Headless mode

Headless mode runs Claurst non-interactively, suitable for scripts, CI pipelines, and programmatic orchestration.

### --print flag

```bash
claurst --print "refactor this function to use async/await"
claurst -p "summarise the changes in this PR"
```

Processes the prompt and exits after printing the final response to stdout. No interactive UI is shown.

Input can also be piped via stdin:

```bash
cat my_prompt.txt | claurst --print
echo "explain this code" | claurst -p
```

### --output-format

```bash
claurst --print --output-format json "..."
claurst --print --output-format stream-json --verbose "..."
```

| Format | Description |
|---|---|
| (default) | Plain text output — only the final assistant message. |
| `json` | Full message array as JSON (requires `--verbose`). |
| `stream-json` | Newline-delimited JSON stream of messages as they arrive (requires `--verbose`). |

`stream-json` is the format used by the Agent SDK transport. It emits every message event as it arrives, making it suitable for real-time processing pipelines.

---

## Budget control

Limit resource consumption per invocation using CLI flags:

```bash
claurst --max-budget-usd 2.00 "..."   # Stop after spending $2.00
claurst --max-turns 10 "..."          # Stop after 10 model turns
claurst --max-tokens 50000 "..."      # Stop after 50,000 output tokens
```

When a limit is reached, Claurst exits with a corresponding error message:
- `Error: Reached max turns (<n>)`
- `Error: Exceeded USD budget (<amount>)`

These flags are intended for automated use where runaway sessions would be costly.

---

## The Buddy companion system

Every Claurst user gets a persistent companion derived deterministically from their user ID. The companion appears as a small sprite in the terminal UI and occasionally comments on activity.

### How companions are generated

The companion's visual traits (species, eyes, hat, rarity, shiny status, stats) are generated by hashing the user ID with a seeded PRNG (Mulberry32). This means the companion is always the same for a given user — it cannot be faked by editing config files, because the bones are regenerated from the hash on every read.

Only the soul (name, personality) is persisted to `~/.claude.json` under the `companion` key, and only after it has been "hatched" (named by the model on first encounter).

### Species

18 species are available: duck, goose, blob, cat, dragon, octopus, owl, penguin, turtle, snail, ghost, axolotl, capybara, cactus, robot, rabbit, mushroom, chonk.

### Rarity tiers

| Rarity | Weight | Stars |
|---|---|---|
| common | 60% | ★ |
| uncommon | 25% | ★★ |
| rare | 10% | ★★★ |
| epic | 4% | ★★★★ |
| legendary | 1% | ★★★★★ |

Rarity affects the floor value of the companion's stats. A legendary companion has a minimum stat floor of 50, while a common companion starts at 5.

### Stats

Each companion has five stats: DEBUGGING, PATIENCE, CHAOS, WISDOM, SNARK. One stat is the peak (higher rolls), one is the dump stat (lower rolls), and the rest are scattered around the rarity floor.

### Persistence

The stored companion format in `~/.claude.json`:

```json
{
  "companion": {
    "name": "Vortox",
    "personality": "a chaotic little axolotl who celebrates every bug as a feature",
    "hatchedAt": 1712345678901
  }
}
```

The bones (species, rarity, stats, eyes, hat, shiny) are never stored and are always recomputed from `hash(userId)`.

---

## Voice mode

```
/voice
```

Experimental voice input using the device microphone. When active, spoken input is transcribed and submitted as a prompt. The integration uses the Deepgram streaming STT API.

The `/voice` command is a toggle. `CLAUDE_CODE_ENABLE_VOICE=1` can be used to pre-enable voice mode.

---

## Vim keybindings

```
/vim
```

Toggles vim-style modal keybindings for the input buffer. When enabled, the prompt input operates in normal/insert/visual modes, allowing navigation and editing with standard vim motions.

The setting persists to user settings. The `--vim` CLI flag enables vim mode for the session without persisting.

---

## Bridge and remote sessions

Claurst can be controlled remotely through a web interface at claude.ai. This "bridge" mode keeps a WebSocket connection open that allows a remote UI to send prompts and receive streaming responses.

```
/session
```

Shows the current remote session URL and a QR code for scanning on mobile.

The bridge operates in two topologies:
- **In-process bridge** — the WebSocket lives inside the Claurst process. If the process dies, the connection is lost.
- **Daemon bridge** — the WebSocket lives in a parent daemon process. The agent can be respawned while the claude.ai session stays connected. This is the `connectRemoteControl` SDK primitive.

SSH sessions work similarly: `claurst --ssh` enables a remote-accessible session that can be connected to from another machine.

---

## AGENTS.md hierarchical memory

Claurst reads instruction files from the filesystem before every session and whenever a relevant file changes. The lookup order is:

1. **Managed** — `/etc/claude-code/AGENTS.md` and `/etc/claude-code/CLAUDE.md` (administrator-controlled, always loaded).
2. **User** — `~/.claurst/AGENTS.md` then `~/.claurst/CLAUDE.md` (personal global instructions).
3. **Project** — `AGENTS.md`, `CLAUDE.md`, `.claurst/AGENTS.md`, and `.claurst/CLAUDE.md` in each directory from the filesystem root down to the current working directory. Files are loaded from the root toward the CWD so that parent-directory rules are visible when processing child-directory rules.

`AGENTS.md` is preferred (universal cross-tool standard); `CLAUDE.md` is loaded next at every scope for compatibility with other Claude tooling. If both exist at the same scope, both are loaded.

Files can `@include` other files using a frontmatter include directive. Included files are resolved relative to the including file.

The `InstructionsLoaded` hook event fires for every file that is loaded, with the `load_reason` field indicating why (e.g. `session_start`, `nested_traversal`, `path_glob_match`, `include`, `compact`).

The `/memory` command opens the memory management UI for viewing, editing, and organising instruction files.

---

## Security and permissions

### Permission modes

| Mode | Description |
|---|---|
| `default` | Prompts the user before executing dangerous or write operations. |
| `plan` | Read-only; write and execute require explicit approval. |
| `autoAccept` | Accepts all tool calls without prompting. Use with caution. |
| `bypassPermissions` | Skips the permission system entirely. Intended for trusted automation only. |

The active mode is set with `--permission-mode <mode>` or via the `PermissionRequest` hook.

### Tool risk classification

Every tool is classified into a risk tier that determines the default permission behaviour:

| Tier | Examples | Default behaviour |
|---|---|---|
| `forbidden` | Directly destructive operations | Always blocked |
| `dangerous` | Broad filesystem writes, network access | Prompt required |
| `execute` | Bash, shell commands | Prompt required |
| `write` | FileWrite, FileEdit, TodoWrite | Prompt in default mode |
| `readonly` | FileRead, Glob, Grep, WebFetch | Allowed automatically |

### Bash command risk classification

Within `BashTool`, commands are further classified by analysing the command string against known patterns. Commands matching dangerous patterns (e.g. `rm -rf`, `dd if=`, pipe chains with destructive intent) receive a higher risk rating and may be blocked depending on the active permission mode.

The `PermissionRequest` hook can intercept any tool call before the user prompt is displayed, allowing automated allow/deny decisions based on context.

---

## Output styles

```
/output-style [style]
```

Controls how Claurst formats its responses. Available styles vary by configuration; the command opens an interactive picker when called without arguments.

Output styles affect markdown rendering, code block formatting, and verbosity of tool call summaries in the terminal UI.

---

## Custom commands

Custom slash commands can be defined in `.claude/settings.json` under a `customCommands` key. A custom command is a template that expands to a prompt when invoked.

```json
{
  "customCommands": [
    {
      "name": "review",
      "description": "Review the staged git diff",
      "command": "Review the output of `git diff --staged`. Focus on correctness, edge cases, and naming."
    },
    {
      "name": "standup",
      "description": "Summarise today's work",
      "command": "Summarise what I worked on today based on the git log since midnight."
    }
  ]
}
```

Custom commands appear alongside built-in commands in the `/` menu.

---

## Formatters

Auto-formatters run automatically after file writes when configured. The typical setup uses a `PostToolUse` hook on `FileWrite` or `FileEdit`:

```json
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "FileWrite",
        "hooks": [
          {
            "type": "command",
            "command": "bash -c 'FILE=$(jq -r .inputs.file_path); prettier --write \"$FILE\" 2>/dev/null || true'"
          }
        ]
      }
    ]
  }
}
```

Common formatters:
- **Prettier** (`prettier --write <file>`) — TypeScript, JavaScript, JSON, CSS, Markdown.
- **Ruff** (`ruff format <file>`) — Python.
- **rustfmt** (`rustfmt <file>`) — Rust.
- **gofmt** (`gofmt -w <file>`) — Go.
- **clang-format** (`clang-format -i <file>`) — C/C++.

The hook exit code does not affect the tool call result; formatters should suppress non-zero exits for unknown file types (`|| true`).

---

## Environment management

### --add-dir

```bash
claurst --add-dir /path/to/additional/project "..."
```

Grants Claurst read access to an additional directory outside the working directory. Useful when a task spans multiple repositories or when config files live outside the project root.

Multiple `--add-dir` flags can be combined.

### Environment variables in config

Environment variables can be set in `.claude/settings.json` under an `env` key. These are injected into tool executions:

```json
{
  "env": {
    "NODE_ENV": "development",
    "DATABASE_URL": "postgres://localhost/mydb"
  }
}
```

The `CwdChanged` hook can also write environment exports to `$CLAUDE_ENV_FILE` to propagate dynamic values into subsequent Bash commands within the same session.

---

## LSP integration

The `LspTool` provides code intelligence by communicating with a Language Server Protocol server for the current file.

### Operations

| Operation | Description |
|---|---|
| `hover` | Get type information and documentation for the symbol at a position |
| `definition` | Find where a symbol is defined |
| `references` | Find all references to a symbol |
| `symbols` | List all symbols (functions, classes, variables) in the file |
| `diagnostics` | Get errors and warnings reported by the language server |

### Input schema

```json
{
  "action": "hover",
  "file": "src/main.rs",
  "line": 42,
  "column": 15
}
```

- `action` — required, one of the operations above
- `file` — required, absolute or working-directory-relative path
- `line` — 1-based line number (required for `hover`, `definition`, `references`)
- `column` — 1-based column number (required for `hover`, `definition`, `references`)

The `symbols` and `diagnostics` actions only require `action` and `file`.

### Configuration

LSP servers must be configured in `settings.json`:

```json
{
  "lsp_servers": [
    {
      "language": "rust",
      "command": "rust-analyzer",
      "args": []
    },
    {
      "language": "typescript",
      "command": "typescript-language-server",
      "args": ["--stdio"]
    }
  ]
}
```

If no LSP server is configured for the file's language, the tool returns an informative error. Path resolution is relative to the current working directory.

---

## File: docs/agents.md

# Agents and Multi-Agent Features

Claurst has a named-agent system that lets you select a pre-configured persona with its own tool permissions, model, system prompt, and turn budget. For larger tasks it also supports a coordinator mode where a top-level agent orchestrates a pool of parallel worker agents.

---

## Built-in Named Agents

Three agents ship by default. Their definitions can be overridden per-user in `~/.claurst/settings.json`.

### build

Full tool access. Intended for implementing features and fixing bugs.

| Property | Value |
|---|---|
| Access | `full` — all tools available |
| Max turns | Unlimited (uses the global default) |
| Display color | Cyan |

Default system prompt prefix:

> You are the build agent. You have full access to read, write, and execute. Focus on implementing the requested changes completely and correctly.

### plan

Read-only analysis. Cannot write files or execute commands. Intended for understanding codebases and planning changes before committing to implementation.

| Property | Value |
|---|---|
| Access | `read-only` — file reads, no writes or shell execution |
| Max turns | 20 |
| Display color | Yellow |

Default system prompt prefix:

> You are the plan agent. You can read files and analyze code but cannot write files or execute commands. Focus on understanding the codebase and describing what changes should be made.

### explore

Fast search-only exploration. Intended for quickly locating relevant code and answering questions about structure.

| Property | Value |
|---|---|
| Access | `search-only` — search tools only |
| Max turns | 15 |
| Display color | Green |

Default system prompt prefix:

> You are the explore agent. You can search and read files. Focus on quickly finding relevant code and answering questions about the codebase.

---

## Selecting an Agent with --agent

Pass `--agent <name>` to activate a named agent for a session:

```
claurst --agent build "implement the OAuth2 login flow"
claurst --agent plan "analyze the database schema and suggest improvements"
claurst --agent explore "find all usages of the deprecated config API"
```

The `--agent` flag can be combined with `--provider` and `--model`:

```
claurst --agent plan --provider openai --model o3 "review this architecture"
```

---

## The /agents Command

Within an interactive session, `/agents` lists all available named agents (built-in and custom):

```
/agents
```

Output shows the agent name, description, access level, and max turn limit. Agents with `visible: false` in their definition are hidden from this list.

---

## Custom Agent Definitions

Define custom agents in `~/.claurst/settings.json` under the `agents` key. Custom definitions override built-in agents of the same name.

```json
{
  "agents": {
    "review": {
      "description": "Senior code reviewer focused on correctness and security",
      "model": "anthropic/claude-opus-4-6",
      "temperature": 0.3,
      "prompt": "You are a senior software engineer performing code review. Focus on correctness, security vulnerabilities, performance issues, and maintainability. Be specific about problems and suggest concrete fixes.",
      "access": "read-only",
      "visible": true,
      "max_turns": 30,
      "color": "magenta"
    },
    "test-writer": {
      "description": "Writes comprehensive unit and integration tests",
      "model": "anthropic/claude-sonnet-4-6",
      "prompt": "You are a test engineer. Write thorough tests covering happy paths, edge cases, and error conditions. Use the project's existing test framework and conventions.",
      "access": "full",
      "visible": true,
      "max_turns": null,
      "color": "blue"
    },
    "docs": {
      "description": "Technical documentation writer",
      "model": "anthropic/claude-sonnet-4-6",
      "temperature": 0.5,
      "prompt": "You are a technical writer. Write clear, accurate documentation for the code you are given. Use the project's existing documentation style.",
      "access": "read-only",
      "visible": true,
      "max_turns": 25,
      "color": "cyan"
    }
  }
}
```

### AgentDefinition Fields

| Field | Type | Description |
|---|---|---|
| `description` | string | Short description shown in `/agents` |
| `model` | string | Model override in `provider/model` or bare `model` form. Omit to use the session default. |
| `temperature` | number | Sampling temperature override (0.0–1.0). Omit to use the model default. |
| `prompt` | string | System prompt prefix prepended before the main system prompt. |
| `access` | string | Permission restriction: `"full"` (all tools), `"read-only"` (no writes/shell), `"search-only"` (search tools only). Default: `"full"`. |
| `visible` | bool | Whether to show in `/agents` output. Default: `true`. |
| `max_turns` | number or null | Maximum agentic turns. Null means unlimited. Overrides the global turn budget. |
| `color` | string | ANSI terminal color for display: `"cyan"`, `"magenta"`, `"green"`, `"yellow"`, `"blue"`, etc. |

Use the agent with the `--agent` flag:

```
claurst --agent review "check the authentication module for security issues"
claurst --agent test-writer "write tests for the payment processor"
```

---

## Coordinator Mode

Coordinator mode enables a single top-level agent to orchestrate multiple parallel worker agents. The coordinator delegates research, implementation, and verification tasks to workers, then synthesises their results.

### Enabling Coordinator Mode

Set the `CLAURST_COORDINATOR_MODE` environment variable to `1` before launching:

```bash
CLAURST_COORDINATOR_MODE=1 claurst "refactor the entire authentication subsystem"
```

Or within a shell session:

```bash
export CLAURST_COORDINATOR_MODE=1
claurst
```

The value `"0"` and `"false"` disable coordinator mode even if the variable is set. Any other non-empty value enables it.

### How the Coordinator Works

When coordinator mode is active, Claurst injects a coordinator system prompt that instructs the model to orchestrate rather than act directly. The recommended workflow is:

1. **Research Phase** — Spawn workers in parallel to gather information about the codebase or requirements.
2. **Synthesis Phase** — Collect worker findings and build a complete understanding before proceeding.
3. **Implementation Phase** — Delegate implementation tasks to workers, each responsible for a well-defined scope.
4. **Verification Phase** — Spawn verification workers to validate results, run tests, and confirm correctness.

Worker prompts must be fully self-contained: workers cannot see the coordinator's conversation history.

### Coordinator-Only Tools

The following tools are available to the coordinator but are not passed to worker agents:

| Tool | Purpose |
|---|---|
| `Agent` | Spawn a new worker agent with a given prompt |
| `SendMessage` | Continue communication with a running worker |
| `TaskStop` | Cancel a worker that is no longer needed |
| `TeamCreate` | Create a named team of workers |
| `TeamDelete` | Dismantle a team |
| `SyntheticOutput` | Inject synthetic output into the conversation |

### Worker Tool Set

Workers receive all standard tools (file operations, Bash, web search, MCP tools, skills) but do not receive the coordinator-only tools listed above. This prevents workers from spawning their own sub-coordinators or interfering with task management.

In simple mode (`CLAURST_SIMPLE=1`), workers are further restricted to `["Bash", "Read", "Edit"]`.

### Banned Tools in Coordinator Mode

The coordinator itself does not use `Bash` directly — shell execution is delegated to workers. This enforces the principle that the coordinator orchestrates rather than executes.

---

## Task Management Tools

These tools are available in coordinator mode for tracking parallel work:

| Tool | Description |
|---|---|
| `TaskCreate` | Create a new tracked task |
| `TaskGet` | Retrieve task details by ID |
| `TaskUpdate` | Update task status or metadata |
| `TaskList` | List all active tasks |
| `TaskStop` | Cancel a running task (coordinator only) |
| `TaskOutput` | Read output produced by a task |

### /tasks Command

Within an interactive session, `/tasks` shows the current task list with status, worker assignments, and results:

```
/tasks
```

---

## Parallel Agent Execution

The coordinator spawns workers via the `Agent` tool. Workers run asynchronously; the coordinator can spawn multiple workers simultaneously and wait for all of them before proceeding to synthesis.

**Example coordinator workflow (expressed as a prompt):**

```
I need to refactor the authentication module. Let me plan this in parallel:

1. Use Agent to spawn a worker that reads and summarises all files in src/auth/
2. Use Agent to spawn a worker that identifies all callers of the auth API across the codebase
3. Wait for both workers to finish
4. Synthesise findings
5. Use Agent to spawn implementation workers for each logical unit of work
6. Run verification workers on the result
```

**Example coordinator session prompt:**

```bash
CLAURST_COORDINATOR_MODE=1 claurst \
  "Audit the entire src/payments directory for security issues. \
   Use parallel workers to examine each file, then produce a \
   consolidated security report with severity rankings."
```

---

## Agent Definitions in settings.json: Complete Example

```
/* Detailed source-code truncated for AI context efficiency. */
```

---

## Session Continuity and Mode Matching

When resuming a saved session, Claurst detects whether the original session used coordinator mode and automatically sets `CLAURST_COORDINATOR_MODE` to match. A warning is printed when the environment is changed to prevent mode confusion in long-running workflows.

---

## Managed Agents (Preview)

Managed agents provide a formal **manager-executor** architecture that is distinct from coordinator mode. In coordinator mode, the orchestrator and workers all share the same configuration. With managed agents, you explicitly configure separate models, turn budgets, concurrency limits, and budget splits for the manager and for executors.

### When to use managed agents vs coordinator mode

| | Coordinator mode | Managed agents |
|---|---|---|
| **Setup** | `CLAURST_COORDINATOR_MODE=1` | `/managed-agents enable` |
| **Model selection** | All agents use the same model | Manager and executors can use different models |
| **Budget control** | Global session limits | Per-role USD caps or percentage splits |
| **Presets** | None | Several built-in presets available |
| **Use case** | Homogeneous parallel workers | Heterogeneous manager/worker separation |

### Enabling and configuring

```
/managed-agents presets                               — list presets
/managed-agents preset <name>                         — apply a preset
/managed-agents configure manager-model  anthropic/claude-opus-4-6
/managed-agents configure executor-model anthropic/claude-sonnet-4-6
/managed-agents configure concurrent     3
/managed-agents budget 5.00
/managed-agents enable
```

See [Managed Agents](./advanced.md#managed-agents) in the advanced guide for the full configuration reference.

---

## File: docs/auth.md

# Claurst Authentication Guide

Claurst needs credentials to call the Anthropic API (or another provider's
API). This document covers every supported authentication method, multi-account
profile switching, how tokens are stored, how to check and clear credentials,
and how to authenticate with non-Anthropic providers.

---

## Authentication Methods

Claurst checks for credentials in the following priority order:

1. `--api-key` flag (highest priority, session-only)
2. `api_key` field in `~/.claurst/settings.json`
3. `ANTHROPIC_API_KEY` environment variable
4. Tokens for the **active Anthropic profile** under
   `~/.claurst/accounts/anthropic//oauth_tokens.json`
5. Legacy `~/.claurst/oauth_tokens.json` (auto-migrated to a profile on first
   read)

The first non-empty credential found is used. Provider-specific credentials
(OpenAI, Google, etc.) follow the same pattern but use their own environment
variables and provider config entries.

Codex (OpenAI ChatGPT subscription) accounts follow a parallel system —
multiple profiles stored under `~/.claurst/accounts/codex//`, with the
active profile selected via the account registry.

---

## Method 1: API Key

The simplest and most reliable authentication method is a direct API key from
the Anthropic Console.

### Get an API key

1. Log in to [console.anthropic.com](https://console.anthropic.com).
2. Navigate to **Settings > API Keys**.
3. Click **Create Key** and copy the generated `sk-ant-...` key.

### Configure the key

**Option A: Environment variable (recommended)**

Set `ANTHROPIC_API_KEY` in your shell profile. This keeps the key out of any
configuration files that might be committed to version control.

```bash
# Add to ~/.bashrc or ~/.zshrc
export ANTHROPIC_API_KEY="sk-ant-api03-..."
```

On Windows (Command Prompt, permanent):

```cmd
setx ANTHROPIC_API_KEY "sk-ant-api03-..."
```

On Windows (PowerShell profile):

```powershell
$env:ANTHROPIC_API_KEY = "sk-ant-api03-..."
# To persist it:
[System.Environment]::SetEnvironmentVariable("ANTHROPIC_API_KEY","sk-ant-api03-...","User")
```

**Option B: Settings file**

Store the key in `~/.claurst/settings.json`. Ensure the file has restricted
permissions on shared systems.

```json
{
  "config": {
    "api_key": "sk-ant-api03-..."
  }
}
```

**Option C: CLI flag (session-only)**

Pass the key directly for a single run. It is not persisted anywhere.

```bash
claurst --api-key "sk-ant-api03-..." "your prompt"
```

---

## Method 2: OAuth Login (Browser-based)

Claurst supports an OAuth 2.0 PKCE flow that authenticates through either
the Anthropic Console or Claude.ai in your browser.

> **Important:** The OAuth client IDs in Claurst are registered to Anthropic's
> official Claude Code CLI application. Anthropic's authorization server may
> reject or misattribute OAuth requests originating from Claurst. The API key
> method is the recommended path for Claurst users.
>
> If OAuth login is attempted and fails, use Method 1 (API key) instead.

### Claude.ai flow (default)

```bash
claurst auth login
```

1. Claurst generates a PKCE code verifier and code challenge.
2. A temporary localhost HTTP server starts on a random port to receive the
   callback.
3. The authorization URL is printed to the terminal and Claurst attempts to
   open it in your default browser.
4. Complete the authorization in the browser (Claude.ai login page).
5. The browser redirects to `http://localhost:/callback` with an
   authorization code.
6. Claurst exchanges the code for tokens via the token endpoint.
7. Tokens are saved under `~/.claurst/accounts/anthropic//oauth_tokens.json`
   and the profile is registered as **active** in `~/.claurst/accounts.json`.

This flow produces a Bearer token (`user:inference` scope) used directly for
API calls.

### Console flow (creates an API key)

```bash
claurst auth login --console
```

This uses the Anthropic Console authorization endpoint. After token exchange,
Claurst calls the Console API to create a new API key, stores it in the
active profile's `oauth_tokens.json`, and uses it as a standard API key for
subsequent requests (not as a Bearer token).

### Naming the profile

Add `--label <name>` to give the new profile a human-friendly name (otherwise
the id is derived from the JWT email's local-part). This becomes the id you
use when running `claurst auth switch`:

```bash
claurst auth login --label work
claurst auth login --label personal
claurst auth switch personal
```

### Manual fallback

If the browser does not open automatically, Claurst prints the full
authorization URL. Copy and paste it into a browser. After you authorize,
paste the authorization code shown in the browser back into the terminal
when prompted.

---

## Multi-Account Profiles

Claurst stores **multiple named accounts per provider** and lets you switch
between them without re-logging-in. Supported providers today: **Anthropic**
(Claude.ai / Console) and **Codex** (OpenAI ChatGPT subscription).

This is useful for separating work and personal accounts, juggling
Pro/Max/Team plans, or testing against multiple organizations.

### On-disk layout

```
~/.claurst/
├── accounts.json                              # registry (active + metadata)
└── accounts/
    ├── anthropic/
    │   ├── work/oauth_tokens.json
    │   └── personal/oauth_tokens.json
    └── codex/
        └── work/codex_tokens.json
```

`accounts.json` schema (excerpt):

```json
{
  "version": 1,
  "providers": {
    "anthropic": {
      "active": "personal",
      "profiles": {
        "work":     { "id": "work",     "email": "kuber@company.example",  "subscription_tier": "max", "added_at": "2026-05-25T19:00:00Z" },
        "personal": { "id": "personal", "email": "kuber@personal.example", "subscription_tier": "pro", "added_at": "2026-05-25T19:05:00Z" }
      }
    },
    "codex": {
      "active": "work",
      "profiles": { "work": { "id": "work", "email": "kuber@company.example" } }
    }
  }
}
```

### CLI

`claurst auth` and `claurst codex` are symmetric — same subcommands for both
providers:

```bash
# Add accounts (each login becomes its own profile)
claurst auth login                       # Claude.ai (default)
claurst auth login --console             # Console / API-key flow
claurst auth login --label work          # name the profile
claurst codex login                      # ChatGPT/Codex OAuth
claurst codex login --label personal

# Inspect
claurst auth status                      # show active Anthropic profile
claurst auth list                        # all Anthropic profiles
claurst codex list                       # all Codex profiles
claurst accounts                         # both at once (use --json for JSON)

# Switch the active account
claurst auth switch work
claurst codex switch personal

# Remove a stored profile
claurst auth remove work                 # delete profile + tokens dir
claurst codex remove personal

# Logout (clears tokens for the active profile)
claurst auth logout
claurst codex logout
```

`claurst auth status` and `claurst codex status` exit `0` when logged in and
`1` otherwise, so they can drive scripts:

```bash
if claurst codex status > /dev/null; then
  echo "Codex login present"
fi
```

### Slash commands

Inside the interactive REPL the same operations are available as slash
commands — Anthropic is the default, pass `--codex` to target Codex:

```
/login                          # OAuth login (Claude.ai)
/login --console                # API-key flow
/login --codex                  # add a Codex account
/login --label work             # name the new profile
/logout                         # clear active Anthropic credentials
/logout --codex                 # clear active Codex credentials
/logout --all                   # purge every stored Anthropic profile
/accounts                       # list every stored account
/switch personal                # set active Anthropic to "personal"
/switch --codex work            # set active Codex to "work"
```

`/accounts` lists every profile with a `*` next to the active one and shows
email and subscription tier when known.

### Identity detection

When you log in, Claurst decodes the JWT id_token (or access token for Codex)
to extract your email and provider-side account_id. If a stored profile
already matches that identity, the existing profile is refreshed instead of
a duplicate being created — re-logging-in the same account is idempotent.

### Backward compatibility

If you previously used Claurst (with the older single-file storage), your
existing tokens are auto-migrated on first read:

- `~/.claurst/oauth_tokens.json` → `~/.claurst/accounts/anthropic/<derived>/oauth_tokens.json`
- `~/.claurst/codex_tokens.json` → `~/.claurst/accounts/codex/<derived>/codex_tokens.json`

The legacy files are removed after a successful migration. No manual action
needed.

---

## Method 3: Device Code Flow

The device code flow (RFC 8628) is designed for headless or server
environments where opening a browser is not practical. Currently this flow
is used internally for GitHub Copilot authentication.

For headless environments without a Copilot subscription, the API key method
(Method 1) is the recommended approach. Set `ANTHROPIC_API_KEY` in the
environment before running Claurst in a CI/CD or server context.

```bash
# Headless / CI example
ANTHROPIC_API_KEY="sk-ant-..." claurst --print "summarize the last 10 commits"
```

---

## Token Storage

### Anthropic OAuth tokens (per profile)

Each Anthropic account profile has its own file:

```
~/.claurst/accounts/anthropic//oauth_tokens.json
```

The file contains the access token, optional refresh token, expiry timestamp,
granted scopes, and account email. Example structure:

```json
{
  "access_token": "...",
  "refresh_token": "...",
  "expires_at_ms": 1700000000000,
  "scopes": ["user:inference", "user:profile"],
  "email": "you@example.com",
  "api_key": "sk-ant-..."
}
```

The active profile pointer lives in `~/.claurst/accounts.json` (see
[Multi-Account Profiles](#multi-account-profiles)). Files are written with
user-only permissions (`600` on Unix). Do not commit them to version control.

### Codex tokens (per profile)

```
~/.claurst/accounts/codex//codex_tokens.json
```

Contains the OpenAI access token, refresh token, account_id, and expiry.

### Provider credential store

API keys for non-Anthropic providers without dedicated OAuth flows are stored in:

```
~/.claurst/auth.json
```

This file is keyed by provider ID and contains either an `api` credential
(plain key) or an `oauth` credential (access + refresh token pair):

```json
{
  "credentials": {
    "openai": { "type": "api", "key": "sk-..." },
    "github-copilot": {
      "type": "oauth",
      "access": "...",
      "refresh": "...",
      "expires": 1700000000
    }
  }
}
```

> **Note:** `~/.claurst/auth.json` is the multi-provider credential cache for
> simple API-key providers. It is **distinct** from `~/.claurst/accounts.json`,
> which is the multi-account registry for Anthropic/Codex OAuth profiles.

---

## Checking Authentication Status

```bash
claurst auth status
```

Prints a human-readable summary:

```
Logged in.
  API provider: Anthropic
  Login method: API Key
  Billing mode: API
  Key source:   ANTHROPIC_API_KEY
```

For machine-readable output:

```bash
claurst auth status --json
```

Example JSON output:

```json
{
  "loggedIn": true,
  "authMethod": "api_key",
  "apiProvider": "Anthropic",
  "billing": "API",
  "apiKeySource": "ANTHROPIC_API_KEY"
}
```

The exit code is `0` when logged in, `1` when not logged in. This makes
`auth status` suitable for scripting:

```bash
if claurst auth status > /dev/null 2>&1; then
  echo "credentials present"
fi
```

---

## Logging Out

By default, `logout` removes the **active** account's tokens and drops that
profile from the registry; other stored profiles are untouched, so a stored
secondary profile becomes the candidate for next selection.

```bash
# Remove the active Anthropic profile
claurst auth logout

# Remove the active Codex profile
claurst codex logout

# Or from inside the REPL
/logout
/logout --codex
```

To purge every stored profile for a provider (and clear any API key in
`settings.json`):

```
/logout --all          # Anthropic
/logout --codex --all  # Codex
```

API keys set via environment variables are not affected by `logout`; remove
them from your shell profile manually.

To delete a specific stored profile without making it active first:

```bash
claurst auth remove work
claurst codex remove personal
```

---

## Token Refresh

When Claurst loads OAuth tokens for the active profile and the access token
is expired, it automatically attempts a silent refresh:

1. A `POST` request is sent to the provider's token endpoint with the stored
   refresh token.
2. If successful, the new access token (and optionally a new refresh token)
   is written back to the same per-profile token file.
3. The refreshed token is used for the current session.

If the refresh fails (network error, expired refresh token, revoked grant),
Claurst falls back to any configured API key. If no API key is available,
authentication fails and you must run `claurst auth login` (optionally with
`--label <name>` to reuse a profile id) again.

---

## Multiple Providers

Claurst supports simultaneous configuration of credentials for multiple
providers. Each provider looks for credentials in this order:

1. `api_key` in the provider's entry under `providers` in `settings.json`
2. The provider-specific environment variable (see table below)
3. The credential stored in `~/.claurst/auth.json`

### Provider environment variables

| Provider | Environment variable |
|----------|---------------------|
| `anthropic` | `ANTHROPIC_API_KEY` |
| `openai` | `OPENAI_API_KEY` |
| `google` | `GOOGLE_API_KEY` |
| `groq` | `GROQ_API_KEY` |
| `cerebras` | `CEREBRAS_API_KEY` |
| `deepseek` | `DEEPSEEK_API_KEY` |
| `mistral` | `MISTRAL_API_KEY` |
| `xai` | `XAI_API_KEY` |
| `openrouter` | `OPENROUTER_API_KEY` |
| `togetherai` | `TOGETHER_API_KEY` |
| `perplexity` | `PERPLEXITY_API_KEY` |
| `cohere` | `COHERE_API_KEY` |
| `deepinfra` | `DEEPINFRA_API_KEY` |
| `venice` | `VENICE_API_KEY` |
| `github-copilot` | `GITHUB_TOKEN` |
| `azure` | `AZURE_API_KEY` |
| `huggingface` | `HF_TOKEN` |
| `nvidia` | `NVIDIA_API_KEY` |

### Example: multiple providers in settings.json

```json
{
  "providers": {
    "anthropic": {
      "api_key": null,
      "enabled": true
    },
    "openai": {
      "api_key": "sk-...",
      "enabled": true
    },
    "ollama": {
      "api_base": "http://localhost:11434",
      "enabled": true
    },
    "openrouter": {
      "api_key": "sk-or-...",
      "enabled": true,
      "models_whitelist": ["anthropic/claude-sonnet-4", "openai/gpt-4o"]
    }
  }
}
```

Switch providers at runtime:

```bash
# Use OpenAI for this session
claurst --provider openai --model gpt-4o "your prompt"

# Use a local Ollama model (no API key needed)
claurst --provider ollama --model llama3.2 "your prompt"

# Or via environment variable
CLAURST_PROVIDER=google claurst "your prompt"
```

---

## Local Models (No API Key)

Providers that run locally require no API key:

**Ollama:**

```bash
# Install Ollama from https://ollama.ai and pull a model
ollama pull llama3.2

# Run Claurst against it
claurst --provider ollama --model llama3.2
```

**LM Studio:**

```bash
# Start the LM Studio local server (default port 1234)
claurst --provider lmstudio
```

**llama.cpp server:**

```bash
claurst --provider llamacpp --api-base http://localhost:8080
```

---

## Security Recommendations

- Store API keys in environment variables or a secrets manager rather than in
  `settings.json`, especially on shared or CI systems.
- Restrict permissions on `~/.claurst/` to your user only:
  ```bash
  chmod 700 ~/.claurst
  chmod 700 ~/.claurst/accounts
  chmod 600 ~/.claurst/accounts.json
  chmod 600 ~/.claurst/auth.json
  chmod 600 ~/.claurst/settings.json
  find ~/.claurst/accounts -type f -name '*tokens.json' -exec chmod 600 {} +
  ```
  Claurst already sets `0600` on `accounts.json` automatically on Unix; the
  command above is the belt-and-braces version that also covers the per-
  profile token files.
- Do not commit `~/.claurst/` to version control.
- Add `.claurst/` to your project's `.gitignore` to prevent accidentally
  committing project-level settings files that may contain keys.
- Rotate API keys periodically from the Anthropic Console.
- Use `claurst auth logout` on shared machines before logging out of your
  user session.

---

## File: docs/commands.md

# Claurst Slash Commands Reference

This document is the complete reference for every slash command available in Claurst, the Rust reimplementation of Claude Code CLI. Commands are invoked by typing `/command-name` at the REPL prompt.

---

## Table of Contents

1. [Command System Overview](#command-system-overview)
2. [Session & Navigation](#session--navigation)
3. [Model & Provider](#model--provider) — `/model`, `/providers`, `/connect`, `/thinking`, `/effort`, `/advisor`, `/fast`
4. [Configuration & Settings](#configuration--settings) — `/config`, `/keybindings`, `/permissions`, `/hooks`, `/privacy-settings`, `/mcp`, `/output-style`, `/theme`, `/statusline`, `/vim`, `/voice`, `/terminal-setup`
5. [Code & Git](#code--git) — `/commit`, `/diff`, `/undo`, `/review`, `/security-review`, `/init`, `/search`
6. [Search & Files](#search--files) — `/files`, `/context`
7. [Memory & Context](#memory--context) — `/memory`, `/usage`, `/cost`, `/stats`, `/status`, `/insights`
8. [Agents & Tasks](#agents--tasks) — `/agents`, `/tasks`, `/goal`, `/managed-agents`, `/agent`
9. [Planning & Review](#planning--review) — `/plan`, `/ultraplan`, `/ultrareview`
10. [MCP & Integrations](#mcp--integrations) — `/mcp`, `/skills`, `ultracode`, `/plugin`, `/chrome`
11. [Authentication](#authentication) — `/login`, `/logout`, `/accounts`, `/switch`, `/refresh`
12. [Display & Terminal](#display--terminal) — `/theme`, `/output-style`, `/statusline`, `/vim`, `/terminal-setup`, `/caveman`, `/rocky`, `/normal`, `/mobile`, `/color`, `/stickers`
13. [Diagnostics & Info](#diagnostics--info) — `/doctor`, `/version`, `/update`
14. [Export & Sharing](#export--sharing) — `/export`, `/copy`
15. [Advanced & Internal](#advanced--internal) — `/thinking`, `/connect`, `/fork`, `/effort`, `/summary`, `/brief`, `/sandbox-toggle`, `/think-back`, `/thinkback-play`
16. [Command Availability](#command-availability)

---

## Command System Overview

Commands are registered in a priority-ordered registry. When you type a command name, Claurst resolves it through this chain:

```
bundledSkills -> builtinPluginSkills -> skillDirCommands ->
workflowCommands -> pluginCommands -> pluginSkills -> COMMANDS()
```

### Command Types

| Type | Behavior |
|------|----------|
| `local` | Runs synchronously; returns text output directly |
| `local-jsx` | Renders an interactive TUI component (model picker, theme selector, etc.) |
| `prompt` | Expands to a prompt sent to the model via the main inference loop |

Commands support aliases — for example `/h`, `/?`, and `/help` all invoke the same handler.

### Usage Syntax

```
/command-name [arguments]
```

Arguments are passed as a single string after the command name. Most commands that accept arguments are documented with an `argumentHint` shown in the command palette.

---

## Session & Navigation

### /help
**Aliases:** `h`, `?`

Display all available commands with their descriptions. Respects `isHidden` flags — internal or rarely-needed commands are suppressed unless you are an Anthropic employee.

```
/help
/h
/?
```

---

### /clear
**Aliases:** `reset`, `c`

Clear the current conversation history. The session id and its on-disk file are retained — only the in-memory message list is wiped, so you stay in the same session. Use `/new` to start a genuinely fresh session instead.

```
/clear
```

---

### /new

Start a fresh session, mirroring opencode's `/new`. The transcript resets to a blank home and a brand-new session id begins, while your current model, provider, effort level and working directory carry over. The new session is *lazy* — it is not written to disk until your first message, so opening `/new` without typing anything leaves no trace.

Unlike `/clear` (which keeps the same session id and history file), `/new` opens a clean, separate session.

```
/new
```

---

### /move

Re-home the current session to another worktree or directory of the **same project**, mirroring opencode's `/move`. Any uncommitted changes in the current directory are carried over to the destination and reset in the original location; the model is informed of the new working directory on its next turn.

The destination must belong to the same git repository (typically a linked `git worktree`); moving to an unrelated project is refused. Pass `--no-changes` to re-home the session without relocating working-tree changes.

```
/move <directory>
/move ../myapp-feature
/move --no-changes /path/to/other/worktree
```

**Adaptation note:** opencode presents an interactive worktree picker and can create a new worktree on the fly. Claurst takes the destination directory as an argument and re-homes the live session's working directory (claurst has no separate session-per-worktree registry). Uncommitted changes are relocated with `git diff`/`git apply` and the source is reset with `git checkout` (index preserved) plus `git clean` (untracked removed), matching opencode's `move-session` change handling.

---

### /exit
**Aliases:** `quit`

Exit the Claurst REPL. Equivalent to pressing `Ctrl+D`. Unsaved session state is flushed before exit.

```
/exit
/quit
```

---

### /resume
**Aliases:** `continue`

Resume a previous session from the session store. Displays a list of recent sessions with timestamps and summaries. Select one to restore its message history and file state.

```
/resume
/resume <session-id>
```

---

### /session
**Aliases:** `remote`

Manage active and stored sessions. Subcommands allow listing, switching, deleting, and attaching to remote sessions.

```
/session
/session list
/session delete <session-id>
/session attach <session-id>
```

---

### /fork

Fork the current session into a new independent session that begins from the current conversation state. Useful for exploring two different approaches without losing either.

```
/fork
/fork <new-session-name>
```

---

### /rename

Rename the current session. The new name is used in session listings and exports.

```
/rename <new-name>
```

---

### /rewind
**Aliases:** `checkpoint`

Rewind the conversation to a previous message. Displays a numbered list of messages; enter a number to truncate history to that point and resume from there.

```
/rewind
/rewind <message-index>
```

---

### /compact

Summarize and compress the conversation history to reduce context window usage. The model is asked to produce a dense summary of the prior exchange; that summary replaces the raw messages.

```
/compact
```

---

## Model & Provider

### /model

Open the interactive model picker. Displays a searchable list of available models from all configured providers. The selected model is used for all subsequent inference in the current session.

```
/model
/model claude-opus-4-5
/model claude-sonnet-4-6
```

---

### /providers

List all configured AI providers and their connection status. Shows provider name, base URL, and whether credentials are present.

```
/providers
```

---

### /connect

Connect to a remote AI provider or configure a custom provider endpoint. Supports OpenAI-compatible APIs, Anthropic direct, and others.

```
/connect
/connect 
/connect openai https://api.openai.com/v1
```

---

### /thinking

Configure extended thinking for the current session. Extended thinking allows the model to reason through problems before responding, at the cost of additional tokens.

```
/thinking
/thinking on
/thinking off
```

See also `/effort` for a higher-level interface to thinking depth.

---

### /effort

Set the thinking effort level. This is a convenience wrapper over `/thinking` that maps human-readable levels to token budgets.

| Level | Description |
|-------|-------------|
| `low` | Minimal thinking; fastest responses |
| `medium` | Balanced thinking and speed |
| `high` | Deep reasoning; slower responses |
| `max` | Maximum token budget for thinking |

```
/effort low
/effort medium
/effort high
/effort max
```

---

### /advisor

Set or unset a secondary advisor model that provides supplementary suggestions alongside the main model. When set, the advisor model's context is available to improve main-model responses.

```
/advisor                          — show current advisor setting
/advisor claude-opus-4-6          — set advisor model by name
/advisor provider/model           — set advisor using provider/model format
/advisor off                      — disable the advisor
/advisor unset                    — disable the advisor
```

The advisor model persists to `~/.claurst/settings.json` under `advisorModel`. Model IDs must start with `claude-` or contain a `/` (provider/model format).

---

### /fast
**Aliases:** `speed`

Toggle fast mode. In fast mode, Claurst switches to the active provider's smaller, faster model for quick responses. Useful when you want rapid answers and deep reasoning is not required.

```
/fast          — toggle fast mode on/off
/fast on       — enable fast mode
/fast off      — disable fast mode
```

Setting persists to `~/.claurst/ui-settings.json`.

---

## Configuration & Settings

### /config
**Aliases:** `settings`

View or modify Claurst configuration values. Without arguments, renders an interactive settings panel. With arguments, acts as a key-value accessor.

```
/config
/config get <key>
/config set <key> <value>
/config reset <key>
```

Common keys:

| Key | Description |
|-----|-------------|
| `model` | Default model name |
| `theme` | Color theme name |
| `vim` | Vim mode enabled (`true`/`false`) |
| `outputStyle` | Output rendering style |
| `autoApprove` | Auto-approve tool calls |

---

### /keybindings

Open the interactive keybinding configurator. Displays all bound actions with their current shortcuts. Select an action to rebind it. Changes are written to `~/.claurst/keybindings.json`.

```
/keybindings
```

See [keybindings.md](./keybindings.md) for the full keybindings reference.

---

### /permissions
**Aliases:** `allowed-tools`

View and manage tool permission rules. Permissions control which tools can run without prompting, which are blocked, and which always require confirmation.

```
/permissions
/permissions list
/permissions allow <tool-name>
/permissions deny <tool-name>
/permissions reset
```

---

### /hooks

Manage event hooks. Hooks are shell commands or scripts that execute when lifecycle events fire (e.g., before/after tool calls, on session start/end).

```
/hooks
/hooks list
/hooks add <event> <command>
/hooks remove <hook-id>
```

Available events: `pre-tool`, `post-tool`, `session-start`, `session-end`, `message-send`, `message-receive`.

---

### /privacy-settings

Open Claurst privacy settings. Launches a browser to the Anthropic privacy portal where you can review data usage preferences, conversation retention, and account privacy options.

```
/privacy-settings
```

---

### /mcp

Configure and manage Model Context Protocol (MCP) servers. MCP servers expose additional tools and resources to the agent.

```
/mcp
/mcp list
/mcp add <name> <command>
/mcp remove <name>
/mcp restart <name>
```

---

### /output-style

Select how the model's output is rendered in the terminal. Choices include `auto`, `plain`, `markdown`, `streaming`, and others depending on terminal capabilities.

```
/output-style
/output-style plain
/output-style markdown
```

---

### /theme

Open the interactive theme picker. Preview and select a color theme for the Claurst TUI.

```
/theme
/theme dark
/theme light
/theme solarized
```

---

### /statusline

Configure the status line displayed at the bottom of the TUI. Toggle individual elements such as model name, token count, session name, and git branch.

```
/statusline
/statusline toggle model
/statusline toggle tokens
```

---

### /vim

Toggle vim keybinding mode on or off. In vim mode the input field behaves like a vim editor (normal/insert/visual modes). Persisted to config.

```
/vim
/vim on
/vim off
```

---

### /voice

Configure voice input/output. Requires a supported audio backend. Subcommands control microphone selection, TTS voice, and push-to-talk behavior.

```
/voice
/voice on
/voice off
/voice mic <device>
/voice tts <voice-name>
```

---

### /terminal-setup

Run the terminal capability detection and setup wizard. Checks for true-color support, font ligatures, Unicode rendering, and configures Claurst accordingly.

```
/terminal-setup
```

---

## Code & Git

### /commit

Stage and commit changes to the current git repository. The model drafts a commit message based on the diff. You can review and edit the message before confirming.

```
/commit
/commit "optional message override"
```

---

### /diff

Show file diffs for changes made during the current session. Displays a unified diff of all files Claurst has written or edited since the session started.

```
/diff
/diff <file-path>
```

---

### /undo

Undo file changes made during the current session. Restores files to their state before Claurst's last write operation. Can be called multiple times to step further back.

```
/undo
/undo <file-path>
```

---

### /review

Initiate a code review pass over recent changes. The model examines all modified files and produces inline comments and a summary of issues found.

```
/review
/review <file-path>
/review --since HEAD~3
```

---

### /security-review

Run a security-focused review pass. The model looks specifically for vulnerabilities, credential exposure, injection risks, and other security concerns in modified files.

```
/security-review
/security-review <file-path>
```

---

### /init

Initialize Claurst project configuration in the current directory. Creates a `CLAUDE.md` file that acts as persistent project-level context injected at the start of every session.

```
/init
```

---

### /search

Search the codebase using natural language or regex patterns. Wraps the GrepTool and GlobTool with a higher-level interface.

```
/search <query>
/search "TODO" --type ts
/search "function.*export" --regex
```

---

## Search & Files

### /files

List all files currently tracked (read or written) in the active session. Useful for reviewing what context the model has access to.

```
/files
/files --written
/files --read
```

---

### /context

Analyze context window usage. Shows a breakdown of tokens consumed by system prompt, conversation history, file contents, and tool results. Helps identify what to compact or drop.

```
/context
```

---

## Memory & Context

### /memory

Manage session memory. Memory entries are short notes persisted across sessions. The model can read these at session start to maintain continuity.

```
/memory
/memory list
/memory add <note>
/memory delete 
/memory clear
```

---

### /usage

Display a detailed token usage breakdown for the current session. Shows input tokens, output tokens, cache reads, cache writes, and estimated cost per API call.

```
/usage
```

---

### /cost

Show the total token usage and estimated cost for the current session. Provides a quick summary without the per-call breakdown of `/usage`.

```
/cost
```

---

### /stats

Display session statistics: number of messages, tool calls, files modified, tokens used, session duration, and model used.

```
/stats
```

---

### /status

Show the current session status. Includes active model, permission mode, thinking config, connected MCP servers, and loaded plugins.

```
/status
```

---

### /insights

Generate an analytical report of the current session. Prints a structured breakdown of conversation statistics including turn count, token usage (input/output/total), average tokens per exchange, estimated cost, total tool calls, and the most frequently invoked tool.

```
/insights
```

Sample output:
```
Session Insights
──────────────────────────────────────
Conversation
├─ User turns          : 12
├─ Assistant turns     : 12
└─ Completed exchanges : 12

Tokens
├─ Input               : 48320
├─ Output              : 9140
├─ Total               : 57460
└─ Avg per exchange    : 4788

Cost
└─ Estimated USD       : $0.1823

Tools
├─ Total calls         : 34
└─ Most used           : Bash (18 calls)
```

---

## Agents & Tasks

### /agents

Manage sub-agents. Sub-agents are parallel model instances that can be spawned to work on independent tasks simultaneously.

```
/agents
/agents list
/agents stop <agent-id>
/agents output <agent-id>
```

---

### /tasks
**Aliases:** `bashes`

Manage tracked background tasks. Tasks are shell commands or model invocations running asynchronously. Monitor progress, fetch output, or stop tasks from this interface.

```
/tasks
/tasks list
/tasks output <task-id>
/tasks stop <task-id>
```

---

### /goal

Set a durable multi-turn autonomous goal. When a goal is active, Claurst continues working across turns until the goal is marked complete, paused, or a 200-turn runaway guard fires. Designed for complex, sustained tasks that would otherwise require repeated manual re-prompting.

```
/goal <objective>                    — set a new goal and begin working autonomously
/goal --tokens 250K <objective>      — set a goal with a soft token budget cap
/goal                                — show current goal status
/goal status                         — show current goal status
/goal pause                          — pause the active goal
/goal resume                         — resume a paused goal
/goal clear                          — delete the current goal
/goal complete                       — request a completion audit
```

When the model believes the goal has been achieved, it calls the `GoalComplete` tool with an audit summary and evidence. Goals can be disabled globally by setting `CLAURST_GOALS=0` in your environment.

See [Goal System](./advanced.md#goal-system) in the advanced guide.

---

### /managed-agents

Configure the manager-executor agent architecture, where a manager model delegates subtasks to one or more executor agents working in parallel. Includes budget controls and isolation options.

```
/managed-agents                                       — show current configuration
/managed-agents status                                — show current configuration
/managed-agents presets                               — list built-in presets
/managed-agents preset <name>                         — apply a named preset
/managed-agents setup                                 — show setup instructions
/managed-agents enable                                — enable managed agents
/managed-agents disable                               — disable managed agents
/managed-agents reset                                 — remove all managed-agent configuration
/managed-agents configure manager-model <model>       — set the manager model
/managed-agents configure executor-model <model>      — set the executor model
/managed-agents configure executor-turns <n>          — set executor max turns
/managed-agents configure concurrent <n>              — set max concurrent executors
/managed-agents configure isolation on|off            — toggle executor isolation
/managed-agents configure budget-split shared         — shared token pool
/managed-agents configure budget-split percentage:<n> — percentage split (manager gets n%)
/managed-agents configure budget-split fixed:<m>:<e>  — fixed USD caps (manager / executor)
/managed-agents budget <amount>                       — set total budget in USD (0 to clear)
```

Model format: `provider/model` (e.g., `anthropic/claude-opus-4-6`, `openai/gpt-4o`). Configuration persists to `~/.claurst/settings.json` under `managed_agents`.

> **Preview feature.** Behaviour may change across releases.

See [Managed Agents](./advanced.md#managed-agents) in the advanced guide.

---

### /agent

List all available named agents, or show details for a specific agent. Named agents are predefined configurations with their own system prompts, model bindings, and access levels. Useful for discovering what agents are available before starting a session.

```
/agent             — list all visible named agents with access levels
/agent <name>      — show full details for a specific named agent
```

To activate an agent, start Claurst with `--agent <name>`. See [agents.md](./agents.md) for defining custom agents.

---

## Planning & Review

### /plan

Enter plan mode (read-only). In plan mode the model can read files and reason about changes but cannot write, edit, or execute anything. Use this to draft an approach before allowing writes.

```
/plan
```

To exit plan mode, use `/plan off` or the `/exit-plan` internal action.

---

### /ultraplan

Extended planning mode with deeper reasoning. Like `/plan` but with an elevated thinking budget to allow more thorough analysis before acting.

```
/ultraplan
```

---

### /ultrareview

Run an exhaustive multi-dimensional code review over the current working directory or a specified path. Goes significantly beyond `/review` and `/security-review`, covering:

- **Security** — OWASP Top 10, injection vulnerabilities, cryptographic weaknesses, path traversal, race conditions, dependency risks
- **Performance** — algorithmic complexity, allocations, N+1 queries, blocking I/O, memory leaks
- **Maintainability** — function length, nesting depth, DRY violations, naming, dead code
- **Error handling** — swallowed errors, panic paths, missing input validation
- **Test coverage** — missing tests, brittle tests, missing edge cases
- **API design, documentation, accessibility, and architecture**

Each finding is tagged by category and severity.

```
/ultrareview
/ultrareview 
/ultrareview 
```

---

## MCP & Integrations

### /mcp

Documented above under [Configuration & Settings](#configuration--settings).

---

### /skills

List and manage skills. Skills are bundled prompt-commands that extend Claurst's capabilities without writing code. They appear alongside built-in commands in the registry.

```
/skills
/skills list
/skills enable <skill-name>
/skills disable <skill-name>
/skills reload
```

---

### ultracode (top effort + keyword)

Run a disciplined **ultracode** workflow for serious coding tasks. Ultracode is claurst's take on Claude Code's `ultrathink`: a supervised procedure that classifies the task, picks a mode, and — when it genuinely helps — delegates bounded work across claurst's native agent primitives, then integrates and verifies in the parent session.

Ultracode is the **highest effort level** — it sits past `max` on the "Smarter" end of the effort ladder and runs the model's top reasoning **plus** the workflow procedure. (It is no longer a `/skill`.) There are two ways to trigger it:

- **In the effort selector.** Run `/effort` and pick **ultracode** — the rightmost level, past the `│` divider, drawn with an animated purple spectrum. Applies for subsequent turns until you change the effort.
- **As a keyword.** Type the single word `ultracode` anywhere in a normal prompt. The keyword renders with a purple gradient in the input, and for that turn the effort is set to ultracode (its operating procedure is injected as a system-prompt addendum). No keyword means no change to normal prompts.

```
please ultracode <task>    — activate ultracode for this one turn via the inline keyword
/effort  →  ultracode      — set ultracode as the current effort level
```

**What it does**

1. **Classify** the task by type, risk, blast radius, verification needs, and whether independent packets exist.
2. **Pick a mode** — *Direct* (small, tightly-coupled work), *Workflow* (multi-phase work executed as isolated passes), or *Delegated* (the default for non-trivial work with independent packets).
3. **Delegate** in delegated mode using native primitives: `Agent` for bounded subagents (with `isolation: "worktree"` / `run_in_background: true`), `TeamCreate` for parallel swarms, and `TaskCreate` for background tasks. It fans out **2–4** subagents (cap ~5) on non-overlapping packets while the parent keeps the blocking critical path.
4. **Integrate** every result in the parent, checking claimed edits against the files and rejecting evidence-free outputs.
5. **Verify** with checks scaled to risk (targeted tests → lint/typecheck → build → smoke → independent review), reporting any skipped checks honestly.

**Composes with `/goal`.** Ultracode governs *how* a turn plans, delegates, integrates, and verifies; `/goal <objective>` keeps the work going *across* turns. Combine them for long, autonomous objectives — the goal loop spans turns while ultracode structures each one.

---

### /plugin
**Aliases:** `plugins`, `marketplace`

Manage plugins. Plugins are loadable modules that can register new commands, tools, and hooks. Browse the marketplace or install from a local path.

```
/plugin
/plugin list
/plugin install <name>
/plugin install 
/plugin remove <name>
/plugin reload
```

---

### /chrome

Browser automation via Chrome DevTools Protocol (CDP). Connects to a running Chrome or Chromium instance and lets Claurst control it — navigate pages, click elements, fill forms, evaluate JavaScript, and take screenshots.

First, launch Chrome with remote debugging enabled:

```bash
chrome --remote-debugging-port=9222 --no-first-run
```

Then:

```
/chrome connect [--port 9222]      — connect to Chrome on the given port (default: 9222)
/chrome navigate              — navigate to a URL
/chrome screenshot                 — take a screenshot, saved to a temp file
/chrome click <selector>           — click a CSS selector
/chrome fill <selector> <text>     — fill an input field
/chrome eval <js>                  — evaluate JavaScript and return the result
/chrome disconnect                 — disconnect from Chrome
```

Useful for testing web applications, scraping, or automating browser-based workflows without a separate browser-automation tool.

---

## Authentication

Claurst supports **multiple named accounts per provider** — Anthropic (Claude.ai or Console) and Codex (OpenAI ChatGPT subscription). Each login creates a profile under `~/.claurst/accounts///` and the registry at `~/.claurst/accounts.json` tracks which one is active.

See [Authentication Guide](./auth.md#multi-account-profiles) for the full story and on-disk layout.

### /login

Authenticate with Anthropic or Codex via OAuth PKCE. Opens a browser for the flow and saves tokens under the active profile (or creates a new profile if none exists).

```
/login                            — Claude.ai OAuth (Bearer token, default)
/login --console                  — Console OAuth (creates an API key)
/login --codex                    — Codex / ChatGPT OAuth
/login --label work               — name the new profile "work"
/login --codex --label personal   — Codex login, name the profile "personal"
```

If a profile matching the JWT's email or account_id already exists, that profile is refreshed in place — re-logging-in is idempotent. Use `--label` to either name a fresh profile or to disambiguate.

---

### /logout

Remove credentials. By default removes only the **active** profile for the provider; other stored profiles remain switchable.

```
/logout                — clear active Anthropic profile (drops it from registry)
/logout --codex        — clear active Codex profile
/logout --all          — purge every Anthropic profile + clear any API key in settings
/logout --codex --all  — purge every Codex profile
```

---

### /accounts

List every stored account across providers. The active profile in each provider is marked with `*`.

```
/accounts
```

Sample output:

```
Anthropic:
  * personal [pro]    kuber@personal.example
    work     [max]    kuber@company.example
Codex:
    work              kuber@company.example
```

---

### /switch

Switch the active account for a provider. Anthropic by default; pass `--codex` for Codex. Run `/accounts` first to see available profile ids.

```
/switch work                     — set active Anthropic profile to "work"
/switch --codex personal         — set active Codex profile to "personal"
```

---

### /refresh

Refresh the provider authentication state. Forces a token refresh without full re-authentication. Useful when a session token has expired mid-session.

```
/refresh
```

---

## Display & Terminal

### /theme

Documented above under [Configuration & Settings](#configuration--settings).

---

### /output-style

Documented above under [Configuration & Settings](#configuration--settings).

---

### /statusline

Documented above under [Configuration & Settings](#configuration--settings).

---

### /vim

Documented above under [Configuration & Settings](#configuration--settings).

---

### /terminal-setup

Documented above under [Code & Git](#code--git).

---

### /caveman

Activate caveman speech mode. In caveman mode the model strips pleasantries, hedging, articles, and transitional phrases from its responses, producing dense, telegraphic output. Useful for reducing verbosity and saving tokens on long sessions.

```
/caveman             — activate full caveman mode (~75% token reduction)
/caveman lite        — remove pleasantries only (~40% reduction)
/caveman full        — compress sentences and drop articles (default, ~75% reduction)
/caveman ultra       — maximum compression, imperative phrases only (~85% reduction)
```

Deactivate with `/normal`.

---

### /rocky

Activate Rocky speech mode. Rocky is the Eridian alien engineer from *Project Hail Mary* who communicates in a distinctive pidgin English with specific grammar rules and expressive emphasis. In rocky mode the model adopts Rocky's communication style.

```
/rocky             — activate full Rocky mode (~75% token reduction)
/rocky lite        — grammar rules only, minimal emphasis (~40% reduction)
/rocky full        — full Rocky grammar + regular emphasis (default, ~75% reduction)
/rocky ultra       — maximum Rocky personality, frequent emphasis, alien observations
```

Deactivate with `/normal`.

---

### /normal

Deactivate any active speech mode (caveman or rocky) and return the model to its standard response style.

```
/normal
```

---

### /mobile

Display a QR code and download links for the Claude mobile app. Supports a `session` subcommand that generates a QR code linking directly to an active remote Claurst session.

```
/mobile             — show QR code for claude.ai/mobile (works for both platforms)
/mobile ios         — show QR code for the iOS App Store
/mobile android     — show QR code for Google Play
/mobile session     — show QR code linking to the active remote session (requires --remote)
```

---

### /color

Set the prompt bar color for the current session. Accepts standard color names or hex values. The color resets when the session ends unless saved via `/config`.

```
/color               — open the interactive color picker
/color <name>        — set to a named color (e.g., blue, red, green)
/color #ff6b6b       — set to a hex color value
/color default       — reset to the theme default
```

---

### /stickers

Opens the Claurst sticker page (`stickermule.com/claudecode`) in your default browser. Falls back to printing the URL if no browser can be launched.

```
/stickers
```

---

## Diagnostics & Info

### /doctor

Run the Claurst diagnostics suite. Checks configuration integrity, provider connectivity, tool availability, MCP server health, and reports any issues.

```
/doctor
```

---

### /version
**Aliases:** `v`

Display the current Claurst version string and build metadata.

```
/version
/v
```

---

### /update
**Aliases:** `upgrade`

Check for available updates. Queries the GitHub releases API and displays the latest version. If a newer version exists, prints the download URL or upgrade instructions. Does not auto-update.

```
/update
/upgrade
```

---

## Export & Sharing

### /export

Export the current session transcript. Supported formats include Markdown, JSON, and plain text. The output is written to a file or printed to stdout.

```
/export
/export --format markdown
/export --format json --output session.json
/export --stdout
```

---

### /copy

Copy the most recent assistant response to the system clipboard. Pass a number to copy the Nth most-recent response. On Linux a `wl-clipboard` or `xclip` backend is used; on macOS and Windows the native clipboard API is used.

```
/copy         — copy the most recent response
/copy 2       — copy the second most recent response
/copy N       — copy the Nth most recent response
```

---

## Advanced & Internal

### /thinking

Documented above under [Model & Provider](#model--provider).

---

### /connect

Documented above under [Model & Provider](#model--provider).

---

### /fork

Documented above under [Session & Navigation](#session--navigation).

---

### /effort

Documented above under [Model & Provider](#model--provider).

---

### /summary

Generate a summary of the current session. The model produces a condensed description of what was accomplished. Primarily used internally for session metadata.

```
/summary
```

---

### /brief

Output a brief status message for use in non-interactive contexts. Renders minimal session info without the full TUI.

```
/brief
```

---

### /context

Documented above under [Search & Files](#search--files).

---

### /sandbox-toggle
**Aliases:** `sandbox`

Enable or disable sandboxed execution of shell commands. When sandbox mode is on, bash/shell commands run in an isolated environment to limit unintended side effects. Supported on macOS, Linux, and WSL2.

```
/sandbox-toggle                          — toggle sandbox mode on/off
/sandbox-toggle on                       — enable sandbox mode
/sandbox-toggle off                      — disable sandbox mode
/sandbox-toggle status                   — show current state and excluded patterns
/sandbox-toggle exclude         — add a command pattern to the exclusion list
```

> A restart is recommended after toggling for full effect. On Windows (non-WSL), sandbox mode is not supported.

---

### /think-back
**Aliases:** `thinkback`

Display the extended-thinking traces from previous model responses in the current session. Only available when extended thinking was used for those responses. Pass a number to view the Nth most-recent trace.

```
/think-back         — show the most recent thinking trace
/think-back 2       — show the second most recent thinking trace
/thinkback          — alias
```

Thinking traces appear when the model uses extended thinking mode (see `/thinking`). If no traces are found, Claurst suggests enabling extended thinking.

---

### /thinkback-play

Replay a previous extended-thinking trace as a formatted, step-numbered walkthrough. Useful for reviewing the model’s reasoning path in detail.

```
/thinkback-play         — replay the most recent thinking trace
/thinkback-play 2       — replay the second most recent thinking trace
```

---

## Command Availability

Not all commands are available in all contexts.

### Remote Mode

When running with `--remote`, only a restricted set of commands is available:

`session`, `exit`, `clear`, `help`, `theme`, `vim`, `cost`, `usage`, `plan`, `keybindings`, `statusline`

### Bridge Mode

Over the Remote Control bridge (used by IDE integrations), only `local`-type commands are forwarded:

`compact`, `clear`, `cost`, `files`

### Internal-Only Commands

The following commands are only available when the `USER_TYPE` environment variable is set to `ant` (Anthropic internal builds):

`commit-push-pr`, `ctx_viz`, `good-claude`, `issue`, `init-verifiers`, `mock-limits`, `bridge-kick`, `ultraplan`, `summary`, `teleport`, `ant-trace`, `perf-issue`, `env`, `oauth-refresh`, `debug-tool-call`, `autofix-pr`, `bughunter`, `backfill-sessions`, `break-cache`

### Availability-Restricted Commands

Some commands are available only under certain account or platform conditions:

| Command | Restriction |
|---------|-------------|
| `/fast` | Available when a fast-mode model is configured for the active provider |
| `/privacy-settings` | Opens Anthropic privacy portal (useful for claude.ai accounts) |
| `/sandbox-toggle` | Functional on macOS, Linux, WSL2 only; no-op on native Windows |

### Feature-Flagged Commands

Some commands check `isEnabled()` at runtime. For example, voice-related commands check for audio device availability; the desktop command checks for a display server.

---

## File: docs/configuration.md

# Claurst Configuration Reference

Claurst is configured through a layered system of JSON files, environment
variables, and command-line flags. This document describes every option.

---

## Configuration File Location

The global settings file lives at:

```
~/.claurst/settings.json
```

The directory `~/.claurst/` is created automatically on first run if it does
not exist. The file is standard JSON (or JSONC — comments are stripped before
parsing).

### Per-project settings

Claurst walks up from the current working directory looking for a project-level
settings file. The first file found wins (project settings take precedence over
global settings):

```
/.claurst/settings.json
/.claurst/settings.jsonc
```

Settings that appear in the project file override the corresponding global
values. Keys absent from the project file fall back to the global value.

---

## Top-level Settings Structure

```json
{
  "version": 1,
  "provider": "anthropic",
  "config": { ... },
  "providers": { ... },
  "modelOverrides": { ... },
  "projects": { ... },
  "commands": { ... },
  "formatter": { ... },
  "agents": { ... },
  "skills": { ... },
  "permissionRules": [],
  "enabledPlugins": [],
  "disabledPlugins": [],
  "hasCompletedOnboarding": false
}
```

Most day-to-day options live inside the `config` object. Provider credentials
live in the `providers` map. Corrected model metadata for self-hosted or
unknown models lives in the `modelOverrides` map — see
[Model metadata overrides](providers.md#overriding-model-metadata).

---

## The `config` Object

The `config` object holds runtime behaviour options.

### Model and token settings

| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `api_key` | string \| null | null | Anthropic API key. Overrides `ANTHROPIC_API_KEY` env var. Prefer the env var in shared environments. |
| `model` | string \| null | provider default | Model ID to use. When absent, the provider's default is used (e.g. `claude-sonnet-4-6` for Anthropic, `gpt-4o` for OpenAI). |
| `max_tokens` | integer \| null | 8192 | Maximum tokens per model response. |
| `provider` | string \| null | `"anthropic"` | Active provider. See the [Providers](#providers) section. |

### Permission mode

| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `permission_mode` | string | `"default"` | Controls how tool permissions are enforced. One of `"default"`, `"acceptEdits"`, `"bypassPermissions"`, `"plan"`. |

See [Permission Modes](#permission-modes) for a full description of each value.

### Interface and output

| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `theme` | string | `"default"` | Color theme for the TUI. One of `"default"`, `"dark"`, `"light"`, `"deuteranopia"`. |
| `output_style` | string \| null | null | Named output style. Built-in values: `"default"`, `"concise"`, `"verbose"`. Custom styles can be added as Markdown files under `~/.claurst/output-styles/`. |
| `output_format` | string | `"text"` | Output format for headless (`--print`) mode. One of `"text"`, `"json"`, `"stream-json"`. |
| `verbose` | boolean | false | Enable debug-level log output. |

### Context compaction

| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `auto_compact` | boolean | true | Automatically compact the conversation context when the context window nears capacity. |
| `compact_threshold` | float | 0.85 | Fraction of the context window that triggers auto-compaction (0.0–1.0). |

### System prompt

| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `custom_system_prompt` | string \| null | null | Replace the default Claurst system prompt entirely with this text. |
| `append_system_prompt` | string \| null | null | Append this text to the end of the assembled system prompt (after AGENTS.md content). |

### Tool access

| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `allowed_tools` | array of strings | [] (all) | Restrict the tool set to this explicit list. An empty array means all tools are available. |
| `disallowed_tools` | array of strings | [] | Always deny these tools, regardless of other settings. |

Tool names match the internal names: `Bash`, `Read`, `Write`, `Edit`, `Glob`,
`Grep`, `WebSearch`, `WebFetch`, `TodoWrite`, `TodoRead`, and MCP tool names
prefixed with their server name (`myserver_toolname`).

### Directory access

| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `additional_dirs` | array of strings | [] | Additional filesystem paths Claurst is allowed to read and write. Equivalent to passing `--add-dir` on the command line. |

### MCP servers

| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `mcp_servers` | array of `McpServerConfig` | [] | Model Context Protocol servers to connect at startup. |

Each `McpServerConfig` object:

```json
{
  "name": "my-server",
  "command": "/path/to/server",
  "args": ["--flag"],
  "env": { "MY_VAR": "value" },
  "type": "stdio"
}
```

`type` can be `"stdio"` (default) or `"http"` (for HTTP-SSE servers, in which
case `command` is the base URL).

### Environment variables injected into tools

| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `env` | object (string → string) | {} | Environment variables injected into every tool execution. Useful for setting project-specific tokens without polluting the system environment. Values may reference existing env vars using `{env:VARNAME}` syntax. |

### Hooks

Hooks let you run shell commands in response to lifecycle events. They are
defined as a map from event name to an array of hook entries.

```json
"hooks": {
  "PreToolUse": [
    { "command": "echo tool=$TOOL_NAME", "blocking": false }
  ],
  "PostToolUse": [
    { "command": "/path/to/my-logger.sh", "tool_filter": "Bash", "blocking": false }
  ],
  "Stop": [
    { "command": "notify-send 'Claurst done'", "blocking": false }
  ]
}
```

Available events:

| Event | When it fires |
|-------|--------------|
| `PreToolUse` | Before a tool executes. Receives event JSON on stdin. |
| `PostToolUse` | After a tool returns its result. |
| `Stop` | When the model finishes its turn (stop reason). |
| `PostModelTurn` | After the model samples a response, before tool execution. |
| `UserPromptSubmit` | When the user submits a prompt. |
| `Notification` | General-purpose notification event. |

Hook entry fields:

| Field | Type | Description |
|-------|------|-------------|
| `command` | string | Shell command to execute. |
| `tool_filter` | string \| null | Only run for this tool name (`PreToolUse`/`PostToolUse` only). |
| `blocking` | boolean | If true, a non-zero exit code blocks the operation. Default: false. |

---

## Permission Modes

The `permission_mode` field (and `--permission-mode` CLI flag) controls how
tool calls are approved.

### `default`

Read-only operations (file reads, searches, glob) are permitted automatically.
Write and execute operations (file writes, shell commands) prompt the user for
confirmation in the TUI, or are denied in headless mode.

### `acceptEdits`

All tool calls — reads, writes, and shell commands — are automatically
accepted without prompting. This is useful for trusted automation pipelines
where you want maximum throughput.

### `bypassPermissions`

All permission checks are skipped entirely. Every tool call is allowed
unconditionally. This mode cannot be used when running as root or via `sudo`
on Unix systems (Claurst blocks it).

Use with caution: the model can read and modify any file reachable from the
current working directory without any user confirmation.

### `plan`

Read-only mode. File reads and searches are allowed; file writes and command
execution are blocked. This matches the built-in `plan` agent's behaviour and
is useful for code analysis sessions where you want to prevent accidental
modifications.

The permission mode can also be overridden per-session on the command line:

```bash
claurst --permission-mode acceptEdits "refactor the auth module"
claurst --dangerously-skip-permissions "..."  # equivalent to bypassPermissions
```

---

## AGENTS.md Memory Files

AGENTS.md files are plain Markdown documents that Claurst injects into the
system prompt at startup. They let you give the model persistent context about
your project, coding standards, or personal preferences without repeating
yourself in every session.

### File locations and priority

Claurst loads AGENTS.md files from four locations. They are processed in the
following order (earlier = higher priority, later content is appended below):

| Scope | Path | Description |
|-------|------|-------------|
| Managed | `~/.claurst/rules/*.md` | Global policy files. All `.md` files in this directory are loaded in alphabetical order. |
| User | `~/.claurst/AGENTS.md` | Your personal preferences and instructions, applied to all projects. |
| Project | `/AGENTS.md` | Project-level context: architecture notes, conventions, workflows. Typically committed to version control. |
| Local | `/.claurst/AGENTS.md` | Local overrides not committed to version control (add `.claurst/` to `.gitignore`). |

Files from all four locations are concatenated (separated by blank lines) into
a single system-prompt fragment. If the same instruction appears at multiple
levels, the narrower scope (Project/Local) effectively wins because it appears
later in the prompt.

### CLAUDE.md compatibility

Files named `CLAUDE.md` in the same locations are treated identically to
`AGENTS.md`. Both names are supported for compatibility with the TypeScript
Claude Code CLI.

### YAML frontmatter

AGENTS.md files may begin with optional YAML frontmatter to control loading:

```markdown
---
memory_type: project
priority: 10
scope: project
---

# My Project Notes

Always use 4-space indentation. Prefer `anyhow` for error handling.
```

Frontmatter fields:

| Field | Description |
|-------|-------------|
| `memory_type` | Informal label (currently informational only). |
| `priority` | Integer sort priority (lower numbers are prepended first within the same scope). |
| `scope` | Informational label for documentation purposes. |

### @include directives

AGENTS.md files support `@include` to pull in content from other files:

```markdown
# Project Guide

@include ./docs/architecture.md
@include ~/shared-notes/coding-standards.md
```

Paths may be relative to the including file, absolute, or tilde-expanded.
Circular includes are detected and skipped. Files larger than 40 KB are
skipped with a warning comment.

### Disabling AGENTS.md loading

To skip all AGENTS.md files for a session:

```bash
claurst --no-claude-md "your prompt"
```

Or in a session, use the `--bare` flag to disable AGENTS.md, hooks, and
plugins simultaneously.

---

## Providers

Claurst can send requests to multiple LLM providers. Set the active provider
via the `provider` key in settings or the `--provider` CLI flag.

### Provider IDs

| Provider ID | Default model |
|-------------|--------------|
| `anthropic` | `claude-sonnet-4-6` (or latest) |
| `openai` | `gpt-4o` |
| `google` | `gemini-2.5-flash` |
| `groq` | `llama-3.3-70b-versatile` |
| `cerebras` | `llama-3.3-70b` |
| `deepseek` | `deepseek-chat` |
| `mistral` | `mistral-large-latest` |
| `xai` | `grok-2` |
| `openrouter` | `anthropic/claude-sonnet-4` |
| `togetherai` | `meta-llama/Llama-3.3-70B-Instruct-Turbo` |
| `perplexity` | `sonar-pro` |
| `cohere` | `command-r-plus` |
| `deepinfra` | `meta-llama/Llama-3.3-70B-Instruct` |
| `github-copilot` | `gpt-4o` |
| `ollama` | `llama3.2` |
| `lmstudio` | `default` |
| `llamacpp` | `default` |
| `azure` | `gpt-4o` |
| `amazon-bedrock` | `anthropic.claude-sonnet-4-6-v1` |
| `venice` | `llama-3.3-70b` |

### Per-provider configuration

Each provider can have its own entry in the `providers` map (top-level in
`settings.json`) or in `config.provider_configs`. Provider-level `api_key`
and `api_base` override the corresponding environment variables.

```json
"providers": {
  "anthropic": {
    "api_key": "sk-ant-...",
    "api_base": "https://api.anthropic.com",
    "enabled": true,
    "models_whitelist": [],
    "models_blacklist": []
  },
  "openai": {
    "api_key": "sk-...",
    "enabled": true
  },
  "ollama": {
    "api_base": "http://localhost:11434",
    "enabled": true
  }
}
```

`ProviderConfig` fields:

| Field | Type | Description |
|-------|------|-------------|
| `api_key` | string \| null | API key for this provider. |
| `api_base` | string \| null | Override the default API base URL. |
| `enabled` | boolean | Whether this provider is active. Default: true. |
| `models_whitelist` | array | If non-empty, only these model IDs are offered. |
| `models_blacklist` | array | These model IDs are never offered. |
| `options` | object | Provider-specific passthrough options. |

---

## Environment Variables

| Variable | Description |
|----------|-------------|
| `ANTHROPIC_API_KEY` | Anthropic API key. Checked after the `config.api_key` setting. |
| `ANTHROPIC_BASE_URL` | Override the Anthropic API base URL. |
| `CLAURST_PROVIDER` | Active provider. Equivalent to `--provider`. |
| `CLAURST_API_BASE` | Override the API base URL for the active provider. Equivalent to `--api_base`. |
| `CLAURST_GOALS` | Set to `0` to disable the goal system (`/goal` command and `GoalCompleteTool`). |
| `OPENAI_API_KEY` | API key for the `openai` provider. |
| `GOOGLE_API_KEY` | API key for the `google` provider. |
| `GROQ_API_KEY` | API key for the `groq` provider. |
| `XAI_API_KEY` | API key for the `xai` provider. |
| `MISTRAL_API_KEY` | API key for the `mistral` provider. |
| `OPENROUTER_API_KEY` | API key for the `openrouter` provider. |
| `DEEPSEEK_API_KEY` | API key for the `deepseek` provider. |
| `COHERE_API_KEY` | API key for the `cohere` provider. |
| `DEEPINFRA_API_KEY` | API key for the `deepinfra` provider. |
| `VENICE_API_KEY` | API key for the `venice` provider. |
| `GITHUB_TOKEN` | Token for the `github-copilot` provider. |
| `AZURE_API_KEY` | API key for the `azure` provider. |
| `HF_TOKEN` | Token for the `huggingface` provider. |
| `NVIDIA_API_KEY` | API key for the `nvidia` provider. |
| `CLAURST_BRIDGE_URL` | Enable the remote-control bridge by setting the server URL. |
| `CLAURST_BRIDGE_TOKEN` | Bearer token for the remote-control bridge. |
| `RUST_LOG` | Tracing filter (e.g. `debug`, `claurst_core=trace`). |

---

## Custom Slash Commands

User-defined slash commands can be added to the `commands` map:

```json
"commands": {
  "review": {
    "template": "Please review the following code for bugs and style: $ARGUMENTS",
    "description": "Review code",
    "agent": "plan",
    "model": null
  }
}
```

`CommandTemplate` fields:

| Field | Description |
|-------|-------------|
| `template` | Template string. `$ARGUMENTS` is replaced with whatever the user types after the command name. |
| `description` | Short description shown in `/help`. |
| `agent` | Optional named agent to use (e.g. `"plan"`, `"build"`, `"explore"`). |
| `model` | Optional model override for this command. |

Use the command with `/review path/to/file.rs`.

---

## Named Agents

Agents are named configurations that combine a system prompt prefix, model,
permission level, and turn limit. Three are built in:

| Agent | Access | Description |
|-------|--------|-------------|
| `build` | full | Read, write, and execute. For feature implementation. |
| `plan` | read-only | Read files; no writes or commands. For analysis and planning. |
| `explore` | search-only | Search and read. For rapid codebase exploration. |

You can define custom agents in `settings.json`:

```json
"agents": {
  "review": {
    "description": "Code review agent",
    "model": "anthropic/claude-haiku-4-5",
    "temperature": 0.3,
    "prompt": "You are a senior engineer doing code review. Be thorough and direct.",
    "access": "read-only",
    "visible": true,
    "max_turns": 30,
    "color": "magenta"
  }
}
```

`AgentDefinition` fields:

| Field | Type | Description |
|-------|------|-------------|
| `description` | string \| null | Description shown in `@agent` autocomplete. |
| `model` | string \| null | Model override for this agent. |
| `temperature` | float \| null | Sampling temperature override. |
| `prompt` | string \| null | System prompt prefix (prepended before the main system prompt). |
| `access` | string | Permission level: `"full"`, `"read-only"`, or `"search-only"`. |
| `visible` | boolean | Whether to show in autocomplete. Default: true. |
| `max_turns` | integer \| null | Maximum agentic turns. |
| `color` | string \| null | ANSI display color: `"cyan"`, `"magenta"`, `"green"`, `"yellow"`, etc. |

Invoke an agent with `@agentname` in the TUI or `--agent agentname` on the CLI.

---

## Managed Agents Configuration

The `managed_agents` key stores the managed-agents architecture configuration set via `/managed-agents configure`. It is written automatically by the command and rarely needs to be edited manually.

```json
"managed_agents": {
  "enabled": true,
  "manager_model": "anthropic/claude-opus-4-6",
  "executor_model": "anthropic/claude-sonnet-4-6",
  "executor_max_turns": 20,
  "max_concurrent": 3,
  "executor_isolation": true,
  "budget_split": {
    "type": "Percentage",
    "manager_pct": 20
  },
  "total_budget_usd": 5.00
}
```

`budget_split` types:

| Type | JSON | Description |
|------|------|-------------|
| `SharedPool` | `{ "type": "SharedPool" }` | All agents draw from a single pool |
| `Percentage` | `{ "type": "Percentage", "manager_pct": 20 }` | Manager gets N% of total budget |
| `FixedCaps` | `{ "type": "FixedCaps", "manager_usd": 0.50, "executor_usd": 2.00 }` | Hard USD caps per role |

Configure via `/managed-agents configure` or `/managed-agents preset <name>`. Set `enabled: false` to disable without removing the configuration.

---

## File Formatters

Formatters run automatically after Claurst writes a file whose extension
matches. They are defined in the `formatter` map:

```json
"formatter": {
  "prettier": {
    "command": ["prettier", "--write"],
    "extensions": [".ts", ".tsx", ".js", ".json"],
    "disabled": false
  },
  "rustfmt": {
    "command": ["rustfmt"],
    "extensions": [".rs"],
    "disabled": false
  }
}
```

| Field | Description |
|-------|-------------|
| `command` | Command array. The filename is appended as the final argument. |
| `extensions` | File extensions this formatter handles (include the leading dot). |
| `disabled` | Set to true to temporarily disable without removing the entry. |

---

## Annotated Example `settings.json`

```
/* Detailed source-code truncated for AI context efficiency. */
```

---

## File: docs/hooks.md

# Hooks

Hooks let you run arbitrary shell commands (or HTTP requests, LLM prompts, or agentic verifiers) in response to events that happen inside a Claurst session. They are the primary mechanism for extending and automating Claurst's behavior without modifying the agent itself.

---

## What hooks are

A hook is a piece of executable logic that Claurst calls at a specific lifecycle event. The simplest kind is a shell command. When the event fires, Claurst:

1. Serialises a JSON payload describing the event.
2. Passes that JSON to the hook's stdin.
3. Waits for the hook to exit (unless the hook is marked async).
4. Interprets the exit code according to that event's blocking rules.

Because every hook receives structured JSON and returns a plain exit code, hooks can be written in any language that can read stdin and write to stderr/stdout.

---

## Hook types

Claurst supports four hook implementations:

### `command` — shell command

```json
{
  "type": "command",
  "command": "bash /path/to/my-hook.sh"
}
```

Runs the given string through the configured shell (`bash` by default, or `powershell`).

| Field | Description |
|---|---|
| `command` | Shell command string to execute. |
| `shell` | `"bash"` (default, uses `$SHELL`) or `"powershell"` (uses `pwsh`). |
| `timeout` | Per-hook timeout in seconds. |
| `statusMessage` | Custom spinner text shown while the hook runs. |
| `async` | If `true`, the hook runs in the background without blocking the event. |
| `asyncRewake` | Background hook that wakes the model on exit code 2. Implies `async`. |
| `once` | If `true`, the hook is removed from the session after it fires once. |
| `if` | Condition filter; see [Filtering with `if`](#filtering-with-if). |

### `prompt` — LLM evaluation

```json
{
  "type": "prompt",
  "prompt": "Does this tool call look safe? $ARGUMENTS"
}
```

Sends the event payload to a lightweight model for evaluation. The model must respond with `{"ok": true}` to pass, or `{"ok": false, "reason": "..."}` to fail.

| Field | Description |
|---|---|
| `prompt` | Prompt string. Use `$ARGUMENTS` as a placeholder for the hook's JSON input. |
| `model` | Model ID to use (e.g. `"claude-haiku-4-5"`). Defaults to the fastest available small model. |
| `timeout` | Timeout in seconds. |
| `statusMessage` | Spinner text. |
| `once` | Run once and remove. |
| `if` | Condition filter. |

### `agent` — agentic verifier

```json
{
  "type": "agent",
  "prompt": "Verify that the unit tests passed. Use $ARGUMENTS for context."
}
```

Spawns a short-lived agent session to verify a condition. Like `prompt`, it expects a structured `{"ok": bool, "reason": "..."}` response from the `SyntheticOutput` tool.

| Field | Description |
|---|---|
| `prompt` | Verification description. `$ARGUMENTS` expands to the hook input JSON. |
| `model` | Model ID to use. Defaults to Haiku. |
| `timeout` | Timeout in seconds (default 60). |
| `statusMessage` | Spinner text. |
| `once` | Run once and remove. |
| `if` | Condition filter. |

### `http` — HTTP POST

```json
{
  "type": "http",
  "url": "https://hooks.example.com/claurst",
  "headers": {
    "Authorization": "Bearer $SLACK_TOKEN"
  },
  "allowedEnvVars": ["SLACK_TOKEN"]
}
```

POSTs the event payload JSON to a URL.

| Field | Description |
|---|---|
| `url` | Destination URL. |
| `headers` | Extra request headers. Values may reference env vars using `$VAR` or `${VAR}`. |
| `allowedEnvVars` | Explicit list of env var names that may be interpolated in headers. |
| `timeout` | Timeout in seconds. |
| `statusMessage` | Spinner text. |
| `once` | Run once and remove. |
| `if` | Condition filter. |

---

## Filtering with `if`

The `if` field accepts permission rule syntax to skip a hook when the event does not match, avoiding unnecessary process spawning.

```json
{
  "type": "command",
  "command": "echo 'git command ran'",
  "if": "Bash(git *)"
}
```

The pattern is evaluated against the hook input's `tool_name` and `tool_input` fields. Standard glob wildcards apply. A hook with no `if` fires for every event matching its event type and matcher.

---

## Hook events

Each event has specific semantics for how it uses the hook's exit code and output.

### `PreToolUse`

Fires **before** any tool executes. The matcher field is compared against `tool_name`.

**Payload fields:** `tool_name`, `tool_input`, `tool_use_id`.

**Exit codes:**
- `0` — allow the tool call; stdout/stderr are not shown.
- `2` — **block the tool call**; stderr is shown to the model.
- Other — show stderr to the user only; the tool call proceeds.

### `PostToolUse`

Fires **after** a tool completes successfully. The matcher field is compared against `tool_name`.

**Payload fields:** `tool_name`, `inputs` (tool call arguments), `response` (tool output).

**Exit codes:**
- `0` — success; stdout is shown in transcript mode (`Ctrl+O`).
- `2` — show stderr to the model immediately.
- Other — show stderr to user only.

### `PostToolUseFailure`

Fires **after** a tool errors. The matcher field is compared against `tool_name`.

**Payload fields:** `tool_name`, `tool_input`, `tool_use_id`, `error`, `error_type`, `is_interrupt`, `is_timeout`.

**Exit codes:** Same as `PostToolUse`.

### `Stop`

Fires **right before** the model concludes its response for a turn.

**Exit codes:**
- `0` — allow the stop; no output shown.
- `2` — **continue the conversation**; stderr is shown to the model.
- Other — show stderr to user only.

### `StopFailure`

Fires when the turn ends due to an API error (rate limit, auth failure, etc.) instead of a normal stop. Fire-and-forget — exit codes and output are ignored.

**Payload fields:** `error` (one of `rate_limit`, `authentication_failed`, `billing_error`, `invalid_request`, `server_error`, `max_output_tokens`, `unknown`).

### `UserPromptSubmit`

Fires when the user submits input.

**Payload fields:** the original prompt text.

**Exit codes:**
- `0` — stdout is shown to Claude as additional context.
- `2` — **block processing**, erase the original prompt, show stderr to the user.
- Other — show stderr to user only.

### `Notification`

Fires when Claurst sends a notification. The matcher field is compared against `notification_type`.

**Notification types:** `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`, `elicitation_complete`, `elicitation_response`.

**Exit codes:**
- `0` — no output shown.
- Other — show stderr to user only.

### `SessionStart`

Fires when a new session begins. The matcher field is compared against `source`.

**Source values:** `startup`, `resume`, `clear`, `compact`.

**Exit codes:**
- `0` — stdout is shown to Claude.
- Other — show stderr to user only. Blocking errors are ignored.

### `SessionEnd`

Fires when a session is ending. The matcher field is compared against `reason`.

**Reason values:** `clear`, `logout`, `prompt_input_exit`, `other`.

**Exit codes:**
- `0` — success.
- Other — show stderr to user only.

### `SubagentStart`

Fires when an agent tool call starts a subagent. The matcher field is compared against `agent_type`.

**Payload fields:** `agent_id`, `agent_type`.

**Exit codes:**
- `0` — stdout is shown to the subagent.
- Other — show stderr to user only. Blocking errors are ignored.

### `SubagentStop`

Fires right before a subagent concludes its response. The matcher field is compared against `agent_type`.

**Payload fields:** `agent_id`, `agent_type`, `agent_transcript_path`.

**Exit codes:**
- `0` — no output shown.
- `2` — show stderr to the subagent; it continues running.
- Other — show stderr to user only.

### `PreCompact`

Fires before a compaction. The matcher field is compared against `trigger`.

**Trigger values:** `manual`, `auto`.

**Exit codes:**
- `0` — stdout is appended as custom compaction instructions.
- `2` — **block the compaction**.
- Other — show stderr to user only; compaction proceeds.

### `PostCompact`

Fires after compaction completes. The matcher field is compared against `trigger`.

**Payload fields:** compaction details and the generated summary.

**Exit codes:**
- `0` — stdout shown to user.
- Other — show stderr to user only.

### `PermissionRequest`

Fires when a permission dialog is displayed to the user. The matcher field is compared against `tool_name`.

**Payload fields:** `tool_name`, `tool_input`, `tool_use_id`.

**Output:** JSON with `hookSpecificOutput` containing a `decision` field to allow or deny automatically.

**Exit codes:**
- `0` — use the hook's decision if one was provided.
- Other — show stderr to user only.

### `PermissionDenied`

Fires when the auto-mode permission classifier denies a tool call. The matcher field is compared against `tool_name`.

**Payload fields:** `tool_name`, `tool_input`, `tool_use_id`, `reason`.

**Output:** Return `{"hookSpecificOutput": {"hookEventName": "PermissionDenied", "retry": true}}` to tell the model it may retry.

**Exit codes:**
- `0` — stdout shown in transcript mode.
- Other — show stderr to user only.

### `TaskCreated`

Fires when a task is being created. Can block creation.

**Payload fields:** `task_id`, `task_subject`, `task_description`, `teammate_name`, `team_name`.

**Exit codes:**
- `0` — allow creation.
- `2` — show stderr to model; **prevent task creation**.
- Other — show stderr to user only.

### `TaskCompleted`

Fires when a task is being marked complete. Can block completion.

**Payload fields:** `task_id`, `task_subject`, `task_description`, `teammate_name`, `team_name`.

**Exit codes:** Same as `TaskCreated`.

### `Elicitation`

Fires when an MCP server requests user input. The matcher field is compared against `mcp_server_name`.

**Payload fields:** `mcp_server_name`, `message`, `requested_schema`.

**Output:** JSON with `hookSpecificOutput` containing `action` (`accept`/`decline`/`cancel`) and optional `content`.

**Exit codes:**
- `0` — use the hook response if one was provided.
- `2` — deny the elicitation.
- Other — show stderr to user only.

### `ElicitationResult`

Fires after the user responds to an MCP elicitation. Can override the response.

**Payload fields:** `mcp_server_name`, `action`, `content`, `mode`, `elicitation_id`.

**Output:** JSON with `hookSpecificOutput` containing optional `action` and `content` overrides.

**Exit codes:**
- `0` — use the hook response if provided.
- `2` — block the response (action becomes `decline`).
- Other — show stderr to user only.

### `ConfigChange`

Fires when a configuration file changes during a session. The matcher field is compared against `source`.

**Source values:** `user_settings`, `project_settings`, `local_settings`, `policy_settings`, `skills`.

**Payload fields:** `source`, `file_path`.

**Exit codes:**
- `0` — allow the change.
- `2` — **block the change** from being applied to the session.
- Other — show stderr to user only.

### `WorktreeCreate`

Fires when a git worktree is being created.

**Payload fields:** `name` (suggested worktree slug).

**Output:** stdout should contain the absolute path to the created worktree directory.

**Exit codes:**
- `0` — success.
- Other — worktree creation fails.

### `WorktreeRemove`

Fires when a previously created worktree is being removed.

**Payload fields:** `worktree_path` (absolute path).

**Exit codes:**
- `0` — success.
- Other — show stderr to user only.

### `InstructionsLoaded`

Fires when a CLAUDE.md or rules file is loaded (observability-only, cannot block).

**Payload fields:** `file_path`, `memory_type` (`User`/`Project`/`Local`/`Managed`), `load_reason` (`session_start`, `nested_traversal`, `path_glob_match`, `include`, `compact`), and optional `globs`, `trigger_file_path`, `parent_file_path`.

**Exit codes:** `0` success; other — show stderr to user only.

### `CwdChanged`

Fires after the working directory changes.

**Payload fields:** `old_cwd`, `new_cwd`.

The `CLAUDE_ENV_FILE` environment variable is set — write `export KEY=VALUE` lines to that file to propagate environment variables into subsequent Bash tool commands.

**Output:** `hookSpecificOutput.watchPaths` (array of absolute paths) registers paths with the `FileChanged` watcher.

### `FileChanged`

Fires when a watched file changes. The matcher field specifies a filename pattern to watch in the current directory (e.g. `".envrc|.env"`).

**Payload fields:** `file_path`, `event` (`change`, `add`, `unlink`).

`CLAUDE_ENV_FILE` is set for env propagation. `hookSpecificOutput.watchPaths` can dynamically update the watch list.

---

## JSON payload structure

Every hook receives a JSON object on stdin. The exact fields depend on the event, but the envelope is always an object with at minimum a `hook_event_name` field and the event-specific fields described above.

For `PreToolUse`:

```json
{
  "hook_event_name": "PreToolUse",
  "tool_name": "Bash",
  "tool_input": {
    "command": "rm -rf /tmp/foo"
  },
  "tool_use_id": "toolu_01abc..."
}
```

For `PostToolUse`:

```json
{
  "hook_event_name": "PostToolUse",
  "tool_name": "FileWrite",
  "inputs": {
    "file_path": "/src/main.rs",
    "content": "fn main() {}"
  },
  "response": {
    "output": "Written successfully"
  }
}
```

For `SessionEnd`:

```json
{
  "hook_event_name": "SessionEnd",
  "reason": "prompt_input_exit"
}
```

---

## Configuring hooks in settings.json

Hooks are declared under the `"hooks"` key in `.claude/settings.json` (project-shared) or `.claude/settings.local.json` (gitignored, user-local).

The value is a map from event name to an array of matcher objects. Each matcher object contains:

- `matcher` (optional) — a string pattern compared against the event's matchable field (e.g. tool name, trigger type). When absent or empty, the hooks apply to all values.
- `hooks` — an array of hook definitions.

```json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "python3 ~/.claurst/hooks/check_bash.py"
          }
        ]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "FileWrite",
        "hooks": [
          {
            "type": "command",
            "command": "prettier --write \"$TOOL_INPUT_FILE_PATH\" 2>/dev/null || true"
          }
        ]
      }
    ],
    "SessionEnd": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "bash ~/.claurst/hooks/notify-slack.sh"
          }
        ]
      }
    ]
  }
}
```

Multiple hook definitions inside a single `hooks` array run in order. Multiple matcher objects for the same event are all evaluated independently.

---

## Configuring hooks in plugin manifests

Plugins can ship their own hooks by declaring them in their manifest. Plugin hooks are registered at plugin load time and are scoped to the plugin's root. They appear in `/hooks` as `pluginHook` source entries.

A plugin `plugin.json` excerpt:

```json
{
  "name": "my-formatter",
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "FileWrite",
        "hooks": [
          {
            "type": "command",
            "command": "node $PLUGIN_ROOT/format.js"
          }
        ]
      }
    ]
  }
}
```

Plugin hooks are subject to the same policy controls as user-defined hooks. If `allowManagedHooksOnly` is set in policy settings, plugin hooks still run; user and project hooks are suppressed.

---

## /hooks command

Run `/hooks` inside an active session to open the interactive hooks configuration menu.

The menu displays all registered hooks grouped by event and matcher, showing the source (user settings, project settings, local settings, plugin, or built-in) for each.

From this menu you can:
- View which hooks are active for each event.
- Add, edit, or remove hooks from editable settings sources.
- Inspect the event metadata for any event (summary, description, matchable fields).

Changes made through `/hooks` are written immediately to the appropriate settings file.

---

## Example hooks

### Log all tool calls to a file

```json
{
  "hooks": {
    "PreToolUse": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "jq -c '{ts: now | todate, event: .hook_event_name, tool: .tool_name, input: .tool_input}' >> ~/.claurst/tool.log"
          }
        ]
      }
    ]
  }
}
```

### Block dangerous shell patterns

Create `~/.claurst/hooks/guard.sh`:

```bash
#!/usr/bin/env bash
set -euo pipefail

INPUT=$(cat)
CMD=$(echo "$INPUT" | jq -r '.tool_input.command // ""')

DANGEROUS_PATTERNS=(
  'rm -rf /'
  'dd if=.*of=/dev/'
  'mkfs\.'
  ':(){:|:&};:'
)

for pattern in "${DANGEROUS_PATTERNS[@]}"; do
  if echo "$CMD" | grep -qP "$pattern"; then
    echo "Blocked: command matches dangerous pattern '$pattern'" >&2
    exit 2
  fi
done
```

Register it:

```json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "bash ~/.claurst/hooks/guard.sh"
          }
        ]
      }
    ]
  }
}
```

An exit code of `2` sends the stderr message directly to the model, which will typically reconsider.

### Send a Slack notification when a session ends

```bash
#!/usr/bin/env bash
# ~/.claurst/hooks/slack-session-end.sh
INPUT=$(cat)
REASON=$(echo "$INPUT" | jq -r '.reason')

curl -s -X POST "$SLACK_WEBHOOK_URL" \
  -H 'Content-Type: application/json' \
  -d "{\"text\": \"Claurst session ended (reason: ${REASON})\"}"
```

```json
{
  "hooks": {
    "SessionEnd": [
      {
        "hooks": [
          {
            "type": "http",
            "url": "https://hooks.slack.com/services/YOUR/WEBHOOK/URL"
          }
        ]
      }
    ]
  }
}
```

Or using a shell command with environment variable interpolation:

```json
{
  "hooks": {
    "SessionEnd": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "bash ~/.claurst/hooks/slack-session-end.sh"
          }
        ]
      }
    ]
  }
}
```

### Auto-format on file write

```json
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "FileWrite",
        "hooks": [
          {
            "type": "command",
            "command": "bash -c 'FILE=$(jq -r .inputs.file_path); case \"$FILE\" in *.ts|*.tsx|*.js|*.jsx|*.json|*.css|*.md) prettier --write \"$FILE\" 2>/dev/null ;; *.py) ruff format \"$FILE\" 2>/dev/null ;; *.rs) rustfmt \"$FILE\" 2>/dev/null ;; esac'"
          }
        ]
      }
    ]
  }
}
```

---

## Testing hooks

The simplest way to test a hook is to print the incoming JSON payload and inspect it:

```bash
#!/usr/bin/env bash
cat > /tmp/last-hook-input.json
```

Register this as a `PreToolUse` hook for the tool you want to observe. After the next tool call, inspect `/tmp/last-hook-input.json` to confirm the payload shape.

To test a blocking hook without a live session, pipe a sample payload directly:

```bash
echo '{"hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"rm -rf /"},"tool_use_id":"test"}' \
  | bash ~/.claurst/hooks/guard.sh
echo "Exit: $?"
```

To test an `http` hook, use a service like `https://webhook.site` as the target URL and inspect the POSTed body in the browser.

For `prompt` and `agent` hooks, enable verbose logging or use `/hooks` to observe whether the hook ran and what it returned during a real session.

---

## File: docs/index.md

---

## What Claurst does

You give Claurst a task in natural language. It plans, reads and writes files, runs shell commands, searches the web, and iterates — all inside your terminal, with every step visible in real time.

```
$ claurst "add input validation to the signup form"
```

Claurst reads your codebase, implements the change across multiple files, runs your tests, and reports back — without you leaving the terminal.

---

## Key capabilities

### Agentic loop
Claurst runs a multi-turn loop: it streams a response from the model, executes any tool calls (file read, bash, web search, …), feeds the results back, and continues until the task is done or the turn limit is reached.

### 40+ built-in tools
- **File operations** — read, write, edit, patch, batch-edit
- **Shell** — bash with persistent working directory and environment
- **Search** — glob file patterns, grep contents, web search, web fetch
- **Git** — commit, branch, worktree
- **Notebooks** — read and edit Jupyter notebooks
- **Desktop automation** — screenshot, click, type (optional feature)
- **Task management** — create, track, and complete tasks

### 15+ LLM providers
Anthropic Claude (default), OpenAI, Google Gemini, AWS Bedrock, Azure OpenAI, Ollama, Groq, Mistral, DeepSeek, xAI, Cohere, OpenRouter, Together AI, Perplexity, GitHub Copilot, Cerebras, LM Studio, and LLaMA.cpp.

### AMOLED terminal UI
A ratatui-based TUI with real-time streaming, syntax-highlighted code blocks, diff viewer, permission dialogs, slash command autocomplete, session browser, and a full keybinding system.

### Multi-account credentials
Store multiple named Anthropic (Claude.ai / Console) and Codex (ChatGPT) accounts in one install and switch between them instantly with `/switch` or `claurst auth switch `. Identity is detected from the OAuth JWT, so re-logging-in the same account is idempotent. See [Authentication](auth#multi-account-profiles).

### @file injection
Type `@path/to/file` anywhere in a prompt to inject the file's contents inline. Typeahead autocomplete suggests paths as you type, with size/binary safety checks before submit. See [@file Injection](keybindings#file-injection-with-typeahead).

### Plugin system
Extend Claurst with TOML-manifest plugins that add custom slash commands, MCP servers, hooks, output styles, and tool overlays.

### Multi-agent orchestration
Run named agents (`build`, `plan`, `explore`) or spawn parallel sub-agents in coordinator mode. Agents communicate via a shared task registry and message channels.

### Goal system
Set a durable objective with `/goal` and Claurst works autonomously across turns until the goal is verified complete — using the `GoalCompleteTool` for audited completion rather than just stopping.

### Managed agents (preview)
Configure a manager-executor architecture with `/managed-agents` where a manager model delegates subtasks to parallel executor agents with full budget split controls.

### Speech modes
Activate `/caveman` or `/rocky` to compress model responses by 40–85%, saving tokens in long sessions. Deactivate with `/normal`.

---

## Quick start

**1. Install**

```bash
# Linux / macOS
curl -fsSL https://github.com/Kuberwastaken/claurst/releases/latest/download/install.sh | bash
```

```powershell
# Windows (PowerShell)
irm https://github.com/Kuberwastaken/claurst/releases/latest/download/install.ps1 | iex
```

The installer auto-detects your platform/arch, drops `claurst` into
`~/.claurst/bin/`, and adds it to your `PATH`. See
[Installation](installation) for flags, manual download, and uninstall steps.

**2. Set your API key**

```bash
export ANTHROPIC_API_KEY=sk-ant-...
```

**3. Run interactively**

```bash
claurst
```

Or send a single prompt and exit:

```bash
claurst --print "explain the auth module"
```

---

## Configuration

Claurst reads `~/.claurst/settings.json` at startup. The most common settings:

```json
{
  "config": {
    "model": "claude-opus-4-6",
    "permission_mode": "default",
    "auto_compact": true,
    "compact_threshold": 0.8
  }
}
```

See [Configuration](configuration) for the full reference.

---

## Using a different provider

```bash
# Use Ollama with a local model
claurst --provider ollama --model llama3.2

# Use OpenAI
OPENAI_API_KEY=sk-... claurst --provider openai --model gpt-4o
```

See [Providers](providers) for setup instructions for every supported provider,
or the [Local Models](local-models) guide for running against llama.cpp,
LM Studio, Ollama, or any OpenAI-compatible server on your own machine.

---

## Interactive vs headless

| Mode | Command | Use case |
|------|---------|----------|
| Interactive TUI | `claurst` | Day-to-day coding |
| Single prompt | `claurst "task"` | Quick one-shot tasks |
| Headless print | `claurst --print "task"` | Scripts, CI |
| JSON output | `claurst --output-format json "task"` | Machine consumption |
| Stream JSON | `claurst --output-format stream-json "task"` | Real-time piping |

---

## Slash commands

Inside the interactive TUI, type `/` to see all available commands. Common ones:

| Command | Description |
|---------|-------------|
| `/help` | Show all commands |
| `/model` | Switch model or provider |
| `/login` | OAuth login (Anthropic; `--codex` for ChatGPT, `--label <name>` to name) |
| `/accounts` | List stored Anthropic + Codex accounts |
| `/switch ` | Switch active account (`--codex` for Codex) |
| `/logout` | Clear credentials for the active account (`--all` to purge) |
| `/goal <objective>` | Set an autonomous multi-turn goal |
| `/managed-agents` | Configure manager-executor agents |
| `/compact` | Compress conversation history |
| `/cost` | Token usage and cost for this session |
| `/insights` | Session statistics and tool usage report |
| `/caveman` | Activate telegraphic speech mode (save tokens) |
| `/rocky` | Activate Rocky (Project Hail Mary) speech mode |
| `/normal` | Deactivate speech modes |
| `/rewind` | Go back to a previous message |
| `/copy` | Copy last response to clipboard |
| `/export` | Save session transcript |
| `/think-back` | View thinking traces from previous responses |
| `/ultrareview` | Exhaustive multi-dimensional code review |
| `/advisor <model>` | Set a secondary advisor model |
| `/sandbox-toggle` | Toggle sandboxed shell execution |
| `/update` | Check for and download updates |
| `/exit` | Quit |

See [Slash Commands](commands) for the complete reference.

---

## Next steps

- [Installation](installation) — download, build from source, system requirements
- [Authentication](auth) — API keys and OAuth
- [Configuration](configuration) — settings.json reference
- [Slash Commands](commands) — all 70+ commands
- [Tools Reference](tools) — all 40+ tools and permission levels
- [Providers](providers) — configuring each LLM provider
- [Local Models](local-models) — llama.cpp, LM Studio, Ollama, and other OpenAI-compatible servers
- [MCP Integration](mcp) — Model Context Protocol servers
- [Plugins](plugins) — building and using plugins
- [Agents](agents) — multi-agent orchestration
- [Hooks](hooks) — event-driven automation
- [Advanced Features](advanced) — extended thinking, sessions, and more

---

## File: docs/installation.md

# Claurst Installation Guide

Claurst is a Rust reimplementation of the Claude Code CLI. The fastest way
to install it is via the one-liner installers below. They drop the binary
into `~/.claurst/bin` (or `%USERPROFILE%\.claurst\bin` on Windows) and add
that directory to your `PATH` automatically.

---

## System Requirements

| Platform | Architecture | Minimum OS |
|----------|-------------|------------|
| Windows  | x86_64      | Windows 10 / Server 2019 |
| Linux    | x86_64      | glibc 2.17+ (most distros from 2014 onward) |
| Linux    | aarch64     | glibc 2.17+ (Raspberry Pi 4, AWS Graviton, etc.) |
| macOS    | x86_64      | macOS 11 Big Sur |
| macOS    | aarch64     | macOS 11 Big Sur (Apple Silicon: M1/M2/M3) |

There are no other runtime dependencies. The binary is statically linked where
possible; on Linux it links against the system glibc.

---

## Quick install (recommended)

### Linux / macOS

```bash
curl -fsSL https://github.com/Kuberwastaken/claurst/releases/latest/download/install.sh | bash
```

### Windows (PowerShell)

```powershell
irm https://github.com/Kuberwastaken/claurst/releases/latest/download/install.ps1 | iex
```

Both installers:

1. Detect your platform and architecture.
2. Download the matching archive from the latest GitHub release.
3. Extract `claurst` into `~/.claurst/bin/` (Windows: `%USERPROFILE%\.claurst\bin\`).
4. Append that directory to your shell config (`.bashrc`, `.zshrc`,
   `.config/fish/config.fish`) or to your Windows user `PATH`.
5. On macOS, strip the quarantine attribute so Gatekeeper does not block the
   unsigned binary.

Open a new terminal afterwards (or `source` the modified shell config) so
the updated `PATH` takes effect, then run `claurst --version` to verify.

### Installer flags

Both scripts accept the same flags:

| Flag (sh) | Flag (ps1) | Effect |
|---|---|---|
| `--version 0.1.0` | `-Version 0.1.0` | Install a specific version |
| `--binary ` | `-Binary ` | Install from a local file (skip download) |
| `--install-dir ` | `-InstallDir ` | Override the install directory |
| `--no-modify-path` | `-NoModifyPath` | Don't touch shell config / user PATH |
| `--help` | `-Help` | Show usage |

Example: `curl -fsSL https://.../install.sh | bash -s -- --version 0.1.0`

---

## Via npm / bun

If you have Node.js or Bun installed, you can install Claurst as a global
package. The postinstall script automatically downloads the correct pre-built
native binary for your platform from GitHub Releases — no compilation needed.

```bash
# npm
npm install claurst

# bun
bun install -g claurst
```

After installation, run `claurst` directly from your terminal.

You can also run Claurst without a permanent install:

```bash
npx claurst          # via npm
bunx claurst         # via bun
```

**Supported platforms via npm:**

| Platform | Architecture |
|----------|-------------|
| Linux    | x86_64, aarch64 |
| macOS    | x86_64 (Intel), aarch64 (Apple Silicon) |
| Windows  | x86_64 |

---

## Upgrading

Once installed, upgrade in place at any time:

```bash
claurst upgrade               # to the latest release
claurst upgrade --version 0.1.0   # pin to a specific version
claurst upgrade --force       # reinstall the same version
```

The upgrade command downloads the matching archive from GitHub, extracts the
new binary, and replaces the running executable atomically. Settings in
`~/.claurst/` are preserved.

---

## Manual install from GitHub Releases

If you'd rather not run an install script, grab archives directly from
[**GitHub Releases**](https://github.com/Kuberwastaken/claurst/releases):

| Archive | Platform |
|---------|----------|
| `claurst-windows-x86_64.zip` | Windows 64-bit |
| `claurst-linux-x86_64.tar.gz` | Linux x86_64 |
| `claurst-linux-aarch64.tar.gz` | Linux ARM64 |
| `claurst-macos-x86_64.tar.gz` | macOS Intel |
| `claurst-macos-aarch64.tar.gz` | macOS Apple Silicon |

Every archive contains a single binary named `claurst` (or `claurst.exe`).
Extract it and put it somewhere on your `PATH`. For example on Linux:

```bash
curl -L https://github.com/Kuberwastaken/claurst/releases/latest/download/claurst-linux-x86_64.tar.gz \
  | tar -xz
chmod +x claurst
sudo mv claurst /usr/local/bin/
```

On macOS, also strip the quarantine flag so Gatekeeper allows the unsigned
binary:

```bash
xattr -rd com.apple.quarantine /usr/local/bin/claurst
```

On Windows, extract the zip and add the folder containing `claurst.exe`
to your user `PATH` via **Settings → System → Advanced system settings →
Environment Variables**.

### User-local install without sudo

```bash
mkdir -p ~/.local/bin
mv claurst ~/.local/bin/claurst
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc
source ~/.bashrc
```

For Zsh users, substitute `.zshrc` for `.bashrc`.

---

## Verifying the Installation

```bash
claurst --version
```

A successful installation prints the version string, for example:

```
claurst 0.1.7
```

To confirm the binary is the one you installed:

```bash
which claurst          # Linux / macOS
where claurst          # Windows (Command Prompt)
```

---

## Building from Source

Building from source requires the Rust toolchain (stable channel, 1.75 or
later). Install Rust via [rustup](https://rustup.rs/):

```bash
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source "$HOME/.cargo/env"
```

### Option A: Install via Cargo

```bash
cargo install claurst --force
```

This downloads, compiles, and installs the binary to `~/.cargo/bin/claurst`.
That directory is added to `PATH` automatically by `rustup`.

### Option B: Clone and Build

```bash
git clone https://github.com/Kuberwastaken/claurst.git
cd claurst/src-rust

# Debug build (fast to compile, larger binary, extra runtime checks)
cargo build --package claurst

# Release build (optimised, smaller, suitable for everyday use)
cargo build --release --package claurst
```

The release binary is placed at:

```
src-rust/target/release/claurst        # Linux / macOS
src-rust/target\release\claurst.exe   # Windows
```

Copy it to a directory on your `PATH` as described above.

### Linux system dependencies

On Linux, the build requires ALSA development headers (for the optional voice
feature) and OpenSSL:

```bash
# Debian / Ubuntu
sudo apt-get install -y libasound2-dev libssl-dev pkg-config

# Fedora / RHEL
sudo dnf install -y alsa-lib-devel openssl-devel

# Arch
sudo pacman -S alsa-lib openssl
```

### Optional cargo features

| Feature | Description |
|---------|-------------|
| `voice` | Microphone input / voice prompting |
| `computer-use` | Screenshot capture and mouse/keyboard control |
| `dev_full` | All experimental features combined |

To enable a feature:

```bash
cargo build --release --package claurst --features voice
cargo build --release --package claurst --features dev_full
```

### Cross-compiling for Linux aarch64

The release workflow uses [cross](https://github.com/cross-rs/cross) for
aarch64 Linux builds. To reproduce it locally:

```bash
cargo install cross --git https://github.com/cross-rs/cross
cd src-rust
cross build --release --locked --package claurst --target aarch64-unknown-linux-gnu
```

`cross` manages the Docker sysroot, OpenSSL, and ALSA headers automatically.

---

## Shell Completions

Claurst does not currently ship a dedicated `completions` subcommand. All
flags can be discovered via `claurst --help`. If you want basic tab completion
in bash or zsh you can use the generic completion helper built into your shell:

```bash
# bash — add to ~/.bashrc
complete -C claurst claurst

# zsh — add to ~/.zshrc (requires compinit)
compdef _gnu_generic claurst
```

Richer completion scripts may be added in a future release.

---

## Upgrading a source install

```bash
cargo install claurst --force
```

For binary installs (the recommended path), use `claurst upgrade` — see
the [Upgrading](#upgrading) section above.

---

## Uninstalling

If you used the install script, remove the install directory:

```bash
rm -rf ~/.claurst/bin                    # Linux / macOS
# Windows (PowerShell):
Remove-Item -Recurse -Force "$env:USERPROFILE\.claurst\bin"
```

For manual installs:

```bash
sudo rm /usr/local/bin/claurst           # if installed system-wide
rm ~/.local/bin/claurst                  # if installed user-local
```

To also remove all settings and session data:

```bash
rm -rf ~/.claurst
```

You may also want to remove the `# claurst` PATH line that the installer
appended to your shell config (`.bashrc`, `.zshrc`, etc.).

---

## File: docs/keybindings.md

# Claurst Keybindings Reference

This document covers all keyboard shortcuts in Claurst, how to customize them, vim mode, and special input behaviors.

---

## Table of Contents

1. [Default Keybindings](#default-keybindings)
   - [Global Context](#global-context)
   - [Chat Context](#chat-context)
   - [Confirmation Context](#confirmation-context)
2. [Keybinding Contexts](#keybinding-contexts)
3. [Customizing Keybindings](#customizing-keybindings)
   - [Via /keybindings command](#via-keybindings-command)
   - [Via keybindings.json](#via-keybindingsjson)
   - [Chord Bindings](#chord-bindings)
4. [Non-Rebindable Keys](#non-rebindable-keys)
5. [Vim Mode](#vim-mode)
6. [Special Input Behaviors](#special-input-behaviors)
   - [Shift+Enter for Newline](#shiftenter-for-newline)
   - [ESC During Streaming](#esc-during-streaming)
   - [@file Injection with Typeahead](#file-injection-with-typeahead)
7. [Non-English Keyboard Layout Support](#non-english-keyboard-layout-support)

---

## Default Keybindings

### Global Context

These bindings are active in all contexts.

| Key | Action | Description |
|-----|--------|-------------|
| `Ctrl+C` | interrupt | Interrupt the current operation (non-rebindable) |
| `Ctrl+D` | exit | Exit Claurst (non-rebindable) |
| `Ctrl+L` | redraw | Redraw the terminal screen |
| `Ctrl+R` | historySearch | Open interactive history search |
| `Ctrl+B` | createBranch | Create a new git branch |
| `Alt+H` | openHelp | Open the help panel |

### Chat Context

These bindings are active when focus is in the chat input field.

| Key | Action | Description |
|-----|--------|-------------|
| `Enter` | submit | Submit the current message to the model |
| `Shift+Enter` | newline | Insert a literal newline without submitting |
| `Ctrl+J` | newline | Newline (fallback for terminals without CSI-u protocol) |
| `Up` / `Ctrl+O` | historyPrev | Navigate to the previous message in input history |
| `Down` / `Ctrl+I` | historyNext | Navigate to the next message in input history |
| `Tab` | indent | Insert indentation (or cycle completions if open) |
| `Shift+Tab` | reverseIndent | Remove one level of indentation |
| `Page Up` | scrollUp | Scroll the conversation view up one page |
| `Page Down` | scrollDown | Scroll the conversation view down one page |
| `Home` / `Cmd+Left` / `Ctrl+A` | goLineStart | Move cursor to beginning of line |
| `End` / `Cmd+Right` / `Ctrl+E` | goLineEnd | Move cursor to end of line |
| `Ctrl+Left` | moveWordBackward | Move one word left |
| `Ctrl+Right` | moveWordForward | Move one word right |
| `Alt+Left` | previousMessage | Jump to previous user/assistant message |
| `Alt+Right` | nextMessage | Jump to next user/assistant message |
| `Ctrl+Shift+A` | openModelPicker | Open the interactive model picker |
| `Ctrl+K` | openCommandPalette | Open the slash command palette |
| `Ctrl+U` | killToStart | Delete from cursor to beginning of line |
| `Ctrl+W` / `Alt+Backspace` | killWord | Delete the word before the cursor |
| `Alt+D` | deleteWord | Delete the word after the cursor |
| `Ctrl+H` | deleteCharBefore | Delete character before cursor |
| `Ctrl+L` | clearLine | Clear current input line |
| `Ctrl+F` | findInMessage | Open inline search within the current conversation |
| `Ctrl+Shift+F` | globalSearch | Open global codebase search |
| `F3` / `Ctrl+]` | findNext | Jump to next search match |
| `Shift+F3` / `Ctrl+[` | findPrev | Jump to previous search match |
| `Ctrl+G` | goToLine | Jump to a specific line |
| `Ctrl+.` | jumpToNextError | Jump to next error / issue |
| `Ctrl+Shift+.` | jumpToPreviousError | Jump to previous error / issue |

> `Ctrl+A` previously opened the model picker; it now moves the cursor to the line start (matching Emacs/readline). The model picker is now `Ctrl+Shift+A`. Old `keybindings.json` files are auto-migrated.

### Confirmation Context

These bindings are active when Claurst is displaying a yes/no confirmation prompt (e.g., tool permission requests).

| Key | Action | Description |
|-----|--------|-------------|
| `Y` / `y` | confirm | Approve the pending action |
| `N` / `n` | deny | Deny the pending action |
| `A` / `a` | alwaysAllow | Approve and add a permanent allow rule |
| `Enter` | defaultAction | Accept the highlighted default option |
| `Escape` | cancel | Cancel the prompt and deny the action |

---

## Keybinding Contexts

Claurst uses a context system so that the same key can have different effects depending on where focus is. A binding in a more specific context takes precedence over a binding in a broader context.

| Context | Description |
|---------|-------------|
| `global` | Always active regardless of focus |
| `chat` | Active when the chat input field has focus |
| `confirmation` | Active when a permission confirmation dialog is open |
| `modelPicker` | Active inside the model selection overlay |
| `commandPalette` | Active inside the slash command palette overlay |
| `search` | Active while the inline search bar is open |
| `vim.normal` | Active in vim normal mode (when vim mode is enabled) |
| `vim.insert` | Active in vim insert mode (when vim mode is enabled) |
| `vim.visual` | Active in vim visual mode (when vim mode is enabled) |

---

## Customizing Keybindings

### Via /keybindings command

The `/keybindings` command opens an interactive TUI keybinding editor:

```
/keybindings
```

The editor lists all bindable actions grouped by context. Use arrow keys to navigate, press `Enter` on an action to enter rebind mode, then press the desired key combination. Press `Escape` to cancel a rebind. Changes are saved immediately to `~/.claurst/keybindings.json`.

### Via keybindings.json

For batch edits or scripted configuration, edit `~/.claurst/keybindings.json` directly. The file format is:

```json
{
  "schema_version": 1,
  "bindings": [
    {
      "context": "Chat",
      "action": "submit",
      "chord": "ctrl+enter"
    },
    {
      "context": "Global",
      "action": "historySearch",
      "chord": "ctrl+p"
    }
  ]
}
```

Each binding object has:

| Field | Type | Description |
|-------|------|-------------|
| `context` | string | Keybinding context (see table above) |
| `action` | string \| null | Action identifier (or `null` to unbind) |
| `chord` | string | Key combination in normalized form |

### Schema Versioning and Smart Merge

`keybindings.json` carries a top-level `schema_version` field (currently `1`). When Claurst's defaults change in a release, the file is auto-migrated on next launch:

1. Claurst reads the file and compares `schema_version` against the bundled `KEYBINDINGS_SCHEMA_VERSION`.
2. If the file is older, Claurst runs a **smart merge**:
   - Your customizations (any binding whose `chord` you set explicitly) are preserved.
   - Stale bindings that match an *old* default that has since changed are dropped — for example, the previous `ctrl+a → openModelPicker` binding is removed because `ctrl+a` is now reserved for select-all in the input.
   - Any new bindings present in the current defaults but not in your file are added.
3. The migrated file is written back with the new `schema_version`.

A warning is logged whenever a migration occurs. If you want to opt out of the merge for a binding, leave a different action assigned to it — explicit customizations always win.

Setting `"action": null` for a chord explicitly **unbinds** the default — useful when you want a key to do nothing rather than fire its default action.

Key notation uses lowercase letters, with modifier prefixes separated by `+`:

| Prefix | Modifier key |
|--------|-------------|
| `ctrl+` | Control |
| `alt+` | Alt / Option |
| `shift+` | Shift |
| `super+` | Super / Cmd |

Special key names: `enter`, `escape`, `tab`, `backspace`, `delete`, `up`, `down`, `left`, `right`, `home`, `end`, `pageup`, `pagedown`, `f1` through `f12`.

After editing the file, run `/keybindings` and then exit to trigger a reload, or restart Claurst.

### Chord Bindings

Claurst supports chord bindings — multi-key sequences where you press a leader key and then a follow-up key. Chord bindings are defined with a `chord` array instead of a single `key`:

```json
{
  "context": "chat",
  "action": "openModelPicker",
  "chord": ["ctrl+x", "ctrl+m"]
}
```

The first key in the chord acts as the leader. After pressing the leader key, Claurst enters a brief chord-wait state (500 ms by default). If the follow-up key arrives within that window, the chord fires. If the timeout expires or a different key is pressed, the leader key's default action (if any) fires instead.

Chords can be up to two keys deep. Three-key chords are not supported.

Example — map `Ctrl+X Ctrl+C` to exit:

```json
{
  "context": "global",
  "action": "exit",
  "chord": ["ctrl+x", "ctrl+c"]
}
```

---

## Non-Rebindable Keys

The following keys have fixed behavior and cannot be rebound:

| Key | Fixed behavior |
|-----|---------------|
| `Ctrl+C` | Interrupt current operation / send SIGINT to foreground process |
| `Ctrl+D` | Exit Claurst when input is empty; signal EOF when input has content |
| `Ctrl+M` | Identical to `Enter` at the terminal level (terminals emit `CR` for both) |

These keys are handled at the terminal input layer before the keybinding system processes events. If any of them appear as a `chord` in `keybindings.json`, Claurst:

1. Logs a warning at startup (`Cannot rebind protected key '<chord>' in keybindings.json`).
2. **Filters the binding out** of the loaded set before resolving any keystrokes.

So overriding a protected key is a no-op in behavior, but you also get a clear signal in the logs that the binding was rejected.

---

## Vim Mode

Vim mode replaces the default line editor with a modal input field that mimics vim's normal, insert, and visual modes.

### Enabling Vim Mode

```
/vim
/vim on
/vim off
```

Or set it persistently:

```
/config set vim true
```

### Vim Mode Keybindings

In vim mode the input field has three modes:

**Insert mode** — behaves like the normal chat input; type freely, `Escape` returns to normal mode.

**Normal mode** — movement and editing commands:

| Key | Action |
|-----|--------|
| `h` / `l` | Move cursor left / right |
| `j` / `k` | History prev / next |
| `w` / `b` | Move forward / backward by word |
| `0` / `$` | Move to line start / end |
| `i` | Enter insert mode at cursor |
| `a` | Enter insert mode after cursor |
| `A` | Enter insert mode at end of line |
| `I` | Enter insert mode at beginning of line |
| `x` | Delete character under cursor |
| `dd` | Delete entire line |
| `u` | Undo last change |
| `Ctrl+R` | Redo |
| `yy` | Yank (copy) line |
| `p` | Paste after cursor |
| `Enter` | Submit message |
| `/` | Enter inline search |
| `Escape` | Clear pending command / return to normal |

**Visual mode** — entered with `v` from normal mode; use movement keys to select text, then:

| Key | Action |
|-----|--------|
| `y` | Yank selection |
| `d` | Delete selection |
| `Escape` | Exit visual mode |

### Vim Mode Indicator

When vim mode is active, a mode indicator (`NORMAL`, `INSERT`, `VISUAL`) is displayed in the status line.

---

## Special Input Behaviors

### Shift+Enter for Newline

Pressing `Shift+Enter` in the chat input field inserts a literal newline character without submitting the message. This is the standard way to write multi-line prompts.

Pressing plain `Enter` always submits the message regardless of the number of lines already in the input buffer.

In vim insert mode, `Enter` also submits. Use `Shift+Enter` for newlines in vim mode as well.

### ESC During Streaming

Pressing `Escape` while the model is streaming a response interrupts the stream. The partial response is preserved in the conversation history and the model stops generating. The input field regains focus and you can send a follow-up message.

This is equivalent to pressing `Ctrl+C` during streaming, except that `Ctrl+C` also signals any tool calls in progress to abort (via `AbortController`), while `Escape` only stops the stream and allows running tools to finish.

---

### @file Injection with Typeahead

Type `@` followed by a path in the prompt to inject a file's contents into your message. The `@` token only triggers when it is at a word boundary (start of input or preceded by whitespace). As you type after the `@`, Claurst opens a typeahead completion overlay scanning the current working directory.

```
explain @src/main.rs and compare to @tests/integration.rs
```

When you press `Enter`, Claurst:

1. Scans the message for `@` tokens at word boundaries.
2. Resolves each path relative to the working directory; `~/` expands to your home directory.
3. Reads the file contents and substitutes them inline before sending the prompt to the model.

The `@` reference works with:

- Plain absolute paths: `@/etc/hosts`
- Paths relative to cwd: `@src/main.rs`
- Home-relative paths: `@~/.bashrc`
- Trailing punctuation is stripped: `@src/main.rs.` is treated as `@src/main.rs`

An `@` that is *not* at a word boundary (e.g. inside an email `me@example.com`) is left alone — neither the typeahead nor the file injection triggers.

**Limits and warnings.** If a referenced path is too large, binary, a directory, or unreadable, Claurst opens a confirmation dialog before sending:

| Issue | Behavior |
|-------|----------|
| File exceeds size limit | Dialog offers "Allow anyway" or "Abort" |
| Binary file | Dialog warns; same choice |
| Path is a directory | Dialog warns; cannot inject (must remove or rewrite the @ref) |
| Path unreadable | Skipped; error shown in dialog |

Files that pass all checks are injected silently — no dialog is shown.

**Configuration.** Two settings in `~/.claurst/settings.json`:

| Setting | Default | Description |
|---------|---------|-------------|
| `fileInjectionEnabled` | `true` | Master switch — set to `false` to disable @-injection entirely |
| `fileInjectionMaxSize` | `100` | Per-file size limit in KB; `0` disables the check (accept all) |

These can also be edited in the in-app settings screen.

**Typeahead navigation.** While the completion overlay is open:

| Key | Action |
|-----|--------|
| `Up` / `Down` | Move selection |
| `Tab` / `Enter` | Insert the highlighted completion |
| `Escape` | Dismiss the overlay (keep typed text) |

---

## Non-English Keyboard Layout Support

### The Problem

Terminal key events for `Ctrl+<key>` combinations are reported as raw control codes (`0x01` through `0x1A` for `Ctrl+A` through `Ctrl+Z`). These codes map to the physical QWERTY key position, not the character printed on the key.

On non-English keyboard layouts (Cyrillic, Arabic, Greek, CJK, etc.), the Latin letters used in Claurst's shortcuts may not appear on the keycaps, and some input methods send layout-translated scan codes for Ctrl combinations — causing Claurst to miss the shortcut entirely.

### The Fix

Claurst resolves this by mapping `Ctrl+<scancode>` events to their QWERTY positional equivalents before keybinding lookup. Concretely:

1. When a `Ctrl+<key>` event arrives, the physical scan position is extracted.
2. That position is mapped to the corresponding QWERTY letter (e.g., physical position of the Cyrillic `Ф` key = QWERTY `A` position).
3. The resulting `Ctrl+A` event is passed to the keybinding system.

This means `Ctrl+Ф` on a Cyrillic layout fires the same action as `Ctrl+A` on a QWERTY layout, regardless of the active input method or language setting. All `Ctrl+<letter>` keybindings in the default table above work by physical position.

### Implications for Custom Bindings

If you add a binding for `ctrl+a` in `keybindings.json`, it will fire when you press `Ctrl` and the key in the `A` position on your physical keyboard, regardless of what character that key is labeled. This is intentional.

If you want a binding that fires only when the `A` character is actually produced (i.e., layout-aware), prefix the key with `char:`:

```json
{
  "context": "chat",
  "action": "myAction",
  "key": "ctrl+char:a"
}
```

Layout-aware bindings are not recommended for the standard workflow bindings because they break on non-QWERTY layouts.

### Alt Key on macOS

On macOS, `Alt` (Option) key combinations produce special Unicode characters at the OS level before they reach the terminal. Claurst intercepts these at the terminal input layer and re-emits them as `alt+<key>` events using the same positional mapping described above.

If an `alt+<key>` binding does not fire on macOS, check whether your terminal emulator is configured to send `Escape + key` sequences for Option key combinations (the iTerm2 and Alacritty option is "Use Option as Meta Key" or equivalent).

## 2. Official Technical Reference & Guides (Kuberwastaken/Kuberwastaken.github.io)

## Welcome to my Personal Portfolio Repository!

This project is the fruit of blood, sweat, and eye strain to showcase my skills, projects, and professional journey through an interactive terminal-style interface. Dive in and feel free to explore the things that set my portfolio apart.

Expect me adding a lot other cool stuff and not mentioning this in the README because I prefer to ship stuff and hate documenting it (ugh) and this is one of my favorite personal projects to mess around with.

---

## 🛠️ Technical Architecture

### **Frontend Framework**
- **React** - Latest React with concurrent features and improved performance
- **Custom Hooks & Context** - Efficient state management and theme switching
- **Component Architecture** - Modular, reusable components with clear separation of concerns

### **Core Technologies**
- **HTML5 & Semantic Markup** - Accessible, SEO-friendly structure (thanks [CSS Naked day](https://github.com/Kuberwastaken/Kuberwastaken.github.io/tree/css-naked-day))
- **CSS3 & Advanced Animations** - Custom CSS grid, flexbox, and smooth transitions
- **ES6+ JavaScript** - Modern JavaScript with async/await, destructuring, and modules
- **Local Storage Integration** - Persistent game scores and user preferences

### **Performance Features**
- **Code Splitting** - Lazy loading for optimal performance
- **Component Memoization** - React.memo for expensive re-renders
- **Event Listener Cleanup** - Proper memory management and cleanup
- **Efficient Re-rendering** - Strategic use of useCallback and useMemo hooks
- **Canvas Optimization** - RequestAnimationFrame for smooth 60fps animations
- **Local Storage Caching** - Persistent data without server calls
- **PWA Ready** - Service worker support for offline functionality
- **Responsive Design** - Mobile-first approach with adaptive layouts
- **Cross-Browser Compatibility** - Tested across Chrome, Firefox, Safari, and Edge

---

## 🎮 Interactive Features Deep Dive

### **🖥️ Terminal Emulator**
A fully functional terminal interface with:
- **Command Autocomplete** - Smart suggestions with fuzzy matching
- **Command History** - Navigate previous commands with arrow keys
- **Error Handling** - Intelligent error messages with command suggestions
- **Real-time Feedback** - Immediate visual and textual responses

### **🎯 Gaming Ecosystem**
**Snake Game**
- Classic gameplay with modern touch controls
- Collision detection and smooth animations
- Mobile-optimized controls and responsive design

**Tetris**
- Full line-clearing mechanics with scoring system
- Piece rotation and collision detection
- Local storage for high scores

**2048**
- Swipe and keyboard controls
- Smooth tile animations and merging logic
- Win/lose detection with game state management

**Flappy Bird**
- Physics-based gameplay with gravity simulation
- Procedural pipe generation
- Touch and keyboard controls with responsive design

**[The Backdooms](https://github.com/kuberwastaken/backdooms)**
- DOOM-inspired game built in under 2.6KB
- QR code integration for viral sharing
- Backrooms aesthetic with 3D-like gameplay

### ** Advanced Calculator**
- Full mathematical expression parsing
- Support for parentheses and complex operations
- Scientific notation and advanced functions
- Responsive button layout for mobile devices

### **🎨 Dynamic Theming System**
- **15+ Pre-built Themes** - Curated solid colors and gradients
- **Real-time Theme Switching** - Instant visual updates without page reload
- **Persistent Preferences** - Themes saved to localStorage for return visits
- **CSS Custom Properties** - Efficient theme management with CSS variables
- **Interactive Theme Gallery** - Visual theme picker with live previews
- **Branded Themes** - Special themes inspired by projects (ORCUS, GitHub Art)
- **Gradient Support** - Complex linear gradients including Deep Space, Cherry Blossom
- **Dynamic Injection** - Runtime CSS injection for seamless theme changes

### **🔍 Integrated Search Capabilities**
Direct search integration for:
- **Google Search** - `google [query]`
- **YouTube Search** - `youtube [query]`
- **Wikipedia Lookup** - `wiki [query]`
- **ChatGPT Access** - `chatgpt [query]`
- **Perplexity AI** - `perplexity [query]`

### **📊 Data Visualization**
- **Animated Skills Charts** - Interactive skill level indicators
- **Project Masonry Layout** - Dynamic grid with hover effects
- **ASCII Art Generation** - Custom ASCII selfie display
- **Neofetch Clone** - System information display

### **🎭 Special Effects**
- **Hollywood Matrix Effect** - Toggle-able background effect with `hackermode` command
- **Smooth Animations** - CSS transitions and transforms
- **Particle Effects** - Canvas-based visual enhancements
- **Loading States** - Elegant loading indicators throughout
- **RGB Animations** - Dynamic color-cycling text effects
- **Glassmorphism UI** - Modern blur effects with backdrop filters

### **🎪 Easter Eggs & Hidden Features**

Try it out yourself 🙃


Click to spoil them anyways

- **ASCII Selfie** - Custom ASCII art with hidden developer comments
- **Command Typo Correction** - Intelligent suggestions using Levenshtein distance algorithm
- **Secret Command Aliases** - Multiple ways to execute the same commands
- **Browser Mockups** - Faux webpage previews for projects
- **Version Display** - Portfolio version tracking in welcome message
- **Memory Persistence** - Game high scores and theme preferences saved locally



---

## 📱 Mobile-First Design

### **Touch Optimizations**
- **Gesture Controls** - Swipe navigation for games
- **Touch-Friendly Buttons** - Optimized touch targets
- **Responsive Typography** - Fluid font scaling
- **Mobile Command Input** - On-screen keyboard optimization

### **Performance on Mobile**
- **Optimized Assets** - Compressed images and efficient loading
- **Touch Event Handling** - Prevents scrolling conflicts
- **Viewport Management** - Proper mobile viewport configuration
- **Battery Efficiency** - Optimized animations and rendering

---

## 🎯 Command System Architecture

### **Available Commands** (28+ total)
```bash
# Navigation & Information
help, who, skills, projects, resume, blog

# Games & Entertainment  
games, snake, tetris, 2048, flappybird, backdooms

# Utilities & Tools
calculator, neofetch, ascii-selfie, time, date

# Search & External
google [query], youtube [query], wiki [query]
chatgpt [query], perplexity [query]

# Customization
theme [name], background [name], hackermode

# Social & Contact
github, linkedin, email, discord, youtube

# System
clear, misc
```

### **Smart Command Processing**
- **Fuzzy Matching** - Suggests similar commands for typos using Levenshtein distance
- **Alias Support** - Multiple ways to call the same command (e.g., `s`, `sk`, `skills`)
- **Parameter Parsing** - Intelligent argument handling for search commands
- **Error Recovery** - Helpful error messages with clickable suggestions
- **Command History** - Navigate previous commands with arrow keys (↑/↓)
- **Auto-complete** - Smart command suggestions with fuzzy matching

### **Advanced Gaming Architecture**
- **Physics Engine** - Custom gravity and collision detection for Flappy Bird
- **Game State Management** - Persistent high scores across sessions
- **Touch Controls** - Region-based touch input for mobile Snake gameplay
- **Frame Rate Optimization** - RequestAnimationFrame for smooth 60fps gaming
- **Cross-Platform Input** - Unified keyboard and touch event handling
- **Memory Management** - Proper cleanup of game intervals and event listeners

---

## 🎨 Design Philosophy

### **Terminal Aesthetics**
- **Monospace Typography** - JetBrains Mono for authentic terminal feel
- **Green-on-Black Color Scheme** - Classic terminal colors with modern touches
- **Scan Lines & CRT Effects** - Subtle retro visual elements
- **Authentic Terminal Behaviors** - Cursor animations, text streaming

### **Modern UX Principles**
- **Progressive Disclosure** - Information revealed as needed
- **Immediate Feedback** - Real-time responses to user actions
- **Error Prevention** - Smart defaults and input validation
- **Accessibility** - Screen reader support and keyboard navigation

---

## 📊 Project Showcase Integration

### **Featured Projects**
- **TREAT** - Tech platform with 1000+ users
- **PolyThink** - AI-powered content platform
- **Engram** - Open-source educational resources
- **LifeMap** - Personal network visualization tool
- **MiniLMs** - Custom AI chatbot development

### **Project Display Features**
- **Interactive Cards** - Hover effects and animations
- **Live Previews** - Embedded iframes for web projects
- **GitHub Integration** - Direct repository links
- **Responsive Gallery** - Mobile carousel and desktop masonry

---

## 🎯 Future Roadmap

Very vibe dependent honestly :P

---

## 🚀 Getting Started

### **Local Development**
```bash
# Clone the repository
git clone https://github.com/Kuberwastaken/Kuberwastaken.github.io.git

# Navigate to project directory
cd Kuberwastaken.github.io

# Install dependencies
npm install

# Start development server
npm start

# Build for production
npm run build

# Deploy to GitHub Pages
npm run deploy
```

### **Key Dependencies**
- **React 19.0.0** - Core framework
- **@react-pdf-viewer** - PDF rendering for resume
- **react-scripts 5.0.1** - Build toolchain
- **gh-pages** - Deployment automation

---

This portfolio represents the intersection of **technical expertise**, **creative design**, and **user experience innovation**. It's not just a showcase of past work—it's a playground for exploring new technologies and pushing the boundaries of what's possible in a web browser.

**Visit the live portfolio**: [kuber.studio](https://kuber.studio/)

---